Skip to main content

magi/
graph.rs

1//! The competition graph.
2//!
3//! ```text
4//! prep ──► implement ×N ──► judge ×M (blind) ──► split? ──► deliberate ──► vote (private)
5//!                                                   │                          │
6//!                                                   └──── unanimous ───────────┤
7//!                                                                              ▼
8//!   merge ◄── gate ◄── review ×R + E2E, fix, repeat ◄── fold losers ◄──────── tally
9//! ```
10//!
11//! Every node persists before the next one starts, so a run can be resumed
12//! after a crash, a rate limit, or a reboot without re-spending the work that
13//! already landed.
14//!
15//! The design decision that matters most is *where the facilitator lives*.
16//! There is no moderator agent: magi assigns the labels, decides the
17//! presentation order, relays the transcript, and collects the final votes
18//! one-to-one. A moderator that never learns an author cannot leak one.
19use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use anyhow::{Context as _, Result, bail};
26use jiff::Timestamp;
27use tokio::sync::Semaphore;
28
29use crate::advise;
30use crate::agent::{self, AgentOutput, Invocation, SeatState};
31use crate::ask;
32use crate::blind;
33use crate::bump;
34use crate::config::{
35    AgentSpec, Config, IncompleteReviewPolicy, LeakPolicy, MergeMode, MergeStyle, Prompts,
36    ResolvedRoles,
37};
38use crate::fixer;
39use crate::git;
40use crate::graft;
41use crate::land;
42use crate::proc::Quiet as _;
43use crate::prompt::{
44    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
45};
46use crate::queue;
47#[cfg(test)]
48use crate::refs;
49use crate::run::{
50    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
51    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord,
52    GithubTextChoice, GraftOutcome, GraftRecord, Handover, JobRecord, JobStatus, Judgement,
53    MergeOutcome, OperatorFixFinding, OperatorFixOutcome, OperatorFixRequest, Origin, ParkCause,
54    QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState, RunStatus, SeatHistory,
55    Tally, VoteRecord, summarize_verify, write_artifact,
56};
57use crate::verdict::{
58    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
59    ReviewVote, Severity,
60};
61
62/// Fixed commit message for graph-owned mechanical `verify.pre_gate` commits.
63pub const PRE_GATE_COMMIT_MESSAGE: &str = "magi: pre_gate (mechanical fixes)";
64
65/// Event node recorded by [`Runner::run_pre_gate`].
66pub(crate) const PRE_GATE_EVENT_NODE: &str = "pre_gate";
67
68/// Durable event text logged when [`Runner::run_pre_gate`] commits mechanical changes.
69pub(crate) fn pre_gate_commit_event(head: &str) -> String {
70    format!("committed mechanical fixes ({head})")
71}
72use crate::worktree_setup;
73
74/// Bytes of a failing command's output kept in an event, so the reason a run
75/// stopped is readable from the report without opening `run.json`.
76const EVENT_OUTPUT_TAIL: usize = 2_000;
77
78/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
79/// command's pid before releasing the build cache's lease.
80const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
81
82/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
83/// command's pid to actually exit before giving up and releasing anyway.
84///
85/// A timeout means the process was asked to die (`kill_on_drop`,
86/// `start_kill`), not that it already has — on Windows in particular that can
87/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
88/// the instant the command returns would let the very next acquirer (this
89/// run's own next round, another run's verification, the janitor's prune)
90/// start touching the same directory while it might still be writing to it,
91/// so this polls the actual pid — real confirmation, not a fixed guess —
92/// until it is gone or this ceiling is reached. It is still not full
93/// process-tree reaping: a grandchild the timed-out process spawned and that
94/// outlives it independently is invisible to a pid check, and continuing to
95/// observe and collect *that* stays a different piece of work with its own
96/// owner. Set generously because the common case returns early the moment
97/// the pid is confirmed gone, not because every timeout pays this in full.
98const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
99
100/// Consecutive review rounds with no tree progress (see
101/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
102/// instead of spending the rest of the round budget.
103///
104/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
105/// legitimately finds nothing left to change (its previous round's fix already
106/// covered it, and this round's reviewers re-raised only nits) looks the same
107/// as one that is spinning, for exactly one round. Two in a row is where the
108/// two stop being distinguishable, and a review round on this workload has
109/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
110/// third attempt at a tree that has not moved twice running is pure cost.
111/// This does not touch `review_rounds` itself, which stays the operator's
112/// call.
113pub(crate) const STAGNANT_LIMIT: usize = 2;
114
115/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
116/// a base that moved before giving up and leaving the run `Blocked` for a
117/// person.
118///
119/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
120/// that keeps moving faster than a run can catch it is not something more
121/// rebasing fixes, it is a person's call. Not the same *number as*
122/// `land_rounds` - this budget is spent before a pull request exists, land's
123/// after - but bounded for the identical reason, so it uses the same
124/// default. Counted across both call sites in [`Runner::finish_after_tally`]
125/// (once before review, once before the gate), because either one finding
126/// the base still moving is the same signal.
127pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
128
129/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
130/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
131/// reply held no [`FixReport`].
132///
133/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
134/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
135/// "I'll pause here until the `cargo make check` background run reports
136/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
137/// No `FixReport` was ever collected from that seat, and the run moved on to
138/// the next review round regardless.
139///
140/// Bounded independently of `review_rounds` and `graph.retries`: this
141/// recovers one seat's missing report mid-round, not a new round of review or
142/// an ordinary parse retry, and must not itself become the unbounded wait the
143/// rest of this module exists to avoid.
144const MAX_FIX_CONTINUATIONS: usize = 2;
145
146/// One queued agent invocation.
147///
148/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
149/// CLI hung up on its own stream is asked again from the same job rather than
150/// rebuilt from scratch. See [`Runner::resume_undelivered`].
151#[derive(Clone)]
152struct SeatJob {
153    spec: AgentSpec,
154    seat: SeatState,
155    cwd: PathBuf,
156    prompt: String,
157    timeout: Duration,
158    allow_write: bool,
159    sessions: bool,
160    artifacts: PathBuf,
161    stem: String,
162    /// The prompt for a seat that has been handed to another roster agent
163    /// (a fresh session): everything the original seat would have
164    /// remembered. `None` when `prompt` already carries it, as the first
165    /// ranking and the implement prompt do. Never a resume-style prompt.
166    handover: Option<String>,
167}
168
169/// How the graph reads one agent invocation.
170///
171/// Quota is split out from an ordinary failure on purpose: a rate-limited call
172/// is known to fail again if retried now, so the retry loop must not spend an
173/// attempt on it. `Dropped` is split out for the opposite reason: unlike
174/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
175/// error JSON, never the agent's answer — a caller that matched only
176/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
177/// left to read that JSON as if it were usable output. `resume_undelivered`
178/// is the only caller that acts on it; everywhere else it is reported like an
179/// ordinary failure.
180enum AgentOutcome {
181    /// A usable output.
182    Ok(AgentOutput),
183    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
184    Quota(AgentOutput),
185    /// The CLI hung up on its own stream after billed work. See
186    /// [`agent::AgentOutput::work_undelivered`].
187    Dropped(AgentOutput),
188    /// Any other failure: a timeout, a bad exit code, an empty reply.
189    Failed(String),
190    /// A resource prevented admission or interrupted execution. Not an agent
191    /// failure: never advance a fallback chain or spend an attempt on it.
192    /// Post-spawn interruptions carry a typed error into wave, which records
193    /// implementation preservation before returning this outcome. This outcome
194    /// alone is not proof that no source changes were made.
195    /// [`RunState::resource_block`] says why.
196    ResourceBlocked(String),
197}
198
199/// A request to park the run at its next node boundary.
200///
201/// Cloning is how the request travels: the loop keeps one handle and hands a
202/// clone to each [`Runner`], and every clone points at the same flag. There
203/// is no channel because there is nothing to send - the only message is
204/// "park", it is idempotent, and a flag cannot be missed by a receiver that
205/// was not listening yet.
206///
207/// The boundary is what makes this cheap. Every node writes the run's state
208/// before the next one starts, and every node skips what is already recorded:
209/// `prep` returns early once candidates exist, `implement` asks only the seats
210/// with nothing on disk, `judge` returns early once judgements exist. So a
211/// parked run resumes into exactly the node it stopped before, and no agent
212/// work is thrown away. Killing the process mid-node, by contrast, loses
213/// whatever the seats in flight had not yet written - which for an implement
214/// wave is an hour of paid work.
215///
216/// A [`Runner`] watches two independent handles of this type - see
217/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
218/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
219/// clone covering the whole daemon's lifetime and is never asked to un-park,
220/// which is correct exactly because nothing is dispatched after it fires.
221/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
222/// that parks for an interrupted task must go on to run other tasks
223/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
224/// reusing the daemon-wide one.
225#[derive(Debug, Clone, Default)]
226pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
227
228impl Pause {
229    /// A pause nobody has asked for yet.
230    #[must_use]
231    pub fn new() -> Self {
232        Self::default()
233    }
234
235    /// Ask the run to park at its next node boundary. Idempotent.
236    pub fn park(&self) {
237        self.0.store(true, Ordering::SeqCst);
238    }
239
240    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
241    /// fold into the run's own `park` event - so an operator reading the run
242    /// later knows this was a deliberate interrupt rather than a shutdown or
243    /// a binary swap. The first reason recorded wins; a park already in
244    /// flight is not relabelled by a second, unrelated request.
245    pub fn park_because(&self, reason: impl Into<String>) {
246        self.park_for(ParkCause::Interrupt {
247            reason: reason.into(),
248        });
249    }
250
251    /// [`Pause::park`], recording the structured cause. The first cause
252    /// recorded wins, like [`Pause::park_because`].
253    pub fn park_for(&self, cause: ParkCause) {
254        let mut reason_guard = self
255            .1
256            .lock()
257            .unwrap_or_else(std::sync::PoisonError::into_inner);
258        if reason_guard.is_none() {
259            *reason_guard = Some(cause);
260        }
261        drop(reason_guard);
262        self.park();
263    }
264
265    /// Has a park been asked for?
266    #[must_use]
267    pub fn parked(&self) -> bool {
268        self.0.load(Ordering::SeqCst)
269    }
270
271    /// Why the park was asked for, when the caller used [`Pause::park_because`].
272    #[must_use]
273    pub fn reason(&self) -> Option<String> {
274        self.cause().map(|c| c.label())
275    }
276
277    /// The structured cause, when one was recorded.
278    #[must_use]
279    pub fn cause(&self) -> Option<ParkCause> {
280        self.1
281            .lock()
282            .unwrap_or_else(std::sync::PoisonError::into_inner)
283            .clone()
284    }
285}
286
287/// Drives one run.
288pub struct Runner {
289    /// Run state; public so the CLI can report on it.
290    pub state: RunState,
291    roles: ResolvedRoles,
292    sem: Arc<Semaphore>,
293    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
294    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
295    /// this is never the same handle as `interrupt`.
296    pause: Pause,
297    /// Set when `magi serve`'s interrupt scheduler wants this specific run
298    /// parked at its next node boundary, to let a task marked
299    /// [`crate::queue::Task::interrupt`] run alone before this one carries
300    /// on. Unlike `pause`, a fresh, unshared handle per run - see
301    /// [`Runner::watch_interrupt`].
302    interrupt: Pause,
303}
304
305/// Where the branch's own commits start: its merge base with the base branch
306/// as the remote has it now, else with the recorded `base_commit`. A branch
307/// rebased onto a base that moved past `base_commit` would otherwise count
308/// the base's commits as its own under `base_commit..branch`.
309async fn review_base(
310    repo: &Path,
311    remote: &str,
312    base_branch: &str,
313    base_commit: &str,
314    branch: &str,
315) -> String {
316    review_base_checked(repo, remote, base_branch, base_commit, branch)
317        .await
318        .0
319}
320
321/// [`review_base`] plus whether the base was read from a freshly fetched
322/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
323/// never older than `base_commit`'s view of the base), but the answer is then
324/// not trusted to rewrite a pull request's title.
325async fn review_base_checked(
326    repo: &Path,
327    remote: &str,
328    base_branch: &str,
329    base_commit: &str,
330    branch: &str,
331) -> (String, bool) {
332    let tracking = format!("{remote}/{base_branch}");
333    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
334    if git::rev_exists(repo, &tracking).await
335        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
336        && !mb.is_empty()
337    {
338        return (mb, fresh);
339    }
340    let mb = git::merge_base(repo, base_commit, branch)
341        .await
342        .ok()
343        .filter(|mb| !mb.is_empty())
344        .unwrap_or_else(|| base_commit.to_owned());
345    (mb, false)
346}
347
348/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
349/// when git cannot say or finds nothing: a stale list is better than a wrong
350/// or empty one.
351pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
352    if !is_review_run(state) {
353        return;
354    }
355    let base = review_base(
356        &state.repo,
357        &state.config.merge.remote,
358        &state.base_branch,
359        &state.base_commit,
360        branch,
361    )
362    .await;
363    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
364        && !subjects.is_empty()
365        && state.reviewed_commits.as_ref() != Some(&subjects)
366    {
367        state.reviewed_commits = Some(subjects);
368        state.save().ok();
369    }
370}
371
372/// Subjects of the base's commits between the recorded start and the branch's
373/// merge base: what a stale `base_commit..branch` would have mistaken for the
374/// branch's own work.
375async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
376    let (base, trusted) = review_base_checked(
377        &state.repo,
378        &state.config.merge.remote,
379        &state.base_branch,
380        &state.base_commit,
381        branch,
382    )
383    .await;
384    if !trusted {
385        return None;
386    }
387    git::subjects(&state.repo, &state.base_commit, &base)
388        .await
389        .ok()
390}
391
392/// May an adopted pull request's title be replaced with `computed`? Only when
393/// it is empty, magi's own shape, or a base commit's subject that leaked in;
394/// a title a person wrote stays. Never when `computed` is itself a leak.
395pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
396    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
397    if is_leak(computed) {
398        return false;
399    }
400    let cur = current.trim();
401    cur.is_empty()
402        || cur.starts_with(REVIEW_PROMPT_OPENING)
403        || cur.starts_with("chore: land candidate")
404        || cur.starts_with("magi: candidate")
405        || is_leak(cur)
406}
407
408/// The commit a run branches from: the base branch as the remote has it.
409///
410/// Two failures this replaces. A run used to branch off `HEAD` and so refused
411/// to start on a dirty tree, which made `magi serve` decline every task for as
412/// long as the operator had work in progress - most of the time. Branching off
413/// the *local* base branch fixed that and introduced a worse one: `land` merges
414/// the winner on GitHub, nothing updates the local ref, and the next run
415/// branches off a base missing everything the previous runs landed. Two tasks
416/// in a row from a phone would have had the second silently re-implementing
417/// against stale code and opening a pull request that reverted the first.
418///
419/// Only refs move here - no checkout, no local branch, no merge - so it is safe
420/// with uncommitted work in the tree. A machine with no network still starts:
421/// the fetch may fail and the local tip is used with a warning, because
422/// refusing to run offline is a worse failure than running against a base the
423/// operator can see for themselves.
424///
425/// One function, called by both entry points. Two answers to "where does a run
426/// branch from" is the kind of drift nobody notices until a diff is wrong.
427/// Bring the local `branch` in line with `<remote>/<branch>` before a review
428/// checks it out.
429///
430/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
431/// anything other than plain `git push` from this checkout (a jj colocated
432/// workspace, another clone) moves only the remote-tracking ref - so the local
433/// one can be a stale placeholder. It moves only when local is behind the remote or is an
434/// empty placeholder that diverged from it; unpushed local work is kept, and a real
435/// divergence is refused rather than guessed at.
436async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
437    let tracking = format!("{remote}/{branch}");
438    let fetched = git::fetch(repo, remote, branch).await;
439    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
440    let local_exists = git::branch_exists(repo, branch).await?;
441    if !fresh {
442        if !local_exists {
443            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
444        }
445        tracing::warn!(
446            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
447        );
448        return Ok(());
449    }
450    let remote_sha = git::rev_parse(repo, &tracking).await?;
451    if !local_exists {
452        git::git(repo, &["branch", branch, &tracking]).await?;
453        return Ok(());
454    }
455    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
456    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
457        return Ok(());
458    }
459    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
460        // Diverged. `reconcile` settles it only when it can prove nothing is
461        // lost: a local tip that is the remote's change rebased is pushed over
462        // it (lease pinned to the tip read here), a tip whose every extra
463        // commit is empty is a placeholder the remote's work replaced, and
464        // anything else is two different changes - a question for a person.
465        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
466            .await?
467        {
468            crate::reconcile::Reconciliation::Pushed => {
469                tracing::warn!(
470                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
471                    short(&local_sha),
472                    short(&remote_sha)
473                );
474                return Ok(());
475            }
476            crate::reconcile::Reconciliation::Placeholder => {}
477            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
478        }
479    }
480    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
481    if !out.ok() {
482        bail!(
483            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
484            short(&local_sha),
485            short(&remote_sha),
486            out.stderr
487        );
488    }
489    tracing::warn!(
490        "local `{branch}` was stale: fast-forwarded {} -> {}",
491        short(&local_sha),
492        short(&remote_sha)
493    );
494    Ok(())
495}
496
497async fn resolve_base(
498    repo: &Path,
499    base_branch: &str,
500    remote: &str,
501    coordination: Option<&crate::config::Coordination>,
502) -> Result<crate::run::FetchedBase> {
503    let _lease = crate::repo_lock::SeatLease::operation_with(
504        repo,
505        coordination,
506        &crate::repo_lock::WaitPolicy::current(),
507    )
508    .await?;
509    let tracking = format!("{remote}/{base_branch}");
510    let fetched = git::fetch(repo, remote, base_branch).await;
511    if let Ok(out) = &fetched
512        && out.ok()
513        && git::rev_exists(repo, &tracking).await
514    {
515        return Ok(crate::run::FetchedBase {
516            remote: remote.to_owned(),
517            branch: base_branch.to_owned(),
518            commit: git::rev_parse(repo, &tracking).await?,
519            fetched_at: jiff::Timestamp::now(),
520        });
521    }
522    let why = match &fetched {
523        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
524        Ok(_) => format!("{remote} has no {base_branch}"),
525        Err(e) => e.to_string(),
526    };
527    // No fallback to the local branch: it may be behind, and branching off an
528    // old commit is the stale-checkout bug this check exists to prevent.
529    bail!(
530        "cannot read {tracking} ({why}); refusing to branch off the local \
531         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
532         base / remote in magi.toml. This is launcher preparation: check the \
533         launcher's network, Git access and repository coordination before \
534         retrying"
535    )
536}
537
538/// Outcome of the shared fixer chain, before caller-owned stop policy.
539enum FixStep {
540    Resource,
541    Recorded { report_lost: bool },
542}
543
544/// Exclusive claim shared by targeted repairs and repository reassignment.
545/// Held before asynchronous fix preflight and released on every return or panic.
546///
547/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
548/// manual `magi fix` invocations against the same run are otherwise
549/// invisible to each other and would race to remove and recreate the same
550/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
551/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
552/// which is only ever reclaimed later, out of band, by
553/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
554/// `magi fix` invocation is not necessarily running under either of those, so
555/// nothing would ever sweep a lock a killed or crashed process left behind.
556/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
557/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
558/// lease use: an unreadable or unparsable pid, or a liveness query the
559/// platform cannot answer, reads as alive and the lock is left in place.
560pub(crate) struct FixClaim {
561    path: PathBuf,
562}
563
564impl FixClaim {
565    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
566        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
567        let path = dir.join("fix.lock");
568        let retry = crate::lock_file::Retry::new(None);
569        match Self::create(&path, retry) {
570            Ok(claim) => Ok(claim),
571            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
572                if Self::reclaim_if_dead(&path) {
573                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
574                } else {
575                    bail!(
576                        "another repair or `magi fix` is already running for this run ({} exists)",
577                        path.display()
578                    )
579                }
580            }
581            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
582        }
583    }
584
585    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
586        let mut f = retry.create(path)?;
587        use std::io::Write as _;
588        // Read back by `reclaim_if_dead` on a later, stuck invocation.
589        writeln!(f, "{}", std::process::id())?;
590        Ok(Self {
591            path: path.to_owned(),
592        })
593    }
594
595    /// True if the lock named a process confirmed dead, in which case it was
596    /// also removed. Never true on an unreadable file, an unparsable pid, or
597    /// a liveness query the platform cannot answer — see this type's own doc.
598    fn reclaim_if_dead(path: &Path) -> bool {
599        let dead = std::fs::read_to_string(path)
600            .ok()
601            .and_then(|body| body.trim().parse::<u32>().ok())
602            .is_some_and(|pid| !crate::proc::pid_alive(pid));
603        dead && std::fs::remove_file(path).is_ok()
604    }
605}
606
607impl Drop for FixClaim {
608    fn drop(&mut self) {
609        let _ = std::fs::remove_file(&self.path);
610    }
611}
612
613#[doc(hidden)]
614pub struct ExecutionLeaseGuard {
615    _lease: crate::driver::ExecutionLease,
616}
617
618#[doc(hidden)]
619pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
620    Ok(ExecutionLeaseGuard {
621        _lease: crate::driver::maintenance(home, run_id)?,
622    })
623}
624
625/// Holds the mutable runner as well as its durable lease: cancellation must
626/// clear both copies of ownership, including state a caller may save later.
627struct DriverExecution<'a> {
628    runner: &'a mut Runner,
629    driver: crate::driver::DriverGuard,
630}
631
632impl Drop for DriverExecution<'_> {
633    fn drop(&mut self) {
634        self.driver.release_local(&mut self.runner.state);
635    }
636}
637
638fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
639    if let Some(startup) = &mut state.startup {
640        startup.stage = stage.to_owned();
641    }
642    state.save()
643}
644
645/// Keep a reservation visible as blocked until startup finishes. A killed process
646/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
647struct StartupGuard {
648    id: String,
649    armed: bool,
650}
651
652impl StartupGuard {
653    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
654        state.startup = Some(crate::run::Startup {
655            kind: kind.to_owned(),
656            branch: branch.map(str::to_owned),
657            stage: "reserved".to_owned(),
658            complete: false,
659            failure: None,
660        });
661        state.status = RunStatus::Blocked;
662        state.reserve()?;
663        Ok(Self {
664            id: state.id.clone(),
665            armed: true,
666        })
667    }
668
669    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
670        startup_stage(state, stage)
671    }
672
673    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
674        let result = result.and_then(|()| {
675            state.startup.as_mut().expect("reserved startup").complete = true;
676            state.save()
677        });
678        self.armed = false;
679        match result {
680            Ok(()) => Ok(()),
681            Err(error) => {
682                let startup = state.startup.as_mut().expect("reserved startup");
683                startup.complete = false;
684                startup.failure = Some(format!("{error:#}"));
685                let context = crate::run::StartupFailure {
686                    run: state.id.clone(),
687                    stage: startup.stage.clone(),
688                };
689                // Repository assets may remain. Never infer that a failed startup
690                // is safe to resume or that an earlier owner has been restored.
691                state.status = RunStatus::Failed;
692                state.driver_exited = true;
693                state.event(
694                    "startup-failed",
695                    format!("{context}: {error:#}; retained assets require inspection"),
696                );
697                if let Err(save) = state.save() {
698                    tracing::warn!(
699                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
700                        state.id
701                    );
702                }
703                Err(error.context(context))
704            }
705        }
706    }
707}
708
709impl Drop for StartupGuard {
710    fn drop(&mut self) {
711        if self.armed
712            && let Ok(mut state) = RunState::load(&self.id)
713        {
714            state.status = RunStatus::Blocked;
715            state.driver_exited = true;
716            if let Some(startup) = &mut state.startup {
717                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
718            }
719            state.event(
720                "startup-interrupted",
721                "startup did not finish; inspect retained assets before recovery",
722            );
723            if let Err(error) = state.save() {
724                tracing::error!(
725                    "could not record interrupted startup {}: {error:#}",
726                    self.id
727                );
728            }
729        }
730    }
731}
732
733impl Runner {
734    /// A queue-side failure after construction must not strand an unexecuted run.
735    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
736        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
737            return error;
738        }
739        if let Some(startup) = &mut self.state.startup {
740            startup.stage = stage.to_owned();
741        } else {
742            // A resumed run already has execution history: do not rewrite it.
743            return error;
744        }
745        StartupGuard {
746            id: self.state.id.clone(),
747            armed: true,
748        }
749        .finish(&mut self.state, Err(error))
750        .expect_err("startup failed")
751    }
752
753    /// Start a fresh run against `repo`.
754    pub async fn start(
755        repo: &Path,
756        instruction: String,
757        config: Config,
758        origin: Origin,
759    ) -> Result<Self> {
760        Self::start_naming(repo, instruction, "", config, origin).await
761    }
762
763    /// [`Runner::start`] for a queued task. Titles and instructions never
764    /// select implementation sources. The title argument is retained for callers.
765    pub async fn start_naming(
766        repo: &Path,
767        instruction: String,
768        _also_scan: &str,
769        config: Config,
770        origin: Origin,
771    ) -> Result<Self> {
772        let repo = git::toplevel(repo).await?;
773        let missing = agent::missing_programs(&config.agents);
774        if !missing.is_empty() {
775            bail!(
776                "these agent programs are not on PATH: {}. Fix the roster in \
777                 magi.toml or install them.",
778                missing.join(", ")
779            );
780        }
781        let base_branch =
782            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
783                .await?;
784        let fetched_base = resolve_base(
785            &repo,
786            &base_branch,
787            &config.merge.remote,
788            config.coordination.as_ref(),
789        )
790        .await?;
791        let base_commit = fetched_base.commit.clone();
792        let roles = config.resolve_roles()?;
793        let max_parallel = config.graph.max_parallel.max(1);
794        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
795        // Capture task identity and repository assignment before the first
796        // save, so publication scope survives crashes and later task moves.
797        state.fetched_base = Some(fetched_base);
798        state.set_origin(origin)?;
799        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
800        state.status = RunStatus::Prep;
801        state.event("start", format!("run {} created", state.id));
802        startup.finish(&mut state, Ok(()))?;
803        Ok(Self {
804            state,
805            roles,
806            sem: Arc::new(Semaphore::new(max_parallel)),
807            pause: Pause::new(),
808            interrupt: Pause::new(),
809        })
810    }
811
812    /// Open a review-only run against work that already exists on `branch`.
813    ///
814    /// The expensive half of the graph is the implement wave — measured at
815    /// 111 and 134 internal tool-loop turns on this repository, against a
816    /// handful for a judge or a reviewer. The cheap half is worth running on
817    /// hand-written work too, and there was no way to reach it.
818    ///
819    /// No new state and no schema change are needed: a run with **one** viable
820    /// candidate and a tally already decided degrades `execute` to exactly
821    /// review → gate → merge, because `judge` skips a single-candidate field,
822    /// `deliberate` has fewer than two first choices to reconcile, `vote`
823    /// returns early, `tally` is already present and `fold_losers` has no
824    /// losers. Resuming such a run therefore does the right thing as well.
825    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
826        Self::review_taking_over(repo, branch, config, None, origin).await
827    }
828
829    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
830    /// at the same task still has `branch` checked out, its worktree is
831    /// released first if that is safe (see [`crate::handover`]), and the
832    /// review refuses with the reason if it is not. `None` is a hand-run
833    /// review: it has no earlier attempts, so only a worktree of a dead run
834    /// magi recorded itself can be released.
835    pub async fn review_taking_over(
836        repo: &Path,
837        branch: &str,
838        config: Config,
839        takeover: Option<crate::handover::Takeover>,
840        origin: Origin,
841    ) -> Result<Self> {
842        let repo = git::toplevel(repo).await?;
843        let missing = agent::missing_programs(&config.agents);
844        if !missing.is_empty() {
845            bail!(
846                "these agent programs are not on PATH: {}. Fix the roster in \
847                 magi.toml or install them.",
848                missing.join(", ")
849            );
850        }
851        let base_branch =
852            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
853                .await?;
854        if base_branch == branch {
855            bail!("`{branch}` is the base branch; there is nothing to review against");
856        }
857        let fetched_base = resolve_base(
858            &repo,
859            &base_branch,
860            &config.merge.remote,
861            config.coordination.as_ref(),
862        )
863        .await?;
864        let base_commit = fetched_base.commit.clone();
865
866        let roles = config.resolve_roles()?;
867        let max_parallel = config.graph.max_parallel.max(1);
868        let mut state = RunState::new(
869            repo.clone(),
870            base_branch,
871            base_commit.clone(),
872            format!("Review the work already on branch `{branch}`."),
873            config,
874        );
875        state.fetched_base = Some(fetched_base);
876        state.set_origin(origin)?;
877        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
878        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
879        let opened = async {
880            startup.stage(&mut state, "handover")?;
881
882            // Released before anything else touches the branch: a stale local
883            // branch is moved with `git branch -f`, which git refuses while an
884            // earlier attempt's worktree still has it checked out. Everything
885            // after this point that can fail puts the old run back.
886            // A hand-run review has no task, hence no earlier attempts, but a
887            // worktree of a dead run magi made may still be released.
888            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
889                earlier: Vec::new(),
890                home: crate::run::home(),
891                choice: None,
892                task_instruction: None,
893            });
894            let wait = repository_wait(&state, None);
895            let coordination_config = state.config.coordination.clone();
896            let coordination =
897                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
898                    .await?;
899            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
900            if let Some(released) = &released {
901                state.event(
902                    "release",
903                    format!(
904                        "took `{branch}` over from run {}: its worktree was released: {}",
905                        crate::run::short_of(&released.old_id),
906                        released.audit
907                    ),
908                );
909            }
910            let opened = async {
911                startup.stage(&mut state, "review-preflight")?;
912                // The owner's answer to an earlier divergence question is applied
913                // here: after the release (git will not move a checked-out branch)
914                // and before the sync that would otherwise ask again.
915                state.foreign_checkout = crate::handover::preflight_review(
916                    &repo,
917                    branch,
918                    &takeover.home,
919                    &state.config.merge.remote,
920                )
921                .await?;
922                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
923                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
924                }
925                if let Some(choice) = takeover.choice.as_ref()
926                    && let Err(e) =
927                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
928                            .await
929                {
930                    return Err(e.context("applying the owner's answer about the diverged branch"));
931                }
932                // An earlier attempt of this task that published the task head, and
933                // whose work is the branch under review, hands that head over: the
934                // review run updates the same pull request. Without one (a legacy
935                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
936                // own head and its own open pull request is adopted as before.
937                for id in takeover.earlier.iter().rev() {
938                    if let Ok(old) = RunState::load_under(id, &takeover.home)
939                        && let Some(head) = old.pr_head.clone()
940                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
941                    {
942                        state.pr_head = Some(head);
943                        break;
944                    }
945                }
946                drop(coordination);
947                startup.stage(&mut state, "open-review")?;
948                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
949            }
950            .await;
951            if opened.is_err()
952                && let Some(released) = &released
953            {
954                // Restoration is ownership checked and best effort. Keep the original
955                // startup cause even if reacquiring coordination is no longer possible.
956                match crate::repo_lock::SeatLease::operation_with(
957                    &repo,
958                    coordination_config.as_ref(),
959                    &wait,
960                )
961                .await
962                {
963                    Ok(_coordination) => {
964                        released.restore(&repo, branch).await;
965                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
966                            .map(|old| {
967                                format!(
968                                    "predecessor released_to={:?}; candidate path exists={}",
969                                    old.released_to,
970                                    old.candidates.iter().any(|c| {
971                                        c.branch == branch && c.worktree.exists()
972                                    }),
973                                )
974                            })
975                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
976                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
977                    }
978                    Err(error) => {
979                        tracing::warn!(
980                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
981                            state.id
982                        );
983                        state.event(
984                            "startup-restore",
985                            format!("restoration not attempted: {error:#}"),
986                        );
987                    }
988                }
989            }
990            opened
991        }
992        .await;
993        startup.finish(&mut state, opened)?;
994        Ok(Self {
995            state,
996            roles,
997            sem: Arc::new(Semaphore::new(max_parallel)),
998            pause: Pause::new(),
999            interrupt: Pause::new(),
1000        })
1001    }
1002
1003    /// Recover exactly the operator-selected public implementation, without touching old sources.
1004    pub async fn recover_pr(
1005        repo: &Path,
1006        task: &str,
1007        selection: crate::pr_recovery::Selection,
1008        mut config: Config,
1009    ) -> Result<Self> {
1010        selection.configure(&mut config)?;
1011        let assignment = crate::run::task_assignment_for(task)?;
1012        selection.check_task_assignment(task, &selection.instruction, assignment)?;
1013        let base_branch =
1014            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1015                .await?;
1016        let fetched_base = resolve_base(
1017            repo,
1018            &base_branch,
1019            &config.merge.remote,
1020            config.coordination.as_ref(),
1021        )
1022        .await?;
1023        let base_commit = fetched_base.commit.clone();
1024        selection
1025            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1026            .await?;
1027        Box::pin(selection.verify_source(repo)).await?;
1028        if let Some(proof) = &selection.source_proof {
1029            anyhow::ensure!(
1030                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1031                "source rebase base is outside the fetched landing base"
1032            );
1033        }
1034        let roles = config.resolve_roles()?;
1035        let max_parallel = config.graph.max_parallel.max(1);
1036        let mut state = RunState::new(
1037            repo.to_path_buf(),
1038            base_branch,
1039            base_commit.clone(),
1040            selection.instruction.clone(),
1041            config,
1042        );
1043        state.fetched_base = Some(fetched_base);
1044        state.set_origin(crate::run::Origin::queue(task))?;
1045        state.pr_head = Some(selection.branch.clone());
1046        state.pr_recovery = Some(selection.clone());
1047        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1048    }
1049
1050    async fn open_selected(
1051        repo: &Path,
1052        mut state: RunState,
1053        roles: ResolvedRoles,
1054        max_parallel: usize,
1055        base_commit: String,
1056        selection: crate::pr_recovery::Selection,
1057    ) -> Result<Self> {
1058        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1059        let opened = async {
1060            startup.stage(&mut state, "predecessors")?;
1061            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1062            startup.stage(&mut state, "open-selected")?;
1063            let branch = state.branch_for('A');
1064            let wait = repository_wait(&state, None);
1065            let prepared = async {
1066                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1067                git::git(repo, &["branch", &branch, selection.source()]).await?;
1068                drop(coordination);
1069                anyhow::Ok(())
1070            }
1071            .await;
1072            prepared?;
1073            state.event(
1074                "recovery",
1075                format!(
1076                    "selected implementation {} for {} (public lease {})",
1077                    selection.source(),
1078                    selection.url,
1079                    selection.head
1080                ),
1081            );
1082            let takeover = crate::handover::Takeover {
1083                earlier: Vec::new(),
1084                home: crate::run::home(),
1085                choice: None,
1086                task_instruction: Some(selection.instruction.clone()),
1087            };
1088            state.save()?;
1089            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1090        }
1091        .await;
1092        startup.finish(&mut state, opened)?;
1093        Ok(Self {
1094            state,
1095            roles,
1096            sem: Arc::new(Semaphore::new(max_parallel)),
1097            pause: Pause::new(),
1098            interrupt: Pause::new(),
1099        })
1100    }
1101
1102    /// What the newest earlier attempt that reviewed `branch` leaves for this
1103    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1104    /// no earlier attempts. Reads the earlier record only: ownership of its
1105    /// worktree and branch is [`crate::handover`]'s business.
1106    async fn inherit(
1107        repo: &Path,
1108        branch: &str,
1109        base_commit: &str,
1110        takeover: &crate::handover::Takeover,
1111    ) -> Option<crate::recovery::RecoveryRecord> {
1112        use crate::recovery::{Relation, assess};
1113        let newest = takeover.earlier.last()?;
1114        let mut chosen = None;
1115        for id in takeover.earlier.iter().rev() {
1116            if let Ok(old) = RunState::load_under(id, &takeover.home)
1117                && !old.reviews.is_empty()
1118                && (old.winner().is_some_and(|w| w.branch == branch)
1119                    || old.pr_head.as_deref() == Some(branch))
1120            {
1121                chosen = Some(old);
1122                break;
1123            }
1124        }
1125        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1126            .await
1127            .unwrap_or_default();
1128        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1129            Some(last) if last.head == tip => Relation::Same,
1130            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1131            _ => Relation::Diverged,
1132        };
1133        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1134        Some(assess(from, chosen.as_ref(), base_commit, relation))
1135    }
1136
1137    /// The half of [`Runner::review_taking_over`] that can fail after an
1138    /// earlier attempt's worktree was released.
1139    async fn open_review(
1140        repo: &Path,
1141        branch: &str,
1142        state: &mut RunState,
1143        base_commit: String,
1144        takeover: &crate::handover::Takeover,
1145    ) -> Result<()> {
1146        startup_stage(state, "review-sync")?;
1147        let wait = repository_wait(state, None);
1148        let _coordination = coordinate_operation(state, repo, &wait).await?;
1149        if state.foreign_checkout.is_some() {
1150            // Never reconcile or force-move a ref checked out by the operator.
1151            if state.pr_head.is_none() {
1152                state.pr_head = Some(branch.to_owned());
1153            }
1154        } else if state.pr_recovery.is_none() {
1155            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1156        }
1157        // The commit subjects are the closest thing to a task statement that
1158        // existing work carries, and the reviewers are told as much.
1159        let start = review_base(
1160            repo,
1161            &state.config.merge.remote,
1162            &state.base_branch,
1163            &base_commit,
1164            branch,
1165        )
1166        .await;
1167        let log = git::log_oneline(repo, &start, branch)
1168            .await
1169            .unwrap_or_default();
1170        let log_text = if log.trim().is_empty() {
1171            "(no commit messages)"
1172        } else {
1173            log.trim()
1174        };
1175        let mut instruction = format!(
1176            "Review the work already on branch `{branch}`. There is no task \
1177             statement: what the change claims to do is whatever its commits \
1178             say.\n\n{log_text}"
1179        );
1180        // A retry of a task whose earlier attempt left reviews behind carries
1181        // that attempt's evidence, and the task's own statement with it: the
1182        // completion criteria are the task's, not whatever the commits claim.
1183        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1184            if let Some(task) = takeover
1185                .task_instruction
1186                .as_deref()
1187                .filter(|t| !t.trim().is_empty())
1188                && rec.reviewed_head.is_some()
1189            {
1190                instruction = format!(
1191                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1192                    task.trim()
1193                );
1194                rec.criteria_inherited = true;
1195            }
1196            state.event("recovery", rec.summary());
1197            state.recovery = Some(rec);
1198        }
1199        if let Some(selected) = &state.pr_recovery {
1200            instruction = selected.instruction.clone();
1201        }
1202        state.task_instruction = takeover.task_instruction.clone();
1203        state.instruction = instruction;
1204        state.reviewed_commits = Some(
1205            git::subjects(repo, &start, branch)
1206                .await
1207                .unwrap_or_default(),
1208        );
1209
1210        // A takeover must not forget a hold that a previous review observed,
1211        // even if repairs have since removed it from the branch.
1212        for id in &takeover.earlier {
1213            if let Ok(old) = RunState::load_under(id, &takeover.home)
1214                && old.repo == state.repo
1215                && (old.pr_head.as_deref() == Some(branch)
1216                    || old.winner().is_some_and(|w| w.branch == branch))
1217            {
1218                for hold in old.branch_owner_holds {
1219                    if !state.branch_owner_holds.contains(&hold) {
1220                        state.event(
1221                            "approval-policy",
1222                            format!(
1223                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1224                                hold.control.key(),
1225                                hold.file,
1226                                hold.head
1227                            ),
1228                        );
1229                        state.branch_owner_holds.push(hold);
1230                    }
1231                }
1232            }
1233        }
1234        // Select the actual review tip before observing owner policy. A foreign
1235        // checkout can lag its remote descendant, and repairs must not erase
1236        // holds introduced only on that selected commit.
1237        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1238            let tracking = format!("{}/{branch}", state.config.merge.remote);
1239            // A surviving tracking ref is not evidence that the remote still
1240            // offers this tip. Adopt it only after a successful fetch here.
1241            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1242            let mut head = checkout.synced_head.clone();
1243            if matches!(fetched, Ok(out) if out.ok()) {
1244                let remote = git::rev_parse(repo, &tracking).await?;
1245                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1246                    head = remote;
1247                }
1248            }
1249            head
1250        } else {
1251            git::rev_parse(repo, branch).await?
1252        };
1253        state.observe_branch_owner_holds(&reviewed_head).await;
1254
1255        // An attached worktree, so the fixer's commits land on the branch under
1256        // review rather than on a detached head nobody will look at again.
1257        let worktree = state.worktree_root().join("under-review");
1258        if let Some(parent) = worktree.parent() {
1259            tokio::fs::create_dir_all(parent).await.ok();
1260        }
1261        let path = worktree.to_string_lossy().to_string();
1262        let review_branch = if state.foreign_checkout.is_some() {
1263            let shadow = format!("magi/{}/review", state.short());
1264            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1265            shadow
1266        } else {
1267            branch.to_owned()
1268        };
1269        startup_stage(state, "review-checkout")?;
1270        git::git(repo, &["worktree", "add", &path, &review_branch])
1271            .await
1272            .with_context(|| {
1273                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1274            })?;
1275
1276        startup_stage(state, "worktree-setup")?;
1277        let setup = match ensure_setup_config(state, repo).await {
1278            Ok(()) => {
1279                worktree_setup::prepare_with(
1280                    &state.config,
1281                    repo,
1282                    &worktree,
1283                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1284                )
1285                .await
1286            }
1287            Err(e) => Err(e),
1288        };
1289        if let Err(e) = setup {
1290            git::worktree_remove_clean(repo, &worktree).await.ok();
1291            return Err(e);
1292        }
1293        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1294            .await
1295            .unwrap_or(0);
1296        if commits == 0 {
1297            git::worktree_remove_clean(repo, &worktree).await.ok();
1298            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1299        }
1300        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1301            .await
1302            .map(|f| f.len())
1303            .unwrap_or(0);
1304        if files == 0
1305            && let (Ok(head_tree), Ok(base_tree)) = (
1306                git::tree_of(&worktree, "HEAD").await,
1307                git::tree_of(&worktree, &base_commit).await,
1308            )
1309            && head_tree == base_tree
1310        {
1311            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1312            git::worktree_remove_clean(repo, &worktree).await.ok();
1313            bail!(
1314                "`{branch}` at {} has a tree identical to base {}; this usually means \
1315                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1316                 against `{}/{branch}`) rather than an empty change",
1317                short(&head),
1318                short(&base_commit),
1319                state.config.merge.remote
1320            );
1321        }
1322        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1323            .await
1324            .unwrap_or_default();
1325
1326        state.candidates.push(Candidate {
1327            index: 0,
1328            label: 'A',
1329            // Not an agent id on purpose: nothing in the roster wrote this, and
1330            // the stats tables must not credit anyone with a win for it.
1331            agent: EXISTING_BRANCH.to_owned(),
1332            branch: review_branch,
1333            worktree,
1334            summary: String::new(),
1335            stat,
1336            files,
1337            commits,
1338            empty: false,
1339            failed: None,
1340            verified_noop: None,
1341            duration_ms: 0,
1342            folded: false,
1343        });
1344        state.tally = Some(Tally {
1345            first_choice: BTreeMap::from([('A', 0)]),
1346            borda: BTreeMap::new(),
1347            winner: 'A',
1348            rankings: 0,
1349            unanimous_initial: false,
1350            deliberated: false,
1351            changed_votes: 0,
1352            unanimous_final: false,
1353            tie_break: None,
1354            // No panel sat, so no quorum applies. Zero judges is the correct
1355            // number for work that never competed, and must not be reported as
1356            // a collapsed panel.
1357            judges: 0,
1358            present: 0,
1359            quorum: 0,
1360            met_quorum: true,
1361            uncontested: Some("review-only run: nothing competed".to_owned()),
1362        });
1363        state.status = RunStatus::Reviewing;
1364        state.prep_complete = Some(true);
1365        state.event(
1366            "start",
1367            format!(
1368                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1369                state.id
1370            ),
1371        );
1372        Ok(())
1373    }
1374
1375    /// Authorize one bounded synchronization interval, under the caller's queue task
1376    /// claim and the same owner/execution locks used by run maintenance.
1377    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1378        Self::authorize_base_recovery_request(home, id, task, false, None, None).await
1379    }
1380
1381    /// Authorize a known preparation failure against the inspected evidence.
1382    pub async fn authorize_base_preparation_recovery(
1383        home: &Path,
1384        id: &str,
1385        task: &str,
1386        digest: &str,
1387    ) -> Result<()> {
1388        Self::authorize_base_recovery_request(home, id, task, false, None, Some(digest)).await
1389    }
1390
1391    /// Queue release uses its durable approval generation exactly once.
1392    pub(crate) async fn authorize_base_recovery_from_resumption(
1393        home: &Path,
1394        id: &str,
1395        task: &str,
1396    ) -> Result<()> {
1397        Self::authorize_base_recovery_request(home, id, task, true, None, None).await
1398    }
1399
1400    pub(crate) async fn authorize_base_recovery_control(
1401        home: &Path,
1402        task: &str,
1403        control: &mut crate::base_recovery_control::Transaction,
1404    ) -> Result<()> {
1405        let id = control.request.run.clone();
1406        Self::authorize_base_recovery_request(home, &id, task, false, Some(control), None).await
1407    }
1408
1409    async fn authorize_base_recovery_request(
1410        home: &Path,
1411        id: &str,
1412        task: &str,
1413        resumption: bool,
1414        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1415        terminal_digest: Option<&str>,
1416    ) -> Result<()> {
1417        let _owner = crate::pr_head::owner_lock(home, id)?;
1418        let mut state = RunState::load_under(id, home)?;
1419        crate::pr_head::ensure_owner(&state)?;
1420        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1421        anyhow::ensure!(
1422            queued.execution_runs().last().is_some_and(|run| run == id)
1423                && queued.assignment_accepts(&state)
1424                && queued.status != crate::queue::TaskStatus::Done
1425                && !queued.fresh_start
1426                && queued.review_branch.is_none(),
1427            "run task ownership changed"
1428        );
1429        anyhow::ensure!(
1430            state
1431                .origin
1432                .as_ref()
1433                .and_then(|o| o.task.as_deref())
1434                .is_none_or(|owner| owner == task),
1435            "run belongs to another task"
1436        );
1437        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1438        anyhow::ensure!(
1439            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1440            "run is live or its ownership is unknown"
1441        );
1442        // Judge the previous driver's lease before acquiring our maintenance
1443        // lease. The owner lock excludes new driver claims across both steps.
1444        let _execution = crate::driver::maintenance(home, id)?;
1445        anyhow::ensure!(
1446            state.status.resumable()
1447                && state.released_to.is_none()
1448                && state.retired_to.is_none()
1449                && state.pr_taken_over_by.is_none(),
1450            "run ownership is final"
1451        );
1452        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1453        anyhow::ensure!(
1454            !state.pr_publication_pending
1455                && !crate::handover::landing_checkpoint(&state)
1456                && state.merge_decision.is_none(),
1457            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1458        );
1459        let winner = state.winner().context("run has no retained winner")?;
1460        anyhow::ensure!(
1461            git::is_clean(&winner.worktree).await?,
1462            "retained worktree has uncommitted changes"
1463        );
1464        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1465        anyhow::ensure!(
1466            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1467            "retained worktree does not match the winner branch"
1468        );
1469        if let Some(control) = control.as_ref() {
1470            anyhow::ensure!(
1471                head.starts_with(&control.request.head),
1472                "retained HEAD changed since the owner request"
1473            );
1474            anyhow::ensure!(
1475                state
1476                    .base_sync_recovery
1477                    .stop
1478                    .as_ref()
1479                    .is_none_or(|stop| stop.head == head),
1480                "retained HEAD differs from the recorded stop head; inspect it first"
1481            );
1482        }
1483        anyhow::ensure!(
1484            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1485            "{}",
1486            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1487        );
1488        state.ensure_base_episode();
1489        state.record_base_sync_stop(&head);
1490        let preparation = state.unknown_preparation_stop(&head);
1491        anyhow::ensure!(
1492            state
1493                .base_sync_recovery
1494                .stop
1495                .as_ref()
1496                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted)
1497                || (preparation && !resumption),
1498            "base recovery refused: missing eligible movement-exhaustion or preparation-stop evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1499        );
1500        let fetched =
1501            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1502        anyhow::ensure!(
1503            fetched.ok(),
1504            "cannot authorize base recovery without a fetched base"
1505        );
1506        let approved_tip = git::rev_parse(
1507            &state.repo,
1508            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1509        )
1510        .await?;
1511        let preparation_digest = state.preparation_digest(&head);
1512        anyhow::ensure!(
1513            preparation
1514                || (terminal_digest.is_none()
1515                    && control
1516                        .as_ref()
1517                        .is_none_or(|c| c.request.evidence_digest.is_none())),
1518            "preparation evidence digest does not name an eligible preparation stop"
1519        );
1520        if preparation {
1521            anyhow::ensure!(
1522                crate::daemon::compatible_run_instruction(&state, &queued),
1523                "task instruction does not match the retained run"
1524            );
1525            if let Some(control) = control.as_ref() {
1526                anyhow::ensure!(
1527                    control.request.head == head
1528                        && control.request.evidence_digest.is_some()
1529                        && control.request.evidence_digest == preparation_digest
1530                        && control.request.decision.is_none(),
1531                    "preparation stop requires the full HEAD and current inspected evidence digest"
1532                );
1533            } else {
1534                anyhow::ensure!(
1535                    terminal_digest.is_some() && terminal_digest == preparation_digest.as_deref(),
1536                    "preparation stop requires the current inspected evidence digest"
1537                );
1538            }
1539            let stop = state.base_sync_recovery.stop.as_ref().unwrap();
1540            anyhow::ensure!(
1541                git::is_ancestor(&state.repo, &stop.tip, &approved_tip).await,
1542                "current base does not descend from the stopped base"
1543            );
1544            git::probe_rebase_preparation(
1545                &state,
1546                &head,
1547                &home.join("runs").join(id),
1548                &repository_wait(&state, None),
1549            )
1550            .await?;
1551        }
1552        if let Some(control) = control.as_deref_mut() {
1553            let queue = crate::queue::Queue::at(home.join("queue"));
1554            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1555            if let Some(prior) = state
1556                .base_sync_recovery
1557                .authorizations
1558                .iter()
1559                .find(|a| a.request.as_deref() == Some(&control.key()))
1560            {
1561                anyhow::ensure!(
1562                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1563                    "recovery request was consumed or invalidated; it cannot queue again"
1564                );
1565                return control.enqueue(&queue);
1566            }
1567        }
1568        if resumption {
1569            anyhow::ensure!(
1570                crate::daemon::compatible_run_instruction(&state, &queued),
1571                "resumption instruction does not match the retained run"
1572            );
1573            let approval = queued
1574                .resumption
1575                .as_ref()
1576                .context("no operator resumption")?;
1577            anyhow::ensure!(
1578                approval.instruction == queued.instruction,
1579                "resumption approval does not match the current task instruction"
1580            );
1581            state.authorize_base_sync_resumption(task, approval)?;
1582        } else {
1583            state.authorize_base_sync(task)?;
1584        }
1585        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1586        state
1587            .base_sync_recovery
1588            .authorizations
1589            .last_mut()
1590            .unwrap()
1591            .scope = Some(crate::base_sync_recovery::Scope {
1592            tip: approved_tip,
1593            instruction: queued.instruction.clone(),
1594            episode,
1595            preparation_digest,
1596        });
1597        if let Some(control) = control.as_deref_mut() {
1598            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1599            authorization.request = Some(control.key());
1600            authorization.generation = control.generation();
1601            authorization.decision = control.decision();
1602            authorization.question = control
1603                .request
1604                .decision
1605                .as_ref()
1606                .map(|_| control.request.request.clone());
1607        }
1608        state.event(
1609            "base-recovery",
1610            if preparation {
1611                "owner authorized the proven preparation-stop recovery; remaining budget retained; fresh verification required"
1612            } else {
1613                "owner authorized a bounded base synchronization interval; fresh verification required"
1614            },
1615        );
1616        state.save_under(home)?;
1617        if let Some(control) = control {
1618            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1619        }
1620        Ok(())
1621    }
1622
1623    /// Reopen an existing run.
1624    pub fn resume(id: &str) -> Result<Self> {
1625        let state = RunState::load(id)?;
1626        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1627        if state.startup.as_ref().is_some_and(|s| !s.complete)
1628            || (state.status == RunStatus::Prep
1629                && state.instruction.trim().is_empty()
1630                && state.candidates.is_empty()
1631                && state.prep_complete == Some(false))
1632        {
1633            bail!(
1634                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1635            );
1636        }
1637        crate::pr_head::ensure_owner(&state)?;
1638        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1639            bail!(
1640                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1641            );
1642        }
1643        if let Some(to) = &state.released_to {
1644            bail!(
1645                "run {} cannot be resumed: its worktree was released to run {}",
1646                state.short(),
1647                crate::run::short_of(to)
1648            );
1649        }
1650        let roles = state.config.resolve_roles()?;
1651        if let Some(id) = &state.config.graph.selected_implementer
1652            && state.candidates.iter().any(|c| c.agent != *id)
1653        {
1654            bail!(
1655                "replacement implementer pin does not match the saved candidates; task must stay held"
1656            );
1657        }
1658        let max_parallel = state.config.graph.max_parallel.max(1);
1659        Ok(Self {
1660            state,
1661            roles,
1662            sem: Arc::new(Semaphore::new(max_parallel)),
1663            pause: Pause::new(),
1664            interrupt: Pause::new(),
1665        })
1666    }
1667
1668    /// Walk the graph to a terminal state, skipping nodes already recorded.
1669    ///
1670    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1671    /// the phone - ends here, so this is the one place a run that ended
1672    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1673    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1674    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1675        // Allocate before polling: boxing inside an async wrapper would still
1676        // retain its construction frame while the nested graph is polled.
1677        Box::pin(self.execute_inner(None))
1678    }
1679
1680    pub(crate) async fn execute_sync_only(
1681        &mut self,
1682        request: crate::base_sync_only::Request,
1683    ) -> Result<()> {
1684        Box::pin(self.execute_inner(Some(request))).await
1685    }
1686
1687    async fn execute_inner(
1688        &mut self,
1689        sync_only: Option<crate::base_sync_only::Request>,
1690    ) -> Result<()> {
1691        anyhow::ensure!(
1692            self.state.startup.as_ref().is_none_or(|s| s.complete),
1693            "startup incomplete; inspect retained evidence before explicit recovery"
1694        );
1695        if let Some(selection) = &self.state.pr_recovery
1696            && (selection.source_proof.is_some() || selection.source_run.is_some())
1697        {
1698            Box::pin(selection.verify_source(&self.state.repo)).await?;
1699        }
1700        // Queue claims cover daemon work; this also serializes manual drivers
1701        // consuming a repair answer, including the new review and decision.
1702        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1703            || self.state.land_approval.is_some()
1704            || self.state.merge_decision.is_some()
1705            || !self.state.merge_repairs.is_empty()
1706            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1707        {
1708            let claim = FixClaim::acquire(&self.state.dir())?;
1709            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1710            let disk = RunState::load(&self.state.id)?;
1711            let checkpoint = |s: &RunState| {
1712                (
1713                    s.merge_repairs.len(),
1714                    s.merge_repairs
1715                        .last()
1716                        .map(|r| (r.question.clone(), r.phase)),
1717                    s.land_approval
1718                        .as_ref()
1719                        .map(|a| (a.question.clone(), a.head.clone())),
1720                )
1721            };
1722            if checkpoint(&disk) != checkpoint(&self.state) {
1723                bail!(
1724                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1725                );
1726            }
1727            Some(claim)
1728        } else {
1729            None
1730        };
1731        let base_only = sync_only.is_some();
1732        let mut execution = self.claim_driver(sync_only).await?;
1733        let runner = &mut *execution.runner;
1734        let wait = runner.repository_wait();
1735        // Keep the graph's large future off the callers' stack, including
1736        // standalone task attempts running on a default-sized test thread.
1737        let result = if base_only {
1738            wait.scope(Box::pin(async {
1739                let repo = runner.state.repo.clone();
1740                let result = async {
1741                    let _coordination = runner.coordinate(&repo).await?;
1742                    anyhow::ensure!(
1743                        !runner.pause.parked() && !runner.interrupt.parked(),
1744                        "paused before base synchronization"
1745                    );
1746                    crate::base_sync_only::sync(&mut runner.state).await
1747                }
1748                .await;
1749                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1750                pass.result = match result {
1751                    Ok(outcome) => outcome,
1752                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1753                };
1754                let summary = pass.summary();
1755                runner.state.event("base-sync-only", summary);
1756                runner.state.save()
1757            }))
1758            .await
1759        } else {
1760            wait.scope(Box::pin(runner.execute_graph())).await
1761        };
1762        let result = match result {
1763            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1764                record_repository_block(&mut runner.state, &e);
1765                runner.park_here()?;
1766                Ok(())
1767            }
1768            other => other,
1769        };
1770        execution.driver.finish(&mut runner.state).await?;
1771        let ended = if result.is_err() {
1772            Some({
1773                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1774                if let Err(error) = &result {
1775                    notice.message = format!(
1776                        "Run {} stopped with an error: {}",
1777                        runner.state.id,
1778                        error.to_string().lines().next().unwrap_or("unknown error")
1779                    );
1780                }
1781                notice
1782            })
1783        } else {
1784            crate::notices::run_ended(&runner.state)
1785        };
1786        if let Some(notice) = ended {
1787            crate::notices::raise(notice);
1788        }
1789        result
1790    }
1791
1792    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1793        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1794    }
1795
1796    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1797        let wait = self.repository_wait();
1798        coordinate_operation(&mut self.state, cwd, &wait).await
1799    }
1800
1801    /// Validate ownership and persist the driver claim in one critical section.
1802    async fn claim_driver(
1803        &mut self,
1804        sync_only: Option<crate::base_sync_only::Request>,
1805    ) -> Result<DriverExecution<'_>> {
1806        let owner = match crate::pr_head::owner_lock_wait(
1807            &crate::run::home(),
1808            &self.state.id,
1809            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1810        )
1811        .await
1812        {
1813            Ok(owner) => owner,
1814            Err(error) => {
1815                let detail = format!("worktree maintenance or ownership update: {error:#}");
1816                // Admission did not own run.json: retain this resource outcome
1817                // in memory for queue settlement without overwriting a concurrent
1818                // retirement or publication transaction.
1819                self.state.resource_block = Some(crate::run::ResourceBlock {
1820                    cause: crate::run::ResourceBlockCause::Other,
1821                    node: "start".into(),
1822                    kind: "worktree maintenance".into(),
1823                    detail: detail.clone(),
1824                    at: Timestamp::now(),
1825                });
1826                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1827            }
1828        };
1829        let disk = RunState::load(&self.state.id)?;
1830        crate::pr_head::ensure_owner(&disk)?;
1831        let now = Timestamp::now();
1832        let home = crate::run::home();
1833        let claim = crate::daemon::other_claim_for_run(&home, &disk.id, now)?;
1834        let assessment = disk.assess_liveness_under(&home, claim, now);
1835        // Only proven-live ownership refuses here. Unknown records (legacy runs
1836        // with no claim marker or process identity) fall through to the
1837        // exclusive execution lease taken just below, which is what actually
1838        // keeps a second driver out.
1839        anyhow::ensure!(
1840            assessment.verdict != crate::run::Liveness::Live,
1841            "{}",
1842            assessment.live_driver_refusal()
1843        );
1844        if let Some(to) = &disk.released_to {
1845            bail!(
1846                "run {} cannot continue: its worktree was released to run {}",
1847                self.state.short(),
1848                crate::run::short_of(to)
1849            );
1850        }
1851        anyhow::ensure!(
1852            serde_json::to_value(&disk.base_sync_recovery)?
1853                == serde_json::to_value(&self.state.base_sync_recovery)?,
1854            "base recovery changed since this run was loaded; reload the saved run"
1855        );
1856        anyhow::ensure!(
1857            disk.sync_only_passes == self.state.sync_only_passes,
1858            "base-only synchronization changed since this run was loaded; reload the saved run"
1859        );
1860        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1861        let mut execution = DriverExecution {
1862            runner: self,
1863            driver,
1864        };
1865        // Declare after the execution guard: on any claim error this short
1866        // lock must drop before that guard reloads and releases ownership.
1867        let _owner = owner;
1868        if let Some(request) = sync_only {
1869            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1870            anyhow::ensure!(
1871                request.run == disk.id,
1872                "sync-base-only request targets a different run"
1873            );
1874            let state = &mut execution.runner.state;
1875            let task_entry = state.next_pass_task_entry;
1876            *state = disk;
1877            state.next_pass_task_entry = task_entry;
1878            if state.pending_sync_only().is_some() {
1879                let pass_index = state.passes.len();
1880                let pass = state.sync_only_passes.last_mut().unwrap();
1881                anyhow::ensure!(
1882                    pass.request == request,
1883                    "interrupted base-only synchronization belongs to a different request"
1884                );
1885                pass.pass_index = pass_index;
1886            } else {
1887                let pass = crate::base_sync_only::Pass::new(request, state);
1888                state.sync_only_passes.push(pass);
1889            }
1890            if state.status == RunStatus::Failed {
1891                state.status = RunStatus::Blocked;
1892            }
1893        } else {
1894            anyhow::ensure!(
1895                disk.pending_sync_only().is_none(),
1896                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1897            );
1898            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1899                .await?;
1900        }
1901        let state = &mut execution.runner.state;
1902        // Moving again, so it is no longer parked. Set before the walk rather
1903        // than in `resume`, so every way of re-entering the graph clears it
1904        // and a card cannot claim a run is waiting to be resumed while the
1905        // agents are already working.
1906        state.parked = false;
1907        state.resource_wait = None;
1908        state.resource_block = None;
1909        // Any seat this state still lists as answering belongs to whatever
1910        // process last drove this run — this one included, if it crashed
1911        // mid-wave. Cleared and flushed immediately, before anything else
1912        // runs, so a resume can never show a seat as live when nothing is
1913        // asking it anything yet; the node that actually dispatches the next
1914        // wave repopulates it.
1915        state.clear_active();
1916        // Recorded in the same spot, and flushed together with the clear
1917        // above: this is the pid a reader checks (`RunState::liveness`) when
1918        // no daemon claim exists to answer "is a process still driving this
1919        // run" — a plain `magi run` / `magi review` typed into a terminal
1920        // claims nothing there. Always overwritten, never only-if-absent, so
1921        // a resumed run's stale pid from a previous, possibly-dead process
1922        // can never survive into this one's own report. Unlike
1923        // `clear_active`, this changes on every single `execute()` call, so
1924        // the save below is now unconditional rather than only-if-cleared.
1925        //
1926        // `driver_started_at` is recorded in the same breath, from this same
1927        // pid, so `liveness` can tell a live pid that is genuinely still us
1928        // apart from one the OS has since handed to an unrelated process —
1929        // see that field's own doc for why the pid alone is not enough.
1930        let pid = std::process::id();
1931        state.driver_pid = Some(pid);
1932        state.driver_started_at = crate::proc::process_started_at(pid);
1933        state.driver_exited = false;
1934        state.driver_claimed = Some(true);
1935        state.begin_pass();
1936        execution.driver.bind(state);
1937        state.save()?;
1938        execution.driver.record(state)?;
1939        Ok(execution)
1940    }
1941
1942    /// No conflict checkpoint proves dispatch was never reached. End that
1943    /// consumed generation so an owner can explicitly authorize a fresh one.
1944    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1945        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1946        if let Err(error) = &result
1947            && !error.is::<crate::repo_lock::ResourceBlocked>()
1948            && self
1949                .state
1950                .repair_grants
1951                .last()
1952                .is_some_and(|g| g.conflict.is_none())
1953        {
1954            self.state.repair_grants.last_mut().unwrap().phase =
1955                crate::repair_budget::Phase::Complete;
1956            self.state.status = RunStatus::Blocked;
1957            self.state.save()?;
1958            bail!(
1959                "{error:#}. The consumed reservation ended before editing-seat dispatch. Inspect its scratch tree, then authorize a new base-conflict grant with a new request ID and current --expect-pass {}; the old request will not dispatch again",
1960                self.state.passes.last().map_or(0, |p| p.index)
1961            );
1962        }
1963        result
1964    }
1965
1966    /// A grant owns only these repair attempts. Confirmation reviews cannot
1967    /// create another fixer allowance, and every operation is restart-checkpointed.
1968    async fn execute_granted_repair(&mut self) -> Result<()> {
1969        use crate::repair_budget::{Kind, Phase};
1970        let index = self.state.repair_grants.len() - 1;
1971        let winner = self
1972            .state
1973            .winner()
1974            .cloned()
1975            .context("repair winner missing")?;
1976        loop {
1977            let grant = self.state.repair_grants[index].clone();
1978            match grant.phase {
1979                Phase::Pending => {
1980                    if grant.spent >= grant.receipt.request.rounds {
1981                        self.state.repair_grants[index].phase = Phase::Complete;
1982                        self.state.status = RunStatus::Blocked;
1983                        self.state.save()?;
1984                        return Ok(());
1985                    }
1986                    if grant.spent == 0 && grant.receipt.request.kind == Kind::Review {
1987                        crate::repair_budget::verify_initial_review_grant(&self.state, &grant)
1988                            .await?;
1989                    }
1990                    // Reserve before dispatch. A crash can consume an attempt,
1991                    // but can never duplicate it or reset saved fixer history.
1992                    self.state.repair_grants[index].spent += 1;
1993                    self.state.repair_grants[index].phase = Phase::Fixing;
1994                    self.state.save()?;
1995                    match grant.receipt.request.kind {
1996                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1997                        Kind::Gate => {
1998                            let failed = self.state.gate.clone();
1999                            let _ = self.gate_fix_round(&winner, &failed).await?;
2000                        }
2001                        Kind::Review => {
2002                            let mut record = self
2003                                .state
2004                                .reviews
2005                                .last()
2006                                .cloned()
2007                                .context("review failure missing")?;
2008                            let round = record.round;
2009                            let step = self.run_fix_round(&winner, &mut record).await?;
2010                            self.state.reviews[round - 1] = record;
2011                            if matches!(step, FixStep::Recorded { report_lost: true }) {
2012                                self.state.repair_grants[index].phase = Phase::Complete;
2013                                self.state.status = RunStatus::Blocked;
2014                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
2015                                self.state.save()?;
2016                                return Ok(());
2017                            }
2018                            if matches!(step, FixStep::Resource) {
2019                                self.stop_for_resource()?;
2020                                return Ok(());
2021                            }
2022                            self.state.save()?;
2023                        }
2024                    }
2025                    if self.resource_halt()? {
2026                        return Ok(());
2027                    }
2028                }
2029                Phase::Fixing => {
2030                    if grant.receipt.request.kind == Kind::BaseConflict {
2031                        self.repair_base_conflict(false).await?;
2032                    }
2033                    // Interrupted fixers may have left source changes or an
2034                    // unpushed commit. Preserve them before fresh assessment.
2035                    let _coordination = self.coordinate(&winner.worktree).await?;
2036                    let rescued = git::rescue_commit(
2037                        &winner.worktree,
2038                        "magi: preserve interrupted granted repair",
2039                    )
2040                    .await?;
2041                    self.state.note_withheld("repair-grant", &rescued.withheld);
2042                    // Fresh checks must supersede even a same-head failure.
2043                    // Archive rather than erase failure evidence or counters.
2044                    self.state
2045                        .verification_history
2046                        .push(crate::run::VerificationEvidence {
2047                            superseded_by: None,
2048                            archived_at: Some(Timestamp::now()),
2049                            fixes_spent: Some(self.state.gate_fixes.len()),
2050                            gate_head: self.state.gate_head.take(),
2051                            gate_ran: std::mem::take(&mut self.state.gate_ran),
2052                            gate: std::mem::take(&mut self.state.gate),
2053                            e2e: self.state.head_e2e.take(),
2054                        });
2055                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
2056                        self.state
2057                            .verification_history
2058                            .push(crate::run::VerificationEvidence {
2059                                superseded_by: None,
2060                                archived_at: Some(Timestamp::now()),
2061                                fixes_spent: Some(self.state.gate_fixes.len()),
2062                                gate_head: None,
2063                                gate_ran: false,
2064                                gate: Vec::new(),
2065                                e2e: Some(e2e),
2066                            });
2067                    }
2068                    self.state.repair_grants[index].review_start = self.state.reviews.len();
2069                    self.state.repair_grants[index].head =
2070                        git::rev_parse(&winner.worktree, "HEAD").await?;
2071                    self.state.repair_grants[index].phase = Phase::Reviewing;
2072                    if grant.receipt.request.kind == Kind::BaseConflict {
2073                        self.state.base_sync_recovery.stop = None;
2074                        if let Some(sync) = &mut self.state.base_sync {
2075                            sync.tip = grant
2076                                .receipt
2077                                .request
2078                                .tip
2079                                .clone()
2080                                .context("repair base tip missing")?;
2081                            sync.conflict = None;
2082                            sync.behind = 0;
2083                        }
2084                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2085                    }
2086                    self.state.save()?;
2087                }
2088                Phase::Reviewing => {
2089                    self.review_loop_pass().await?;
2090                    if self.resource_halt()? {
2091                        return Ok(());
2092                    }
2093                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2094                    let reviewed = (self.state.reviews.len() > grant.review_start)
2095                        .then(|| self.state.reviews.last())
2096                        .flatten();
2097                    let review_passed = reviewed.is_some_and(|r| {
2098                        r.clean
2099                            && r.expected > 0
2100                            && r.answered == r.expected
2101                            && matches!(
2102                                r.e2e_status(),
2103                                E2eStatus::Passed | E2eStatus::NotConfigured
2104                            )
2105                            && ((r.e2e_status() == E2eStatus::NotConfigured
2106                                && self.state.config.verify.e2e.is_empty())
2107                                || r.verified_head.as_deref() == Some(head.as_str()))
2108                    });
2109                    let clean = review_passed && reviewed.is_some_and(|r| r.head == head);
2110                    if !clean {
2111                        let next = if review_passed
2112                            && let Some(r) = reviewed
2113                            && r.head != head
2114                        {
2115                            crate::repair_budget::prove_mechanical_pre_gate_commit(
2116                                &self.state,
2117                                r,
2118                                &head,
2119                            )
2120                            .await
2121                            .map(|_| Some(Phase::Reviewing))
2122                        } else if grant.receipt.request.kind == Kind::Review
2123                            && grant.spent < grant.receipt.request.rounds
2124                        {
2125                            crate::repair_budget::prove_review_target(&self.state, &head)
2126                                .await
2127                                .map(|_| Some(Phase::Pending))
2128                        } else {
2129                            Ok(None)
2130                        };
2131                        let next = match next {
2132                            Ok(next) => next,
2133                            Err(error) => {
2134                                if self.state.repair_grants[index]
2135                                    .checkpoint_provenance_retry(&head, &error)
2136                                {
2137                                    self.state.status = RunStatus::Blocked;
2138                                    self.state.event("repair-grant", format!(
2139                                        "pre-gate provenance unavailable; resume confirmation without spending repair budget: {error:#}"
2140                                    ));
2141                                    self.state.save()?;
2142                                    return Ok(());
2143                                }
2144                                None
2145                            }
2146                        };
2147                        if next == Some(Phase::Reviewing) {
2148                            self.state.repair_grants[index].review_start = self.state.reviews.len();
2149                            self.state.repair_grants[index].head = head;
2150                            self.state.repair_grants[index].phase = Phase::Reviewing;
2151                            self.state.status = RunStatus::Blocked;
2152                            self.state.event(
2153                                "repair-grant",
2154                                "pre-gate changed the reviewed head; resume for fresh review before publication",
2155                            );
2156                            self.state.save()?;
2157                            return Ok(());
2158                        }
2159                        // A confirmation review carries no additional fix budget.
2160                        self.state.repair_grants[index].phase = if next == Some(Phase::Pending) {
2161                            self.state.repair_grants[index].head = head;
2162                            Phase::Pending
2163                        } else {
2164                            Phase::Complete
2165                        };
2166                        self.state.status = RunStatus::Blocked;
2167                        self.state.event(
2168                            "repair-grant",
2169                            "fresh review did not clear the repaired head; no publication",
2170                        );
2171                        self.state.save()?;
2172                        if self.state.repair_grants[index].phase == Phase::Pending {
2173                            continue;
2174                        }
2175                        return Ok(());
2176                    }
2177                    self.state.repair_grants[index].phase = Phase::Gating;
2178                    self.state.save()?;
2179                }
2180                Phase::Gating => {
2181                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2182                    self.state.reconcile_verification_head(&head);
2183                    let wait = self.repository_wait();
2184                    if self
2185                        .state
2186                        .reviews
2187                        .last()
2188                        .is_none_or(|r| r.head != head || !r.clean)
2189                    {
2190                        self.state.status = RunStatus::Blocked;
2191                        self.state.repair_grants[index].phase = Phase::Complete;
2192                        self.state.event(
2193                            "repair-grant",
2194                            "head changed since fresh review; repair held",
2195                        );
2196                        self.state.save()?;
2197                        return Ok(());
2198                    }
2199                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2200                        return Ok(());
2201                    }
2202                    let outcomes = self.run_gate(&winner).await?;
2203                    if verify_inconclusive(&outcomes) {
2204                        return Ok(());
2205                    }
2206                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2207                    if after != head {
2208                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2209                        self.state.repair_grants[index].head = after;
2210                        self.state.repair_grants[index].phase = Phase::Reviewing;
2211                        self.state.status = RunStatus::Blocked;
2212                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2213                        self.state.save()?;
2214                        return Ok(());
2215                    }
2216                    let passed = outcomes.iter().all(CommandOutcome::ok);
2217                    // Follow-up grants owe the same guarded checkout delivery
2218                    // as the conflict repair that introduced the new head.
2219                    if passed
2220                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2221                    {
2222                        return Ok(());
2223                    }
2224                    self.state.repair_grants[index].succeeded = passed;
2225                    self.state.gate = outcomes;
2226                    self.state.gate_ran = true;
2227                    self.state.status = if passed {
2228                        RunStatus::Gating
2229                    } else {
2230                        RunStatus::Blocked
2231                    };
2232                    self.state.repair_grants[index].phase = if !passed
2233                        && grant.receipt.request.kind == Kind::Gate
2234                        && grant.spent < grant.receipt.request.rounds
2235                    {
2236                        Phase::Pending
2237                    } else {
2238                        Phase::Complete
2239                    };
2240                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2241                        // Persist publication debt with the successful checkpoint.
2242                        self.state.pr_publication_pending = true;
2243                    } else if passed {
2244                        self.state.status = RunStatus::Ready;
2245                    }
2246                    self.state.save()?;
2247                    if !passed {
2248                        continue;
2249                    }
2250                    // Existing PR ownership and push lease stay in place. The
2251                    // normal publisher owes the new reviewed/gated SHA, and
2252                    // land's fresh owner approval remains mandatory.
2253                    if self.state.config.merge.mode != MergeMode::Pr {
2254                        self.state.status = RunStatus::Ready;
2255                        self.state.event(
2256                            "repair-grant",
2257                            "repair verified locally; grant carries no merge authorization",
2258                        );
2259                        self.state.save()?;
2260                        return Ok(());
2261                    }
2262                    return self.merge().await;
2263                }
2264                Phase::Complete => return Ok(()),
2265            }
2266        }
2267    }
2268
2269    async fn execute_graph(&mut self) -> Result<()> {
2270        // Even a terminal run may reenter through an explicit recovery action.
2271        // Restore before prep shortcuts, saved conversations or graph nodes use
2272        // a disposable path; GC may already have removed its original objects.
2273        let archive_home = crate::run::home().canonicalize()?;
2274        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2275            let repo = self.state.repo.clone();
2276            let _coordination = self.coordinate(&repo).await?;
2277            ensure_setup_config(&mut self.state, &repo).await?;
2278            crate::retention::restore_execution_seats(
2279                &archive_home,
2280                &self.state,
2281                _coordination.as_ref(),
2282            )
2283            .await?;
2284        }
2285        self.state.configure_recovery_resume()?;
2286        if self
2287            .state
2288            .repair_grants
2289            .last()
2290            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2291        {
2292            return self.execute_granted_repair().await;
2293        }
2294        if self
2295            .state
2296            .repair_grants
2297            .last()
2298            .is_some_and(|g| !g.succeeded)
2299        {
2300            self.state.status = RunStatus::Blocked;
2301            self.state.save()?;
2302            return Ok(());
2303        }
2304        // Preservation may invalidate an old empty classification. Resolve it
2305        // before any resume shortcut can reuse a verdict or publish a branch.
2306        self.persist_candidates().await?;
2307        // A saved base stop outranks stage markers, including legacy Voting.
2308        // Recovery never reenters implementation, deliberation or voting.
2309        if self.state.base_sync_blocked() {
2310            self.sync_to_base().await?;
2311            if !self.state.base_sync_blocked()
2312                && self.state.status != RunStatus::AlreadyInBase
2313                && !self.resource_halt()?
2314            {
2315                self.finish_after_tally().await?;
2316            }
2317            return Ok(());
2318        }
2319        if self
2320            .state
2321            .merge_decision
2322            .as_ref()
2323            .is_some_and(|decision| !decision.closed)
2324            && self.state.status != RunStatus::Landing
2325        {
2326            if crate::merge_decision::resumable_hold(&self.state) {
2327                self.state.merge = Some(MergeOutcome {
2328                    mode: MergeMode::Pr,
2329                    ok: false,
2330                    detail: self
2331                        .state
2332                        .merge_decision
2333                        .as_ref()
2334                        .unwrap()
2335                        .target
2336                        .pr
2337                        .clone(),
2338                    empty: false,
2339                });
2340                self.run_land().await?;
2341                self.settle_questions();
2342                return Ok(());
2343            }
2344            bail!(
2345                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2346            );
2347        }
2348        if self.state.config.graph.selected_implementer.is_some()
2349            && self.state.status == RunStatus::Blocked
2350            && self.state.tally.is_none()
2351            && self.state.candidate_preservation.is_empty()
2352            && self.state.interrupted_implementations.is_empty()
2353        {
2354            bail!(
2355                "selected implementation is held; explicitly release the owning task to retry it"
2356            );
2357        }
2358
2359        if self.state.merge_repairs.last().is_some_and(|r| {
2360            matches!(
2361                r.phase,
2362                crate::run::MergeRepairPhase::Requested
2363                    | crate::run::MergeRepairPhase::Fixing
2364                    | crate::run::MergeRepairPhase::Reviewing
2365            )
2366        }) {
2367            if self.repair_merge_review().await? {
2368                self.run_land().await?;
2369            }
2370            self.settle_questions();
2371            return Ok(());
2372        }
2373        // Publication already passed review and gate. Resume only that node:
2374        // syncing to a newer base here could change the verified commit.
2375        if self.state.pr_publication_pending {
2376            self.merge().await?;
2377            if self.resource_halt()? {
2378                return Ok(());
2379            }
2380            self.state.save()?;
2381            self.settle_questions();
2382            return Ok(());
2383        }
2384        // A run that already lost its quorum never resumes into the verdict
2385        // machinery: `deliberate` and `vote` would otherwise clobber the
2386        // stalled marker back to Voting and the run would keep going past a
2387        // verdict that is no longer trustworthy. Everything already recorded is
2388        // kept, so the run stays resumable (or foldable) for a human to pick up.
2389        //
2390        // On --resume the run gets one chance to repair itself: the seats a
2391        // rate limit took out are re-asked. If their quota has since reset and
2392        // the quorum is restored, the run picks up and finishes; otherwise it
2393        // stays stale and still-resumable for a later retry. If it does not
2394        // recover, the returned status stays `Stalled` and nothing was
2395        // clobbered (the recovery only mutates entries for the lost seats).
2396        if self.state.status == RunStatus::Stalled {
2397            if self.recover_stall().await? {
2398                self.finish_after_tally().await?;
2399            } else {
2400                // Still below quorum: persist the marker and stay resumable.
2401                self.state.save()?;
2402            }
2403            return Ok(());
2404        }
2405        // A run parked inside `land` - watching CI, mid fix-round, or
2406        // waiting on the owner's merge approval - resumes directly into it,
2407        // never back through `prep`. Everything before `merge` already
2408        // concluded; that is the only way `status` reaches `Landing` in the
2409        // first place. Re-walking `review_loop` first would also be actively
2410        // wrong: its own status recomputation (see its doc) treats any
2411        // clean round as reason to set `status` to `Gating`, which would
2412        // clobber this marker before `merge` ever ran, and this run would
2413        // never find its way back into `land` at all.
2414        if self.state.status == RunStatus::Landing
2415            || crate::handover::landing_checkpoint(&self.state)
2416        {
2417            self.state.land_sync_pending = true;
2418            self.state.save()?;
2419            self.run_land().await?;
2420            // `run_land` may have settled the run right here - CI came back
2421            // green and the PR merged, say - without ever passing back
2422            // through `merge`'s own trailing call. Whatever it left `status`
2423            // as is what this has to read.
2424            self.settle_questions();
2425            return Ok(());
2426        }
2427        // A run parked at `merge` on the owner's word about a withheld PR text
2428        // resumes straight into `merge`. Re-walking the tail would sync to the
2429        // base again (possibly rebasing, possibly spending the fixer) after the
2430        // gate had passed, and then push a tree nobody reviewed or gated.
2431        if self.state.github_text.is_some()
2432            && self.state.merge.is_none()
2433            && self.state.status == RunStatus::Gating
2434        {
2435            self.merge().await?;
2436            if self.resource_halt()? {
2437                return Ok(());
2438            }
2439            self.state.save()?;
2440            return Ok(());
2441        }
2442        // A resource stop left the reserved synchronization unfinished. Reconcile
2443        // its exact HEAD and base before starting any earlier graph stage.
2444        if self.state.pending_base_operation().is_some() {
2445            return self.finish_after_tally().await;
2446        }
2447        if let Err(e) = self.prep().await {
2448            if e.is::<crate::repo_lock::ResourceBlocked>() {
2449                return Err(e);
2450            }
2451            self.state.status = RunStatus::Blocked;
2452            self.state
2453                .prep_failure
2454                .get_or_insert_with(|| format!("{e:#}"));
2455            self.state
2456                .event("prep", format!("preparation stopped: {e:#}"));
2457            self.state.save()?;
2458            return Err(e);
2459        }
2460        if self.park_here()? {
2461            return Ok(());
2462        }
2463        self.advise().await?;
2464        if self.park_here()? {
2465            return Ok(());
2466        }
2467        self.implement().await?;
2468        if self.park_here()? {
2469            return Ok(());
2470        }
2471        // `after_implement` already saved the state and settled any open
2472        // questions when it set this; nothing later in the graph has
2473        // anything to judge.
2474        if self.state.status == RunStatus::VerifiedNoop {
2475            return Ok(());
2476        }
2477        self.judge().await?;
2478        if self.park_here()? {
2479            return Ok(());
2480        }
2481        self.deliberate().await?;
2482        if self.park_here()? {
2483            return Ok(());
2484        }
2485        self.vote().await?;
2486        if self.park_here()? {
2487            return Ok(());
2488        }
2489        self.tally()?;
2490        // A verdict that lost its quorum is not trustworthy: do not review,
2491        // gate, or merge on it. Everything already done is kept, so the run
2492        // stays resumable (or foldable); the human can replace the agent that
2493        // ran out of quota and pick it up.
2494        if self.state.status == RunStatus::Stalled {
2495            // Persist the stalled marker now — the normal end-of-execute save
2496            // below is below this early return, and without it a resumed run
2497            // would reload a pre-tally status and keep going.
2498            self.state.save()?;
2499            return Ok(());
2500        }
2501        self.finish_after_tally().await?;
2502        Ok(())
2503    }
2504
2505    /// A wave could not start its agents because a shared resource stayed busy
2506    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2507    /// resumable. Unstarted seats have no result; completed peers retain
2508    /// their saved candidate state.
2509    fn stop_for_resource(&mut self) -> Result<()> {
2510        // Resource acquisition observes cancellation inside a node. Complete
2511        // the same durable park as every other node boundary before returning.
2512        if self.pause.parked() || self.interrupt.parked() {
2513            self.park_here()?;
2514            return Ok(());
2515        }
2516        if self.state.resource_block.is_some() {
2517            self.state.status = RunStatus::Blocked;
2518        }
2519        self.state.save()
2520    }
2521
2522    /// Stop walking the graph if a node ended on a resource block.
2523    fn resource_halt(&mut self) -> Result<bool> {
2524        if self.state.resource_block.is_none() {
2525            return Ok(false);
2526        }
2527        self.stop_for_resource()?;
2528        Ok(true)
2529    }
2530
2531    /// Park here if asked to, recording it in the run's own timeline.
2532    ///
2533    /// Returns whether the caller should stop walking the graph. The state is
2534    /// saved either way by the node that just finished; this adds the event so
2535    /// the operator's card says why a run that is neither finished nor moving
2536    /// is sitting where it is.
2537    fn park_here(&mut self) -> Result<bool> {
2538        let parking = self.pause.parked() || self.interrupt.parked();
2539        if !parking && self.state.resource_block.is_some() {
2540            self.stop_for_resource()?;
2541            return Ok(true);
2542        }
2543        // Either handle asking is enough - see `Pause`'s own doc for why
2544        // they are never the same one. `interrupt` is checked second so a
2545        // reason it carries is preferred in the message below over a plain
2546        // shutdown park racing it at the same boundary.
2547        if !self.pause.parked() && !self.interrupt.parked() {
2548            return Ok(false);
2549        }
2550        if self.state.parked {
2551            return Ok(true);
2552        }
2553        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2554        if let Some(block) = &mut self.state.resource_block
2555            && matches!(
2556                block.cause,
2557                crate::run::ResourceBlockCause::Cancelled { .. }
2558            )
2559        {
2560            block.cause = crate::run::ResourceBlockCause::Cancelled {
2561                park: cause.clone(),
2562            };
2563        }
2564        let why = match cause.as_ref().map(ParkCause::label) {
2565            Some(reason) => format!(
2566                "parked after `{}` ({reason}) — resume to carry on from here",
2567                self.state.status.as_str()
2568            ),
2569            None => format!(
2570                "parked after `{}` — resume to carry on from here",
2571                self.state.status.as_str()
2572            ),
2573        };
2574        self.state.event("park", why);
2575        self.state
2576            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2577        self.state.parked = true;
2578        self.state.save()?;
2579        Ok(true)
2580    }
2581
2582    /// Only a new explicit operator approval may retry failed preparation.
2583    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2584        if self.state.prep_failure.is_none() {
2585            return Ok(());
2586        }
2587        let failed_at = self
2588            .state
2589            .events
2590            .iter()
2591            .rev()
2592            .find(|event| event.node == "prep")
2593            .map_or(self.state.updated_at, |event| event.at);
2594        anyhow::ensure!(
2595            approval_at > failed_at,
2596            "preparation retry requires a new explicit release after the failure"
2597        );
2598        self.state.prep_failure = None;
2599        self.state.prep_complete = Some(false);
2600        self.state
2601            .event("prep-retry", "operator approved retry of preparation");
2602        Ok(())
2603    }
2604
2605    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2606    pub fn on_pause(&mut self, pause: Pause) {
2607        self.pause = pause;
2608    }
2609
2610    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2611    /// scheduler asking this one run - and no other - to park so a task
2612    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2613    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2614    /// handle.
2615    pub fn watch_interrupt(&mut self, pause: Pause) {
2616        self.interrupt = pause;
2617    }
2618
2619    /// Abandon this run's own open questions, once `status` has actually
2620    /// settled rather than merely paused.
2621    ///
2622    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2623    /// either back up with the candidates, the review round and the seat
2624    /// sessions already on disk, so a question an implementer asked mid-round
2625    /// may still get a real answer read by a real resume. Only the statuses
2626    /// `resumable` excludes are actually final: the run merged, it reached
2627    /// `Ready` with nothing left to do, it failed outright with no
2628    /// established point to continue from, or every candidate agreed, with
2629    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2630    /// every one of those the seat that asked is gone for good, exactly like
2631    /// the run being deleted under `magi run rm` - so the same cleanup
2632    /// applies, worded for what actually happened instead of "the run was
2633    /// deleted".
2634    ///
2635    /// Best-effort and silent on success: called from every place `status`
2636    /// can land on one of those three, including ones a resumed run revisits,
2637    /// so it must cost nothing when there was nothing open to begin with.
2638    fn settle_questions(&mut self) {
2639        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2640            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2641        }
2642    }
2643
2644    /// The tail of the graph after a trustworthy tally: fold losers, review,
2645    /// gate, merge, and persist.
2646    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2647        Box::pin(self.finish_after_tally_inner())
2648    }
2649
2650    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2651        // Before the losers are folded: their branches are what the graft
2652        // reads from.
2653        self.graft().await?;
2654        if self.resource_halt()? {
2655            return Ok(());
2656        }
2657        self.fold_losers().await?;
2658        // Before review starts, and again right before the gate: a run's
2659        // review rounds can themselves take long enough for the base to move
2660        // a second time, and the gate is the one node whose "green" gets
2661        // acted on.
2662        self.sync_to_base().await?;
2663        if self.hold_base_sync().await? || self.resource_halt()? {
2664            return Ok(());
2665        }
2666        if self.state.status == RunStatus::AlreadyInBase {
2667            return Ok(());
2668        }
2669        self.review_loop().await?;
2670        if self.resource_halt()? {
2671            return Ok(());
2672        }
2673        self.sync_to_base().await?;
2674        if self.hold_base_sync().await? || self.resource_halt()? {
2675            return Ok(());
2676        }
2677        if self.state.status == RunStatus::AlreadyInBase {
2678            return Ok(());
2679        }
2680        self.gate().await?;
2681        self.merge().await?;
2682        if self.resource_halt()? {
2683            return Ok(());
2684        }
2685        self.state.save()?;
2686        Ok(())
2687    }
2688
2689    // ---------------------------------------------------------------- prep
2690
2691    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2692    /// run with the step and its output in the event; it is never swallowed.
2693    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2694    /// resume starts over instead of finding candidates and missing seats.
2695    async fn setup_seat_worktree(
2696        &mut self,
2697        repo: &Path,
2698        wt: &Path,
2699        in_prep: bool,
2700        coordination: Option<&crate::repo_lock::SeatLease>,
2701    ) -> Result<()> {
2702        let result = match ensure_setup_config(&mut self.state, repo).await {
2703            Ok(()) => {
2704                worktree_setup::prepare_with(
2705                    &self.state.config,
2706                    repo,
2707                    wt,
2708                    crate::build_target::Coordination::Held(coordination),
2709                )
2710                .await
2711            }
2712            Err(e) => Err(e),
2713        };
2714        if let Err(e) = result {
2715            git::worktree_remove_clean(repo, wt).await.ok();
2716            if in_prep {
2717                self.rollback_prep(repo).await;
2718            }
2719            self.state.status = RunStatus::Blocked;
2720            self.state.event(
2721                "setup",
2722                format!("worktree setup failed in {}: {e:#}", wt.display()),
2723            );
2724            self.state.save()?;
2725            return Err(e);
2726        }
2727        Ok(())
2728    }
2729
2730    /// Undo everything `prep` created, so a resume re-runs it whole.
2731    async fn rollback_prep(&mut self, repo: &Path) {
2732        let root = self.state.worktree_root();
2733        for c in std::mem::take(&mut self.state.candidates) {
2734            if matches!(
2735                git::worktree_remove_clean(repo, &c.worktree).await,
2736                Ok(true)
2737            ) {
2738                git::branch_delete(repo, &c.branch).await.ok();
2739            } else {
2740                self.state.candidates.push(c);
2741            }
2742        }
2743        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2744        for j in 1..=seats {
2745            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2746                .await
2747                .ok();
2748        }
2749        for k in 1..=self.state.config.graph.advisors {
2750            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2751                .await
2752                .ok();
2753        }
2754    }
2755
2756    async fn prep(&mut self) -> Result<()> {
2757        if let Some(reason) = &self.state.prep_failure {
2758            bail!(
2759                "candidate preparation previously failed: {reason}; correct the source before retrying"
2760            );
2761        }
2762        if self
2763            .state
2764            .prep_complete
2765            .unwrap_or(!self.state.candidates.is_empty())
2766        {
2767            return Ok(());
2768        }
2769        let repo = self.state.repo.clone();
2770        // Includes rollback, config, refs, checkout creation and setup. No
2771        // repository mutation may precede the real shared lock acquisition.
2772        let _coordination = self.coordinate(&repo).await?;
2773        let base = self.state.base_commit.clone();
2774        let plan = self.state.sources.plan(&repo, &base).await?;
2775        self.rollback_prep(&repo).await;
2776        if !self.state.candidates.is_empty() {
2777            bail!(
2778                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2779            );
2780        }
2781        self.state.prep_complete = Some(false);
2782        self.state.status = RunStatus::Prep;
2783        self.state.save()?;
2784        let repo = self.state.repo.clone();
2785        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2786        let root = self.state.worktree_root();
2787        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2788
2789        // The hook is the write-time half of the blindness contract; the
2790        // presentation filter in `blind` is the half that cannot be bypassed.
2791        let hooks_dir = self.state.dir().join("hooks");
2792        if self.state.config.blind.commit_msg_hook {
2793            std::fs::create_dir_all(&hooks_dir)
2794                .with_context(|| format!("create {}", hooks_dir.display()))?;
2795            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2796            let path = hooks_dir.join("commit-msg");
2797            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2798            make_executable(&path)?;
2799            // Ref-counted rather than a plain idempotent set: with more than
2800            // one run able to be in flight in the same repository at once
2801            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2802            // true?" check cannot tell "another run of mine still needs
2803            // this" from "nobody does", and the run that happens to finish
2804            // first would disable the hook out from under a sibling still
2805            // relying on it.
2806            git::acquire_worktree_config(&repo).await?;
2807            self.state.enabled_worktree_config = true;
2808        }
2809
2810        // `[worktree] setup` hides its products per worktree, which needs the
2811        // same per-worktree config the hook does. Held until fold, like it.
2812        ensure_setup_config(&mut self.state, &repo).await?;
2813
2814        for (index, (spec, label)) in self
2815            .roles
2816            .implementers
2817            .clone()
2818            .into_iter()
2819            .zip(labels)
2820            .enumerate()
2821        {
2822            let branch = self.state.branch_for(label);
2823            let worktree = root.join(format!("cand-{label}"));
2824            // Persist intent before Git can leave a partially created tree.
2825            // Candidate registration follows setup, so it cannot inventory
2826            // crashes or refusals during creation itself.
2827            self.state.event(
2828                "prep-intent",
2829                serde_json::json!({
2830                    "branch": branch,
2831                    "worktree": worktree,
2832                    "start": start,
2833                    "picks": plan.picks,
2834                })
2835                .to_string(),
2836            );
2837            self.state.save()?;
2838            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2839            if self.state.config.blind.commit_msg_hook {
2840                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2841            }
2842            git::local_exclude(&worktree, "/.magi/").await?;
2843            if let Err(e) = worktree_setup::prepare_with(
2844                &self.state.config,
2845                &repo,
2846                &worktree,
2847                crate::build_target::Coordination::Held(_coordination.as_ref()),
2848            )
2849            .await
2850            {
2851                // Nothing of this prep may survive: a resume must start over,
2852                // not find half the candidates and skip the rest.
2853                git::worktree_remove_clean(&repo, &worktree).await.ok();
2854                git::branch_delete(&repo, &branch).await.ok();
2855                self.rollback_prep(&repo).await;
2856                self.state.status = RunStatus::Blocked;
2857                self.state
2858                    .event("prep", format!("worktree setup failed: {e:#}"));
2859                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2860                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2861                }
2862                self.state.save()?;
2863                return Err(e);
2864            }
2865            self.state.candidates.push(Candidate {
2866                index,
2867                label,
2868                agent: spec.id.clone(),
2869                branch,
2870                worktree,
2871                summary: String::new(),
2872                stat: String::new(),
2873                files: 0,
2874                commits: 0,
2875                empty: false,
2876                failed: None,
2877                verified_noop: None,
2878                duration_ms: 0,
2879                folded: false,
2880            });
2881            self.state.save()?;
2882            for pick in &plan.picks {
2883                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2884                {
2885                    self.state.status = RunStatus::Blocked;
2886                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2887                    self.state
2888                        .event("prep", format!("cannot apply referenced commit: {e}"));
2889                    self.state.save()?;
2890                    return Err(e);
2891                }
2892            }
2893        }
2894
2895        for j in 1..=self.roles.judges.len() {
2896            let wt = root.join(format!("judge-{j}"));
2897            if !wt.exists() {
2898                git::worktree_add_detached(&repo, &wt, &base).await?;
2899                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2900                    .await?;
2901            }
2902        }
2903
2904        // Disposable, detached checkouts for the design-deliberation stage's
2905        // advisor seats — the same shape as the judges' above, at the same
2906        // base commit, since advisors also only ever read. Sized off the
2907        // configured count directly rather than a resolved roster: unlike
2908        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2909        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2910        // `prep` has no `ResolvedRoles` field to read a count from here.
2911        if self.state.config.graph.advise {
2912            for k in 1..=self.state.config.graph.advisors {
2913                let wt = root.join(format!("advisor-{k}"));
2914                if !wt.exists() {
2915                    git::worktree_add_detached(&repo, &wt, &base).await?;
2916                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2917                        .await?;
2918                }
2919            }
2920        }
2921
2922        // A judge cannot tell it is looking at its own patch — the seats keep
2923        // separate conversations — but a panel that shares agents with the
2924        // field is less independent than it looks, and that is worth saying out
2925        // loud once per run rather than leaving it in the config.
2926        let authors: Vec<&str> = self
2927            .roles
2928            .implementers
2929            .iter()
2930            .map(|a| a.id.as_str())
2931            .collect();
2932        let overlap: Vec<String> = self
2933            .roles
2934            .judges
2935            .iter()
2936            .enumerate()
2937            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2938            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2939            .collect();
2940        if !overlap.is_empty() {
2941            let note = format!(
2942                "{} also authored a candidate; blind, but the panel is less \
2943                 independent than {} distinct agents would be",
2944                overlap.join(", "),
2945                self.roles.judges.len()
2946            );
2947            self.state.event("prep", note);
2948        }
2949
2950        self.state.event(
2951            "prep",
2952            format!(
2953                "{} candidates, {} judges, base {} ({})",
2954                self.state.candidates.len(),
2955                self.roles.judges.len(),
2956                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2957                self.state.base_branch
2958            ),
2959        );
2960        self.state.prep_complete = Some(true);
2961        self.state.status = RunStatus::Implementing;
2962        self.state.save()?;
2963        Ok(())
2964    }
2965
2966    // -------------------------------------------------------------- advise
2967
2968    /// The design-deliberation stage: independent, read-only advisor seats
2969    /// each sketch a design before any implementer touches the repository,
2970    /// and (when at least one produced a usable proposal) a synthesis seat
2971    /// blends them into a brief `implement` carries in every candidate's
2972    /// prompt.
2973    ///
2974    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2975    /// advisors` is the proposal count. Everything here is best-effort and
2976    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2977    /// that cannot reach quota, or a synthesis seat that produced nothing
2978    /// usable all leave `implement` exactly as it was before this stage
2979    /// existed — the task instruction alone — rather than failing the whole
2980    /// competition over an enrichment stage. Every outcome is still recorded
2981    /// as an event, so a run that got nothing from this stage says why.
2982    ///
2983    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2984    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2985    /// resumed run whose stage failed would re-run it, and re-spend the
2986    /// agent calls, on every reentry before `implement`.
2987    ///
2988    /// Also skipped once any candidate shows implementation progress — the
2989    /// exact predicate `implement` itself uses to decide a candidate is no
2990    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2991    /// is not enough: a run created by an older binary that predates this
2992    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2993    /// an already-`Implementing`-or-later run under this build would
2994    /// otherwise walk straight back through `prep` (a no-op once candidates
2995    /// exist) into this node and spawn every advisor seat against worktrees
2996    /// `prep` never recreated — after implementation has already started,
2997    /// which is exactly the invariant this stage exists to guarantee.
2998    async fn advise(&mut self) -> Result<()> {
2999        let implement_untouched = self
3000            .state
3001            .candidates
3002            .iter()
3003            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
3004        if !self.state.config.graph.advise || self.state.advise_attempted {
3005            return Ok(());
3006        }
3007        if !implement_untouched {
3008            self.state.event(
3009                "advise",
3010                "skipping the design-deliberation stage: at least one \
3011                 candidate already shows implementation progress, so this \
3012                 run is past the point the stage exists to run before"
3013                    .to_owned(),
3014            );
3015            self.state.advise_attempted = true;
3016            self.state.save()?;
3017            return Ok(());
3018        }
3019        let run_id = self.state.id.clone();
3020        let prompts = self.state.config.prompts.clone();
3021        let instruction = self.state.instruction.clone();
3022        let language = self.state.config.graph.language.clone();
3023        let root = self.state.worktree_root();
3024        let n = self.state.config.graph.advisors;
3025        let where_recorded = self.state.dir().join("run.json");
3026
3027        let seats = match self.state.config.advisors() {
3028            Ok(seats) if !seats.is_empty() => seats,
3029            Ok(_) => {
3030                self.state.event(
3031                    "advise",
3032                    format!(
3033                        "[graph] advisors is 0; skipping the design-deliberation \
3034                         stage and continuing without a synthesis brief (see {})",
3035                        where_recorded.display()
3036                    ),
3037                );
3038                self.state.advise_attempted = true;
3039                self.state.save()?;
3040                return Ok(());
3041            }
3042            Err(e) => {
3043                self.state.event(
3044                    "advise",
3045                    format!(
3046                        "could not resolve advisor seats ({e:#}); continuing \
3047                         without a design-deliberation brief (see {})",
3048                        where_recorded.display()
3049                    ),
3050                );
3051                self.state.advise_attempted = true;
3052                self.state.save()?;
3053                return Ok(());
3054            }
3055        };
3056
3057        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3058        let artifacts = agent::artifacts_dir(&self.state.dir());
3059        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
3060
3061        let mut jobs = Vec::new();
3062        for (i, spec) in seats.iter().cloned().enumerate() {
3063            let seat_key = format!("advisor-{}", i + 1);
3064            let seat = self.seat(&seat_key, &spec.id);
3065            jobs.push(SeatJob {
3066                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
3067                spec,
3068                seat,
3069                cwd: worktrees[i % worktrees.len()].clone(),
3070                timeout,
3071                allow_write: false,
3072                sessions: false,
3073                artifacts: artifacts.clone(),
3074                stem: seat_key,
3075                handover: None,
3076            });
3077        }
3078
3079        self.state.event(
3080            "advise",
3081            format!(
3082                "{} advisor seat(s) sketching a design in parallel",
3083                jobs.len()
3084            ),
3085        );
3086        let mut quota_losses = Vec::new();
3087        let cache = self.state.config.cache_dir();
3088        let ctx = WaveCtx {
3089            carry_seats: false,
3090            pauses: Some((&self.pause, &self.interrupt)),
3091            run: &run_id,
3092            node: "advise",
3093            prompts: &prompts,
3094            cache: cache.as_deref(),
3095            round: None,
3096        };
3097        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
3098        let results = ask_json_wave::<Proposal>(
3099            jobs,
3100            Arc::clone(&self.sem),
3101            self.state.config.graph.retries,
3102            &advisor_roster,
3103            &ctx,
3104            &mut quota_losses,
3105            &mut self.state,
3106            &|p: &Proposal| p.validate(),
3107        )
3108        .await;
3109        if self.state.resource_block.is_some() {
3110            return self.stop_for_resource();
3111        }
3112        self.state.quota.extend(quota_losses);
3113
3114        let mut records = Vec::with_capacity(results.len());
3115        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
3116            let agent_id = seat.agent.clone();
3117            self.state.seats.insert(seat.key.clone(), seat);
3118            match res {
3119                Ok((proposal, out)) => {
3120                    self.state
3121                        .event("advise", format!("advisor-{} proposed a design", i + 1));
3122                    records.push(advise::AdvisorRecord::proposed(
3123                        i + 1,
3124                        agent_id,
3125                        proposal,
3126                        out.duration_ms,
3127                    ));
3128                }
3129                Err(e) => {
3130                    self.state.event(
3131                        "advise",
3132                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3133                    );
3134                    records.push(advise::AdvisorRecord::failed(
3135                        i + 1,
3136                        agent_id,
3137                        e.to_string(),
3138                    ));
3139                }
3140            }
3141        }
3142
3143        let mut advice = advise::Advice {
3144            records,
3145            synthesis: None,
3146        };
3147        if advice.proposals().is_empty() {
3148            self.state.event(
3149                "advise",
3150                "no advisor produced a usable proposal; continuing without a \
3151                 synthesis brief"
3152                    .to_owned(),
3153            );
3154        } else {
3155            match self
3156                .synthesize_brief(
3157                    &advice,
3158                    &instruction,
3159                    &language,
3160                    &worktrees[0],
3161                    &artifacts,
3162                    &run_id,
3163                    &prompts,
3164                    cache.as_deref(),
3165                )
3166                .await
3167            {
3168                Ok(Some(text)) => {
3169                    self.state.event(
3170                        "advise",
3171                        "synthesized a design brief for the implementer".to_owned(),
3172                    );
3173                    advice.synthesis = Some(text);
3174                }
3175                Ok(None) => {
3176                    self.state.event(
3177                        "advise",
3178                        "the synthesis seat produced nothing usable; continuing \
3179                         without a design brief"
3180                            .to_owned(),
3181                    );
3182                }
3183                Err(e) => {
3184                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3185                        return Err(e);
3186                    }
3187                    self.state.event(
3188                        "advise",
3189                        format!("could not synthesize a design brief: {e:#}"),
3190                    );
3191                }
3192            }
3193        }
3194        advise::apply_reflection(&mut advice);
3195
3196        self.state.advice = Some(advice);
3197        self.state.advise_attempted = true;
3198        self.state.save()?;
3199        Ok(())
3200    }
3201
3202    /// The synthesis seat: reads every advisor's proposal and blends them
3203    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3204    /// out of [`Runner::advise`] only for readability — it is not called
3205    /// anywhere else.
3206    ///
3207    /// Picked the same way [`crate::talk`]'s standing conversation and
3208    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3209    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3210    /// order (a claude seat, else the first runnable agent in roster order)
3211    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3212    /// in [`crate::config`] for why a dedicated field exists here at all.
3213    #[allow(clippy::too_many_arguments)]
3214    async fn synthesize_brief(
3215        &mut self,
3216        advice: &advise::Advice,
3217        instruction: &str,
3218        language: &str,
3219        cwd: &Path,
3220        artifacts: &Path,
3221        run_id: &str,
3222        prompts: &Prompts,
3223        cache: Option<&Path>,
3224    ) -> Result<Option<String>> {
3225        let chain = agent::pick_chain(
3226            &self.state.config.agents,
3227            self.state.config.roles.synthesizer.as_ref(),
3228            &agent::installed,
3229            "synthesizer",
3230        )?;
3231        let proposals = advice.proposals();
3232        let mut prompt = prompt::with_overlay(
3233            prompt::synthesize_brief(instruction, &proposals, language),
3234            prompts.overlay("advise"),
3235        );
3236        if cache.is_some() {
3237            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3238            // below — see `prompt::build_cache_note`'s doc for why telling a
3239            // read-only seat to build through the shared cache is exactly how
3240            // a sandbox's write refusal gets misread as a defect.
3241            prompt.push('\n');
3242            prompt.push_str(&prompt::build_cache_note("advise", false));
3243        }
3244        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3245        // Each id is tried once, in order; a quota hit, error or unusable
3246        // answer moves to the next. The seat is single-turn (`sessions:
3247        // false`) and the prompt is the whole context, so a fallback agent
3248        // needs nothing carried over.
3249        let mut last = None;
3250        for (n, spec) in chain.iter().enumerate() {
3251            if n > 0 {
3252                self.state
3253                    .event("advise", format!("synthesis falling back to {}", spec.id));
3254            }
3255            let mut seat = self.seat("advise-synthesis", &spec.id);
3256            let wait = self.repository_wait();
3257            let outcome = wait
3258                .scope(agent::invoke(
3259                    spec,
3260                    &mut seat,
3261                    &Invocation {
3262                        coordination: self.state.config.coordination.as_ref(),
3263                        fetched_base: None,
3264                        cwd,
3265                        prompt: &prompt,
3266                        timeout,
3267                        allow_write: false,
3268                        sessions: false,
3269                        artifacts,
3270                        stem: &if n == 0 {
3271                            "advise-synthesis".to_owned()
3272                        } else {
3273                            format!("advise-synthesis-{}", spec.id)
3274                        },
3275                        run: run_id,
3276                        node: "advise",
3277                        cache_dir: None,
3278                        attachments: &[],
3279                        writable: &[],
3280                    },
3281                ))
3282                .await;
3283            if outcome.is_ok() {
3284                self.state.seats.insert(seat.key.clone(), seat);
3285            }
3286            let advance = agent::chain_advances(&outcome);
3287            last = Some(outcome);
3288            if !advance {
3289                break;
3290            }
3291        }
3292        // Exhausted: the last attempt's result is what a single failed seat
3293        // would have produced.
3294        let out = last.expect("a chain holds at least one agent")?;
3295        if !out.usable() {
3296            return Ok(None);
3297        }
3298        let text =
3299            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3300        Ok((!text.trim().is_empty()).then_some(text))
3301    }
3302
3303    // ----------------------------------------------------------- implement
3304
3305    async fn implement(&mut self) -> Result<()> {
3306        self.persist_candidates().await?;
3307        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3308        // agent files with `magi task add` name the run that paid for it. The
3309        // prompt overlay is cloned alongside it because the waves borrow it
3310        // while `self` is mutably borrowed by the node's own bookkeeping.
3311        let run_id = self.state.id.clone();
3312        let prompts = self.state.config.prompts.clone();
3313        let todo: Vec<usize> = self
3314            .state
3315            .candidates
3316            .iter()
3317            .enumerate()
3318            .filter(|(_, c)| {
3319                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3320                    && c.failed.is_none()
3321                    && !c.empty
3322            })
3323            .map(|(i, _)| i)
3324            .collect();
3325        if todo.is_empty() {
3326            return self.after_implement();
3327        }
3328        self.state.status = RunStatus::Implementing;
3329
3330        let language = self.state.config.graph.language.clone();
3331        let github_language = self.state.config.graph.github_language.clone();
3332        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3333        let sessions = self.state.config.graph.sessions;
3334        let artifacts = agent::artifacts_dir(&self.state.dir());
3335        // The design-deliberation stage's blended brief, when `advise` found
3336        // one — carried into every implementer's prompt the same way
3337        // regardless of which candidate it is.
3338        let brief = self
3339            .state
3340            .advice
3341            .as_ref()
3342            .and_then(|a| a.synthesis.as_deref())
3343            .map(str::to_owned);
3344        let attachments = self.state.attachments.clone();
3345
3346        let mut jobs = Vec::new();
3347        for &i in &todo {
3348            let (index, label, worktree) = {
3349                let c = &self.state.candidates[i];
3350                (c.index, c.label, c.worktree.clone())
3351            };
3352            let spec = self.roles.implementers[index].clone();
3353            let seat_key = format!("impl-{label}");
3354            let seat = self.seat(&seat_key, &spec.id);
3355            let instruction = seeded_instruction(&self.state);
3356            jobs.push(SeatJob {
3357                spec,
3358                seat,
3359                prompt: prompt::implement_in(
3360                    &instruction,
3361                    &worktree.to_string_lossy(),
3362                    &language,
3363                    &github_language,
3364                    brief.as_deref(),
3365                    &attachments,
3366                ),
3367                cwd: worktree,
3368                timeout,
3369                allow_write: true,
3370                sessions,
3371                artifacts: artifacts.clone(),
3372                stem: format!("impl-{label}"),
3373                handover: None,
3374            });
3375        }
3376
3377        self.state.event(
3378            "implement",
3379            format!("{} candidates in parallel", jobs.len()),
3380        );
3381        // Kept so a seat whose CLI hung up can be asked again from the same
3382        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3383        // can update a seat's own entry once a fallback agent takes it over —
3384        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3385        // whichever agent actually answered, not the one that quota'd out.
3386        let mut sent = jobs.clone();
3387        let cache = self.state.config.cache_dir();
3388        let ctx = WaveCtx {
3389            carry_seats: false,
3390            pauses: Some((&self.pause, &self.interrupt)),
3391            run: &run_id,
3392            node: "implement",
3393            prompts: &prompts,
3394            cache: cache.as_deref(),
3395            round: None,
3396        };
3397        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3398        if !wave_blocked(&results) {
3399            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3400                .await;
3401            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3402                .await?;
3403            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3404                .await;
3405        }
3406        // Do not finalize failed candidates when the entire wave needs machine
3407        // recovery: leaving them pending resumes this node with its work intact.
3408        if !results.is_empty()
3409            && results
3410                .iter()
3411                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3412        {
3413            let losses: Vec<_> = results
3414                .iter()
3415                .map(|(_, seat, out)| {
3416                    let AgentOutcome::Quota(o) = out else {
3417                        unreachable!()
3418                    };
3419                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3420                })
3421                .collect();
3422            self.state.quota.extend(losses.clone());
3423            for (_, seat, _) in results {
3424                self.state.seats.insert(seat.key.clone(), seat);
3425            }
3426            for &i in &todo {
3427                let label = self.state.candidates[i].label;
3428                self.state.interrupted_implementations.insert(label);
3429                self.state
3430                    .candidate_preservation
3431                    .insert(label, "machine outage awaiting persistence".into());
3432            }
3433            // Preserve partial edits too, while keeping every interrupted seat
3434            // pending even when its tree already contains an inherited patch.
3435            block_machine_outage(&mut self.state, "implement", &losses);
3436            self.state.save()?;
3437            self.persist_candidates().await?;
3438            for &i in &todo {
3439                self.state
3440                    .interrupted_implementations
3441                    .insert(self.state.candidates[i].label);
3442            }
3443            return self.stop_for_resource();
3444        }
3445        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3446
3447        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3448            && results
3449                .iter()
3450                .any(|(_, _, out)| FailClass::of(out).is_some());
3451        let base_commit = self.state.base_commit.clone();
3452        let blind_cfg = self.state.config.blind.clone();
3453        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3454        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3455            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3456                // Executed turns interrupted by disk pressure already carry
3457                // a preservation barrier from wave. Admission-only waits do
3458                // not. Keep the interrupted seat's session for recovery too.
3459                if self
3460                    .state
3461                    .candidate_preservation
3462                    .contains_key(&self.state.candidates[i].label)
3463                {
3464                    self.state.seats.insert(seat.key.clone(), seat);
3465                }
3466                continue;
3467            }
3468            let seat_key = seat.key.clone();
3469            // A quota fallback (`resume_seat_handovers`) may have handed this
3470            // seat to a different agent than the one `prep` recorded on the
3471            // candidate; the stats tables and any later fixer-defaults-to-
3472            // winner's-author lookup must credit whoever actually answered —
3473            // unless every fallback also quota'd out, in which case nobody
3474            // actually answered and crediting the last agent tried would
3475            // erase every earlier agent's own quota loss from the stats
3476            // tables instead of just this one seat's.
3477            let agent = seat.agent.clone();
3478            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3479            self.state.seats.insert(seat.key.clone(), seat);
3480            let label = self.state.candidates[i].label;
3481            let worktree = self.state.candidates[i].worktree.clone();
3482            self.state.interrupted_implementations.remove(&label);
3483
3484            let (sanitized_summary, duration, failed, verified_claim) = match out {
3485                AgentOutcome::Ok(o) => {
3486                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3487                    let failed = (!o.usable()).then(|| {
3488                        if o.timed_out {
3489                            "agent timed out".to_owned()
3490                        } else {
3491                            format!(
3492                                "agent exited with {}",
3493                                crate::notices::exit_status(o.exit_code)
3494                            )
3495                        }
3496                    });
3497                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3498                    let verified_claim = match verified_noop_claim_in_worktree(
3499                        failed.is_none(),
3500                        &o.commands,
3501                        &text,
3502                        &worktree,
3503                        &base_commit,
3504                    )
3505                    .await
3506                    {
3507                        NoopClaimVerdict::Accepted => {
3508                            if matches!(
3509                                verdict::parse_verified_noop(&sanitized_summary),
3510                                Some(Ok(_))
3511                            ) {
3512                                Some(sanitized_summary.clone())
3513                            } else {
3514                                rejected_noops.push((
3515                                    label,
3516                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3517                                ));
3518                                None
3519                            }
3520                        }
3521                        NoopClaimVerdict::Rejected(reason) => {
3522                            rejected_noops.push((label, reason));
3523                            None
3524                        }
3525                        NoopClaimVerdict::Absent => None,
3526                    };
3527                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3528                }
3529                // Left un-resumed by `resume_undelivered` (a dirty tree
3530                // already rescues the work, or there was no session left to
3531                // resume into) — reported like the ordinary failure it is,
3532                // never as if `o.text` (the CLI's raw error JSON) were an
3533                // answer.
3534                AgentOutcome::Dropped(o) => {
3535                    let why = o
3536                        .dropped
3537                        .as_ref()
3538                        .map(|d| d.why.as_str())
3539                        .unwrap_or("the CLI ended the stream without delivering its answer");
3540                    (
3541                        String::new(),
3542                        o.duration_ms,
3543                        Some(format!("the CLI dropped the stream ({why})")),
3544                        None,
3545                    )
3546                }
3547                AgentOutcome::Quota(o) => {
3548                    self.state.quota.push(QuotaLoss::from_report(
3549                        seat_key,
3550                        "implement",
3551                        o.quota.as_ref(),
3552                    ));
3553                    (
3554                        String::new(),
3555                        o.duration_ms,
3556                        Some("rate limited (quota); produced no change".to_owned()),
3557                        None,
3558                    )
3559                }
3560                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3561                    (String::new(), 0, Some(e), None)
3562                }
3563            };
3564
3565            // Save every completed turn before any fallible Git operation. A failed
3566            // rescue must not erase the reply or prevent collection of other seats.
3567            let c = &mut self.state.candidates[i];
3568            if !exhausted_the_fallback_chain {
3569                c.agent = agent;
3570            }
3571            c.summary = sanitized_summary;
3572            c.duration_ms = duration;
3573            c.failed = failed;
3574            c.verified_noop = verified_claim;
3575            self.state
3576                .candidate_preservation
3577                .insert(label, "awaiting persistence".to_owned());
3578        }
3579        self.state.save()?;
3580        self.persist_candidates().await?;
3581
3582        let mut recorded_rejection = false;
3583        for (label, reason) in rejected_noops {
3584            if self.state.interrupted_implementations.contains(&label) {
3585                continue;
3586            }
3587            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3588                && c.empty
3589            {
3590                c.verified_noop = None;
3591                c.failed
3592                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3593                self.state.event(
3594                    "implement",
3595                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3596                );
3597                recorded_rejection = true;
3598            }
3599        }
3600        if recorded_rejection {
3601            self.state.save()?;
3602        }
3603
3604        if resource_blocked {
3605            return self.stop_for_resource();
3606        }
3607        if selected_failed {
3608            self.state.status = RunStatus::Blocked;
3609            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3610            self.state.save()?;
3611            bail!(
3612                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3613            );
3614        }
3615        self.after_implement()
3616    }
3617
3618    /// Retry only persistence after a completed implementation turn.
3619    async fn persist_candidates(&mut self) -> Result<()> {
3620        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3621        for label in labels {
3622            let i = self
3623                .state
3624                .candidates
3625                .iter()
3626                .position(|c| c.label == label)
3627                .context("pending candidate is missing")?;
3628            let c = self.state.candidates[i].clone();
3629            let interrupted = self.state.interrupted_implementations.contains(&label);
3630            let result = async {
3631                let wait = crate::repo_lock::WaitPolicy::new(
3632                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3633                    || false,
3634                );
3635                let _coordination =
3636                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3637                // Best effort evidence requires no index writes. A successful snapshot
3638                // never authorizes removal of a tree whose rescue failed.
3639                if let Err(e) = git::snapshot_uncommitted(
3640                    &c.worktree,
3641                    &self
3642                        .state
3643                        .dir()
3644                        .join("artifacts")
3645                        .join(format!("candidate-{label}-recovery")),
3646                )
3647                .await
3648                {
3649                    self.state.event(
3650                        "preserve",
3651                        format!("candidate {label} snapshot incomplete: {e:#}"),
3652                    );
3653                }
3654                let rescued = git::rescue_commit(
3655                    &c.worktree,
3656                    &format!("magi: candidate {label} (uncommitted work)"),
3657                )
3658                .await?;
3659                self.state.note_withheld("implement", &rescued.withheld);
3660                let base = &self.state.base_commit;
3661                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3662                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3663                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3664                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3665                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3666                if c.empty && commits > 0 && !patch.trim().is_empty()
3667                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3668                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3669                        || self.state.tally.is_some())
3670                {
3671                    // Keep the old classification and pending marker so every
3672                    // retry stops too. Retain decisions as recovery evidence;
3673                    // only a supported recovery operation may replace them.
3674                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3675                }
3676                let c = &mut self.state.candidates[i];
3677                c.commits = commits;
3678                c.stat = stat;
3679                c.files = files;
3680                let no_changes = commits == 0 || patch.trim().is_empty();
3681                c.empty = no_changes && !interrupted;
3682                if interrupted && no_changes {
3683                    c.failed = None;
3684                    c.verified_noop = None;
3685                }
3686                if !c.empty {
3687                    c.failed = None;
3688                    c.verified_noop = None;
3689                }
3690                self.state.event(
3691                    "preserve",
3692                    format!("candidate {label}: {files} files, {commits} commits"),
3693                );
3694                Ok::<_, anyhow::Error>(())
3695            }
3696            .await;
3697            match result {
3698                Ok(()) => {
3699                    self.state.candidate_preservation.remove(&label);
3700                    if !interrupted || self.state.candidates[i].files > 0 {
3701                        self.state.interrupted_implementations.remove(&label);
3702                    }
3703                }
3704                Err(e) => {
3705                    let reason = format!("candidate {label} preservation failed: {e:#}");
3706                    self.state.event("preserve", &reason);
3707                    self.state.candidate_preservation.insert(label, reason);
3708                }
3709            }
3710            if self.state.candidate_preservation.is_empty()
3711                && self.state.status == RunStatus::Blocked
3712                && self.state.candidates.iter().all(|c| c.failed.is_none())
3713            {
3714                // Persist the recovered phase with the cleared pending marker;
3715                // a crash between saves must not turn this into a selected-seat
3716                // failure hold on the next resume.
3717                self.state.status = RunStatus::Implementing;
3718                self.state.event(
3719                    "preserve",
3720                    "candidate persistence recovered; implementation can continue",
3721                );
3722            }
3723            self.state.save()?;
3724        }
3725        if !self.state.candidate_preservation.is_empty() {
3726            self.state.status = RunStatus::Blocked;
3727            self.state.save()?;
3728            bail!(
3729                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3730            );
3731        }
3732        Ok(())
3733    }
3734
3735    /// Ask again, once, for work a CLI did and then failed to hand over.
3736    ///
3737    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3738    /// status with an empty response and a usage report showing output tokens,
3739    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3740    /// seven minutes and 14,267 output tokens that arrived as an empty
3741    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3742    ///
3743    /// Two conditions, and both matter:
3744    ///
3745    /// - **Only when the tree is untouched.** Often the agent has already
3746    ///   written its files and only the closing message was lost; the rescue
3747    ///   commit below picks that up and there is nothing to ask for. Re-asking
3748    ///   then would pay for a second implementation of work already on disk.
3749    /// - **Once.** A CLI that drops one stream can drop the next, and this
3750    ///   node is the most expensive in the graph.
3751    ///
3752    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3753    /// dropped reply still carried its `conversation_id`, so the seat is asked
3754    /// to finish what it was doing rather than sent the whole task again. It
3755    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3756    /// node's - for the same reason a re-ranked judge does: restating finished
3757    /// work is not the work.
3758    ///
3759    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3760    /// same way until it resets, while an abandoned conversation is still
3761    /// there to be picked up.
3762    async fn resume_undelivered(
3763        &mut self,
3764        results: &mut [(usize, SeatState, AgentOutcome)],
3765        sent: &[SeatJob],
3766        prompts: &Prompts,
3767        run_id: &str,
3768    ) {
3769        for (wi, seat, out) in results.iter_mut() {
3770            let Some(dropped) = (match &*out {
3771                AgentOutcome::Dropped(o) => o.dropped.clone(),
3772                _ => None,
3773            }) else {
3774                continue;
3775            };
3776            let Some(job) = sent.get(*wi) else { continue };
3777            // Already on disk? Then only the closing message was lost.
3778            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3779                self.state.event(
3780                    "implement",
3781                    format!(
3782                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3783                         work is in the tree",
3784                        seat.key, dropped.output_tokens, dropped.why
3785                    ),
3786                );
3787                continue;
3788            }
3789            // The re-ask only makes sense as a resume: `resume_after_drop`
3790            // says nothing about the task, trusting the seat to still hold it.
3791            // Without a session to resume — sessions disabled, or this CLI's
3792            // drop shape happened not to carry a session id — that prompt
3793            // would open a brand-new conversation with no context at all,
3794            // which is worse than leaving this as the ordinary failure it
3795            // already is.
3796            if !has_context(&job.spec, seat, job.sessions) {
3797                self.state.event(
3798                    "implement",
3799                    format!(
3800                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3801                         is no session left to resume",
3802                        seat.key, dropped.output_tokens, dropped.why
3803                    ),
3804                );
3805                continue;
3806            }
3807            self.state.event(
3808                "implement",
3809                format!(
3810                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3811                     conversation",
3812                    seat.key, dropped.output_tokens, dropped.why
3813                ),
3814            );
3815            let mut retry = job.clone();
3816            retry.seat = seat.clone();
3817            retry.prompt = prompt::resume_after_drop(&dropped.why);
3818            retry.timeout = retry_budget(job.timeout, true);
3819            retry.stem = format!("{}-resume", job.stem);
3820            let cache = self.state.config.cache_dir();
3821            let ctx = WaveCtx {
3822                carry_seats: false,
3823                pauses: Some((&self.pause, &self.interrupt)),
3824                run: run_id,
3825                node: "implement",
3826                prompts,
3827                cache: cache.as_deref(),
3828                round: None,
3829            };
3830            let (resumed_seat, resumed) =
3831                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3832            *seat = resumed_seat;
3833            *out = resumed;
3834        }
3835    }
3836
3837    /// Fall an implement seat through to the next untried agent in the
3838    /// implementer roster when it lost to quota — or, since the handover was
3839    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3840    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3841    /// quota path itself being unchanged — instead of leaving the
3842    /// seat's loss final the moment one agent's account runs dry.
3843    ///
3844    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3845    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3846    /// truncates to the single slot rotation picked, so a solo task whose one
3847    /// implementer hits quota mid-run used to have nothing else to try. This
3848    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3849    /// unrotated roster — which is the only place the *other* candidates in
3850    /// the machine's roster still exist once `implementers` has been cut down
3851    /// to size.
3852    ///
3853    /// Walks forward from just past the seat's own original position in the
3854    /// roster, never wrapping back to the front: a later candidate slot (say
3855    /// `beta`, the roster's second entry) must fall through to the *next*
3856    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3857    /// almost certainly a different candidate's own agent already — and once
3858    /// the roster's tail is exhausted there is nothing left to fall through
3859    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3860    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3861    /// let this retry that id forever. The loop keeps falling through until
3862    /// an attempt lands something other than `Quota` or the roster's tail
3863    /// runs out of untried ids, at which point the seat is left exactly as
3864    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3865    /// `QuotaLoss` recorded, the candidate failed/empty.
3866    ///
3867    /// `sent` is taken mutably and updated with the fallback agent's spec:
3868    /// `resume_unconfirmed_commands`, which runs after this and also reads
3869    /// `sent`, must see whichever agent actually ended up answering the seat
3870    /// — reading the stale, original spec there would check session
3871    /// eligibility against the wrong CLI and could hand a fallback agent's
3872    /// session id to the agent that just lost the seat to quota.
3873    ///
3874    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3875    /// — `self.seat` only reuses state when the agent id is unchanged, so
3876    /// handing it a different id already gets this for free. Reusing the old
3877    /// seat would resume a different CLI's session as if it were a
3878    /// continuation of this one.
3879    ///
3880    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3881    /// a quota loss cuts an agent off mid-turn, so anything already in the
3882    /// tree is unfinished work, not a completed candidate a re-ask would pay
3883    /// for twice. A dirty tree is rescued into a commit first (the same
3884    /// neutral-identity rescue `implement`'s own outcome loop gives every
3885    /// candidate) so the next agent starts clean.
3886    ///
3887    /// The new agent gets the implementer's full prompt and full
3888    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3889    /// it has no session and no context, and is implementing the task from
3890    /// nothing, unlike a resumed drop which is only restating work already
3891    /// done.
3892    ///
3893    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3894    /// `implement` event, never into `self.state.quota` — that is what
3895    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3896    /// go unspent, and a seat that ultimately recovered on its second or
3897    /// third agent is not the stalled panel that check exists to catch. Only
3898    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3899    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3900    /// outcome loop already has — this helper never pushes to it itself.
3901    async fn resume_seat_handovers(
3902        &mut self,
3903        results: &mut [(usize, SeatState, AgentOutcome)],
3904        sent: &mut [SeatJob],
3905        prompts: &Prompts,
3906        run_id: &str,
3907    ) -> Result<()> {
3908        let instruction = seeded_instruction(&self.state);
3909        let language = self.state.config.graph.language.clone();
3910        let github_language = self.state.config.graph.github_language.clone();
3911        let brief = self
3912            .state
3913            .advice
3914            .as_ref()
3915            .and_then(|a| a.synthesis.as_deref())
3916            .map(str::to_owned);
3917        let attachments = self.state.attachments.clone();
3918        for (wi, seat, out) in results.iter_mut() {
3919            // Who holds the other candidate seats of this wave right now
3920            // (earlier handovers already written back to `sent`).
3921            let others: BTreeSet<String> = sent
3922                .iter()
3923                .enumerate()
3924                .filter(|(j, _)| j != wi)
3925                .map(|(_, j)| j.spec.id.clone())
3926                .collect();
3927            let Some(job) = sent.get_mut(*wi) else {
3928                continue;
3929            };
3930            // Where the seat's own original agent sits in the roster — the
3931            // fallback walk starts just past here, never at the front, so a
3932            // later candidate slot's quota loss does not fall back onto an
3933            // earlier slot's own agent.
3934            let start = self
3935                .roles
3936                .implementer_roster
3937                .iter()
3938                .position(|s| s.id == job.spec.id)
3939                .unwrap_or(0);
3940            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3941            let mut fallback_attempt = 0usize;
3942            let mut prev: Option<FailClass> = None;
3943            while let Some(cur) = FailClass::of(&*out) {
3944                if !should_hand_over(prev.as_ref(), &cur) {
3945                    break;
3946                }
3947                let Some(next) =
3948                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3949                        .cloned()
3950                else {
3951                    break;
3952                };
3953                tried.insert(next.id.clone());
3954                fallback_attempt += 1;
3955
3956                let coordination = self.coordinate(&job.cwd).await?;
3957                if let Ok(r) = git::rescue_commit(
3958                    &job.cwd,
3959                    &format!(
3960                        "magi: candidate {} (uncommitted work before {} fallback)",
3961                        seat.key,
3962                        if cur == FailClass::Quota {
3963                            "quota"
3964                        } else {
3965                            "handover"
3966                        }
3967                    ),
3968                )
3969                .await
3970                {
3971                    self.state.note_withheld("implement", &r.withheld);
3972                }
3973                drop(coordination);
3974
3975                record_handover(
3976                    &mut self.state,
3977                    "implement",
3978                    &seat.key,
3979                    &seat.agent,
3980                    &next.id,
3981                    &cur,
3982                    &fail_reason(&*out),
3983                );
3984                prev = Some(cur.clone());
3985
3986                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3987                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3988                // Kept in sync on `sent` itself, not just the local retry: a
3989                // later helper (`resume_unconfirmed_commands`) reads `sent`
3990                // after this one returns and must see whichever agent is now
3991                // occupying the seat, not the one that just quota'd out —
3992                // otherwise it would judge session/continuation eligibility
3993                // by the wrong CLI and could resend a fallback's session id
3994                // to the agent that lost it the seat in the first place.
3995                job.spec = next.clone();
3996                let mut retry = job.clone();
3997                retry.seat = new_seat;
3998                retry.prompt = prompt::implement_in(
3999                    &instruction,
4000                    &job.cwd.to_string_lossy(),
4001                    &language,
4002                    &github_language,
4003                    brief.as_deref(),
4004                    &attachments,
4005                );
4006                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
4007                let cache = self.state.config.cache_dir();
4008                let ctx = WaveCtx {
4009                    carry_seats: false,
4010                    pauses: Some((&self.pause, &self.interrupt)),
4011                    run: run_id,
4012                    node: "implement",
4013                    prompts,
4014                    cache: cache.as_deref(),
4015                    round: None,
4016                };
4017                let (fallback_seat, fallback_out) = run_one(
4018                    retry,
4019                    Arc::clone(&self.sem),
4020                    &ctx,
4021                    &mut self.state,
4022                    fallback_attempt,
4023                )
4024                .await;
4025                *seat = fallback_seat;
4026                *out = fallback_out;
4027            }
4028        }
4029        Ok(())
4030    }
4031
4032    /// Ask an implement seat's own CLI to confirm what it started, once, when
4033    /// its reply reported a command whose completion status it never
4034    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
4035    /// that does and does not mean.
4036    ///
4037    /// The completion contract this task asks for, extended to `implement`
4038    /// with the same signal `continue_fix_report` reads for the fixer,
4039    /// rather than a keyword search over the reply or a hard requirement on
4040    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
4041    /// a candidate's CLI turn ended cleanly while a test run it had started
4042    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
4043    /// named in it at all is untouched by this: `commands` is empty, so
4044    /// there is nothing to be unconfirmed.
4045    ///
4046    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
4047    /// this is not about recovering edits that might already be on disk, it
4048    /// is about a result the seat itself never vouched for, which resuming
4049    /// asks for regardless of what the tree already holds. Bounded to one
4050    /// attempt for the same reason `resume_undelivered` is — this is the
4051    /// most expensive node in the graph — and a seat that still cannot
4052    /// confirm on that attempt is left as whatever its (possibly still
4053    /// unconfirmed) reply says; this does not invent a new "failed" reason
4054    /// for a candidate that otherwise produced a real, committed change.
4055    async fn resume_unconfirmed_commands(
4056        &mut self,
4057        results: &mut [(usize, SeatState, AgentOutcome)],
4058        sent: &[SeatJob],
4059        prompts: &Prompts,
4060        run_id: &str,
4061    ) {
4062        for (wi, seat, out) in results.iter_mut() {
4063            let AgentOutcome::Ok(o) = &*out else {
4064                continue;
4065            };
4066            if !has_unconfirmed_command(&o.commands) {
4067                continue;
4068            }
4069            let Some(job) = sent.get(*wi) else { continue };
4070            if !has_context(&job.spec, seat, job.sessions) {
4071                self.state.event(
4072                    "implement",
4073                    format!(
4074                        "{}: the reply named a command whose own CLI never confirmed the exit \
4075                         status of, but there is no session left to resume",
4076                        seat.key
4077                    ),
4078                );
4079                continue;
4080            }
4081            self.state.event(
4082                "implement",
4083                format!(
4084                    "{}: the reply named a command whose own CLI never confirmed the exit \
4085                     status of; resuming the conversation",
4086                    seat.key
4087                ),
4088            );
4089            let mut retry = job.clone();
4090            retry.seat = seat.clone();
4091            retry.prompt = prompt::resume_incomplete(
4092                "a command in your last reply had no confirmed exit status",
4093            );
4094            retry.timeout = retry_budget(job.timeout, true);
4095            retry.stem = format!("{}-confirm", job.stem);
4096            let cache = self.state.config.cache_dir();
4097            let ctx = WaveCtx {
4098                carry_seats: false,
4099                pauses: Some((&self.pause, &self.interrupt)),
4100                run: run_id,
4101                node: "implement",
4102                prompts,
4103                cache: cache.as_deref(),
4104                round: None,
4105            };
4106            let (resumed_seat, resumed) =
4107                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4108            *seat = resumed_seat;
4109            *out = resumed;
4110        }
4111    }
4112
4113    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
4114    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
4115    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
4116    /// that motivated this.
4117    ///
4118    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
4119    /// own nudge loop already covers for judge/review/vote seats, and not a
4120    /// dropped stream, which [`Runner::resume_undelivered`] covers for
4121    /// implement seats: here the CLI turn genuinely finished while the node's
4122    /// own work — the fixer's account of what it did — had not. Gated purely
4123    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
4124    /// reply, never on any wording in it, so a fixer whose valid, first-try
4125    /// `FixReport` happens to mention having waited on a background test is
4126    /// never resumed — the `Ok(report)` branch at the call site returns
4127    /// before this is ever invoked.
4128    ///
4129    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4130    /// attempt ([`retry_budget`]), nothing attempted once the session is
4131    /// gone, and a quota hit ends the loop immediately rather than retrying a
4132    /// rate limit that fails the same way again.
4133    async fn continue_fix_report(
4134        &mut self,
4135        mut seat: SeatState,
4136        parse_err: String,
4137        job: &SeatJob,
4138        prompts: &Prompts,
4139        run_id: &str,
4140        round: usize,
4141    ) -> (
4142        SeatState,
4143        Option<FixReport>,
4144        Option<String>,
4145        ContinuationRecord,
4146    ) {
4147        let mut last_err = parse_err;
4148        let mut cumulative_wait_ms = 0u64;
4149        let mut attempts = 0usize;
4150        loop {
4151            if !has_context(&job.spec, &seat, job.sessions) {
4152                self.state.event(
4153                    "fix",
4154                    format!(
4155                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4156                         session left to resume into"
4157                    ),
4158                );
4159                let outcome = if attempts == 0 {
4160                    ContinuationOutcome::NoSession
4161                } else {
4162                    ContinuationOutcome::Exhausted
4163                };
4164                return (
4165                    seat,
4166                    None,
4167                    Some(format!("unparsable fix report: {last_err}")),
4168                    ContinuationRecord {
4169                        attempts,
4170                        cumulative_wait_ms,
4171                        outcome,
4172                    },
4173                );
4174            }
4175            if attempts >= MAX_FIX_CONTINUATIONS {
4176                self.state.event(
4177                    "fix",
4178                    format!(
4179                        "round {round}: fixer's reply still had no adoption report after \
4180                         {attempts} continuation(s) ({last_err}); giving up"
4181                    ),
4182                );
4183                return (
4184                    seat,
4185                    None,
4186                    Some(format!(
4187                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4188                    )),
4189                    ContinuationRecord {
4190                        attempts,
4191                        cumulative_wait_ms,
4192                        outcome: ContinuationOutcome::Exhausted,
4193                    },
4194                );
4195            }
4196            attempts += 1;
4197            self.state.event(
4198                "fix",
4199                format!(
4200                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4201                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4202                ),
4203            );
4204            let mut retry = job.clone();
4205            retry.seat = seat.clone();
4206            retry.prompt = prompt::resume_incomplete(&last_err);
4207            retry.timeout = retry_budget(job.timeout, true);
4208            retry.stem = format!("{}-continue{attempts}", job.stem);
4209            let cache = self.state.config.cache_dir();
4210            let ctx = WaveCtx {
4211                carry_seats: false,
4212                pauses: Some((&self.pause, &self.interrupt)),
4213                run: run_id,
4214                node: "fix",
4215                prompts,
4216                cache: cache.as_deref(),
4217                round: Some(round),
4218            };
4219            let (resumed_seat, resumed_out) = run_one(
4220                retry,
4221                Arc::clone(&self.sem),
4222                &ctx,
4223                &mut self.state,
4224                attempts,
4225            )
4226            .await;
4227            seat = resumed_seat;
4228            match resumed_out {
4229                AgentOutcome::Ok(o) => {
4230                    cumulative_wait_ms += o.duration_ms;
4231                    match verdict::extract_json::<FixReport>(&o.text) {
4232                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4233                            self.state.event(
4234                                "fix",
4235                                format!(
4236                                    "round {round}: fixer's adoption report recovered after \
4237                                     {attempts} continuation(s)"
4238                                ),
4239                            );
4240                            return (
4241                                seat,
4242                                Some(report),
4243                                None,
4244                                ContinuationRecord {
4245                                    attempts,
4246                                    cumulative_wait_ms,
4247                                    outcome: ContinuationOutcome::Resumed,
4248                                },
4249                            );
4250                        }
4251                        // The report parsed, but this same reply's own
4252                        // CommandEvidence — the identical record `state.jobs`
4253                        // renders — names a command whose CLI never
4254                        // confirmed an exit status. Read together, that is
4255                        // not a resolved answer: keep nudging rather than
4256                        // accept a report standing next to a command the
4257                        // seat's own CLI cannot vouch for.
4258                        Ok(_) => {
4259                            last_err = "the reply parsed, but it reported a command whose own CLI \
4260                                 never confirmed an exit status"
4261                                .to_owned();
4262                        }
4263                        Err(e) => last_err = e.to_string(),
4264                    }
4265                }
4266                AgentOutcome::Quota(o) => {
4267                    cumulative_wait_ms += o.duration_ms;
4268                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4269                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4270                    self.state.quota.push(loss);
4271                    self.state.event(
4272                        "fix",
4273                        format!(
4274                            "round {round}: continuation rate limited (quota); not retrying now"
4275                        ),
4276                    );
4277                    return (
4278                        seat,
4279                        None,
4280                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4281                        ContinuationRecord {
4282                            attempts,
4283                            cumulative_wait_ms,
4284                            outcome: ContinuationOutcome::QuotaLost,
4285                        },
4286                    );
4287                }
4288                AgentOutcome::Dropped(o) => {
4289                    cumulative_wait_ms += o.duration_ms;
4290                    let why = o
4291                        .dropped
4292                        .as_ref()
4293                        .map(|d| d.why.as_str())
4294                        .unwrap_or("the CLI ended the stream without delivering its answer");
4295                    last_err = format!("the CLI dropped the stream ({why})");
4296                }
4297                AgentOutcome::Failed(e) => last_err = e,
4298                // The continuation was never started; the report stays lost
4299                // and the caller records that, without any handover.
4300                AgentOutcome::ResourceBlocked(e) => {
4301                    return (
4302                        seat,
4303                        None,
4304                        Some(format!("the continuation was not started: {e}")),
4305                        ContinuationRecord {
4306                            attempts: attempts.saturating_sub(1),
4307                            cumulative_wait_ms,
4308                            outcome: ContinuationOutcome::NoSession,
4309                        },
4310                    );
4311                }
4312            }
4313        }
4314    }
4315
4316    fn after_implement(&mut self) -> Result<()> {
4317        if !self.state.candidate_preservation.is_empty() {
4318            bail!("candidate preservation incomplete; judging is unsafe");
4319        }
4320        // Scan every candidate patch once the set is complete.
4321        if self.state.leaks.is_empty() {
4322            let cfg = self.state.config.blind.clone();
4323            let mut leaks = Vec::new();
4324            for c in &self.state.candidates {
4325                let Some(patch) =
4326                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4327                else {
4328                    continue;
4329                };
4330                leaks.extend(blind::scan(
4331                    &format!("candidate {} patch", c.label),
4332                    &patch,
4333                    &cfg.vendor_tokens,
4334                ));
4335            }
4336            if !leaks.is_empty() {
4337                let summary = leaks
4338                    .iter()
4339                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4340                    .collect::<Vec<_>>()
4341                    .join(", ");
4342                match cfg.on_leak {
4343                    LeakPolicy::Fail => {
4344                        self.state.status = RunStatus::Failed;
4345                        self.state
4346                            .event("blind", format!("vendor text in a patch: {summary}"));
4347                        self.state.leaks = leaks;
4348                        self.state.save()?;
4349                        self.settle_questions();
4350                        bail!(
4351                            "blind.on_leak = \"fail\" and vendor text reached a \
4352                             judged patch: {summary}"
4353                        );
4354                    }
4355                    LeakPolicy::Redact => self.state.event(
4356                        "blind",
4357                        format!("redacting vendor text for judging: {summary}"),
4358                    ),
4359                    LeakPolicy::Warn => self.state.event(
4360                        "blind",
4361                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4362                    ),
4363                }
4364                self.state.leaks = leaks;
4365            }
4366        }
4367
4368        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4369        // incomplete or inconsistent saved state cannot bypass the strict contract.
4370        let mut invalidated = Vec::new();
4371        for c in &mut self.state.candidates {
4372            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4373                c.verified_noop = None;
4374                if c.empty && c.failed.is_none() {
4375                    c.failed = Some(
4376                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4377                            .to_owned(),
4378                    );
4379                }
4380                invalidated.push(c.label);
4381            }
4382        }
4383        for label in invalidated {
4384            self.state.event(
4385                "implement",
4386                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4387            );
4388        }
4389
4390        if self.state.viable().is_empty() {
4391            if self.state.all_candidates_verified_noop() {
4392                // Every candidate agreed, with evidence the adoption guard
4393                // accepted, that nothing belongs in this worktree. That is
4394                // not the same fact as a candidate that simply failed to
4395                // write anything, and settling it as an ordinary `Failed`
4396                // (see `SCHEMA`'s doc for schema 10) is what let two of
4397                // task 391f's attempts burn a retry each re-discovering the
4398                // same already-landed fix. Terminal either way, so `judge`
4399                // must never run over an empty candidate set — unlike the
4400                // `Failed` branch below this returns `Ok`, not an error:
4401                // nothing here failed.
4402                self.state.status = RunStatus::VerifiedNoop;
4403                self.state.save()?;
4404                self.settle_questions();
4405                return Ok(());
4406            }
4407            self.state.status = RunStatus::Failed;
4408            self.state.save()?;
4409            self.settle_questions();
4410            bail!("no candidate produced a change; nothing to judge");
4411        }
4412        self.state.status = RunStatus::Judging;
4413        self.state.save()?;
4414        Ok(())
4415    }
4416
4417    // --------------------------------------------------------------- judge
4418
4419    async fn judge(&mut self) -> Result<()> {
4420        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4421        // agent files with `magi task add` name the run that paid for it. The
4422        // prompt overlay is cloned alongside it because the waves borrow it
4423        // while `self` is mutably borrowed by the node's own bookkeeping.
4424        let run_id = self.state.id.clone();
4425        let prompts = self.state.config.prompts.clone();
4426        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4427            return Ok(());
4428        }
4429        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4430        if viable.len() == 1 {
4431            // Recorded so this is a one-time event: `judgements` stays empty
4432            // either way, which without this flag is indistinguishable from
4433            // "not yet judged" on the next reentry — and status is left
4434            // untouched, so a later node's conclusion (e.g. `Blocked` after
4435            // the review budget ran out) survives a resume instead of being
4436            // clobbered back to `Judging` by this node running again.
4437            self.state.judge_skipped = true;
4438            self.state.event(
4439                "judge",
4440                format!(
4441                    "only candidate {} produced a change; judging skipped",
4442                    viable[0].label
4443                ),
4444            );
4445            self.state.save()?;
4446            return Ok(());
4447        }
4448        self.state.status = RunStatus::Judging;
4449
4450        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4451        let language = self.state.config.graph.language.clone();
4452        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4453        let sessions = self.state.config.graph.sessions;
4454        let artifacts = agent::artifacts_dir(&self.state.dir());
4455        let root = self.state.worktree_root();
4456        let base_short = short(&self.state.base_commit);
4457
4458        let mut jobs = Vec::new();
4459        let mut orders = Vec::new();
4460        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4461            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4462            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4463            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4464            let seat_key = format!("judge-{}", j + 1);
4465            let seat = self.seat(&seat_key, &spec.id);
4466            jobs.push(SeatJob {
4467                prompt: prompt::judge(
4468                    &self.state.instruction,
4469                    &views,
4470                    self.roles.judges.len(),
4471                    &base_short,
4472                    &language,
4473                ),
4474                spec,
4475                seat,
4476                cwd: root.join(format!("judge-{}", j + 1)),
4477                timeout,
4478                allow_write: false,
4479                sessions,
4480                artifacts: artifacts.clone(),
4481                stem: format!("judge-{}", j + 1),
4482                handover: None,
4483            });
4484        }
4485
4486        self.state.event(
4487            "judge",
4488            format!(
4489                "{} judges ranking {} candidates blind",
4490                jobs.len(),
4491                viable.len()
4492            ),
4493        );
4494        let labels_for_check = labels.clone();
4495        let mut quota_losses = Vec::new();
4496        let cache = self.state.config.cache_dir();
4497        let ctx = WaveCtx {
4498            carry_seats: false,
4499            pauses: Some((&self.pause, &self.interrupt)),
4500            run: &run_id,
4501            node: "judge",
4502            prompts: &prompts,
4503            cache: cache.as_deref(),
4504            round: None,
4505        };
4506        let results = ask_json_wave::<Ranking>(
4507            jobs,
4508            Arc::clone(&self.sem),
4509            self.state.config.graph.retries,
4510            &self.roles.judge_roster,
4511            &ctx,
4512            &mut quota_losses,
4513            &mut self.state,
4514            &move |r: &Ranking| r.validate(&labels_for_check),
4515        )
4516        .await;
4517        if self.state.resource_block.is_some() {
4518            return self.stop_for_resource();
4519        }
4520        self.state.quota.extend(quota_losses);
4521
4522        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4523            let agent_id = seat.agent.clone();
4524            self.state.seats.insert(seat.key.clone(), seat);
4525            let mut record = Judgement {
4526                judge: j + 1,
4527                seat: format!("judge-{}", j + 1),
4528                agent: agent_id,
4529                ranking: Vec::new(),
4530                reasons: BTreeMap::new(),
4531                confidence: None,
4532                strengths: BTreeMap::new(),
4533                order: orders[j].clone(),
4534                failed: None,
4535                duration_ms: 0,
4536            };
4537            match res {
4538                Ok((ranking, out)) => {
4539                    record.ranking = ranking.normalized();
4540                    record.reasons = ranking.reasons;
4541                    record.strengths = ranking.strengths;
4542                    record.confidence = ranking.confidence;
4543                    record.duration_ms = out.duration_ms;
4544                    self.state.event(
4545                        "judge",
4546                        format!(
4547                            "judge {} ranked {}",
4548                            j + 1,
4549                            record.ranking.iter().collect::<String>()
4550                        ),
4551                    );
4552                }
4553                Err(e) => {
4554                    record.failed = Some(e.to_string());
4555                    self.state
4556                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4557                }
4558            }
4559            self.state.judgements.push(record);
4560            self.state.save()?;
4561        }
4562        Ok(())
4563    }
4564
4565    // ---------------------------------------------------------- deliberate
4566
4567    async fn deliberate(&mut self) -> Result<()> {
4568        if self.hold_base_sync().await? {
4569            return Ok(());
4570        }
4571        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4572        // agent files with `magi task add` name the run that paid for it. The
4573        // prompt overlay is cloned alongside it because the waves borrow it
4574        // while `self` is mutably borrowed by the node's own bookkeeping.
4575        let run_id = self.state.id.clone();
4576        let prompts = self.state.config.prompts.clone();
4577        let rounds = self.state.config.graph.deliberate_rounds;
4578        // Resume unfinished rounds after an outage, but never reopen a tally.
4579        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4580            return Ok(());
4581        }
4582        let tops: Vec<char> = self
4583            .state
4584            .judgements
4585            .iter()
4586            .filter_map(|j| j.ranking.first().copied())
4587            .collect();
4588        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4589            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4590                self.state.event(
4591                    "deliberate",
4592                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4593                );
4594            }
4595            self.state.status = RunStatus::Voting;
4596            self.state.save()?;
4597            return Ok(());
4598        }
4599
4600        self.state.status = RunStatus::Deliberating;
4601        self.state.event(
4602            "deliberate",
4603            format!(
4604                "split: first choices were {} — opening {rounds} round(s)",
4605                tops.iter().collect::<String>()
4606            ),
4607        );
4608
4609        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4610        let language = self.state.config.graph.language.clone();
4611        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4612        let sessions = self.state.config.graph.sessions;
4613        let artifacts = agent::artifacts_dir(&self.state.dir());
4614        let root = self.state.worktree_root();
4615        let base_short = short(&self.state.base_commit);
4616
4617        // Judges argue in sequence so that a turn can answer the one before it;
4618        // that is the difference between deliberation and three parallel
4619        // monologues.
4620        for round in self.state.deliberation.len() + 1..=rounds {
4621            let mut turns: Vec<DeliberationTurn> = Vec::new();
4622            let mut round_losses = Vec::new();
4623            let mut asked = 0;
4624            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4625                if self.state.judgements[j].failed.is_some() {
4626                    continue;
4627                }
4628                let seat_key = format!("judge-{}", j + 1);
4629                let spec = self.occupant(&seat_key, spec);
4630                let mut seat = self.seat(&seat_key, &spec.id);
4631                let transcript = self.transcript(&turns, j);
4632                let build = |context: Option<&str>| {
4633                    prompt::deliberate(
4634                        &self.state.instruction,
4635                        context,
4636                        &transcript,
4637                        round,
4638                        rounds,
4639                        &language,
4640                    )
4641                };
4642                let block = self.candidate_block(&viable, &base_short);
4643                let full = build(Some(&block));
4644                let text = if has_context(&spec, &seat, sessions) {
4645                    build(None)
4646                } else {
4647                    full.clone()
4648                };
4649                let job = SeatJob {
4650                    spec,
4651                    seat: seat.clone(),
4652                    prompt: text,
4653                    cwd: root.join(format!("judge-{}", j + 1)),
4654                    timeout,
4655                    allow_write: false,
4656                    sessions,
4657                    artifacts: artifacts.clone(),
4658                    stem: format!("delib-{round}-judge-{}", j + 1),
4659                    handover: Some(full),
4660                };
4661                let cache = self.state.config.cache_dir();
4662                let ctx = WaveCtx {
4663                    carry_seats: false,
4664                    pauses: Some((&self.pause, &self.interrupt)),
4665                    run: &run_id,
4666                    node: "deliberate",
4667                    prompts: &prompts,
4668                    cache: cache.as_deref(),
4669                    round: None,
4670                };
4671                // A turn is never nudged (`retries` 0): a failed seat is
4672                // handed to the next roster agent, which gets the full
4673                // context. An empty answer is a turn, not a failure.
4674                let mut losses = Vec::new();
4675                asked += 1;
4676                let mut results = ask_wave_with::<String>(
4677                    vec![job],
4678                    Arc::clone(&self.sem),
4679                    0,
4680                    &self.roles.judge_roster,
4681                    &ctx,
4682                    &mut losses,
4683                    &mut self.state,
4684                    &|text: &str| {
4685                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4686                    },
4687                )
4688                .await;
4689                if self.state.resource_block.is_some() {
4690                    return self.stop_for_resource();
4691                }
4692                round_losses.extend(losses.iter().cloned());
4693                self.state.quota.extend(losses);
4694                let (updated, res, _) = results.pop().expect("one job in, one result out");
4695                seat = updated;
4696                let agent_id = seat.agent.clone();
4697                self.state.seats.insert(seat.key.clone(), seat);
4698                let body = match res {
4699                    Ok((body, _)) => body,
4700                    // Skip the seat; a CLI's raw error JSON is never read as
4701                    // this judge's position.
4702                    Err(e) => {
4703                        self.state
4704                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4705                        continue;
4706                    }
4707                };
4708                let tentative = verdict::extract_json::<Position>(&body)
4709                    .ok()
4710                    .and_then(|p| p.tentative)
4711                    .and_then(|s| s.trim().chars().next())
4712                    .map(|c| c.to_ascii_uppercase());
4713                self.state.event(
4714                    "deliberate",
4715                    format!(
4716                        "round {round}: judge {} now favours {}",
4717                        j + 1,
4718                        tentative.map_or("—".to_owned(), |c| c.to_string())
4719                    ),
4720                );
4721                turns.push(DeliberationTurn {
4722                    judge: j + 1,
4723                    agent: agent_id,
4724                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4725                    tentative,
4726                });
4727            }
4728            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4729                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4730                return self.stop_for_resource();
4731            }
4732            self.state
4733                .deliberation
4734                .push(DeliberationRound { round, turns });
4735            self.state.save()?;
4736        }
4737
4738        self.state.status = RunStatus::Voting;
4739        self.state.save()?;
4740        Ok(())
4741    }
4742
4743    // ---------------------------------------------------------------- vote
4744
4745    async fn vote(&mut self) -> Result<()> {
4746        if self.hold_base_sync().await? {
4747            return Ok(());
4748        }
4749        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4750        // agent files with `magi task add` name the run that paid for it. The
4751        // prompt overlay is cloned alongside it because the waves borrow it
4752        // while `self` is mutably borrowed by the node's own bookkeeping.
4753        let run_id = self.state.id.clone();
4754        let prompts = self.state.config.prompts.clone();
4755        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4756            return Ok(());
4757        }
4758        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4759        if viable.len() == 1 {
4760            return Ok(());
4761        }
4762        self.state.status = RunStatus::Voting;
4763
4764        let language = self.state.config.graph.language.clone();
4765        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4766        let sessions = self.state.config.graph.sessions;
4767        let artifacts = agent::artifacts_dir(&self.state.dir());
4768        let root = self.state.worktree_root();
4769        let base_short = short(&self.state.base_commit);
4770        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4771
4772        let mut jobs = Vec::new();
4773        let mut seats_at = Vec::new();
4774        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4775            if self
4776                .state
4777                .judgements
4778                .get(j)
4779                .is_some_and(|r| r.failed.is_some())
4780            {
4781                continue;
4782            }
4783            let seat_key = format!("judge-{}", j + 1);
4784            let spec = self.occupant(&seat_key, spec);
4785            let seat = self.seat(&seat_key, &spec.id);
4786            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4787            let text = if has_context(&spec, &seat, sessions) {
4788                prompt::final_vote(&viable, &language)
4789            } else {
4790                full.clone()
4791            };
4792            jobs.push(SeatJob {
4793                spec,
4794                seat,
4795                prompt: text,
4796                cwd: root.join(format!("judge-{}", j + 1)),
4797                timeout,
4798                allow_write: false,
4799                sessions,
4800                artifacts: artifacts.clone(),
4801                stem: format!("vote-judge-{}", j + 1),
4802                handover: Some(full),
4803            });
4804            seats_at.push(j);
4805        }
4806
4807        self.state.event(
4808            "vote",
4809            format!(
4810                "collecting {} final votes one by one, privately",
4811                jobs.len()
4812            ),
4813        );
4814        let allowed = viable.clone();
4815        let mut quota_losses = Vec::new();
4816        let cache = self.state.config.cache_dir();
4817        let ctx = WaveCtx {
4818            carry_seats: false,
4819            pauses: Some((&self.pause, &self.interrupt)),
4820            run: &run_id,
4821            node: "vote",
4822            prompts: &prompts,
4823            cache: cache.as_deref(),
4824            round: None,
4825        };
4826        let results = ask_json_wave::<FinalVote>(
4827            jobs,
4828            Arc::clone(&self.sem),
4829            self.state.config.graph.retries,
4830            &self.roles.judge_roster,
4831            &ctx,
4832            &mut quota_losses,
4833            &mut self.state,
4834            &move |v: &FinalVote| match v.label() {
4835                Some(c) if allowed.contains(&c) => Ok(()),
4836                other => bail!("vote {other:?} is not one of {allowed:?}"),
4837            },
4838        )
4839        .await;
4840        if self.state.resource_block.is_some() {
4841            return self.stop_for_resource();
4842        }
4843        self.state.quota.extend(quota_losses);
4844
4845        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4846            let agent_id = seat.agent.clone();
4847            self.state.seats.insert(seat.key.clone(), seat);
4848            let initial = self
4849                .state
4850                .judgements
4851                .get(j)
4852                .and_then(|r| r.ranking.first().copied());
4853            let mut record = VoteRecord {
4854                judge: j + 1,
4855                agent: agent_id,
4856                vote: None,
4857                reason: String::new(),
4858                changed: false,
4859            };
4860            match res {
4861                Ok((v, _)) => {
4862                    record.vote = v.label();
4863                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4864                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4865                    self.state.event(
4866                        "vote",
4867                        format!(
4868                            "judge {} voted {}{}",
4869                            j + 1,
4870                            record.vote.unwrap_or('?'),
4871                            if record.changed { " (changed)" } else { "" }
4872                        ),
4873                    );
4874                }
4875                Err(e) => {
4876                    self.state
4877                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4878                }
4879            }
4880            self.state.votes.push(record);
4881            self.state.save()?;
4882        }
4883        Ok(())
4884    }
4885
4886    // --------------------------------------------------------------- tally
4887
4888    fn tally(&mut self) -> Result<()> {
4889        if self.state.tally.is_some() {
4890            return Ok(());
4891        }
4892        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4893        let tops: Vec<char> = self
4894            .state
4895            .judgements
4896            .iter()
4897            .filter_map(|j| j.ranking.first().copied())
4898            .collect();
4899        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4900
4901        // A judge whose private vote failed still counted once, in the initial
4902        // ranking; using it beats discarding a whole seat.
4903        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4904        let mut cast: Vec<char> = Vec::new();
4905        for (i, j) in self.state.judgements.iter().enumerate() {
4906            let vote = self
4907                .state
4908                .votes
4909                .iter()
4910                .find(|v| v.judge == i + 1)
4911                .and_then(|v| v.vote)
4912                .or_else(|| j.ranking.first().copied());
4913            if let Some(v) = vote {
4914                *first_choice.entry(v).or_insert(0) += 1;
4915                cast.push(v);
4916            }
4917        }
4918
4919        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4920        for j in &self.state.judgements {
4921            let n = j.ranking.len();
4922            for (pos, label) in j.ranking.iter().enumerate() {
4923                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4924            }
4925        }
4926
4927        let best = first_choice.values().copied().max().unwrap_or(0);
4928        let mut leaders: Vec<char> = first_choice
4929            .iter()
4930            .filter(|(_, v)| **v == best)
4931            .map(|(k, _)| *k)
4932            .collect();
4933        let mut tie_break = None;
4934        if leaders.len() > 1 {
4935            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4936            let borda_leaders: Vec<char> = leaders
4937                .iter()
4938                .copied()
4939                .filter(|l| borda[l] == top_borda)
4940                .collect();
4941            tie_break = Some(if borda_leaders.len() == 1 {
4942                format!(
4943                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4944                    leaders.len()
4945                )
4946            } else {
4947                format!(
4948                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4949                    leaders.len()
4950                )
4951            });
4952            leaders = borda_leaders;
4953            leaders.sort_unstable();
4954        }
4955        let winner = *leaders
4956            .first()
4957            .or(viable.first())
4958            .context("no candidate to declare a winner from")?;
4959
4960        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4961        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4962        let deliberated = !self.state.deliberation.is_empty();
4963
4964        // Whose verdict is this? A rate-limited seat is absent even if it
4965        // ranked before the limit hit, so presence is measured against the
4966        // recorded losses, not just "did a ranking ever appear".
4967        let quota_seats: std::collections::BTreeSet<&str> =
4968            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4969        let mut present = 0usize;
4970        for (i, j) in self.state.judgements.iter().enumerate() {
4971            if quota_seats.contains(j.seat.as_str()) {
4972                continue;
4973            }
4974            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4975            let voted = self
4976                .state
4977                .votes
4978                .iter()
4979                .any(|v| v.judge == i + 1 && v.vote.is_some());
4980            if ranked || voted {
4981                present += 1;
4982            }
4983        }
4984        // Strict majority of the configured panel. A bare majority is real
4985        // signal we can act on, while a minority verdict must never stand in
4986        // for a healthy one. A one-candidate run needs no panel at all, and
4987        // `judges` stays `0` rather than the roster size a panel that never
4988        // sat would otherwise be credited with.
4989        let needs_quorum = viable.len() > 1;
4990        let judges_total = if needs_quorum {
4991            self.roles.judges.len()
4992        } else {
4993            0
4994        };
4995        let quorum = if needs_quorum {
4996            judges_total / 2 + 1
4997        } else {
4998            0
4999        };
5000        let met_quorum = !needs_quorum || present >= quorum;
5001        let uncontested = (!needs_quorum).then(|| {
5002            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
5003        });
5004
5005        self.state.event(
5006            "tally",
5007            match &uncontested {
5008                Some(reason) => format!("winner {winner} — {reason}"),
5009                None => format!(
5010                    "winner {winner} — votes {} | initial {} | {} changed | \
5011                     {present}/{judges_total} judges{}",
5012                    first_choice
5013                        .iter()
5014                        .map(|(k, v)| format!("{k}:{v}"))
5015                        .collect::<Vec<_>>()
5016                        .join(" "),
5017                    if unanimous_initial {
5018                        "unanimous"
5019                    } else {
5020                        "split"
5021                    },
5022                    changed_votes,
5023                    if met_quorum {
5024                        String::new()
5025                    } else {
5026                        format!(" — below quorum ({quorum} required)")
5027                    },
5028                ),
5029            },
5030        );
5031        if !met_quorum {
5032            self.state.event(
5033                "stall",
5034                format!(
5035                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
5036                     the run stops here, resumable"
5037                ),
5038            );
5039        }
5040        self.state.tally = Some(Tally {
5041            first_choice,
5042            borda,
5043            winner,
5044            rankings: tops.len(),
5045            unanimous_initial,
5046            deliberated,
5047            changed_votes,
5048            unanimous_final,
5049            tie_break,
5050            judges: judges_total,
5051            present,
5052            quorum,
5053            met_quorum,
5054            uncontested,
5055        });
5056        self.state.status = if met_quorum {
5057            RunStatus::Reviewing
5058        } else {
5059            RunStatus::Stalled
5060        };
5061        self.state.save()?;
5062        Ok(())
5063    }
5064
5065    // ------------------------------------------------------------- recover
5066
5067    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
5068    /// resumed toward completion once the transient cause clears.
5069    ///
5070    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
5071    /// it toward the quorum, which is exactly the set of seats whose absence
5072    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
5073    /// not depend on which node happened to hit the limit), or an ordinary
5074    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
5075    /// seat is never disturbed.
5076    ///
5077    /// A seat that now answers with a usable ranking is "recovered": its
5078    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
5079    /// `tally` counts it present again), and its vote re-collected. A seat that
5080    /// still fails keeps its loss and stays absent.
5081    ///
5082    /// Returns `true` when the re-tally restores the quorum (the run may proceed
5083    /// to review/gate/merge), `false` when it is still below quorum (the run
5084    /// stays `Stalled`, still resumable for a later retry).
5085    #[allow(clippy::too_many_lines)]
5086    async fn recover_stall(&mut self) -> Result<bool> {
5087        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
5088        // agent files with `magi task add` name the run that paid for it. The
5089        // prompt overlay is cloned alongside it because the waves borrow it
5090        // while `self` is mutably borrowed by the node's own bookkeeping.
5091        let run_id = self.state.id.clone();
5092        let prompts = self.state.config.prompts.clone();
5093        // Absent seats = quota-lost at any node, or failed outright. Mirroring
5094        // `tally`'s presence test (rather than the old quota-judge/vote filter)
5095        // is what keeps a non-quota collapse — or a quota loss recorded at the
5096        // deliberate node — from being a permanent dead-end on `--resume`.
5097        let quota_seats: BTreeSet<&str> =
5098            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5099        let absent: Vec<String> = self
5100            .state
5101            .judgements
5102            .iter()
5103            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
5104            .map(|j| j.seat.clone())
5105            .collect();
5106        if absent.is_empty() {
5107            return Ok(false);
5108        }
5109        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
5110        if viable.len() <= 1 {
5111            return Ok(false);
5112        }
5113        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
5114        let language = self.state.config.graph.language.clone();
5115        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
5116        let sessions = self.state.config.graph.sessions;
5117        let artifacts = agent::artifacts_dir(&self.state.dir());
5118        let root = self.state.worktree_root();
5119        let base_short = short(&self.state.base_commit);
5120        let candidates: Vec<Candidate> = viable.clone();
5121
5122        // Map each absent seat key to its 0-based position in `roles.judges`.
5123        let mut positions: Vec<usize> = absent
5124            .iter()
5125            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5126            .collect();
5127        if positions.is_empty() {
5128            return Ok(false);
5129        }
5130        positions.sort_unstable();
5131        positions.dedup();
5132
5133        // Re-rank the lost seats, one blind prompt each.
5134        let mut judge_jobs = Vec::new();
5135        for &j in &positions {
5136            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5137            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5138            let seat_key = format!("judge-{}", j + 1);
5139            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5140            let seat = self.seat(&seat_key, &spec.id);
5141            judge_jobs.push(SeatJob {
5142                spec,
5143                seat,
5144                prompt: prompt::judge(
5145                    &self.state.instruction,
5146                    &views,
5147                    self.roles.judges.len(),
5148                    &base_short,
5149                    &language,
5150                ),
5151                cwd: root.join(seat_key),
5152                timeout,
5153                allow_write: false,
5154                sessions,
5155                artifacts: artifacts.clone(),
5156                stem: format!("judge-{}-recover", j + 1),
5157                handover: None,
5158            });
5159        }
5160
5161        let labels_for_check = labels.clone();
5162        let mut judge_losses = Vec::new();
5163        let retries = self.state.config.graph.retries;
5164        let cache = self.state.config.cache_dir();
5165        let ctx = WaveCtx {
5166            carry_seats: false,
5167            pauses: Some((&self.pause, &self.interrupt)),
5168            run: &run_id,
5169            node: "judge",
5170            prompts: &prompts,
5171            cache: cache.as_deref(),
5172            round: None,
5173        };
5174        let results = ask_json_wave::<Ranking>(
5175            judge_jobs,
5176            Arc::clone(&self.sem),
5177            retries,
5178            &self.roles.judge_roster,
5179            &ctx,
5180            &mut judge_losses,
5181            &mut self.state,
5182            &move |r: &Ranking| r.validate(&labels_for_check),
5183        )
5184        .await;
5185        if self.state.resource_block.is_some() {
5186            self.stop_for_resource()?;
5187            return Ok(false);
5188        }
5189
5190        // Refresh the judgement of every seat that ranked again.
5191        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5192        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5193            let agent_id = seat.agent.clone();
5194            self.state.seats.insert(seat.key.clone(), seat);
5195            let record = &mut self.state.judgements[j];
5196            match res {
5197                Ok((ranking, out)) => {
5198                    record.agent = agent_id;
5199                    record.ranking = ranking.normalized();
5200                    record.reasons = ranking.reasons;
5201                    record.strengths = ranking.strengths;
5202                    record.confidence = ranking.confidence;
5203                    record.failed = None;
5204                    record.duration_ms = out.duration_ms;
5205                    recovered.insert(j);
5206                    self.state.event(
5207                        "recover",
5208                        format!("judge {} ranked again after the limit", j + 1),
5209                    );
5210                }
5211                Err(e) => {
5212                    self.state
5213                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5214                }
5215            }
5216        }
5217
5218        // Re-ask the votes of the seats that recovered a ranking.
5219        let mut vote_jobs = Vec::new();
5220        let mut vote_pos: Vec<usize> = Vec::new();
5221        for &j in &recovered {
5222            let seat_key = format!("judge-{}", j + 1);
5223            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5224            let seat = self.seat(&seat_key, &spec.id);
5225            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5226            let text = if has_context(&spec, &seat, sessions) {
5227                prompt::final_vote(&labels, &language)
5228            } else {
5229                full.clone()
5230            };
5231            vote_jobs.push(SeatJob {
5232                spec,
5233                seat,
5234                prompt: text,
5235                cwd: root.join(seat_key),
5236                timeout,
5237                allow_write: false,
5238                sessions,
5239                artifacts: artifacts.clone(),
5240                stem: format!("vote-judge-{}-recover", j + 1),
5241                handover: Some(full),
5242            });
5243            vote_pos.push(j);
5244        }
5245        let allowed = labels.clone();
5246        let mut vote_losses = Vec::new();
5247        let vote_retries = self.state.config.graph.retries;
5248        let vote_cache = self.state.config.cache_dir();
5249        let ctx = WaveCtx {
5250            carry_seats: false,
5251            pauses: Some((&self.pause, &self.interrupt)),
5252            run: &run_id,
5253            node: "vote",
5254            prompts: &prompts,
5255            cache: vote_cache.as_deref(),
5256            round: None,
5257        };
5258        let votes = ask_json_wave::<FinalVote>(
5259            vote_jobs,
5260            Arc::clone(&self.sem),
5261            vote_retries,
5262            &self.roles.judge_roster,
5263            &ctx,
5264            &mut vote_losses,
5265            &mut self.state,
5266            &move |v: &FinalVote| match v.label() {
5267                Some(c) if allowed.contains(&c) => Ok(()),
5268                other => bail!("vote {other:?} is not one of {allowed:?}"),
5269            },
5270        )
5271        .await;
5272        if self.state.resource_block.is_some() {
5273            self.stop_for_resource()?;
5274            return Ok(false);
5275        }
5276        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5277            let agent_id = seat.agent.clone();
5278            self.state.seats.insert(seat.key.clone(), seat);
5279            match res {
5280                Ok((v, _)) => {
5281                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5282                        rec.vote = v.label();
5283                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5284                    } else {
5285                        self.state.votes.push(VoteRecord {
5286                            judge: j + 1,
5287                            agent: agent_id,
5288                            vote: v.label(),
5289                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5290                            changed: false,
5291                        });
5292                    }
5293                    self.state.event(
5294                        "recover",
5295                        format!("judge {} voted again after the limit", j + 1),
5296                    );
5297                }
5298                Err(e) => {
5299                    self.state
5300                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5301                }
5302            }
5303        }
5304
5305        // A seat that ranked again is present even if its re-vote failed —
5306        // `tally` falls back to the initial ranking's first choice — so clear
5307        // its quota loss. Seats that still fail keep theirs and stay absent.
5308        let recovered_keys: BTreeSet<String> = recovered
5309            .iter()
5310            .map(|&j| format!("judge-{}", j + 1))
5311            .collect();
5312        self.state
5313            .quota
5314            .retain(|q| !recovered_keys.contains(&q.seat));
5315        // A seat that hit the limit again is a fresh loss, not the old one:
5316        // replace the stale entry so the history stays one-per-seat and the
5317        // daemon can tell this attempt's loss from a previous session's.
5318        for loss in judge_losses.into_iter().chain(vote_losses) {
5319            if recovered_keys.contains(&loss.seat) {
5320                continue;
5321            }
5322            self.state.quota.retain(|q| q.seat != loss.seat);
5323            self.state.quota.push(loss);
5324        }
5325
5326        // Recompute the verdict from the refreshed panel.
5327        self.state.tally = None;
5328        self.tally()?;
5329        Ok(self
5330            .state
5331            .tally
5332            .as_ref()
5333            .map(|t| t.met_quorum)
5334            .unwrap_or(false))
5335    }
5336
5337    // ---------------------------------------------------------------- graft
5338
5339    /// Port the strengths the judges attributed to the losing candidates onto
5340    /// the winner, once, between the tally and the review loop.
5341    ///
5342    /// Best-effort by construction: it returns nothing and fails nothing. A
5343    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5344    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5345    /// the run carries on as if the phase were off. See [`graft`] for the
5346    /// decisions and `AGENTS.md` for the invariants.
5347    ///
5348    /// The one exception is a rollback that could not be confirmed: the
5349    /// rejected commit may still be the winner's tip, so the run is blocked
5350    /// (resumable; the record stays `Running`, which makes a resume retry the
5351    /// restore) instead of reviewing, gating and merging it.
5352    async fn graft(&mut self) -> Result<()> {
5353        let Err(e) = self.graft_inner().await else {
5354            return Ok(());
5355        };
5356        if e.is::<crate::repo_lock::ResourceBlocked>() {
5357            return Err(e);
5358        }
5359        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5360            self.state.status = RunStatus::Blocked;
5361            self.state.event("graft", format!("blocked: {e:#}"));
5362            self.state.save()?;
5363            return Err(e);
5364        }
5365        // An error after the `Running` record was saved may have left the
5366        // fixer's work in the tree: the record must not stay unsettled
5367        // (a later resume would reset past the review fixes), so confirm the
5368        // restore now, or block.
5369        if let Some(rec) = self.state.graft.clone()
5370            && !rec.outcome.settled()
5371        {
5372            if let Some(winner) = self.state.winner().cloned() {
5373                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5374                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5375                        return Err(re);
5376                    }
5377                    self.state.status = RunStatus::Blocked;
5378                    self.state.event("graft", format!("blocked: {re:#}"));
5379                    self.state.save()?;
5380                    return Err(re);
5381                }
5382            }
5383            if let Some(g) = self.state.graft.as_mut() {
5384                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5385            }
5386        }
5387        self.state.event("graft", format!("skipped: {e:#}"));
5388        if let Err(e) = self.state.save() {
5389            tracing::warn!("save after graft: {e:#}");
5390        }
5391        Ok(())
5392    }
5393
5394    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5395    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5396    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5397        let _coordination = self.coordinate(wt).await?;
5398        crate::recovery::restore_repair(wt, pre)
5399            .await
5400            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5401    }
5402
5403    /// A skip is a run event, recorded once however often the node is re-entered.
5404    fn graft_skipped(&mut self, why: &str) {
5405        let message = format!("skipped: {why}");
5406        if !self
5407            .state
5408            .events
5409            .iter()
5410            .any(|e| e.node == "graft" && e.message == message)
5411        {
5412            self.state.event("graft", message);
5413        }
5414    }
5415
5416    async fn graft_inner(&mut self) -> Result<()> {
5417        // A round that was started and never finished (crash, kill): the
5418        // fixer may have left anything in the tree, so put the winner back.
5419        if let Some(rec) = self.state.graft.clone()
5420            && !rec.outcome.settled()
5421        {
5422            // Reviews exist only if the graft ended without its record being
5423            // settled (a swallowed error): the tree has moved on since, and
5424            // a reset to `pre` would discard the review fixes.
5425            if self.state.reviews.is_empty()
5426                && let Some(winner) = self.state.winner().cloned()
5427            {
5428                self.graft_restore(&winner.worktree, &rec.pre).await?;
5429            }
5430            if rec.outcome == GraftOutcome::WaitingForRestore {
5431                self.state.graft = None;
5432                self.state.save()?;
5433            } else {
5434                if let Some(g) = self.state.graft.as_mut() {
5435                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5436                }
5437                self.state.event(
5438                    "graft",
5439                    "rolled back: the previous round was interrupted; the winner is untouched",
5440                );
5441                self.state.save()?;
5442                return Ok(());
5443            }
5444        }
5445        let plan = match graft::plan(&self.state) {
5446            Ok(plan) => plan,
5447            Err(skip) => {
5448                if skip != graft::Skip::AlreadyDone {
5449                    self.graft_skipped(skip.reason());
5450                    self.state.save()?;
5451                }
5452                return Ok(());
5453            }
5454        };
5455        let Some(winner) = self.state.winner().cloned() else {
5456            return Ok(());
5457        };
5458        let wt = winner.worktree.clone();
5459        if !git::is_clean(&wt).await? {
5460            self.graft_skipped("the winner's worktree has uncommitted changes");
5461            self.state.save()?;
5462            return Ok(());
5463        }
5464        let pre = git::rev_parse(&wt, "HEAD").await?;
5465        // Saved before the fixer is called: a stop from here on is repaired
5466        // by the branch above on the next entry.
5467        self.state.graft = Some(GraftRecord {
5468            pre: pre.clone(),
5469            post: None,
5470            lines: None,
5471            limit: None,
5472            agent: None,
5473            outcome: GraftOutcome::Running,
5474            requested: graft::requested(&plan),
5475            adoption: None,
5476            adoption_error: None,
5477        });
5478        self.state.event(
5479            "graft",
5480            format!(
5481                "porting strengths of candidate(s) {} onto {}",
5482                plan.strengths
5483                    .iter()
5484                    .map(|(l, _, _)| l.to_string())
5485                    .collect::<Vec<_>>()
5486                    .join(", "),
5487                plan.winner
5488            ),
5489        );
5490        self.state.save()?;
5491
5492        let fix_prompt = prompt::graft(
5493            &self.state.instruction,
5494            plan.winner,
5495            &plan.strengths,
5496            &self.state.config.graph.language,
5497        );
5498        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5499        let sessions = self.state.config.graph.sessions;
5500        let artifacts = agent::artifacts_dir(&self.state.dir());
5501        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5502        let (_, seat, out) = self
5503            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5504                SeatJob {
5505                    prompt: fix_prompt.clone(),
5506                    spec,
5507                    seat,
5508                    cwd: wt.clone(),
5509                    timeout,
5510                    allow_write: true,
5511                    sessions,
5512                    artifacts: artifacts.clone(),
5513                    stem: "graft".to_owned(),
5514                    handover: None,
5515                }
5516            })
5517            .await;
5518        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5519            // Preserve the need to restore earlier fallback edits without
5520            // confusing an unstarted seat with an interrupted invocation.
5521            self.state.graft.as_mut().expect("graft record").outcome =
5522                GraftOutcome::WaitingForRestore;
5523            return self.stop_for_resource();
5524        }
5525        let mut why: Option<String> = None;
5526        match &out {
5527            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5528                why = Some("the fixer produced nothing usable".to_owned());
5529            }
5530            AgentOutcome::Ok(_) => {}
5531            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5532            AgentOutcome::Quota(o) => {
5533                self.state.quota.push(QuotaLoss::from_report(
5534                    seat.key.clone(),
5535                    "graft",
5536                    o.quota.as_ref(),
5537                ));
5538                why = Some("rate limited (quota)".to_owned());
5539            }
5540            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5541                why = Some(format!(
5542                    "the fixer failed: {}",
5543                    e.lines()
5544                        .next()
5545                        .unwrap_or("")
5546                        .chars()
5547                        .take(160)
5548                        .collect::<String>()
5549                ));
5550            }
5551        }
5552        let agent_id = seat.agent.clone();
5553        self.state.seats.insert(seat.key.clone(), seat);
5554
5555        let mut post = None;
5556        let mut lines = None;
5557        let _coordination = self.coordinate(&wt).await?;
5558        if why.is_none() {
5559            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5560            if let Ok(r) = &rescued {
5561                self.state.note_withheld("graft", &r.withheld);
5562            }
5563            let head = git::rev_parse(&wt, "HEAD").await?;
5564            // What is measured must be what gets reviewed and gated: a failed
5565            // rescue, or anything still uncommitted (withheld lockfiles
5566            // aside, which are never part of the tree), rejects the graft.
5567            let dirty = match &rescued {
5568                Ok(r) => git::status_porcelain(&wt)
5569                    .await
5570                    .map(|st| {
5571                        st.lines().any(|l| {
5572                            !r.withheld
5573                                .iter()
5574                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5575                        })
5576                    })
5577                    .unwrap_or(true),
5578                Err(_) => true,
5579            };
5580            if dirty {
5581                why = Some("the fixer left changes that could not be committed".to_owned());
5582            } else if head == pre {
5583                why = Some("the fixer changed nothing".to_owned());
5584            } else {
5585                lines = git::changed_lines(&wt, &pre, &head).await;
5586                post = Some(head);
5587            }
5588        }
5589        let (adoption, adoption_error) = match &out {
5590            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5591            _ => (None, None),
5592        };
5593        let requested = graft::requested(&plan);
5594        let outcome = match why {
5595            None => {
5596                self.state.event(
5597                    "graft",
5598                    format!(
5599                        "applied: {}",
5600                        lines.map_or_else(
5601                            || "changed lines unavailable".to_owned(),
5602                            |n| format!("{n} changed lines")
5603                        )
5604                    ),
5605                );
5606                GraftOutcome::Applied
5607            }
5608            Some(why) => {
5609                // Not settled until the restore is confirmed: the record
5610                // stays `Running`, so a resume retries it.
5611                crate::recovery::restore_repair(&wt, &pre)
5612                    .await
5613                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5614                self.state.event(
5615                    "graft",
5616                    format!("rolled back: {why}; the winner is untouched"),
5617                );
5618                GraftOutcome::RolledBack(why)
5619            }
5620        };
5621        self.state.graft = Some(GraftRecord {
5622            pre,
5623            post,
5624            lines,
5625            limit: None,
5626            agent: Some(agent_id),
5627            outcome,
5628            requested,
5629            adoption,
5630            adoption_error,
5631        });
5632        self.state.save()?;
5633        Ok(())
5634    }
5635
5636    // ----------------------------------------------------------------- fold
5637
5638    async fn fold_losers(&mut self) -> Result<()> {
5639        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5640            return Ok(());
5641        };
5642        if !self.state.candidate_preservation.is_empty() {
5643            bail!("candidate preservation incomplete; refusing cleanup");
5644        }
5645        let repo = self.state.repo.clone();
5646        let _coordination = self.coordinate(&repo).await?;
5647        let home = crate::run::home();
5648        let root = self.state.worktree_root();
5649        let isolated = crate::build_target::isolated(&self.state.config);
5650        let mut folded = Vec::new();
5651        for i in 0..self.state.candidates.len() {
5652            let c = &self.state.candidates[i];
5653            if c.label == winner || c.folded {
5654                continue;
5655            }
5656            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5657            let target = fold_target(&home, &root, &wt, isolated);
5658            remove_preserved_worktree(&repo, &wt).await?;
5659            reclaim_fold_target(&home, target);
5660            if git::branch_exists(&repo, &branch).await?
5661                && !git::branch_delete(&repo, &branch).await?
5662            {
5663                bail!("candidate branch removal refused");
5664            }
5665            self.state.candidates[i].folded = true;
5666            self.state.save()?;
5667            folded.push(label.to_string());
5668        }
5669        // The judges are finished; their checkouts are pure cost from here.
5670        for j in 1..=self.roles.judges.len() {
5671            let wt = root.join(format!("judge-{j}"));
5672            if wt.exists() {
5673                let target = fold_target(&home, &root, &wt, isolated);
5674                remove_read_seat_worktree(&mut self.state, &wt).await?;
5675                reclaim_fold_target(&home, target);
5676                self.state.save()?;
5677            }
5678        }
5679        // The design-deliberation stage is finished by the time a tally
5680        // exists — same reasoning as the judges above.
5681        if self.state.config.graph.advise {
5682            for k in 1..=self.state.config.graph.advisors {
5683                let wt = root.join(format!("advisor-{k}"));
5684                if wt.exists() {
5685                    let target = fold_target(&home, &root, &wt, isolated);
5686                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5687                    reclaim_fold_target(&home, target);
5688                    self.state.save()?;
5689                }
5690            }
5691        }
5692        if !folded.is_empty() {
5693            self.state
5694                .event("fold", format!("folded candidates {}", folded.join(", ")));
5695            self.state.save()?;
5696        }
5697        Ok(())
5698    }
5699
5700    // ------------------------------------------------------------ base sync
5701
5702    async fn hold_base_sync(&mut self) -> Result<bool> {
5703        self.hold_base_sync_as(None).await
5704    }
5705
5706    async fn hold_base_sync_kind(
5707        &mut self,
5708        kind: crate::base_sync_recovery::StopKind,
5709    ) -> Result<()> {
5710        self.hold_base_sync_as(Some(kind)).await?;
5711        Ok(())
5712    }
5713
5714    async fn hold_base_sync_as(
5715        &mut self,
5716        kind: Option<crate::base_sync_recovery::StopKind>,
5717    ) -> Result<bool> {
5718        if !self.state.base_sync_blocked() {
5719            self.state.base_sync_recovery.stop = None;
5720            return Ok(false);
5721        }
5722        let head = match self.state.winner() {
5723            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5724                .await
5725                .unwrap_or_default(),
5726            None => String::new(),
5727        };
5728        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5729            && !authorization.consumed
5730            && authorization.stop.head != head
5731        {
5732            authorization.refuse(format!(
5733                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5734                authorization.stop.head
5735            ));
5736        }
5737        self.state.record_base_sync_stop(&head);
5738        if let Some(kind) = kind {
5739            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5740            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5741                stop.kind = kind;
5742            }
5743        }
5744        self.state.save()?;
5745        Ok(true)
5746    }
5747
5748    async fn resume_legacy_sequencer_stop(
5749        &mut self,
5750        winner: &Candidate,
5751        scratch: &Path,
5752        head: &str,
5753    ) -> Result<()> {
5754        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5755
5756        if !resumable_sequencer_stop(&self.state)
5757            || legacy_sequencer_head(&self.state) != Some(head)
5758            || self.state.base_recovery_pending()
5759            || self
5760                .state
5761                .repair_grants
5762                .iter()
5763                .any(|grant| !grant.succeeded)
5764        {
5765            return Ok(());
5766        }
5767        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5768            return Ok(());
5769        };
5770        let owner = crate::queue::Queue::open().get(task)?;
5771        if owner.execution_runs().last() != Some(&self.state.id)
5772            || owner.status == crate::queue::TaskStatus::Done
5773            || owner.fresh_start
5774            || owner.review_branch.is_some()
5775            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5776        {
5777            return Ok(());
5778        }
5779
5780        let repo = self.state.repo.clone();
5781        let wait = repository_wait(&self.state, None);
5782        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5783        let common = crate::repo_lock::common_dir(&repo).await?;
5784        let op = self.state.base_sync_recovery.operations.last().unwrap();
5785        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5786            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5787            || git::current_branch(&winner.worktree).await?.as_deref()
5788                != Some(winner.branch.as_str())
5789            || common.is_none()
5790            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5791            || crate::repo_lock::common_dir(&owner.repo).await? != common
5792            || !git::is_clean(&winner.worktree).await?
5793        {
5794            return Ok(());
5795        }
5796        if scratch.try_exists()? {
5797            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5798            if admin.join("locked").try_exists()?
5799                || !git::git(
5800                    scratch,
5801                    &[
5802                        "status",
5803                        "--porcelain",
5804                        "--untracked-files=all",
5805                        "--ignored",
5806                    ],
5807                )
5808                .await?
5809                .is_empty()
5810            {
5811                return Ok(());
5812            }
5813            if git::checked_rebase_in_progress(scratch).await? {
5814                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5815                    || crate::rebase::rebase_target(scratch).await? != op.tip
5816                    || !git::unmerged_paths(scratch).await?.is_empty()
5817                {
5818                    return Ok(());
5819                }
5820            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5821                || git::rev_parse(scratch, "HEAD").await? != head
5822            {
5823                return Ok(());
5824            }
5825        }
5826
5827        self.state
5828            .base_sync_recovery
5829            .operations
5830            .last_mut()
5831            .unwrap()
5832            .finished = false;
5833        let diagnostic = self
5834            .state
5835            .base_sync
5836            .as_mut()
5837            .unwrap()
5838            .conflict
5839            .take()
5840            .unwrap();
5841        self.state.base_sync_recovery.stop = None;
5842        self.state.event(
5843            "rebase",
5844            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
5845        );
5846        self.state.save()
5847    }
5848
5849    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5850    /// anything verifies it.
5851    ///
5852    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5853    /// read whatever is checked out in the winner's worktree. Left alone that
5854    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5855    /// it when the run *branched* - and a run takes long enough that the base
5856    /// has usually moved by the time it gets here. A gate that ran there
5857    /// answers "green on the commit this run started from", not "green on
5858    /// what is about to land", and the difference showed up three times in
5859    /// one day as a green run whose merge would have reverted a file another
5860    /// pull request had already landed.
5861    ///
5862    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5863    /// `land::Step::Rebase` calls, rather than a second implementation of the
5864    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5865    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5866    /// doc warns about ("two answers to a question nobody notices until a
5867    /// diff is wrong").
5868    ///
5869    /// Foreign-checkout reviews instead merge the base into the owned shadow
5870    /// worktree, preserving the ancestry required for fast-forward delivery.
5871    /// A conflicting merge is aborted and held for operator resolution.
5872    ///
5873    /// A conflict is not the end of the road: the standing rebase is handed
5874    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5875    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5876    /// land). Once it finishes, review and the gate run as usual on the
5877    /// rebased tree, which is where a breakage the new base caused is caught
5878    /// by the ordinary gate-fix round. magi resolves nothing itself.
5879    ///
5880    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5881    /// the current durable recovery interval, bounds how often the base is
5882    /// synchronized during active recovery (lifetime attempts remain evidence).
5883    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5884    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5885    /// what was tried (rounds spent, paths still conflicted) and the branch
5886    /// and worktree stay exactly as they were - untouched, for a person to
5887    /// look at - which is also what makes re-entering this function
5888    /// afterwards a no-op instead of a second attempt at the same wall. A
5889    /// push failure ends the same way.
5890    async fn sync_to_base(&mut self) -> Result<()> {
5891        if self.state.status == RunStatus::AlreadyInBase {
5892            return Ok(());
5893        }
5894        self.hold_base_sync().await?;
5895        let Some(winner) = self.state.winner().cloned() else {
5896            return Ok(());
5897        };
5898
5899        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5900
5901        let repo = self.state.repo.clone();
5902        let remote = self.state.config.merge.remote.clone();
5903        let base_branch = self.state.base_branch.clone();
5904        let tracking = format!("{remote}/{base_branch}");
5905
5906        let fetched_base =
5907            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5908        if !fetched_base
5909            && self
5910                .state
5911                .base_sync_recovery
5912                .stop
5913                .as_ref()
5914                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
5915        {
5916            self.state.event(
5917                "land",
5918                "cannot recheck recorded public branch divergence without a fresh base",
5919            );
5920            self.state.save()?;
5921            return Ok(());
5922        }
5923        // No network, or the remote never had this branch: the run already
5924        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5925        // otherwise), and one that got this far is not blocked by a fetch
5926        // that fails now. It just has no newer tip to compare against.
5927        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5928            return Ok(());
5929        };
5930
5931        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5932        self.state.ensure_base_episode();
5933        let scratch = self.state.dir().join("base-sync");
5934        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
5935            .await?;
5936        let conflicted = self
5937            .state
5938            .base_sync
5939            .as_ref()
5940            .is_some_and(|s| s.conflict.is_some());
5941        let mut pending = self.state.pending_base_operation().cloned();
5942        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
5943        {
5944            Ok(active) => active,
5945            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
5946            Err(error) => return Err(error),
5947        };
5948        if in_progress {
5949            // Older resource stops predate operation reservations. Import the
5950            // standing Git operation, never retarget it to today's main.
5951            if pending.is_none()
5952                && self.state.base_sync_recovery.operations.is_empty()
5953                && !conflicted
5954                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5955                    .await
5956                    .ok()
5957                    .as_deref()
5958                    == Some(head.as_str())
5959                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5960                && git::is_clean(&winner.worktree).await?
5961            {
5962                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5963                if self.state.base_sync.is_none() {
5964                    self.state.base_sync = Some(BaseSync {
5965                        tip: saved_tip.clone(),
5966                        behind: 0,
5967                        attempts: 0,
5968                        conflict: None,
5969                        already_in: None,
5970                    });
5971                }
5972                self.state.reserve_base_operation(&head, &saved_tip);
5973                self.state.event(
5974                    "base-recovery",
5975                    "imported standing legacy rebase as a spent synchronization reservation",
5976                );
5977                self.state.save()?;
5978                pending = self.state.base_sync_recovery.operations.last().cloned();
5979            }
5980            let expected = pending.as_ref().map(|op| op.tip.as_str());
5981            if expected.is_none()
5982                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5983            {
5984                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5985                if self.state.base_sync.is_none() {
5986                    self.state.base_sync = Some(BaseSync {
5987                        tip: tip.clone(),
5988                        behind: 0,
5989                        attempts: 0,
5990                        conflict: None,
5991                        already_in: None,
5992                    });
5993                }
5994                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5995                self.state.event("land", why);
5996                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5997                    .await?;
5998                return Ok(());
5999            }
6000        }
6001        if let Some(op) = &pending {
6002            // A replay may add the pinned base's commits, never foreign work.
6003            let mut replay_proven =
6004                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
6005            if !replay_proven && !in_progress && scratch.try_exists()? {
6006                let wait = repository_wait(&self.state, None);
6007                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6008                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
6009                    Ok(true) => {
6010                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
6011                        self.state.save()?;
6012                        git::worktree_remove(&repo, &scratch).await.ok();
6013                        replay_proven = true;
6014                    }
6015                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
6016                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
6017                }
6018            }
6019            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
6020                if self.state.foreign_checkout.is_some() {
6021                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
6022                        .await
6023                        .ok()
6024                        .as_deref()
6025                        == Some(op.head.as_str())
6026                        && git::rev_parse(&repo, &format!("{head}^2"))
6027                            .await
6028                            .ok()
6029                            .as_deref()
6030                            == Some(op.tip.as_str());
6031                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
6032                    .await
6033                    .is_ok_and(|m| m.is_empty())
6034                    && let Ok(added) =
6035                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
6036                {
6037                    replay_proven = true;
6038                    for commit in added {
6039                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
6040                            replay_proven = false;
6041                            break;
6042                        }
6043                    }
6044                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
6045                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
6046                }
6047            }
6048            // Never retarget an operation across a crash, even if main moved.
6049            // sync_to_head resets and cleans with -x, so even ignored untracked
6050            // files must stop recovery independently of the old tracked tree.
6051            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6052                || (head != op.head
6053                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
6054                        .await?
6055                        .is_empty())
6056                || (!git::is_clean(&winner.worktree).await?
6057                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
6058                        .await
6059                        .is_ok_and(|o| o.ok()))
6060                || !replay_proven
6061            {
6062                let why = format!(
6063                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
6064                    op.id
6065                );
6066                let sync = self
6067                    .state
6068                    .base_sync
6069                    .as_mut()
6070                    .context("reserved synchronization has no lifetime accounting")?;
6071                sync.conflict = Some(why.clone());
6072                self.state.event("land", why);
6073                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6074                    .await?;
6075                return Ok(());
6076            }
6077            if head != op.head {
6078                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6079            }
6080            tip = op.tip.clone();
6081        }
6082        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
6083        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
6084        if pending.is_none()
6085            && !conflicted
6086            && fetched_base
6087            && self
6088                .state
6089                .base_sync_recovery
6090                .episodes
6091                .last()
6092                .is_some_and(|e| e.boundary.is_some())
6093            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
6094            && let Ok(owner) = crate::queue::Queue::open().get(&task)
6095            && owner.execution_runs().last() == Some(&self.state.id)
6096            && owner.status != crate::queue::TaskStatus::Done
6097            && !owner.fresh_start
6098            && owner.review_branch.is_none()
6099            && crate::daemon::compatible_run_instruction(&self.state, &owner)
6100            && let Some(approval) = owner.resumption.as_ref()
6101            && approval.instruction == owner.instruction
6102            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6103            && git::is_clean(&winner.worktree).await?
6104            && self.state.renew_base_episode(&task, approval, &head, &tip)
6105        {
6106            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
6107            self.state.save()?;
6108        }
6109
6110        // Before any rebase, and before a recorded conflict is honoured: a
6111        // branch whose change reached the base under other commit ids has
6112        // nothing to rebase and nothing to conflict with, and a run that
6113        // already stopped on that phantom conflict recovers here on resume.
6114        // `behind == 0` with head == tip is a branch the base has since taken
6115        // in whole, whether or not a conflict was ever recorded: the ancestry
6116        // proof must still run (`classify` ignores a head still on the start
6117        // commit).
6118        if (behind > 0 || conflicted || head == tip)
6119            && self
6120                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
6121                .await?
6122        {
6123            return Ok(());
6124        }
6125        if conflicted && self.state.base_recovery_pending() {
6126            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6127            let owner =
6128                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6129            let owner_valid = owner.as_ref().is_ok_and(|t| {
6130                t.execution_runs().last() == Some(&self.state.id)
6131                    && t.assignment_accepts(&self.state)
6132                    && t.status != crate::queue::TaskStatus::Done
6133                    && !t.fresh_start
6134                    && t.review_branch.is_none()
6135            });
6136            let invalidation = if !owner_valid {
6137                Some("latest task ownership changed")
6138            } else if !owner.as_ref().is_ok_and(|t| {
6139                authorization
6140                    .generation
6141                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6142            }) {
6143                Some("owner approval generation changed")
6144            } else if authorization.question.as_ref().is_some_and(|question| {
6145                !crate::base_recovery_control::decision_current(
6146                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6147                    &self.state,
6148                    &authorization.task,
6149                    question,
6150                )
6151            }) {
6152                Some("recovery decision ownership, routing or stop evidence changed")
6153            } else if authorization.request.is_some()
6154                && !owner
6155                    .as_ref()
6156                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6157            {
6158                Some("owner decision changed")
6159            } else if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown
6160                && !authorization.scope.as_ref().is_some_and(|scope| {
6161                    scope.preparation_digest.is_some()
6162                        && scope.preparation_digest == self.state.preparation_digest(&head)
6163                })
6164            {
6165                Some("scratch preparation stop evidence changed")
6166            } else if let Some(scope) = &authorization.scope {
6167                if scope.tip != tip {
6168                    Some("fetched base changed")
6169                } else if !self
6170                    .state
6171                    .base_sync_recovery
6172                    .episodes
6173                    .last()
6174                    .is_some_and(|e| e.id == scope.episode)
6175                {
6176                    Some("active synchronization interval changed")
6177                } else if !owner
6178                    .as_ref()
6179                    .is_ok_and(|t| t.instruction == scope.instruction)
6180                {
6181                    Some("task instruction changed")
6182                } else {
6183                    None
6184                }
6185            } else {
6186                None
6187            };
6188            if let Some(reason) = invalidation {
6189                let authorization = self
6190                    .state
6191                    .base_sync_recovery
6192                    .authorizations
6193                    .last_mut()
6194                    .unwrap();
6195                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6196                self.state.save()?;
6197                return Ok(());
6198            }
6199            if !fetched_base
6200                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6201                || !git::is_clean(&winner.worktree).await?
6202                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6203            {
6204                return Ok(());
6205            }
6206            if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown {
6207                git::check_rebase_preparation(&self.state, &head, &self.state.dir()).await?;
6208            }
6209        }
6210        let recovery = conflicted && self.state.consume_base_recovery(&head);
6211        if conflicted {
6212            // Consumption (including a refused changed HEAD) is durable before Git.
6213            self.state.save()?;
6214            if !recovery {
6215                return Ok(());
6216            }
6217        }
6218
6219        if behind == 0 {
6220            // A fixer-finished rebase moves the branch ref before the
6221            // winner's worktree is told (`sync_to_head` below). A run that
6222            // died in between resumes here with `behind == 0` and a tree still
6223            // holding the pre-rebase files, which review and the gate would
6224            // then read. That state is exactly: HEAD moved off the tip the
6225            // rebase started from, yet the tree is still identical to that
6226            // tip. A tree with edits of its own differs from it, so nothing
6227            // is thrown away.
6228            if let Some(from) = self
6229                .state
6230                .rebase_fixes
6231                .iter()
6232                .rev()
6233                .find_map(|r| r.from.clone())
6234                && from != head
6235                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6236                    .await
6237                    .is_ok_and(|o| o.ok())
6238            {
6239                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6240            }
6241            // An earlier attempt may have rebased the branch locally and died
6242            // before pushing it (only the fresh-rebase arm below pushes).
6243            // Publish it now, so the plain push at PR time is not refused as
6244            // a non-fast-forward. A run already holding a recorded conflict
6245            // never reaches here; that case is out of scope.
6246            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6247            if let Some(why) = &conflict {
6248                self.state.status = RunStatus::Blocked;
6249                self.state.event("land", why.clone());
6250            }
6251            self.state.base_sync = Some(BaseSync {
6252                tip,
6253                behind: 0,
6254                attempts,
6255                conflict,
6256                already_in: None,
6257            });
6258            if pending.is_some() {
6259                self.state.finish_base_operation(Some(&head));
6260            }
6261            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6262                .await?;
6263            self.state.save()?;
6264            return Ok(());
6265        }
6266
6267        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6268            let why = format!(
6269                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6270                 synchronization(s); synchronizing again would only race it",
6271                winner.branch
6272            );
6273            self.state.status = RunStatus::Blocked;
6274            self.state.base_sync = Some(BaseSync {
6275                tip,
6276                behind,
6277                attempts,
6278                conflict: Some(why.clone()),
6279                already_in: None,
6280            });
6281            self.state.event("land", why);
6282            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6283                .await?;
6284            self.state.save()?;
6285            return Ok(());
6286        }
6287
6288        if self.state.foreign_checkout.is_some() {
6289            // Delivery to the operator's checkout is fast-forward only. A
6290            // rebase here would discard its saved head from our ancestry.
6291            let wait = repository_wait(&self.state, None);
6292            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6293            if self.state.base_sync.is_none() {
6294                self.state.base_sync = Some(BaseSync {
6295                    tip: tip.clone(),
6296                    behind,
6297                    attempts: 0,
6298                    conflict: None,
6299                    already_in: None,
6300                });
6301            }
6302            self.state.reserve_base_operation(&head, &tip);
6303            self.state.save()?;
6304            let merged = git::git_raw(
6305                &winner.worktree,
6306                &[
6307                    "-c",
6308                    "core.hooksPath=/dev/null",
6309                    "merge",
6310                    "--no-ff",
6311                    "--no-autostash",
6312                    "--no-edit",
6313                    "-m",
6314                    &format!("Merge {tracking} before verifying"),
6315                    &tip,
6316                ],
6317            )
6318            .await?;
6319            let conflict = if merged.ok() {
6320                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6321                self.state.event(
6322                    "land",
6323                    format!("merged {tracking} into {} before verifying", winner.branch),
6324                );
6325                None
6326            } else {
6327                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6328                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6329                }
6330                let why = format!(
6331                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6332                    winner.branch,
6333                    merged.stderr.chars().take(600).collect::<String>()
6334                );
6335                self.state.status = RunStatus::Blocked;
6336                self.state.event("land", &why);
6337                Some(why)
6338            };
6339            let synced = conflict.is_none();
6340            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6341            self.state
6342                .finish_base_operation(synced.then_some(fresh.as_str()));
6343            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6344            self.state.base_sync = Some(BaseSync {
6345                tip,
6346                behind: if synced { 0 } else { behind },
6347                attempts,
6348                conflict,
6349                already_in: None,
6350            });
6351            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6352                .await?;
6353            self.state.save()?;
6354            return Ok(());
6355        }
6356
6357        self.state.event(
6358            "land",
6359            format!(
6360                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6361                winner.branch
6362            ),
6363        );
6364        self.state.save()?;
6365
6366        // The remote's copy of the branch, read now and only if the fetch
6367        // really succeeded (a stale tracking ref must never pin a lease). It is
6368        // pushed over after a rebase only when it is a commit this branch
6369        // already contains, by ancestry or by patch (an earlier rebase of ours
6370        // that never reached the remote): anything else is somebody else's work.
6371        let branch_tracking = format!("{remote}/{}", winner.branch);
6372        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6373        let remote_tip = if self.state.task_pr_branch().is_none()
6374            && matches!(&fetched_branch, Ok(o) if o.ok())
6375        {
6376            git::rev_parse(&repo, &branch_tracking).await.ok()
6377        } else {
6378            None
6379        };
6380        // A remote tip this branch does not contain is somebody else's work:
6381        // rebasing would leave a local tip that can never be pushed. Stop
6382        // before touching anything and say so.
6383        if let Some(theirs) = &remote_tip
6384            && !git::is_ancestor(&repo, theirs, &head).await
6385            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6386                .await
6387                .is_ok_and(|missing| missing.is_empty())
6388        {
6389            let why = format!(
6390                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6391                 them",
6392                short(theirs),
6393                winner.branch
6394            );
6395            self.state.status = RunStatus::Blocked;
6396            self.state.base_sync = Some(BaseSync {
6397                tip,
6398                behind,
6399                attempts,
6400                conflict: Some(why.clone()),
6401                already_in: None,
6402            });
6403            self.state.event("land", why);
6404            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6405                .await?;
6406            self.state.save()?;
6407            return Ok(());
6408        }
6409
6410        if self.state.base_sync.is_none() {
6411            self.state.base_sync = Some(BaseSync {
6412                tip: tip.clone(),
6413                behind,
6414                attempts: 0,
6415                conflict: None,
6416                already_in: None,
6417            });
6418        }
6419        let scratch = self.state.dir().join("base-sync");
6420        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6421        {
6422            if error.is::<crate::repo_lock::ResourceBlocked>() {
6423                return Ok(());
6424            }
6425            return Err(error);
6426        }
6427        self.state.reserve_base_operation(&head, &tip);
6428        self.state.save()?;
6429        let rebased =
6430            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6431                .await
6432            {
6433                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6434                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6435                Err(e) => Err(e),
6436            };
6437        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6438        let stop_kind = match &rebased {
6439            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6440            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6441            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6442        };
6443        match rebased {
6444            Ok(None) => {
6445                // The branch ref moved, but a worktree that already had it
6446                // checked out (the winner's) was not told; sync its index and
6447                // files before anything reads them.
6448                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6449                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6450                self.state.finish_base_operation(Some(&fresh));
6451                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6452                let mut conflict = None;
6453                if let Some(pinned) = &remote_tip {
6454                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6455                    match pushed {
6456                        Ok(o) if o.ok() => self.state.event(
6457                            "land",
6458                            format!("pushed rebased {} to {remote}", winner.branch),
6459                        ),
6460                        Ok(o) => {
6461                            conflict = Some(format!(
6462                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6463                                winner.branch,
6464                                short(pinned),
6465                                o.stderr.chars().take(600).collect::<String>()
6466                            ));
6467                        }
6468                        Err(e) => {
6469                            conflict = Some(format!(
6470                                "rebased {} locally but could not push it: {e:#}",
6471                                winner.branch
6472                            ));
6473                        }
6474                    }
6475                }
6476                if let Some(why) = &conflict {
6477                    self.state.status = RunStatus::Blocked;
6478                    self.state.event("land", why.clone());
6479                }
6480                self.state.base_sync = Some(BaseSync {
6481                    tip: tip.clone(),
6482                    behind: 0,
6483                    attempts,
6484                    conflict,
6485                    already_in: None,
6486                });
6487                self.state
6488                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6489            }
6490            Ok(Some(conflict)) => {
6491                self.state.finish_base_operation(None);
6492                let why = format!(
6493                    "{} conflicts with {tracking} and did not rebase: {}",
6494                    winner.branch,
6495                    conflict.chars().take(600).collect::<String>()
6496                );
6497                self.state.status = RunStatus::Blocked;
6498                self.state.base_sync = Some(BaseSync {
6499                    tip,
6500                    behind,
6501                    attempts,
6502                    conflict: Some(why.clone()),
6503                    already_in: None,
6504                });
6505                self.state.event("land", why);
6506            }
6507            // A refused Git write or a busy repository: nothing is wrong with
6508            // the branch. The scratch rebase stays standing and the run
6509            // resumes into it (`base_sync` must not claim a conflict).
6510            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6511                self.state.save()?;
6512                return Ok(());
6513            }
6514            Err(e) => {
6515                self.state.finish_base_operation(None);
6516                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6517                self.state.status = RunStatus::Blocked;
6518                self.state.base_sync = Some(BaseSync {
6519                    tip,
6520                    behind,
6521                    attempts,
6522                    conflict: Some(why.clone()),
6523                    already_in: None,
6524                });
6525                self.state.event("land", why);
6526            }
6527        }
6528        if !self.state.base_sync_blocked() {
6529            self.state.base_sync_recovery.stop = None;
6530        }
6531        self.hold_base_sync_kind(stop_kind).await?;
6532        self.state.save()?;
6533        Ok(())
6534    }
6535
6536    /// Push a branch an earlier attempt rebased locally but never published,
6537    /// pinned to the remote tip read right after a successful fetch. Returns
6538    /// the reason when the run must stop; `None` when there was nothing to do
6539    /// (no remote copy, the same tip, or a remote copy this branch already
6540    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6541    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6542        // Task competitions publish only after the PR text gate, to their
6543        // public head; never resurrect a candidate branch on the remote.
6544        if self.state.task_pr_branch().is_some() {
6545            return None;
6546        }
6547        let repo = self.state.repo.clone();
6548        let remote = self.state.config.merge.remote.clone();
6549        let fetched = git::fetch(&repo, &remote, branch).await;
6550        if !matches!(&fetched, Ok(o) if o.ok()) {
6551            return None;
6552        }
6553        let branch_tracking = format!("{remote}/{branch}");
6554        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6555        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6556            return None;
6557        }
6558        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6559            .await
6560            .is_ok_and(|missing| missing.is_empty())
6561        {
6562            return Some(format!(
6563                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6564                 them",
6565                short(&theirs)
6566            ));
6567        }
6568        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6569            Ok(o) if o.ok() => {
6570                self.state
6571                    .event("land", format!("pushed rebased {branch} to {remote}"));
6572                None
6573            }
6574            Ok(o) => Some(format!(
6575                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6576                 someone may have pushed): {}",
6577                short(&theirs),
6578                o.stderr.chars().take(600).collect::<String>()
6579            )),
6580            Err(e) => Some(format!(
6581                "{branch} is rebased locally but could not be pushed: {e:#}"
6582            )),
6583        }
6584    }
6585
6586    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6587    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6588    /// whether it did.
6589    ///
6590    /// Checked only when the base is ahead of the branch. A failing check is
6591    /// "not proven" - the ordinary rebase path then decides - never a reason to
6592    /// stop the run.
6593    ///
6594    /// The remote copy of the branch is held to the same standard as the local
6595    /// one: if it carries a tip this worktree does not, that tip must itself be
6596    /// proven in the base, or nothing is settled (a pull request would
6597    /// otherwise be closed over commits nobody checked). The pull request is
6598    /// closed *before* the terminal status is saved; if that fails for a
6599    /// reason other than a refusal (no network, a `gh` error) the run is left
6600    /// `Blocked` with the reason as its conflict, which a resume retries -
6601    /// the same recovery a phantom conflict gets.
6602    async fn settle_already_in(
6603        &mut self,
6604        branch: &str,
6605        tip: &str,
6606        head: &str,
6607        attempts: usize,
6608        behind: usize,
6609    ) -> Result<bool> {
6610        let repo = self.state.repo.clone();
6611        let remote = self.state.config.merge.remote.clone();
6612        let start = self.state.base_commit.clone();
6613        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6614            Ok(Some(e)) => e,
6615            Ok(None) => return Ok(false),
6616            Err(e) => {
6617                tracing::warn!("already-in-base check for {branch}: {e:#}");
6618                return Ok(false);
6619            }
6620        };
6621        let mut verified = vec![head.to_owned()];
6622        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6623        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6624        let divergence = self
6625            .state
6626            .base_sync_recovery
6627            .stop
6628            .as_ref()
6629            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6630        if matches!(&fetched, Ok(o) if o.ok()) {
6631            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6632                Ok(theirs) if theirs != head => {
6633                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6634                        Ok(Some(_)) => verified.push(theirs),
6635                        _ => return Ok(false),
6636                    }
6637                }
6638                Err(_) if divergence => return Ok(false),
6639                _ => {}
6640            }
6641        } else if divergence
6642            && !matches!(
6643                git::remote_has_branch(&repo, &remote, &public_branch).await,
6644                Ok(false)
6645            )
6646        {
6647            // A failed fetch cannot discharge a recorded divergence.
6648            return Ok(false);
6649        }
6650        let base_branch = self.state.base_branch.clone();
6651        let message = format!(
6652            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6653             land",
6654            evidence.names(),
6655            evidence.proof.as_str()
6656        );
6657        let closed =
6658            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6659                .await;
6660        match closed {
6661            Ok(Ok(url)) => self
6662                .state
6663                .event("land", format!("closed {url}: superseded on {base_branch}")),
6664            Ok(Err(why)) => self
6665                .state
6666                .event("land", format!("did not close a pull request: {why}")),
6667            Err(e) => {
6668                let why = format!(
6669                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6670                     not be closed ({e:#}); resume to retry"
6671                );
6672                self.state.status = RunStatus::Blocked;
6673                self.state.base_sync = Some(BaseSync {
6674                    tip: tip.to_owned(),
6675                    behind,
6676                    attempts,
6677                    conflict: Some(why.clone()),
6678                    already_in: None,
6679                });
6680                self.state.event("land", why);
6681                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6682                    .await?;
6683                self.state.save()?;
6684                return Ok(true);
6685            }
6686        }
6687        self.state.status = RunStatus::AlreadyInBase;
6688        self.state.base_sync_recovery.stop = None;
6689        self.state.base_sync = Some(BaseSync {
6690            tip: tip.to_owned(),
6691            behind,
6692            attempts,
6693            conflict: None,
6694            already_in: Some(evidence),
6695        });
6696        self.state.event("land", message);
6697        self.state.save()?;
6698        self.settle_questions();
6699        Ok(true)
6700    }
6701
6702    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6703    /// last landed the winner on, once it has run, else the commit the run
6704    /// branched from.
6705    ///
6706    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6707    /// and `vote` all happen before there is a winner to rebase, so they
6708    /// compare every candidate against the branch point on purpose, and a
6709    /// base that moves after they are already done cannot change an answer
6710    /// they already gave.
6711    fn landing_base(&self) -> String {
6712        self.state
6713            .base_sync
6714            .as_ref()
6715            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6716    }
6717
6718    // ------------------------------------------------------- operator fix
6719
6720    /// Route specific, already-recorded review findings to a fixer for a
6721    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6722    /// entry point.
6723    ///
6724    /// Distinct from `review_loop`'s own fix step in three ways: it never
6725    /// runs a reviewer wave, it never spends review-round budget, and what
6726    /// happened is recorded as an [`OperatorFixRequest`] appended to
6727    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6728    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6729    /// and vote must never be rewritten to look like a manufactured blocking
6730    /// verdict.
6731    ///
6732    /// Only meaningful once review has actually concluded: `Ready` (handed
6733    /// off with findings still open, or simply concluded clean while minor
6734    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6735    /// gate failed). Everything else is refused: a run still in progress
6736    /// should simply be resumed, and a `Merged` run's branch has already
6737    /// landed — reopening *this* run's own record cannot change that, so the
6738    /// answer there is a fresh `magi review <branch>`.
6739    ///
6740    /// A real commit here re-verifies through a fresh, ordinary review-only
6741    /// run on the same branch ([`Self::review`]) rather than reopening this
6742    /// run's own `review_loop`: once any round in this run's history went
6743    /// clean, `review_conclusion` treats that as permanent by design (the
6744    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6745    /// way to force one more genuine reviewer wave out of *this* run without
6746    /// either rewriting history or weakening that guarantee for every other
6747    /// caller. A review-only run costs nothing extra — no implementation, no
6748    /// judging, no vote — and exercises the exact same review → verify →
6749    /// gate → (human) merge path, unmodified.
6750    pub async fn fix_selected(
6751        &mut self,
6752        ids: &[String],
6753        reason: &str,
6754        allow_stale: bool,
6755    ) -> Result<()> {
6756        let reason = reason.trim();
6757        if reason.is_empty() {
6758            bail!("a fix request needs a reason — that is the operator's own record of why");
6759        }
6760        if ids.is_empty() {
6761            bail!("no finding id given");
6762        }
6763        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6764            bail!(
6765                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6766                 has already concluded — can be given a targeted fix. A run still \
6767                 in progress should simply be resumed; a `merged` run's branch has \
6768                 already landed, so its answer is a fresh `magi review <branch>`, \
6769                 not reopening this run's own record",
6770                self.state.id,
6771                self.state.status.as_str()
6772            );
6773        }
6774        // Reassignment shares this claim through its atomic task save. Check
6775        // the canonical run identity inside it, before preflight or any await.
6776        let _claim = FixClaim::acquire(&self.state.dir())?;
6777        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6778        let home = crate::run::home();
6779        // The ordinary driver takes these same locks at admission. Keep the
6780        // execution lease through the fix, but never the owner lock across Git
6781        // or agent awaits.
6782        let execution = {
6783            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6784            let disk = RunState::load(&self.state.id)?;
6785            crate::pr_head::ensure_owner(&disk)?;
6786            anyhow::ensure!(
6787                disk.status == self.state.status && disk.released_to.is_none(),
6788                "run changed since it was loaded; reload before fixing"
6789            );
6790            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6791            anyhow::ensure!(
6792                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6793                "run {} is currently being worked on or its ownership is unknown",
6794                disk.id
6795            );
6796            let lease = crate::driver::maintenance(&home, &disk.id).context(
6797                "run is currently being worked on or its execution lease is unavailable",
6798            )?;
6799            self.state = disk;
6800            lease
6801        };
6802        let Some(winner) = self.state.winner().cloned() else {
6803            bail!("run {} has no winning candidate to fix", self.state.id);
6804        };
6805        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6806            bail!(
6807                "branch `{}` no longer exists; this run cannot be extended",
6808                winner.branch
6809            );
6810        }
6811        // Resolve every id before spending anything — an unknown id refuses
6812        // the whole request rather than silently dropping it — and dedup
6813        // while keeping the operator's own order.
6814        let mut seen = BTreeSet::new();
6815        let mut findings = Vec::new();
6816        let mut missing = Vec::new();
6817        for id in ids {
6818            if !seen.insert(id.clone()) {
6819                continue;
6820            }
6821            match self.state.finding(id) {
6822                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6823                    id: f.id.clone(),
6824                    severity: f.severity,
6825                    reviewer_vote: rec.vote,
6826                    round: round.round,
6827                    round_head: round.head.clone(),
6828                    reviewer: rec.reviewer,
6829                    agent: rec.agent.clone(),
6830                    file: f.file.clone(),
6831                    line: f.line,
6832                    title: f.title.clone(),
6833                    detail: f.detail.clone(),
6834                    outcome: OperatorFixOutcome::Pending,
6835                }),
6836                None => missing.push(id.clone()),
6837            }
6838        }
6839        if !missing.is_empty() {
6840            bail!(
6841                "unknown finding id(s): {}; nothing was changed",
6842                missing.join(", ")
6843            );
6844        }
6845
6846        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6847        let stale_details: Vec<(String, String)> = findings
6848            .iter()
6849            .filter(|f| f.round_head != head_at_request)
6850            .map(|f| (f.id.clone(), f.round_head.clone()))
6851            .collect();
6852        let stale = !stale_details.is_empty();
6853        if stale && !allow_stale {
6854            bail!(
6855                "the branch has moved since some finding(s) were raised — {} — now \
6856                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6857                stale_details
6858                    .iter()
6859                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6860                    .collect::<Vec<_>>()
6861                    .join(", "),
6862                short(&head_at_request)
6863            );
6864        }
6865
6866        let request = OperatorFixRequest {
6867            requested_at: Timestamp::now(),
6868            reason: reason.to_owned(),
6869            findings,
6870            head_at_request: head_at_request.clone(),
6871            allow_stale,
6872            stale,
6873            fix: None,
6874            result_head: None,
6875            follow_up_review_run: None,
6876        };
6877        self.state.event(
6878            "fix",
6879            format!(
6880                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6881                request.findings.len(),
6882                request
6883                    .findings
6884                    .iter()
6885                    .map(|f| f.id.as_str())
6886                    .collect::<Vec<_>>()
6887                    .join(", "),
6888            ),
6889        );
6890        // Recorded now, before any worktree work or the fixer call itself —
6891        // and re-saved at each checkpoint below: a crash at any point after
6892        // this (mid fixer call, mid follow-up review) must not lose the fact
6893        // that this was requested, for which findings, and why. Everything
6894        // past this point reads and writes through `request_index` rather
6895        // than a local variable, since `request` itself is moved here.
6896        self.state.operator_fixes.push(request);
6897        self.state.save()?;
6898        let request_index = self.state.operator_fixes.len() - 1;
6899
6900        // A fresh, dedicated worktree for this one call, never the winner's
6901        // own worktree in place: that one may already be gone (folded away),
6902        // and reusing it in place would leave the branch checked out there
6903        // when the follow-up review below tries to check it out again. Freed
6904        // immediately after, either way — but only once confirmed clean:
6905        // `worktree_remove` is a `git worktree remove --force`, which would
6906        // otherwise discard uncommitted work left there by the operator or
6907        // another process before this had a chance to even look at it.
6908        let repo = self.state.repo.clone();
6909        let coordination = self.coordinate(&repo).await?;
6910        if winner.worktree.exists() {
6911            // Lockfiles a rescue commit withheld stay untracked on purpose and
6912            // are already recorded; they are not the operator's work to protect.
6913            let dirty = git::git(
6914                &winner.worktree,
6915                &["status", "--porcelain", "--untracked-files=all"],
6916            )
6917            .await?;
6918            let only_withheld = dirty.lines().all(|l| {
6919                l.strip_prefix("?? ")
6920                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6921            });
6922            if !only_withheld {
6923                bail!(
6924                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6925                     discard them first",
6926                    winner.worktree.display()
6927                );
6928            }
6929            git::worktree_remove(&self.state.repo, &winner.worktree)
6930                .await
6931                .ok();
6932        }
6933        let fix_worktree = self.state.worktree_root().join("operator-fix");
6934        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6935        git::git(
6936            &self.state.repo,
6937            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6938        )
6939        .await
6940        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6941        if !git::is_clean(&fix_worktree).await? {
6942            git::worktree_remove(&self.state.repo, &fix_worktree)
6943                .await
6944                .ok();
6945            bail!(
6946                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6947                winner.branch
6948            );
6949        }
6950        let repo_for_setup = self.state.repo.clone();
6951        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6952            Ok(()) => {
6953                worktree_setup::prepare_with(
6954                    &self.state.config,
6955                    &repo_for_setup,
6956                    &fix_worktree,
6957                    crate::build_target::Coordination::Held(coordination.as_ref()),
6958                )
6959                .await
6960            }
6961            Err(e) => Err(e),
6962        };
6963        if let Err(e) = setup {
6964            git::worktree_remove(&self.state.repo, &fix_worktree)
6965                .await
6966                .ok();
6967            return Err(e);
6968        }
6969
6970        // This explicit operator request retries availability independently
6971        // of execute(); the previous call has already saved and cleaned up.
6972        self.state.resource_block = None;
6973
6974        let run_id = self.state.id.clone();
6975        let prompts = self.state.config.prompts.clone();
6976        let language = self.state.config.graph.language.clone();
6977        let sessions = self.state.config.graph.sessions;
6978        let artifacts = agent::artifacts_dir(&self.state.dir());
6979        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6980            .findings
6981            .iter()
6982            .map(|f| Finding {
6983                id: f.id.clone(),
6984                severity: f.severity,
6985                file: f.file.clone(),
6986                line: f.line,
6987                title: f.title.clone(),
6988                detail: f.detail.clone(),
6989            })
6990            .collect();
6991        let fix_prompt = prompt::operator_fix_in(
6992            &self.state.instruction,
6993            &finding_list,
6994            reason,
6995            &stale_details,
6996            &head_at_request,
6997            &language,
6998            &self.state.config.graph.github_language,
6999        );
7000        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7001        drop(coordination);
7002        let (job, seat, out) = self
7003            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
7004                prompt: fix_prompt.clone(),
7005                spec,
7006                seat,
7007                cwd: fix_worktree.clone(),
7008                timeout,
7009                allow_write: true,
7010                sessions,
7011                artifacts: artifacts.clone(),
7012                stem: "operator-fix".to_owned(),
7013                handover: None,
7014            })
7015            .await;
7016        let agent_id = seat.agent.clone();
7017
7018        let mut fix = FixRecord {
7019            agent: agent_id,
7020            addressed: Vec::new(),
7021            rejected: Vec::new(),
7022            notes: String::new(),
7023            committed: false,
7024            failed: None,
7025            duration_ms: 0,
7026            continuation: None,
7027        };
7028        let mut final_seat = seat.clone();
7029        match out {
7030            AgentOutcome::Ok(o) => {
7031                fix.duration_ms = o.duration_ms;
7032                let parsed = verdict::extract_json::<FixReport>(&o.text);
7033                let incomplete_reason = match &parsed {
7034                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
7035                        "the reply parsed, but it reported a command whose own CLI \
7036                         never confirmed an exit status"
7037                            .to_owned(),
7038                    ),
7039                    Ok(_) => None,
7040                    Err(e) => Some(e.to_string()),
7041                };
7042                match incomplete_reason {
7043                    None => {
7044                        let report = parsed.expect("checked Ok above");
7045                        fix.addressed = report.addressed;
7046                        fix.rejected = report.rejected;
7047                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
7048                    }
7049                    Some(reason) => {
7050                        let (resumed_seat, resolved, failure, cont) = self
7051                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
7052                            .await;
7053                        fix.duration_ms += cont.cumulative_wait_ms;
7054                        fix.continuation = Some(cont);
7055                        final_seat = resumed_seat;
7056                        match resolved {
7057                            Some(report) => {
7058                                fix.addressed = report.addressed;
7059                                fix.rejected = report.rejected;
7060                                fix.notes =
7061                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
7062                            }
7063                            None => fix.failed = failure,
7064                        }
7065                    }
7066                }
7067            }
7068            AgentOutcome::Dropped(o) => {
7069                fix.duration_ms = o.duration_ms;
7070                let why = o
7071                    .dropped
7072                    .as_ref()
7073                    .map(|d| d.why.as_str())
7074                    .unwrap_or("the CLI ended the stream without delivering its answer");
7075                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
7076            }
7077            AgentOutcome::Quota(o) => {
7078                self.state.quota.push(QuotaLoss::from_report(
7079                    final_seat.key.clone(),
7080                    "fix",
7081                    o.quota.as_ref(),
7082                ));
7083                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
7084            }
7085            AgentOutcome::Failed(e) => fix.failed = Some(e),
7086            AgentOutcome::ResourceBlocked(e) => {
7087                fix.failed = Some(format!("the fixer was not started: {e}"));
7088            }
7089        }
7090        // Even a deferred call must rescue edits, release the worktree and
7091        // finalize its record below so an explicit `magi fix` can retry.
7092        if fix.continuation.is_none() {
7093            fix.continuation = Some(ContinuationRecord::not_needed());
7094        }
7095        self.state.seats.insert(final_seat.key.clone(), final_seat);
7096
7097        let rescue_message = format!(
7098            "magi: operator-selected fix ({}) (uncommitted work)",
7099            self.state.operator_fixes[request_index]
7100                .findings
7101                .iter()
7102                .map(|f| f.id.as_str())
7103                .collect::<Vec<_>>()
7104                .join(", ")
7105        );
7106        let repo = self.state.repo.clone();
7107        let coordination = self.coordinate(&repo).await?;
7108        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
7109            self.state.note_withheld("fix", &r.withheld);
7110        }
7111        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
7112        fix.committed = after != head_at_request;
7113        git::worktree_remove(&self.state.repo, &fix_worktree)
7114            .await
7115            .ok();
7116        drop(coordination);
7117
7118        self.state.event(
7119            "fix",
7120            match &fix.failed {
7121                Some(reason) => format!(
7122                    "operator fix: adoption report was lost ({reason}); {}",
7123                    if fix.committed {
7124                        "committed"
7125                    } else {
7126                        "NO new commit"
7127                    }
7128                ),
7129                None => format!(
7130                    "operator fix: {} addressed, {} rejected, {}",
7131                    fix.addressed.len(),
7132                    fix.rejected.len(),
7133                    if fix.committed {
7134                        "committed"
7135                    } else {
7136                        "NO new commit"
7137                    }
7138                ),
7139            },
7140        );
7141
7142        // Every selected finding gets an outcome — never left `Pending` once
7143        // the fixer's own turn is over. A report that never came back at all
7144        // marks every one of them `Unreported`, not silently "not addressed":
7145        // quota, a dropped stream, or an exhausted continuation are gaps in
7146        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7147        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7148        for f in &mut self.state.operator_fixes[request_index].findings {
7149            f.outcome = if fix.failed.is_some() {
7150                OperatorFixOutcome::Unreported
7151            } else if fix.addressed.contains(&f.id) {
7152                OperatorFixOutcome::Addressed
7153            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7154                OperatorFixOutcome::Rejected { why: r.why.clone() }
7155            } else {
7156                OperatorFixOutcome::Unreported
7157            };
7158        }
7159
7160        let committed = fix.committed;
7161        if committed {
7162            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7163        }
7164        self.state.operator_fixes[request_index].fix = Some(fix);
7165        // Saved again now that the fixer's own outcome is final, on top of
7166        // the save right after the request was first pushed above.
7167        self.state.save()?;
7168        if self.state.resource_block.is_some() {
7169            return self.stop_for_resource();
7170        }
7171
7172        if committed {
7173            self.state.event(
7174                "fix",
7175                format!(
7176                    "operator fix committed {}; opening a follow-up review-only run",
7177                    short(&after)
7178                ),
7179            );
7180            self.state.save()?;
7181            drop(execution);
7182            // The new review owns its own execution. Update only its audit link
7183            // afterwards, since publication may have changed the old record.
7184            let event_count = self.state.events.len();
7185            let save_follow_up = |state: &mut RunState| -> Result<()> {
7186                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7187                let _execution = crate::driver::maintenance(&home, &state.id)?;
7188                let mut disk = RunState::load(&state.id)?;
7189                disk.events.extend(state.events.drain(event_count..));
7190                let follow_up = state.operator_fixes[request_index]
7191                    .follow_up_review_run
7192                    .clone();
7193                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7194                disk.save()?;
7195                *state = disk;
7196                Ok(())
7197            };
7198            // The operator asked for the fix, and the follow-up serves whatever
7199            // task the run it follows served.
7200            let origin =
7201                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7202            match Self::review(
7203                &self.state.repo,
7204                &winner.branch,
7205                self.state.config.clone(),
7206                origin,
7207            )
7208            .await
7209            {
7210                Ok(mut follow_up) => {
7211                    follow_up.state.event(
7212                        "start",
7213                        format!(
7214                            "requested by an operator fix on run {} for finding(s) {}",
7215                            self.state.id,
7216                            self.state.operator_fixes[request_index]
7217                                .findings
7218                                .iter()
7219                                .map(|f| f.id.as_str())
7220                                .collect::<Vec<_>>()
7221                                .join(", "),
7222                        ),
7223                    );
7224                    follow_up.state.save()?;
7225                    let follow_up_id = follow_up.state.id.clone();
7226                    // The follow-up is a run like any other: it belongs to the
7227                    // task of the run it follows, or to one filed for it.
7228                    let adopted = match crate::direct::adopt(
7229                        &follow_up.state,
7230                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7231                    ) {
7232                        Ok(a) => a,
7233                        Err(e) => {
7234                            // An ownerless run must not spend agent calls; it
7235                            // stays saved, and `magi run --resume` adopts it.
7236                            self.state.event(
7237                                "fix",
7238                                format!(
7239                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7240                                ),
7241                            );
7242                            save_follow_up(&mut self.state)?;
7243                            return Ok(());
7244                        }
7245                    };
7246                    let executed = follow_up.execute().await;
7247                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7248                    if let Some(a) = adopted {
7249                        a.finish(&follow_up.state, executed);
7250                    }
7251                    if let Some(e) = failure {
7252                        self.state.event(
7253                            "fix",
7254                            format!(
7255                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7256                            ),
7257                        );
7258                    }
7259                    self.state.operator_fixes[request_index].follow_up_review_run =
7260                        Some(follow_up_id);
7261                }
7262                Err(e) => {
7263                    self.state.event(
7264                        "fix",
7265                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7266                    );
7267                }
7268            }
7269            save_follow_up(&mut self.state)?;
7270        }
7271
7272        Ok(())
7273    }
7274
7275    // --------------------------------------------------------------- review
7276
7277    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7278    /// names, in order, each at most once, moving on only when the call
7279    /// advances (an error, a quota hit or nothing usable - the same decision
7280    /// point `agent::chain_advances` is for the other chained roles).
7281    ///
7282    /// Each agent gets its own seat from `Runner::seat`: the same agent
7283    /// continues its conversation (the winner's own implementer seat when it
7284    /// is the winner's author, now that the competition is over), another
7285    /// takes a fresh one so the full prompt is sent again. A handover is
7286    /// recorded under `node`, which is what makes the fallback stick for the
7287    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7288    /// is returned, so an exhausted chain reads exactly like a single failed
7289    /// fixer: one quota loss, the same wording, the same refund. An earlier
7290    /// attempt's edits are left in the tree and judged, with the final
7291    /// attempt's, by what git says afterwards.
7292    ///
7293    /// Returns the job that produced the outcome, for `continue_fix_report`.
7294    async fn ask_fixer(
7295        &mut self,
7296        winner: &Candidate,
7297        node: &'static str,
7298        round: Option<usize>,
7299        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7300    ) -> (SeatJob, SeatState, AgentOutcome) {
7301        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7302        self.ask_fixer_among(attempts, node, round, None, build)
7303            .await
7304    }
7305
7306    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7307    /// worktree and a commit: before the next agent is asked after one that
7308    /// did not satisfy the call, the worktree is put back on that commit, so
7309    /// a failed agent's partial edits are not carried into the next one.
7310    async fn ask_fixer_among(
7311        &mut self,
7312        attempts: Vec<(AgentSpec, String)>,
7313        node: &'static str,
7314        round: Option<usize>,
7315        restore: Option<(&Path, &str)>,
7316        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7317    ) -> (SeatJob, SeatState, AgentOutcome) {
7318        let run_id = self.state.id.clone();
7319        let prompts = self.state.config.prompts.clone();
7320        let cache = self.state.config.cache_dir();
7321        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7322        let mut last = None;
7323        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7324            let seat = self.seat(&key, &spec.id);
7325            let mut job = build(spec.clone(), seat);
7326            if i > 0 {
7327                job.stem = format!("{}-{}", job.stem, spec.id);
7328            }
7329            let ctx = WaveCtx {
7330                carry_seats: false,
7331                pauses: Some((&self.pause, &self.interrupt)),
7332                run: &run_id,
7333                node,
7334                prompts: &prompts,
7335                cache: cache.as_deref(),
7336                round,
7337            };
7338            let (seat, out) =
7339                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7340            // A resource block never advances the chain: the chosen agent
7341            // was not asked, so it must be the one asked again on resume.
7342            let advances = match &out {
7343                AgentOutcome::Ok(o) => agent::output_advances(o),
7344                AgentOutcome::ResourceBlocked(_) => false,
7345                _ => true,
7346            };
7347            if let Some(next) = ids.get(i + 1)
7348                && advances
7349            {
7350                self.state.seats.insert(seat.key.clone(), seat.clone());
7351                let class =
7352                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7353                let reason = match &out {
7354                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7355                    other => fail_reason(other),
7356                };
7357                // A failed agent's edits must not reach the next one, and a
7358                // restore that did not work ends the chain: the call fails
7359                // and the caller's own (confirmed) restore decides.
7360                if let Some((wt, rev)) = restore
7361                    && let Err(e) = self.graft_restore(wt, rev).await
7362                {
7363                    let why =
7364                        format!("could not restore the worktree before the next fixer: {e:#}");
7365                    tracing::warn!("{why}");
7366                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7367                        AgentOutcome::ResourceBlocked(why)
7368                    } else {
7369                        AgentOutcome::Failed(why)
7370                    };
7371                    last = Some((job, seat, out));
7372                    break;
7373                }
7374                record_handover(
7375                    &mut self.state,
7376                    node,
7377                    &seat.key,
7378                    &spec.id,
7379                    next,
7380                    &class,
7381                    &reason,
7382                );
7383                continue;
7384            }
7385            last = Some((job, seat, out));
7386            break;
7387        }
7388        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7389        if let AgentOutcome::Quota(output) = &out
7390            && node != "graft"
7391        {
7392            // Graft is best effort: its caller records the loss and restores
7393            // the pre-graft tree, then proceeds to review and gate.
7394            // Every fallback was tried. Machine outages cannot be repaired by
7395            // spending a fix round; use each caller's resumable resource path.
7396            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7397            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7398            self.state.quota.push(loss);
7399            self.state.seats.insert(seat.key.clone(), seat.clone());
7400            self.state.status = RunStatus::Blocked;
7401            return (
7402                job,
7403                seat,
7404                AgentOutcome::ResourceBlocked(
7405                    "fixer unavailable; restore agent availability and resume".into(),
7406                ),
7407            );
7408        }
7409        (job, seat, out)
7410    }
7411
7412    /// The one repair a verification-only failure earns (see
7413    /// [`crate::recovery`]), before the first review round of a run that took
7414    /// a branch over.
7415    ///
7416    /// Saved as started *before* the fixer is called, so a resume never
7417    /// repairs twice; a start found on re-entry is rolled back to the commit
7418    /// it began from. A failed or unusable fixer leaves the tree as it was and
7419    /// the review goes on over it, so the first round's own verification
7420    /// reports the failure again. The failure is never carried into a round as
7421    /// a result: verification is re-run on whatever commit this leaves.
7422    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7423        use crate::recovery::{Mode, Repair};
7424        if !self.state.reviews.is_empty() {
7425            return Ok(());
7426        }
7427        let Some(mut rec) = self.state.recovery.clone() else {
7428            return Ok(());
7429        };
7430        if rec.mode != Mode::VerifyRepair {
7431            return Ok(());
7432        }
7433        let wt = winner.worktree.clone();
7434        let mut head = git::rev_parse(&wt, "HEAD").await?;
7435        match rec.repair.clone() {
7436            Repair::Done { .. } => return Ok(()),
7437            Repair::WaitingForRestore { before } => {
7438                self.graft_restore(&wt, &before).await?;
7439                head = before;
7440                rec.repair = Repair::NotStarted;
7441                self.state.recovery = Some(rec.clone());
7442                self.state.save()?;
7443            }
7444            Repair::Started { before } => {
7445                // Interrupted: the unfinished edits are not trusted.
7446                // An unconfirmed rollback blocks the run with `Started` kept,
7447                // so a resume retries it; the tree is never reviewed as is.
7448                if let Err(e) = self.graft_restore(&wt, &before).await {
7449                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7450                        return Err(e);
7451                    }
7452                    return self
7453                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7454                        .await;
7455                }
7456                rec.repair = Repair::Done {
7457                    before: before.clone(),
7458                    after: before,
7459                    committed: false,
7460                    failed: Some("interrupted; rolled back".to_owned()),
7461                };
7462                self.state
7463                    .event("recovery", "the repair was interrupted and rolled back");
7464                self.state.recovery = Some(rec);
7465                self.state.save()?;
7466                return Ok(());
7467            }
7468            Repair::NotStarted => {}
7469        }
7470        if crate::recovery::recheck(&mut rec, &head) {
7471            self.state.event("recovery", rec.summary());
7472            self.state.recovery = Some(rec);
7473            self.state.save()?;
7474            return Ok(());
7475        }
7476        rec.repair = Repair::Started {
7477            before: head.clone(),
7478        };
7479        self.state.recovery = Some(rec.clone());
7480        self.state.save()?;
7481
7482        let language = self.state.config.graph.language.clone();
7483        let sessions = self.state.config.graph.sessions;
7484        let artifacts = agent::artifacts_dir(&self.state.dir());
7485        let fix_prompt = prompt::recovery_fix(
7486            &self.state.instruction,
7487            &rec,
7488            self.state.config.graph.review_rounds,
7489            &language,
7490        );
7491        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7492        self.state.event(
7493            "recovery",
7494            format!(
7495                "repair: the fixer starts from the failed verification on {}",
7496                short(&head)
7497            ),
7498        );
7499        let (_job, seat, out) = self
7500            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7501                prompt: fix_prompt.clone(),
7502                spec,
7503                seat,
7504                cwd: wt.clone(),
7505                timeout,
7506                allow_write: true,
7507                sessions,
7508                artifacts: artifacts.clone(),
7509                stem: "fix-recovery".to_owned(),
7510                handover: None,
7511            })
7512            .await;
7513        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7514            rec.repair = Repair::WaitingForRestore { before: head };
7515            self.state.recovery = Some(rec);
7516            return self.stop_for_resource();
7517        }
7518        let failed = match &out {
7519            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7520            AgentOutcome::Quota(o) => {
7521                self.state.quota.push(QuotaLoss::from_report(
7522                    seat.key.clone(),
7523                    "fix",
7524                    o.quota.as_ref(),
7525                ));
7526                Some("rate limited (quota); the fixer could not run".to_owned())
7527            }
7528            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7529            AgentOutcome::Failed(e) => Some(e.clone()),
7530        };
7531        self.state.seats.insert(seat.key.clone(), seat);
7532        let coordination = self.coordinate(&wt).await?;
7533        let failed = match failed {
7534            // The agent's partial edits are not kept.
7535            Some(why) => {
7536                if let Err(e) = git::restore_to(&wt, &head).await {
7537                    return self
7538                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7539                        .await;
7540                }
7541                Some(why)
7542            }
7543            None => {
7544                if let Ok(r) = git::rescue_commit(
7545                    &wt,
7546                    "magi: recovery repair of the failed verification (uncommitted work)",
7547                )
7548                .await
7549                {
7550                    self.state.note_withheld("fix", &r.withheld);
7551                }
7552                None
7553            }
7554        };
7555        let after = git::rev_parse(&wt, "HEAD").await?;
7556        drop(coordination);
7557        self.state.event(
7558            "recovery",
7559            match &failed {
7560                Some(why) => format!("repair: nothing kept ({why})"),
7561                None if after != head => {
7562                    format!("repair: committed {}", short(&after))
7563                }
7564                None => "repair: the fixer made no commit".to_owned(),
7565            },
7566        );
7567        rec.repair = Repair::Done {
7568            before: head.clone(),
7569            committed: after != head,
7570            after,
7571            failed,
7572        };
7573        self.state.recovery = Some(rec);
7574        self.state.save()?;
7575        Ok(())
7576    }
7577
7578    /// A repair whose rollback could not be confirmed: the run is blocked and
7579    /// resumable, and the unconfirmed state is never reviewed.
7580    async fn stop_recovery(
7581        &mut self,
7582        mut rec: crate::recovery::RecoveryRecord,
7583        head: &str,
7584        why: String,
7585    ) -> Result<()> {
7586        // `Started` stays recorded: a resume retries the restore.
7587        rec.repair = crate::recovery::Repair::Started {
7588            before: head.to_owned(),
7589        };
7590        self.state.recovery = Some(rec);
7591        self.state
7592            .event("recovery", format!("repair could not be undone: {why}"));
7593        self.state.status = RunStatus::Blocked;
7594        self.state.save()?;
7595        bail!("recovery repair could not be rolled back: {why}")
7596    }
7597
7598    async fn review_loop(&mut self) -> Result<()> {
7599        if self.hold_base_sync().await? {
7600            return Ok(());
7601        }
7602        loop {
7603            if self
7604                .state
7605                .base_sync
7606                .as_ref()
7607                .is_some_and(|s| s.conflict.is_some())
7608            {
7609                return Ok(());
7610            }
7611            if self.catchup_repairable() {
7612                let record = self.state.reviews.last().expect("repairable round").clone();
7613                let winner = self
7614                    .state
7615                    .winner()
7616                    .cloned()
7617                    .context("catch-up repair has no winner")?;
7618                if !self.fix_review_round(&winner, record).await? {
7619                    return Ok(());
7620                }
7621            }
7622            self.review_loop_pass().await?;
7623            if !self.catchup_repairable() {
7624                return Ok(());
7625            }
7626        }
7627    }
7628
7629    /// Derive an owed catch-up repair from durable round evidence, including
7630    /// reentry after a crash before the fixer was dispatched.
7631    fn catchup_repairable(&self) -> bool {
7632        self.state.reviews.len() < self.state.config.graph.review_rounds
7633            && self.state.reviews.last().is_some_and(|r| {
7634                !r.clean
7635                    && r.blocking == 0
7636                    && r.fix.is_none()
7637                    && r.e2e_status() == E2eStatus::Failed
7638            })
7639    }
7640
7641    async fn review_loop_pass(&mut self) -> Result<()> {
7642        // A base that would not rebase is a person's decision, not a review
7643        // round: nothing here would change the answer, and reviewers and a
7644        // fixer would be spending real budget on a tree that cannot land
7645        // regardless of what they find.
7646        if self
7647            .state
7648            .base_sync
7649            .as_ref()
7650            .is_some_and(|s| s.conflict.is_some())
7651        {
7652            return Ok(());
7653        }
7654        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7655        // agent files with `magi task add` name the run that paid for it. The
7656        // prompt overlay is cloned alongside it because the waves borrow it
7657        // while `self` is mutably borrowed by the node's own bookkeeping.
7658        let run_id = self.state.id.clone();
7659        let prompts = self.state.config.prompts.clone();
7660        let Some(winner) = self.state.winner().cloned() else {
7661            return Ok(());
7662        };
7663        let granted_review = self
7664            .state
7665            .repair_grants
7666            .last()
7667            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7668            .cloned();
7669        let fresh_review = granted_review
7670            .as_ref()
7671            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7672        let max_rounds = granted_review
7673            .as_ref()
7674            .map_or(self.state.config.graph.review_rounds, |g| {
7675                g.review_start.saturating_add(1)
7676            });
7677        // A clean round, an exhausted round budget, or a stalled tree (see
7678        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7679        // they are recorded — recomputed here, not read off `status`, so a
7680        // reentry into a run that already stopped restates the identical
7681        // verdict instead of silently handing back whatever an earlier node
7682        // in this same walk clobbered `status` to (a solo-candidate
7683        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7684        // below runs an empty range once the budget is spent, and would
7685        // otherwise fall through without touching `status` at all.
7686        if let Some(status) =
7687            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7688        {
7689            // A reentry after a crash between the last round's save and
7690            // `stop_reviewing` reaches the hand-off here, not there.
7691            if status == RunStatus::Gating {
7692                self.record_contested_handoff();
7693            }
7694            self.state.status = status;
7695            self.state.save()?;
7696            return Ok(());
7697        }
7698        self.state.status = RunStatus::Reviewing;
7699        // A last recorded round whose own verification never resolved
7700        // (`ResourceBlocked` — the shared build cache, not the patch) is
7701        // never a concluded round, whatever the round budget says: starting
7702        // a fresh round on top of it would spend a whole new reviewer wave
7703        // re-reading an unchanged patch instead of just retrying the one
7704        // check that actually needs it, and once the budget is spent the
7705        // loop below has nothing left to do at all (its range is empty).
7706        // Retry that check directly instead, exactly the same retry
7707        // `stop_reviewing` already does for its own catch-up case.
7708        if !fresh_review
7709            && self.state.reviews.last().is_some_and(|r| {
7710                r.e2e_status() == E2eStatus::ResourceBlocked
7711                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7712            })
7713        {
7714            let shell = self.state.config.shell();
7715            return self
7716                .stop_unresolved_review(
7717                    "the last round's own verification never resolved",
7718                    &shell,
7719                    &winner.worktree,
7720                )
7721                .await;
7722        }
7723
7724        if granted_review.is_none() {
7725            self.recovery_repair(&winner).await?;
7726        }
7727        if self.resource_halt()? {
7728            return Ok(());
7729        }
7730
7731        let repo = self.state.repo.clone();
7732        let root = self.state.worktree_root();
7733        let language = self.state.config.graph.language.clone();
7734        let sessions = self.state.config.graph.sessions;
7735        let artifacts = self.merge_repair_artifacts();
7736        let base = self.landing_base();
7737        let base_short = short(&base);
7738        let reviewers = self.roles.reviewers.clone();
7739        let shell = self.state.config.shell();
7740
7741        for round in (self.state.reviews.len() + 1)..=max_rounds {
7742            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7743            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7744            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7745            // The prior round's own record, already persisted — never a
7746            // hand-carried variable of just its failing output: that is
7747            // exactly what let a round's e2e result drift out of sync with
7748            // which commit it was actually about (see `SCHEMA`'s doc for
7749            // schema 8). Judged against `head`, the commit reviewers are
7750            // about to look at now, so the summary always reads as "an
7751            // earlier head" here — this round's own patch has not been
7752            // checked yet.
7753            let prev_verification = self
7754                .state
7755                .reviews
7756                .last()
7757                .and_then(|r| r.verification_summary(&head));
7758            // Only the first round of a run that took a branch over: later
7759            // rounds have this run's own history.
7760            let prior_section = match (&self.state.recovery, round) {
7761                (Some(rec), 1) if self.state.reviews.is_empty() => {
7762                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7763                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7764                            Some(crate::recovery::head_of(
7765                                &git::diff(&winner.worktree, reviewed, "HEAD")
7766                                    .await
7767                                    .unwrap_or_default(),
7768                                crate::recovery::SINCE_DIFF_MAX,
7769                            ))
7770                        }
7771                        _ => None,
7772                    };
7773                    Some(prompt::recovery_review(rec, since.as_deref()))
7774                }
7775                _ => None,
7776            };
7777
7778            // Each reviewer gets its own detached checkout of exactly this
7779            // commit: nobody can perturb the winner's tree, and the fixer can
7780            // keep working without racing a reviewer.
7781            let mut jobs = Vec::new();
7782            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7783                self.coordinate(&repo).await?
7784            } else {
7785                None
7786            };
7787            for (r, spec) in reviewers.iter().cloned().enumerate() {
7788                let wt = root.join(format!("review-{}", r + 1));
7789                // `clean -fdx` in a reset wipes setup's products, so every
7790                // round sets the seat up again.
7791                if wt.exists() {
7792                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7793                } else {
7794                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7795                        None
7796                    } else {
7797                        self.coordinate(&repo).await?
7798                    };
7799                    git::worktree_add_detached(&repo, &wt, &head).await?;
7800                }
7801                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7802                    None
7803                } else {
7804                    self.coordinate(&repo).await?
7805                };
7806                self.setup_seat_worktree(
7807                    &repo,
7808                    &wt,
7809                    false,
7810                    coordination.as_ref().or(_setup_lease.as_ref()),
7811                )
7812                .await?;
7813                let seat_key = format!("review-{}", r + 1);
7814                // The seat starts the round on whoever answered it last, not
7815                // on the agent the spec names, so a failure is not re-paid.
7816                let spec = pick_start_spec(
7817                    &self.roles.reviewer_roster,
7818                    spec,
7819                    self.state.seat_history.get(&seat_key),
7820                );
7821                let seat = self.seat(&seat_key, &spec.id);
7822                jobs.push(SeatJob {
7823                    prompt: prompt::review(&prompt::ReviewCtx {
7824                        instruction: &self.state.instruction,
7825                        branch: &winner.branch,
7826                        base_short: &base_short,
7827                        stat: &stat,
7828                        patch: &patch,
7829                        verification: prev_verification.as_ref(),
7830                        prior: prior_section.as_deref(),
7831                        reviewers: reviewers.len(),
7832                        round,
7833                        rounds: max_rounds,
7834                        // A review-only run has no rankings, so nothing
7835                        // competed for this patch and the reviewer is told so.
7836                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7837                        lens: Lens::for_seat(r),
7838                        language: &language,
7839                        github_language: &self.state.config.graph.github_language,
7840                    }),
7841                    spec,
7842                    seat,
7843                    cwd: wt,
7844                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7845                    allow_write: false,
7846                    sessions,
7847                    artifacts: artifacts.clone(),
7848                    stem: format!("review-{round}-{}", r + 1),
7849                    handover: None,
7850                });
7851            }
7852
7853            drop(coordination);
7854            self.state.event(
7855                "review",
7856                format!(
7857                    "round {round}: {} reviewers on {}",
7858                    jobs.len(),
7859                    short(&head)
7860                ),
7861            );
7862            let mut quota_losses = Vec::new();
7863            let review_retries = self.state.config.graph.retries;
7864            let review_cache = self.state.config.cache_dir();
7865            let ctx = WaveCtx {
7866                carry_seats: true,
7867                pauses: Some((&self.pause, &self.interrupt)),
7868                run: &run_id,
7869                node: "review",
7870                prompts: &prompts,
7871                cache: review_cache.as_deref(),
7872                round: Some(round),
7873            };
7874            let results = ask_json_wave::<Review>(
7875                jobs,
7876                Arc::clone(&self.sem),
7877                review_retries,
7878                &self.roles.reviewer_roster,
7879                &ctx,
7880                &mut quota_losses,
7881                &mut self.state,
7882                &|_: &Review| Ok(()),
7883            )
7884            .await;
7885            if self.state.resource_block.is_some() {
7886                return self.stop_for_resource();
7887            }
7888            // Counted before the move below: how many of *this* round's
7889            // reviewer seats were lost to their own rate limit, as opposed to
7890            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7891            let round_quota_missing = quota_losses.len();
7892            self.state.quota.extend(quota_losses);
7893
7894            let mut records = Vec::new();
7895            let mut all_findings = Vec::new();
7896            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7897                let agent_id = seat.agent.clone();
7898                self.state.seats.insert(seat.key.clone(), seat);
7899                let mut record = ReviewRecord {
7900                    reviewer: r + 1,
7901                    agent: agent_id,
7902                    summary: String::new(),
7903                    findings: Vec::new(),
7904                    vote: None,
7905                    failed: None,
7906                    duration_ms: 0,
7907                    // Set for both outcomes: `failed: Some(_)` with
7908                    // `attempts > 0` is a seat every retry still lost, not a
7909                    // recovered one — only `failed: None` with `attempts > 0`
7910                    // reads as "answered after a nudge" (see this field's own
7911                    // doc).
7912                    attempts,
7913                };
7914                match res {
7915                    Ok((review, out)) => {
7916                        // Sanitized here, at the point every other piece of
7917                        // agent prose in this file is (candidate summaries,
7918                        // deliberation turns, vote reasons): a reviewer's own
7919                        // words are the one thing about it that could name
7920                        // it, and reconsideration below broadcasts this same
7921                        // summary and these same findings to every other
7922                        // seat on the panel.
7923                        record.summary =
7924                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7925                        record.vote = Some(review.vote);
7926                        record.duration_ms = out.duration_ms;
7927                        for (n, mut f) in review.findings.into_iter().enumerate() {
7928                            // ids are magi's, never the agent's: the fixer's
7929                            // adoption report is keyed by them.
7930                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7931                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7932                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7933                            // `file` is agent-supplied prose too, never
7934                            // checked against the real tree — the same
7935                            // exposure `title`/`detail` above have, just in
7936                            // a field easy to forget because it looks like a
7937                            // path rather than free text.
7938                            f.file = f
7939                                .file
7940                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7941                            all_findings.push(f.clone());
7942                            record.findings.push(f);
7943                        }
7944                        self.state.event(
7945                            "review",
7946                            format!(
7947                                "round {round}: reviewer {} voted {} with {} finding(s)",
7948                                r + 1,
7949                                review.vote.label(),
7950                                record.findings.len()
7951                            ),
7952                        );
7953                    }
7954                    Err(e) => {
7955                        record.failed = Some(e.to_string());
7956                        self.state.event(
7957                            "review",
7958                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7959                        );
7960                    }
7961                }
7962                records.push(record);
7963            }
7964
7965            // Tally the round's votes and, if they split, spend the one
7966            // round of reconsideration the split -> deliberate -> revote
7967            // shape `judge`/`vote` use for the panel, sized down to what a
7968            // read-only review round can afford: one round, and a revote
7969            // rather than an argument, because the panel already wrote its
7970            // reasoning down as findings the first time around.
7971            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7972            let vote_split =
7973                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7974            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7975            if vote_split {
7976                self.state.event(
7977                    "review",
7978                    format!(
7979                        "round {round}: votes split ({}) — one round of reconsideration",
7980                        initial_votes
7981                            .iter()
7982                            .map(|v| v.label())
7983                            .collect::<Vec<_>>()
7984                            .join(", ")
7985                    ),
7986                );
7987                // Seats read every seat's findings and votes, still numbered
7988                // and never named — the same anonymity `review` itself keeps.
7989                let panel: Vec<ReviewSeatReport<'_>> = records
7990                    .iter()
7991                    .filter_map(|r| {
7992                        r.vote.map(|vote| ReviewSeatReport {
7993                            reviewer: r.reviewer,
7994                            vote,
7995                            summary: &r.summary,
7996                            findings: &r.findings,
7997                        })
7998                    })
7999                    .collect();
8000
8001                let mut jobs = Vec::new();
8002                let mut seats_at = Vec::new();
8003                for (r, spec) in reviewers.iter().cloned().enumerate() {
8004                    // A seat with no initial vote has nothing to reconsider
8005                    // from and stays absent, the same as it stayed absent
8006                    // from `panel` above.
8007                    if records[r].vote.is_none() {
8008                        continue;
8009                    }
8010                    let wt = root.join(format!("review-{}", r + 1));
8011                    let seat_key = format!("review-{}", r + 1);
8012                    let spec = self.occupant(&seat_key, spec);
8013                    let seat = self.seat(&seat_key, &spec.id);
8014                    // A seat with no live session has already forgotten the
8015                    // initial review's prompt — restate the patch it is
8016                    // voting on, the same as `deliberate`/`vote` do for a
8017                    // judge in the same position.
8018                    // The panel already carries this seat's own review and
8019                    // vote, so restating the patch makes the prompt whole for
8020                    // a seat handed to another agent.
8021                    let build = |with_patch: bool| {
8022                        prompt::review_reconsider(&ReviewReconsiderCtx {
8023                            instruction: &self.state.instruction,
8024                            reviewer: r + 1,
8025                            lens: Lens::for_seat(r),
8026                            panel: &panel,
8027                            patch: with_patch.then_some(ReviewPatch {
8028                                branch: &winner.branch,
8029                                base_short: &base_short,
8030                                stat: &stat,
8031                                patch: &patch,
8032                            }),
8033                            round,
8034                            rounds: max_rounds,
8035                            language: &language,
8036                        })
8037                    };
8038                    let full = build(true);
8039                    let prompt = if has_context(&spec, &seat, sessions) {
8040                        build(false)
8041                    } else {
8042                        full.clone()
8043                    };
8044                    jobs.push(SeatJob {
8045                        prompt,
8046                        spec,
8047                        seat,
8048                        cwd: wt,
8049                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8050                        allow_write: false,
8051                        sessions,
8052                        artifacts: artifacts.clone(),
8053                        stem: format!("review-{round}-reconsider-{}", r + 1),
8054                        handover: Some(full),
8055                    });
8056                    seats_at.push(r);
8057                }
8058
8059                let mut recon_quota_losses = Vec::new();
8060                let recon_cache = self.state.config.cache_dir();
8061                let recon_ctx = WaveCtx {
8062                    carry_seats: true,
8063                    pauses: Some((&self.pause, &self.interrupt)),
8064                    run: &run_id,
8065                    node: "review",
8066                    prompts: &prompts,
8067                    cache: recon_cache.as_deref(),
8068                    round: Some(round),
8069                };
8070                let recon_results = ask_json_wave::<ReviewRevote>(
8071                    jobs,
8072                    Arc::clone(&self.sem),
8073                    review_retries,
8074                    &self.roles.reviewer_roster,
8075                    &recon_ctx,
8076                    &mut recon_quota_losses,
8077                    &mut self.state,
8078                    &|_: &ReviewRevote| Ok(()),
8079                )
8080                .await;
8081                if self.state.resource_block.is_some() {
8082                    return self.stop_for_resource();
8083                }
8084                self.state.quota.extend(recon_quota_losses);
8085
8086                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
8087                    let agent_id = seat.agent.clone();
8088                    self.state.seats.insert(seat.key.clone(), seat);
8089                    let mut rec = ReviewRevoteRecord {
8090                        reviewer: r + 1,
8091                        agent: agent_id,
8092                        vote: None,
8093                        reason: String::new(),
8094                        failed: None,
8095                    };
8096                    match res {
8097                        Ok((rv, _)) => {
8098                            rec.vote = Some(rv.vote);
8099                            rec.reason =
8100                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
8101                            self.state.event(
8102                                "review",
8103                                format!(
8104                                    "round {round}: reviewer {} revoted {}",
8105                                    r + 1,
8106                                    rv.vote.label()
8107                                ),
8108                            );
8109                        }
8110                        Err(e) => {
8111                            rec.failed = Some(e.to_string());
8112                            self.state.event(
8113                                "review",
8114                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
8115                            );
8116                        }
8117                    }
8118                    reconsideration.push(rec);
8119                }
8120            } else if initial_votes.len() > 1 {
8121                self.state.event(
8122                    "review",
8123                    format!(
8124                        "round {round}: votes agreed ({}) — no reconsideration",
8125                        initial_votes[0].label()
8126                    ),
8127                );
8128            }
8129
8130            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
8131            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8132            // A round that already has a blocking finding and a round left to
8133            // try is going back to the fixer no matter what `verify.e2e`
8134            // says, so running it first only spends the loop's slowest step
8135            // (minutes, for a Rust repo's full test suite) on a head about
8136            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8137            // runs once a round has no blocking findings left (see
8138            // `round_is_clean`, which a deferred — empty — `e2e` can never
8139            // satisfy since `blocking` is nonzero whenever this branch is
8140            // taken), and `stop_reviewing` forces a real run before it will
8141            // ever read a deferred round as green.
8142            let defer_e2e =
8143                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8144            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8145                let reason =
8146                    format!("{blocking} blocking finding(s) already required a fix this round");
8147                self.state.event(
8148                    "verify",
8149                    format!(
8150                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8151                         {}); it will run once a round has none left",
8152                        short(&head)
8153                    ),
8154                );
8155                (Vec::new(), false, true, Some(reason))
8156            } else {
8157                let e2e_commands = self.state.config.verify.e2e.clone();
8158                let cache_dir = self.state.config.cache_dir();
8159                let context = format!("round {round}");
8160                let wait = self.repository_wait();
8161                let (e2e, verify_retried) = with_cache_lease(
8162                    &mut self.state,
8163                    cache_dir.as_deref(),
8164                    "e2e",
8165                    "e2e",
8166                    &winner.worktree,
8167                    &head,
8168                    verify_timeout,
8169                    &context,
8170                    &wait,
8171                    |state, budget| {
8172                        let shell = shell.clone();
8173                        let e2e_commands = e2e_commands.clone();
8174                        let worktree = winner.worktree.clone();
8175                        let context = context.clone();
8176                        let winner = winner.clone();
8177                        async move {
8178                            if !e2e_commands.is_empty() {
8179                                // The suite certifies one SHA. Format before it
8180                                // runs, or the commit `pre_gate` makes at the
8181                                // gate owes the whole suite again.
8182                                Self::run_pre_gate(state, &winner).await;
8183                            }
8184                            run_e2e_with_retry(
8185                                state,
8186                                &shell,
8187                                &e2e_commands,
8188                                &worktree,
8189                                budget,
8190                                &context,
8191                                Some(round),
8192                            )
8193                            .await
8194                        }
8195                    },
8196                )
8197                .await?;
8198                (e2e, verify_retried, false, None)
8199            };
8200
8201            let expected = records.len();
8202            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8203            let incomplete = answered < expected;
8204            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8205            let policy = self.state.config.graph.incomplete_review;
8206            let clean = round_is_clean(
8207                blocking,
8208                e2e_ok,
8209                answered,
8210                expected,
8211                round_quota_missing,
8212                policy,
8213            );
8214
8215            let mut round_record = ReviewRound {
8216                round,
8217                head: head.clone(),
8218                verified_head: None,
8219                verified_at: None,
8220                reviews: records,
8221                e2e,
8222                verify_retried,
8223                e2e_deferred,
8224                e2e_defer_reason,
8225                fix: None,
8226                blocking,
8227                answered,
8228                expected,
8229                clean,
8230                progressed: false,
8231                vote_split,
8232                reconsideration,
8233                verdict: None,
8234            };
8235            // The final vote per seat is its revote where reconsideration
8236            // ran and answered, its initial vote otherwise — the same
8237            // fallback `tally` uses for a judge whose private vote failed.
8238            round_record.verdict = ReviewVote::worst(
8239                round_record
8240                    .final_votes()
8241                    .into_iter()
8242                    .map(|(_, _, vote)| vote),
8243            );
8244            // Which commit and when magi actually attempted to check —
8245            // known the moment a command was dispatched against `head`,
8246            // whether or not it finished: a resource-blocked attempt still
8247            // targeted a specific commit at a specific time, and leaving
8248            // that unrecorded is exactly what made `verification_summary`
8249            // report a fresh attempt as "commit unknown ... recorded before
8250            // this was tracked", indistinguishable from a genuinely old,
8251            // untracked record. Only a deferred or unconfigured round never
8252            // ran at all and has nothing to record — see
8253            // `ReviewRound::verified_head`'s own doc.
8254            if !matches!(
8255                round_record.e2e_status(),
8256                E2eStatus::Deferred | E2eStatus::NotConfigured
8257            ) {
8258                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8259                // mechanical fixes before the commands ran.
8260                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8261                round_record.verified_at = Some(Timestamp::now());
8262            }
8263
8264            if incomplete {
8265                let missing: Vec<String> = round_record
8266                    .reviews
8267                    .iter()
8268                    .filter(|r| r.failed.is_some())
8269                    .map(|r| format!("review-{}", r.reviewer))
8270                    .collect();
8271                self.state.event(
8272                    "review",
8273                    format!(
8274                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8275                        missing.join(", ")
8276                    ),
8277                );
8278            }
8279
8280            if clean {
8281                self.state.event(
8282                    "review",
8283                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8284                        format!(
8285                            "round {round}: clean (warn policy, incomplete panel) — no \
8286                             blocking findings from the seats that answered, verification green"
8287                        )
8288                    } else if incomplete {
8289                        format!(
8290                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8291                             quorum) — no blocking findings from the seats that answered, \
8292                             verification green",
8293                            expected - answered
8294                        )
8295                    } else {
8296                        format!("round {round}: clean — no blocking findings, verification green")
8297                    },
8298                );
8299                self.state.reviews.push(round_record);
8300                self.state.status = RunStatus::Gating;
8301                self.state.save()?;
8302                return Ok(());
8303            }
8304
8305            // Nothing was raised and verification passed, but not every seat
8306            // answered and `round_is_clean` still refused to call it clean —
8307            // either a seat is missing for a reason other than its own quota
8308            // (a crash, a timeout, unparsable output — worth another try), or
8309            // every seat that could have answered lost its quota and nobody
8310            // is left to decide on: re-review rather than send the fixer
8311            // after a round with nothing to fix.
8312            if incomplete && blocking == 0 && e2e_ok {
8313                self.state.reviews.push(round_record);
8314                self.state.save()?;
8315                if round == max_rounds {
8316                    self.state.status = RunStatus::Blocked;
8317                    self.state.event(
8318                        "review",
8319                        format!(
8320                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8321                             refusing to call it clean",
8322                            expected - answered
8323                        ),
8324                    );
8325                    return Ok(());
8326                }
8327                continue;
8328            }
8329
8330            // Nothing for the fixer to act on (`blocking == 0`) and the only
8331            // reason this round is not clean is that magi itself never got
8332            // a command to run — the shared build cache, not the patch (see
8333            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8334            // the fixer would invite a change to appease contention that has
8335            // nothing to do with the diff, and would leave this attempt
8336            // sitting in the next round's prompt as if it were about an
8337            // earlier, superseded commit rather than what it actually is:
8338            // the same head, still waiting to be checked. Wait for it the
8339            // same way the final round's own contention is already handled,
8340            // whatever round this happens to be.
8341            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8342                self.state.reviews.push(round_record);
8343                return self
8344                    .stop_unresolved_review(
8345                        "the round's own verification could not run",
8346                        &shell,
8347                        &winner.worktree,
8348                    )
8349                    .await;
8350            }
8351
8352            if round == max_rounds {
8353                self.state.reviews.push(round_record);
8354                return self
8355                    .stop_reviewing(
8356                        &format!(
8357                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8358                        ),
8359                        &shell,
8360                        &winner.worktree,
8361                    )
8362                    .await;
8363            }
8364
8365            if !self.fix_review_round(&winner, round_record).await? {
8366                return Ok(());
8367            }
8368        }
8369        Ok(())
8370    }
8371
8372    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8373    /// False means admission or continuation policy stopped the review loop.
8374    async fn fix_review_round(
8375        &mut self,
8376        winner: &Candidate,
8377        mut round_record: ReviewRound,
8378    ) -> Result<bool> {
8379        let round = round_record.round;
8380        let shell = self.state.config.shell();
8381        let step = self.run_fix_round(winner, &mut round_record).await?;
8382        if matches!(step, FixStep::Resource) {
8383            self.stop_for_resource()?;
8384            return Ok(false);
8385        }
8386        if self.state.reviews.len() < round {
8387            self.state.reviews.push(round_record);
8388        } else {
8389            self.state.reviews[round - 1] = round_record;
8390        }
8391        self.state.save()?;
8392
8393        // The fixer's own report never came back this round, even after
8394        // `continue_fix_report`'s own budget was spent on it — not an
8395        // ordinary "no report" (dropped stream, quota, plain failure),
8396        // which already reads that way and is left to the existing round
8397        // budget. Stopping here, rather than opening another round, is
8398        // what keeps a next reviewer/fixer wave from ever being
8399        // dispatched onto `winner.worktree` while whatever the seat's
8400        // last call may still have running there is unaccounted for: no
8401        // process liveness check exists (and none is being added — see
8402        // AGENTS.md/this task's own scope), so the only way to honour
8403        // "nothing starts before a valid report returns" is to not start
8404        // anything further on this worktree from this run at all.
8405        if matches!(step, FixStep::Recorded { report_lost: true }) {
8406            self.stop_reviewing(
8407                "the fixer's adoption report never came back, even after resuming its \
8408                         own seat; refusing to start another round against the same worktree \
8409                         while that is unresolved",
8410                &shell,
8411                &winner.worktree,
8412            )
8413            .await?;
8414            return Ok(false);
8415        }
8416
8417        let streak = self
8418            .state
8419            .reviews
8420            .iter()
8421            .rev()
8422            .take_while(|r| !r.progressed)
8423            .count();
8424        if streak >= STAGNANT_LIMIT {
8425            self.stop_reviewing(
8426                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8427                &shell,
8428                &winner.worktree,
8429            )
8430            .await?;
8431            return Ok(false);
8432        }
8433        Ok(true)
8434    }
8435
8436    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8437    async fn run_fix_round(
8438        &mut self,
8439        winner: &Candidate,
8440        round_record: &mut ReviewRound,
8441    ) -> Result<FixStep> {
8442        let round = round_record.round;
8443        let max_rounds = self.state.config.graph.review_rounds;
8444        let run_id = self.state.id.clone();
8445        let prompts = self.state.config.prompts.clone();
8446        let language = self.state.config.graph.language.clone();
8447        let sessions = self.state.config.graph.sessions;
8448        let artifacts = self.merge_repair_artifacts();
8449        let base = self.landing_base();
8450        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8451        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8452        let this_round_verification = round_record.verification_summary(&head);
8453        let all_findings: Vec<_> = round_record
8454            .reviews
8455            .iter()
8456            .flat_map(|r| r.findings.iter().cloned())
8457            .collect();
8458        // Fix. The winner's own implementer seat continues its conversation:
8459        // the competition is over, so context is pure benefit now.
8460        let blocking_findings: Vec<_> = all_findings
8461            .iter()
8462            .filter(|f| f.severity.blocks())
8463            .cloned()
8464            .collect();
8465        let fix_prompt = prompt::fix_in(
8466            &self.state.instruction,
8467            &blocking_findings,
8468            this_round_verification.as_ref(),
8469            round,
8470            max_rounds,
8471            &language,
8472            &self.state.config.graph.github_language,
8473        );
8474        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8475        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8476        let (job, seat, out) = self
8477            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8478                prompt: fix_prompt.clone(),
8479                spec,
8480                seat,
8481                cwd: winner.worktree.clone(),
8482                timeout,
8483                allow_write: true,
8484                sessions,
8485                artifacts: artifacts.clone(),
8486                stem: format!("fix-{round}"),
8487                handover: None,
8488            })
8489            .await;
8490        // Not asked: the round is not recorded (so a resume repeats it),
8491        // no fixer was handed over to, and the seat is left as it was.
8492        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8493            return Ok(FixStep::Resource);
8494        }
8495        let agent_id = seat.agent.clone();
8496
8497        let mut fix = FixRecord {
8498            agent: agent_id,
8499            addressed: Vec::new(),
8500            rejected: Vec::new(),
8501            notes: String::new(),
8502            committed: false,
8503            failed: None,
8504            duration_ms: 0,
8505            continuation: None,
8506        };
8507        let mut continuation = ContinuationRecord::not_needed();
8508        let mut final_seat = seat.clone();
8509        match out {
8510            AgentOutcome::Ok(o) => {
8511                fix.duration_ms = o.duration_ms;
8512                let parsed = verdict::extract_json::<FixReport>(&o.text);
8513                // A parsed report standing next to a command this same
8514                // reply's own CLI never confirmed the exit status of is
8515                // not a resolved answer — the identical `CommandEvidence`
8516                // `state.jobs` renders, read here instead of only on
8517                // display, per the completion judgment and the shown
8518                // record needing to agree.
8519                let incomplete_reason = match &parsed {
8520                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8521                        "the reply parsed, but it reported a command whose own CLI never \
8522                             confirmed an exit status"
8523                            .to_owned(),
8524                    ),
8525                    Ok(_) => None,
8526                    Err(e) => Some(e.to_string()),
8527                };
8528                match incomplete_reason {
8529                    None => {
8530                        let report = parsed.expect("checked Ok above");
8531                        fix.addressed = report.addressed;
8532                        fix.rejected = report.rejected;
8533                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8534                    }
8535                    Some(reason) => {
8536                        let (resumed_seat, resolved, failure, cont) = self
8537                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8538                            .await;
8539                        fix.duration_ms += cont.cumulative_wait_ms;
8540                        continuation = cont;
8541                        final_seat = resumed_seat;
8542                        match resolved {
8543                            Some(report) => {
8544                                fix.addressed = report.addressed;
8545                                fix.rejected = report.rejected;
8546                                fix.notes =
8547                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8548                            }
8549                            None => fix.failed = failure,
8550                        }
8551                    }
8552                }
8553            }
8554            // The CLI's raw error JSON is not a fix report to parse.
8555            AgentOutcome::Dropped(o) => {
8556                fix.duration_ms = o.duration_ms;
8557                let why = o
8558                    .dropped
8559                    .as_ref()
8560                    .map(|d| d.why.as_str())
8561                    .unwrap_or("the CLI ended the stream without delivering its answer");
8562                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8563            }
8564            AgentOutcome::Quota(o) => {
8565                self.state.quota.push(QuotaLoss::from_report(
8566                    final_seat.key.clone(),
8567                    "fix",
8568                    o.quota.as_ref(),
8569                ));
8570                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8571            }
8572            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8573        }
8574        if self.state.resource_block.is_some() {
8575            self.state.seats.insert(final_seat.key.clone(), final_seat);
8576            return Ok(FixStep::Resource);
8577        }
8578        fix.continuation = Some(continuation);
8579        self.state.seats.insert(final_seat.key.clone(), final_seat);
8580        let coordination = self.coordinate(&winner.worktree).await?;
8581        if let Ok(r) = git::rescue_commit(
8582            &winner.worktree,
8583            &format!("magi: review round {round} fixes (uncommitted work)"),
8584        )
8585        .await
8586        {
8587            self.state.note_withheld("fix", &r.withheld);
8588        }
8589        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8590        fix.committed = after != before;
8591        // Judged by what `git` says moved against base, never by the
8592        // fixer's own `addressed`/`rejected` count — see
8593        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8594        // `patch` snapshot above: swallowing this error would default
8595        // `diff_after` to empty, which almost always differs from a
8596        // non-empty `patch` and reads as "progressed" — exactly backwards
8597        // for a `git` failure the stagnation check cannot see through.
8598        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8599        drop(coordination);
8600        let progressed = diff_after != patch;
8601        let commit_note = if fix.committed {
8602            "committed"
8603        } else {
8604            "NO new commit"
8605        };
8606        let tree_note = if progressed {
8607            "changed vs base"
8608        } else {
8609            "unchanged vs base"
8610        };
8611        self.state.event(
8612            "fix",
8613            match &fix.failed {
8614                // Distinct on purpose from "0 addressed, 0 rejected": the
8615                // fixer's own diff still landed (blocking counts do keep
8616                // falling round over round), only its adoption report did
8617                // not come back, so this must never read like every
8618                // finding was reviewed and declined.
8619                Some(reason) => {
8620                    format!(
8621                        "round {round}: fixer's adoption report was lost ({reason}); \
8622                             {commit_note}, tree {tree_note}"
8623                    )
8624                }
8625                None => format!(
8626                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8627                         {tree_note}{}",
8628                    fix.addressed.len(),
8629                    fix.rejected.len(),
8630                    if continuation.outcome == ContinuationOutcome::Resumed {
8631                        format!(
8632                            " (adoption report recovered after {} continuation(s))",
8633                            continuation.attempts
8634                        )
8635                    } else {
8636                        String::new()
8637                    },
8638                ),
8639            },
8640        );
8641        round_record.fix = Some(fix);
8642        round_record.progressed = progressed;
8643        Ok(FixStep::Recorded {
8644            report_lost: matches!(
8645                continuation.outcome,
8646                ContinuationOutcome::Exhausted
8647                    | ContinuationOutcome::QuotaLost
8648                    | ContinuationOutcome::NoSession
8649            ),
8650        })
8651    }
8652
8653    /// Decide, from the last recorded round's own verification, whether
8654    /// stopping the review loop is a hand-off or a genuine block.
8655    ///
8656    /// Called once the loop has given up trying — the round budget is spent,
8657    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8658    /// findings still open, never while a round is still clean or the
8659    /// incomplete-panel case handled inline above. Gate and e2e are facts
8660    /// about the tree; a lingering review finding is an opinion, and this
8661    /// workload's own `magi stats` puts reviewer precision low enough
8662    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8663    /// must not by itself stand between a green, verified change and the
8664    /// human who decides what to do with it. A red e2e is not an opinion, so
8665    /// that case still blocks, with the failing command and a tail of its
8666    /// output recorded here rather than left in `run.json` for someone to go
8667    /// find.
8668    ///
8669    /// A round that deferred its own e2e (see [`Config::graph`]'s
8670    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8671    /// only because nothing ran, and treating an empty list as a passing one
8672    /// here is exactly the "deferred painted green" bug this function exists
8673    /// to not have. When the last round's own verification never resolved —
8674    /// deferred on purpose, or a real attempt the shared build cache blocked
8675    /// — this makes (or retries) the real run, on the actual worktree this
8676    /// loop is about to stop touching, before deciding anything. A
8677    /// resource-blocked attempt is likewise never read as either green or
8678    /// red: it is evidence about the machine, not the patch (see
8679    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8680    /// blocked cache leaves this call without deciding rather than guessing
8681    /// — the caller retries on a later reentry.
8682    /// Record, once, that the review loop handed off over a blocking finding
8683    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8684    /// `land` asks the owner even with `land_approval` off. Called from every
8685    /// path that concludes `Gating`; a reentry keeps the first record.
8686    fn record_contested_handoff(&mut self) {
8687        if self.state.contested_handoff.is_some() {
8688            return;
8689        }
8690        let Some(contested) = self
8691            .state
8692            .reviews
8693            .last()
8694            .and_then(ReviewRound::contested_handoff)
8695        else {
8696            return;
8697        };
8698        self.state.event(
8699            "review",
8700            format!(
8701                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8702                 wait for the owner's approval",
8703                contested.findings.len(),
8704                contested.rejecters.len()
8705            ),
8706        );
8707        self.state.contested_handoff = Some(contested);
8708    }
8709
8710    async fn stop_unresolved_review(
8711        &mut self,
8712        why: &str,
8713        shell: &[String],
8714        worktree: &Path,
8715    ) -> Result<()> {
8716        self.stop_reviewing_inner(why, shell, worktree, true).await
8717    }
8718
8719    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8720        self.stop_reviewing_inner(why, shell, worktree, false).await
8721    }
8722
8723    async fn stop_reviewing_inner(
8724        &mut self,
8725        why: &str,
8726        shell: &[String],
8727        worktree: &Path,
8728        repairable: bool,
8729    ) -> Result<()> {
8730        let round_idx = self.state.reviews.len() - 1;
8731        // A deferred round and a resource-blocked one are the same shape
8732        // here: neither has a real result yet, and both get one more
8733        // attempt. Read off `e2e_status` — the single source for this —
8734        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8735        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8736        // still retries instead of being read as a settled result the
8737        // instant it stops being empty.
8738        let needs_catchup_run = matches!(
8739            self.state.reviews[round_idx].e2e_status(),
8740            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8741        );
8742        if needs_catchup_run {
8743            let round = self.state.reviews[round_idx].round;
8744            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8745            let commands = self.state.config.verify.e2e.clone();
8746            let before_head = git::rev_parse(worktree, "HEAD").await?;
8747            let winner = self.state.winner().cloned();
8748            let cache_dir = self.state.config.cache_dir();
8749            let context = format!(
8750                "round {round}: verification unresolved, catching up before the final decision"
8751            );
8752            let wait = self.repository_wait();
8753            let (outcomes, verify_retried) = with_cache_lease(
8754                &mut self.state,
8755                cache_dir.as_deref(),
8756                "e2e",
8757                "e2e",
8758                worktree,
8759                &before_head,
8760                timeout,
8761                &context,
8762                &wait,
8763                |state, budget| {
8764                    let shell = shell.to_vec();
8765                    let commands = commands.clone();
8766                    let context = context.clone();
8767                    async move {
8768                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8769                            // Same reason as in the round itself: format before
8770                            // the suite, not after it.
8771                            Self::run_pre_gate(state, &winner).await;
8772                        }
8773                        run_e2e_with_retry(
8774                            state,
8775                            &shell,
8776                            &commands,
8777                            worktree,
8778                            budget,
8779                            &context,
8780                            Some(round),
8781                        )
8782                        .await
8783                    }
8784                },
8785            )
8786            .await?;
8787            // After `pre_gate`: the commit the commands actually ran against.
8788            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8789            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8790                self.state.record_base_progress(&attempted_head);
8791            }
8792            let last = &mut self.state.reviews[round_idx];
8793            last.e2e = outcomes;
8794            last.verify_retried = verify_retried;
8795            // Always the commit and time this attempt actually targeted,
8796            // whether or not it happens to equal the reviewed `head` and
8797            // whether or not a command finished — see
8798            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8799            // attempt is recorded too, so a later reader sees "attempted
8800            // again at T2" rather than silence.
8801            last.verified_head = Some(attempted_head);
8802            last.verified_at = Some(Timestamp::now());
8803            if verify_inconclusive(&last.e2e) {
8804                // Still not a real result: `e2e_deferred` is left exactly
8805                // as it was, so `needs_catchup_run` above reads
8806                // `ResourceBlocked` (via `e2e_status`, which checks
8807                // `resource_blocked` before `e2e_deferred`) and retries
8808                // again on the next reentry, rather than recording
8809                // contention as a red e2e and blocking the run on it.
8810                self.state.save()?;
8811                return Ok(());
8812            }
8813            last.e2e_deferred = false;
8814            // A complete panel may have been saved as unclean solely because
8815            // verification could not run. Refresh that verdict with the new
8816            // outcomes before a granted repair consumes the round's result.
8817            // Incomplete panels retain their original policy/quota decision.
8818            if last.answered == last.expected {
8819                last.clean = round_is_clean(
8820                    last.blocking,
8821                    last.e2e.iter().all(CommandOutcome::ok),
8822                    last.answered,
8823                    last.expected,
8824                    0,
8825                    self.state.config.graph.incomplete_review,
8826                );
8827            }
8828        }
8829        let last = &self.state.reviews[round_idx];
8830        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8831
8832        match last.e2e_status() {
8833            E2eStatus::Failed => {
8834                let red: Vec<String> = last
8835                    .e2e
8836                    .iter()
8837                    .filter(|o| !o.ok())
8838                    .map(|o| {
8839                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8840                            .map(|c| format!(" ({c})"))
8841                            .unwrap_or_default();
8842                        format!(
8843                            "`{}` -> {:?}{comparison}\n{}",
8844                            o.command,
8845                            o.code,
8846                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8847                        )
8848                    })
8849                    .collect();
8850                let can_repair = last.blocking == 0 && last.fix.is_none();
8851                self.state.reviews[round_idx].clean = false;
8852                self.state
8853                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8854                self.state.status = RunStatus::Blocked;
8855                if repairable
8856                    && can_repair
8857                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8858                {
8859                    self.state.status = RunStatus::Reviewing;
8860                }
8861            }
8862            // `needs_catchup_run` above already retried once this call; if
8863            // it is still blocked, this is magi's own admission it could
8864            // not get a command to run, never a verdict on the patch — the
8865            // run is left exactly where a later reentry can retry again.
8866            E2eStatus::ResourceBlocked => {
8867                self.state.event(
8868                    "review",
8869                    format!(
8870                        "{why}; e2e could not run (resource unavailable); not \
8871                         deciding yet"
8872                    ),
8873                );
8874            }
8875            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8876                self.state.event(
8877                    "review",
8878                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8879                );
8880                self.record_contested_handoff();
8881                self.state.status = RunStatus::Gating;
8882            }
8883        }
8884        self.state.save()?;
8885        Ok(())
8886    }
8887
8888    // ----------------------------------------------------------------- gate
8889
8890    async fn gate(&mut self) -> Result<()> {
8891        if self.hold_base_sync().await? {
8892            return Ok(());
8893        }
8894        // Judged by the review record itself, not by `status`: a solo
8895        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8896        // reentry (see `judge`), and trusting it here is exactly how a run
8897        // that exhausted its review budget got gated and merged a second
8898        // time around. `review_conclusion` recomputes the review loop's own
8899        // verdict from the round records themselves — `Gating` for a clean
8900        // round or a hand-off (see `stop_reviewing`), anything else means the
8901        // loop is still going or genuinely blocked.
8902        // A base the winner could not be replayed onto is a decision, not a
8903        // round: there is no landing tree to gate. Read as its own record for
8904        // the same reason the review verdict is.
8905        if self.state.status == RunStatus::Failed
8906            || self
8907                .state
8908                .base_sync
8909                .as_ref()
8910                .is_some_and(|s| s.conflict.is_some())
8911            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8912                != Some(RunStatus::Gating)
8913        {
8914            return Ok(());
8915        }
8916        let Some(winner) = self.state.winner().cloned() else {
8917            return Ok(());
8918        };
8919        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8920        self.state.reconcile_verification_head(&head);
8921        self.state.save()?;
8922        let wait = self.repository_wait();
8923        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8924            return Ok(());
8925        }
8926        if self.state.gate_ran {
8927            // `review_loop` derives its conclusion from the clean review
8928            // record on every reentry and therefore puts a completed run back
8929            // in `Gating`. A recorded gate is a stronger, terminal fact:
8930            // retain its original command output (or lack of any, for a repo
8931            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8932            // doc) and restore `Blocked` on a real failure rather than
8933            // pretending the command is still running or running it a second
8934            // time. `gate_ran == false` remains the only shape — unattempted,
8935            // or a resource-blocked retry — that may still need to execute a
8936            // command.
8937            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8938                self.state.status = RunStatus::Blocked;
8939                self.state.save()?;
8940            }
8941            return Ok(());
8942        }
8943        self.state.status = RunStatus::Gating;
8944        let mut outcomes = self.run_gate(&winner).await?;
8945        let mut attempted_head = self.state.gate_head.clone();
8946        loop {
8947            // A resource-blocked outcome means the gate command never actually
8948            // ran - the shared build cache could not be acquired or confirmed
8949            // fresh in time - which is evidence about the machine, not about
8950            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8951            // Recording it as a red gate would mark a run `Blocked` on nothing
8952            // but contention magi has already logged; leaving `self.state.gate`
8953            // empty and `self.state.gate_ran` false instead keeps the shape
8954            // this function already treats as "still needs to run" (see the
8955            // early-return above), so the next call retries the command
8956            // rather than concluding anything.
8957            if verify_inconclusive(&outcomes) {
8958                self.state.save()?;
8959                return Ok(());
8960            }
8961            if outcomes.iter().all(CommandOutcome::ok) {
8962                break;
8963            }
8964            let fixes_before = self.state.gate_fixes.len();
8965            match self.gate_fix_round(&winner, &outcomes).await? {
8966                GateFix::Retry => {
8967                    outcomes = self.run_gate(&winner).await?;
8968                    attempted_head = self.state.gate_head.clone();
8969                }
8970                GateFix::Stop => {
8971                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8972                    if self.state.gate_fixes.len() > fixes_before
8973                        && attempted_head.as_deref() != Some(current.as_str())
8974                        && verify_current_head(&mut self.state, &winner, &wait).await?
8975                    {
8976                        // A new SHA owes a gate even when a spent fixer changed only
8977                        // commit metadata. This does not grant another repair round.
8978                        outcomes = self.run_gate(&winner).await?;
8979                        attempted_head = self.state.gate_head.clone();
8980                    } else {
8981                        break;
8982                    }
8983                }
8984                GateFix::Defer => {
8985                    self.state.save()?;
8986                    return Ok(());
8987                }
8988            }
8989        }
8990        let passed = outcomes.iter().all(CommandOutcome::ok);
8991        self.state.gate = outcomes;
8992        self.state.gate_ran = true;
8993        self.state.gate_head = attempted_head;
8994        if !self.state.gate.is_empty()
8995            && !verify_inconclusive(&self.state.gate)
8996            && let Some(head) = self.state.gate_head.clone()
8997        {
8998            self.state.record_base_progress(&head);
8999        }
9000        self.state.save()?;
9001        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9002            return Ok(());
9003        }
9004        if !passed {
9005            self.state.status = RunStatus::Blocked;
9006            let spent = self.state.gate_fixes.len();
9007            self.state.event(
9008                "gate",
9009                if spent == 0 {
9010                    "gate failed; not merging".to_owned()
9011                } else {
9012                    format!("gate failed after {spent} gate-fix round(s); not merging")
9013                },
9014            );
9015        }
9016        self.state.save()?;
9017        Ok(())
9018    }
9019
9020    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
9021    /// changed into one commit. Runs before `verify.e2e` in the review loop
9022    /// and again before the gate commands, always on the winner and never on
9023    /// a candidate awaiting judging.
9024    ///
9025    /// Before e2e as well as before the gate because command evidence belongs
9026    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
9027    /// commit e2e never saw, and the suite ran again for a formatter's diff -
9028    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
9029    /// own call then finds nothing left to change. The commands must be
9030    /// idempotent; one that is not makes a commit per call.
9031    ///
9032    /// Never fails the run: a non-zero exit or timeout is a warning and a
9033    /// recorded outcome, and the gate remains the single arbiter. Nothing
9034    /// configured means nothing happens - no event, no commit. `commit_all`
9035    /// commits any leftover change under the neutral identity and returns
9036    /// `false` when the tree is clean, so no empty commit is ever made.
9037    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
9038        let commands = state.config.verify.pre_gate.clone();
9039        if commands.is_empty() {
9040            return;
9041        }
9042        let shell = state.config.shell();
9043        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
9044        let (outcomes, _) = run_commands(
9045            state,
9046            "pre_gate",
9047            "pre_gate",
9048            0,
9049            &shell,
9050            &commands,
9051            &winner.worktree,
9052            timeout,
9053        )
9054        .await;
9055        for o in &outcomes {
9056            if !o.ok() {
9057                tracing::warn!(
9058                    "pre_gate `{}` failed ({:?}); the gate decides",
9059                    o.command,
9060                    o.code
9061                );
9062            }
9063            state.event(
9064                "pre_gate",
9065                format!(
9066                    "`{}` -> {}",
9067                    o.command,
9068                    if o.ok() {
9069                        "pass".to_owned()
9070                    } else {
9071                        format!(
9072                            "FAIL ({:?})\n{}",
9073                            o.code,
9074                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9075                        )
9076                    }
9077                ),
9078            );
9079        }
9080        state.pre_gate = outcomes;
9081        match git::commit_all(&winner.worktree, PRE_GATE_COMMIT_MESSAGE).await {
9082            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
9083                Ok(head) => {
9084                    state.event(PRE_GATE_EVENT_NODE, pre_gate_commit_event(&head));
9085                    state.pre_gate_commit = Some(head);
9086                }
9087                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
9088            },
9089            Ok(false) => {}
9090            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
9091        }
9092        if let Err(e) = state.save() {
9093            tracing::warn!("could not persist the pre_gate record: {e:#}");
9094        }
9095    }
9096
9097    /// Run `verify.gate` once against the winner's current tree, logging one
9098    /// event per command. Empty when nothing is configured.
9099    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
9100        let wait = self.repository_wait();
9101        run_landing_gate(&mut self.state, winner, &wait).await
9102    }
9103
9104    /// One bounded fix round for a failing gate.
9105    ///
9106    /// The fixer is told the failure came from the gate itself, not from a
9107    /// reviewer, and is shown the failed commands, their exit codes and a tail
9108    /// of their output - whatever `[verify].gate` holds, nothing here knows
9109    /// what those commands run. Only a normal non-zero exit that printed
9110    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
9111    /// command or a full disk says nothing about the code, and a fixer sent
9112    /// after it can only appease the machine. The round is judged by what git
9113    /// says moved, never by the fixer's own report, and `verify.e2e` runs
9114    /// again before the gate does, so a fix cannot trade a green gate for a
9115    /// red e2e unnoticed.
9116    async fn gate_fix_round(
9117        &mut self,
9118        winner: &Candidate,
9119        outcomes: &[CommandOutcome],
9120    ) -> Result<GateFix> {
9121        let cap = if self.state.repair_grants.last().is_some_and(|g| {
9122            g.phase == crate::repair_budget::Phase::Fixing
9123                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
9124        }) {
9125            self.state.gate_fixes.len().saturating_add(1)
9126        } else {
9127            self.state.config.graph.gate_fix_rounds
9128        };
9129        let spent = self.state.gate_fixes.len();
9130        if spent >= cap {
9131            if cap > 0 {
9132                self.state.event(
9133                    "gate",
9134                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
9135                );
9136            }
9137            return Ok(GateFix::Stop);
9138        }
9139        if !gate_fixable(outcomes) {
9140            self.state.event(
9141                "gate",
9142                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9143                 command or similar); not spending a fix round on it",
9144            );
9145            return Ok(GateFix::Stop);
9146        }
9147        let min_free = self.state.config.disk.min_free_bytes;
9148        if min_free > 0 {
9149            match crate::disk::free_bytes(&winner.worktree) {
9150                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9151                Ok(free) => {
9152                    self.state.event(
9153                        "gate",
9154                        format!(
9155                            "only {free} bytes free ({min_free} required by `[disk] \
9156                             min_free_bytes`); not spending a fix round on a failure the disk \
9157                             may explain"
9158                        ),
9159                    );
9160                    return Ok(GateFix::Stop);
9161                }
9162                Err(e) => {
9163                    self.state.event(
9164                        "gate",
9165                        format!("free disk space could not be measured ({e:#}); no fix round"),
9166                    );
9167                    return Ok(GateFix::Stop);
9168                }
9169            }
9170        }
9171
9172        let attempt = spent + 1;
9173        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9174        let base = self.landing_base();
9175        let fix_prompt = prompt::gate_fix_in(
9176            &self.state.instruction,
9177            &failed,
9178            attempt,
9179            cap,
9180            &self.state.config.graph.language,
9181            &self.state.config.graph.github_language,
9182        );
9183        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9184        let sessions = self.state.config.graph.sessions;
9185        let artifacts = self.merge_repair_artifacts();
9186        self.state.event(
9187            "gate",
9188            format!("gate failed; gate-fix round {attempt} of {cap}"),
9189        );
9190        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9191        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9192        // Persist before invoking the fixer: it may commit and then be
9193        // interrupted before its result (or the following e2e) is saved.
9194        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9195            before.clone(),
9196            false,
9197            Vec::new(),
9198        ));
9199        self.state.save()?;
9200        let (_, seat, out) = self
9201            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9202                prompt: fix_prompt.clone(),
9203                spec,
9204                seat,
9205                cwd: winner.worktree.clone(),
9206                timeout,
9207                allow_write: true,
9208                sessions,
9209                artifacts: artifacts.clone(),
9210                stem: format!("gate-fix-{attempt}"),
9211                handover: None,
9212            })
9213            .await;
9214        // The fixer was never asked: no round is spent (nothing is recorded)
9215        // and a later reentry asks the same agent again.
9216        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9217            return Ok(GateFix::Defer);
9218        }
9219        let mut record = GateFixRecord {
9220            agent: seat.agent.clone(),
9221            failed,
9222            notes: String::new(),
9223            committed: false,
9224            error: None,
9225        };
9226        match out {
9227            AgentOutcome::Ok(o) => {
9228                // A missing report is not a failed fix: the round is judged
9229                // by the tree below, and the report only carries prose.
9230                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9231                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9232                }
9233            }
9234            AgentOutcome::Dropped(_) => {
9235                record.error = Some("the CLI dropped the stream".to_owned());
9236            }
9237            AgentOutcome::Quota(o) => {
9238                self.state.quota.push(QuotaLoss::from_report(
9239                    seat.key.clone(),
9240                    "gate-fix",
9241                    o.quota.as_ref(),
9242                ));
9243                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9244            }
9245            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9246        }
9247        self.state.seats.insert(seat.key.clone(), seat);
9248        let coordination = self.coordinate(&winner.worktree).await?;
9249        if let Ok(r) = git::rescue_commit(
9250            &winner.worktree,
9251            &format!("magi: gate fix {attempt} (uncommitted work)"),
9252        )
9253        .await
9254        {
9255            self.state.note_withheld("gate-fix", &r.withheld);
9256        }
9257        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9258        record.committed = after != before;
9259        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9260        let note = record.error.clone();
9261        self.state.gate_fixes.push(record);
9262        self.state.save()?;
9263        if !changed {
9264            self.state.event(
9265                "gate",
9266                match note {
9267                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9268                    None => format!("gate-fix round {attempt}: the tree did not change"),
9269                },
9270            );
9271            return Ok(GateFix::Stop);
9272        }
9273        self.state.event(
9274            "gate",
9275            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9276        );
9277
9278        drop(coordination);
9279        let wait = self.repository_wait();
9280        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9281    }
9282
9283    // ---------------------------------------------------------------- merge
9284
9285    /// One read-only rewrite by the summary's author; a text the gate still
9286    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9287    /// applies on their word or on silence. `None` means the run is parked on
9288    /// that question and nothing may be pushed or opened yet.
9289    async fn guarded_pr_message(
9290        &mut self,
9291        winner: &Candidate,
9292        facts: Option<&BranchFacts>,
9293        posting: bool,
9294    ) -> Result<Option<PrMessage>> {
9295        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9296        let head = match final_head.as_deref() {
9297            Some(h) => crate::pr_outcome::FinalHead::At(h),
9298            None => crate::pr_outcome::FinalHead::Unknown,
9299        };
9300        // Only a pull request that is about to be posted pays for a summary.
9301        let summarized = if posting {
9302            Some(self.summarize_change(winner, final_head.as_deref()).await)
9303        } else {
9304            None
9305        };
9306        // A busy shared resource is not a permanent cause: publishing an
9307        // "unavailable" description would stick (a later head move never
9308        // edits the body). Stop before anything is pushed or opened; the
9309        // run is `Blocked` and a resume asks the summary again.
9310        if self.state.resource_block.is_some() {
9311            self.state.event(
9312                "pr-summary",
9313                "a shared resource was busy; nothing was published, resume to summarize again",
9314            );
9315            return Ok(None);
9316        }
9317        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9318            anyhow::bail!(
9319                "the final commit moved during public description generation; retry before publishing"
9320            );
9321        }
9322        let note = match (&summarized, &self.state.change_summary) {
9323            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9324            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9325            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9326            (None, _) => ChangeNote::NotAsked,
9327        };
9328        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9329        if !posting {
9330            let identity = crate::scrub::Identity::current();
9331            return Ok(Some(PrMessage {
9332                title: crate::scrub::scrub(&pr.title, &identity),
9333                body: crate::scrub::scrub(&pr.body, &identity),
9334            }));
9335        }
9336        // This very text was already rejected and asked about: no second
9337        // judge call, rewrite or question, just carry the record on.
9338        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9339        if let Some(known) = self
9340            .state
9341            .github_text
9342            .clone()
9343            .filter(|g| g.fingerprint == raw_fp)
9344        {
9345            return self.settle_withheld(winner, &pr, known).await;
9346        }
9347        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9348        let mut violations =
9349            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9350        let identity = crate::scrub::Identity::current();
9351        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9352            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9353            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9354        {
9355            violations.push(crate::github_text::Violation::SensitiveData);
9356        }
9357        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9358        // only a language violation starts one; sensitive data alone goes
9359        // straight to the owner, with the redacted text as the fallback.
9360        let has_language = violations
9361            .iter()
9362            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9363        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9364            self.state.event(
9365                "github-text",
9366                if has_language {
9367                    format!("description rejected: {violations:?}; requesting one rewrite")
9368                } else {
9369                    format!("description rejected: {violations:?}; asking the owner")
9370                },
9371            );
9372            let mut rewritten = false;
9373            let mut rejected_rewrite = None;
9374            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9375            {
9376                let output = text;
9377                if let Some(title) = summary_title(&output) {
9378                    // Judge the redacted candidate that will actually be posted.
9379                    // Sensitive data alone must not discard a useful rewrite.
9380                    let raw_body = summary_without_title(&output);
9381                    let clean_title = crate::scrub::scrub(&title, &identity);
9382                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9383                    let redacted = clean_title != title || body != raw_body;
9384                    let title = clean_title;
9385                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9386                    if !complete {
9387                        self.state.event(
9388                            "github-text",
9389                            "description rewrite omitted required findings",
9390                        );
9391                    }
9392                    if !body.trim().is_empty() {
9393                        body.push_str("\n\n");
9394                        body.push_str(&public_pr_evidence(&self.state, head));
9395                    }
9396                    let marker = format!("magi:run/{}", self.state.id);
9397                    if !body.trim().is_empty() && !body.contains(&marker) {
9398                        body.push_str(&format!("\n\n{marker}"));
9399                    }
9400                    let rewrite = PrMessage {
9401                        title: title.clone(),
9402                        body: body.clone(),
9403                    };
9404                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9405                    let mut failed = crate::github_text::check_for(
9406                        &self.state.config.graph,
9407                        &title,
9408                        &body,
9409                        redecision,
9410                    );
9411                    if (!crate::github_text::shareable(&title)
9412                        || !crate::github_text::shareable(&body))
9413                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9414                    {
9415                        failed.push(crate::github_text::Violation::SensitiveData);
9416                    }
9417                    if complete
9418                        && !title.trim().is_empty()
9419                        && !body.trim().is_empty()
9420                        && !failed.is_empty()
9421                    {
9422                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9423                            title: title.clone(),
9424                            body: body.clone(),
9425                            failed: failed
9426                                .iter()
9427                                .map(|v| crate::github_text::category(*v).to_owned())
9428                                .collect(),
9429                        });
9430                    }
9431                    if complete
9432                        && !title.trim().is_empty()
9433                        && !raw_body.trim().is_empty()
9434                        && failed.is_empty()
9435                    {
9436                        decision = redecision;
9437                        pr = PrMessage { title, body };
9438                        rewritten = true;
9439                        self.state
9440                            .event("github-text", "description rewrite passed");
9441                        if redacted {
9442                            self.state.event(
9443                                "github-text",
9444                                "sensitive data removed from description rewrite",
9445                            );
9446                        }
9447                    }
9448                }
9449            }
9450            if !rewritten {
9451                self.state.event(
9452                    "github-text",
9453                    "description rewrite unavailable or rejected; asking the owner",
9454                );
9455                if let Some(w) =
9456                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9457                {
9458                    // A different text than the one asked about before: that
9459                    // question no longer describes anything.
9460                    self.retire_github_text_question("the withheld text changed");
9461                    let record = crate::run::GithubTextAsk {
9462                        rewrite: rejected_rewrite,
9463                        fingerprint: raw_fp,
9464                        title: w.title,
9465                        body: w.body,
9466                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9467                        question: None,
9468                        asks: 0,
9469                        resolved: false,
9470                        chosen_title: None,
9471                        choice: None,
9472                        publication: None,
9473                    };
9474                    return self.settle_withheld(winner, &pr, record).await;
9475                }
9476            }
9477        }
9478        let (title, body) =
9479            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9480        Ok(Some(PrMessage { title, body }))
9481    }
9482
9483    /// Describe the whole change from its final diff in either run mode.
9484    ///
9485    /// The summary is tied to the final commit and to the merge base of the
9486    /// resolved remote base; a record for any other pair is dropped and the
9487    /// agent asked again, so a description never outlives the diff it was
9488    /// written from. The seat is read-only and the prompt tells it to read the
9489    /// diff and the code around it. `[roles] synthesizer` selects the agents
9490    /// (unset: the default pick), each asked at most once, advancing on an
9491    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9492    /// carries the reason it is unavailable; nothing is invented then.
9493    async fn summarize_change(
9494        &mut self,
9495        winner: &Candidate,
9496        head: Option<&str>,
9497    ) -> std::result::Result<(), String> {
9498        let Some(head) = head else {
9499            return Err("the final commit could not be read".to_owned());
9500        };
9501        let remote = self.state.config.merge.remote.clone();
9502        let tracking = format!("{remote}/{}", self.state.base_branch);
9503        if !git::rev_exists(&winner.worktree, &tracking).await {
9504            return Err(format!("the remote base `{tracking}` could not be read"));
9505        }
9506        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9507            Ok(b) if !b.is_empty() => b,
9508            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9509        };
9510        let evidence = crate::pr_outcome::summary_evidence(
9511            &self.state,
9512            crate::pr_outcome::FinalHead::At(head),
9513        );
9514        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9515        if self
9516            .state
9517            .change_summary
9518            .as_ref()
9519            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9520        {
9521            return Ok(());
9522        }
9523        if self.state.change_summary.take().is_some() {
9524            self.state.event(
9525                "pr-summary",
9526                "the final diff or evidence changed; the earlier change summary was discarded",
9527            );
9528        }
9529        // Save the source snapshot even if no generation agent is available.
9530        if let Err(e) = write_artifact(
9531            &self.state,
9532            &format!("public-description-{fingerprint}.md"),
9533            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9534        ) {
9535            tracing::warn!("could not save public description evidence: {e:#}");
9536        }
9537        let chain = match agent::pick_chain(
9538            &self.state.config.agents,
9539            self.state.config.roles.synthesizer.as_ref(),
9540            &agent::installed,
9541            "synthesizer",
9542        ) {
9543            Ok(chain) => chain,
9544            Err(e) => {
9545                tracing::warn!("no agent for the change summary: {e:#}");
9546                self.state.event("pr-summary", "no summary agent available");
9547                return Err("no agent was available to summarize it".to_owned());
9548            }
9549        };
9550        let subjects = git::subjects(&winner.worktree, &base, head)
9551            .await
9552            .unwrap_or_default();
9553        let stat = git::diff_stat(&winner.worktree, &base, head)
9554            .await
9555            .unwrap_or_default();
9556        let stat: String = stat.chars().take(6_000).collect();
9557        let mut prompt = crate::prompt::change_summary_in(
9558            &base,
9559            head,
9560            &subjects,
9561            stat.trim(),
9562            &self.state.config.graph.github_language,
9563        );
9564        prompt.push_str(&format!("\n\n# Final-state evidence\n{evidence}\n\nUse these records as evidence, not public text to copy. Paraphrase every open or declined finding and its reason in the requested GitHub language, retaining its exact ID and severity when available. Do not translate or quote internal operator reports. Explain unresolved risks for a reviewer without the task conversation. Historical sandbox or commit failures are not the final state. Verification is appended from these records; do not make additional validation claims."));
9565        let sessions = self.state.config.graph.sessions;
9566        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9567        let prompts = self.state.config.prompts.clone();
9568        let cache = self.state.config.cache_dir();
9569        let run = self.state.id.clone();
9570        for (i, spec) in chain.into_iter().enumerate() {
9571            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9572            let github_spec = match agent::for_github_text(
9573                &spec,
9574                &self.state.config.graph.github_language,
9575                &winner.worktree,
9576            ) {
9577                Ok(spec) => spec,
9578                Err(e) => {
9579                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9580                    continue;
9581                }
9582            };
9583            let job = SeatJob {
9584                spec: github_spec,
9585                seat,
9586                cwd: winner.worktree.clone(),
9587                prompt: prompt.clone(),
9588                timeout,
9589                allow_write: false,
9590                sessions,
9591                artifacts: agent::artifacts_dir(&self.state.dir()),
9592                stem: if i == 0 {
9593                    "change-summary".to_owned()
9594                } else {
9595                    format!("change-summary-{}", spec.id)
9596                },
9597                handover: None,
9598            };
9599            let ctx = WaveCtx {
9600                run: &run,
9601                node: "pr-summary",
9602                prompts: &prompts,
9603                cache: cache.as_deref(),
9604                round: None,
9605                carry_seats: false,
9606                pauses: Some((&self.pause, &self.interrupt)),
9607            };
9608            let (seat, outcome) =
9609                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9610            self.state.seats.insert(seat.key.clone(), seat);
9611            let text = match outcome {
9612                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9613                AgentOutcome::ResourceBlocked(why) => {
9614                    // No agent was asked: the run stops resumably before
9615                    // anything is published (see `guarded_pr_message`).
9616                    if self.state.resource_block.is_none() {
9617                        self.state.resource_block = Some(crate::run::ResourceBlock {
9618                            cause: crate::run::ResourceBlockCause::Other,
9619                            node: "pr-summary".to_owned(),
9620                            kind: "shared resource".to_owned(),
9621                            detail: why,
9622                            at: Timestamp::now(),
9623                        });
9624                    }
9625                    return Err("a shared resource was busy".to_owned());
9626                }
9627                _ => continue,
9628            };
9629            let blind = &self.state.config.blind;
9630            let Some(title) = summary_title(&text) else {
9631                continue;
9632            };
9633            let body: String = summary_without_title(&text)
9634                .lines()
9635                .filter(|l| !l.contains("magi:run/"))
9636                .collect::<Vec<_>>()
9637                .join("\n");
9638            let body = blind::sanitize_prose(body.trim(), blind);
9639            let title = blind::sanitize_prose(&title, blind);
9640            if body.trim().is_empty() || title.trim().is_empty() {
9641                continue;
9642            }
9643            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9644                continue;
9645            }
9646            // The branch must still be the one the agent was shown.
9647            if git::rev_parse(&winner.worktree, "HEAD")
9648                .await
9649                .ok()
9650                .as_deref()
9651                != Some(head)
9652            {
9653                return Err("the branch moved while the summary was written".to_owned());
9654            }
9655            if git::merge_base(&winner.worktree, &tracking, head)
9656                .await
9657                .ok()
9658                .as_deref()
9659                != Some(base.as_str())
9660                || crate::pr_outcome::summary_evidence(
9661                    &self.state,
9662                    crate::pr_outcome::FinalHead::At(head),
9663                ) != evidence
9664            {
9665                return Err("the summary evidence changed while it was written".to_owned());
9666            }
9667            self.state.change_summary = Some(crate::run::ChangeSummary {
9668                head: head.to_owned(),
9669                base,
9670                evidence: fingerprint,
9671                title,
9672                body,
9673            });
9674            self.state.event(
9675                "pr-summary",
9676                format!("change summary written by {} for the final diff", spec.id),
9677            );
9678            if let Err(e) = self.state.save() {
9679                tracing::warn!("could not save the change summary: {e:#}");
9680            }
9681            return Ok(());
9682        }
9683        self.state
9684            .event("pr-summary", "no agent produced a change summary");
9685        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9686    }
9687
9688    /// One read-only rewrite request for a withheld description. The
9689    /// implementer's own conversation is tried first when it exists and can be
9690    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9691    /// writes it in a separate conversation, skipping the implementer's agent.
9692    /// The prompt carries the whole text, so no agent needs any memory. Each
9693    /// agent is asked at most once and the chain advances on an error, quota,
9694    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9695    /// that has run out of quota must not end the rewrite. Nothing is recorded
9696    /// as a handover.
9697    async fn rewrite_pr_text(
9698        &mut self,
9699        winner: &Candidate,
9700        pr: &PrMessage,
9701        violations: &[crate::github_text::Violation],
9702    ) -> Option<String> {
9703        let prompt = format!(
9704            "Rewrite only the following pull request description into English. The posting gate reported {violations:?}. Keep every substantive detail (file names, commands, numbers, findings, code blocks and <details> sections) and translate the prose. Remove all machine or operator identifying data and secrets. Do not edit files or run commands. Return TITLE: followed by the title, then the rewritten description. Include an explanation of every open or declined finding with its exact ID. Omit the generated Review rounds, Final verification and Open review findings sections, the Evidence line and run markers: magi appends those from its records.\n\nTITLE: {}\n{}",
9705            pr.title, pr.body
9706        );
9707        let sessions = self.state.config.graph.sessions;
9708        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9709        // (spec, the resumed implementer's seat). A fallback seat is created
9710        // only when its turn comes, so an unused fallback leaves no record.
9711        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9712        let key = format!("impl-{}", winner.label);
9713        if let Some(spec) = self
9714            .state
9715            .config
9716            .agents
9717            .iter()
9718            .find(|a| a.id == winner.agent)
9719            .cloned()
9720            && let Some(existing) = self.state.seats.get(&key)
9721            && existing.agent == spec.id
9722            && agent::has_session(spec.kind, existing, sessions)
9723        {
9724            attempts.push((spec, Some(existing.clone())));
9725        }
9726        match agent::pick_chain(
9727            &self.state.config.agents,
9728            self.state.config.roles.language_judge.as_ref(),
9729            &agent::installed,
9730            "language_judge",
9731        ) {
9732            Ok(chain) => {
9733                for spec in chain {
9734                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9735                        continue;
9736                    }
9737                    attempts.push((spec, None));
9738                }
9739            }
9740            Err(e) if attempts.is_empty() => {
9741                tracing::warn!("no agent for the description rewrite: {e:#}");
9742                self.state
9743                    .event("github-text", "no rewrite agent available");
9744                return None;
9745            }
9746            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9747        }
9748        let prompts = self.state.config.prompts.clone();
9749        let cache = self.state.config.cache_dir();
9750        let run = self.state.id.clone();
9751        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9752            let resumed = resumed_seat.is_some();
9753            let seat = resumed_seat.unwrap_or_else(|| {
9754                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9755            });
9756            let github_spec = match agent::for_github_text(
9757                &spec,
9758                &self.state.config.graph.github_language,
9759                &winner.worktree,
9760            ) {
9761                Ok(spec) => spec,
9762                Err(e) => {
9763                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9764                    continue;
9765                }
9766            };
9767            let job = SeatJob {
9768                spec: github_spec,
9769                seat,
9770                cwd: winner.worktree.clone(),
9771                prompt: prompt.clone(),
9772                timeout: retry_budget(timeout_full, resumed),
9773                allow_write: false,
9774                sessions,
9775                artifacts: agent::artifacts_dir(&self.state.dir()),
9776                stem: if i == 0 {
9777                    "github-text-rewrite".to_owned()
9778                } else {
9779                    format!("github-text-rewrite-{}", spec.id)
9780                },
9781                handover: None,
9782            };
9783            let ctx = WaveCtx {
9784                run: &run,
9785                node: "github-text",
9786                prompts: &prompts,
9787                cache: cache.as_deref(),
9788                round: None,
9789                carry_seats: false,
9790                pauses: Some((&self.pause, &self.interrupt)),
9791            };
9792            let (seat, outcome) =
9793                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9794            self.state.seats.insert(seat.key.clone(), seat);
9795            match outcome {
9796                AgentOutcome::Ok(o)
9797                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9798                {
9799                    return Some(o.text);
9800                }
9801                AgentOutcome::ResourceBlocked(_) => return None,
9802                _ => {}
9803            }
9804        }
9805        None
9806    }
9807
9808    /// Abandon the standing posting-gate question, if any.
9809    fn retire_github_text_question(&mut self, why: &str) {
9810        let Some(id) = self
9811            .state
9812            .github_text
9813            .as_ref()
9814            .and_then(|g| g.question.clone())
9815        else {
9816            return;
9817        };
9818        let _ = ask::Questions::open().update(&id, |q| {
9819            q.abandon(why);
9820            Ok(())
9821        });
9822    }
9823
9824    /// Carry a withheld text to its end: file the question, park while it is
9825    /// open, and on an answer, silence or timeout pick the text to post. The
9826    /// decision is saved before it is used, so it applies once.
9827    async fn settle_withheld(
9828        &mut self,
9829        winner: &Candidate,
9830        pr: &PrMessage,
9831        mut g: crate::run::GithubTextAsk,
9832    ) -> Result<Option<PrMessage>> {
9833        use crate::github_text as gt;
9834        let store = ask::Questions::open();
9835        let timeout = self.state.config.graph.answer_timeout;
9836        if !g.resolved {
9837            let mut standing = g
9838                .question
9839                .as_ref()
9840                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9841            if let Some(q) = standing.as_ref()
9842                && q.status.open()
9843                && !store.held_reply(&q.id)
9844                && gt::expired(q, timeout)
9845            {
9846                let why = format!("no answer within {}s of asking", timeout.max(1));
9847                standing = store
9848                    .update(&q.id, |q| {
9849                        q.abandon(&why);
9850                        Ok(())
9851                    })
9852                    .ok()
9853                    .map(|(q, ())| q);
9854            }
9855            let mut ask_again: Option<Option<Vec<String>>> = None;
9856            match standing {
9857                // Recorded but never written (a stop between the two saves),
9858                // or removed: ask again without spending the retry.
9859                None if g.asks <= 1 => {
9860                    g.asks = 0;
9861                    ask_again = Some(None);
9862                }
9863                None => {
9864                    g.resolved = true;
9865                    g.chosen_title = None;
9866                    g.choice = Some(GithubTextChoice::Fallback);
9867                }
9868                Some(q) if q.status.open() => {
9869                    self.park_on_github_text(&g)?;
9870                    return Ok(None);
9871                }
9872                Some(q) => match gt::read_reply(&q) {
9873                    gt::Reply::Fallback => {
9874                        g.resolved = true;
9875                        g.chosen_title = None;
9876                        g.choice = Some(GithubTextChoice::Fallback);
9877                    }
9878                    gt::Reply::Original => {
9879                        g.resolved = true;
9880                        g.chosen_title = None;
9881                        g.choice = Some(GithubTextChoice::Original);
9882                    }
9883                    gt::Reply::Rewrite => {
9884                        g.resolved = true;
9885                        g.chosen_title = None;
9886                        g.choice = Some(if g.rewrite.is_some() {
9887                            GithubTextChoice::Rewrite
9888                        } else {
9889                            GithubTextChoice::Fallback
9890                        });
9891                    }
9892                    gt::Reply::Title(text) => {
9893                        let first = text
9894                            .lines()
9895                            .map(str::trim)
9896                            .find(|l| !l.is_empty())
9897                            .unwrap_or("");
9898                        let decision = if first.is_empty() {
9899                            None
9900                        } else {
9901                            let candidate = PrMessage {
9902                                title: first.to_owned(),
9903                                body: String::new(),
9904                            };
9905                            self.judge_pr_language(&winner.worktree, &candidate).await
9906                        };
9907                        match gt::vet_title(
9908                            &text,
9909                            decision,
9910                            self.state.config.graph.github_english(),
9911                        ) {
9912                            Ok(title) => {
9913                                g.resolved = true;
9914                                g.chosen_title = Some(title);
9915                                g.choice = Some(GithubTextChoice::MyTitle);
9916                            }
9917                            Err(cats) if g.asks < 2 => {
9918                                ask_again = Some(Some(
9919                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9920                                ))
9921                            }
9922                            Err(_) => {
9923                                g.resolved = true;
9924                                g.chosen_title = None;
9925                                g.choice = Some(GithubTextChoice::Fallback);
9926                            }
9927                        }
9928                    }
9929                },
9930            }
9931            if let Some(rejected) = ask_again {
9932                // A retry (after a rejected replacement title) is still about
9933                // the original text: the same ORIGINAL / FALLBACK comparison.
9934                let w = gt::Withheld {
9935                    title: g.title,
9936                    body: g.body,
9937                    categories: g.categories.clone(),
9938                };
9939                // Named by the original text's fingerprint alone, so a resume
9940                // rewrites the same file and the detail stays identical.
9941                let artifact = match crate::run::write_artifact(
9942                    &self.state,
9943                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9944                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9945                ) {
9946                    Ok(p) => Some(p),
9947                    Err(e) => {
9948                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9949                        None
9950                    }
9951                };
9952                let (detail, comparison) = gt::question_content(
9953                    &w,
9954                    &pr.title,
9955                    &pr.body,
9956                    &self.state.id,
9957                    rejected.as_deref(),
9958                    artifact.as_deref(),
9959                    g.rewrite.as_ref(),
9960                );
9961                let mut q = ask::Question::new(
9962                    self.state.id.clone(),
9963                    gt::ASK_NODE.to_owned(),
9964                    gt::ASK_SEAT.to_owned(),
9965                    gt::question_summary(&self.state.config.graph.language, &w),
9966                    detail,
9967                    gt::question_choices(&w, g.rewrite.as_ref()),
9968                );
9969                q.posting_comparison = Some(comparison);
9970                q.answer_timeout = timeout;
9971                // Recorded before it is written: a stop in between leaves a
9972                // record naming a question the resume then files again.
9973                g.question = Some(q.id.clone());
9974                g.asks += 1;
9975                self.state.github_text = Some(g.clone());
9976                self.state.event(
9977                    "github-text",
9978                    format!("asking the owner about the withheld text ({})", q.short()),
9979                );
9980                self.state.save()?;
9981                store
9982                    .put_executable(&mut q)
9983                    .context("file the posting-gate question")?;
9984                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9985                    tracing::warn!(
9986                        "could not notify about posting-gate question {}: {e:#}",
9987                        q.short()
9988                    );
9989                }
9990                self.park_on_github_text(&g)?;
9991                return Ok(None);
9992            }
9993        }
9994        let resolved = g.chosen_title.clone();
9995        let original = g.choice == Some(GithubTextChoice::Original);
9996        // Field names only: the event log never records the text.
9997        self.state.event(
9998            "github-text",
9999            if original {
10000                format!(
10001                    "posting the original text for: {}",
10002                    match (g.title, g.body) {
10003                        (true, true) => "title, description",
10004                        (true, false) => "title",
10005                        _ => "description",
10006                    }
10007                )
10008            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
10009                "posting the saved rewrite title and description".to_owned()
10010            } else if resolved.is_some() {
10011                "posting the owner's replacement title".to_owned()
10012            } else {
10013                "posting the neutral text for the withheld fields".to_owned()
10014            },
10015        );
10016        self.state.github_text = Some(g.clone());
10017        self.state.save()?;
10018        if g.choice == Some(GithubTextChoice::Rewrite)
10019            && let Some(r) = g.rewrite.as_ref()
10020        {
10021            return Ok(Some(PrMessage {
10022                title: r.title.clone(),
10023                body: r.body.clone(),
10024            }));
10025        }
10026        let w = gt::Withheld {
10027            title: g.title,
10028            body: g.body,
10029            categories: g.categories.clone(),
10030        };
10031        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
10032        if let Some(t) = resolved {
10033            title = t;
10034        }
10035        // Every withheld field is now neutral or vetted English.
10036        let english = gt::LanguageDecision {
10037            title_english: true,
10038            body_english: true,
10039            body_complete: true,
10040        };
10041        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
10042        if original {
10043            // The owner's explicit choice overrides the gate for the fields it
10044            // was made for; the others keep what the gate produced.
10045            if g.title {
10046                title = pr.title.clone();
10047            }
10048            if g.body {
10049                body = pr.body.clone();
10050            }
10051        }
10052        Ok(Some(PrMessage { title, body }))
10053    }
10054
10055    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
10056        self.state.github_text = Some(g.clone());
10057        self.state.end_pass_parked(ParkCause::Question);
10058        self.state.parked = true;
10059        self.state.event(
10060            "github-text",
10061            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
10062        );
10063        self.state.save()
10064    }
10065
10066    /// Ask `[roles] language_judge` about this text and record which source
10067    /// decided; the text itself is never recorded.
10068    async fn judge_pr_language(
10069        &mut self,
10070        cwd: &Path,
10071        pr: &PrMessage,
10072    ) -> Option<crate::github_text::LanguageDecision> {
10073        self.state.config.roles.language_judge.as_ref()?;
10074        if !self.state.config.graph.language_gate() {
10075            return None;
10076        }
10077        let decision =
10078            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
10079        self.state.event(
10080            "github-text",
10081            if decision.is_some() {
10082                "language decided by the language judge"
10083            } else {
10084                "language judge unavailable; using built-in heuristics"
10085            },
10086        );
10087        decision
10088    }
10089
10090    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10091        Box::pin(self.merge_inner())
10092    }
10093
10094    async fn merge_inner(&mut self) -> Result<()> {
10095        if self.resource_halt()? || self.hold_base_sync().await? {
10096            return Ok(());
10097        }
10098        // Same reasoning as `gate`: ask the review and gate records directly
10099        // rather than `status`, which a solo-candidate `judge`/`deliberate`
10100        // skip can rewrite on reentry to something that no longer says
10101        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
10102        // so a hand-off (open findings, green verification) reaches merge
10103        // exactly like a genuinely clean round does.
10104        //
10105        // A run resumed mid-`land` never reaches here at all: `execute`
10106        // recognises `RunStatus::Landing` before it even calls `prep`, and
10107        // routes straight to `run_land` instead. That has to happen a level
10108        // up from this function, not with a check in here, because
10109        // `review_loop`'s own status recomputation (see its doc) runs
10110        // *before* `merge` on every reentry and would otherwise overwrite
10111        // the `Landing` marker with `Gating` before this node ever saw it.
10112        if self
10113            .state
10114            .base_sync
10115            .as_ref()
10116            .is_some_and(|s| s.conflict.is_some())
10117            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10118                != Some(RunStatus::Gating)
10119            // `gate_ran == false` is not "passed" - `gate` leaves it false
10120            // both before it has ever run and when its last attempt was
10121            // resource-blocked (see `Runner::gate`'s own doc), and neither is
10122            // permission to merge on nothing but the review record. Only a
10123            // gate that actually ran may proceed; an intentional local
10124            // review can also finish with verification explicitly not configured.
10125            // `RunState::gate_status` computes that distinction.
10126            || !self.state.gate_allows_progress()
10127        {
10128            return Ok(());
10129        }
10130        // This node's own record, not `status`: `status == Ready` is not
10131        // unique to the harmless `MergeMode::None` path this line was
10132        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
10133        // run's PR was closed without merging — and on that run `mode` is
10134        // still `Pr`, so a reentry that fell through here would push and
10135        // open a second pull request. `self.state.merge` is set exactly once
10136        // this node (or `land`) has already produced a verdict, under every
10137        // mode, which is what "already done" actually means here.
10138        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10139            return Ok(());
10140        }
10141        let Some(winner) = self.state.winner().cloned() else {
10142            return Ok(());
10143        };
10144        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10145        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10146            self.state.status = RunStatus::Blocked;
10147            self.state.event(
10148                "gate",
10149                "winner changed after gate; fresh verification required",
10150            );
10151            self.state.save()?;
10152            return Ok(());
10153        }
10154        let wait = self.repository_wait();
10155        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10156            return Ok(());
10157        }
10158        let repo = self.state.repo.clone();
10159        let base = self.state.base_branch.clone();
10160        let mode = self.state.config.merge.mode;
10161        let style = self.state.config.merge.style;
10162        let facts = if is_review_run(&self.state) {
10163            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10164            let start = review_base(
10165                &repo,
10166                &self.state.config.merge.remote,
10167                &base,
10168                &self.state.base_commit,
10169                &winner.branch,
10170            )
10171            .await;
10172            branch_facts(&repo, &start, &winner.branch).await
10173        } else {
10174            None
10175        };
10176        // `None` when the base could not be freshly read: then an adopted
10177        // pull request's title is left alone.
10178        let leaked = if is_review_run(&self.state) {
10179            leaked_subjects(&self.state, &winner.branch).await
10180        } else {
10181            Some(Vec::new())
10182        };
10183        // `None`: parked on the owner's word about a withheld title or body.
10184        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10185        // the resume arrives here again.
10186        let Some(pr) = self
10187            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10188            .await?
10189        else {
10190            return Ok(());
10191        };
10192        let message = pr.commit_message();
10193
10194        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10195        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10196            return Ok(());
10197        }
10198        let outcome = match mode {
10199            MergeMode::None => MergeOutcome {
10200                mode,
10201                ok: true,
10202                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10203                empty: false,
10204            },
10205            MergeMode::Pr | MergeMode::Local
10206                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10207            {
10208                MergeOutcome {
10209                    mode,
10210                    ok: false,
10211                    detail: empty_candidate_detail(&self.state, &base),
10212                    empty: true,
10213                }
10214            }
10215            MergeMode::Local => {
10216                let on = git::current_branch(&repo).await?;
10217                if on.as_deref() != Some(base.as_str()) {
10218                    MergeOutcome {
10219                        mode,
10220                        ok: false,
10221                        detail: format!(
10222                            "{} has {} checked out, not the base branch {base}",
10223                            repo.display(),
10224                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10225                        ),
10226                        empty: false,
10227                    }
10228                } else if !git::is_clean(&repo).await? {
10229                    MergeOutcome {
10230                        mode,
10231                        ok: false,
10232                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10233                        empty: false,
10234                    }
10235                } else {
10236                    let out = match style {
10237                        MergeStyle::Merge => {
10238                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10239                        }
10240                        MergeStyle::Squash => {
10241                            git::merge_squash(&repo, &winner.branch, &message).await?
10242                        }
10243                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10244                    };
10245                    MergeOutcome {
10246                        mode,
10247                        ok: out.ok(),
10248                        detail: if out.ok() { out.stdout } else { out.stderr },
10249                        empty: false,
10250                    }
10251                }
10252            }
10253            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10254                self.state.pr_publication_pending = true;
10255                self.state.save()?;
10256                let out =
10257                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10258                self.state.pr_publication_pending = out.is_err();
10259                MergeOutcome {
10260                    mode,
10261                    ok: out.is_ok(),
10262                    detail: match out {
10263                        Ok(url) => url,
10264                        Err(e) => format!("{e:#}"),
10265                    },
10266                    empty: false,
10267                }
10268            }
10269            MergeMode::Pr => {
10270                let remote = self.state.config.merge.remote.clone();
10271                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10272                let pushed = if self.state.foreign_checkout.is_some() {
10273                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10274                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10275                } else {
10276                    git::push(&winner.worktree, &remote, &winner.branch).await?
10277                };
10278                if !pushed.ok() {
10279                    MergeOutcome {
10280                        mode,
10281                        ok: false,
10282                        detail: pushed.stderr,
10283                        empty: false,
10284                    }
10285                } else {
10286                    if self.state.foreign_checkout.is_some() {
10287                        self.state.pr_pushed_head = Some(delivery_head.clone());
10288                    }
10289                    // A retry or resume of a run whose branch already has an
10290                    // open pull request adopts it rather than failing on a
10291                    // duplicate. Only this winner branch into this base:
10292                    // `branch_for` derives the name from the run id, so a
10293                    // different run's pull request never matches.
10294                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10295                    let out = match pr_merge_plan(found) {
10296                        PrPlan::Create => {
10297                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10298                                .await
10299                        }
10300                        PrPlan::Adopt { url, title } => {
10301                            self.state
10302                                .event("merge", format!("Pr: adopted open pull request {url}"));
10303                            if self.state.explicit_github_text_selection() {
10304                                // An explicit publication selection applies the prepared
10305                                // payload; acceptance alone is not publication proof.
10306                                land::set_pr_text_verbatim(
10307                                    &winner.worktree,
10308                                    &url,
10309                                    &pr.title,
10310                                    &pr.body,
10311                                )
10312                                .await
10313                                .map(|()| url)
10314                            } else {
10315                                if title != pr.title
10316                                    && (!is_review_run(&self.state)
10317                                        || leaked
10318                                            .as_deref()
10319                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10320                                    && let Err(e) =
10321                                        if self.state.github_text.as_ref().is_some_and(|g| {
10322                                            g.resolved
10323                                                && g.title
10324                                                && g.choice == Some(GithubTextChoice::Original)
10325                                        }) {
10326                                            // The owner chose to post this title unmodified.
10327                                            land::set_pr_title_verbatim(
10328                                                &winner.worktree,
10329                                                &url,
10330                                                &pr.title,
10331                                            )
10332                                            .await
10333                                        } else {
10334                                            land::set_pr_title(
10335                                                &mut self.state,
10336                                                &winner.worktree,
10337                                                &url,
10338                                                &pr.title,
10339                                            )
10340                                            .await
10341                                        }
10342                                {
10343                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10344                                    self.state
10345                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10346                                }
10347                                Ok(url)
10348                            }
10349                        }
10350                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10351                    };
10352                    match out {
10353                        Ok(url) => MergeOutcome {
10354                            mode,
10355                            ok: true,
10356                            detail: url,
10357                            empty: false,
10358                        },
10359                        Err(e) => MergeOutcome {
10360                            mode,
10361                            ok: false,
10362                            detail: e.to_string(),
10363                            empty: false,
10364                        },
10365                    }
10366                }
10367            }
10368        };
10369
10370        self.state.status = match (mode, outcome.ok) {
10371            (MergeMode::None, _) => RunStatus::Ready,
10372            (_, true) if outcome.empty => RunStatus::Ready,
10373            (MergeMode::Pr, true) => RunStatus::Ready,
10374            (_, true) => RunStatus::Merged,
10375            (_, false) => RunStatus::Blocked,
10376        };
10377        self.state.event(
10378            "merge",
10379            format!(
10380                "{:?}: {}",
10381                mode,
10382                outcome.detail.lines().next().unwrap_or("")
10383            ),
10384        );
10385        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10386            self.state.record_github_text_publication(&outcome.detail);
10387        }
10388        self.state.merge = Some(outcome);
10389        self.state.save()?;
10390
10391        // The PR is open and the run would historically stop here, leaving the
10392        // operator to watch checks, feed review comments back to a fixer, and
10393        // merge. That was done by hand six times in one session before this
10394        // existed. Opt-in, because merging is the one irreversible thing magi
10395        // can do to a repository.
10396        if self.state.config.graph.land
10397            && mode == MergeMode::Pr
10398            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10399        {
10400            self.run_land().await?;
10401        }
10402        // `run_land` may have left `status` at `Landing` - still waiting on
10403        // CI or the owner's approval, not actually settled - so this has to
10404        // read whatever `status` ended up as here, not the `Merged` this
10405        // function set a few lines up.
10406        self.settle_questions();
10407        Ok(())
10408    }
10409
10410    /// Enter `land`.
10411    ///
10412    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10413    /// a resumed run's re-entry. `land::land` itself is what serialises the
10414    /// two git-mutating moments inside the loop — the rebase push and
10415    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10416    /// to hold a lock across the whole call, and doing so would serialise
10417    /// this run's CI wait against a *different* run's land-approval resume
10418    /// in the same repository, which is exactly the "must not wait on
10419    /// another task" property the daemon's slot-freeing exists to give.
10420    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10421        Box::pin(self.run_land_inner())
10422    }
10423
10424    async fn run_land_inner(&mut self) -> Result<()> {
10425        crate::pr_head::ensure_owner(&self.state)?;
10426        let url = self
10427            .state
10428            .pr
10429            .as_ref()
10430            .map(|pr| pr.url.clone())
10431            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10432            .unwrap_or_default();
10433        let url = url.lines().next().unwrap_or("").trim().to_owned();
10434        if !url.starts_with("http") {
10435            return Ok(());
10436        }
10437        // A land failure is not a lost run: the work is on a branch and the
10438        // pull request is open, which is exactly where a human takes over.
10439        loop {
10440            match land::land(&mut self.state, &url).await {
10441                Ok(_)
10442                    if self
10443                        .state
10444                        .merge_repairs
10445                        .last()
10446                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10447                {
10448                    if self.repair_merge_review().await? {
10449                        continue;
10450                    }
10451                }
10452                Ok(_) if self.state.resource_block.is_some() => {
10453                    return self.stop_for_resource();
10454                }
10455                Ok(pr) if self.state.parked => {
10456                    // `land` already saved the parked marker; nothing here
10457                    // overrides `status` back to a terminal value while an
10458                    // approval is still outstanding.
10459                    let _ = pr;
10460                }
10461                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10462                    self.state.status = RunStatus::Superseded;
10463                    self.state.save()?;
10464                }
10465                Ok(pr) => {
10466                    self.state.status = match pr.state {
10467                        land::PrLifecycle::Merged => RunStatus::Merged,
10468                        _ => RunStatus::Blocked,
10469                    };
10470                    // Downstream of a confirmed merge only - see
10471                    // `bump::should_release_bump`'s own doc for why this one
10472                    // check covers all three of `land`'s success paths.
10473                    // Best-effort: the run already landed, so a failure here
10474                    // (the decision call, `gh`, `cargo`) is recorded and never
10475                    // turns a landed run into a failed one.
10476                    if bump::should_release_bump(self.state.status)
10477                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10478                    {
10479                        // The event is the run's own record. Not-eligible cases
10480                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10481                        // `Err` is a bump that was tried and failed:
10482                        // `after_merge` itself raises the operator notice for
10483                        // that, whether or not a release PR exists yet.
10484                        self.state
10485                            .event("bump", format!("release bump skipped: {e:#}"));
10486                    }
10487                    // Independent of the bump, and best-effort in the same way:
10488                    // findings the merge left open become follow-up tasks.
10489                    if self.state.status == RunStatus::Merged {
10490                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10491                    }
10492                    self.state.save()?;
10493                }
10494                Err(e) => {
10495                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10496                        return Err(e);
10497                    }
10498                    self.state.status = RunStatus::Blocked;
10499                    self.state.event("land", format!("gave up: {e}"));
10500                    self.state.save()?;
10501                }
10502            }
10503            break;
10504        }
10505        Ok(())
10506    }
10507
10508    /// One repair cycle stays under the existing driver/task claim. An
10509    /// interrupted fixer is rolled back and held rather than run twice.
10510    async fn repair_merge_review(&mut self) -> Result<bool> {
10511        use crate::run::MergeRepairPhase as Phase;
10512        crate::pr_head::ensure_owner(&self.state)?;
10513        let i = self.state.merge_repairs.len() - 1;
10514        let request = self.state.merge_repairs[i].clone();
10515        if request.phase == Phase::Fixing {
10516            let restored = match self.state.winner().cloned() {
10517                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10518                None => Err(anyhow::anyhow!("repair has no winning branch")),
10519            };
10520            let why = match restored {
10521                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10522                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10523                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10524            };
10525            self.hold_merge_repair(i, why)?;
10526            return Ok(false);
10527        }
10528        // A completed repair gate is a publication checkpoint. On reentry,
10529        // reject external changes before the ordinary gate path can replace
10530        // that evidence by verifying a new head. Requested repairs still
10531        // start their own review generation below.
10532        if request.phase == Phase::Reviewing && self.state.gate_ran {
10533            let winner = self
10534                .state
10535                .winner()
10536                .context("repair has no winning branch")?;
10537            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10538            if self.state.gate_head.as_deref() != Some(head.as_str())
10539                || !git::is_clean(&winner.worktree).await?
10540            {
10541                self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10542                return Ok(false);
10543            }
10544        }
10545        let failure = if i >= self.state.config.graph.land_rounds
10546            || self.state.config.graph.review_rounds == 0
10547        {
10548            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10549        } else {
10550            None
10551        };
10552        if let Some(why) = failure {
10553            self.hold_merge_repair(i, why)?;
10554            return Ok(false);
10555        }
10556        if request.phase == Phase::Requested {
10557            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10558                Ok(pr) => pr,
10559                Err(e) => {
10560                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10561                    return Ok(false);
10562                }
10563            };
10564            self.state.merge_repairs[i].phase = Phase::Fixing;
10565            self.state.land_approval = None;
10566            self.state.land_armed_head = None;
10567            self.state.save()?;
10568            // Serialize the exact records, including finding ids/details,
10569            // reconsideration reasons, final votes and verification output.
10570            let evidence = serde_json::to_string_pretty(&request)?;
10571            let reason = format!(
10572                "The owner requested fix findings and re-review, without merging. Address the unresolved Major findings and final rejecting votes in this exact review evidence. Do not merge or approve the PR.\n\n{evidence}"
10573            );
10574            let budget = self.state.config.graph.land_rounds;
10575            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10576            match result {
10577                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10578                Ok(land::Fixed::Deferred) => {
10579                    // An unavailable fixer did not spend this repair request.
10580                    // Restore partial fallback work before retrying it, as for
10581                    // an interrupted repair, without closing the request.
10582                    let worktree = self
10583                        .state
10584                        .winner()
10585                        .context("repair has no winning branch")?
10586                        .worktree
10587                        .clone();
10588                    self.graft_restore(&worktree, &request.head).await?;
10589                    self.state.merge_repairs[i].phase = Phase::Requested;
10590                    self.stop_for_resource()?;
10591                    return Ok(false);
10592                }
10593                Ok(land::Fixed::Failed(why)) => {
10594                    self.hold_merge_repair(
10595                        i,
10596                        format!(
10597                            "repair failed: {why}; inspect the branch and run an explicit review"
10598                        ),
10599                    )?;
10600                    return Ok(false);
10601                }
10602                Err(e) => {
10603                    self.hold_merge_repair(
10604                        i,
10605                        format!(
10606                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10607                        ),
10608                    )?;
10609                    return Ok(false);
10610                }
10611            }
10612            // Even no change gets a real new reviewer wave. The previous
10613            // evidence remains in the request; a former clean/concluded round
10614            // cannot short-circuit the new review or gate.
10615            self.begin_merge_repair_review(i)?;
10616        }
10617        self.review_loop().await?;
10618        self.gate().await?;
10619        if self.resource_halt()? || self.state.parked {
10620            return Ok(false);
10621        }
10622        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10623            != Some(RunStatus::Gating)
10624            || !self.state.gate_allows_progress()
10625        {
10626            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10627            return Ok(false);
10628        }
10629        // Review and gate may have added commits after the initial repair.
10630        // Publish exactly their final head to the existing PR, with a lease.
10631        let winner = self
10632            .state
10633            .winner()
10634            .cloned()
10635            .context("repair has no winning branch")?;
10636        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10637        if self.state.gate_head.as_deref() != Some(after.as_str())
10638            || !git::is_clean(&winner.worktree).await?
10639        {
10640            self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10641            return Ok(false);
10642        }
10643        let expected = self
10644            .state
10645            .pr_pushed_head
10646            .as_deref()
10647            .unwrap_or(&request.head)
10648            .to_owned();
10649        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10650        // Push the checked commit itself: a local ref moving after the check
10651        // must not change which commit the forge receives.
10652        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10653            return Ok(false);
10654        }
10655        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10656        let refspec = format!("{after}:refs/heads/{public}");
10657        let push = git::git_raw(
10658            &winner.worktree,
10659            &["push", &lease, &self.state.config.merge.remote, &refspec],
10660        )
10661        .await;
10662        match push {
10663            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10664            Ok(out) => {
10665                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10666                return Ok(false);
10667            }
10668            Err(e) => {
10669                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10670                return Ok(false);
10671            }
10672        }
10673        self.state.merge_repairs[i].phase = Phase::Complete;
10674        self.state.status = RunStatus::Landing;
10675        self.state.event(
10676            "repair",
10677            "new review and gate completed; fresh owner merge decision required",
10678        );
10679        self.state.save()?;
10680        Ok(true)
10681    }
10682
10683    fn merge_repair_artifacts(&self) -> PathBuf {
10684        let artifacts = agent::artifacts_dir(&self.state.dir());
10685        match self
10686            .state
10687            .merge_repairs
10688            .last()
10689            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10690        {
10691            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10692            None => artifacts,
10693        }
10694    }
10695
10696    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10697        if let Some(e2e) = self.state.head_e2e.take() {
10698            self.state
10699                .verification_history
10700                .push(crate::run::VerificationEvidence {
10701                    superseded_by: None,
10702                    archived_at: Some(Timestamp::now()),
10703                    fixes_spent: Some(self.state.gate_fixes.len()),
10704                    gate_head: None,
10705                    gate_ran: false,
10706                    gate: Vec::new(),
10707                    e2e: Some(e2e),
10708                });
10709        }
10710        self.state.reviews.clear();
10711        self.state.gate.clear();
10712        self.state.gate_ran = false;
10713        self.state.gate_head = None;
10714        self.state.gate_fixes.clear();
10715        self.state.gate_repair_e2e = None;
10716        self.state.pre_gate.clear();
10717        self.state.pre_gate_commit = None;
10718        self.state.contested_handoff = None;
10719        self.state.land_reruns = None;
10720        self.state.land_approval = None;
10721        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10722        self.state.status = RunStatus::Reviewing;
10723        self.state.save()
10724    }
10725
10726    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10727        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10728        self.state.merge_repairs[index].failure = Some(why.clone());
10729        self.state.status = RunStatus::Blocked;
10730        self.state.event("repair", why);
10731        self.state.save()
10732    }
10733
10734    // -------------------------------------------------------------- helpers
10735
10736    /// Fetch or create a seat, keeping its conversation across nodes.
10737    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10738        if let Some(existing) = self.state.seats.get(key)
10739            && existing.agent == agent
10740        {
10741            return existing.clone();
10742        }
10743        // A seat that changes agent mints its session id from the agent too,
10744        // like a handover: the old agent's uuid is already taken by the CLI.
10745        let fresh = if self.state.seats.contains_key(key) {
10746            handover_seat(key, agent, self.state.next_seat_seed())
10747        } else {
10748            SeatState::new(key, agent, self.state.seed)
10749        };
10750        self.state.seats.insert(key.to_owned(), fresh.clone());
10751        fresh
10752    }
10753
10754    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10755    /// seat to another roster agent, in which case that agent. Nodes that
10756    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10757    /// reconsideration) must keep talking to whoever answered it, not slip
10758    /// back to the agent that failed it.
10759    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10760        match self.state.seats.get(key) {
10761            Some(s) if s.agent != spec.id => {
10762                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10763            }
10764            _ => spec,
10765        }
10766    }
10767
10768    /// A candidate rendered for judging, with the leak policy applied.
10769    fn view(&self, c: &Candidate) -> CandidateView {
10770        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10771            .unwrap_or_default();
10772        let (patch, _) = blind::sanitize_patch(
10773            &format!("candidate {} patch", c.label),
10774            &raw,
10775            &self.state.config.blind,
10776        );
10777        CandidateView {
10778            label: c.label,
10779            branch: c.branch.clone(),
10780            summary: c.summary.clone(),
10781            stat: c.stat.clone(),
10782            patch,
10783        }
10784    }
10785
10786    /// The full candidate set as prompt text, for seats with no live session.
10787    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10788        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10789        prompt::judge(
10790            "(see above)",
10791            &views,
10792            self.roles.judges.len(),
10793            base_short,
10794            "en",
10795        )
10796    }
10797
10798    /// The final-vote prompt with everything a seat that has no session of its
10799    /// own needs: the candidates, the seat's own ranking and reasons, and the
10800    /// anonymised deliberation it took part in (only when there was one, so a
10801    /// handed-over seat never sees more than the seat it replaces did). The
10802    /// `Final vote` heading stays first.
10803    fn vote_prompt_full(
10804        &self,
10805        j: usize,
10806        labels: &[char],
10807        language: &str,
10808        candidates: &[Candidate],
10809        base_short: &str,
10810    ) -> String {
10811        let mut text = format!(
10812            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10813            prompt::final_vote(labels, language),
10814            self.state.instruction,
10815            self.candidate_block(candidates, base_short)
10816        );
10817        if let Some(own) = self
10818            .state
10819            .judgements
10820            .get(j)
10821            .filter(|r| !r.ranking.is_empty())
10822        {
10823            let reasons = own
10824                .reasons
10825                .iter()
10826                .map(|(k, v)| format!("- {k}: {v}"))
10827                .collect::<Vec<_>>()
10828                .join("\n");
10829            text.push_str(&format!(
10830                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10831                own.ranking.iter().collect::<String>(),
10832                if reasons.is_empty() {
10833                    ""
10834                } else {
10835                    ", because:\n"
10836                }
10837            ));
10838        }
10839        if !self.state.deliberation.is_empty() {
10840            text.push_str("\n# What was argued before this vote\n");
10841            for t in self.transcript(&[], j) {
10842                text.push_str(&format!(
10843                    "\n## {}{}\n\n{}\n",
10844                    t.who,
10845                    if t.is_self { " (you)" } else { "" },
10846                    t.body.trim()
10847                ));
10848            }
10849        }
10850        text
10851    }
10852
10853    /// Anonymised transcript for judge `self_idx`.
10854    ///
10855    /// The initial rankings are always the opening statements. Seeding them
10856    /// only when no turn had been taken yet meant every judge after the first
10857    /// argued against a single voice instead of against the actual split — the
10858    /// disagreement is the information, so it is always on the table.
10859    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10860        let mut turns = Vec::new();
10861        for j in &self.state.judgements {
10862            if j.ranking.is_empty() {
10863                continue;
10864            }
10865            let reasons = j
10866                .reasons
10867                .iter()
10868                .map(|(k, v)| format!("- {k}: {v}"))
10869                .collect::<Vec<_>>()
10870                .join("\n");
10871            turns.push(Turn {
10872                who: format!("Judge {} (opening ranking)", j.judge),
10873                is_self: j.judge == self_idx + 1,
10874                body: format!(
10875                    "Ranked {}{}{reasons}",
10876                    j.ranking.iter().collect::<String>(),
10877                    if reasons.is_empty() {
10878                        ""
10879                    } else {
10880                        ", because:\n"
10881                    }
10882                ),
10883            });
10884        }
10885        for t in self
10886            .state
10887            .deliberation
10888            .iter()
10889            .flat_map(|r| r.turns.iter())
10890            .chain(current)
10891        {
10892            turns.push(Turn {
10893                who: format!("Judge {}", t.judge),
10894                is_self: t.judge == self_idx + 1,
10895                body: t.body.clone(),
10896            });
10897        }
10898        turns
10899    }
10900}
10901
10902/// Does this seat still hold the context a follow-up prompt would rely on?
10903fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10904    agent::has_session(spec.kind, seat, sessions)
10905}
10906
10907/// The next entry in `roster` after `start`, never wrapping back to the
10908/// front, whose id is not in `tried` yet.
10909///
10910/// Starts one past `start` rather than at the front of `roster`: `start` is
10911/// the seat's own original position, and a seat whose candidate slot already
10912/// sits on the roster's second entry must fall through to the third next, not
10913/// restart at the first — which is very likely a different candidate's own
10914/// agent already. Never wraps back past `start`, for the same reason: an
10915/// entry earlier in the roster than the seat's own position is almost
10916/// certainly some *other* candidate slot's own agent, and once the tail of
10917/// the roster is exhausted there are no more untried agents for *this* seat
10918/// to fall through to — the caller's fallback chain ends there, exactly as
10919/// "no further untried agents remain in the list for that seat" asks for.
10920///
10921/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10922/// the same id twice (an operator's `roles.implementers` typo, or a
10923/// `[[agents]]` list reused across roles) must not let
10924/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10925/// over `roster` either finds an untried id or runs out, so this always
10926/// terminates regardless of duplicates.
10927fn next_untried_in_roster<'a>(
10928    roster: &'a [AgentSpec],
10929    start: usize,
10930    tried: &BTreeSet<String>,
10931) -> Option<&'a AgentSpec> {
10932    roster
10933        .get(start + 1..)?
10934        .iter()
10935        .find(|s| !tried.contains(&s.id))
10936}
10937
10938/// The successor for a seat, shared by all four seat kinds (implement, judge,
10939/// review, advise). `others` holds the ids that *currently* occupy the other
10940/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10941/// sees them), so roster entries beyond the seat count act as spares: a failed
10942/// seat goes to an agent no other seat holds whenever the roster permits.
10943///
10944/// `carried` is `Some` only for the review loop's carried failure history.
10945/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10946/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10947/// whole roster: untried and not another seat's occupant; (3) the plain walk
10948/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10949/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10950/// a better outcome than an empty seat, and it keeps the answer to "is there
10951/// a successor at all" exactly what it was before occupants were considered,
10952/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10953/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10954/// carried failure is a cheaper bet than doubling an agent on the panel, and
10955/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10956/// the same round are handled one at a time, so a seat later in the batch
10957/// sees an earlier one's new occupant but not yet its own freed agent.
10958fn pick_successor<'a>(
10959    roster: &'a [AgentSpec],
10960    start: usize,
10961    tried: &BTreeSet<String>,
10962    carried: Option<&BTreeSet<String>>,
10963    others: &BTreeSet<String>,
10964) -> Option<&'a AgentSpec> {
10965    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10966    roster
10967        .get(start + 1..)
10968        .and_then(|tail| {
10969            tail.iter()
10970                .filter(free)
10971                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10972        })
10973        .or_else(|| {
10974            carried
10975                .is_some()
10976                .then(|| roster.iter().find(free))
10977                .flatten()
10978        })
10979        .or_else(|| match carried {
10980            Some(c) => next_for_seat(roster, start, tried, c),
10981            None => next_untried_in_roster(roster, start, tried),
10982        })
10983}
10984
10985/// The next agent for a seat that carries its failure history across rounds
10986/// (the review loop). `round_tried` is this round's own bound and starts
10987/// empty every round; `carried_failed` only decides priority.
10988///
10989/// First: an id walking forward from `start`, never wrapping, that is neither
10990/// tried this round nor failed in an earlier one. Only when that is exhausted
10991/// does it rescue: the first roster id (in roster order, so this one *does*
10992/// look before `start`) not yet tried this round, which is by then a carried
10993/// failure. Each id is rescued at most once per round, so it cannot loop.
10994fn next_for_seat<'a>(
10995    roster: &'a [AgentSpec],
10996    start: usize,
10997    round_tried: &BTreeSet<String>,
10998    carried_failed: &BTreeSet<String>,
10999) -> Option<&'a AgentSpec> {
11000    roster
11001        .get(start + 1..)?
11002        .iter()
11003        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
11004        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
11005}
11006
11007/// Where a reviewer seat starts a round: the agent that last answered it when
11008/// it is still on the roster and not marked failed, else the spec's own agent
11009/// unless it failed, else the next roster agent that has not failed, else the
11010/// spec's own agent again (the whole roster failed). Ids no longer on the
11011/// roster are ignored. An empty roster has no handover, so the spec stands.
11012fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
11013    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
11014        return spec;
11015    };
11016    let ok = |id: &str| !h.failed.contains(id);
11017    if let Some(last) = h.last_ok.as_deref()
11018        && ok(last)
11019        && let Some(s) = roster.iter().find(|s| s.id == last)
11020    {
11021        return s.clone();
11022    }
11023    if ok(&spec.id) {
11024        return spec;
11025    }
11026    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
11027    roster
11028        .get(from + 1..)
11029        .into_iter()
11030        .flatten()
11031        .chain(roster.iter())
11032        .find(|s| ok(&s.id))
11033        .cloned()
11034        .unwrap_or(spec)
11035}
11036
11037/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
11038/// seed so a CLI that mints its session id up front (`--session-id`) never
11039/// reuses the uuid the previous agent already opened under the same seat key.
11040pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
11041    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
11042}
11043
11044/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
11045/// so the classifier below and the code that builds the message cannot drift.
11046const TIMED_OUT: &str = "timed out";
11047
11048impl FailClass {
11049    /// `None` for an answer; otherwise how the turn failed.
11050    fn of(out: &AgentOutcome) -> Option<Self> {
11051        match out {
11052            AgentOutcome::Ok(_) => None,
11053            AgentOutcome::Quota(_) => Some(Self::Quota),
11054            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
11055            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
11056            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
11057            // Not a failure of the agent. Callers check for it first; `None`
11058            // here means "no class to hand over on".
11059            AgentOutcome::ResourceBlocked(_) => None,
11060        }
11061    }
11062
11063    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11064    fn stem_word(&self) -> &'static str {
11065        match self {
11066            Self::Quota => "quota",
11067            _ => "handover",
11068        }
11069    }
11070}
11071
11072/// The message's first line with its variable parts removed — digit runs and
11073/// path-like tokens — so "exit code 2" and "exit code 7" read
11074/// as one kind of failure.
11075fn failure_signature(msg: &str) -> String {
11076    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11077    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11078    // the historical machine key while the process diagnosis uses readable prose.
11079    if let Some(code) = line
11080        .strip_prefix("process exited with no usable output (exit code ")
11081        .and_then(|s| s.strip_suffix(')'))
11082        .and_then(|s| s.parse::<i32>().ok())
11083    {
11084        line = format!("exited with some({code}) and no usable output");
11085    } else if matches!(
11086        line.as_str(),
11087        "process exited with no usable output (no exit code reported)"
11088            | "process exited with no usable output (exit code unavailable)"
11089    ) {
11090        line = "exited with none and no usable output".to_owned();
11091    }
11092    let mut out = Vec::new();
11093    for word in line.split_whitespace() {
11094        if word.contains('/') || word.contains('\\') {
11095            out.push("<path>".to_owned());
11096            continue;
11097        }
11098        let mut w = String::new();
11099        let mut in_digits = false;
11100        for c in word.chars() {
11101            if c.is_ascii_digit() {
11102                if !in_digits {
11103                    w.push('#');
11104                }
11105                in_digits = true;
11106            } else {
11107                in_digits = false;
11108                w.push(c);
11109            }
11110        }
11111        out.push(w);
11112    }
11113    out.join(" ").chars().take(120).collect()
11114}
11115
11116/// Whether a seat that just failed with `cur` may go to the next roster agent.
11117/// A quota or a timeout always may. Any other failure may not when the agent
11118/// before it failed the same way: an error the prompt causes would otherwise
11119/// walk the whole roster. `prev` is the class of the immediately preceding
11120/// agent's failure, so a quota or timeout in between breaks the run of
11121/// identical failures by itself.
11122fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11123    match cur {
11124        FailClass::Quota | FailClass::Timeout => true,
11125        FailClass::Other(_) => prev != Some(cur),
11126    }
11127}
11128
11129/// A short human reason for a failed outcome, for the handover record.
11130fn fail_reason(out: &AgentOutcome) -> String {
11131    match out {
11132        AgentOutcome::Ok(_) => String::new(),
11133        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11134        AgentOutcome::Dropped(o) => format!(
11135            "the CLI dropped the stream ({})",
11136            o.dropped
11137                .as_ref()
11138                .map(|d| d.why.as_str())
11139                .unwrap_or("it ended without delivering its answer")
11140        ),
11141        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11142            e.lines().next().unwrap_or("").chars().take(160).collect()
11143        }
11144    }
11145}
11146
11147/// Note one handover in the run: the structured record and, in the timeline,
11148/// the sentence a person reads. A quota keeps the wording it always had.
11149pub(crate) fn record_handover(
11150    state: &mut RunState,
11151    node: &str,
11152    seat: &str,
11153    from: &str,
11154    to: &str,
11155    class: &FailClass,
11156    reason: &str,
11157) {
11158    let message = if *class == FailClass::Quota {
11159        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11160    } else {
11161        format!("{seat}: handed over {from} -> {to} ({reason})")
11162    };
11163    state.event(node, message);
11164    state.handovers.push(Handover {
11165        at: Timestamp::now(),
11166        node: node.to_owned(),
11167        seat: seat.to_owned(),
11168        from: from.to_owned(),
11169        to: to.to_owned(),
11170        reason: reason.to_owned(),
11171    });
11172}
11173
11174/// Did this reply report running a command whose own CLI never confirmed an
11175/// exit status?
11176///
11177/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11178/// command *finished* (see that type's own doc), so this can only be `true`
11179/// for a command whose completion event carried no readable exit code — not
11180/// for one that simply is not mentioned at all. That is the one signal this
11181/// crate can read, from the same record `state.jobs` renders, about a reply
11182/// standing next to work its own CLI cannot vouch for finishing; it is
11183/// deliberately not a check on the exit code's *value* (a fixer legitimately
11184/// runs a command that fails mid-iteration before it succeeds) and not a
11185/// guess at a command still running in the background (which emits no event
11186/// at all, and so leaves no evidence here to find).
11187fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11188    commands.iter().any(|c| c.exit_code.is_none())
11189}
11190
11191/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11192/// adoption guard.
11193#[derive(Debug, Clone, PartialEq, Eq)]
11194enum NoopClaimVerdict {
11195    /// Reply did not open with `NO CHANGE NEEDED:`.
11196    Absent,
11197    /// Structured evidence passed schema, CLI command, and repository checks.
11198    Accepted,
11199    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11200    /// concrete reason.
11201    Rejected(String),
11202}
11203
11204fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11205    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11206    cmd.description.trim() == check.method.trim()
11207}
11208
11209/// Checks cited by `requirements` plus the final check, deduplicated in order.
11210fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11211    let mut out = report.cited_checks();
11212    if let Some(last) = report.checks.last()
11213        && !out
11214            .iter()
11215            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11216    {
11217        out.push(last);
11218    }
11219    out
11220}
11221
11222/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11223/// when the backend reported commands. Empty `commands` is allowed because not
11224/// every backend emits structured command events.
11225fn check_command_evidence(
11226    report: &verdict::VerifiedNoopReport,
11227    commands: &[agent::CommandEvidence],
11228) -> std::result::Result<(), String> {
11229    if commands.is_empty() {
11230        return Ok(());
11231    }
11232    for check in checks_to_cross_verify(report) {
11233        let matching: Vec<&agent::CommandEvidence> = commands
11234            .iter()
11235            .filter(|cmd| command_matches_check(cmd, check))
11236            .collect();
11237        match check.kind {
11238            verdict::NoopEvidenceKind::Command
11239            | verdict::NoopEvidenceKind::Test
11240            | verdict::NoopEvidenceKind::Path => {
11241                let Some(last_cmd) = matching.last() else {
11242                    return Err(format!(
11243                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11244                         but no matching command was recorded by the CLI",
11245                        check.id.trim(),
11246                        check.kind,
11247                        check.target.trim()
11248                    ));
11249                };
11250                if last_cmd.exit_code != Some(0) {
11251                    return Err(format!(
11252                        "contradictory command evidence: check `{}` claims `{}` passed, \
11253                         but its last recorded CLI command (`{}`) exited with {}",
11254                        check.id.trim(),
11255                        check.target.trim(),
11256                        last_cmd.description.trim(),
11257                        crate::notices::exit_status(last_cmd.exit_code)
11258                    ));
11259                }
11260                if check.kind == verdict::NoopEvidenceKind::Test
11261                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11262                {
11263                    return Err(format!(
11264                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11265                         but its last recorded CLI output reports failure or no passing tests",
11266                        check.id.trim(),
11267                        check.target.trim()
11268                    ));
11269                }
11270            }
11271            verdict::NoopEvidenceKind::Commit => {
11272                if let Some(last_cmd) = matching.last()
11273                    && last_cmd.exit_code != Some(0)
11274                {
11275                    return Err(format!(
11276                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11277                         but its last recorded CLI command (`{}`) exited with {}",
11278                        check.id.trim(),
11279                        check.target.trim(),
11280                        last_cmd.description.trim(),
11281                        crate::notices::exit_status(last_cmd.exit_code)
11282                    ));
11283                }
11284            }
11285        }
11286    }
11287    Ok(())
11288}
11289
11290/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11291/// exit, confirmed commands, strict structured JSON validation, and
11292/// `CommandEvidence` consistency.
11293fn evaluate_noop_claim(
11294    usable: bool,
11295    commands: &[agent::CommandEvidence],
11296    text: &str,
11297) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11298    if !text
11299        .trim_start()
11300        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11301    {
11302        return Ok(None);
11303    }
11304    if !usable {
11305        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11306    }
11307    if has_unconfirmed_command(commands) {
11308        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11309    }
11310    let Some(parsed) = verdict::parse_verified_noop(text) else {
11311        return Ok(None);
11312    };
11313    let report = parsed?;
11314    check_command_evidence(&report, commands)?;
11315    Ok(Some(report))
11316}
11317
11318/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11319/// structured no-op report against the candidate's real Git history and
11320/// worktree. Existence alone never satisfies a requirement (the report still
11321/// had to carry concrete passing checks), while a missing commit/path or a
11322/// commit not on `base_commit` disqualifies the claim.
11323async fn verify_noop_repo_evidence(
11324    report: &verdict::VerifiedNoopReport,
11325    worktree: &Path,
11326    base_commit: &str,
11327) -> std::result::Result<(), String> {
11328    let wt_canon = std::fs::canonicalize(worktree).ok();
11329    for check in checks_to_cross_verify(report) {
11330        match check.kind {
11331            verdict::NoopEvidenceKind::Commit => {
11332                let target = check.target.trim();
11333                let Some(sha) = git::commit_of(worktree, target).await else {
11334                    return Err(format!(
11335                        "check `{}` cites commit `{target}`, which does not exist in git history",
11336                        check.id.trim()
11337                    ));
11338                };
11339                if !git::is_ancestor(worktree, &sha, base_commit).await {
11340                    return Err(format!(
11341                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11342                        check.id.trim(),
11343                        short(base_commit)
11344                    ));
11345                }
11346            }
11347            verdict::NoopEvidenceKind::Path => {
11348                let target = check.target.trim();
11349                let rel = verdict::strip_path_locator(target);
11350                let full = worktree.join(rel);
11351                if !full.exists() {
11352                    return Err(format!(
11353                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11354                        check.id.trim()
11355                    ));
11356                }
11357                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11358                    && !path_canon.starts_with(wt_canon)
11359                {
11360                    return Err(format!(
11361                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11362                        check.id.trim()
11363                    ));
11364                }
11365            }
11366            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11367        }
11368    }
11369    Ok(())
11370}
11371
11372/// Full adoption guard for an implementer reply, including real Git history and
11373/// worktree path verification.
11374async fn verified_noop_claim_in_worktree(
11375    usable: bool,
11376    commands: &[agent::CommandEvidence],
11377    text: &str,
11378    worktree: &Path,
11379    base_commit: &str,
11380) -> NoopClaimVerdict {
11381    let report = match evaluate_noop_claim(usable, commands, text) {
11382        Ok(Some(r)) => r,
11383        Ok(None) => return NoopClaimVerdict::Absent,
11384        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11385    };
11386    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11387        return NoopClaimVerdict::Rejected(reason);
11388    }
11389    NoopClaimVerdict::Accepted
11390}
11391
11392/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11393/// trusted as a verified no-op — the adoption guard's pure text-and-command
11394/// half (repository history/path verification runs in
11395/// [`verified_noop_claim_in_worktree`]).
11396///
11397/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11398/// timed out): a marker only earns the benefit of the doubt from a turn the
11399/// CLI itself vouches for finishing properly, the same house style
11400/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11401/// *fix* report to for `commands`. A candidate that timed out, exited
11402/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11403/// or failed structured validation returns `None`.
11404#[cfg(test)]
11405fn verified_noop_claim(
11406    usable: bool,
11407    commands: &[agent::CommandEvidence],
11408    text: &str,
11409) -> Option<String> {
11410    evaluate_noop_claim(usable, commands, text)
11411        .ok()
11412        .flatten()
11413        .map(|report| report.summary_text())
11414}
11415
11416fn short(commit: &str) -> String {
11417    commit.chars().take(7).collect()
11418}
11419
11420fn make_executable(path: &Path) -> Result<()> {
11421    #[cfg(unix)]
11422    {
11423        use std::os::unix::fs::PermissionsExt as _;
11424        let mut perms = std::fs::metadata(path)?.permissions();
11425        perms.set_mode(0o755);
11426        std::fs::set_permissions(path, perms)?;
11427    }
11428    #[cfg(not(unix))]
11429    {
11430        let _ = path;
11431    }
11432    Ok(())
11433}
11434
11435/// What every seat in one batch shares: where the answers are attributed, the
11436/// prompt overlay they inherit, and the build cache they are told to use.
11437///
11438/// A struct rather than four more parameters: `wave` also needs the run's
11439/// state (to record who is answering right now) and the attempt number, and
11440/// eight positional arguments is both unreadable and a clippy error.
11441struct WaveCtx<'a> {
11442    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11443    /// paid for it.
11444    run: &'a str,
11445    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11446    node: &'a str,
11447    prompts: &'a Prompts,
11448    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11449    cache: Option<&'a Path>,
11450    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11451    /// `JobRecord::round`. `None` for every other node.
11452    round: Option<usize>,
11453    /// Carry each seat's failed-agent history across waves (the review loop
11454    /// only): start-of-round priority and handover choice read
11455    /// [`RunState::seat_history`], and every answer or failure writes it.
11456    carry_seats: bool,
11457    /// The run's park / interrupt requests, so a wait for a shared resource
11458    /// can be abandoned the moment the operator asks to park.
11459    pauses: Option<(&'a Pause, &'a Pause)>,
11460}
11461
11462/// Shared scheduling policy for operations and spawned seat invocations.
11463fn repository_wait(
11464    state: &RunState,
11465    pauses: Option<(&Pause, &Pause)>,
11466) -> crate::repo_lock::WaitPolicy {
11467    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11468    let inherited = crate::repo_lock::WaitPolicy::current();
11469    crate::repo_lock::WaitPolicy::new(
11470        Duration::from_secs(state.config.graph.timeout_resource_wait),
11471        move || {
11472            inherited.cancelled()
11473                || pauses
11474                    .as_ref()
11475                    .is_some_and(|(a, b)| a.parked() || b.parked())
11476        },
11477    )
11478}
11479
11480fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11481    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11482        state.event("resource", timeout.0.description());
11483        state.resource_block = Some(timeout.0.clone());
11484        return;
11485    }
11486    if error.is::<crate::repo_lock::ResourceBlocked>() {
11487        state.resource_block = Some(crate::run::ResourceBlock {
11488            cause: crate::run::ResourceBlockCause::Other,
11489            node: "repository".into(),
11490            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11491                "disk admission"
11492            } else if error.to_string().contains("disk pressure") {
11493                "disk pressure"
11494            } else if error.to_string().contains("disk admission") {
11495                "disk admission"
11496            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11497                "incremental cache admission"
11498            } else {
11499                "repository coordination"
11500            }
11501            .into(),
11502            detail: format!("{error:#}"),
11503            at: Timestamp::now(),
11504        });
11505        state.event("resource", error.to_string());
11506    }
11507}
11508
11509async fn coordinate_operation(
11510    state: &mut RunState,
11511    cwd: &Path,
11512    wait: &crate::repo_lock::WaitPolicy,
11513) -> Result<Option<crate::repo_lock::SeatLease>> {
11514    let result =
11515        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11516            .await;
11517    if let Err(e) = &result {
11518        record_repository_block(state, e);
11519    }
11520    result
11521}
11522
11523/// Run one job, honouring the parallelism budget.
11524async fn run_one(
11525    job: SeatJob,
11526    sem: Arc<Semaphore>,
11527    ctx: &WaveCtx<'_>,
11528    state: &mut RunState,
11529    attempt: usize,
11530) -> (SeatState, AgentOutcome) {
11531    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11532        .await
11533        .pop()
11534        .expect("one job in, one result out");
11535    (seat, out)
11536}
11537
11538/// Run every job concurrently, capped by the semaphore, preserving order.
11539///
11540/// Every seat in the batch is recorded into [`RunState::active`] before the
11541/// wave starts and cleared as each answer lands, so the run's own record says
11542/// who is still being waited on rather than only who finished.
11543async fn wave(
11544    jobs: Vec<SeatJob>,
11545    sem: Arc<Semaphore>,
11546    ctx: &WaveCtx<'_>,
11547    state: &mut RunState,
11548    attempt: usize,
11549) -> Vec<(usize, SeatState, AgentOutcome)> {
11550    let WaveCtx {
11551        run,
11552        node,
11553        prompts,
11554        cache,
11555        round,
11556        carry_seats: _,
11557        pauses,
11558    } = *ctx;
11559    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11560    for job in &jobs {
11561        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11562    }
11563    if let Err(e) = state.save() {
11564        // A failed persist of "who is answering right now" must not abort the
11565        // wave: the seats are already being asked, and the alternative is
11566        // losing the answers to save a status line nobody may even be
11567        // watching.
11568        tracing::warn!("could not persist in-progress seats: {e:#}");
11569    }
11570    // Shared-mode waves keep their existing single lease. Isolated writers
11571    // acquire their own checkout's target at seat admission.
11572    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11573    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11574    // never borrowed from a job's agent budget (and never charged to it either,
11575    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11576    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11577    let cache_guard = if let Some(cache_dir) = cache {
11578        if jobs_had_a_writer {
11579            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11580            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11581            match acquire_cache_lease(
11582                state,
11583                cache_dir,
11584                &owner,
11585                resource_limit,
11586                node,
11587                node,
11588                &cancel,
11589            )
11590            .await
11591            {
11592                Ok(Some(g)) => Some(g),
11593                // Parking: leave without spawning anything. The run parks at
11594                // the next boundary and the seats are asked afresh on resume.
11595                Ok(None) => {
11596                    if let Some(block) = &mut state.resource_block {
11597                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11598                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11599                        };
11600                    }
11601                    return block_wave(
11602                        jobs,
11603                        state,
11604                        node,
11605                        attempt,
11606                        "parked while waiting for the shared build cache",
11607                    );
11608                }
11609                // An unreadable lease is not contention: keep the old
11610                // fallback (no shared cache for this wave's seats).
11611                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11612                Err(e) => {
11613                    // Writing seats may not build into a cache this run does
11614                    // not hold, and an agent that cannot be given one is not
11615                    // asked at all: the run stops resumably instead.
11616                    let why = format!("{e:#}");
11617                    state.event(
11618                        "resource",
11619                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11620                    );
11621                    return block_wave(jobs, state, node, attempt, &why);
11622                }
11623            }
11624        } else {
11625            None
11626        }
11627    } else {
11628        None
11629    };
11630    // Every job keeps its whole budget: the wait above was not the agent's.
11631    // Restart the seats' clocks so "started" means "being spawned now".
11632    state.seats_spawning(node, attempt);
11633    if let Err(e) = state.save() {
11634        tracing::warn!("could not persist the start of a wave: {e:#}");
11635    }
11636    // Queueing behind this wave's own seats for a parallelism slot is normal
11637    // (each of them is bounded by its own agent timeout); only a wait beyond
11638    // all of them plus the resource limit means the slots never came back.
11639    let slot_limit = resource_limit
11640        + jobs
11641            .iter()
11642            .map(|j| j.timeout)
11643            .max()
11644            .unwrap_or_default()
11645            .saturating_mul(jobs.len() as u32);
11646    let mut set = tokio::task::JoinSet::new();
11647    // Seats announce themselves here the moment they hold a parallelism
11648    // permit, i.e. just before their CLI is spawned.
11649    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11650    let overlay = prompts.overlay(node);
11651    let repository_wait = repository_wait(state, pauses);
11652    for (i, mut job) in jobs.into_iter().enumerate() {
11653        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11654        if cache.is_some() {
11655            job.prompt.push('\n');
11656            job.prompt
11657                .push_str(&prompt::build_cache_note(node, job.allow_write));
11658        }
11659        let sem = Arc::clone(&sem);
11660        let run = run.to_owned();
11661        let node = node.to_owned();
11662        // Only implementers were told about the task's attachments, so only
11663        // their seats get the directory widened for reading.
11664        let attachments = if node == "implement" {
11665            state.attachments.clone()
11666        } else {
11667            Vec::new()
11668        };
11669        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11670        // `prompt::build_cache_note`'s doc for why setting it anyway is
11671        // exactly how a sandboxed reviewer's write refusal got reported as a
11672        // defect in the patch, not a property of its own seat. And a
11673        // write-allowed one is handed it only when the lease above was
11674        // actually acquired: a wave that could not get it (`cache_guard` is
11675        // `None`, see its own comment) must not send seats to build into a
11676        // directory this run does not hold - that is the exact concurrent,
11677        // unmanaged-write race this module exists to prevent, not something
11678        // "proceeding anyway" is allowed to reintroduce.
11679        let cache = cache
11680            .filter(|_| job.allow_write && cache_guard.is_some())
11681            .map(Path::to_path_buf);
11682        let spawned_tx = spawned_tx.clone();
11683        let repository_wait = repository_wait.clone();
11684        let coordination = state.config.coordination.clone();
11685        let fetched_base = state.fetched_base.clone();
11686        set.spawn(async move {
11687            // A wait for a parallelism slot is scheduling, not the agent: it
11688            // is bounded by its own limit and ends as a resource block, never
11689            // as a timeout of the agent that was not started.
11690            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11691                Ok(p) => p,
11692                Err(_) => {
11693                    return (
11694                        i,
11695                        job.seat,
11696                        AgentOutcome::ResourceBlocked(format!(
11697                            "no parallel slot became free within {}s",
11698                            slot_limit.as_secs()
11699                        )),
11700                        None,
11701                        false,
11702                    );
11703                }
11704            };
11705            spawned_tx.send(job.seat.key.clone()).ok();
11706            let mut seat = job.seat;
11707            let out = repository_wait
11708                .scope(agent::invoke(
11709                    &job.spec,
11710                    &mut seat,
11711                    &Invocation {
11712                        coordination: coordination.as_ref(),
11713                        fetched_base: fetched_base.as_ref(),
11714                        cwd: &job.cwd,
11715                        prompt: &job.prompt,
11716                        timeout: job.timeout,
11717                        allow_write: job.allow_write,
11718                        sessions: job.sessions,
11719                        artifacts: &job.artifacts,
11720                        stem: &job.stem,
11721                        run: &run,
11722                        node: &node,
11723                        cache_dir: cache.as_deref(),
11724                        attachments: &attachments,
11725                        writable: &[],
11726                    },
11727                ))
11728                .await;
11729            let cache_block = out
11730                .as_ref()
11731                .err()
11732                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11733                .map(|timeout| timeout.0.clone());
11734            let interrupted = out
11735                .as_ref()
11736                .err()
11737                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11738            let out = match out {
11739                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11740                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11741                // Billed work the CLI failed to hand over is not an ordinary
11742                // failure, but its text is the CLI's raw error JSON, not an
11743                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11744                // read it as one by forgetting to check. `usable()` is always
11745                // false here (dropped implies an empty response), so this has
11746                // to be checked before the catch-all `Failed` below or the
11747                // one shape this exists for is lost with the rest.
11748                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11749                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11750                Ok(o) => AgentOutcome::Failed(format!(
11751                    "process exited with no usable output ({})",
11752                    crate::notices::exit_status(o.exit_code)
11753                )),
11754                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11755                    AgentOutcome::ResourceBlocked(e.to_string())
11756                }
11757                Err(e) => AgentOutcome::Failed(e.to_string()),
11758            };
11759            (i, seat, out, cache_block, interrupted)
11760        });
11761    }
11762    drop(spawned_tx);
11763    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11764    loop {
11765        let joined = tokio::select! {
11766            Some(key) = spawned_rx.recv() => {
11767                // The clock of this seat starts now, not when it queued.
11768                state.seat_spawned(&key);
11769                if let Err(e) = state.save() {
11770                    tracing::warn!("could not persist a seat's start: {e:#}");
11771                }
11772                continue;
11773            }
11774            joined = set.join_next() => joined,
11775        };
11776        let Some(joined) = joined else {
11777            break;
11778        };
11779        let (i, seat, out, cache_block, interrupted) = match joined {
11780            Ok(v) => v,
11781            // No seat to clear: a panicked task never reported which one it
11782            // was. The defensive sweep below this loop is what stops that
11783            // seat's `active` entry from surviving forever.
11784            Err(e) => {
11785                tracing::error!("agent task panicked: {e}");
11786                continue;
11787            }
11788        };
11789        state.seat_finished(&seat.key);
11790        if interrupted
11791            && node == "implement"
11792            && let Some(label) = state
11793                .candidates
11794                .iter()
11795                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11796                .map(|candidate| candidate.label)
11797        {
11798            state.candidate_preservation.insert(
11799                label,
11800                "interrupted implementation awaiting persistence".into(),
11801            );
11802            state.interrupted_implementations.insert(label);
11803        }
11804        if let Some(block) = cache_block
11805            && state.resource_block.is_none()
11806        {
11807            state.event("resource", block.description());
11808            state.resource_block = Some(block);
11809        }
11810        if let AgentOutcome::ResourceBlocked(why) = &out
11811            && state.resource_block.is_none()
11812        {
11813            state.resource_block = Some(crate::run::ResourceBlock {
11814                cause: crate::run::ResourceBlockCause::Other,
11815                node: node.to_owned(),
11816                kind: if why.contains("disk pressure") {
11817                    "disk pressure"
11818                } else if why.contains("disk admission") {
11819                    "disk admission"
11820                } else if why.contains(crate::incremental::BLOCKED) {
11821                    "incremental cache admission"
11822                } else if why.contains(crate::build_target::KIND) {
11823                    crate::build_target::KIND
11824                } else if why.contains("repository coordination") {
11825                    "repository coordination"
11826                } else {
11827                    "parallel slot"
11828                }
11829                .to_owned(),
11830                detail: why.clone(),
11831                at: Timestamp::now(),
11832            });
11833            let activity = if interrupted {
11834                "agent execution interrupted"
11835            } else {
11836                "no agent was started"
11837            };
11838            state.event("resource", format!("{node}: {activity} - {why}"));
11839        }
11840        record_jobs(state, node, round, &seat.key, &out);
11841        if let Err(e) = state.save() {
11842            tracing::warn!("could not persist a seat's completion: {e:#}");
11843        }
11844        if collected.len() <= i {
11845            collected.resize_with(i + 1, || None);
11846        }
11847        collected[i] = Some((i, seat, out));
11848    }
11849    // Belt-and-braces for the panic branch above: every seat this exact batch
11850    // started shares this `(node, attempt)` pair, and every seat that finished
11851    // normally already cleared itself, so anything left tagged with it here
11852    // can only be a panicked task's leftover. Cleared unconditionally rather
11853    // than left to read as still answering forever.
11854    if state
11855        .active
11856        .values()
11857        .any(|a| a.node == node && a.attempt == attempt)
11858    {
11859        state
11860            .active
11861            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11862        if let Err(e) = state.save() {
11863            tracing::warn!("could not persist the end of a wave: {e:#}");
11864        }
11865    }
11866    // Whether or not the lease above was actually held, several worktrees
11867    // may just have built into the cache with nothing here able to name one
11868    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11869    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11870    // clean it might not have strictly needed; trusting a stale match would
11871    // cost it a wrong answer.
11872    if let Some(cache_dir) = cache
11873        && jobs_had_a_writer
11874    {
11875        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11876    }
11877    if let Some(guard) = cache_guard {
11878        guard.release();
11879    }
11880    collected.into_iter().flatten().collect()
11881}
11882
11883/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11884/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11885/// this is data collection, not the fix-specific completion contract in
11886/// [`Runner::continue_fix_report`], and applies regardless of which node
11887/// asked.
11888///
11889/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11890/// evidence from; `Failed` does not, and correctly contributes nothing — a
11891/// timeout or crash is not itself evidence about a command the seat may have
11892/// started.
11893fn record_jobs(
11894    state: &mut RunState,
11895    node: &str,
11896    round: Option<usize>,
11897    seat: &str,
11898    out: &AgentOutcome,
11899) {
11900    let commands: &[agent::CommandEvidence] = match out {
11901        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11902        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11903    };
11904    let checked_at = Timestamp::now();
11905    for c in commands {
11906        state.jobs.push(JobRecord {
11907            node: node.to_owned(),
11908            round,
11909            seat: seat.to_owned(),
11910            id: c.id.clone(),
11911            description: c.description.clone(),
11912            checked_at,
11913            status: match c.exit_code {
11914                Some(0) => JobStatus::Completed,
11915                Some(_) => JobStatus::Failed,
11916                None => JobStatus::Unknown,
11917            },
11918            exit_code: c.exit_code,
11919            result_summary: c.result_summary.clone(),
11920            source: c.source.clone(),
11921        });
11922    }
11923}
11924
11925/// Is a review round clean, given how many reviewer seats answered against
11926/// how many the round expected?
11927///
11928/// A seat that never answered (timeout, crash, unparsable output) is not a
11929/// seat that read the patch and found nothing — treating it as such is
11930/// exactly the bug this function exists to close. Under the default `block`
11931/// policy a missing seat can never be clean; `warn` still requires the seats
11932/// that *did* answer to have found nothing blocking and verification to be
11933/// green.
11934///
11935/// `quota_missing` narrows that `block` default for exactly one cause of
11936/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11937/// a session limit lifts by the very next round buys nothing — the seat is
11938/// asked again with the same quota — so once every missing seat is accounted
11939/// for by a quota loss (and at least one seat *did* answer, so a decision has
11940/// something to rest on) the round is decided on the panel that could answer,
11941/// same as `warn` would. A panel that lost every seat to quota is not
11942/// decided here: `answered == 0` falls through to the existing `block`
11943/// fallback so a fully collapsed panel still waits rather than landing on no
11944/// review at all.
11945fn round_is_clean(
11946    blocking: usize,
11947    e2e_ok: bool,
11948    answered: usize,
11949    expected: usize,
11950    quota_missing: usize,
11951    policy: IncompleteReviewPolicy,
11952) -> bool {
11953    if blocking != 0 || !e2e_ok {
11954        return false;
11955    }
11956    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11957        return true;
11958    }
11959    answered > 0 && expected - answered <= quota_missing
11960}
11961
11962/// The review loop's own conclusion, derived entirely from its persisted
11963/// round records and the round budget that produced them — never from
11964/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11965/// recomputes the identical answer regardless of what an earlier node in the
11966/// same walk, or a previous walk, did to `status`.
11967///
11968/// `None` while more rounds remain to try, including when review never ran
11969/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11970/// gone clean, or the budget is spent, or the tree has stopped moving (see
11971/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11972///
11973/// - An incomplete panel that raised nothing is missing input, not a
11974///   verified tree — never a hand-off candidate, whatever verification said
11975///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11976/// - Otherwise, green e2e on the last round hands off (see
11977///   [`Runner::stop_reviewing`]); red e2e blocks.
11978///
11979/// A last round whose own verification is still `ResourceBlocked` — magi
11980/// itself never got a command to run, not evidence the patch is broken —
11981/// is neither: this returns `None` for it too, the same as "more rounds
11982/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11983/// handling of that shape) instead of this cheap recomputation guessing a
11984/// verdict a real attempt never produced.
11985pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11986    if max_rounds == 0
11987        || reviews.last().is_some_and(|r| {
11988            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11989        })
11990    {
11991        return Some(RunStatus::Gating);
11992    }
11993    let last = reviews.last()?;
11994    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11995    if reviews.len() < max_rounds && !stagnant {
11996        return None;
11997    }
11998    if last.incomplete() && last.blocking == 0 {
11999        return Some(RunStatus::Blocked);
12000    }
12001    if last.e2e_status() == E2eStatus::ResourceBlocked
12002        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
12003    {
12004        return None;
12005    }
12006    Some(if last.e2e.iter().all(CommandOutcome::ok) {
12007        RunStatus::Gating
12008    } else {
12009        RunStatus::Blocked
12010    })
12011}
12012
12013/// How long a re-ask may take, given the budget the first attempt had.
12014///
12015/// A `nudged` retry is a request to restate an answer the seat has already
12016/// worked out: it carries no new work, so it does not deserve the original
12017/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
12018/// 133 seconds while a third sat for over ten minutes on a resumed session
12019/// holding 410 KB of prior output - and because the retry had inherited the
12020/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
12021/// judging round whose other seats were long finished.
12022///
12023/// A quarter of the budget, with a floor so that a deliberately short timeout
12024/// does not collapse to nothing. A retry that re-sends the whole prompt
12025/// (because the seat kept no context) is the original job again, and keeps the
12026/// original budget.
12027pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
12028    if nudged {
12029        (full / 4).max(Duration::from_secs(120)).min(full)
12030    } else {
12031        full
12032    }
12033}
12034
12035/// Run a wave and parse each reply, re-asking the seats whose reply was
12036/// unusable.
12037///
12038/// The re-ask is a nudge rather than the whole prompt again when the seat still
12039/// holds its conversation, which is the difference between a cheap retry and
12040/// paying for the entire candidate set twice.
12041///
12042/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
12043/// successor in `roster` is handed to it instead of being re-asked: the
12044/// handover is the retry. A seat with no successor left (a single-agent
12045/// roster, the roster's tail) is nudged as before, up to `retries` times. So
12046/// the asks to one seat in one node number at most
12047/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
12048/// is asked once (a dropped stream is nudged first), and only the last agent
12049/// of the chain gets the `retries` same-agent nudges. Each roster agent is
12050/// tried at most once per seat, walking forward from the seat's own position and never wrapping
12051/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
12052/// other failure stops the chain when the previous agent failed the same way
12053/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
12054/// [`has_context`] is false and the job's own full prompt and full budget are
12055/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
12056/// intermediate ones are not losses) and is returned as a failure like any
12057/// other absent seat — the caller decides whether the panel still has a
12058/// quorum. An empty `roster` disables handover: failures are nudged as they
12059/// always were, and a quota is simply lost. A reply that fails to parse or
12060/// validate is the prompt's doing and is only ever nudged, never handed over.
12061///
12062/// The returned [`SeatState`] names the agent that answered (or tried last).
12063#[allow(clippy::too_many_arguments)]
12064async fn ask_json_wave<T>(
12065    jobs: Vec<SeatJob>,
12066    sem: Arc<Semaphore>,
12067    retries: usize,
12068    roster: &[AgentSpec],
12069    ctx: &WaveCtx<'_>,
12070    losses: &mut Vec<QuotaLoss>,
12071    state: &mut RunState,
12072    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12073) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12074where
12075    T: serde::de::DeserializeOwned + Send + 'static,
12076{
12077    ask_wave_with(
12078        jobs,
12079        sem,
12080        retries,
12081        roster,
12082        ctx,
12083        losses,
12084        state,
12085        &|text: &str| {
12086            let v = verdict::extract_json::<T>(text)?;
12087            validate(&v)?;
12088            Ok(v)
12089        },
12090    )
12091    .await
12092}
12093
12094/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12095/// a node whose answer is prose (deliberation) shares the same handover,
12096/// failure classification, quota bookkeeping and bounds instead of a copy.
12097///
12098/// A seat handed to another roster agent is sent the job's `handover` prompt
12099/// (when it has one) rather than `prompt`: the new agent has no session, so a
12100/// resume-style prompt would be incomplete. That holds for the handover ask
12101/// and for every nudge to that agent whose `has_context` is false.
12102#[allow(clippy::too_many_arguments)]
12103async fn ask_wave_with<T>(
12104    jobs: Vec<SeatJob>,
12105    sem: Arc<Semaphore>,
12106    retries: usize,
12107    roster: &[AgentSpec],
12108    ctx: &WaveCtx<'_>,
12109    losses: &mut Vec<QuotaLoss>,
12110    state: &mut RunState,
12111    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12112) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12113where
12114    T: Send + 'static,
12115{
12116    let n = jobs.len();
12117    let originals: Vec<SeatJob> = jobs;
12118    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12119    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12120    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12121    // answer, N once it has gone through N nudges. Read back once this
12122    // returns, so a caller building a history record (`ReviewRecord`) can
12123    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12124    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12125    // field's own doc.
12126    let mut nudges: Vec<usize> = vec![0; n];
12127    // The agent now occupying each seat, the ids it has already been through,
12128    // where in the roster the walk began, the class of the last failure, and
12129    // the stem word of a handover not yet asked (full prompt, full budget).
12130    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12131    let mut tried: Vec<BTreeSet<String>> = specs
12132        .iter()
12133        .map(|s| BTreeSet::from([s.id.clone()]))
12134        .collect();
12135    let starts: Vec<usize> = specs
12136        .iter()
12137        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12138        .collect();
12139    let carry = ctx.carry_seats && !roster.is_empty();
12140    // Carried across rounds: ids that failed the seat earlier, and how the
12141    // last failure went (so a repeat of it is not handed over again).
12142    let carried: Vec<BTreeSet<String>> = originals
12143        .iter()
12144        .map(|j| {
12145            state
12146                .seat_history
12147                .get(&j.seat.key)
12148                .filter(|_| carry)
12149                .map(|h| h.failed.clone())
12150                .unwrap_or_default()
12151        })
12152        .collect();
12153    let mut prev: Vec<Option<FailClass>> = originals
12154        .iter()
12155        .map(|j| {
12156            state
12157                .seat_history
12158                .get(&j.seat.key)
12159                .filter(|_| carry)
12160                .and_then(|h| h.last_fail.clone())
12161        })
12162        .collect();
12163    let next_agent =
12164        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12165            let others: BTreeSet<String> = specs
12166                .iter()
12167                .enumerate()
12168                .filter(|(j, _)| *j != i)
12169                .map(|(_, s)| s.id.clone())
12170                .collect();
12171            pick_successor(
12172                roster,
12173                starts[i],
12174                tried,
12175                carry.then(|| &carried[i]),
12176                &others,
12177            )
12178            .cloned()
12179        };
12180    let mut fresh: Vec<Option<String>> = vec![None; n];
12181    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12182    let mut pending: Vec<usize> = (0..n).collect();
12183
12184    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12185    // asks: an agent with a successor is asked once and handed over, and only
12186    // a seat with no successor spends `retries` nudges on the same agent. This
12187    // only guarantees the loop's own termination whatever those say.
12188    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12189    for round in 0..max_rounds {
12190        if pending.is_empty() {
12191            break;
12192        }
12193        let mut batch = Vec::with_capacity(pending.len());
12194        let mut renudged: Vec<&str> = Vec::new();
12195        for &i in &pending {
12196            let src = &originals[i];
12197            // A seat now held by another agent than the job named has no
12198            // session of its own: it gets the full-context prompt whenever
12199            // it is asked in full (the handover ask, a nudge it cannot
12200            // resume).
12201            let full: &str = match &src.handover {
12202                Some(h) if specs[i].id != src.spec.id => h,
12203                _ => &src.prompt,
12204            };
12205            // The prompt and the budget are one decision: a nudge restates
12206            // finished work, a re-sent prompt redoes it.
12207            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12208                (
12209                    full.to_owned(),
12210                    src.timeout,
12211                    format!("{}-{word}-{}", src.stem, specs[i].id),
12212                )
12213            } else if nudges[i] == 0 {
12214                (full.to_owned(), src.timeout, src.stem.clone())
12215            } else {
12216                renudged.push(src.seat.key.as_str());
12217                let why = done[i]
12218                    .as_ref()
12219                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12220                    .unwrap_or_else(|| "no parsable answer".to_owned());
12221                let nudge = prompt::nudge(&why);
12222                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12223                let prompt = if nudged {
12224                    nudge
12225                } else {
12226                    format!("{full}\n\n---\n\n{nudge}")
12227                };
12228                (
12229                    prompt,
12230                    retry_budget(src.timeout, nudged),
12231                    format!("{}-retry{}", src.stem, nudges[i]),
12232                )
12233            };
12234            batch.push(SeatJob {
12235                spec: specs[i].clone(),
12236                seat: seats[i].clone(),
12237                cwd: src.cwd.clone(),
12238                prompt,
12239                timeout,
12240                allow_write: src.allow_write,
12241                sessions: src.sessions,
12242                artifacts: src.artifacts.clone(),
12243                stem,
12244                handover: None,
12245            });
12246        }
12247
12248        if !renudged.is_empty() {
12249            state.event(
12250                ctx.node,
12251                format!("retry {round}: re-asking {}", renudged.join(", ")),
12252            );
12253        }
12254        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12255        let mut still = Vec::new();
12256        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12257            seats[i] = seat;
12258            // No agent was asked: nothing to hand over, nudge, remember or
12259            // charge. The caller sees `resource_block` and stops the node.
12260            if let AgentOutcome::ResourceBlocked(why) = &out {
12261                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12262                continue;
12263            }
12264            let class = FailClass::of(&out);
12265            // A dropped stream is nudged first (the conversation is still
12266            // there to pick up); only a seat whose nudges are spent hands over.
12267            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12268                && nudges[i] < retries
12269                && !roster.is_empty();
12270            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12271                let next = should_hand_over(prev[i].as_ref(), &cur)
12272                    .then(|| next_agent(i, &tried[i], &specs))
12273                    .flatten();
12274                if carry {
12275                    let h = state
12276                        .seat_history
12277                        .entry(originals[i].seat.key.clone())
12278                        .or_default();
12279                    h.failed.insert(specs[i].id.clone());
12280                    h.last_fail = Some(cur.clone());
12281                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12282                        h.last_ok = None;
12283                    }
12284                    // Saved before the next agent is asked, so a restart in
12285                    // between does not forget who failed.
12286                    if let Err(e) = state.save() {
12287                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12288                    }
12289                }
12290                if let Some(next) = next {
12291                    record_handover(
12292                        state,
12293                        ctx.node,
12294                        &originals[i].seat.key,
12295                        &specs[i].id,
12296                        &next.id,
12297                        &cur,
12298                        &fail_reason(&out),
12299                    );
12300                    tried[i].insert(next.id.clone());
12301                    prev[i] = Some(cur.clone());
12302                    seats[i] =
12303                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12304                    specs[i] = next;
12305                    fresh[i] = Some(cur.stem_word().to_owned());
12306                    nudges[i] = 0;
12307                    done[i] = Some(Err(anyhow::anyhow!(
12308                        "handed over after: {}",
12309                        fail_reason(&out)
12310                    )));
12311                    still.push(i);
12312                    continue;
12313                }
12314            }
12315            if carry
12316                && !nudge_first
12317                && let Some(cur) = class.clone()
12318            {
12319                // The chain ended here (no successor, or a repeated failure).
12320                let h = state
12321                    .seat_history
12322                    .entry(originals[i].seat.key.clone())
12323                    .or_default();
12324                h.failed.insert(specs[i].id.clone());
12325                h.last_fail = Some(cur);
12326            }
12327            let parsed = match out {
12328                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12329                AgentOutcome::Quota(o) => {
12330                    last_quota[i] = o.quota.clone();
12331                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12332                }
12333                // Not a parseable answer: the nudge loop re-asks it, which is
12334                // exactly what a dropped stream needs. Just don't hand its raw
12335                // error JSON to `extract_json`.
12336                AgentOutcome::Dropped(o) => {
12337                    let why = o
12338                        .dropped
12339                        .as_ref()
12340                        .map(|d| d.why.as_str())
12341                        .unwrap_or("the CLI ended the stream without delivering its answer");
12342                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12343                }
12344                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12345                    Err(anyhow::anyhow!(e))
12346                }
12347            };
12348            let quota = class == Some(FailClass::Quota);
12349            let failed = parsed.is_err();
12350            if !failed && matches!(ctx.node, "judge" | "vote") {
12351                // A validated answer restores this seat's quorum presence,
12352                // including on the normal path after an all-seat block.
12353                state
12354                    .quota
12355                    .retain(|loss| loss.seat != originals[i].seat.key);
12356            }
12357            done[i] = Some(parsed);
12358            if carry && !failed {
12359                let h = state
12360                    .seat_history
12361                    .entry(originals[i].seat.key.clone())
12362                    .or_default();
12363                h.failed.remove(&specs[i].id);
12364                h.last_ok = Some(specs[i].id.clone());
12365                h.last_fail = None;
12366            }
12367            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12368            // fail the same way; and never re-ask a seat that already parsed.
12369            // A failed agent that still has a successor is not re-asked
12370            // either: the handover was its remedy and has just been refused
12371            // (the chain stops on a repeated failure class). A seat with no
12372            // successor left (a single-agent roster, the roster's tail, or an
12373            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12374            let agent_failure = class.is_some()
12375                && !nudge_first
12376                && !roster.is_empty()
12377                && next_agent(i, &tried[i], &specs).is_some();
12378            if failed && !quota && !agent_failure && nudges[i] < retries {
12379                nudges[i] += 1;
12380                still.push(i);
12381            }
12382        }
12383        pending = still;
12384    }
12385
12386    // One loss per seat whose chain ended on a quota: the intermediate ones
12387    // were absorbed by a handover and are not losses.
12388    for (i, q) in last_quota.into_iter().enumerate() {
12389        if let Some(quota) = q {
12390            losses.push(QuotaLoss::from_report(
12391                originals[i].seat.key.clone(),
12392                ctx.node,
12393                Some(&quota),
12394            ));
12395        }
12396    }
12397
12398    // A stalled quorum already has its own recovery checkpoint. Refresh
12399    // its missing seats before deciding whether it can resume.
12400    if state.status != RunStatus::Stalled
12401        && ctx.node != "deliberate"
12402        && n > 0
12403        && losses.len() == n
12404        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12405    {
12406        block_machine_outage(state, ctx.node, losses);
12407        state.quota.append(losses);
12408    }
12409
12410    seats
12411        .into_iter()
12412        .zip(done)
12413        .zip(nudges)
12414        .map(|((seat, res), attempts)| {
12415            (
12416                seat,
12417                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12418                attempts,
12419            )
12420        })
12421        .collect()
12422}
12423
12424/// A node with no available agent has no task verdict. Preserve the node
12425/// checkpoint and record why a subsequent explicit resume is needed.
12426pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12427    let mut auth: Vec<_> = losses
12428        .iter()
12429        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12430        .map(|loss| loss.agent.clone())
12431        .collect();
12432    auth.sort();
12433    auth.dedup();
12434    let (kind, detail) = if auth.is_empty() {
12435        (
12436            "agent usage limit",
12437            "All seats reached their agent usage limits; resume after usage is available"
12438                .to_owned(),
12439        )
12440    } else {
12441        (
12442            "agent authentication",
12443            format!(
12444                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12445                auth.join(", ")
12446            ),
12447        )
12448    };
12449    state.resource_block = Some(crate::run::ResourceBlock {
12450        node: node.to_owned(),
12451        kind: kind.to_owned(),
12452        cause: crate::run::ResourceBlockCause::Other,
12453        detail: detail.clone(),
12454        at: Timestamp::now(),
12455    });
12456    state.event(node, detail);
12457}
12458
12459/// Did the wave end without asking any agent (see [`block_wave`])?
12460fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12461    results
12462        .iter()
12463        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12464}
12465
12466/// Settle a wave that never spawned anything: every job answers
12467/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12468/// else about the seat (session, history, quota) is touched.
12469fn block_wave(
12470    jobs: Vec<SeatJob>,
12471    state: &mut RunState,
12472    node: &str,
12473    attempt: usize,
12474    why: &str,
12475) -> Vec<(usize, SeatState, AgentOutcome)> {
12476    state.resource_wait = None;
12477    state
12478        .active
12479        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12480    if let Err(e) = state.save() {
12481        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12482    }
12483    jobs.into_iter()
12484        .enumerate()
12485        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12486        .collect()
12487}
12488
12489/// Acquire the shared build cache's lease, waiting out contention within
12490/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12491/// unbounded wait is never acceptable).
12492///
12493/// A first, non-blocking check happens before ever waiting; if it finds the
12494/// lease busy, that fact is logged as a `verify` event *and* flushed with
12495/// [`RunState::save`] immediately — not only once the wait finally succeeds
12496/// or gives up — so a `magi show` run by a different process while this one
12497/// is still waiting reads a `run.json` that says so, rather than whatever it
12498/// looked like before the wait started. The same applies to the terminal
12499/// failure: logged and saved before this returns `Err`, so a caller that
12500/// could not get the lease at all still leaves a legible record of why.
12501async fn acquire_cache_lease(
12502    state: &mut RunState,
12503    cache_dir: &Path,
12504    owner: &crate::cache::Owner,
12505    budget: Duration,
12506    node: &str,
12507    context: &str,
12508    cancel: &(dyn Fn() -> bool + Sync),
12509) -> Result<Option<crate::cache::Guard>> {
12510    let home = crate::run::home();
12511    let kind = if crate::build_target::isolated(&state.config) {
12512        crate::build_target::KIND
12513    } else {
12514        "shared build cache"
12515    };
12516    let started = Instant::now();
12517    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12518        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12519        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12520        Err(e) => {
12521            state.event(
12522                "verify",
12523                format!(
12524                    "{context}: could not check the {kind} at {}: {e:#}",
12525                    cache_dir.display()
12526                ),
12527            );
12528            if let Err(e2) = state.save() {
12529                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12530            }
12531            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12532        }
12533    };
12534    state.event(
12535        "verify",
12536        format!(
12537            "{context}: waiting for the {kind} at {} ({})",
12538            cache_dir.display(),
12539            busy.describe()
12540        ),
12541    );
12542    // Seats of this node are waiting, not running: say so, so the countdown a
12543    // reader sees only ever measures an agent that has been spawned.
12544    state.resource_wait = Some(crate::run::ResourceWait {
12545        node: context.to_owned(),
12546        kind: kind.to_owned(),
12547        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12548        since: Timestamp::now(),
12549        limit_secs: budget.as_secs(),
12550    });
12551    if let Err(e) = state.save() {
12552        tracing::warn!("could not persist a cache wait: {e:#}");
12553    }
12554    let remaining = budget.saturating_sub(started.elapsed());
12555    let waited = crate::cache::wait_for_unless(
12556        &home,
12557        cache_dir,
12558        owner,
12559        remaining,
12560        Duration::from_secs(5),
12561        cancel,
12562    )
12563    .await;
12564    state.resource_wait = None;
12565    let cause = match &waited {
12566        Ok(Some(_)) => None,
12567        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12568        Err(error)
12569            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12570        {
12571            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12572                target: cache_dir.to_owned(),
12573                waited_secs: started.elapsed().as_secs(),
12574                limit_secs: budget.as_secs(),
12575            })
12576        }
12577        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12578            Some(crate::run::ResourceBlockCause::Timeout {
12579                waited_secs: started.elapsed().as_secs(),
12580                limit_secs: budget.as_secs(),
12581            })
12582        }
12583        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12584    };
12585    if let Some(cause) = cause {
12586        let detail = match &waited {
12587            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12588            Err(error) => format!("{error:#}"),
12589        };
12590        state.resource_block = Some(crate::run::ResourceBlock {
12591            cause,
12592            node: node.to_owned(),
12593            kind: kind.into(),
12594            detail: format!("{}: {detail}", cache_dir.display()),
12595            at: Timestamp::now(),
12596        });
12597        state.event(
12598            "resource",
12599            state.resource_block.as_ref().unwrap().description(),
12600        );
12601    }
12602    if let Err(error) = state.save() {
12603        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12604    }
12605    waited
12606}
12607
12608/// The lease state could not be read at all (unreadable lease file, a
12609/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12610/// known to be contended, so a wave degrades to running without a shared cache
12611/// instead of stopping on a hold that [`crate::triage`] could never release.
12612#[derive(Debug)]
12613struct CacheCheckError(String);
12614
12615impl std::fmt::Display for CacheCheckError {
12616    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12617        f.write_str(&self.0)
12618    }
12619}
12620
12621impl std::error::Error for CacheCheckError {}
12622
12623/// Keep a specific acquisition outcome when the caller adds command evidence.
12624fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12625    let kind = if crate::build_target::isolated(&state.config) {
12626        crate::build_target::KIND
12627    } else {
12628        "shared build cache"
12629    };
12630    state
12631        .resource_block
12632        .get_or_insert_with(|| crate::run::ResourceBlock {
12633            cause: crate::run::ResourceBlockCause::Other,
12634            node: node.to_owned(),
12635            kind: kind.into(),
12636            detail: format!("{error:#}"),
12637            at: Timestamp::now(),
12638        });
12639    if let Err(error) = state.save() {
12640        tracing::warn!("could not persist cache resource block: {error:#}");
12641    }
12642}
12643
12644tokio::task_local! {
12645    static VERIFY_TARGET: PathBuf;
12646}
12647
12648/// Run `body` — a verify command batch — while holding the shared build
12649/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12650/// never interleave with another borrower's build against the same
12651/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12652/// timeout, or a human's own `magi review`. See the `cache` module doc for
12653/// why this matters more than Cargo's own per-target locking covers — two
12654/// *different* worktrees building the same package name/version into one
12655/// cache directory is a staleness bug, not a lock contention one.
12656///
12657/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12658/// agent waves do. Repository scheduling also has its own bounded,
12659/// cancellable resource-wait policy. Contention must not consume the
12660/// verification budget: `body` receives the full `budget` after both leases
12661/// are acquired and the cache is fresh. Without a shared cache, only
12662/// repository coordination is acquired before handing over the full budget.
12663///
12664/// A lease that cannot be acquired within the resource wait is reported as a single
12665/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12666/// verification — the same shape a spawn failure already takes in
12667/// [`run_commands`], so a caller need not special-case it.
12668#[allow(clippy::too_many_arguments)]
12669async fn with_cache_lease<'s, F, Fut>(
12670    state: &'s mut RunState,
12671    cache_dir: Option<&Path>,
12672    node: &str,
12673    seat: &str,
12674    worktree: &Path,
12675    head: &str,
12676    budget: Duration,
12677    context: &str,
12678    wait: &crate::repo_lock::WaitPolicy,
12679    body: F,
12680) -> Result<(Vec<CommandOutcome>, bool)>
12681where
12682    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12683    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12684{
12685    // Match editing waves: cache first, repository second. In particular,
12686    // pre_gate must never hold the repository while waiting for a wave's cache.
12687    let started = Instant::now();
12688    let home = crate::run::home();
12689    let isolated = crate::build_target::isolated(&state.config);
12690    let planned_target = if isolated {
12691        let plan = (|| -> Result<PathBuf> {
12692            crate::build_target::supports(&state.config)?;
12693            crate::build_target::resolve(&home, worktree)
12694        })();
12695        match plan {
12696            Ok(path) => Some(path),
12697            Err(error) => {
12698                record_cache_error(state, node, &error);
12699                return Ok((
12700                    vec![CommandOutcome {
12701                        command: "(planning isolated build cache)".into(),
12702                        code: None,
12703                        output_tail: format!("{error:#}"),
12704                        duration_ms: 0,
12705                        resource_blocked: true,
12706                        ..Default::default()
12707                    }],
12708                    false,
12709                ));
12710            }
12711        }
12712    } else {
12713        None
12714    };
12715    let cache_dir = planned_target.as_deref().or(cache_dir);
12716    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12717    let guard = if let Some(cache_dir) = cache_dir {
12718        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12719        match acquire_cache_lease(
12720            state,
12721            cache_dir,
12722            &owner,
12723            resource_limit,
12724            node,
12725            context,
12726            &|| wait.cancelled(),
12727        )
12728        .await
12729        .and_then(|g| {
12730            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12731        }) {
12732            Ok(g) => Some(g),
12733            Err(e) => {
12734                record_cache_error(state, node, &e);
12735                return Ok((
12736                    vec![CommandOutcome {
12737                        command: if isolated {
12738                            "(waiting for the isolated build cache)"
12739                        } else {
12740                            "(waiting for the shared build cache)"
12741                        }
12742                        .into(),
12743                        code: None,
12744                        output_tail: e.to_string(),
12745                        duration_ms: started.elapsed().as_millis() as u64,
12746                        resource_blocked: true,
12747                        ..Default::default()
12748                    }],
12749                    false,
12750                ));
12751            }
12752        }
12753    } else {
12754        None
12755    };
12756    let _coordination = coordinate_operation(state, worktree, wait).await?;
12757    if let Some(path) = &planned_target {
12758        state.event(node, format!("isolated build target: {}", path.display()));
12759    }
12760    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12761        let identity = crate::cache::Identity::new(worktree, head);
12762        let fresh = crate::cache::ensure_fresh(
12763            &home,
12764            cache_dir,
12765            &identity,
12766            &state.config.verify.cargo_manifests(),
12767        );
12768        if let Err(e) = fresh {
12769            record_cache_error(state, node, &e);
12770            state.event(
12771                "verify",
12772                format!(
12773                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12774                    worktree.display(),
12775                    short(head)
12776                ),
12777            );
12778            if let Some(guard) = guard {
12779                guard.release();
12780            }
12781            return Ok((
12782                vec![CommandOutcome {
12783                    command: "(confirming the build cache is fresh)".into(),
12784                    code: None,
12785                    output_tail: e.to_string(),
12786                    duration_ms: started.elapsed().as_millis() as u64,
12787                    resource_blocked: true,
12788                    ..Default::default()
12789                }],
12790                false,
12791            ));
12792        }
12793    }
12794    let future = body(state, budget);
12795    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12796        VERIFY_TARGET.scope(target, future).await
12797    } else {
12798        future.await
12799    };
12800    if !timed_out_pids.is_empty() {
12801        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12802    }
12803    // Drop repository coordination before releasing the cache, reversing the
12804    // acquisition order. A cancelled/error future also drops both guards.
12805    drop(_coordination);
12806    if let Some(guard) = guard {
12807        guard.release();
12808    }
12809    Ok((outcomes, retried))
12810}
12811
12812/// Poll `pids` — commands [`run_commands`] reports as still running when its
12813/// own timeout elapsed — until every one is confirmed gone, or
12814/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12815///
12816/// Real confirmation where confirmation is possible, not a substitute for
12817/// full process-tree observation: a grandchild the timed-out process spawned
12818/// and that survives independently of it is invisible to a pid check the
12819/// same way it always was, and continuing to observe and collect *that*
12820/// stays a different piece of work with its own owner. This only narrows a
12821/// fixed blind wait into an actual check of the pids this process does know
12822/// about.
12823async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12824    wait_for_pids_with(
12825        pids,
12826        crate::proc::pid_alive,
12827        LEASE_RELEASE_POLL,
12828        LEASE_RELEASE_MAX_WAIT,
12829    )
12830    .await;
12831}
12832
12833/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12834/// interval and ceiling supplied by the caller, so the polling *logic* -
12835/// returns as soon as every pid reports dead, gives up at the ceiling
12836/// otherwise - is testable on millisecond durations without asking the real
12837/// OS about a pid at all.
12838async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12839    pids: &[u32],
12840    alive: F,
12841    poll: Duration,
12842    max_wait: Duration,
12843) {
12844    let deadline = Instant::now() + max_wait;
12845    loop {
12846        if pids.iter().all(|&pid| !alive(pid)) {
12847            return;
12848        }
12849        if Instant::now() >= deadline {
12850            return;
12851        }
12852        tokio::time::sleep(poll).await;
12853    }
12854}
12855
12856/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12857/// admission that it could not even get a verify command to run, as opposed
12858/// to evidence the command actually produced? A caller that would otherwise
12859/// read a resource-blocked outcome as a red command must check this first:
12860/// see [`Runner::gate`], which retries rather than records `Blocked` when
12861/// this is true.
12862fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12863    outcomes.iter().any(|o| o.resource_blocked)
12864}
12865
12866/// What [`Runner::gate_fix_round`] decided.
12867pub(crate) enum GateFix {
12868    /// The tree changed and `verify.e2e` is still green: run the gate again.
12869    Retry,
12870    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12871    /// last failure stands and the run ends blocked.
12872    Stop,
12873    /// `verify.e2e` could not run after the fix (magi's own contention):
12874    /// decide nothing now, a later reentry retries.
12875    Defer,
12876}
12877
12878/// Is every red command in `outcomes` an ordinary failure the code could
12879/// explain: it ran, exited non-zero, and said something?
12880///
12881/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12882/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12883/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12884/// what the command is stays the gate's business.
12885pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12886    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12887    red.peek().is_some()
12888        && red.all(|o| {
12889            !o.resource_blocked
12890                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12891                && !o.output_tail.trim().is_empty()
12892        })
12893}
12894
12895/// Describe one verify command's outcome for the event log, distinguishing a
12896/// build/link failure — the toolchain never produced a binary to run — from
12897/// an actual test failure, since only the latter is a verdict on the patch.
12898fn e2e_outcome_label(o: &CommandOutcome) -> String {
12899    if o.ok() {
12900        return "pass".to_owned();
12901    }
12902    let reason = if o.build_failed() {
12903        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12904    } else {
12905        format!("FAIL ({:?})", o.code)
12906    };
12907    format!(
12908        "{reason}\n{}",
12909        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12910    )
12911}
12912
12913/// Does `outcomes` hold a failure worth one more run on the same commit?
12914///
12915/// Only an ordinary test result qualifies: every red command ran, exited
12916/// non-zero and said which way (not a build/link failure, a timeout or kill,
12917/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12918/// evidence about the machine or the toolchain, never about a flaky test.
12919fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12920    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12921    red.peek().is_some()
12922        && !verify_inconclusive(outcomes)
12923        && red.all(|o| {
12924            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12925        })
12926}
12927
12928/// Run `verify.e2e`, retrying once if the first attempt could not build or
12929/// link — a build/link failure is frequently a race against a shared
12930/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12931/// `verify` event per command, tagged with `context` (normally `"round N"`)
12932/// so the call sites that need this — the ordinary per-round leg in
12933/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12934/// will ever call a round green, `verify_current_head` and the gate-repair
12935/// check — read identically in the event log.
12936///
12937/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12938/// only after the failed commands have run once more on the same commit, in
12939/// the same worktree and — because the caller holds it around this whole
12940/// function — under the same cache lease, with a full `timeout` of their own
12941/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12942/// flake: the head is verified, the first failure is recorded and filed
12943/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12944/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
12945/// preserving bounded evidence and artifact references for both attempts;
12946/// it claims a matching reproduction only when both attempts yield identical
12947/// confirmed terminal test failures. One verification is therefore run at most
12948/// three times: the build/link retry, then this one rerun. `round` is the
12949/// review round the verification belongs to, if any.
12950async fn run_e2e_with_retry(
12951    state: &mut RunState,
12952    shell: &[String],
12953    commands: &[String],
12954    worktree: &Path,
12955    timeout: Duration,
12956    context: &str,
12957    round: Option<usize>,
12958) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12959    let (mut e2e, mut timed_out_pids) = run_commands(
12960        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12961    )
12962    .await;
12963    for o in &e2e {
12964        state.event(
12965            "verify",
12966            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12967        );
12968    }
12969    // A build/link failure is not a verdict on the patch — it is frequently a
12970    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12971    // one retry before letting a red like that decide the round.
12972    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12973    if verify_retried {
12974        state.event(
12975            "verify",
12976            format!(
12977                "{context}: verify could not build/link, not a test result — retrying once \
12978                 before concluding"
12979            ),
12980        );
12981        let retried = run_commands(
12982            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12983        )
12984        .await;
12985        e2e = retried.0;
12986        // Both attempts' timeouts matter, not just the last one: the first
12987        // attempt's descendants may still be alive alongside the retry's.
12988        timed_out_pids.extend(retried.1);
12989        for o in &e2e {
12990            state.event(
12991                "verify",
12992                format!(
12993                    "{context}: retry `{}` -> {}",
12994                    o.command,
12995                    e2e_outcome_label(o)
12996                ),
12997            );
12998        }
12999    }
13000    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
13001        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
13002        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
13003        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
13004        state.event(
13005            "verify",
13006            format!(
13007                "{context}: {} failed with a test result — running it once more on the same \
13008                 commit {} before deciding",
13009                rerun_commands
13010                    .iter()
13011                    .map(|c| format!("`{c}`"))
13012                    .collect::<Vec<_>>()
13013                    .join(", "),
13014                short(&head)
13015            ),
13016        );
13017        let (second, pids) = run_commands(
13018            state,
13019            "verify",
13020            "e2e",
13021            1 + usize::from(verify_retried),
13022            shell,
13023            &rerun_commands,
13024            worktree,
13025            timeout,
13026        )
13027        .await;
13028        timed_out_pids.extend(pids);
13029        for o in &second {
13030            state.event(
13031                "verify",
13032                format!(
13033                    "{context}: rerun `{}` -> {}",
13034                    o.command,
13035                    e2e_outcome_label(o)
13036                ),
13037            );
13038        }
13039        for (slot, &i) in failed.iter().enumerate() {
13040            let Some(again) = second.get(slot) else {
13041                break;
13042            };
13043            let first = std::mem::replace(&mut e2e[i], again.clone());
13044            if again.ok() {
13045                let signature = crate::flake::signature(&first.output_tail, first.code);
13046                let flake = crate::run::VerifyFlake {
13047                    round,
13048                    context: context.to_owned(),
13049                    head: head.clone(),
13050                    command: first.command.clone(),
13051                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
13052                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
13053                    at: Timestamp::now(),
13054                    task: None,
13055                    filed: false,
13056                    filing_error: None,
13057                };
13058                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
13059            } else if !again.resource_blocked {
13060                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
13061                let message = crate::verify_evidence::rerun_event_message(
13062                    context,
13063                    &e2e[i].command,
13064                    &comparison,
13065                );
13066                e2e[i].rerun_comparison = Some(comparison);
13067                state.event("verify", message);
13068            }
13069        }
13070    }
13071    (e2e, verify_retried, timed_out_pids)
13072}
13073
13074/// Run configured shell commands in `cwd`, in order. The second element is
13075/// the pid of every command that hit `timeout` and was still running when
13076/// this stopped waiting on it (best-effort: `None` when the platform did not
13077/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13078/// that releases a shared resource afterward needs to know.
13079///
13080/// Records `task` into [`RunState::active`] at every command boundary
13081/// (`RunState::task_command`) and clears it once the whole list has run
13082/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13083/// for minutes with no seat and no output of its own to show for it (see
13084/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13085/// apart from "not yet run" without this), and this is the only place that
13086/// knows which command is running right now and how many are left. Three
13087/// saves per command — start, not per second — matching the same "only at a
13088/// boundary" rule [`wave`] already follows for seats.
13089#[allow(clippy::too_many_arguments)]
13090async fn run_commands(
13091    state: &mut RunState,
13092    node: &str,
13093    task: &str,
13094    attempt: usize,
13095    shell: &[String],
13096    commands: &[String],
13097    cwd: &Path,
13098    timeout: Duration,
13099) -> (Vec<CommandOutcome>, Vec<u32>) {
13100    let isolated = crate::build_target::isolated(&state.config);
13101    if isolated && let Some(block) = &state.resource_block {
13102        return (
13103            vec![CommandOutcome {
13104                command: "(isolated build admission)".into(),
13105                code: None,
13106                output_tail: block.description(),
13107                duration_ms: 0,
13108                resource_blocked: true,
13109                ..Default::default()
13110            }],
13111            Vec::new(),
13112        );
13113    }
13114    if commands.is_empty() {
13115        // Nothing to mark as running and nothing to clear — an empty list
13116        // means "not configured", and touching `active` (or the disk) over
13117        // that would be a write for every round of a repo with no
13118        // `verify.e2e` / `verify.gate` commands at all.
13119        return (Vec::new(), Vec::new());
13120    }
13121    let mut out = Vec::new();
13122    let mut timed_out_pids = Vec::new();
13123    let total = commands.len();
13124    for (idx, command) in commands.iter().enumerate() {
13125        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13126        if let Err(e) = state.save() {
13127            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13128        }
13129        let started = Instant::now();
13130        let mut cmd = tokio::process::Command::new(&shell[0]);
13131        cmd.quiet();
13132        // Verify the checkout as a standalone caller. Worker ownership and
13133        // pinned executable selection belong to this driver, not to tests or
13134        // tools it runs. Preserve home/seat context and Running's containment.
13135        for key in crate::worker::INVOCATION_ENV {
13136            cmd.env_remove(key);
13137        }
13138        cmd.env_remove(crate::build_id::EXPECT_ENV);
13139        cmd.args(&shell[1..])
13140            .current_dir(cwd)
13141            .stdin(std::process::Stdio::null())
13142            .stdout(std::process::Stdio::piped())
13143            .stderr(std::process::Stdio::piped())
13144            .kill_on_drop(true);
13145        let mut outputs = Vec::new();
13146        let mut cache = None;
13147        let home = crate::run::home();
13148        let head = if isolated {
13149            Some(git::rev_parse(cwd, "HEAD").await)
13150        } else {
13151            None
13152        };
13153        let protected = (|| -> Result<()> {
13154            crate::incremental::configure(&mut cmd, cwd)?;
13155            cache = if isolated {
13156                let target = VERIFY_TARGET
13157                    .try_with(Clone::clone)
13158                    .context("isolated verification has no target lease")?;
13159                cmd.arg(crate::build_target::command::normalize(command)?);
13160                crate::build_target::command::configure(&mut cmd, &target)?;
13161                Some(target)
13162            } else {
13163                crate::build_target::command::clear(&mut cmd)?;
13164                cmd.arg(command);
13165                state.config.cache_dir()
13166            };
13167            let mut paths = vec![cwd.to_owned()];
13168            if let Some(cache) = &cache {
13169                paths.push(cache.clone());
13170            }
13171            let admit = if isolated {
13172                crate::retention::OutputLease::admit_isolated
13173            } else {
13174                crate::retention::OutputLease::admit
13175            };
13176            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13177            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13178                outputs.push(guard);
13179            }
13180            if let Some(cache) = &cache {
13181                outputs.push(crate::retention::OutputLease::cache(
13182                    &crate::run::home(),
13183                    cache,
13184                    false,
13185                )?);
13186                if let Some(head) = head {
13187                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13188                    if task == "pre_gate" {
13189                        crate::cache::invalidate_identity(&home, cache);
13190                    }
13191                }
13192            }
13193            Ok(())
13194        })();
13195        if let Err(e) = protected {
13196            let detail = format!("execution admission unavailable: {e:#}");
13197            state.resource_block = Some(crate::run::ResourceBlock {
13198                cause: crate::run::ResourceBlockCause::Other,
13199                node: node.to_owned(),
13200                kind: if detail.contains("disk admission") {
13201                    "disk admission"
13202                } else {
13203                    "output ownership"
13204                }
13205                .to_owned(),
13206                detail: detail.clone(),
13207                at: Timestamp::now(),
13208            });
13209            out.push(CommandOutcome {
13210                command: command.clone(),
13211                code: None,
13212                output_tail: detail,
13213                duration_ms: 0,
13214                resource_blocked: true,
13215                ..Default::default()
13216            });
13217            break;
13218        }
13219        let spawned = if isolated {
13220            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13221        } else {
13222            crate::seat_process::Running::spawn(cmd, None, outputs)
13223        };
13224        let (code, out_text, err_text, body) = match spawned {
13225            Ok(mut running) => {
13226                let pid = running.child().id();
13227                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13228                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13229                let mut paths = vec![cwd.to_owned()];
13230                if let Some(cache) = cache {
13231                    paths.push(cache);
13232                }
13233                let mut pressure = None;
13234                let status = tokio::select! {
13235                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13236                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13237                        pressure = Some(reason); None
13238                    }
13239                };
13240                let (code, failure) = match status {
13241                    Some(Ok(Ok(status))) => (
13242                        status.code(),
13243                        status
13244                            .code()
13245                            .is_none()
13246                            .then(|| format!("command terminated: {status}")),
13247                    ),
13248                    Some(Ok(Err(error))) => {
13249                        (None, Some(format!("failed waiting for command: {error}")))
13250                    }
13251                    Some(Err(_)) => {
13252                        // Leased cleanup confirms process-tree death itself.
13253                        // Unleased commands still need the caller's PID check
13254                        // after kill-on-drop, before releasing cache ownership.
13255                        if !running.coordinated()
13256                            && let Some(pid) = pid
13257                        {
13258                            timed_out_pids.push(pid);
13259                        }
13260                        (
13261                            None,
13262                            Some(format!("timed out after {}s", timeout.as_secs())),
13263                        )
13264                    }
13265                    None => (None, None),
13266                };
13267                running.finish().await;
13268                if let Some(reason) = pressure {
13269                    state.resource_block = Some(crate::run::ResourceBlock {
13270                        cause: crate::run::ResourceBlockCause::Other,
13271                        node: node.to_owned(),
13272                        kind: "disk pressure".to_owned(),
13273                        detail: reason.clone(),
13274                        at: Timestamp::now(),
13275                    });
13276                    out.push(CommandOutcome {
13277                        command: command.clone(),
13278                        code: None,
13279                        output_tail: reason,
13280                        duration_ms: started.elapsed().as_millis() as u64,
13281                        resource_blocked: true,
13282                        ..Default::default()
13283                    });
13284                    break;
13285                }
13286                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13287                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13288                let mut body = out_text.clone();
13289                body.push_str(&err_text);
13290                if let Some(failure) = failure {
13291                    body.push('\n');
13292                    body.push_str(&failure);
13293                }
13294                (code, out_text, err_text, body)
13295            }
13296            Err(e) if isolated => {
13297                let e = anyhow::Error::new(e)
13298                    .context(format!("could not start managed build `{}`", shell[0]));
13299                record_cache_error(state, node, &e);
13300                out.push(CommandOutcome {
13301                    command: command.clone(),
13302                    code: None,
13303                    output_tail: format!("{e:#}"),
13304                    duration_ms: 0,
13305                    resource_blocked: true,
13306                    ..Default::default()
13307                });
13308                break;
13309            }
13310            Err(e) => (
13311                None,
13312                String::new(),
13313                String::new(),
13314                format!("failed to spawn `{}`: {e}", shell[0]),
13315            ),
13316        };
13317        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13318        let mut artifact = None;
13319        if !body.is_empty() {
13320            // The full text is kept whatever the summary dropped. A fresh
13321            // name per command so a resume or retry never overwrites an
13322            // earlier run's output. A failed write changes no verdict.
13323            match crate::run::write_verification_artifact(state, task, &body) {
13324                Ok(name) => {
13325                    let rel = format!("artifacts/{name}");
13326                    if summary != body {
13327                        summary = format!("[full output: {rel}]\n{summary}");
13328                    }
13329                    artifact = Some(rel);
13330                }
13331                Err(e) => {
13332                    let warning = format!("could not save the full {task} output: {e:#}");
13333                    tracing::warn!("{warning}");
13334                    state.event(node, warning);
13335                    if summary != body {
13336                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13337                    }
13338                }
13339            }
13340        }
13341        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13342        let mut outcome = CommandOutcome {
13343            command: command.clone(),
13344            code,
13345            output_tail: summary,
13346            duration_ms: started.elapsed().as_millis() as u64,
13347            resource_blocked,
13348            artifact,
13349            failure_evidence: None,
13350            rerun_comparison: None,
13351        };
13352        if !outcome.ok() && !outcome.resource_blocked {
13353            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13354                code,
13355                outcome.build_failed(),
13356                &out_text,
13357                &err_text,
13358            ));
13359        }
13360        out.push(outcome);
13361        if resource_blocked {
13362            state.resource_block = Some(crate::run::ResourceBlock {
13363                cause: crate::run::ResourceBlockCause::Other,
13364                node: node.to_owned(),
13365                kind: "incremental cache admission".into(),
13366                detail: body,
13367                at: Timestamp::now(),
13368            });
13369            break;
13370        }
13371    }
13372    state.task_finished(task);
13373    if let Err(e) = state.save() {
13374        tracing::warn!("could not persist the end of {task}: {e:#}");
13375    }
13376    (out, timed_out_pids)
13377}
13378
13379/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13380/// section (`report::run`) and in the `merge` event this node records — for
13381/// the operator to run by hand.
13382///
13383/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13384/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13385/// merge commits", or "require linear history") rejects the push a `--no-ff`
13386/// merge would produce, which is exactly the guidance this function replaces.
13387/// `message`'s first line becomes the squash commit's subject, matching the
13388/// note `report::run` prints alongside this command — see that function for
13389/// why an explicit subject is not optional there.
13390fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13391    let repo = repo.display();
13392    match style {
13393        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13394        MergeStyle::Squash => {
13395            // The subject sits inside double quotes, and a title an agent
13396            // wrote may carry the characters that break out of them.
13397            let subject = message
13398                .lines()
13399                .next()
13400                .unwrap_or(branch)
13401                .replace(['\\', '"', '$', '`'], "");
13402            format!(
13403                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13404            )
13405        }
13406        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13407    }
13408}
13409
13410/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13411/// under the hood, rejects a `title` over 256 characters and the whole
13412/// command fails — no PR at all, for a run whose body was otherwise fine
13413/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13414/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13415/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13416/// this bound. It is a margin, not a guarantee — a title packed
13417/// with multi-unit characters could still in principle land close to the
13418/// edge, but a real task title's occasional emoji or accented letter fits
13419/// comfortably inside it.
13420const PR_TITLE_MAX: usize = 240;
13421
13422/// A pull request title from the opening line of `text`, or `None` when that
13423/// line is not English (GitHub text is) or has no letters.
13424///
13425/// A line within `max` is kept as is. A longer one is cut at the end of its
13426/// first sentence when that falls inside `max`, else at a word boundary with a
13427/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13428/// make every merely-truncated title look non-English). The language check
13429/// runs on the kept text before any mark is added, so only what GitHub will
13430/// show is judged: an English opening followed by non-ASCII far past the cut
13431/// still passes.
13432fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13433    let line = queue::first_line(text)?;
13434    let chars: Vec<char> = line.chars().collect();
13435    let (kept, mark) = if chars.len() <= max {
13436        (line.to_owned(), "")
13437    } else if let Some(end) = sentence_end(&chars, max) {
13438        (chars[..end].iter().collect::<String>(), "")
13439    } else {
13440        let room = max.saturating_sub(3);
13441        // Cut at the last space inside the room; when the char just past the
13442        // room is a space the room already ends on a word.
13443        let cut = if chars[room].is_whitespace() {
13444            room
13445        } else {
13446            chars[..room]
13447                .iter()
13448                .rposition(|c| c.is_whitespace())
13449                .unwrap_or(room)
13450        };
13451        let head: String = chars[..cut].iter().collect();
13452        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13453        (head.to_owned(), "...")
13454    };
13455    if kept.is_empty() {
13456        return None;
13457    }
13458    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13459        return None;
13460    }
13461    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13462        return None;
13463    }
13464    Some(format!("{kept}{mark}"))
13465}
13466
13467/// The char length of the first sentence of `chars` when it ends within `max`
13468/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13469/// abbreviations so `e.g. foo` does not end a title early.
13470fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13471    const MIN: usize = 20;
13472    for i in MIN..max.min(chars.len()) {
13473        if !matches!(chars[i], '.' | '!' | '?') {
13474            continue;
13475        }
13476        let Some(&next) = chars.get(i + 1) else {
13477            continue;
13478        };
13479        if !next.is_whitespace() {
13480            continue;
13481        }
13482        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13483        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13484            continue;
13485        }
13486        let word: String = chars[..i]
13487            .iter()
13488            .rev()
13489            .take_while(|c| !c.is_whitespace())
13490            .collect::<Vec<_>>()
13491            .into_iter()
13492            .rev()
13493            .collect();
13494        let word = word.to_ascii_lowercase();
13495        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13496            continue;
13497        }
13498        let end = chars[..i]
13499            .iter()
13500            .rposition(|c| !c.is_whitespace())
13501            .map_or(i, |p| p + 1);
13502        return Some(end);
13503    }
13504    None
13505}
13506
13507/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13508/// change: a title and a body describing what was *implemented*, not the task
13509/// that asked for it. A task reads as a request; a reader of the merged
13510/// history wants the change.
13511struct PrMessage {
13512    title: String,
13513    body: String,
13514}
13515
13516impl PrMessage {
13517    /// Title, blank line, body. The first line is the squash/merge commit
13518    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13519    /// has to stay one sensible line.
13520    fn commit_message(&self) -> String {
13521        format!("{}\n\n{}", self.title, self.body)
13522    }
13523}
13524
13525/// The text after a leading `TITLE:` (any case) on `line`.
13526fn title_marker(line: &str) -> Option<&str> {
13527    let line = line.trim();
13528    let head = line.get(..6)?;
13529    head.eq_ignore_ascii_case("title:")
13530        .then(|| line[6..].trim())
13531}
13532
13533/// The implementer's own one-line title: the `TITLE:` line the implement
13534/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13535/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13536/// source, and a title that says as much is refused here too.
13537fn summary_title(summary: &str) -> Option<String> {
13538    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13539    let raw = title_marker(first)?;
13540    if raw.is_empty() {
13541        return None;
13542    }
13543    let title = queue::title_from(raw, PR_TITLE_MAX);
13544    let lower = title.to_ascii_lowercase();
13545    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13546        return None;
13547    }
13548    Some(title)
13549}
13550
13551/// How `open_review`'s instruction begins; see [`landing_title`].
13552const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13553
13554/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13555pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13556
13557/// Does this run review work that already existed, rather than implement a
13558/// task? Runs recorded before `reviewed_commits` existed carry only the
13559/// candidate marker.
13560pub(crate) fn is_review_run(state: &RunState) -> bool {
13561    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13562}
13563
13564/// The title of a review-only run: the subject of the oldest commit under
13565/// review. Later commits are usually fixups, and `instruction` is the review
13566/// prompt, which says nothing about the change. GitHub text is English, so a
13567/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13568fn review_title(state: &RunState) -> Option<String> {
13569    english_subject(
13570        state.reviewed_commits.as_ref()?.first()?,
13571        state.config.graph.github_english(),
13572    )
13573}
13574
13575/// `raw` as a pull request title, or `None` when it is blank, not English
13576/// (GitHub text is), or one of magi's own candidate commit subjects.
13577fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13578    let raw = raw.trim();
13579    if raw.is_empty() {
13580        return None;
13581    }
13582    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13583        return None;
13584    }
13585    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13586        return None;
13587    }
13588    let title = queue::title_from(raw, PR_TITLE_MAX);
13589    let lower = title.to_ascii_lowercase();
13590    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13591        return None;
13592    }
13593    Some(title)
13594}
13595
13596/// What a review-only run's branch says about itself, read at the moment the
13597/// pull request is opened.
13598#[derive(Debug, Clone, PartialEq, Eq)]
13599struct BranchFacts {
13600    /// `(subject, body)` of each commit, oldest first.
13601    commits: Vec<(String, String)>,
13602    /// Trimmed `git diff --stat`.
13603    stat: String,
13604}
13605
13606/// Longest diff stat shown: this many file lines plus the summary line.
13607const STAT_FILE_LINES: usize = 25;
13608/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13609const COMMITS_MAX_CHARS: usize = 20_000;
13610
13611/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13612/// say or finds nothing, so the caller falls back to what the run recorded.
13613async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13614    let commits = git::commit_log(repo, base, branch).await.ok()?;
13615    if commits.is_empty() {
13616        return None;
13617    }
13618    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13619    let lines: Vec<&str> = stat.lines().collect();
13620    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13621        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13622        let more = format!(" ... {omitted} more file(s)");
13623        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13624        kept.push(&more);
13625        kept.push(lines[lines.len() - 1]);
13626        kept.join("\n")
13627    } else {
13628        lines.join("\n")
13629    };
13630    Some(BranchFacts { commits, stat })
13631}
13632
13633/// Defang what would break the surrounding markdown: a closing `</details>`
13634/// and a code fence.
13635fn markdown_safe(text: &str) -> String {
13636    text.replace("</details>", "&lt;/details&gt;")
13637        .replace("\x60\x60\x60", "~~~")
13638}
13639
13640fn neutral_title(state: &RunState, winner: char) -> String {
13641    format!(
13642        "chore: land candidate {} of run {}",
13643        winner.to_ascii_uppercase(),
13644        state.id
13645    )
13646}
13647
13648/// Reuse the graph's bounded fixer without starting another graph or driver.
13649/// Copy the working state back even on errors so spent rounds remain visible.
13650pub(crate) async fn repair_landing_gate(
13651    state: &mut RunState,
13652    winner: &Candidate,
13653    outcomes: &[CommandOutcome],
13654) -> Result<GateFix> {
13655    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13656        return Ok(GateFix::Stop);
13657    }
13658    let mut runner = Runner {
13659        roles: state.config.resolve_roles()?,
13660        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13661        state: state.clone(),
13662        pause: Pause::new(),
13663        interrupt: Pause::new(),
13664    };
13665    let result = runner.gate_fix_round(winner, outcomes).await;
13666    *state = runner.state;
13667    result
13668}
13669
13670/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13671/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13672pub(crate) async fn verify_current_head(
13673    state: &mut RunState,
13674    winner: &Candidate,
13675    wait: &crate::repo_lock::WaitPolicy,
13676) -> Result<bool> {
13677    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13678    // Preserve the previous record before replacing it, including on crash recovery.
13679    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13680        state
13681            .verification_history
13682            .push(crate::run::VerificationEvidence {
13683                superseded_by: Some(head.clone()),
13684                archived_at: Some(Timestamp::now()),
13685                fixes_spent: Some(state.gate_fixes.len()),
13686                gate_head: None,
13687                gate_ran: false,
13688                gate: Vec::new(),
13689                e2e: state.head_e2e.take(),
13690            });
13691    }
13692    if let Some(e) = &state.head_e2e
13693        && e.head == head
13694    {
13695        if e.passed {
13696            return Ok(true);
13697        }
13698        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13699            state.status = RunStatus::Blocked;
13700            state.save()?;
13701            return Ok(false);
13702        }
13703    } else if state.reviews.last().is_some_and(|r| {
13704        r.verified_head.as_deref() == Some(head.as_str())
13705            && (r.e2e_status() == E2eStatus::Passed
13706                || (r.e2e_status() == E2eStatus::NotConfigured
13707                    && state.config.verify.e2e.is_empty()))
13708    }) || state
13709        .gate_repair_e2e
13710        .as_ref()
13711        .is_some_and(|e| e.head == head && e.passed)
13712    {
13713        return Ok(true);
13714    }
13715    if let Some(e) = &state.gate_repair_e2e
13716        && e.head == head
13717        && !e.passed
13718        && !e.outcomes.is_empty()
13719        && !verify_inconclusive(&e.outcomes)
13720    {
13721        state.status = RunStatus::Blocked;
13722        state.save()?;
13723        return Ok(false);
13724    }
13725    // Bind the result to the base used by the candidate, not a tracking ref
13726    // that the background fetch can advance independently of verification.
13727    let base_commit = state
13728        .base_sync
13729        .as_ref()
13730        .map(|s| s.tip.clone())
13731        .filter(|tip| !tip.is_empty())
13732        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13733    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13734        head.clone(),
13735        false,
13736        Vec::new(),
13737    ));
13738    state.save()?;
13739    let commands = state.config.verify.e2e.clone();
13740    let shell = state.config.shell();
13741    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13742    let cache_dir = state.config.cache_dir();
13743    let outcomes = if commands.is_empty() {
13744        Vec::new()
13745    } else {
13746        let (outcomes, _) = with_cache_lease(
13747            state,
13748            cache_dir.as_deref(),
13749            "e2e",
13750            "e2e",
13751            &winner.worktree,
13752            &head,
13753            timeout,
13754            "current head e2e",
13755            wait,
13756            |state, budget| async move {
13757                run_e2e_with_retry(
13758                    state,
13759                    &shell,
13760                    &commands,
13761                    &winner.worktree,
13762                    budget,
13763                    "current head e2e",
13764                    None,
13765                )
13766                .await
13767            },
13768        )
13769        .await?;
13770        outcomes
13771    };
13772    let unresolved = verify_inconclusive(&outcomes);
13773    let passed = !unresolved
13774        && outcomes.iter().all(CommandOutcome::ok)
13775        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13776    if !outcomes.is_empty() && !unresolved {
13777        state.record_base_progress(&head);
13778    }
13779    let generation = Some(state.verification_history.len());
13780    let pass = state.passes.last().map(|p| p.index);
13781    let recorded_at = Some(Timestamp::now());
13782    let resumption_generation = state.entry_resumption_generation;
13783    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
13784    record.base_commit = base_commit;
13785    record.generation = generation;
13786    record.pass = pass;
13787    record.recorded_at = recorded_at;
13788    record.resumption_generation = resumption_generation;
13789    if !passed && !unresolved {
13790        let detail = state
13791            .head_e2e
13792            .as_ref()
13793            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13794            .map(|d| format!(" ({d})"))
13795            .unwrap_or_default();
13796        state.status = RunStatus::Blocked;
13797        state.event(
13798            "e2e",
13799            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13800        );
13801        record.recorded_events = Some(state.events.len());
13802    }
13803    state.head_e2e = Some(record);
13804    state.save()?;
13805    Ok(passed)
13806}
13807
13808/// Recheck a repair's e2e requirement across failures, resource deferrals and
13809/// process interruptions. A successful result only applies to its exact SHA.
13810pub(crate) async fn check_gate_repair_e2e(
13811    state: &mut RunState,
13812    winner: &Candidate,
13813    wait: &crate::repo_lock::WaitPolicy,
13814) -> Result<GateFix> {
13815    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13816        return Ok(GateFix::Retry);
13817    }
13818    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13819    if let Some(record) = &state.gate_repair_e2e
13820        && record.head == head
13821    {
13822        if record.passed {
13823            return Ok(GateFix::Retry);
13824        }
13825        if !record.outcomes.is_empty()
13826            && record.outcomes.iter().all(|o| {
13827                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13828            })
13829        {
13830            return Ok(GateFix::Stop);
13831        }
13832    }
13833    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
13834        head.clone(),
13835        false,
13836        Vec::new(),
13837    ));
13838    state.save()?;
13839    let commands = state.config.verify.e2e.clone();
13840    let outcomes = if commands.is_empty() {
13841        Vec::new()
13842    } else {
13843        let shell = state.config.shell();
13844        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13845        let cache_dir = state.config.cache_dir();
13846        let (outcomes, _) = with_cache_lease(
13847            state,
13848            cache_dir.as_deref(),
13849            "e2e",
13850            "e2e",
13851            &winner.worktree,
13852            &head,
13853            timeout,
13854            "gate repair e2e",
13855            wait,
13856            |state, budget| async move {
13857                run_e2e_with_retry(
13858                    state,
13859                    &shell,
13860                    &commands,
13861                    &winner.worktree,
13862                    budget,
13863                    "gate repair e2e",
13864                    None,
13865                )
13866                .await
13867            },
13868        )
13869        .await?;
13870        outcomes
13871    };
13872    let deferred = verify_inconclusive(&outcomes);
13873    let passed = outcomes.iter().all(CommandOutcome::ok)
13874        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13875    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
13876    state.save()?;
13877    if deferred {
13878        Ok(GateFix::Defer)
13879    } else if !passed {
13880        let detail = state
13881            .gate_repair_e2e
13882            .as_ref()
13883            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13884            .map(|d| format!(" ({d})"))
13885            .unwrap_or_default();
13886        state.event(
13887            "gate",
13888            format!("verify.e2e failed after gate repair{detail}; nothing published"),
13889        );
13890        Ok(GateFix::Stop)
13891    } else {
13892        Ok(GateFix::Retry)
13893    }
13894}
13895
13896/// Run the same configured gate for a landing head and a fresh graph.
13897pub(crate) async fn run_landing_gate(
13898    state: &mut RunState,
13899    winner: &Candidate,
13900    wait: &crate::repo_lock::WaitPolicy,
13901) -> Result<Vec<CommandOutcome>> {
13902    let shell = state.config.shell();
13903    let gate_commands = state.config.verify.gate.clone();
13904    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13905    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13906        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13907        Vec::new()
13908    } else {
13909        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13910        let cache_dir = state.config.cache_dir();
13911        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13912        let (outcomes, _) = with_cache_lease(
13913            state,
13914            cache_dir.as_deref(),
13915            "gate",
13916            "gate",
13917            &winner.worktree,
13918            &head,
13919            timeout,
13920            "final gate",
13921            wait,
13922            |state, budget| {
13923                let shell = shell.clone();
13924                let gate_commands = gate_commands.clone();
13925                let winner = winner.clone();
13926                async move {
13927                    Runner::run_pre_gate(state, &winner).await;
13928                    // Bind command evidence after mechanical fixes, before commands start.
13929                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13930                    let (outcomes, timed_out_pids) = run_commands(
13931                        state,
13932                        "gate",
13933                        "gate",
13934                        0,
13935                        &shell,
13936                        &gate_commands,
13937                        &winner.worktree,
13938                        budget,
13939                    )
13940                    .await;
13941                    (outcomes, false, timed_out_pids)
13942                }
13943            },
13944        )
13945        .await?;
13946        outcomes
13947    };
13948    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13949    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13950        let mut outcomes = outcomes;
13951        outcomes.push(CommandOutcome {
13952            command: "gate head stability".into(), code: None,
13953            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13954            duration_ms: 0, resource_blocked: false,
13955            ..Default::default()
13956        });
13957        return Ok(outcomes);
13958    }
13959    if outcomes.is_empty() {
13960        // Nothing configured to check — distinct from every other
13961        // silence in this run's event log, since an empty `gate` alone
13962        // no longer says whether the gate ran at all (see
13963        // `RunState::gate_ran`'s own doc).
13964        state.event("gate", "no gate commands configured; not tested");
13965    }
13966    for o in &outcomes {
13967        state.event(
13968            "gate",
13969            format!(
13970                "`{}` -> {}",
13971                o.command,
13972                if o.ok() {
13973                    "pass".to_owned()
13974                } else {
13975                    format!(
13976                        "FAIL ({:?})\n{}",
13977                        o.code,
13978                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13979                    )
13980                }
13981            ),
13982        );
13983    }
13984    Ok(outcomes)
13985}
13986
13987/// The pull request title to hand to `land::merge_subject`. A review-only run
13988/// opened by an earlier build titled its pull request with the review prompt;
13989/// that title is dropped (empty, so the fallback applies) rather than landed.
13990/// Any other title, including an operator's rename, passes through untouched,
13991/// and so does every title of a run that implements a task.
13992pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13993    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13994        ""
13995    } else {
13996        pr_title
13997    }
13998}
13999
14000/// What the squash subject falls back to when the pull request title is empty
14001/// or candidate-shaped: for a review-only run the derived title, never the
14002/// review prompt held in `instruction`.
14003pub fn landing_subject_source(state: &RunState) -> String {
14004    if is_review_run(state) {
14005        let winner = state.candidates.first().map_or('A', |c| c.label);
14006        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
14007    }
14008    state.instruction.clone()
14009}
14010
14011/// `summary` without its `TITLE:` line, which the pull request title already
14012/// carries.
14013fn summary_without_title(summary: &str) -> String {
14014    let mut lines = summary.trim().lines().peekable();
14015    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
14016        lines.next();
14017    }
14018    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
14019}
14020
14021/// The pull request title and body for the winning candidate.
14022///
14023/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
14024/// the task's own opening line via [`queue::title_from`] when there is none.
14025/// `state.instruction` can open with blank lines (`task_text` only rejects a
14026/// body that is blank *entirely*), which `title_from` skips.
14027///
14028/// Publishing uses an independent description generated from the final diff
14029/// and structured evidence. Internal summaries and reports remain local.
14030/// Non-publishing previews may display the original task and candidate summary.
14031/// The footer retains the run and candidate provenance.
14032#[cfg(test)]
14033fn pr_message(state: &RunState, winner: char) -> PrMessage {
14034    pr_message_with(state, winner, None)
14035}
14036
14037/// [`pr_message`] with what the branch of a review-only run says about itself.
14038/// `facts` is ignored for a run that implements a task.
14039#[cfg(test)]
14040fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
14041    let raw = pr_message_raw(
14042        state,
14043        winner,
14044        facts,
14045        crate::pr_outcome::FinalHead::Unreported,
14046        ChangeNote::NotAsked,
14047    );
14048    let id = crate::scrub::Identity::current();
14049    PrMessage {
14050        title: crate::scrub::scrub(&raw.title, &id),
14051        body: crate::scrub::scrub(&raw.body, &id),
14052    }
14053}
14054
14055/// What the public description may say about the change itself.
14056#[derive(Debug, Clone, Copy)]
14057enum ChangeNote<'a> {
14058    /// A local preview or non-publishing merge mode: no public generation needed.
14059    NotAsked,
14060    /// A summary written from the final diff.
14061    Summary(&'a crate::run::ChangeSummary),
14062    /// A summary was asked for and could not be produced; the text says why.
14063    Unavailable(&'a str),
14064}
14065
14066fn pr_message_raw(
14067    state: &RunState,
14068    winner: char,
14069    facts: Option<&BranchFacts>,
14070    head: crate::pr_outcome::FinalHead<'_>,
14071    change: ChangeNote<'_>,
14072) -> PrMessage {
14073    if !matches!(change, ChangeNote::NotAsked) {
14074        let (title, mut body) = match change {
14075            ChangeNote::Summary(c) => (
14076                c.title.clone(),
14077                format!("## Summary\n\n{}\n\n", c.body.trim()),
14078            ),
14079            ChangeNote::Unavailable(why) => (
14080                neutral_title(state, winner),
14081                format!(
14082                    "## Summary\n\nNo description of what this change does could be generated ({why}). Review the final diff; internal reports remain in local records.\n\n"
14083                ),
14084            ),
14085            ChangeNote::NotAsked => unreachable!(),
14086        };
14087        body.push_str(&public_pr_evidence(state, head));
14088        body.push_str(&format!(
14089            "\n---\nmagi:run/{} magi:candidate-{}\n",
14090            state.id,
14091            winner.to_ascii_lowercase()
14092        ));
14093        return PrMessage { title, body };
14094    }
14095    pr_preview(state, winner, facts, head)
14096}
14097
14098/// Append public facts from the run records after every prose generation,
14099/// including posting-gate rewrites. The agent cannot drop this provenance.
14100fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14101    let mut body = crate::pr_outcome::review_rounds(state);
14102    body.push_str(&crate::pr_outcome::final_verification(state, head));
14103    let open = state.last_round_findings();
14104    if !open.is_empty() {
14105        body.push_str("## Open review findings\n\n");
14106        for f in open {
14107            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14108        }
14109        body.push('\n');
14110    }
14111    if let Some(c) = state.change_summary.as_ref()
14112        && head == crate::pr_outcome::FinalHead::At(&c.head)
14113    {
14114        body.push_str(&format!(
14115            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14116            c.base, c.head
14117        ));
14118    }
14119    body
14120}
14121
14122/// Local-only preview of the operator's task and candidate summary.
14123fn pr_preview(
14124    state: &RunState,
14125    winner: char,
14126    facts: Option<&BranchFacts>,
14127    head: crate::pr_outcome::FinalHead<'_>,
14128) -> PrMessage {
14129    let summary = state
14130        .candidates
14131        .iter()
14132        .find(|c| c.label == winner)
14133        .map(|c| c.summary.as_str())
14134        .unwrap_or_default();
14135    // The fallback is the operator's own words and may not be English; GitHub
14136    // text always is, so a non-English task gets a neutral title instead.
14137    let review = is_review_run(state);
14138    let title = if review {
14139        facts
14140            .and_then(|f| {
14141                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14142            })
14143            .or_else(|| review_title(state))
14144            .or_else(|| {
14145                state
14146                    .candidates
14147                    .iter()
14148                    .find(|c| c.label == winner)
14149                    .filter(|c| !c.branch.starts_with("magi/"))
14150                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14151            })
14152            .unwrap_or_else(|| neutral_title(state, winner))
14153    } else {
14154        summary_title(summary).unwrap_or_else(|| {
14155            english_title(
14156                &state.instruction,
14157                PR_TITLE_MAX,
14158                state.config.graph.github_english(),
14159            )
14160            .unwrap_or_else(|| neutral_title(state, winner))
14161        })
14162    };
14163
14164    let mut body = String::new();
14165    let what = summary_without_title(summary);
14166    if !what.is_empty() {
14167        body.push_str("## Summary\n\n");
14168        body.push_str(&what);
14169        body.push_str("\n\n");
14170    }
14171
14172    // Review history uses structured facts across all rounds, never reports.
14173    body.push_str(&crate::pr_outcome::review_rounds(state));
14174    body.push_str(&crate::pr_outcome::final_verification(state, head));
14175    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14176
14177    let open = state.open_findings();
14178    if !open.is_empty() {
14179        body.push_str("## Open review findings\n\n");
14180        for f in &open {
14181            body.push_str(&format!(
14182                "- `{}` [{:?}] {}\n",
14183                f.id, f.severity, "Context retained in local review records."
14184            ));
14185        }
14186        body.push('\n');
14187    }
14188
14189    if let Some(fix) = fix
14190        && !fix.rejected.is_empty()
14191    {
14192        body.push_str("## Declined by the fixer\n\n");
14193        for r in &fix.rejected {
14194            body.push_str(&format!(
14195                "- `{}`: {}\n",
14196                r.id, "Reason retained in local review records."
14197            ));
14198        }
14199        body.push('\n');
14200    }
14201
14202    if review {
14203        // The review prompt is not the task; list what the branch carries.
14204        body.push_str("## Commits under review\n\n");
14205        if let Some(facts) = facts {
14206            let mut left = COMMITS_MAX_CHARS;
14207            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14208                let mut entry = format!("- {}\n", markdown_safe(subject));
14209                for l in markdown_safe(text).lines() {
14210                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14211                }
14212                if left == 0 {
14213                    body.push_str(&format!(
14214                        "- ... {} more commit(s)\n",
14215                        facts.commits.len() - i
14216                    ));
14217                    break;
14218                }
14219                if entry.len() > left {
14220                    // Even the first commit is cut: one huge body must not
14221                    // push the whole description past GitHub's limit.
14222                    let mut end = left;
14223                    while !entry.is_char_boundary(end) {
14224                        end -= 1;
14225                    }
14226                    entry.truncate(end);
14227                    entry.push_str("\n  ... (truncated)\n");
14228                    left = 0;
14229                } else {
14230                    left -= entry.len();
14231                }
14232                body.push_str(&entry);
14233            }
14234            if !facts.stat.trim().is_empty() {
14235                body.push_str(&format!(
14236                    "\n## Diff stat\n\n```\n{}\n```\n",
14237                    markdown_safe(facts.stat.trim())
14238                ));
14239            }
14240        } else {
14241            match &state.reviewed_commits {
14242                Some(subjects) => {
14243                    for s in subjects {
14244                        body.push_str(&format!("- {}\n", s.trim()));
14245                    }
14246                }
14247                None => {
14248                    // An older run kept only the prompt, with the commit list
14249                    // after its first paragraph.
14250                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14251                    body.push_str(rest.trim());
14252                    body.push('\n');
14253                }
14254            }
14255        }
14256    } else {
14257        let task = state.instruction.trim();
14258        let task = if task.is_empty() {
14259            "(empty task)"
14260        } else {
14261            task
14262        };
14263        body.push_str(&format!(
14264            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14265            task.replace("</details>", "&lt;/details&gt;")
14266        ));
14267    }
14268
14269    body.push_str(&format!(
14270        "\n---\nmagi:run/{} magi:candidate-{}\n",
14271        state.id,
14272        winner.to_ascii_lowercase()
14273    ));
14274
14275    PrMessage { title, body }
14276}
14277
14278/// Source imports have already been prepared from structured inputs. Legacy
14279/// inferred references must never instruct a seat to reconstruct those imports.
14280fn seeded_instruction(state: &RunState) -> String {
14281    let mut inputs = Vec::new();
14282    if let Some(start) = &state.sources.start_from {
14283        inputs.push(format!(
14284            "Start from `{}` at `{}` (including ancestry).",
14285            start.token, start.sha
14286        ));
14287    }
14288    for pick in &state.sources.pick_commits {
14289        inputs.push(format!(
14290            "Pick `{}` at `{}` (single commit).",
14291            pick.token, pick.sha
14292        ));
14293    }
14294    if inputs.is_empty() {
14295        state.instruction.clone()
14296    } else {
14297        format!(
14298            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14299            state.instruction,
14300            inputs.join("\n")
14301        )
14302    }
14303}
14304
14305/// Does the winner have no commits ahead of the base it would land on?
14306/// Any failure to find out reads as "not empty": the merge then behaves as it
14307/// always did rather than refusing on a guess.
14308async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14309    let base = &state.base_branch;
14310    let mut against = base.clone();
14311    if mode == MergeMode::Pr {
14312        // A pull request lands on the remote's base, never the local branch
14313        // of the same name: if that cannot be read, "not empty" is the safe
14314        // answer.
14315        let remote = &state.config.merge.remote;
14316        let tracking = format!("{remote}/{base}");
14317        let fetched = git::fetch(repo, remote, base).await;
14318        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14319            against = tracking;
14320        } else {
14321            return false;
14322        }
14323    }
14324    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14325}
14326
14327/// Why nothing was opened for an empty winner, with what the task's own
14328/// references resolved to.
14329fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14330    let mut detail = format!(
14331        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14332         nothing to open a pull request for"
14333    );
14334    detail.push_str(
14335        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14336    );
14337    detail
14338}
14339
14340/// What the `Pr` merge does once it knows whether the branch already has an
14341/// open pull request.
14342#[derive(Debug, PartialEq, Eq)]
14343enum PrPlan {
14344    Create,
14345    Adopt { url: String, title: String },
14346    Stop(String),
14347}
14348
14349/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14350/// a failed lookup -> stop with the real reason. Never guesses.
14351fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14352    match found {
14353        Ok(land::OpenPr::None) => PrPlan::Create,
14354        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14355        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14356            "several open pull requests exist for this branch, not picking one: {}",
14357            urls.join(" ")
14358        )),
14359        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14360    }
14361}
14362
14363/// `gh pr create`, returning the PR url.
14364pub(crate) async fn gh_pr_create(
14365    cwd: &Path,
14366    base: &str,
14367    head: &str,
14368    title: &str,
14369    body: &str,
14370) -> Result<String> {
14371    let out = tokio::process::Command::new("gh")
14372        .args([
14373            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14374        ])
14375        .current_dir(cwd)
14376        .quiet()
14377        .stdin(std::process::Stdio::null())
14378        .output()
14379        .await
14380        .context("spawn gh")?;
14381    if out.status.success() {
14382        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14383    } else {
14384        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14385    }
14386}
14387
14388/// Never force deletion of uncommitted work, including unknown legacy trees.
14389async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14390    match std::fs::symlink_metadata(path) {
14391        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14392            // A previous cleanup may have removed the tree before a branch
14393            // deletion or state save failed. Unregister it if still present.
14394            git::worktree_remove_clean(repo, path).await?;
14395            return Ok(());
14396        }
14397        Err(e) => return Err(e.into()),
14398        Ok(_) => {}
14399    }
14400    if !git::is_clean(path).await? {
14401        bail!(
14402            "worktree has uncommitted work; refusing removal: {}",
14403            path.display()
14404        );
14405    }
14406    if !git::worktree_remove_clean(repo, path).await? {
14407        bail!("worktree removal refused: {}", path.display());
14408    }
14409    Ok(())
14410}
14411
14412/// Read seats return replies, not working-tree changes. Only registered,
14413/// detached seats directly inside this run's root may discard those changes.
14414async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14415    if !crate::retention::read_seat(path) || !path.exists() {
14416        return remove_preserved_worktree(&state.repo, path).await;
14417    }
14418    let owned = std::fs::symlink_metadata(path)?.is_dir()
14419        && path.parent().map(Path::canonicalize).transpose()?
14420            == Some(state.worktree_root().canonicalize()?)
14421        && crate::retention::worktrees(state)
14422            .await?
14423            .contains(&path.canonicalize()?);
14424    let common = crate::repo_lock::common_dir(&state.repo).await?;
14425    if !owned
14426        || common.is_none()
14427        || crate::repo_lock::common_dir(path).await? != common
14428        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14429            .await?
14430            .ok()
14431        || state.candidates.iter().any(|c| c.worktree == path)
14432    {
14433        return remove_preserved_worktree(&state.repo, path).await;
14434    }
14435    let changes = git::status_porcelain(path).await?;
14436    if !git::worktree_remove(&state.repo, path).await? {
14437        bail!(
14438            "read-only seat worktree removal refused: {}",
14439            path.display()
14440        );
14441    }
14442    if !changes.is_empty() {
14443        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14444        let paths: String = paths.chars().take(1024).collect();
14445        state.event(
14446            "fold",
14447            format!(
14448                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14449                path.file_name().unwrap_or_default().to_string_lossy(),
14450                changes.lines().count()
14451            ),
14452        );
14453    }
14454    Ok(())
14455}
14456
14457fn fold_target(
14458    home: &Path,
14459    root: &Path,
14460    path: &Path,
14461    isolated: bool,
14462) -> Option<crate::build_target::FoldTarget> {
14463    if !isolated {
14464        return None;
14465    }
14466    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14467        Ok(target) => target,
14468        Err(error) => {
14469            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14470            None
14471        }
14472    }
14473}
14474
14475fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14476    if let Some(target) = target
14477        && let Err(error) = target.reclaim_orphaned_target(home)
14478    {
14479        tracing::warn!(%error, "isolated target retained after fold");
14480    }
14481}
14482
14483/// Tear a run's worktrees and branches down.
14484///
14485/// `home` is where the updated `run.json` is saved (via
14486/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14487/// a housekeeping pass already has its own honest `home` handed to it, and
14488/// falling through to the global here would write back through whichever
14489/// directory some other process or test pinned into that `OnceLock` first,
14490/// not the one the caller actually resolved its `runs` and `state` from.
14491pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14492    fold_run_with_policy(state, drop_winner, home, false).await
14493}
14494
14495/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14496pub async fn fold_run_overriding_recovery_retention(
14497    state: &mut RunState,
14498    drop_winner: bool,
14499    home: &Path,
14500) -> Result<Vec<String>> {
14501    fold_run_with_policy(state, drop_winner, home, true).await
14502}
14503
14504async fn fold_run_with_policy(
14505    state: &mut RunState,
14506    drop_winner: bool,
14507    home: &Path,
14508    override_recovery_retention: bool,
14509) -> Result<Vec<String>> {
14510    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14511        && !override_recovery_retention
14512    {
14513        bail!("refusing fold: {reason}");
14514    }
14515    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14516        bail!("candidate preservation incomplete; refusing cleanup");
14517    }
14518    // Serialize ordinary folding with the same starts/resumes as target-only
14519    // eviction. Otherwise a second janitor could remove the whole worktree
14520    // around a live output borrower even though target eviction was fenced.
14521    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
14522    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
14523    // An override must use current durable ownership, not a pre-lock snapshot.
14524    if override_recovery_retention {
14525        *state = RunState::load_under(&state.id, home)?;
14526        anyhow::ensure!(
14527            state.status.done() && !state.status.resumable(),
14528            "recovery retention override requires a finished, non-resumable run"
14529        );
14530        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
14531        anyhow::ensure!(
14532            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14533            "run is live or its ownership is unknown"
14534        );
14535        anyhow::ensure!(
14536            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
14537            "candidate preservation incomplete; refusing cleanup"
14538        );
14539    }
14540    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14541    if let Some(reason) = &retention_reason
14542        && !override_recovery_retention
14543    {
14544        bail!("refusing fold: {reason}");
14545    }
14546    let _driver = crate::driver::maintenance(home, &state.id)?;
14547    let mut output_guards = Vec::new();
14548    for entry in std::fs::read_dir(state.worktree_root())
14549        .into_iter()
14550        .flatten()
14551        .flatten()
14552    {
14553        if entry.path().join(".git").is_file() {
14554            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
14555        }
14556    }
14557    let repo = state.repo.clone();
14558    // CLI, Web and automatic cleanup all enter here, independently of
14559    // Runner::fold_losers. Protect deletion and shared config release too.
14560    let wait = repository_wait(state, None);
14561    let _coordination = match coordinate_operation(state, &repo, &wait).await {
14562        Ok(lease) => lease,
14563        Err(e) => {
14564            state.save_under(home)?;
14565            return Err(e);
14566        }
14567    };
14568    // Confirmed merges dispose of their owned sources after durable evidence
14569    // capture. Preflight every source before removing anything.
14570    let _source_outputs = if retention_reason.is_some()
14571        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
14572    {
14573        verify_merged_fold_sources(state, drop_winner, home).await?
14574    } else {
14575        Vec::new()
14576    };
14577    if let Some(reason) = retention_reason {
14578        state.event(
14579            "fold",
14580            format!(
14581                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
14582                state.id
14583            ),
14584        );
14585        state.save_under(home)?;
14586    }
14587    let root = state.worktree_root();
14588    let winner = state.tally.as_ref().map(|t| t.winner);
14589    let mut removed = Vec::new();
14590    let isolated = crate::build_target::isolated(&state.config);
14591
14592    for i in 0..state.candidates.len() {
14593        let c = state.candidates[i].clone();
14594        let is_winner = Some(c.label) == winner;
14595        if is_winner && !drop_winner {
14596            continue;
14597        }
14598        let existed = c.worktree.exists();
14599        let target = fold_target(home, &root, &c.worktree, isolated);
14600        // A vanished directory can still have a Git registration that keeps
14601        // its branch checked out. Remove that registration before the branch.
14602        remove_preserved_worktree(&repo, &c.worktree).await?;
14603        reclaim_fold_target(home, target);
14604        if existed {
14605            removed.push(c.worktree.to_string_lossy().into_owned());
14606        }
14607        // A branch handed to a later run (and its pull request) is not this
14608        // run's to delete.
14609        let handed_over = state.released_branches.contains(&c.branch);
14610        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
14611            if !git::branch_delete(&repo, &c.branch).await? {
14612                bail!("candidate branch removal refused");
14613            }
14614            removed.push(c.branch.clone());
14615        }
14616        state.candidates[i].folded = true;
14617    }
14618
14619    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
14620        let path = name.path();
14621        let keep = !drop_winner
14622            && winner.is_some_and(|w| {
14623                path.file_name()
14624                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14625            });
14626        if keep {
14627            continue;
14628        }
14629        let target = fold_target(home, &root, &path, isolated);
14630        remove_read_seat_worktree(state, &path).await?;
14631        reclaim_fold_target(home, target);
14632        removed.push(path.to_string_lossy().into_owned());
14633    }
14634
14635    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14636    // judge worktrees, so once the loop above has cleared all of them out,
14637    // the parent is a bare directory nobody else was ever going to remove -
14638    // git only ever managed what was inside it. Left alone, one of these
14639    // accumulates per fully-folded run; the operator's own machine had 74.
14640    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14641    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14642    // so does anything a run never claimed that happens to share the bay.
14643    remove_if_empty(&root);
14644
14645    if state.enabled_worktree_config && drop_winner {
14646        // A release, not a raw disable: some sibling run in this repository
14647        // may still hold its own reference (see `git::acquire_worktree_config`),
14648        // and only the last release actually turns the setting back off.
14649        git::release_worktree_config(&repo).await.ok();
14650        state.enabled_worktree_config = false;
14651    }
14652    state.save_under(home)?;
14653    Ok(removed)
14654}
14655
14656async fn verify_merged_fold_sources(
14657    state: &RunState,
14658    drop_winner: bool,
14659    home: &Path,
14660) -> Result<Vec<std::fs::File>> {
14661    let winner = state.tally.as_ref().map(|t| t.winner);
14662    let mut heads = BTreeSet::new();
14663    for candidate in &state.candidates {
14664        if Some(candidate.label) == winner && !drop_winner {
14665            continue;
14666        }
14667        anyhow::ensure!(
14668            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14669            "candidate recovery source is outside the inventoried run root: {}",
14670            candidate.worktree.display()
14671        );
14672        match std::fs::symlink_metadata(&candidate.worktree) {
14673            Ok(_) => {}
14674            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14675            Err(error) => return Err(error.into()),
14676        }
14677        if !state.released_branches.contains(&candidate.branch)
14678            && git::branch_exists(&state.repo, &candidate.branch).await?
14679        {
14680            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14681        }
14682    }
14683    let mut cargo_guards = Vec::new();
14684    let entries = match std::fs::read_dir(state.worktree_root()) {
14685        Ok(entries) => Some(entries),
14686        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14687        Err(error) => return Err(error.into()),
14688    };
14689    for entry in entries.into_iter().flatten() {
14690        let path = entry?.path();
14691        let metadata = std::fs::symlink_metadata(&path)?;
14692        anyhow::ensure!(
14693            metadata.is_dir() && !metadata.file_type().is_symlink(),
14694            "non-directory or symlink recovery source retained: {}",
14695            path.display()
14696        );
14697        if !drop_winner
14698            && winner.is_some_and(|w| {
14699                path.file_name()
14700                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14701            })
14702        {
14703            continue;
14704        }
14705        anyhow::ensure!(
14706            path.join(".git").is_file(),
14707            "unregistered recovery source retained: {}",
14708            path.display()
14709        );
14710        anyhow::ensure!(
14711            git::git(
14712                &path,
14713                &[
14714                    "status",
14715                    "--porcelain",
14716                    "--untracked-files=all",
14717                    "--ignored",
14718                    "--",
14719                    ".",
14720                    ":(exclude)target"
14721                ]
14722            )
14723            .await?
14724            .is_empty(),
14725            "source changes or ignored recovery files retained: {}",
14726            path.display()
14727        );
14728        match std::fs::symlink_metadata(path.join("target")) {
14729            Ok(_) => {
14730                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14731            }
14732            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14733            Err(error) => return Err(error.into()),
14734        }
14735        for checkpoint in [
14736            "rebase-merge",
14737            "rebase-apply",
14738            "sequencer",
14739            "CHERRY_PICK_HEAD",
14740            "MERGE_HEAD",
14741            "REBASE_HEAD",
14742            "REVERT_HEAD",
14743            "BISECT_LOG",
14744            "AUTO_MERGE",
14745            "MERGE_MSG",
14746        ] {
14747            let location = git::git(
14748                &path,
14749                &[
14750                    "rev-parse",
14751                    "--path-format=absolute",
14752                    "--git-path",
14753                    checkpoint,
14754                ],
14755            )
14756            .await?;
14757            anyhow::ensure!(
14758                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14759                if e.kind() == std::io::ErrorKind::NotFound),
14760                "Git recovery checkpoint retained: {checkpoint}"
14761            );
14762        }
14763        heads.insert(git::rev_parse(&path, "HEAD").await?);
14764    }
14765    crate::fold_evidence::preserve(state, home, &heads).await?;
14766
14767    Ok(cargo_guards)
14768}
14769
14770/// Remove `dir` if it exists and has nothing in it.
14771///
14772/// Best-effort and silent by design: a directory that is not empty (a run
14773/// whose winner is still parked there, a stray file some other process left)
14774/// is exactly the case this must refuse, and a directory that is already gone
14775/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14776/// already refuses a non-empty directory, so the emptiness check below is
14777/// belt, not suspenders - it is what keeps this from ever attempting the
14778/// removal in the case that matters, rather than trusting `remove_dir`'s
14779/// error path to have no side effects if it ever changed.
14780fn remove_if_empty(dir: &Path) {
14781    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14782        std::fs::remove_dir(dir).ok();
14783    }
14784}
14785
14786/// Severity of the worst open finding in the last review round, for reporting.
14787pub fn worst_open(state: &RunState) -> Option<Severity> {
14788    state
14789        .reviews
14790        .last()?
14791        .reviews
14792        .iter()
14793        .flat_map(|r| r.findings.iter())
14794        .map(|f| f.severity)
14795        .max()
14796}
14797
14798/// `[worktree] setup` hides its products per worktree, which needs
14799/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14800/// worktrees, like the hook's; every place that runs setup calls this first.
14801async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14802    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14803        git::acquire_worktree_config(repo).await?;
14804        state.enabled_worktree_config = true;
14805    }
14806    Ok(())
14807}
14808
14809#[cfg(test)]
14810mod tests {
14811    #[tokio::test]
14812    async fn launcher_base_fetch_requires_remote_success() {
14813        let tmp = tempfile::tempdir().unwrap();
14814        let repo = tmp.path().join("repo");
14815        let remote = tmp.path().join("remote");
14816        std::fs::create_dir(&repo).unwrap();
14817        std::fs::create_dir(&remote).unwrap();
14818        git::git(&remote, &["init", "--bare", "-b", "main"])
14819            .await
14820            .unwrap();
14821        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14822        git::git(
14823            &repo,
14824            &[
14825                "-c",
14826                "user.name=Fixture",
14827                "-c",
14828                "user.email=fixture@example.invalid",
14829                "commit",
14830                "--allow-empty",
14831                "-m",
14832                "fixture",
14833            ],
14834        )
14835        .await
14836        .unwrap();
14837        git::git(
14838            &repo,
14839            &["remote", "add", "origin", remote.to_str().unwrap()],
14840        )
14841        .await
14842        .unwrap();
14843        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14844        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14845        assert_eq!(
14846            resolve_base(&repo, "main", "origin", None)
14847                .await
14848                .unwrap()
14849                .commit,
14850            head
14851        );
14852        #[cfg(unix)]
14853        {
14854            let policy: crate::config::Coordination = toml::from_str(
14855                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14856            ).unwrap();
14857            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14858            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14859            let held = crate::repo_lock::SeatLease::operation_with(
14860                &repo,
14861                Some(&policy),
14862                &crate::repo_lock::WaitPolicy::default(),
14863            )
14864            .await
14865            .unwrap();
14866            assert!(held.is_some());
14867            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14868            tokio::pin!(fetch);
14869            assert!(
14870                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14871                    .await
14872                    .is_err()
14873            );
14874            assert!(
14875                !repo.join(".git/FETCH_HEAD").exists(),
14876                "no fetch before admission"
14877            );
14878            drop(held);
14879            let fetched = fetch.await.unwrap();
14880            assert_eq!(fetched.commit, head);
14881            assert_eq!(fetched.remote, "origin");
14882            assert_eq!(fetched.branch, "main");
14883        }
14884        // A surviving tracking ref is not successful fetch evidence.
14885        git::git(
14886            &repo,
14887            &[
14888                "remote",
14889                "set-url",
14890                "origin",
14891                tmp.path().join("missing").to_str().unwrap(),
14892            ],
14893        )
14894        .await
14895        .unwrap();
14896        let error = resolve_base(&repo, "main", "origin", None)
14897            .await
14898            .unwrap_err()
14899            .to_string();
14900        assert!(error.contains("cannot read origin/main"));
14901        assert!(error.contains("refusing to branch off"));
14902    }
14903
14904    #[test]
14905    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14906        let leaked = vec!["chore(deps): update a crate".to_owned()];
14907        let own = "fix(daemon): apply a chosen action";
14908        assert!(should_retitle("", own, &leaked));
14909        assert!(should_retitle(
14910            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14911            own,
14912            &leaked
14913        ));
14914        assert!(should_retitle(
14915            "chore: land candidate A of run 1",
14916            own,
14917            &leaked
14918        ));
14919        assert!(should_retitle(
14920            "magi: candidate A (uncommitted work)",
14921            own,
14922            &leaked
14923        ));
14924        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14925        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14926        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14927    }
14928
14929    #[test]
14930    fn pr_merge_plan_creates_adopts_or_stops() {
14931        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14932        assert_eq!(
14933            pr_merge_plan(Ok(land::OpenPr::One {
14934                url: "u".into(),
14935                title: "t".into()
14936            })),
14937            PrPlan::Adopt {
14938                url: "u".into(),
14939                title: "t".into()
14940            }
14941        );
14942        let PrPlan::Stop(many) =
14943            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14944        else {
14945            panic!("many must stop");
14946        };
14947        assert!(many.contains('a') && many.contains('b'));
14948        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14949            panic!("a failed lookup must stop");
14950        };
14951        assert!(err.contains("bad token"));
14952    }
14953
14954    use super::*;
14955    use crate::run::GateStatus;
14956    use std::collections::BTreeMap;
14957    use std::time::Duration;
14958
14959    fn conductor() -> AgentSpec {
14960        AgentSpec {
14961            id: "conductor".to_owned(),
14962            kind: crate::config::AgentKind::Command,
14963            model: None,
14964            command: vec!["true".to_owned()],
14965            extra_args: Vec::new(),
14966            env: BTreeMap::new(),
14967            prompt_delivery: None,
14968            max_turn_secs: None,
14969        }
14970    }
14971
14972    fn spec(id: &str) -> AgentSpec {
14973        AgentSpec {
14974            id: id.to_owned(),
14975            kind: crate::config::AgentKind::Command,
14976            model: None,
14977            command: vec!["true".to_owned()],
14978            extra_args: Vec::new(),
14979            env: BTreeMap::new(),
14980            prompt_delivery: None,
14981            max_turn_secs: None,
14982        }
14983    }
14984
14985    fn ids(xs: &[&str]) -> BTreeSet<String> {
14986        xs.iter().map(|s| (*s).to_owned()).collect()
14987    }
14988
14989    #[test]
14990    fn pick_successor_skips_an_agent_another_seat_holds() {
14991        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14992        let roster = [spec("a"), spec("b"), spec("c")];
14993        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14994        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14995    }
14996
14997    #[test]
14998    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14999        // The other seat started on c but was handed to d; c is free again.
15000        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
15001        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15002        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15003        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
15004        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
15005    }
15006
15007    #[test]
15008    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
15009        let roster = [spec("a"), spec("b")];
15010        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15011        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15012        let carried = ids(&["b"]);
15013        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
15014        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15015    }
15016
15017    #[test]
15018    fn pick_successor_returns_none_without_any_untried_successor() {
15019        let roster = [spec("a"), spec("b")];
15020        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
15021        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
15022        let carried = ids(&["a"]);
15023        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
15024    }
15025
15026    #[test]
15027    fn pick_successor_rescue_avoids_another_seats_occupant() {
15028        // b is a carried failure and free; a is held by the other seat.
15029        let roster = [spec("a"), spec("b"), spec("c")];
15030        let carried = ids(&["b", "c"]);
15031        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
15032        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15033    }
15034
15035    #[test]
15036    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
15037        let roster = [spec("a"), spec("b"), spec("c")];
15038        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
15039        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15040    }
15041
15042    #[test]
15043    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
15044        let roster = [spec("a"), spec("b"), spec("c")];
15045        let failed = ids(&["a", "b", "c"]);
15046        // Rescue looks at the whole roster, once per id, then runs out.
15047        let mut tried = ids(&["b"]);
15048        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15049        assert_eq!(first.id, "a");
15050        tried.insert(first.id.clone());
15051        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15052        assert_eq!(second.id, "c");
15053        tried.insert(second.id.clone());
15054        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
15055    }
15056
15057    #[test]
15058    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
15059        let roster = [spec("a"), spec("b")];
15060        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
15061        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15062    }
15063
15064    #[test]
15065    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15066        let roster = [spec("a"), spec("b"), spec("c")];
15067        let h = SeatHistory {
15068            failed: ids(&["a"]),
15069            last_ok: Some("b".to_owned()),
15070            last_fail: None,
15071        };
15072        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15073        // A last answerer that left the roster, or later failed, is ignored.
15074        let gone = SeatHistory {
15075            last_ok: Some("zzz".to_owned()),
15076            ..h.clone()
15077        };
15078        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15079        let failed = SeatHistory {
15080            failed: ids(&["a", "b"]),
15081            last_ok: Some("b".to_owned()),
15082            last_fail: None,
15083        };
15084        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15085    }
15086
15087    #[test]
15088    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15089        let first = SeatState::new("review-1", "alpha", 7);
15090        let next = handover_seat("review-1", "gamma", 7);
15091        assert_ne!(first.claude_session, next.claude_session);
15092    }
15093
15094    #[test]
15095    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15096        let mut state = state_with_summary("x", "y");
15097        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15098        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15099        assert_ne!(a.claude_session, b.claude_session);
15100    }
15101
15102    #[test]
15103    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15104        let roster = [spec("a"), spec("b")];
15105        let h = SeatHistory {
15106            failed: ids(&["a", "b"]),
15107            ..SeatHistory::default()
15108        };
15109        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15110        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15111        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15112    }
15113
15114    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15115    // fallback loop depends on to terminate: it must walk forward from the
15116    // seat's own position, never restart at the front of the roster, and it
15117    // must never hand back an id already tried, however many times that id
15118    // happens to appear.
15119
15120    #[test]
15121    fn failure_signature_ignores_numbers_and_paths() {
15122        assert_eq!(
15123            failure_signature("exited with Some(2) and no usable output"),
15124            failure_signature("exited with Some(137) and no usable output")
15125        );
15126        assert_eq!(
15127            failure_signature("process exited with no usable output (exit code 2)"),
15128            failure_signature("process exited with no usable output (exit code 137)")
15129        );
15130        for (old, new) in [
15131            (
15132                "exited with Some(2) and no usable output",
15133                "process exited with no usable output (exit code 2)",
15134            ),
15135            (
15136                "exited with None and no usable output",
15137                "process exited with no usable output (exit code unavailable)",
15138            ),
15139        ] {
15140            let previous = FailClass::Other(failure_signature(old));
15141            let current = FailClass::Other(failure_signature(new));
15142            assert_eq!(previous, current, "resumption retains the failure class");
15143            assert!(!should_hand_over(Some(&previous), &current));
15144        }
15145        assert_eq!(
15146            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15147            failure_signature("cannot open /var/x.txt: denied")
15148        );
15149        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15150    }
15151
15152    #[test]
15153    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15154        let other = FailClass::Other("x".into());
15155        assert!(should_hand_over(None, &FailClass::Quota));
15156        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15157        assert!(should_hand_over(
15158            Some(&FailClass::Timeout),
15159            &FailClass::Timeout
15160        ));
15161        assert!(should_hand_over(None, &other));
15162        assert!(!should_hand_over(Some(&other), &other));
15163        assert!(should_hand_over(
15164            Some(&other),
15165            &FailClass::Other("y".into())
15166        ));
15167        // A quota or timeout in between ends the run of identical failures.
15168        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15169        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15170    }
15171
15172    #[test]
15173    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15174        let a = SeatState::new("judge-1", "alpha", 7);
15175        let b = handover_seat("judge-1", "beta", 7);
15176        assert_ne!(a.claude_session, b.claude_session);
15177        assert_eq!(b.turns, 0);
15178    }
15179
15180    #[test]
15181    fn a_timeout_is_classified_apart_from_other_failures() {
15182        assert_eq!(
15183            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15184            Some(FailClass::Timeout)
15185        );
15186        assert!(matches!(
15187            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15188            Some(FailClass::Other(_))
15189        ));
15190    }
15191
15192    #[test]
15193    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15194        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15195        let tried = BTreeSet::from(["beta".to_owned()]);
15196        // beta sits at index 1; the next candidate is gamma, never alpha —
15197        // which is very likely a different candidate slot's own agent.
15198        let next = next_untried_in_roster(&roster, 1, &tried);
15199        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15200    }
15201
15202    #[test]
15203    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15204        let roster = vec![spec("alpha"), spec("beta")];
15205        let tried = BTreeSet::from(["beta".to_owned()]);
15206        // beta is the roster's last entry: nothing follows it, and alpha —
15207        // earlier in the roster, almost certainly a different candidate
15208        // slot's own agent — must not be reached by wrapping back to it.
15209        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15210    }
15211
15212    #[test]
15213    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15214        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15215        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15216        // beta (index 1) and gamma (index 2, the only entry after it) have
15217        // both been tried; alpha (index 0) never has, but it comes before
15218        // beta's own position, so there is nothing further for this seat.
15219        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15220    }
15221
15222    #[test]
15223    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15224        let roster = vec![spec("a"), spec("a"), spec("b")];
15225        let tried = BTreeSet::from(["a".to_owned()]);
15226        let next = next_untried_in_roster(&roster, 0, &tried);
15227        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15228    }
15229
15230    #[test]
15231    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15232        let roster = vec![spec("a"), spec("b")];
15233        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15234        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15235    }
15236
15237    #[test]
15238    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15239        let dir = tempfile::tempdir().unwrap();
15240        let bay = dir.path().join("ffff");
15241
15242        // Not there yet: nothing to do, nothing to panic on.
15243        remove_if_empty(&bay);
15244        assert!(!bay.exists());
15245
15246        // Something still inside - the winner's worktree, or a stray file -
15247        // keeps the directory standing.
15248        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15249        remove_if_empty(&bay);
15250        assert!(bay.exists(), "non-empty directory must survive");
15251
15252        // Once the last entry is gone, so is the directory itself.
15253        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15254        remove_if_empty(&bay);
15255        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15256    }
15257
15258    // `round_is_clean` is the exact decision this task fixed: a round with a
15259    // seat that never answered must not read the same as a round every seat
15260    // actually reviewed. These are deterministic and process-free by design —
15261    // the equivalent end-to-end check (a real reviewer timing out under a
15262    // live graph run) is a genuine race against wall-clock contention, and a
15263    // spawn slow enough to blow even a generous budget under a loaded test
15264    // run must not turn this specific regression check flaky.
15265
15266    #[test]
15267    fn a_full_panel_that_found_nothing_is_clean() {
15268        assert!(round_is_clean(
15269            0,
15270            true,
15271            2,
15272            2,
15273            0,
15274            IncompleteReviewPolicy::Block
15275        ));
15276    }
15277
15278    #[test]
15279    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15280        assert!(!round_is_clean(
15281            0,
15282            true,
15283            1,
15284            2,
15285            0,
15286            IncompleteReviewPolicy::Block
15287        ));
15288    }
15289
15290    #[test]
15291    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15292        assert!(!round_is_clean(
15293            1,
15294            true,
15295            1,
15296            2,
15297            0,
15298            IncompleteReviewPolicy::Warn
15299        ));
15300    }
15301
15302    #[test]
15303    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15304        assert!(round_is_clean(
15305            0,
15306            true,
15307            1,
15308            2,
15309            0,
15310            IncompleteReviewPolicy::Warn
15311        ));
15312    }
15313
15314    #[test]
15315    fn a_full_panel_with_an_open_finding_is_not_clean() {
15316        assert!(!round_is_clean(
15317            1,
15318            true,
15319            2,
15320            2,
15321            0,
15322            IncompleteReviewPolicy::Block
15323        ));
15324    }
15325
15326    #[test]
15327    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15328        assert!(!round_is_clean(
15329            0,
15330            false,
15331            2,
15332            2,
15333            0,
15334            IncompleteReviewPolicy::Block
15335        ));
15336    }
15337
15338    // The stall this task closes: under the default `block` policy, a seat
15339    // missing only because it was rate limited must not force a wait for a
15340    // session limit that will not lift by the next round. `round_is_clean`
15341    // is where that quorum carve-out lives; the review loop around it never
15342    // changes what a reviewer's vote or a finding's severity means.
15343
15344    #[test]
15345    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15346        // 1 of 2 answered, and the one missing was quota'd — the exact
15347        // "review-2 rate limited (quota)" shape from the field report.
15348        assert!(round_is_clean(
15349            0,
15350            true,
15351            1,
15352            2,
15353            1,
15354            IncompleteReviewPolicy::Block
15355        ));
15356    }
15357
15358    #[test]
15359    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15360        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15361        // not a quota loss (`quota_missing` stays 0) — worth another try.
15362        assert!(!round_is_clean(
15363            0,
15364            true,
15365            1,
15366            2,
15367            0,
15368            IncompleteReviewPolicy::Block
15369        ));
15370    }
15371
15372    #[test]
15373    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15374        assert!(!round_is_clean(
15375            1,
15376            true,
15377            1,
15378            2,
15379            1,
15380            IncompleteReviewPolicy::Block
15381        ));
15382        assert!(!round_is_clean(
15383            0,
15384            false,
15385            1,
15386            2,
15387            1,
15388            IncompleteReviewPolicy::Block
15389        ));
15390    }
15391
15392    #[test]
15393    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15394        // Every seat quota'd, nobody answered: there is no panel to decide
15395        // on, so this must fall through to the existing block-and-retry
15396        // fallback rather than call an unreviewed patch clean.
15397        assert!(!round_is_clean(
15398            0,
15399            true,
15400            0,
15401            2,
15402            2,
15403            IncompleteReviewPolicy::Block
15404        ));
15405    }
15406
15407    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15408        CommandOutcome {
15409            command: "test".to_owned(),
15410            code,
15411            output_tail: String::new(),
15412            duration_ms: 0,
15413            resource_blocked,
15414            ..Default::default()
15415        }
15416    }
15417
15418    #[cfg(unix)]
15419    #[tokio::test]
15420    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15421        ask_test_home();
15422        let temp = tempfile::tempdir().unwrap();
15423        let mut runner = runner_at(RunStatus::Gating);
15424        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15425        let commands = vec![
15426            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15427            "touch must-not-run".to_owned(),
15428        ];
15429        let (outcomes, retried, pids) = run_e2e_with_retry(
15430            &mut runner.state,
15431            &shell,
15432            &commands,
15433            temp.path(),
15434            Duration::from_secs(5),
15435            "fixture",
15436            None,
15437        )
15438        .await;
15439        assert_eq!(outcomes.len(), 1);
15440        assert!(outcomes[0].resource_blocked);
15441        assert!(!outcomes[0].build_failed());
15442        assert!(!retried);
15443        assert!(pids.is_empty());
15444        assert!(!temp.path().join("must-not-run").exists());
15445        assert_eq!(
15446            runner.state.resource_block.as_ref().unwrap().kind,
15447            "incremental cache admission"
15448        );
15449    }
15450
15451    #[test]
15452    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15453        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15454        assert!(
15455            !verify_inconclusive(&[outcome(Some(1), false)]),
15456            "an ordinary failure is still evidence about the patch"
15457        );
15458        assert!(verify_inconclusive(&[outcome(None, true)]));
15459        assert!(
15460            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15461            "one inconclusive outcome taints the whole batch"
15462        );
15463        assert!(!verify_inconclusive(&[]));
15464    }
15465
15466    #[tokio::test]
15467    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15468        // Alive for the first two checks, then dead - confirms the loop
15469        // actually re-polls rather than deciding once and sleeping out the
15470        // ceiling regardless.
15471        let calls = std::sync::atomic::AtomicUsize::new(0);
15472        let started = Instant::now();
15473        wait_for_pids_with(
15474            &[123],
15475            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15476            Duration::from_millis(5),
15477            Duration::from_secs(5),
15478        )
15479        .await;
15480        assert!(
15481            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15482            "must keep checking rather than deciding on the first answer"
15483        );
15484        assert!(
15485            started.elapsed() < Duration::from_secs(1),
15486            "must return the moment it is confirmed dead, not wait out the ceiling"
15487        );
15488    }
15489
15490    #[tokio::test]
15491    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15492        let started = Instant::now();
15493        wait_for_pids_with(
15494            &[123],
15495            |_| true, // never reports dead
15496            Duration::from_millis(5),
15497            Duration::from_millis(30),
15498        )
15499        .await;
15500        let elapsed = started.elapsed();
15501        assert!(
15502            elapsed >= Duration::from_millis(30),
15503            "must not give up before its own ceiling: {elapsed:?}"
15504        );
15505        assert!(
15506            elapsed < Duration::from_secs(1),
15507            "must not wait past its own ceiling either: {elapsed:?}"
15508        );
15509    }
15510
15511    #[tokio::test]
15512    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
15513        let started = Instant::now();
15514        wait_for_pids_with(
15515            &[],
15516            |_| true,
15517            Duration::from_secs(5),
15518            Duration::from_secs(5),
15519        )
15520        .await;
15521        assert!(
15522            started.elapsed() < Duration::from_millis(200),
15523            "an empty pid list has nothing to confirm"
15524        );
15525    }
15526
15527    // `review_conclusion` is the exact decision the review hand-off task
15528    // fixed: a round budget spent (or a tree that stopped moving) must not
15529    // collapse into `Blocked` regardless of what verification actually
15530    // said. Deterministic and process-free for the same reason the
15531    // `round_is_clean` family above is.
15532    fn review_round(
15533        clean: bool,
15534        blocking: usize,
15535        answered: usize,
15536        expected: usize,
15537        progressed: bool,
15538        e2e_ok: bool,
15539    ) -> ReviewRound {
15540        ReviewRound {
15541            round: 1,
15542            head: "h".to_owned(),
15543            verified_head: None,
15544            verified_at: None,
15545            reviews: Vec::new(),
15546            e2e: vec![CommandOutcome {
15547                command: "test".to_owned(),
15548                code: Some(if e2e_ok { 0 } else { 1 }),
15549                output_tail: String::new(),
15550                duration_ms: 0,
15551                resource_blocked: false,
15552                ..Default::default()
15553            }],
15554            verify_retried: false,
15555            e2e_deferred: false,
15556            e2e_defer_reason: None,
15557            fix: None,
15558            blocking,
15559            answered,
15560            expected,
15561            clean,
15562            progressed,
15563            vote_split: false,
15564            reconsideration: Vec::new(),
15565            verdict: None,
15566        }
15567    }
15568
15569    #[test]
15570    fn review_conclusion_is_none_when_nothing_has_run() {
15571        assert_eq!(review_conclusion(&[], 3), None);
15572    }
15573
15574    #[test]
15575    fn review_conclusion_is_none_while_rounds_remain() {
15576        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
15577        assert_eq!(review_conclusion(&rounds, 3), None);
15578    }
15579
15580    #[test]
15581    fn review_conclusion_is_gating_once_a_round_is_clean() {
15582        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
15583        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
15584    }
15585
15586    #[test]
15587    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
15588        let rounds = vec![
15589            review_round(false, 1, 2, 2, true, true),
15590            review_round(false, 1, 2, 2, true, true),
15591        ];
15592        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
15593    }
15594
15595    #[test]
15596    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
15597        let rounds = vec![
15598            review_round(false, 1, 2, 2, true, true),
15599            review_round(false, 1, 2, 2, true, false),
15600        ];
15601        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
15602    }
15603
15604    #[test]
15605    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
15606        // Magi never got a command to run against this round's own head — a
15607        // resource-blocked attempt, not a red one — so this must never
15608        // settle on `Blocked` the way a genuine e2e failure would. `None`
15609        // here is what tells `Runner::review_loop` to retry the check
15610        // itself rather than trust this cheap recomputation with a verdict
15611        // it cannot actually produce.
15612        let mut blocked = review_round(false, 1, 2, 2, true, false);
15613        blocked.e2e[0].resource_blocked = true;
15614        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
15615        assert_eq!(review_conclusion(&rounds, 2), None);
15616    }
15617
15618    #[test]
15619    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
15620        // Missing input, not a verified tree — never a hand-off candidate.
15621        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
15622        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
15623    }
15624
15625    #[test]
15626    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15627        let rounds = vec![
15628            review_round(false, 1, 2, 2, false, true),
15629            review_round(false, 1, 2, 2, false, true),
15630        ];
15631        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15632    }
15633
15634    fn secs(n: u64) -> Duration {
15635        Duration::from_secs(n)
15636    }
15637
15638    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15639    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15640    #[tokio::test]
15641    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15642        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15643        if std::env::var_os(CHILD).is_none() {
15644            // Other tests reconcile every run in the process-global home,
15645            // briefly taking owner locks. This ancestry test expects an idle
15646            // predecessor, so give it its own process and pinned test home.
15647            let output = std::process::Command::new(std::env::current_exe().unwrap())
15648                .args([
15649                    "--exact",
15650                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15651                    "--nocapture",
15652                ])
15653                .env(CHILD, "1")
15654                .env_remove("MAGI_WORKER_HOME")
15655                .env_remove("MAGI_WORKER_ID")
15656                .output()
15657                .unwrap();
15658            assert!(
15659                output.status.success()
15660                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15661                "{}\n{}",
15662                String::from_utf8_lossy(&output.stdout),
15663                String::from_utf8_lossy(&output.stderr)
15664            );
15665            return;
15666        }
15667        ask_test_home();
15668        let tmp = tempfile::tempdir().unwrap();
15669        let repo = tmp.path().join("repo");
15670        std::fs::create_dir_all(&repo).unwrap();
15671        init_repo(&repo);
15672        let g = |args: &[&str]| {
15673            let out = std::process::Command::new("git")
15674                .args(args)
15675                .current_dir(&repo)
15676                .quiet()
15677                .output()
15678                .unwrap();
15679            assert!(
15680                out.status.success(),
15681                "{}",
15682                String::from_utf8_lossy(&out.stderr)
15683            );
15684        };
15685        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15686        g(&["checkout", "-b", "historical"]);
15687        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15688        g(&["add", "."]);
15689        g(&["commit", "-m", "old alternative"]);
15690        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15691        g(&["checkout", "-b", "magi/task-selected", &base]);
15692        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15693        g(&["add", "."]);
15694        g(&["commit", "-m", "measurement infrastructure"]);
15695        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15696        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15697        g(&["add", "."]);
15698        g(&["commit", "-m", "dependent implementation"]);
15699        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15700        g(&["checkout", "main"]);
15701        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15702        g(&["add", "."]);
15703        g(&["commit", "-m", "unrelated base change"]);
15704        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15705        let origin = tmp.path().join("origin.git");
15706        g(&[
15707            "clone",
15708            "--bare",
15709            repo.to_str().unwrap(),
15710            origin.to_str().unwrap(),
15711        ]);
15712        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15713        g(&["fetch", "origin"]);
15714        let selection = crate::pr_recovery::Selection {
15715            url: "https://example.test/project/pull/1".into(),
15716            branch: "magi/task-selected".into(),
15717            head: head.clone(),
15718            source_head: None,
15719            source_run: None,
15720            source_proof: None,
15721            disposition: Some(crate::pr_recovery::Disposition::Review),
15722            instruction: "preserve measured behavior".into(),
15723            approved_at: jiff::Timestamp::now(),
15724        };
15725        let mut template = runner_at(RunStatus::Reviewing);
15726        template.state.repo = repo.clone();
15727        template.state.base_commit = current.clone();
15728        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15729        template.state.origin = Some(crate::run::Origin::queue("selected"));
15730        template.state.pr_head = Some(selection.branch.clone());
15731        template.state.pr_recovery = Some(selection.clone());
15732        let mut runner =
15733            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15734                .await
15735                .unwrap();
15736        let wt = runner.state.winner().unwrap().worktree.clone();
15737        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15738        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15739        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15740        assert!(runner.state.seeds.is_empty());
15741        assert_eq!(runner.state.instruction, "preserve measured behavior");
15742        runner.sync_to_base().await.unwrap();
15743        assert_eq!(
15744            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15745            "prerequisite"
15746        );
15747        assert_eq!(
15748            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15749            "measured implementation"
15750        );
15751        assert_eq!(
15752            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15753            "current main change"
15754        );
15755        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15756        assert_eq!(
15757            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15758            head
15759        );
15760
15761        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15762        let mut partial = runner_at(RunStatus::Reviewing);
15763        partial.state.repo = repo.clone();
15764        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15765        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15766            run: Some("exit 1".into()),
15767            ..Default::default()
15768        }];
15769        let selection = runner.state.pr_recovery.clone().unwrap();
15770        partial.state.pr_recovery = Some(selection.clone());
15771        partial.state.pr_head = Some(selection.branch.clone());
15772        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15773        let id = partial.state.id.clone();
15774        let error = match Runner::open_selected(
15775            &repo,
15776            partial.state,
15777            partial.roles,
15778            1,
15779            runner.state.base_commit.clone(),
15780            selection,
15781        )
15782        .await
15783        {
15784            Ok(_) => panic!("setup must fail"),
15785            Err(e) => e,
15786        };
15787        assert_eq!(
15788            error
15789                .downcast_ref::<crate::run::StartupFailure>()
15790                .unwrap()
15791                .run,
15792            id
15793        );
15794        let failed = RunState::load(&id).unwrap();
15795        assert_eq!(failed.status, RunStatus::Failed);
15796        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15797        assert!(Runner::resume(&id).is_err());
15798        runner.state.status = RunStatus::Ready;
15799        runner.state.driver_exited = true;
15800        runner.state.save().unwrap();
15801        let mut retry = runner_at(RunStatus::Reviewing);
15802        retry.state.repo = repo.clone();
15803        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15804        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15805        reselected.approved_at = jiff::Timestamp::now();
15806        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15807        retry.state.pr_head = Some(reselected.branch.clone());
15808        retry.state.pr_recovery = Some(reselected.clone());
15809        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15810            .await
15811            .unwrap();
15812        let restarted = Runner::open_selected(
15813            &repo,
15814            retry.state,
15815            retry.roles,
15816            1,
15817            runner.state.base_commit.clone(),
15818            reselected,
15819        )
15820        .await
15821        .unwrap();
15822        assert_eq!(
15823            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15824                .await
15825                .unwrap(),
15826            head
15827        );
15828        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15829        assert_eq!(
15830            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15831            head
15832        );
15833    }
15834
15835    #[tokio::test]
15836    #[cfg(unix)]
15837    async fn fallback_and_interrupted_restoration_require_coordination() {
15838        use std::os::fd::AsRawFd as _;
15839        ask_test_home();
15840        let tmp = tempfile::tempdir().unwrap();
15841        let mut runner = registered_runner(tmp.path()).await;
15842        runner.state.config.graph.timeout_resource_wait = 1;
15843        let winner = runner.state.candidates[0].clone();
15844        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15845        let leftover = winner.worktree.join("leftover");
15846        std::fs::write(&leftover, "untrusted edits").unwrap();
15847        let next = tmp.path().join("next-fixer");
15848        let mut failed = spec("first");
15849        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15850        let mut successor = spec("second");
15851        successor.command = vec![
15852            "sh".into(),
15853            "-c".into(),
15854            format!("touch '{}'; echo done", next.display()),
15855        ];
15856        let attempts = vec![
15857            (failed.clone(), "first".into()),
15858            (successor.clone(), "second".into()),
15859        ];
15860        let lock_path = runner.state.repo.join(".git/updater.lock");
15861        let external = std::fs::File::create(&lock_path).unwrap();
15862        assert_eq!(
15863            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15864            0
15865        );
15866        let artifacts = tmp.path().join("artifacts");
15867        let build = |spec, seat| SeatJob {
15868            spec,
15869            seat,
15870            cwd: winner.worktree.clone(),
15871            prompt: "fixture".into(),
15872            timeout: Duration::from_secs(10),
15873            allow_write: true,
15874            sessions: false,
15875            artifacts: artifacts.clone(),
15876            stem: "fix".into(),
15877            handover: None,
15878        };
15879        let (_, _, out) = runner
15880            .ask_fixer_among(
15881                attempts.clone(),
15882                "graft",
15883                None,
15884                Some((&winner.worktree, &head)),
15885                build,
15886            )
15887            .await;
15888        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15889        assert!(leftover.exists(), "contention must prevent clean");
15890        assert!(!next.exists());
15891        assert!(runner.state.handovers.is_empty());
15892        // Early interrupted-repair rollback uses the same protected route.
15893        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15894            from_run: "earlier".into(),
15895            generation: 1,
15896            mode: crate::recovery::Mode::VerifyRepair,
15897            reasons: Vec::new(),
15898            reviewed_head: None,
15899            rounds: Vec::new(),
15900            open_findings: Vec::new(),
15901            evidence: None,
15902            criteria_inherited: true,
15903            repair: crate::recovery::Repair::Started {
15904                before: head.clone(),
15905            },
15906        });
15907        assert!(
15908            runner
15909                .recovery_repair(&winner)
15910                .await
15911                .unwrap_err()
15912                .is::<crate::repo_lock::ResourceBlocked>()
15913        );
15914        assert!(matches!(
15915            runner.state.recovery.as_ref().unwrap().repair,
15916            crate::recovery::Repair::Started { .. }
15917        ));
15918        assert!(leftover.exists());
15919        drop(external);
15920        runner.recovery_repair(&winner).await.unwrap();
15921        assert!(!leftover.exists());
15922        assert!(matches!(
15923            runner.state.recovery.as_ref().unwrap().repair,
15924            crate::recovery::Repair::Done { .. }
15925        ));
15926        // A hard lock-open failure also leaves HEAD and untracked work intact.
15927        std::fs::remove_file(&lock_path).unwrap();
15928        std::fs::create_dir(&lock_path).unwrap();
15929        std::fs::write(&leftover, "untrusted edits").unwrap();
15930        let (_, _, out) = runner
15931            .ask_fixer_among(
15932                attempts,
15933                "graft",
15934                None,
15935                Some((&winner.worktree, &head)),
15936                build,
15937            )
15938            .await;
15939        assert!(matches!(out, AgentOutcome::Failed(_)));
15940        assert!(leftover.exists());
15941        assert!(!next.exists());
15942        assert_eq!(
15943            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15944            head
15945        );
15946    }
15947
15948    #[cfg(unix)]
15949    async fn registered_runner(root: &Path) -> Runner {
15950        repository_runner(root, crate::config::test_coordination()).await
15951    }
15952
15953    async fn repository_runner(
15954        root: &Path,
15955        coordination: Option<crate::config::Coordination>,
15956    ) -> Runner {
15957        ask_test_home();
15958        let repo = root.join("repo");
15959        std::fs::create_dir_all(&repo).unwrap();
15960        init_repo(&repo);
15961        if coordination.is_some() {
15962            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15963        }
15964        let mut runner = runner_at(RunStatus::Prep);
15965        runner.state.repo = repo.clone();
15966        runner.state.config.coordination = coordination;
15967        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15968        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15969        runner.state.config.graph.advise = false;
15970        runner.roles.implementers = vec![spec("implement")];
15971        runner.roles.judges = vec![spec("judge")];
15972        runner.prep().await.unwrap();
15973        runner
15974    }
15975
15976    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15977
15978    #[tokio::test]
15979    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15980        let tmp = tempfile::tempdir().unwrap();
15981        let mut runner = repository_runner(tmp.path(), None).await;
15982        let prompts = runner.state.config.prompts.clone();
15983        let run = runner.state.id.clone();
15984        let ctx = WaveCtx {
15985            carry_seats: false,
15986            pauses: None,
15987            run: &run,
15988            node: "advise",
15989            prompts: &prompts,
15990            cache: None,
15991            round: None,
15992        };
15993        let jobs: Vec<_> = ["alpha", "beta"]
15994            .into_iter()
15995            .map(|id| SeatJob {
15996                spec: scripted(id, AUTH_OUTAGE),
15997                seat: SeatState::new(id, id, 7),
15998                prompt: "propose".into(),
15999                cwd: runner.state.candidates[0].worktree.clone(),
16000                timeout: Duration::from_secs(10),
16001                allow_write: false,
16002                sessions: false,
16003                artifacts: agent::artifacts_dir(&runner.state.dir()),
16004                stem: id.into(),
16005                handover: None,
16006            })
16007            .collect();
16008        let mut losses = Vec::new();
16009        let results = ask_wave_with(
16010            jobs.clone(),
16011            runner.sem.clone(),
16012            2,
16013            &[],
16014            &ctx,
16015            &mut losses,
16016            &mut runner.state,
16017            &|_: &str| Ok(()),
16018        )
16019        .await;
16020        assert!(
16021            results
16022                .iter()
16023                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
16024        );
16025        assert_eq!(runner.state.quota.len(), 2);
16026        assert!(
16027            runner
16028                .state
16029                .quota
16030                .iter()
16031                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
16032        );
16033        assert!(!runner.state.advise_attempted);
16034        runner.stop_for_resource().unwrap();
16035        assert_eq!(runner.state.status, RunStatus::Blocked);
16036        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
16037        assert_eq!(
16038            runner.state.resource_block.as_ref().unwrap().kind,
16039            "agent authentication"
16040        );
16041        // A machine loss followed by an ordinary failure is not evidence
16042        // that the whole node was unavailable, and must not earn a refund.
16043        runner.state.resource_block = None;
16044        runner.state.quota.clear();
16045        let mut mixed = jobs;
16046        mixed[1].spec.command = vec!["false".into()];
16047        let results = ask_wave_with(
16048            mixed,
16049            runner.sem.clone(),
16050            0,
16051            &[],
16052            &ctx,
16053            &mut losses,
16054            &mut runner.state,
16055            &|_: &str| Ok(()),
16056        )
16057        .await;
16058        assert!(results.iter().all(|(_, res, _)| res.is_err()));
16059        assert!(runner.state.resource_block.is_none());
16060        assert_eq!(losses.len(), 1);
16061    }
16062
16063    #[tokio::test]
16064    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16065        let tmp = tempfile::tempdir().unwrap();
16066        let mut runner = repository_runner(tmp.path(), None).await;
16067        let implementer = scripted("implement", AUTH_OUTAGE);
16068        runner.roles.implementers = vec![implementer.clone()];
16069        runner.state.config.agents = vec![implementer];
16070        runner.implement().await.unwrap();
16071        assert_eq!(runner.state.status, RunStatus::Blocked);
16072        assert_eq!(runner.state.quota.len(), 1);
16073        assert_eq!(
16074            runner.state.quota[0].cause,
16075            agent::QuotaCause::Authentication
16076        );
16077        let candidate = &runner.state.candidates[0];
16078        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16079        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16080    }
16081
16082    #[tokio::test]
16083    #[cfg(unix)]
16084    async fn parked_implementer_persists_completed_work() {
16085        for registered in [false, true] {
16086            let tmp = tempfile::tempdir().unwrap();
16087            let mut runner = registered_runner(tmp.path()).await;
16088            if !registered {
16089                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16090            }
16091            let marker = tmp.path().join("started");
16092            let release = tmp.path().join("release");
16093            let mut implementer = spec("implement");
16094            implementer.command = vec![
16095                "sh".into(),
16096                "-c".into(),
16097                format!(
16098                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16099                    marker.display(),
16100                    release.display()
16101                ),
16102            ];
16103            runner.roles.implementers = vec![implementer.clone()];
16104            runner.state.config.agents = vec![implementer];
16105            let pause = runner.pause.clone();
16106            let (result, ()) = tokio::join!(runner.implement(), async {
16107                tokio::time::timeout(Duration::from_secs(10), async {
16108                    while !marker.exists() {
16109                        tokio::time::sleep(Duration::from_millis(10)).await;
16110                    }
16111                })
16112                .await
16113                .unwrap();
16114                pause.park();
16115                std::fs::write(&release, "go").unwrap();
16116            });
16117            result.unwrap();
16118            let candidate = &runner.state.candidates[0];
16119            assert!(candidate.commits > 0, "{candidate:?}");
16120            assert!(candidate.summary.contains("saved-result"));
16121            assert_eq!(candidate.files, 1);
16122            let before = candidate.commits;
16123            runner.implement().await.unwrap();
16124            assert_eq!(runner.state.candidates[0].commits, before);
16125        }
16126    }
16127
16128    #[tokio::test]
16129    #[cfg(unix)]
16130    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16131        let tmp = tempfile::tempdir().unwrap();
16132        let mut runner = registered_runner(tmp.path()).await;
16133        let winner = runner.state.candidates[0].clone();
16134        let cache = tmp.path().join("cache");
16135        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16136        runner.state.config.graph.timeout_resource_wait = 0;
16137        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16138        let crate::cache::AcquireOutcome::Acquired(held) =
16139            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16140        else {
16141            panic!("cache must be free")
16142        };
16143        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16144            from_run: "earlier".into(),
16145            generation: 1,
16146            mode: crate::recovery::Mode::VerifyRepair,
16147            reasons: Vec::new(),
16148            reviewed_head: None,
16149            rounds: Vec::new(),
16150            open_findings: Vec::new(),
16151            evidence: None,
16152            criteria_inherited: true,
16153            repair: crate::recovery::Repair::NotStarted,
16154        });
16155        runner.recovery_repair(&winner).await.unwrap();
16156        assert!(matches!(
16157            runner.state.recovery.as_ref().unwrap().repair,
16158            crate::recovery::Repair::WaitingForRestore { .. }
16159        ));
16160        drop(held);
16161        runner.state.resource_block = None;
16162        runner.state.config.graph.timeout_resource_wait = 1;
16163        runner.recovery_repair(&winner).await.unwrap();
16164        assert!(matches!(
16165            runner.state.recovery.as_ref().unwrap().repair,
16166            crate::recovery::Repair::Done { .. }
16167        ));
16168        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16169    }
16170
16171    #[tokio::test]
16172    #[cfg(unix)]
16173    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16174        use std::os::fd::AsRawFd as _;
16175        for graft in [false, true] {
16176            let tmp = tempfile::tempdir().unwrap();
16177            let mut runner = registered_runner(tmp.path()).await;
16178            runner.state.config.graph.timeout_resource_wait = 1;
16179            let winner = runner.state.candidates[0].clone();
16180            let marker = tmp.path().join("fixer-started");
16181            let mut fixer = spec("fixer");
16182            fixer.command = vec![
16183                "sh".into(),
16184                "-c".into(),
16185                format!("echo started >> '{}'; echo done", marker.display()),
16186            ];
16187            runner.roles.fixer = Some(vec![fixer]);
16188            if graft {
16189                let mut loser = winner.clone();
16190                loser.label = 'B';
16191                loser.index = 1;
16192                runner.state.candidates.push(loser);
16193                runner.state.config.graph.graft_runner_up = true;
16194                runner.state.tally = Some(Tally {
16195                    first_choice: BTreeMap::new(),
16196                    borda: BTreeMap::new(),
16197                    winner: winner.label,
16198                    rankings: 1,
16199                    unanimous_initial: true,
16200                    deliberated: false,
16201                    changed_votes: 0,
16202                    unanimous_final: true,
16203                    tie_break: None,
16204                    judges: 1,
16205                    present: 1,
16206                    quorum: 1,
16207                    met_quorum: true,
16208                    uncontested: None,
16209                });
16210                runner.state.judgements.push(crate::run::Judgement {
16211                    judge: 1,
16212                    seat: "judge-1".into(),
16213                    agent: "judge".into(),
16214                    ranking: vec![winner.label, 'B'],
16215                    reasons: BTreeMap::new(),
16216                    confidence: None,
16217                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16218                    order: vec![0, 1],
16219                    failed: None,
16220                    duration_ms: 0,
16221                });
16222            } else {
16223                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16224                    from_run: "earlier".into(),
16225                    generation: 1,
16226                    mode: crate::recovery::Mode::VerifyRepair,
16227                    reasons: Vec::new(),
16228                    reviewed_head: None,
16229                    rounds: Vec::new(),
16230                    open_findings: Vec::new(),
16231                    evidence: None,
16232                    criteria_inherited: true,
16233                    repair: crate::recovery::Repair::NotStarted,
16234                });
16235            }
16236            let reader = crate::repo_lock::SeatLease::for_checkout(
16237                &winner.worktree,
16238                false,
16239                crate::config::test_coordination().as_ref(),
16240            )
16241            .await
16242            .unwrap();
16243            let pause = runner.pause.clone();
16244            let (result, ()) = tokio::join!(
16245                async {
16246                    if graft {
16247                        runner.graft().await
16248                    } else {
16249                        runner.recovery_repair(&winner).await
16250                    }
16251                },
16252                async {
16253                    tokio::time::sleep(Duration::from_millis(100)).await;
16254                    pause.park();
16255                }
16256            );
16257            result.unwrap();
16258            assert!(!marker.exists(), "a blocked seat must not spawn");
16259            // Exercise the persisted state, as a binary replacement/resume does.
16260            runner.state = RunState::load(&runner.state.id).unwrap();
16261            if graft {
16262                assert_eq!(
16263                    runner.state.graft.as_ref().unwrap().outcome,
16264                    GraftOutcome::WaitingForRestore
16265                );
16266            } else {
16267                assert!(matches!(
16268                    runner.state.recovery.as_ref().unwrap().repair,
16269                    crate::recovery::Repair::WaitingForRestore { .. }
16270                ));
16271            }
16272            drop(reader);
16273            runner.pause = Pause::new();
16274            runner.state.resource_block = None;
16275            // Deferred restoration must still respect an external lock owner.
16276            let external =
16277                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16278            assert_eq!(
16279                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16280                0
16281            );
16282            let leftover = winner.worktree.join("leftover");
16283            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16284            let result = if graft {
16285                runner.graft().await
16286            } else {
16287                runner.recovery_repair(&winner).await
16288            };
16289            assert!(
16290                result
16291                    .unwrap_err()
16292                    .is::<crate::repo_lock::ResourceBlocked>()
16293            );
16294            assert!(leftover.exists());
16295            assert!(!marker.exists());
16296            drop(external);
16297            runner.state.resource_block = None;
16298            let result = if graft {
16299                runner.graft().await
16300            } else {
16301                runner.recovery_repair(&winner).await
16302            };
16303            result.unwrap();
16304            assert!(!leftover.exists(), "restore must precede retry");
16305            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16306            if graft {
16307                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16308            } else {
16309                assert!(matches!(
16310                    runner.state.recovery.as_ref().unwrap().repair,
16311                    crate::recovery::Repair::Done { .. }
16312                ));
16313            }
16314        }
16315    }
16316
16317    #[tokio::test]
16318    #[cfg(unix)]
16319    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16320        use std::os::fd::AsRawFd as _;
16321        let tmp = tempfile::tempdir().unwrap();
16322        let mut runner = registered_runner(tmp.path()).await;
16323        runner.state.config.graph.timeout_resource_wait = 1;
16324        let winner = runner.state.candidates[0].clone();
16325        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16326        runner.state.tally = Some(Tally {
16327            first_choice: BTreeMap::new(),
16328            borda: BTreeMap::new(),
16329            winner: winner.label,
16330            rankings: 0,
16331            unanimous_initial: false,
16332            deliberated: false,
16333            changed_votes: 0,
16334            unanimous_final: false,
16335            tie_break: None,
16336            judges: 0,
16337            present: 0,
16338            quorum: 0,
16339            met_quorum: true,
16340            uncontested: Some("fixture".into()),
16341        });
16342        runner.state.graft = Some(GraftRecord {
16343            pre: pre.clone(),
16344            post: None,
16345            lines: None,
16346            limit: None,
16347            agent: None,
16348            outcome: GraftOutcome::Running,
16349            requested: Vec::new(),
16350            adoption: None,
16351            adoption_error: None,
16352        });
16353        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16354        git::commit_all(&winner.worktree, "unfinished graft")
16355            .await
16356            .unwrap();
16357        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16358        let leftover = winner.worktree.join("leftover");
16359        std::fs::write(&leftover, "untrusted edits").unwrap();
16360        let path = runner.state.repo.join(".git/updater.lock");
16361        let external = std::fs::File::create(&path).unwrap();
16362        assert_eq!(
16363            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16364            0
16365        );
16366        assert!(
16367            runner
16368                .graft()
16369                .await
16370                .unwrap_err()
16371                .is::<crate::repo_lock::ResourceBlocked>()
16372        );
16373        assert!(matches!(
16374            runner.state.graft.as_ref().unwrap().outcome,
16375            GraftOutcome::Running
16376        ));
16377        assert_eq!(
16378            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16379            unfinished
16380        );
16381        assert!(leftover.exists());
16382        drop(external);
16383        std::fs::remove_file(&path).unwrap();
16384        std::fs::create_dir(&path).unwrap();
16385        assert!(runner.graft().await.is_err());
16386        assert!(matches!(
16387            runner.state.graft.as_ref().unwrap().outcome,
16388            GraftOutcome::Running
16389        ));
16390        assert_eq!(
16391            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16392            unfinished
16393        );
16394        assert!(leftover.exists());
16395        std::fs::remove_dir(&path).unwrap();
16396        runner.graft().await.unwrap();
16397        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16398        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16399        assert!(!leftover.exists());
16400    }
16401
16402    #[tokio::test]
16403    #[cfg(unix)]
16404    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16405        use std::os::fd::AsRawFd as _;
16406        let tmp = tempfile::tempdir().unwrap();
16407        let mut runner = registered_runner(tmp.path()).await;
16408        runner.state.prep_complete = Some(false);
16409        runner.state.config.graph.timeout_resource_wait = 1;
16410        runner.state.save().unwrap();
16411        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16412        assert_eq!(
16413            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16414            0
16415        );
16416        runner.execute().await.unwrap();
16417        let disk = RunState::load(&runner.state.id).unwrap();
16418        assert!(disk.driver_exited);
16419        assert_eq!(disk.driver_pid, None);
16420        assert_eq!(runner.state.status, RunStatus::Blocked);
16421        assert_eq!(
16422            runner.state.resource_block.as_ref().unwrap().kind,
16423            "repository coordination"
16424        );
16425        assert!(runner.state.prep_failure.is_none());
16426        assert!(runner.state.seats.is_empty());
16427        runner.pause.park();
16428        // Include headroom for Git subprocesses under parallel test load;
16429        // the repository contention deadline itself remains one second.
16430        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16431            .await
16432            .unwrap()
16433            .unwrap();
16434        assert!(runner.state.parked);
16435        assert!(runner.state.prep_failure.is_none());
16436        let disk = RunState::load(&runner.state.id).unwrap();
16437        assert!(disk.driver_exited);
16438        assert_eq!(disk.driver_pid, None);
16439    }
16440
16441    #[tokio::test]
16442    #[cfg(unix)]
16443    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16444        use std::os::fd::AsRawFd as _;
16445        let tmp = tempfile::tempdir().unwrap();
16446        let mut runner = registered_runner(tmp.path()).await;
16447        runner.state.prep_complete = Some(false);
16448        runner.state.config.graph.timeout_resource_wait = 30;
16449        runner.state.save().unwrap();
16450        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16451        assert_eq!(
16452            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16453            0
16454        );
16455        assert!(
16456            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16457                .await
16458                .is_err()
16459        );
16460        let disk = RunState::load(&runner.state.id).unwrap();
16461        assert!(disk.driver_exited);
16462        assert_eq!(disk.driver_pid, None);
16463        assert!(disk.status.resumable());
16464        assert!(runner.state.driver_exited);
16465        assert_eq!(runner.state.driver_pid, None);
16466        runner.state.save().unwrap();
16467        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16468    }
16469
16470    #[tokio::test]
16471    #[cfg(unix)]
16472    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16473        let tmp = tempfile::tempdir().unwrap();
16474        let mut runner = registered_runner(tmp.path()).await;
16475        let winner = runner.state.candidates[0].clone();
16476        let cache = tmp.path().join("cache");
16477        let started = tmp.path().join("pre-gate-started");
16478        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16479        runner.state.config.verify.gate =
16480            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16481        let home = crate::run::home();
16482        let owner =
16483            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16484        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16485            crate::cache::AcquireOutcome::Acquired(g) => g,
16486            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16487        };
16488        let mut gate = Box::pin(runner.run_gate(&winner));
16489        assert!(
16490            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16491                .await
16492                .is_err()
16493        );
16494        assert!(!started.exists(), "pre-gate must wait for the cache too");
16495        // Simulate the wave that already owns the cache entering invoke.
16496        // It must obtain the editor reservation and finish without waiting
16497        // for the gate that is queued behind its cache.
16498        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16499        let editor = crate::repo_lock::SeatLease::checkout_with(
16500            &winner.worktree,
16501            true,
16502            crate::config::test_coordination().as_ref(),
16503            &wait,
16504        )
16505        .await
16506        .unwrap();
16507        drop(editor);
16508        guard.release();
16509        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16510            .await
16511            .unwrap()
16512            .unwrap();
16513        drop(gate);
16514        assert!(outcomes.iter().all(CommandOutcome::ok));
16515        assert!(started.exists());
16516    }
16517
16518    #[tokio::test]
16519    #[cfg(unix)]
16520    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
16521        use std::os::fd::AsRawFd as _;
16522
16523        ask_test_home();
16524        let tmp = tempfile::tempdir().unwrap();
16525        let repo = tmp.path().join("repo");
16526        std::fs::create_dir_all(&repo).unwrap();
16527        init_repo(&repo);
16528        let common = repo.join(".git");
16529        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16530        let mut runner = runner_at(RunStatus::Prep);
16531        runner.state.repo = repo.clone();
16532        runner.state.config.coordination = crate::config::test_coordination();
16533        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16534        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16535        runner.state.config.graph.advise = false;
16536        runner.roles.implementers = vec![spec("implement")];
16537        runner.roles.judges = vec![spec("judge")];
16538        runner.prep().await.unwrap();
16539        let winner = runner.state.candidates[0].clone();
16540        // Emulate edits already left by a completed seat. The fixture CLI
16541        // only reports completion; it performs no repository operations.
16542        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16543        let completed = tmp.path().join("seat-completed");
16544        runner.roles.implementers[0].command = vec![
16545            "sh".into(),
16546            "-c".into(),
16547            format!("touch '{}'; echo completed", completed.display()),
16548        ];
16549        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16550        assert_eq!(
16551            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16552            0
16553        );
16554        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16555        let mut implement = Box::pin(runner.implement());
16556        tokio::select! {
16557            result = &mut implement => panic!("rescue must wait: {result:?}"),
16558            result = tokio::time::timeout(Duration::from_secs(10), async {
16559                while !completed.exists() {
16560                    tokio::time::sleep(Duration::from_millis(20)).await;
16561                }
16562            }) => result.unwrap(),
16563        }
16564        assert!(
16565            tokio::time::timeout(Duration::from_millis(200), &mut implement)
16566                .await
16567                .is_err()
16568        );
16569        assert_eq!(
16570            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16571            before
16572        );
16573        assert_eq!(
16574            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16575            0
16576        );
16577        tokio::time::timeout(Duration::from_secs(10), &mut implement)
16578            .await
16579            .unwrap()
16580            .unwrap();
16581        drop(implement);
16582        assert_ne!(
16583            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16584            before
16585        );
16586        assert!(git::is_clean(&winner.worktree).await.unwrap());
16587
16588        let started = tmp.path().join("pre-gate-started");
16589        let proceed = tmp.path().join("pre-gate-proceed");
16590        let checked = tmp.path().join("gate-ran");
16591        runner.state.config.verify.pre_gate = vec![format!(
16592            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16593            started.display(),
16594            proceed.display()
16595        )];
16596        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
16597        assert_eq!(
16598            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16599            0
16600        );
16601        let mut gate = Box::pin(runner.run_gate(&winner));
16602        assert!(
16603            tokio::time::timeout(Duration::from_millis(200), &mut gate)
16604                .await
16605                .is_err()
16606        );
16607        assert!(!started.exists());
16608        assert!(!checked.exists());
16609        assert!(git::is_clean(&winner.worktree).await.unwrap());
16610        assert_eq!(
16611            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16612            0
16613        );
16614        tokio::select! {
16615            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
16616            result = tokio::time::timeout(Duration::from_secs(10), async {
16617                while !started.exists() {
16618                    tokio::time::sleep(Duration::from_millis(20)).await;
16619                }
16620            }) => result.unwrap(),
16621        }
16622        assert_eq!(
16623            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16624            -1,
16625            "mechanical edits must hold the real lock"
16626        );
16627        std::fs::write(proceed, "ready").unwrap();
16628        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16629            .await
16630            .unwrap()
16631            .unwrap();
16632        drop(gate);
16633        assert!(outcomes.iter().all(CommandOutcome::ok));
16634        assert!(checked.exists());
16635        assert!(runner.state.pre_gate_commit.is_some());
16636        assert!(git::is_clean(&winner.worktree).await.unwrap());
16637        assert_eq!(
16638            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16639            0,
16640            "gate completion must release coordination"
16641        );
16642        drop(outsider);
16643        std::fs::remove_file(common.join("updater.lock")).unwrap();
16644        std::fs::create_dir(common.join("updater.lock")).unwrap();
16645        std::fs::remove_file(&started).unwrap();
16646        std::fs::remove_file(&checked).unwrap();
16647        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16648        let error = runner.run_gate(&winner).await.unwrap_err();
16649        assert!(
16650            error
16651                .to_string()
16652                .contains("acquire mandatory repository lock")
16653        );
16654        assert!(
16655            !started.exists(),
16656            "failed acquisition must prevent pre-gate"
16657        );
16658        assert!(!checked.exists(), "failed acquisition must prevent gate");
16659        assert!(git::is_clean(&winner.worktree).await.unwrap());
16660        assert_eq!(
16661            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16662            head
16663        );
16664    }
16665
16666    #[tokio::test]
16667    #[cfg(unix)]
16668    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16669        use std::os::fd::AsRawFd as _;
16670        use std::time::Duration;
16671
16672        ask_test_home();
16673        let tmp = tempfile::tempdir().unwrap();
16674        let repo = tmp.path().join("repo");
16675        std::fs::create_dir_all(&repo).unwrap();
16676        init_repo(&repo);
16677        let common = repo.join(".git");
16678        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16679        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16680        assert_eq!(
16681            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16682            0
16683        );
16684        let mut runner = runner_at(RunStatus::Prep);
16685        runner.state.repo = repo.clone();
16686        runner.state.config.coordination = crate::config::test_coordination();
16687        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16688        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16689        runner.state.config.graph.advise = true;
16690        runner.state.config.graph.advisors = 1;
16691        runner.roles.implementers = vec![spec("implement")];
16692        runner.roles.judges = vec![spec("judge")];
16693        let root = runner.state.worktree_root();
16694        let started = tmp.path().join("setup-started");
16695        let proceed = tmp.path().join("setup-proceed");
16696        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16697            run: Some(format!(
16698                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16699                started.display(),
16700                proceed.display()
16701            )),
16702            ..Default::default()
16703        }];
16704        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16705        let config = git::git(&repo, &["config", "--local", "--list"])
16706            .await
16707            .unwrap();
16708        let mut prep = Box::pin(runner.prep());
16709        assert!(
16710            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16711                .await
16712                .is_err()
16713        );
16714        assert!(
16715            !root.exists(),
16716            "contention must prevent even checkout creation"
16717        );
16718        assert!(!started.exists(), "contention must prevent setup");
16719        assert_eq!(
16720            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16721            branches
16722        );
16723        assert_eq!(
16724            git::git(&repo, &["config", "--local", "--list"])
16725                .await
16726                .unwrap(),
16727            config
16728        );
16729        drop(lock);
16730        tokio::select! {
16731            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16732            result = tokio::time::timeout(Duration::from_secs(10), async {
16733                while !started.exists() {
16734                    tokio::time::sleep(Duration::from_millis(20)).await;
16735                }
16736            }) => result.unwrap(),
16737        }
16738        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16739        assert_eq!(
16740            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16741            -1
16742        );
16743        assert!(
16744            tokio::time::timeout(
16745                Duration::from_millis(100),
16746                crate::repo_lock::SeatLease::for_checkout(
16747                    &repo,
16748                    true,
16749                    crate::config::test_coordination().as_ref()
16750                )
16751            )
16752            .await
16753            .is_err(),
16754            "preparation must also exclude local editors"
16755        );
16756        std::fs::write(proceed, "ready").unwrap();
16757        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16758            .await
16759            .unwrap()
16760            .unwrap();
16761        drop(prep);
16762        assert_eq!(runner.state.prep_complete, Some(true));
16763        assert!(root.join("judge-1").exists());
16764        assert!(root.join("advisor-1").exists());
16765        assert_eq!(
16766            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16767            0
16768        );
16769    }
16770
16771    #[tokio::test]
16772    #[cfg(unix)]
16773    async fn preparation_lock_failure_prevents_repository_changes() {
16774        ask_test_home();
16775        let tmp = tempfile::tempdir().unwrap();
16776        let repo = tmp.path().join("repo");
16777        std::fs::create_dir_all(&repo).unwrap();
16778        init_repo(&repo);
16779        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16780        // A directory at the required lock path makes opening the real lock
16781        // fail, rather than merely exercising an invalid registration.
16782        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16783        let mut runner = runner_at(RunStatus::Prep);
16784        runner.state.repo = repo.clone();
16785        runner.state.config.coordination = crate::config::test_coordination();
16786        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16787        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16788        runner.roles.implementers = vec![spec("implement")];
16789        let error = runner.prep().await.unwrap_err();
16790        assert!(
16791            error
16792                .to_string()
16793                .contains("acquire mandatory repository lock")
16794        );
16795        assert!(!runner.state.worktree_root().exists());
16796        assert!(runner.state.candidates.is_empty());
16797        assert!(!repo.join(".git/config.worktree").exists());
16798        assert_eq!(
16799            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16800            "* main"
16801        );
16802    }
16803
16804    #[tokio::test]
16805    async fn preparation_records_creation_intent_before_git_can_fail() {
16806        ask_test_home();
16807        let tmp = tempfile::tempdir().unwrap();
16808        let repo = tmp.path().join("repo");
16809        std::fs::create_dir_all(&repo).unwrap();
16810        init_repo(&repo);
16811        let mut runner = runner_at(RunStatus::Prep);
16812        runner.state.repo = repo.clone();
16813        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16814        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16815        runner.state.config.blind.commit_msg_hook = false;
16816        runner.roles.implementers = vec![spec("one")];
16817        let label = blind::assign_labels(1, runner.state.seed)[0];
16818        let branch = runner.state.branch_for(label);
16819        // A conflicting branch makes Git refuse creation before a candidate
16820        // can be registered. The durable intent must still identify it.
16821        git::git(&repo, &["branch", &branch]).await.unwrap();
16822        assert!(runner.prep().await.is_err());
16823        let saved = RunState::load(&runner.state.id).unwrap();
16824        assert!(saved.candidates.is_empty());
16825        let event = saved
16826            .events
16827            .iter()
16828            .find(|e| e.node == "prep-intent")
16829            .unwrap();
16830        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16831        assert_eq!(intent["branch"], branch);
16832        assert_eq!(intent["start"], runner.state.base_commit);
16833        assert_eq!(
16834            intent["worktree"],
16835            runner
16836                .state
16837                .worktree_root()
16838                .join(format!("cand-{label}"))
16839                .to_string_lossy()
16840                .as_ref()
16841        );
16842        assert_eq!(intent["picks"], serde_json::json!([]));
16843    }
16844
16845    #[tokio::test]
16846    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16847        ask_test_home();
16848        let tmp = tempfile::tempdir().unwrap();
16849        let repo = tmp.path().join("repo");
16850        std::fs::create_dir_all(&repo).unwrap();
16851        init_repo(&repo);
16852        let mut runner = runner_at(RunStatus::Prep);
16853        runner.state.repo = repo.clone();
16854        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16855        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16856        runner.state.sources.pick_commits.push(refs::Input {
16857            token: "missing".into(),
16858            sha: "0".repeat(40),
16859            provenance: refs::Provenance::ExplicitCli,
16860        });
16861        assert!(runner.prep().await.is_err());
16862        assert!(runner.state.candidates.is_empty());
16863        assert!(!runner.state.worktree_root().exists());
16864    }
16865
16866    #[tokio::test]
16867    async fn prose_and_legacy_inference_never_import_into_candidates() {
16868        ask_test_home();
16869        let tmp = tempfile::tempdir().unwrap();
16870        let repo = tmp.path().join("repo");
16871        std::fs::create_dir_all(&repo).unwrap();
16872        init_repo(&repo);
16873        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16874        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16875            .await
16876            .unwrap();
16877        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16878        git::git(&repo, &["add", "."]).await.unwrap();
16879        git::git(&repo, &["commit", "-m", "historical implementation"])
16880            .await
16881            .unwrap();
16882        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16883        git::git(&repo, &["checkout", "main"]).await.unwrap();
16884        for instruction in [
16885            format!("Example: magi/history/A at {source}"),
16886            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16887            format!("Never import magi/history/A or {source}"),
16888            format!("Conversation answer: I mentioned {source} only as background"),
16889        ] {
16890            let mut runner = runner_at(RunStatus::Prep);
16891            runner.state.repo = repo.clone();
16892            runner.state.base_commit = base.clone();
16893            runner.state.instruction = instruction.clone();
16894            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16895            runner.state.config.blind.commit_msg_hook = false;
16896            runner.state.seeds = vec![refs::Seed {
16897                token: "magi/history/A".into(),
16898                sha: source.clone(),
16899                kind: refs::SeedKind::Unmerged,
16900                branch: true,
16901                detail: String::new(),
16902            }];
16903            runner.roles.implementers = vec![spec("one")];
16904            assert_eq!(seeded_instruction(&runner.state), instruction);
16905            // Model an old record with inferred seeds but no structured input field.
16906            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16907            legacy.as_object_mut().unwrap().remove("sources");
16908            runner.state = serde_json::from_value(legacy).unwrap();
16909            assert_eq!(runner.state.sources, refs::Sources::default());
16910            runner.state.save().unwrap();
16911            runner.state = RunState::load(&runner.state.id).unwrap();
16912            runner.prep().await.unwrap();
16913            for candidate in &runner.state.candidates {
16914                assert_eq!(
16915                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16916                    base
16917                );
16918                assert!(!candidate.worktree.join("unwanted").exists());
16919            }
16920        }
16921    }
16922
16923    #[tokio::test]
16924    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16925        ask_test_home();
16926        let tmp = tempfile::tempdir().unwrap();
16927        let repo = tmp.path().join("repo");
16928        std::fs::create_dir_all(&repo).unwrap();
16929        init_repo(&repo);
16930        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16931        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16932        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16933        git::git(&repo, &["add", "."]).await.unwrap();
16934        git::git(&repo, &["commit", "-m", "required seed"])
16935            .await
16936            .unwrap();
16937        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16938        git::git(&repo, &["checkout", "main"]).await.unwrap();
16939        let mut runner = runner_at(RunStatus::Prep);
16940        runner.state.repo = repo.clone();
16941        runner.state.base_commit = base.clone();
16942        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16943        runner.state.config.graph.advise = false;
16944        runner.state.config.blind.commit_msg_hook = false;
16945        runner.state.sources =
16946            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16947                .await
16948                .unwrap();
16949        runner.roles.implementers = vec![spec("one"), spec("two")];
16950        runner.roles.judges = vec![spec("judge")];
16951        let label = blind::assign_labels(2, runner.state.seed)[0];
16952        let branch = runner.state.branch_for(label);
16953        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16954        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16955            .await
16956            .unwrap();
16957        runner.state.candidates.push(Candidate {
16958            index: 0,
16959            label,
16960            agent: "one".into(),
16961            branch,
16962            worktree,
16963            summary: String::new(),
16964            stat: String::new(),
16965            files: 0,
16966            commits: 0,
16967            empty: false,
16968            failed: None,
16969            verified_noop: None,
16970            duration_ms: 0,
16971            folded: false,
16972        });
16973        runner.state.save().unwrap();
16974        // Reload the checkpoint immediately before its first cherry-pick.
16975        runner.state = RunState::load(&runner.state.id).unwrap();
16976        assert_eq!(runner.state.prep_complete, Some(false));
16977        runner.prep().await.unwrap();
16978        assert_eq!(runner.state.prep_complete, Some(true));
16979        assert_eq!(runner.state.candidates.len(), 2);
16980        for candidate in &runner.state.candidates {
16981            assert_eq!(
16982                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16983                git::tree_of(&repo, &seed).await.unwrap()
16984            );
16985            assert_eq!(
16986                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16987                "required commit"
16988            );
16989        }
16990        assert!(runner.state.worktree_root().join("judge-1").exists());
16991        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16992        runner.prep().await.unwrap();
16993        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16994
16995        runner.state.prep_complete = Some(false);
16996        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16997            run: Some(format!(
16998                "test -f '{}'",
16999                tmp.path().join("dependency-ready").display()
17000            )),
17001            ..Default::default()
17002        }];
17003        assert!(runner.prep().await.is_err());
17004        assert!(runner.state.prep_failure.is_some());
17005        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
17006        runner.state = RunState::load(&runner.state.id).unwrap();
17007        assert!(
17008            runner.prep().await.is_err(),
17009            "correcting the cause alone must not auto-retry"
17010        );
17011        let failed_at = runner.state.events.last().unwrap().at;
17012        assert!(
17013            runner.retry_preparation(failed_at).is_err(),
17014            "old approvals cannot unlock the hold"
17015        );
17016        let mut task = crate::queue::Task::new(
17017            "retry".into(),
17018            "retry setup".into(),
17019            repo.clone(),
17020            crate::queue::Source::Human,
17021        );
17022        task.start(runner.state.id.clone());
17023        task.hold_machine(Some("setup failed".into()));
17024        task.release_operator("cli", None);
17025        runner
17026            .retry_preparation(task.resumption.as_ref().unwrap().at)
17027            .unwrap();
17028        runner.prep().await.unwrap();
17029        assert!(runner.state.prep_failure.is_none());
17030        assert_eq!(runner.state.prep_complete, Some(true));
17031        assert_eq!(runner.state.candidates.len(), 2);
17032        assert!(runner.state.worktree_root().join("judge-1").exists());
17033        for candidate in &runner.state.candidates {
17034            assert_eq!(
17035                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17036                git::tree_of(&repo, &seed).await.unwrap()
17037            );
17038        }
17039    }
17040
17041    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
17042        let mut heads = Vec::new();
17043        for candidate in candidates {
17044            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
17045        }
17046        heads
17047    }
17048
17049    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
17050        ask_test_home();
17051        let tmp = tempfile::tempdir().unwrap();
17052        let repo = tmp.path().join("repo");
17053        std::fs::create_dir(&repo).unwrap();
17054        init_repo(&repo);
17055        let mut runner = runner_at(RunStatus::Reviewing);
17056        runner.state.repo = repo.clone();
17057        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17058        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17059        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17060            let branch = format!("candidate-{label}");
17061            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17062            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17063                .await
17064                .unwrap();
17065            if label == 'B' {
17066                std::fs::write(worktree.join("change"), "winner").unwrap();
17067                git::rescue_commit(&worktree, "candidate change")
17068                    .await
17069                    .unwrap();
17070            }
17071            runner.state.candidates.push(Candidate {
17072                index,
17073                label,
17074                agent: "alpha".into(),
17075                branch,
17076                worktree,
17077                summary: "completed reply".into(),
17078                stat: String::new(),
17079                files: usize::from(label == 'B'),
17080                commits: usize::from(label == 'B'),
17081                empty: label == 'A',
17082                failed: None,
17083                verified_noop: None,
17084                duration_ms: 1,
17085                folded: false,
17086            });
17087        }
17088        runner.state.judge_skipped = true;
17089        runner.state.tally = Some(Tally {
17090            first_choice: BTreeMap::new(),
17091            borda: BTreeMap::new(),
17092            winner: 'B',
17093            rankings: 0,
17094            unanimous_initial: false,
17095            deliberated: false,
17096            changed_votes: 0,
17097            unanimous_final: false,
17098            tie_break: None,
17099            judges: 0,
17100            present: 0,
17101            quorum: 0,
17102            met_quorum: true,
17103            uncontested: Some("only B produced a change".into()),
17104        });
17105        runner.state.save().unwrap();
17106        (tmp, runner)
17107    }
17108
17109    #[tokio::test]
17110    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17111        let (_tmp, mut runner) = preservation_resume_fixture().await;
17112        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17113        runner.state.config.disk.cache_limit_bytes = 0;
17114        runner.state.config.graph.advise = true;
17115        runner.state.config.graph.advisors = 1;
17116        let advisor = runner.state.worktree_root().join("advisor-1");
17117        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17118            .await
17119            .unwrap();
17120        let home = crate::run::home();
17121        let loser =
17122            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17123        let winner =
17124            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17125        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17126        for target in [&loser, &winner, &advisor] {
17127            std::fs::write(target.join("build-output"), "compiled").unwrap();
17128        }
17129
17130        runner.fold_losers().await.unwrap();
17131
17132        assert!(!loser.join("build-output").exists());
17133        assert!(!advisor.join("build-output").exists());
17134        assert!(winner.join("build-output").is_file());
17135    }
17136
17137    #[tokio::test]
17138    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17139        let (_tmp, mut runner) = preservation_resume_fixture().await;
17140        runner.state.candidates[0].folded = true;
17141        runner.state.config.graph.advise = true;
17142        runner.state.config.graph.advisors = 2;
17143        let repo = runner.state.repo.clone();
17144        let root = runner.state.worktree_root();
17145        let discarded = root.join("advisor-1");
17146        git::worktree_add_detached(&repo, &discarded, "main")
17147            .await
17148            .unwrap();
17149        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17150        let protected = root.join("advisor-2");
17151        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17152            .await
17153            .unwrap();
17154        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17155        runner.state.save().unwrap();
17156
17157        assert!(runner.fold_losers().await.is_err());
17158        assert!(!discarded.exists());
17159        assert!(protected.join("keep").exists());
17160        let saved = RunState::load(&runner.state.id).unwrap();
17161        assert!(saved.events.iter().any(|event| {
17162            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17163        }));
17164    }
17165
17166    #[tokio::test]
17167    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17168        let (tmp, mut runner) = preservation_resume_fixture().await;
17169        let repo = runner.state.repo.clone();
17170        let root = runner.state.worktree_root();
17171        for name in ["advisor-3", "judge-1", "review-2"] {
17172            let path = root.join(name);
17173            git::worktree_add_detached(&repo, &path, "main")
17174                .await
17175                .unwrap();
17176            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17177            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17178            remove_read_seat_worktree(&mut runner.state, &path)
17179                .await
17180                .unwrap();
17181            assert!(!path.exists());
17182        }
17183        let outside = tmp.path().join("advisor-1");
17184        let unknown = root.join("unknown");
17185        let attached = root.join("advisor-4");
17186        git::worktree_add_detached(&repo, &outside, "main")
17187            .await
17188            .unwrap();
17189        git::worktree_add_detached(&repo, &unknown, "main")
17190            .await
17191            .unwrap();
17192        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17193            .await
17194            .unwrap();
17195        let foreign = tmp.path().join("foreign");
17196        std::fs::create_dir(&foreign).unwrap();
17197        init_repo(&foreign);
17198        let wrong_repo = root.join("judge-2");
17199        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17200            .await
17201            .unwrap();
17202        let candidate = runner.state.candidates[0].worktree.clone();
17203        for path in [outside, unknown, attached, wrong_repo, candidate] {
17204            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17205            assert!(
17206                remove_read_seat_worktree(&mut runner.state, &path)
17207                    .await
17208                    .is_err()
17209            );
17210            assert_eq!(
17211                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17212                "keep"
17213            );
17214        }
17215    }
17216
17217    #[tokio::test]
17218    #[cfg(unix)]
17219    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17220        for (solo, failed_checkpoint) in
17221            [(true, false), (false, false), (true, true), (false, true)]
17222        {
17223            let (_tmp, mut runner) = preservation_resume_fixture().await;
17224            if solo {
17225                runner.state.candidates.retain(|c| c.label == 'A');
17226            }
17227            runner.state.candidates[0].empty = false;
17228            runner.state.candidates[0].summary.clear();
17229            runner.state.tally = None;
17230            runner.state.judge_skipped = false;
17231            runner.state.status = RunStatus::Implementing;
17232            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17233            let mut implementer = spec("alpha");
17234            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17235            runner.roles.implementers = vec![implementer];
17236            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17237            if failed_checkpoint {
17238                std::fs::create_dir_all(&patch).unwrap();
17239            }
17240            runner.state.save().unwrap();
17241            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17242            drop(pressure);
17243            runner.state = RunState::load(&runner.state.id).unwrap();
17244            assert_eq!(runner.state.status, RunStatus::Blocked);
17245            assert!(runner.state.interrupted_implementations.contains(&'A'));
17246            assert_eq!(runner.state.candidates[0].commits, 0);
17247            assert!(!runner.state.candidates[0].empty);
17248            assert!(runner.state.candidates[0].failed.is_none());
17249            if failed_checkpoint {
17250                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17251                std::fs::remove_dir(patch).unwrap();
17252            }
17253            runner.state.resource_block = None;
17254            runner.state.config.disk.min_free_bytes = 0;
17255            runner.roles.implementers[0].command = vec![
17256                "sh".into(),
17257                "-c".into(),
17258                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17259            ];
17260            runner.implement().await.unwrap();
17261            assert!(runner.state.interrupted_implementations.is_empty());
17262            assert!(runner.state.candidate_preservation.is_empty());
17263            assert_eq!(runner.state.candidates[0].commits, 1);
17264            assert!(!runner.state.candidates[0].empty);
17265            assert!(
17266                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17267                    .unwrap()
17268                    .contains("retried empty interrupted seat")
17269            );
17270            if !solo {
17271                assert_eq!(runner.state.candidates[1].commits, 1);
17272            }
17273        }
17274    }
17275
17276    #[tokio::test]
17277    #[cfg(unix)]
17278    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17279        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17280            let (_tmp, mut runner) = preservation_resume_fixture().await;
17281            runner.state.candidates.retain(|c| c.label == 'A');
17282            runner.state.candidates[0].empty = false;
17283            runner.state.candidates[0].summary.clear();
17284            runner.state.tally = None;
17285            runner.state.judge_skipped = false;
17286            runner.state.status = RunStatus::Implementing;
17287            // Force only the real post-spawn watchdog, without failing the
17288            // separate admission check. Existing edits predate its measurement.
17289            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17290            let wt = runner.state.candidates[0].worktree.clone();
17291            std::fs::write(
17292                wt.join("interrupted-source"),
17293                "retain implementation work\n",
17294            )
17295            .unwrap();
17296            if committed {
17297                git::rescue_commit(&wt, "implementation checkpoint")
17298                    .await
17299                    .unwrap();
17300            }
17301            let lock = git::git(
17302                &wt,
17303                &[
17304                    "rev-parse",
17305                    "--path-format=absolute",
17306                    "--git-path",
17307                    "index.lock",
17308                ],
17309            )
17310            .await
17311            .unwrap();
17312            if block_rescue {
17313                std::fs::write(&lock, "fixture-owned lock").unwrap();
17314            }
17315            let mut implementer = spec("alpha");
17316            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17317            runner.roles.implementers = vec![implementer];
17318            runner.state.save().unwrap();
17319            let result = runner.implement().await;
17320            drop(pressure);
17321            assert_eq!(result.is_err(), block_rescue);
17322            assert_eq!(
17323                runner.state.resource_block.as_ref().unwrap().kind,
17324                "disk pressure"
17325            );
17326            assert!(
17327                runner
17328                    .state
17329                    .events
17330                    .iter()
17331                    .any(|e| e.message.contains("agent execution interrupted"))
17332            );
17333            assert!(
17334                runner
17335                    .state
17336                    .dir()
17337                    .join("artifacts/candidate-A-recovery/staged.patch")
17338                    .exists()
17339            );
17340            if block_rescue {
17341                let saved = RunState::load(&runner.state.id).unwrap();
17342                assert!(saved.candidate_preservation.contains_key(&'A'));
17343                assert!(!saved.candidates[0].empty);
17344                assert_eq!(
17345                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17346                    "retain implementation work\n"
17347                );
17348                std::fs::remove_file(lock).unwrap();
17349                runner.state = saved;
17350            } else {
17351                assert_eq!(runner.state.status, RunStatus::Blocked);
17352                assert_eq!(runner.state.candidates[0].commits, 1);
17353            }
17354            // Recovery must save the candidate before deciding whether another
17355            // implementation is needed. No implementer is available on retry.
17356            runner.roles.implementers.clear();
17357            runner.state.config.disk.min_free_bytes = 0;
17358            runner.state.resource_block = None;
17359            runner.implement().await.unwrap();
17360            assert!(runner.state.candidate_preservation.is_empty());
17361            assert_eq!(runner.state.candidates[0].commits, 1);
17362            assert!(!runner.state.candidates[0].empty);
17363            assert!(git::is_clean(&wt).await.unwrap());
17364            assert!(
17365                crate::run::read_artifact(&runner.state, "cand-A.patch")
17366                    .unwrap()
17367                    .contains("retain implementation work")
17368            );
17369        }
17370    }
17371
17372    #[tokio::test]
17373    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17374        let (_tmp, mut runner) = preservation_resume_fixture().await;
17375        // Schema 15 already confirmed the unfolded no-change result.
17376        runner.implement().await.unwrap();
17377        assert!(runner.state.candidate_preservation.is_empty());
17378        assert!(
17379            !runner
17380                .state
17381                .dir()
17382                .join("artifacts/candidate-A-recovery")
17383                .exists()
17384        );
17385        runner.fold_losers().await.unwrap();
17386        assert!(!runner.state.candidates[0].worktree.exists());
17387        for schema in [14, crate::run::SCHEMA] {
17388            runner.state.schema = schema;
17389            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17390            runner.state.save().unwrap();
17391            runner.state = RunState::load(&runner.state.id).unwrap();
17392            runner.implement().await.unwrap();
17393            assert!(runner.state.candidate_preservation.is_empty());
17394            assert!(runner.state.candidates[0].folded);
17395            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17396        }
17397    }
17398
17399    #[tokio::test]
17400    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17401        let (_tmp, mut runner) = preservation_resume_fixture().await;
17402        runner.state.candidates.retain(|c| c.label == 'A');
17403        runner.state.tally = None;
17404        runner.state.judge_skipped = false;
17405        let candidate = &mut runner.state.candidates[0];
17406        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17407        candidate.failed = Some("deployment validation unavailable".into());
17408        std::fs::write(
17409            candidate.worktree.join("repair"),
17410            "future launcher policy\n",
17411        )
17412        .unwrap();
17413        runner
17414            .state
17415            .candidate_preservation
17416            .insert('A', "awaiting persistence".into());
17417        runner.persist_candidates().await.unwrap();
17418        let candidate = &runner.state.candidates[0];
17419        assert!(!candidate.empty);
17420        assert_eq!(candidate.commits, 1);
17421        assert_eq!(candidate.files, 1);
17422        assert!(candidate.failed.is_none());
17423        assert!(candidate.summary.contains("EPERM"));
17424        assert!(
17425            crate::run::read_artifact(&runner.state, "cand-A.patch")
17426                .unwrap()
17427                .contains("future launcher policy")
17428        );
17429        assert!(runner.state.candidate_preservation.is_empty());
17430    }
17431
17432    #[tokio::test]
17433    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17434        let (_tmp, mut runner) = preservation_resume_fixture().await;
17435        let wt = runner.state.candidates[0].worktree.clone();
17436        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17437        runner.state.schema = 14;
17438        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17439        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17440        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17441        for _ in 0..2 {
17442            assert!(runner.implement().await.is_err());
17443            assert_eq!(runner.state.status, RunStatus::Blocked);
17444            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17445            assert!(
17446                runner.state.candidates[0].empty,
17447                "old verdict must remain unusable"
17448            );
17449            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17450            assert!(runner.state.judge_skipped);
17451            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17452            assert!(
17453                crate::run::read_artifact(&runner.state, "cand-A.patch")
17454                    .unwrap()
17455                    .contains("owned edits")
17456            );
17457            assert!(wt.exists());
17458            assert_eq!(
17459                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17460                    .await
17461                    .unwrap(),
17462                1
17463            );
17464            runner.state = RunState::load(&runner.state.id).unwrap();
17465        }
17466    }
17467
17468    #[tokio::test]
17469    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17470        let (_tmp, mut runner) = preservation_resume_fixture().await;
17471        let wt = runner.state.candidates[0].worktree.clone();
17472        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17473        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17474        let index_lock = PathBuf::from(
17475            git::git(
17476                &wt,
17477                &[
17478                    "rev-parse",
17479                    "--path-format=absolute",
17480                    "--git-path",
17481                    "index.lock",
17482                ],
17483            )
17484            .await
17485            .unwrap(),
17486        );
17487        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17488        runner.state.schema = 14;
17489        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17490        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17491        assert!(runner.implement().await.is_err());
17492        assert!(runner.after_implement().is_err());
17493        assert!(runner.fold_losers().await.is_err());
17494        assert_eq!(
17495            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17496            "failed seat edits"
17497        );
17498        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17499        runner.state = RunState::load(&runner.state.id).unwrap();
17500        std::fs::remove_file(index_lock).unwrap();
17501        // Recovery finds changes that the old uncontested result never judged.
17502        assert!(runner.implement().await.is_err());
17503        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17504        assert!(runner.state.candidates[0].empty);
17505        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17506        assert!(
17507            crate::run::read_artifact(&runner.state, "cand-A.patch")
17508                .unwrap()
17509                .contains("failed seat edits")
17510        );
17511        assert!(wt.exists());
17512    }
17513
17514    #[tokio::test]
17515    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
17516        let (_tmp, mut runner) = preservation_resume_fixture().await;
17517        let repo = runner.state.repo.clone();
17518        let common = git::git(
17519            &repo,
17520            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
17521        )
17522        .await
17523        .unwrap();
17524        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
17525        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
17526        assert!(runner.fold_losers().await.is_err());
17527        assert!(!runner.state.candidates[0].worktree.exists());
17528        assert!(!runner.state.candidates[0].folded);
17529        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
17530        runner.state = RunState::load(&runner.state.id).unwrap();
17531        std::fs::remove_file(branch_lock).unwrap();
17532        let judge = runner.state.worktree_root().join("judge-1");
17533        git::worktree_add_detached(&repo, &judge, "main")
17534            .await
17535            .unwrap();
17536        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
17537        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
17538            .await
17539            .unwrap();
17540        runner.roles.judges = vec![spec("judge")];
17541        assert!(runner.fold_losers().await.is_err());
17542        runner.state = RunState::load(&runner.state.id).unwrap();
17543        assert!(
17544            runner.state.candidates[0].folded,
17545            "candidate progress saved before judge failure"
17546        );
17547        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17548        assert!(judge.join("uncommitted").exists());
17549        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17550            .await
17551            .unwrap();
17552        runner.fold_losers().await.unwrap();
17553        assert!(!judge.exists());
17554        runner.fold_losers().await.unwrap();
17555    }
17556
17557    #[tokio::test]
17558    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
17559        let (_tmp, mut runner) = preservation_resume_fixture().await;
17560        runner.state.candidates.retain(|c| c.label == 'B');
17561        runner.state.tally = None;
17562        runner.state.judge_skipped = false;
17563        runner.state.prep_complete = Some(true);
17564        runner.state.config.graph.advise = false;
17565        runner.state.config.graph.selected_implementer = Some("alpha".into());
17566        let wt = runner.state.candidates[0].worktree.clone();
17567        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
17568        runner
17569            .state
17570            .candidate_preservation
17571            .insert('B', "awaiting persistence".into());
17572        let index_lock = git::git(
17573            &wt,
17574            &[
17575                "rev-parse",
17576                "--path-format=absolute",
17577                "--git-path",
17578                "index.lock",
17579            ],
17580        )
17581        .await
17582        .unwrap();
17583        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17584        runner.state.save().unwrap();
17585        assert!(runner.execute_graph().await.is_err());
17586        assert_eq!(runner.state.status, RunStatus::Blocked);
17587        assert!(runner.state.candidate_preservation.contains_key(&'B'));
17588        std::fs::remove_file(index_lock).unwrap();
17589        // Park at the next graph boundary: this tests the real selected-seat
17590        // hold guard without dispatching reviewers or publishing anything.
17591        for _ in 0..2 {
17592            runner.state = RunState::load(&runner.state.id).unwrap();
17593            runner.pause.park();
17594            runner.execute_graph().await.unwrap();
17595            assert_eq!(runner.state.status, RunStatus::Implementing);
17596            assert!(runner.state.candidate_preservation.is_empty());
17597            assert_eq!(runner.state.candidates[0].commits, 2);
17598            assert!(runner.state.tally.is_none());
17599        }
17600        runner.implement().await.unwrap();
17601        assert_eq!(runner.state.status, RunStatus::Judging);
17602        // A genuine selected-implementer hold must still require release.
17603        runner.state.status = RunStatus::Blocked;
17604        runner.state.candidates[0].failed = Some("implementation failed".into());
17605        runner.state.save().unwrap();
17606        let error = runner.execute_graph().await.unwrap_err();
17607        assert!(
17608            error
17609                .to_string()
17610                .contains("selected implementation is held")
17611        );
17612    }
17613
17614    #[tokio::test]
17615    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
17616        let (_tmp, mut runner) = preservation_resume_fixture().await;
17617        let repo = runner.state.repo.clone();
17618        let candidate = runner.state.candidates[0].clone();
17619        // Remove only the disposable fixture directory, leaving Git's linked
17620        // worktree registration and branch intact, as in a vanished checkout.
17621        let registered = git::worktree_holding(&repo, &candidate.branch)
17622            .await
17623            .unwrap()
17624            .unwrap();
17625        assert_eq!(
17626            registered.canonicalize().unwrap(),
17627            candidate.worktree.canonicalize().unwrap()
17628        );
17629        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17630        assert_eq!(
17631            git::worktree_holding(&repo, &candidate.branch)
17632                .await
17633                .unwrap(),
17634            Some(registered)
17635        );
17636        assert!(
17637            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17638            "the stale registration initially keeps the branch checked out"
17639        );
17640        runner.fold_losers().await.unwrap();
17641        assert!(runner.state.candidates[0].folded);
17642        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17643        assert_eq!(
17644            git::worktree_holding(&repo, &candidate.branch)
17645                .await
17646                .unwrap(),
17647            None
17648        );
17649        runner.state = RunState::load(&runner.state.id).unwrap();
17650        runner.fold_losers().await.unwrap();
17651    }
17652
17653    #[tokio::test]
17654    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17655        let (_tmp, mut runner) = preservation_resume_fixture().await;
17656        let repo = runner.state.repo.clone();
17657        let candidate = runner.state.candidates[0].clone();
17658        let winner = runner.state.candidates[1].clone();
17659        let registered = git::worktree_holding(&repo, &candidate.branch)
17660            .await
17661            .unwrap()
17662            .unwrap();
17663        assert_eq!(
17664            registered.canonicalize().unwrap(),
17665            candidate.worktree.canonicalize().unwrap()
17666        );
17667        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17668        assert_eq!(
17669            git::worktree_holding(&repo, &candidate.branch)
17670                .await
17671                .unwrap(),
17672            Some(registered)
17673        );
17674        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17675
17676        for _ in 0..2 {
17677            fold_run(&mut runner.state, false, &crate::run::home())
17678                .await
17679                .unwrap();
17680            runner.state = RunState::load(&runner.state.id).unwrap();
17681            assert!(runner.state.candidates[0].folded);
17682            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17683            assert_eq!(
17684                git::worktree_holding(&repo, &candidate.branch)
17685                    .await
17686                    .unwrap(),
17687                None
17688            );
17689            assert!(!runner.state.candidates[1].folded);
17690            assert!(winner.worktree.exists());
17691            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17692        }
17693    }
17694    #[tokio::test]
17695    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17696        for sidecar in [false, true] {
17697            let tmp = tempfile::tempdir().unwrap();
17698            let home = tmp.path().join("home");
17699            let repo = tmp.path().join("repo");
17700            std::fs::create_dir(&repo).unwrap();
17701            init_repo(&repo);
17702            let mut state = runner_at(RunStatus::Superseded).state;
17703            state.repo = repo.clone();
17704            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17705            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17706            state.driver_exited = true;
17707            state.reserve_under(&home).unwrap();
17708            git::git(
17709                &repo,
17710                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17711            )
17712            .await
17713            .unwrap();
17714            let wt = state.worktree_root().join("cand-A");
17715            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17716                .await
17717                .unwrap();
17718            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17719            git::commit_all(&wt, "fixture: independent source")
17720                .await
17721                .unwrap();
17722            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17723            state.candidates.push(Candidate {
17724                index: 0,
17725                label: 'A',
17726                agent: "fixture".into(),
17727                branch: "candidate".into(),
17728                worktree: wt.clone(),
17729                summary: String::new(),
17730                stat: String::new(),
17731                files: 0,
17732                commits: 0,
17733                empty: false,
17734                failed: None,
17735                verified_noop: None,
17736                duration_ms: 0,
17737                folded: false,
17738            });
17739            let mut task = crate::queue::Task::new(
17740                "task".into(),
17741                "task".into(),
17742                repo.clone(),
17743                crate::queue::Source::Human,
17744            );
17745            task.runs.push(state.id.clone());
17746            crate::queue::Queue::at(home.join("queue"))
17747                .put(&mut task)
17748                .unwrap();
17749            if sidecar {
17750                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17751            }
17752            state.save_under(&home).unwrap();
17753            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17754            assert!(
17755                fold_run(&mut state, true, &home)
17756                    .await
17757                    .unwrap_err()
17758                    .to_string()
17759                    .contains(&reason)
17760            );
17761            let mut disk = state.config.disk.clone();
17762            disk.fold_grace_secs = 0;
17763            assert_eq!(
17764                crate::clean::fold_due(
17765                    &home.join("runs"),
17766                    &home,
17767                    &state.worktree_root(),
17768                    &disk,
17769                    Timestamp::now() + std::time::Duration::from_secs(10),
17770                )
17771                .await
17772                .unwrap(),
17773                (0, 0)
17774            );
17775            assert!(wt.exists());
17776            state.status = RunStatus::Blocked;
17777            state.save_under(&home).unwrap();
17778            assert!(
17779                fold_run_overriding_recovery_retention(&mut state, true, &home)
17780                    .await
17781                    .is_err()
17782            );
17783            state.status = RunStatus::Superseded;
17784            state.driver_exited = false;
17785            state.driver_claimed = None;
17786            state.save_under(&home).unwrap();
17787            assert!(
17788                fold_run_overriding_recovery_retention(&mut state, true, &home)
17789                    .await
17790                    .is_err()
17791            );
17792            state.driver_pid = Some(std::process::id());
17793            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17794            state.save_under(&home).unwrap();
17795            assert!(
17796                fold_run_overriding_recovery_retention(&mut state, true, &home)
17797                    .await
17798                    .is_err()
17799            );
17800            state.driver_exited = true;
17801            state.driver_pid = None;
17802            state.driver_started_at = None;
17803            state.save_under(&home).unwrap();
17804            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17805            assert!(
17806                fold_run_overriding_recovery_retention(&mut state, true, &home)
17807                    .await
17808                    .is_err()
17809            );
17810            drop(lease);
17811            #[cfg(unix)]
17812            {
17813                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17814                assert!(
17815                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17816                        .await
17817                        .is_err()
17818                );
17819                drop(output);
17820            }
17821            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17822            assert!(
17823                fold_run_overriding_recovery_retention(&mut state, true, &home)
17824                    .await
17825                    .is_err()
17826            );
17827            drop(owner);
17828            let checkpoint = git::git(
17829                &wt,
17830                &[
17831                    "rev-parse",
17832                    "--path-format=absolute",
17833                    "--git-path",
17834                    "CHERRY_PICK_HEAD",
17835                ],
17836            )
17837            .await
17838            .unwrap();
17839            std::fs::write(&checkpoint, &head).unwrap();
17840            assert!(
17841                fold_run_overriding_recovery_retention(&mut state, true, &home)
17842                    .await
17843                    .is_err()
17844            );
17845            std::fs::remove_file(checkpoint).unwrap();
17846            std::fs::write(wt.join("dirty"), "keep").unwrap();
17847            assert!(
17848                fold_run_overriding_recovery_retention(&mut state, true, &home)
17849                    .await
17850                    .is_err()
17851            );
17852            assert!(wt.join("dirty").exists());
17853            std::fs::remove_file(wt.join("dirty")).unwrap();
17854            let evidence = home
17855                .join("runs")
17856                .join(&state.id)
17857                .join("artifacts/fold-evidence");
17858            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17859            std::fs::write(&evidence, "blocked archive").unwrap();
17860            assert!(
17861                fold_run_overriding_recovery_retention(&mut state, true, &home)
17862                    .await
17863                    .is_err()
17864            );
17865            assert!(wt.exists());
17866            assert!(
17867                !RunState::load_under(&state.id, &home)
17868                    .unwrap()
17869                    .events
17870                    .iter()
17871                    .any(|event| event.message.contains("--override-recovery-retention"))
17872            );
17873            std::fs::remove_file(&evidence).unwrap();
17874            fold_run_overriding_recovery_retention(&mut state, true, &home)
17875                .await
17876                .unwrap();
17877            assert!(!wt.exists());
17878            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17879            assert!(
17880                git::worktree_holding(&repo, "candidate")
17881                    .await
17882                    .unwrap()
17883                    .is_none()
17884            );
17885            assert!(
17886                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17887                    .unwrap()
17888                    .contains("retained implementation")
17889            );
17890            assert!(evidence.join(format!("{head}.index")).is_file());
17891            let saved = RunState::load_under(&state.id, &home).unwrap();
17892            assert_eq!(saved.status, RunStatus::Superseded);
17893            assert!(saved.candidates[0].folded);
17894            assert!(saved.events.iter().any(|event| {
17895                event.message.contains("--override-recovery-retention")
17896                    && event.message.contains(&state.id)
17897                    && event.message.contains(&reason)
17898            }));
17899            assert_eq!(
17900                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17901                sidecar
17902            );
17903        }
17904    }
17905
17906    #[tokio::test]
17907    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17908        ask_test_home();
17909        let tmp = tempfile::tempdir().unwrap();
17910        let repo = tmp.path().join("repo");
17911        std::fs::create_dir(&repo).unwrap();
17912        init_repo(&repo);
17913        let mut runner = runner_at(RunStatus::Implementing);
17914        runner.state.repo = repo.clone();
17915        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17916        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17917        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17918            let branch = format!("candidate-{label}");
17919            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17920            git::worktree_add_branch(&repo, &wt, &branch, "main")
17921                .await
17922                .unwrap();
17923            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17924            git::git(&wt, &["add", "README.md"]).await.unwrap();
17925            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17926            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17927            runner.state.candidates.push(Candidate {
17928                index,
17929                label,
17930                agent: "alpha".to_owned(),
17931                branch,
17932                worktree: wt,
17933                summary: "completed implementation".to_owned(),
17934                stat: String::new(),
17935                files: 0,
17936                commits: 0,
17937                empty: false,
17938                failed: None,
17939                verified_noop: None,
17940                duration_ms: 42,
17941                folded: false,
17942            });
17943            runner
17944                .state
17945                .candidate_preservation
17946                .insert(label, "awaiting persistence".to_owned());
17947        }
17948        let wt = runner.state.candidates[0].worktree.clone();
17949        let index_lock = git::git(
17950            &wt,
17951            &[
17952                "rev-parse",
17953                "--path-format=absolute",
17954                "--git-path",
17955                "index.lock",
17956            ],
17957        )
17958        .await
17959        .unwrap();
17960        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17961        runner.state.save().unwrap();
17962        assert!(runner.persist_candidates().await.is_err());
17963        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17964        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17965        assert_eq!(
17966            runner.state.candidates[1].commits, 1,
17967            "other results are still collected"
17968        );
17969        assert!(
17970            !runner.state.candidates[0].empty,
17971            "failed rescue is not no change"
17972        );
17973        assert_eq!(
17974            runner.state.candidates[0].summary,
17975            "completed implementation"
17976        );
17977        assert!(runner.after_implement().is_err());
17978        let home = tmp.path().join("fold-home");
17979        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17980        assert!(wt.join("new-file").exists());
17981        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17982        assert!(recovery.join("staged.patch").exists());
17983        assert!(recovery.join("unstaged.patch").exists());
17984        assert_eq!(
17985            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17986            "untracked edits\n"
17987        );
17988        runner.state.begin_pass();
17989        runner.state.end_pass_parked(ParkCause::Upgrade {
17990            from: "1.0".into(),
17991            to: Some("1.1".into()),
17992        });
17993        runner.state.save().unwrap();
17994        runner.state = RunState::load(&runner.state.id).unwrap();
17995        assert!(matches!(
17996            runner.state.passes.last().unwrap().end,
17997            Some(crate::run::PassEnd::Parked {
17998                cause: ParkCause::Upgrade { .. }
17999            })
18000        ));
18001        std::fs::remove_file(index_lock).unwrap();
18002        // No implementer is configured: a persistence retry cannot dispatch a seat.
18003        runner.implement().await.unwrap();
18004        assert!(runner.state.candidate_preservation.is_empty());
18005        assert!(
18006            runner
18007                .state
18008                .candidates
18009                .iter()
18010                .all(|c| c.commits == 1 && !c.empty)
18011        );
18012        assert!(git::is_clean(&wt).await.unwrap());
18013        assert!(
18014            crate::run::read_artifact(&runner.state, "cand-A.patch")
18015                .unwrap()
18016                .contains("later tracked edits")
18017        );
18018    }
18019
18020    #[tokio::test]
18021    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
18022        ask_test_home();
18023        let tmp = tempfile::tempdir().unwrap();
18024        let repo = tmp.path().join("repo");
18025        std::fs::create_dir(&repo).unwrap();
18026        init_repo(&repo);
18027        let wt = tmp.path().join("candidate");
18028        git::worktree_add_branch(&repo, &wt, "candidate", "main")
18029            .await
18030            .unwrap();
18031        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18032        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
18033        assert!(wt.join("uncommitted").exists());
18034        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18035        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18036        let mut runner = runner_at(RunStatus::Implementing);
18037        runner.state.repo = repo.clone();
18038        runner.state.base_commit = "missing-base".to_owned();
18039        runner.state.candidates.push(Candidate {
18040            index: 0,
18041            label: 'A',
18042            agent: "alpha".into(),
18043            branch: "candidate".into(),
18044            worktree: wt.clone(),
18045            summary: "completed".into(),
18046            stat: String::new(),
18047            files: 0,
18048            commits: 0,
18049            empty: false,
18050            failed: None,
18051            verified_noop: None,
18052            duration_ms: 1,
18053            folded: false,
18054        });
18055        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18056        assert!(
18057            fold_run(&mut runner.state, true, &tmp.path().join("home"))
18058                .await
18059                .is_err()
18060        );
18061        assert!(!runner.state.candidates[0].folded);
18062        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18063        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18064        runner
18065            .state
18066            .candidate_preservation
18067            .insert('A', "pending".into());
18068        assert!(runner.persist_candidates().await.is_err());
18069        assert!(!runner.state.candidates[0].empty);
18070        assert!(!runner.state.candidates[0].folded);
18071        assert!(wt.exists());
18072        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18073        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18074        std::fs::create_dir_all(&patch_path).unwrap();
18075        assert!(
18076            runner.persist_candidates().await.is_err(),
18077            "artifact failure stays pending"
18078        );
18079        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18080        assert!(!runner.state.candidates[0].empty);
18081        std::fs::remove_dir(patch_path).unwrap();
18082        runner.persist_candidates().await.unwrap();
18083        assert!(
18084            runner.state.candidates[0].empty,
18085            "only successful inspection confirms no change"
18086        );
18087    }
18088
18089    fn init_repo(dir: &Path) {
18090        let run = |args: &[&str]| {
18091            let out = std::process::Command::new("git")
18092                .args(args)
18093                .current_dir(dir)
18094                .quiet()
18095                .output()
18096                .expect("spawn git");
18097            assert!(
18098                out.status.success(),
18099                "git {args:?} failed: {}",
18100                String::from_utf8_lossy(&out.stderr)
18101            );
18102        };
18103        run(&["init", "-b", "main"]);
18104        run(&["config", "user.name", "magi test"]);
18105        run(&["config", "user.email", "magi@example.com"]);
18106        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18107        run(&["add", "-A"]);
18108        run(&["commit", "-m", "init"]);
18109    }
18110
18111    // `settle_questions` is what closes the ghost the phone showed: a run's
18112    // seat asked something, the run then ended, and nothing was left to
18113    // abandon the question it left `open`. `HOME` is a process-wide
18114    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18115    // first time it runs in the binary — every test below still reaches the
18116    // same directory whichever call won, and each gets its own run id from
18117    // `RunState::new`, so they never collide there.
18118    fn ask_test_home() {
18119        crate::run::pin_test_home();
18120    }
18121
18122    #[test]
18123    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18124        ask_test_home();
18125        let mut runner = runner_at(RunStatus::Prep);
18126        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18127        // A blocked temporary output path makes the terminal save fail while
18128        // preserving the already published reservation.
18129        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18130        let error = guard
18131            .finish(
18132                &mut runner.state,
18133                Err(
18134                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18135                        .into(),
18136                ),
18137            )
18138            .unwrap_err();
18139        assert_eq!(
18140            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18141            std::io::ErrorKind::PermissionDenied
18142        );
18143        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18144        let message = format!("{error:#}");
18145        assert!(message.contains("original refusal"));
18146        assert!(!message.contains("could not save terminal"));
18147        assert_eq!(
18148            error.chain().count(),
18149            2,
18150            "only startup attribution wraps the original error"
18151        );
18152        let saved = RunState::load(&runner.state.id).unwrap();
18153        assert_eq!(saved.status, RunStatus::Blocked);
18154        assert!(!saved.startup.unwrap().complete);
18155    }
18156
18157    #[test]
18158    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18159        ask_test_home();
18160        let mut runner = runner_at(RunStatus::Prep);
18161        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18162        let id = runner.state.id.clone();
18163        drop(guard);
18164        let saved = RunState::load(&id).unwrap();
18165        assert_eq!(saved.status, RunStatus::Blocked);
18166        assert!(!saved.startup.as_ref().unwrap().complete);
18167        assert!(
18168            saved
18169                .startup
18170                .unwrap()
18171                .failure
18172                .unwrap()
18173                .contains("interrupted")
18174        );
18175        assert!(Runner::resume(&id).is_err());
18176    }
18177
18178    #[test]
18179    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18180        ask_test_home();
18181        let mut runner = runner_at(RunStatus::Prep);
18182        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18183        let error = guard
18184            .finish(
18185                &mut runner.state,
18186                Err(
18187                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18188                        .into(),
18189                ),
18190            )
18191            .unwrap_err();
18192        assert_eq!(
18193            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18194            std::io::ErrorKind::PermissionDenied
18195        );
18196        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18197        let mut task = crate::queue::Task::new(
18198            "review".into(),
18199            "criteria".into(),
18200            runner.state.repo.clone(),
18201            crate::queue::Source::Human,
18202        );
18203        task.record_startup_failure(failure.clone());
18204        task.record_startup_failure(failure.clone());
18205        assert_eq!(task.startup_failures.len(), 1);
18206        assert!(task.runs.is_empty());
18207        assert_eq!(task.attempts, 0);
18208    }
18209
18210    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18211        ask_test_home();
18212        let tmp = tempfile::tempdir().unwrap();
18213        let repo = tmp.path().join("repo");
18214        std::fs::create_dir(&repo).unwrap();
18215        init_repo(&repo);
18216        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18217        let origin = tmp.path().join("origin.git");
18218        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18219            .await
18220            .unwrap();
18221        git::git(
18222            &repo,
18223            &["remote", "add", "origin", origin.to_str().unwrap()],
18224        )
18225        .await
18226        .unwrap();
18227        git::git(&repo, &["checkout", "-b", "fix/retained"])
18228            .await
18229            .unwrap();
18230        std::fs::write(repo.join("retained"), "retained change").unwrap();
18231        git::git(&repo, &["add", "."]).await.unwrap();
18232        git::git(&repo, &["commit", "-m", "retained implementation"])
18233            .await
18234            .unwrap();
18235        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18236        git::git(&repo, &["checkout", "main"]).await.unwrap();
18237        std::fs::write(repo.join("base-change"), "new base").unwrap();
18238        git::git(&repo, &["add", "."]).await.unwrap();
18239        git::git(&repo, &["commit", "-m", "base moved"])
18240            .await
18241            .unwrap();
18242        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18243        git::git(&repo, &["checkout", "fix/retained"])
18244            .await
18245            .unwrap();
18246        let mut runner = runner_at(RunStatus::Voting);
18247        runner.state.repo = repo.clone();
18248        runner.state.base_commit = base;
18249        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18250        runner.state.config.disk.min_free_bytes = 0;
18251        runner.state.config.graph.review_rounds = 1;
18252        runner.state.config.verify.e2e = vec!["true".into()];
18253        runner.state.config.verify.gate = vec!["true".into()];
18254        runner.state.candidates = vec![Candidate {
18255            index: 0,
18256            label: 'A',
18257            agent: "fixture".into(),
18258            branch: "fix/retained".into(),
18259            worktree: repo.clone(),
18260            summary: String::new(),
18261            stat: String::new(),
18262            files: 1,
18263            commits: 1,
18264            empty: false,
18265            failed: None,
18266            verified_noop: None,
18267            duration_ms: 0,
18268            folded: false,
18269        }];
18270        runner.state.tally = Some(Tally {
18271            first_choice: BTreeMap::new(),
18272            borda: BTreeMap::new(),
18273            winner: 'A',
18274            rankings: 0,
18275            unanimous_initial: true,
18276            deliberated: false,
18277            changed_votes: 0,
18278            unanimous_final: true,
18279            tie_break: None,
18280            judges: 0,
18281            present: 0,
18282            quorum: 0,
18283            met_quorum: true,
18284            uncontested: Some("review-only".into()),
18285        });
18286        let mut task = crate::queue::Task::new(
18287            "fixture".into(),
18288            "fixture".into(),
18289            repo,
18290            crate::queue::Source::Human,
18291        );
18292        task.link_run(&runner.state.id);
18293        crate::queue::Queue::open().put(&mut task).unwrap();
18294        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18295        runner.state.base_sync = Some(BaseSync {
18296            tip: String::new(),
18297            behind: 1,
18298            attempts: BASE_SYNC_ROUNDS,
18299            conflict: None,
18300            already_in: None,
18301        });
18302        runner.sync_to_base().await.unwrap();
18303        assert_eq!(runner.state.status, RunStatus::Blocked);
18304        (tmp, runner, head, task.id)
18305    }
18306
18307    #[tokio::test]
18308    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18309        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18310        runner.state.status = RunStatus::Voting;
18311        runner.state.base_sync = None;
18312        runner.state.base_sync_recovery = Default::default();
18313        let scratch = runner.state.dir().join("base-sync");
18314        std::fs::create_dir_all(&scratch).unwrap();
18315        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18316        runner.sync_to_base().await.unwrap();
18317        assert!(runner.state.resource_block.is_some());
18318        assert!(!runner.state.base_sync_blocked());
18319        assert!(runner.state.base_sync.is_none());
18320        assert_eq!(
18321            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18322            "keep"
18323        );
18324        assert_eq!(runner.state.base_episode_used(), 0);
18325        assert!(runner.state.base_sync_recovery.operations.is_empty());
18326        assert!(runner.state.rebase_fixes.is_empty());
18327        assert_eq!(
18328            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18329            head
18330        );
18331        std::fs::remove_dir_all(&scratch).unwrap();
18332        runner.state.resource_block = None;
18333        runner.sync_to_base().await.unwrap();
18334        assert!(!runner.state.base_sync_blocked());
18335        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18336        assert_eq!(runner.state.base_episode_used(), 1);
18337        assert!(runner.state.base_sync_recovery.operations[0].finished);
18338        assert!(runner.state.rebase_fixes.is_empty());
18339        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18340        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18341    }
18342
18343    #[tokio::test]
18344    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18345        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18346        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18347        runner.state.base_sync_recovery = Default::default();
18348        runner.state.task_instruction = Some("fixture".into());
18349        runner.state.config.agents = vec![spec("fixture")];
18350        runner.state.config.graph.review_rounds = 0;
18351        runner.state.config.merge.mode = MergeMode::None;
18352        runner.state.driver_exited = true;
18353        let sync = runner.state.base_sync.as_mut().unwrap();
18354        sync.conflict = None;
18355        sync.attempts = 0;
18356        runner.state.reserve_base_operation(&head, &tip);
18357        runner.state.finish_base_operation(None);
18358        let detail = format!(
18359            "fix/retained conflicts with origin/main and did not rebase: \
18360             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18361             remaining conflicted path(s): none recorded; git said: \
18362             warning: execution failed: {}",
18363            git::REBASE_EXEC
18364        );
18365        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18366        runner.state.record_base_sync_stop(&head);
18367        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18368            unstarted: false,
18369            agent: "fixture".into(),
18370            paths: Vec::new(),
18371            from: Some(head.clone()),
18372            finished: true,
18373            error: None,
18374            stop: None,
18375            onto: None,
18376            index_outside: None,
18377            launcher: None,
18378            infra: None,
18379            outage: None,
18380        });
18381        runner.state.save().unwrap();
18382        assert_eq!(
18383            crate::resume::validate(&crate::run::home(), &runner.state.id)
18384                .unwrap()
18385                .id,
18386            runner.state.id
18387        );
18388
18389        let dirty = runner.state.repo.join("owner-work");
18390        std::fs::write(&dirty, "keep").unwrap();
18391        runner.sync_to_base().await.unwrap();
18392        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18393        assert!(runner.state.base_sync_recovery.operations[0].finished);
18394        assert!(runner.state.base_sync_blocked());
18395        std::fs::remove_file(dirty).unwrap();
18396
18397        let queue = crate::queue::Queue::open();
18398        let id = runner.state.id.clone();
18399        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18400        let _claim = queue.claim(&owner).unwrap();
18401        let mut task = queue.get(&owner).unwrap();
18402        let config = tmp.path().join("test-config.toml");
18403        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18404        let opts = crate::daemon::Opts {
18405            repo: task.repo.clone(),
18406            config: Some(config),
18407            ..Default::default()
18408        };
18409        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18410        let task = queue.get(&owner).unwrap();
18411        assert_eq!(
18412            task.runs.as_slice(),
18413            std::slice::from_ref(&id),
18414            "{:?}",
18415            task.hold_reason
18416        );
18417        runner.state = RunState::load(&id).unwrap();
18418        assert!(!runner.state.base_sync_blocked());
18419        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18420        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18421        assert!(runner.state.base_sync_recovery.operations[0].finished);
18422        assert_eq!(
18423            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18424            detail
18425        );
18426        assert_eq!(runner.state.rebase_fixes.len(), 1);
18427        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18428    }
18429
18430    #[cfg(unix)]
18431    #[tokio::test]
18432    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18433        for routed in [false, true] {
18434            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18435            let home = crate::run::home();
18436            let queue = crate::queue::Queue::open();
18437            let task = queue.get(&owner).unwrap();
18438            runner.state.task_instruction = Some(task.instruction.clone());
18439            runner.state.driver_exited = true;
18440            runner.state.save().unwrap();
18441            let questions = crate::ask::Questions::at(home.join("questions"));
18442            let mut q = crate::ask::Question::new(
18443                runner.state.id.clone(),
18444                "base-recovery".into(),
18445                "owner".into(),
18446                "Recover bounded base movement?".into(),
18447                String::new(),
18448                vec!["recover".into()],
18449            );
18450            q.actions.insert(
18451                "recover".into(),
18452                crate::ask::ChoiceAction::RecoverBase {
18453                    run: runner.state.id.clone(),
18454                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
18455                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
18456                },
18457            );
18458            q.routed_task = Some(owner.clone());
18459            q.answer(crate::ask::Answer::Choice("recover".into()))
18460                .unwrap();
18461            questions.put(&mut q).unwrap();
18462            crate::base_recovery_control::recover(
18463                &queue,
18464                &home,
18465                crate::base_recovery_control::Request {
18466                    run: runner.state.id.clone(),
18467                    head: head.clone(),
18468                    actor: "decisions".into(),
18469                    request: q.id.clone(),
18470                    decision: Some((owner.clone(), q.answered_at.unwrap())),
18471                    expected_stop: Some((
18472                        runner.state.base_sync_recovery.stop.clone().unwrap(),
18473                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
18474                    )),
18475                    evidence_digest: None,
18476                },
18477            )
18478            .await
18479            .unwrap();
18480            if routed {
18481                questions
18482                    .update(&q.id, |q| {
18483                        q.routed_task = Some("another-owner".into());
18484                        Ok(())
18485                    })
18486                    .unwrap();
18487            } else {
18488                let mut task = queue.get(&owner).unwrap();
18489                task.hold_manual(Some("new owner decision".into()));
18490                // Keep the generation to exercise the separate owner-decision binding.
18491                task.status = crate::queue::TaskStatus::Queued;
18492                queue.put(&mut task).unwrap();
18493            }
18494            runner.state = RunState::load(&runner.state.id).unwrap();
18495            runner.sync_to_base().await.unwrap();
18496            let approval = runner
18497                .state
18498                .base_sync_recovery
18499                .authorizations
18500                .last()
18501                .unwrap();
18502            assert!(approval.consumed);
18503            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
18504                "routing"
18505            } else {
18506                "owner decision"
18507            }));
18508            assert_eq!(
18509                runner.state.base_sync.as_ref().unwrap().attempts,
18510                BASE_SYNC_ROUNDS
18511            );
18512            assert_eq!(
18513                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18514                head
18515            );
18516        }
18517    }
18518
18519    #[cfg(unix)]
18520    #[tokio::test]
18521    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
18522        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
18523        if std::env::var_os(CHILD).is_none() {
18524            let home = tempfile::tempdir().unwrap();
18525            let output = std::process::Command::new(std::env::current_exe().unwrap())
18526                .args([
18527                    "--exact",
18528                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
18529                    "--nocapture",
18530                ])
18531                .env(CHILD, "1")
18532                .env("MAGI_HOME", home.path())
18533                .env("MAGI_WORKER_HOME", home.path())
18534                .env("MAGI_WORKER_ID", "abcdef")
18535                .output()
18536                .unwrap();
18537            assert!(
18538                output.status.success()
18539                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18540                "{}\n{}",
18541                String::from_utf8_lossy(&output.stdout),
18542                String::from_utf8_lossy(&output.stderr)
18543            );
18544            return;
18545        }
18546        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
18547        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18548        let home = crate::run::home();
18549        let queue = crate::queue::Queue::open();
18550        let mut owner = queue.get(&task).unwrap();
18551        owner.release_operator("test-release", None);
18552        owner.start(runner.state.id.clone());
18553        queue.put(&mut owner).unwrap();
18554        runner.state.driver_exited = true;
18555        runner.state.task_instruction = Some(owner.instruction.clone());
18556        runner.state.save().unwrap();
18557        let _claim = queue.claim(&task).unwrap();
18558        let reserve = |id: &str| {
18559            let directory = home.join("workers/jobs").join(id);
18560            std::fs::create_dir_all(&directory).unwrap();
18561            let job = crate::worker::Job {
18562                id: id.into(),
18563                sequence: 1,
18564                kind: "task".into(),
18565                key: format!("task:{task}"),
18566                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
18567                generation: "fixture-generation".into(),
18568                version: None,
18569                status: crate::worker::Status::Running,
18570                result: None,
18571                pid: Some(std::process::id()),
18572                created_at: 0,
18573                finished_at: None,
18574            };
18575            std::fs::write(
18576                directory.join("job.json"),
18577                serde_json::to_vec(&job).unwrap(),
18578            )
18579            .unwrap();
18580            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
18581        };
18582        let _own = reserve("abcdef");
18583        let other = reserve("fedcba");
18584        assert!(
18585            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18586                .await
18587                .is_err()
18588        );
18589        assert!(
18590            RunState::load(&runner.state.id)
18591                .unwrap()
18592                .base_sync_recovery
18593                .authorizations
18594                .is_empty()
18595        );
18596        drop(other);
18597        assert!(crate::daemon::is_working_on(
18598            &home,
18599            &runner.state.id,
18600            Timestamp::now()
18601        ));
18602        assert!(
18603            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
18604        );
18605        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18606            .await
18607            .unwrap();
18608        assert!(
18609            RunState::load(&runner.state.id)
18610                .unwrap()
18611                .base_recovery_pending()
18612        );
18613    }
18614
18615    #[cfg(unix)]
18616    #[tokio::test]
18617    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
18618        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18619        let home = crate::run::home();
18620        runner.state.driver_pid = Some(std::process::id());
18621        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
18622        runner.state.driver_exited = false;
18623        runner.state.begin_pass();
18624        runner.state.save().unwrap();
18625        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
18626        driver.record(&runner.state).unwrap();
18627        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
18628        // Preserve the durable claim as if the process died before Drop saved.
18629        drop(driver);
18630        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
18631        assert_eq!(
18632            runner.state.liveness_under(&home, false),
18633            crate::run::Liveness::Dead
18634        );
18635        let queue = crate::queue::Queue::open();
18636        let _claim = queue.claim(&task).unwrap();
18637        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18638            .await
18639            .unwrap();
18640        let disk = RunState::load(&runner.state.id).unwrap();
18641        assert!(!disk.driver_exited);
18642        assert!(disk.base_recovery_pending());
18643    }
18644
18645    #[cfg(unix)]
18646    #[tokio::test]
18647    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
18648        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
18649        if std::env::var_os(CHILD).is_none() {
18650            use std::os::unix::fs::PermissionsExt;
18651            let tmp = tempfile::tempdir().unwrap();
18652            let gh = tmp.path().join("gh");
18653            std::fs::write(&gh, r#"#!/bin/sh
18654case "$1 $2" in
18655  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
18656  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
18657  *) exit 2 ;;
18658esac
18659"#).unwrap();
18660            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
18661            let mut paths = vec![tmp.path().to_path_buf()];
18662            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
18663            let output = std::process::Command::new(std::env::current_exe().unwrap())
18664                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
18665                .env(CHILD, "1")
18666                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
18667                .env("PATH", std::env::join_paths(paths).unwrap())
18668                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
18669                .output().unwrap();
18670            assert!(
18671                output.status.success()
18672                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18673                "{}\n{}",
18674                String::from_utf8_lossy(&output.stdout),
18675                String::from_utf8_lossy(&output.stderr)
18676            );
18677            return;
18678        }
18679        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18680        let repo = runner.state.repo.clone();
18681        git::git(&repo, &["checkout", "main"]).await.unwrap();
18682        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
18683        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18684        git::git(&repo, &["checkout", "fix/retained"])
18685            .await
18686            .unwrap();
18687        runner.state.pr = Some(crate::run::PrRecord {
18688            url: "https://example.test/project/pull/1".into(),
18689            number: 1,
18690            state: "open".into(),
18691            checks: "unknown".into(),
18692            round: 0,
18693            rounds: 1,
18694            red_at_merge: Vec::new(),
18695        });
18696        runner.sync_to_base().await.unwrap();
18697        assert_eq!(runner.state.status, RunStatus::Blocked);
18698        assert_eq!(
18699            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18700            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
18701        );
18702        assert!(runner.state.base_sync_closure_pending());
18703        assert!(crate::handover::can_resume(&runner.state));
18704        let queue = crate::queue::Queue::open();
18705        assert!(!crate::base_sync_recovery::held_task(
18706            &queue,
18707            &queue.get(&task).unwrap()
18708        ));
18709        assert!(runner.state.authorize_base_sync(&task).is_err());
18710        // Legacy closure stops have no typed stop but must retain the checkpoint.
18711        runner.state.base_sync_recovery.stop = None;
18712        runner.state.status = RunStatus::Voting;
18713        runner.state.gate_ran = true;
18714        runner.state.config.graph.review_rounds = 0;
18715        runner.state.save().unwrap();
18716        assert!(crate::handover::can_resume(&runner.state));
18717        runner.state = RunState::load(&runner.state.id).unwrap();
18718        runner.execute_graph().await.unwrap();
18719        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18720        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18721        assert_eq!(
18722            runner.state.base_sync.as_ref().unwrap().attempts,
18723            BASE_SYNC_ROUNDS
18724        );
18725        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18726        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18727        assert!(runner.state.reviews.is_empty());
18728        assert!(runner.state.gate.is_empty());
18729    }
18730
18731    #[cfg(unix)]
18732    #[tokio::test]
18733    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18734        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18735        runner.state.driver_exited = true;
18736        runner.state.save().unwrap();
18737        let home = crate::run::home();
18738        let queue = crate::queue::Queue::open();
18739        let _claim = queue.claim(&task).unwrap();
18740        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18741        assert!(
18742            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18743                .await
18744                .is_err()
18745        );
18746        drop(lease);
18747        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18748        assert!(
18749            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18750                .await
18751                .is_err()
18752        );
18753        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18754        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18755            .await
18756            .unwrap();
18757        let disk = RunState::load(&runner.state.id).unwrap();
18758        assert!(disk.base_recovery_pending());
18759        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18760        assert!(
18761            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18762                .await
18763                .is_err()
18764        );
18765        assert_eq!(
18766            RunState::load(&runner.state.id)
18767                .unwrap()
18768                .base_sync_recovery
18769                .authorizations
18770                .len(),
18771            1
18772        );
18773        let mut owner = queue.get(&task).unwrap();
18774        owner.runs.push("20260101-000000-ffff".into());
18775        queue.put(&mut owner).unwrap();
18776        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18777            .await
18778            .unwrap_err();
18779        assert!(error.to_string().contains("run task ownership changed"));
18780    }
18781
18782    #[cfg(unix)]
18783    #[tokio::test]
18784    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18785        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18786        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18787        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18788        legacy["status"] = serde_json::json!("voting");
18789        runner.state = serde_json::from_value(legacy).unwrap();
18790        runner.state.save().unwrap();
18791        for _ in 0..3 {
18792            runner.execute_graph().await.unwrap();
18793            assert_eq!(runner.state.status, RunStatus::Blocked);
18794            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18795            assert!(!crate::handover::can_resume(&runner.state));
18796            assert_eq!(
18797                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18798                head
18799            );
18800            assert!(runner.state.reviews.is_empty());
18801            assert!(!runner.state.gate_ran);
18802        }
18803        let notice = crate::notices::run_ended(&runner.state).unwrap();
18804        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18805        runner.state.begin_pass();
18806        runner.state.status = RunStatus::Voting;
18807        runner.deliberate().await.unwrap();
18808        runner.vote().await.unwrap();
18809        runner.finish_after_tally().await.unwrap();
18810        assert_eq!(runner.state.status, RunStatus::Blocked);
18811        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18812        assert_eq!(
18813            crate::notices::run_ended(&runner.state).unwrap().since,
18814            notice.since
18815        );
18816    }
18817
18818    #[cfg(unix)]
18819    #[tokio::test]
18820    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18821        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18822        for detail in [
18823            "fix/retained conflicts with origin/main and did not rebase: conflict",
18824            "rebased fix/retained locally but origin refused the push",
18825            "unknown failure",
18826        ] {
18827            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18828            runner.state.record_base_sync_stop(&head);
18829            assert!(runner.state.authorize_base_sync(&task).is_err());
18830            runner.state.status = RunStatus::Voting;
18831            runner.execute_graph().await.unwrap();
18832            assert_eq!(runner.state.status, RunStatus::Blocked);
18833            assert!(!crate::handover::can_resume(&runner.state));
18834            assert_eq!(
18835                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18836                head
18837            );
18838        }
18839    }
18840
18841    #[tokio::test]
18842    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
18843        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18844        let state = &mut runner.state;
18845        let tip = state.base_sync.as_ref().unwrap().tip.clone();
18846        let branch = state.winner().unwrap().branch.clone();
18847        state.base_sync_recovery = Default::default();
18848        state.base_sync.as_mut().unwrap().attempts = 0;
18849        state.reserve_base_operation(&head, &tip);
18850        state.finish_base_operation(None);
18851        let detail = format!(
18852            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
18853        );
18854        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18855        state.event("land", detail);
18856        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
18857        assert!(state.unknown_preparation_stop(&head));
18858        let digest = state.preparation_digest(&head).unwrap();
18859        state
18860            .base_sync_recovery
18861            .operations
18862            .last_mut()
18863            .unwrap()
18864            .validated_head = Some(head.clone());
18865        assert!(!state.unknown_preparation_stop(&head));
18866        state
18867            .base_sync_recovery
18868            .operations
18869            .last_mut()
18870            .unwrap()
18871            .validated_head = None;
18872        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
18873        state.driver_exited = true;
18874        state.save().unwrap();
18875        let home = crate::run::home();
18876        let queue = crate::queue::Queue::open();
18877        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
18878            .await
18879            .unwrap();
18880        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
18881        assert_eq!(inspection["evidence_digest"], digest);
18882        let request = crate::base_recovery_control::Request {
18883            run: state.id.clone(),
18884            head: head.clone(),
18885            actor: "test".into(),
18886            request: "preparation".into(),
18887            decision: None,
18888            expected_stop: None,
18889            evidence_digest: Some(digest),
18890        };
18891        let mut stale = request.clone();
18892        stale.evidence_digest = Some("stale".into());
18893        assert!(
18894            crate::base_recovery_control::recover(&queue, &home, stale)
18895                .await
18896                .is_err()
18897        );
18898        let scratch = state.dir().join("base-sync");
18899        std::fs::create_dir(&scratch).unwrap();
18900        assert!(
18901            crate::base_recovery_control::recover(&queue, &home, request.clone())
18902                .await
18903                .is_err()
18904        );
18905        std::fs::remove_dir(&scratch).unwrap();
18906        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
18907        git::git(
18908            &state.repo,
18909            &[
18910                "commit",
18911                "--allow-empty",
18912                "-m",
18913                "base advanced after inspection",
18914            ],
18915        )
18916        .await
18917        .unwrap();
18918        git::git(&state.repo, &["push", "origin", "main"])
18919            .await
18920            .unwrap();
18921        git::git(&state.repo, &["checkout", "fix/retained"])
18922            .await
18923            .unwrap();
18924        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
18925            .await
18926            .unwrap();
18927        assert!(!outcome.repeated);
18928        assert!(
18929            crate::base_recovery_control::recover(&queue, &home, request)
18930                .await
18931                .unwrap()
18932                .repeated
18933        );
18934        runner.state = RunState::load(&runner.state.id).unwrap();
18935        assert!(runner.state.base_recovery_pending());
18936        runner.sync_to_base().await.unwrap();
18937        assert!(!runner.state.base_sync_blocked());
18938        assert!(!runner.state.consume_base_recovery(&head));
18939        assert_eq!(runner.state.base_episode_used(), 2);
18940        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18941        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18942        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
18943    }
18944
18945    #[cfg(unix)]
18946    #[tokio::test]
18947    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18948        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18949        runner.state.authorize_base_sync(&task).unwrap();
18950        assert!(runner.state.consume_base_recovery(&head));
18951        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18952        runner.state.reserve_base_operation(&head, &tip);
18953        runner.state.save().unwrap();
18954        runner.state = RunState::load(&runner.state.id).unwrap();
18955        assert!(!runner.state.consume_base_recovery(&head));
18956        runner.sync_to_base().await.unwrap();
18957        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18958        assert_eq!(runner.state.base_episode_used(), 1);
18959        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18960        assert!(
18961            runner
18962                .state
18963                .base_sync_recovery
18964                .operations
18965                .last()
18966                .unwrap()
18967                .finished
18968        );
18969        assert!(!runner.state.base_sync_blocked());
18970        runner.sync_to_base().await.unwrap();
18971        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18972    }
18973
18974    #[cfg(unix)]
18975    #[tokio::test]
18976    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18977        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18978        // Both historical diagnostic spellings retain an exhaustion identity.
18979        let original = runner
18980            .state
18981            .base_sync
18982            .as_ref()
18983            .unwrap()
18984            .conflict
18985            .clone()
18986            .unwrap();
18987        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18988            original
18989                .replace("synchronization(s)", "rebase(s)")
18990                .replace("synchronizing", "rebasing"),
18991        );
18992        runner.state.base_sync_recovery = Default::default();
18993        runner.state.record_base_sync_stop(&head);
18994        assert_eq!(
18995            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18996            crate::base_sync_recovery::StopKind::Exhausted
18997        );
18998        runner.state.authorize_base_sync(&task).unwrap();
18999        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19000        let auth = legacy["base_sync_recovery"]["authorizations"][0]
19001            .as_object_mut()
19002            .unwrap();
19003        auth.remove("interval");
19004        auth.remove("scope");
19005        runner.state = serde_json::from_value(legacy).unwrap();
19006        assert!(runner.state.consume_base_recovery(&head));
19007        assert_eq!(runner.state.base_episode_used(), 3);
19008        runner.sync_to_base().await.unwrap();
19009        assert_eq!(runner.state.base_episode_used(), 4);
19010        runner.state.resource_block = Some(crate::run::ResourceBlock {
19011            node: "gate".into(),
19012            kind: "cache".into(),
19013            detail: "legacy wait".into(),
19014            at: Timestamp::now(),
19015            cause: crate::run::ResourceBlockCause::Unrecorded,
19016        });
19017        runner.state.save().unwrap();
19018        assert!(
19019            runner
19020                .state
19021                .base_sync_recovery
19022                .episodes
19023                .last()
19024                .unwrap()
19025                .boundary
19026                .is_none()
19027        );
19028        runner.state.resource_block = None;
19029        advance_base_fixture(&runner).await;
19030        runner.sync_to_base().await.unwrap();
19031        assert!(runner.state.base_sync_blocked());
19032        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19033    }
19034
19035    #[cfg(unix)]
19036    async fn advance_base_fixture(runner: &Runner) {
19037        let repo = &runner.state.repo;
19038        for args in [
19039            vec!["checkout", "main"],
19040            vec!["commit", "--allow-empty", "-m", "base advanced"],
19041            vec!["push", "origin", "main"],
19042            vec!["checkout", "fix/retained"],
19043        ] {
19044            git::git(repo, &args).await.unwrap();
19045        }
19046    }
19047
19048    #[cfg(unix)]
19049    fn fresh_base_interval_fixture(runner: &mut Runner) {
19050        runner.state.base_sync.as_mut().unwrap().attempts = 0;
19051        runner.state.base_sync.as_mut().unwrap().conflict = None;
19052        runner.state.base_sync_recovery = Default::default();
19053        runner.state.status = RunStatus::Voting;
19054    }
19055
19056    #[cfg(unix)]
19057    #[tokio::test]
19058    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
19059        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19060        fresh_base_interval_fixture(&mut runner);
19061        runner.state.begin_pass();
19062        runner.sync_to_base().await.unwrap();
19063        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19064        runner.state.resource_block = Some(crate::run::ResourceBlock {
19065            node: "gate".into(),
19066            kind: "build cache".into(),
19067            detail: "busy".into(),
19068            at: Timestamp::now(),
19069            cause: crate::run::ResourceBlockCause::Timeout {
19070                waited_secs: 1,
19071                limit_secs: 1,
19072            },
19073        });
19074        runner.state.save().unwrap();
19075        let queue = crate::queue::Queue::open();
19076        let mut owner = queue.get(&task).unwrap();
19077        runner.state.task_instruction = Some(owner.instruction.clone());
19078        owner.release_operator("fixture-owner", None);
19079        queue.put(&mut owner).unwrap();
19080        let approval = owner.resumption.clone().unwrap();
19081        runner.state.resource_block = None;
19082        runner.state.save().unwrap();
19083        runner.state = RunState::load(&runner.state.id).unwrap();
19084        advance_base_fixture(&runner).await;
19085        runner.sync_to_base().await.unwrap();
19086        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19087        assert_eq!(runner.state.base_episode_used(), 1);
19088        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19089        assert!(
19090            runner.state.base_sync_recovery.episodes[0]
19091                .boundary
19092                .as_ref()
19093                .unwrap()
19094                .consumed
19095        );
19096        assert!(
19097            !runner
19098                .state
19099                .renew_base_episode(&task, &approval, &head, "base")
19100        );
19101        for _ in 0..3 {
19102            owner.release_operator("fixture-owner", None);
19103            queue.put(&mut owner).unwrap();
19104            runner.state = RunState::load(&runner.state.id).unwrap();
19105            runner.state.begin_pass();
19106            runner.sync_to_base().await.unwrap();
19107            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19108            assert_eq!(runner.state.base_episode_used(), 1);
19109        }
19110        runner.state.resource_block = Some(crate::run::ResourceBlock {
19111            node: "gate".into(),
19112            kind: "disk pressure".into(),
19113            detail: "free space required".into(),
19114            at: Timestamp::now(),
19115            cause: crate::run::ResourceBlockCause::Other,
19116        });
19117        runner.state.end_pass_parked(ParkCause::Interrupt {
19118            reason: "disk pressure".into(),
19119        });
19120        runner.state.save().unwrap();
19121        owner.release_operator("fixture-owner-after-disk", None);
19122        queue.put(&mut owner).unwrap();
19123        runner.state.resource_block = None;
19124        advance_base_fixture(&runner).await;
19125        runner.sync_to_base().await.unwrap();
19126        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19127        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19128        assert_eq!(runner.state.base_episode_used(), 1);
19129        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19130    }
19131
19132    #[cfg(unix)]
19133    #[tokio::test]
19134    async fn base_recovery_continuous_advancement_stops_at_four() {
19135        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19136        fresh_base_interval_fixture(&mut runner);
19137        for spent in 1..=BASE_SYNC_ROUNDS {
19138            runner.sync_to_base().await.unwrap();
19139            assert!(!runner.state.base_sync_blocked());
19140            assert_eq!(runner.state.base_episode_used(), spent);
19141            advance_base_fixture(&runner).await;
19142        }
19143        runner.sync_to_base().await.unwrap();
19144        assert_eq!(
19145            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19146            crate::base_sync_recovery::StopKind::Exhausted
19147        );
19148        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19149        assert!(stop.unverified_sync);
19150        let action = runner.state.base_sync_next_action();
19151        assert!(action.contains("never reached its gate"));
19152        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19153        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19154        runner.state = RunState::load(&runner.state.id).unwrap();
19155        runner.sync_to_base().await.unwrap();
19156        assert_eq!(runner.state.base_episode_used(), 4);
19157        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19158    }
19159
19160    #[cfg(unix)]
19161    #[tokio::test]
19162    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19163        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19164        runner.state.ensure_base_episode();
19165        // Verification progress alone is not evidence of a successful sync.
19166        runner.state.record_base_progress(&head);
19167        runner.state.base_sync_recovery.stop = None;
19168        runner.state.record_base_sync_stop(&head);
19169        assert!(
19170            !runner
19171                .state
19172                .base_sync_recovery
19173                .stop
19174                .as_ref()
19175                .unwrap()
19176                .unverified_sync
19177        );
19178
19179        runner.state.finish_base_operation(Some(&head));
19180        // A gate for another head cannot verify this synchronization.
19181        runner.state.gate_ran = true;
19182        runner.state.gate_head = Some("older-head".into());
19183        runner.state.base_sync_recovery.stop = None;
19184        runner.state.record_base_sync_stop(&head);
19185        runner.state.save().unwrap();
19186        runner.state = RunState::load(&runner.state.id).unwrap();
19187        assert!(
19188            runner
19189                .state
19190                .base_sync_recovery
19191                .stop
19192                .as_ref()
19193                .unwrap()
19194                .unverified_sync
19195        );
19196
19197        runner.state.gate_head = Some(head.clone());
19198        runner.state.base_sync_recovery.stop = None;
19199        runner.state.record_base_sync_stop(&head);
19200        assert!(
19201            !runner
19202                .state
19203                .base_sync_recovery
19204                .stop
19205                .as_ref()
19206                .unwrap()
19207                .unverified_sync
19208        );
19209        assert!(
19210            !runner
19211                .state
19212                .base_sync_next_action()
19213                .contains("never reached its gate")
19214        );
19215
19216        // Historical records cannot establish the missing synchronization evidence.
19217        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19218        legacy["base_sync_recovery"]["stop"]
19219            .as_object_mut()
19220            .unwrap()
19221            .remove("unverified_sync");
19222        legacy["base_sync_recovery"]["episodes"][0]
19223            .as_object_mut()
19224            .unwrap()
19225            .remove("last_sync_head");
19226        runner.state = serde_json::from_value(legacy).unwrap();
19227        assert!(
19228            !runner
19229                .state
19230                .base_sync_recovery
19231                .stop
19232                .as_ref()
19233                .unwrap()
19234                .unverified_sync
19235        );
19236        assert!(
19237            runner.state.base_sync_recovery.episodes[0]
19238                .last_sync_head
19239                .is_none()
19240        );
19241    }
19242
19243    #[cfg(unix)]
19244    #[tokio::test]
19245    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19246        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19247        runner.state.authorize_base_sync(&task).unwrap();
19248        assert!(
19249            runner
19250                .state
19251                .base_sync_next_action()
19252                .contains("Approval recorded")
19253        );
19254        assert!(
19255            runner
19256                .state
19257                .base_sync_next_action()
19258                .contains("4/4 in episode 0, 4 lifetime")
19259        );
19260        assert!(runner.state.consume_base_recovery(&head));
19261        assert!(
19262            runner
19263                .state
19264                .base_sync_next_action()
19265                .contains("0/4 in episode 1, 4 lifetime")
19266        );
19267    }
19268
19269    #[cfg(unix)]
19270    #[tokio::test]
19271    async fn base_recovery_changed_head_invalidates_without_spending() {
19272        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19273        runner.state.authorize_base_sync(&task).unwrap();
19274        git::git(
19275            &runner.state.repo,
19276            &["commit", "--allow-empty", "-m", "external head change"],
19277        )
19278        .await
19279        .unwrap();
19280        runner.sync_to_base().await.unwrap();
19281        let a = runner
19282            .state
19283            .base_sync_recovery
19284            .authorizations
19285            .last()
19286            .unwrap();
19287        assert!(a.consumed);
19288        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19289        runner.state = RunState::load(&runner.state.id).unwrap();
19290        assert!(
19291            runner
19292                .state
19293                .base_sync_next_action()
19294                .contains("Approval invalidated")
19295        );
19296        assert!(!runner.state.base_recovery_pending());
19297        assert!(runner.state.base_sync_blocked());
19298        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19299    }
19300
19301    #[cfg(unix)]
19302    #[tokio::test]
19303    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19304        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19305        runner.state.driver_exited = true;
19306        runner.state.save().unwrap();
19307        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19308            .await
19309            .unwrap();
19310        runner.state = RunState::load(&runner.state.id).unwrap();
19311        advance_base_fixture(&runner).await;
19312        runner.sync_to_base().await.unwrap();
19313        let a = runner
19314            .state
19315            .base_sync_recovery
19316            .authorizations
19317            .last()
19318            .unwrap();
19319        assert!(
19320            a.consumed
19321                && a.invalidated
19322                    .as_deref()
19323                    .unwrap()
19324                    .contains("fetched base changed")
19325        );
19326        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19327        assert_eq!(
19328            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19329            head
19330        );
19331        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19332            .await
19333            .unwrap();
19334        runner.state = RunState::load(&runner.state.id).unwrap();
19335        runner.sync_to_base().await.unwrap();
19336        assert!(!runner.state.base_sync_blocked());
19337        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19338    }
19339
19340    #[cfg(unix)]
19341    #[tokio::test]
19342    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19343        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19344        runner.state.authorize_base_sync(&task).unwrap();
19345        assert!(runner.state.consume_base_recovery(&head));
19346        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19347        runner.state.reserve_base_operation(&head, &tip);
19348        runner.state.save().unwrap();
19349        let scratch = runner.state.dir().join("base-sync");
19350        assert_eq!(
19351            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19352                .await
19353                .unwrap(),
19354            crate::rebase::Rebased::Applied
19355        );
19356        runner.state = RunState::load(&runner.state.id).unwrap();
19357        runner.sync_to_base().await.unwrap();
19358        assert!(
19359            runner
19360                .state
19361                .base_sync_recovery
19362                .operations
19363                .last()
19364                .unwrap()
19365                .finished
19366        );
19367        assert_eq!(runner.state.base_episode_used(), 1);
19368        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19369        assert!(!runner.state.base_sync_blocked());
19370    }
19371
19372    #[cfg(unix)]
19373    #[tokio::test]
19374    async fn base_recovery_crash_preserves_untracked_files() {
19375        for ignored in [false, true] {
19376            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19377            runner.state.authorize_base_sync(&task).unwrap();
19378            assert!(runner.state.consume_base_recovery(&head));
19379            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19380            runner.state.reserve_base_operation(&head, &tip);
19381            runner.state.save().unwrap();
19382            let scratch = runner.state.dir().join("base-sync");
19383            assert_eq!(
19384                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19385                    .await
19386                    .unwrap(),
19387                crate::rebase::Rebased::Applied
19388            );
19389            let repo = &runner.state.repo;
19390            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19391            assert_ne!(result, head);
19392            if ignored {
19393                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19394                    .await
19395                    .unwrap();
19396                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19397            }
19398            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19399            assert!(
19400                git::git_raw(repo, &["diff", "--quiet", &head])
19401                    .await
19402                    .unwrap()
19403                    .ok()
19404            );
19405            // Resume after the branch moved, before its checkout was reset.
19406            runner.state = RunState::load(&runner.state.id).unwrap();
19407            runner.sync_to_base().await.unwrap();
19408            assert!(runner.state.base_sync_blocked());
19409            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19410            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19411            assert_eq!(
19412                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19413                result
19414            );
19415            assert_eq!(
19416                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19417                "retained work\n"
19418            );
19419            assert!(
19420                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19421                    .await
19422                    .unwrap()
19423                    .ok()
19424            );
19425        }
19426    }
19427
19428    #[cfg(unix)]
19429    #[tokio::test]
19430    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19431        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19432        runner.state.authorize_base_sync(&task).unwrap();
19433        assert!(runner.state.consume_base_recovery(&head));
19434        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19435        runner.state.reserve_base_operation(&head, &tip);
19436        runner.state.save().unwrap();
19437        let scratch = runner.state.dir().join("base-sync");
19438        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19439            .await
19440            .unwrap();
19441        git::sync_to_head(&runner.state.repo).await.unwrap();
19442        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19443        git::git(&runner.state.repo, &["add", "foreign"])
19444            .await
19445            .unwrap();
19446        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
19447            .await
19448            .unwrap();
19449        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19450        runner.state = RunState::load(&runner.state.id).unwrap();
19451        runner.sync_to_base().await.unwrap();
19452        assert!(runner.state.base_sync_blocked());
19453        assert!(
19454            !runner
19455                .state
19456                .base_sync_recovery
19457                .operations
19458                .last()
19459                .unwrap()
19460                .finished
19461        );
19462        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19463        assert_eq!(
19464            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19465            foreign_head
19466        );
19467    }
19468
19469    #[cfg(unix)]
19470    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
19471    {
19472        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19473        fresh_base_interval_fixture(&mut runner);
19474        let repo = &runner.state.repo;
19475        git::git(repo, &["checkout", "main"]).await.unwrap();
19476        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
19477        git::git(repo, &["add", "retained"]).await.unwrap();
19478        git::git(repo, &["commit", "-m", "upstream retained change"])
19479            .await
19480            .unwrap();
19481        git::git(repo, &["push", "origin", "main"]).await.unwrap();
19482        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
19483        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
19484        let scratch = runner.state.dir().join("base-sync");
19485        assert!(matches!(
19486            git::rebase_start(repo, &scratch, "fix/retained", &tip)
19487                .await
19488                .unwrap(),
19489            git::RebaseStart::Conflicted(_)
19490        ));
19491        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
19492            unstarted: false,
19493            agent: "fixture".into(),
19494            paths: vec!["retained".into()],
19495            from: Some(head.clone()),
19496            onto: None,
19497            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
19498            index_outside: None,
19499            finished: false,
19500            error: None,
19501            launcher: None,
19502            infra: None,
19503            outage: None,
19504        });
19505        (tmp, runner, head, tip, scratch)
19506    }
19507
19508    #[cfg(unix)]
19509    #[tokio::test]
19510    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
19511        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19512        // A resource stop from before reservations existed, with resolved
19513        // contents left for the launcher's ordinary staging continuation.
19514        std::fs::write(
19515            scratch.join("retained"),
19516            "upstream and retained resolution\n",
19517        )
19518        .unwrap();
19519        runner.state.resource_block = Some(crate::run::ResourceBlock {
19520            node: "rebase".into(),
19521            kind: "repository coordination".into(),
19522            detail: "busy".into(),
19523            at: Timestamp::now(),
19524            cause: crate::run::ResourceBlockCause::Other,
19525        });
19526        runner.state.save().unwrap();
19527        // Advance the remote without moving either checkout participating
19528        // in the standing rebase.
19529        let newer = git::git(
19530            &runner.state.repo,
19531            &[
19532                "commit-tree",
19533                "main^{tree}",
19534                "-p",
19535                "main",
19536                "-m",
19537                "base advanced during wait",
19538            ],
19539        )
19540        .await
19541        .unwrap();
19542        git::git(
19543            &runner.state.repo,
19544            &[
19545                "push",
19546                "origin",
19547                &format!("{}:refs/heads/main", newer.trim()),
19548            ],
19549        )
19550        .await
19551        .unwrap();
19552        runner.state = RunState::load(&runner.state.id).unwrap();
19553        runner.state.resource_block = None;
19554        runner.sync_to_base().await.unwrap();
19555        assert!(!runner.state.base_sync_blocked());
19556        let op = &runner.state.base_sync_recovery.operations[0];
19557        assert_eq!(op.head, head);
19558        assert_eq!(op.tip, tip);
19559        assert!(op.finished);
19560        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19561        assert_eq!(runner.state.rebase_fixes.len(), 1);
19562        let latest = git::rev_parse(&runner.state.repo, "origin/main")
19563            .await
19564            .unwrap();
19565        assert_ne!(latest, tip);
19566        runner.state = RunState::load(&runner.state.id).unwrap();
19567        runner.sync_to_base().await.unwrap();
19568        assert!(!runner.state.base_sync_blocked());
19569        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
19570        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
19571        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19572    }
19573
19574    #[cfg(unix)]
19575    #[tokio::test]
19576    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
19577        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19578        runner.state.reserve_base_operation(&head, &tip);
19579        runner.state.save().unwrap();
19580        std::fs::write(
19581            scratch.join("retained"),
19582            "upstream and retained resolution\n",
19583        )
19584        .unwrap();
19585        git::git(&scratch, &["add", "retained"]).await.unwrap();
19586        git::git(
19587            &scratch,
19588            &["-c", "core.editor=true", "rebase", "--continue"],
19589        )
19590        .await
19591        .unwrap();
19592        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19593        assert!(
19594            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19595                .await
19596                .unwrap()
19597                .is_empty()
19598        );
19599        assert_eq!(
19600            crate::rebase::finish(
19601                &mut runner.state,
19602                &scratch,
19603                "fix/retained",
19604                &head,
19605                &tip,
19606                &["retained".into()],
19607                ""
19608            )
19609            .await
19610            .unwrap(),
19611            crate::rebase::Rebased::Applied
19612        );
19613        assert!(!scratch.exists());
19614        // Simulate losing the caller before finish_base_operation/save.
19615        runner.state = RunState::load(&runner.state.id).unwrap();
19616        let op = &runner.state.base_sync_recovery.operations[0];
19617        assert!(!op.finished);
19618        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
19619        runner.sync_to_base().await.unwrap();
19620        assert!(!runner.state.base_sync_blocked());
19621        assert!(runner.state.base_sync_recovery.operations[0].finished);
19622        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19623        assert_eq!(runner.state.rebase_fixes.len(), 1);
19624        let winner = runner.state.winner().unwrap().clone();
19625        let wait = runner.repository_wait();
19626        assert!(
19627            verify_current_head(&mut runner.state, &winner, &wait)
19628                .await
19629                .unwrap()
19630        );
19631        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19632    }
19633
19634    #[cfg(unix)]
19635    #[tokio::test]
19636    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
19637        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
19638            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19639            runner.state.reserve_base_operation(&head, &tip);
19640            runner.state.save().unwrap();
19641            std::fs::write(
19642                scratch.join("retained"),
19643                "upstream and retained resolution\n",
19644            )
19645            .unwrap();
19646            git::git(&scratch, &["add", "retained"]).await.unwrap();
19647            git::git(
19648                &scratch,
19649                &["-c", "core.editor=true", "rebase", "--continue"],
19650            )
19651            .await
19652            .unwrap();
19653            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19654            assert!(!git::rebase_in_progress(&scratch).await);
19655            assert!(
19656                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19657                    .await
19658                    .unwrap()
19659                    .is_empty()
19660            );
19661            match damage {
19662                Some("record") => {
19663                    let path =
19664                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
19665                            .await
19666                            .unwrap();
19667                    std::fs::write(scratch.join(path), "").unwrap();
19668                }
19669                Some("foreign") => {
19670                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
19671                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
19672                    git::git(&scratch, &["commit", "-m", "foreign work"])
19673                        .await
19674                        .unwrap();
19675                }
19676                Some("dirty") => {
19677                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
19678                }
19679                _ => {}
19680            }
19681            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19682            // Crash immediately after Git continuation, before finish runs.
19683            runner.state = RunState::load(&runner.state.id).unwrap();
19684            assert!(
19685                runner.state.base_sync_recovery.operations[0]
19686                    .validated_head
19687                    .is_none()
19688            );
19689            runner.sync_to_base().await.unwrap();
19690            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19691            assert_eq!(runner.state.base_episode_used(), 1);
19692            assert_eq!(runner.state.rebase_fixes.len(), 1);
19693            assert_eq!(
19694                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19695                retained_head
19696            );
19697            if damage.is_some() {
19698                assert!(runner.state.base_sync_blocked());
19699                assert!(scratch.exists());
19700                assert!(!runner.state.base_sync_recovery.operations[0].finished);
19701                assert!(
19702                    runner.state.base_sync_recovery.operations[0]
19703                        .validated_head
19704                        .is_none()
19705                );
19706            } else {
19707                assert!(!runner.state.base_sync_blocked());
19708                assert!(!scratch.exists());
19709                assert!(runner.state.base_sync_recovery.operations[0].finished);
19710                assert_eq!(
19711                    runner.state.base_sync_recovery.operations[0]
19712                        .validated_head
19713                        .as_deref(),
19714                    Some(result.as_str())
19715                );
19716                let winner = runner.state.winner().unwrap().clone();
19717                let wait = runner.repository_wait();
19718                assert!(
19719                    verify_current_head(&mut runner.state, &winner, &wait)
19720                        .await
19721                        .unwrap()
19722                );
19723                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19724                runner.state = RunState::load(&runner.state.id).unwrap();
19725                runner.sync_to_base().await.unwrap();
19726                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19727            }
19728        }
19729    }
19730
19731    #[cfg(unix)]
19732    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
19733        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19734        // This is an ordinary gate stop, not an authorized base-budget recovery.
19735        runner.state.prep_complete = Some(true);
19736        runner.state.base_sync = None;
19737        runner.state.base_sync_recovery = Default::default();
19738        runner.state.config.graph.gate_fix_rounds = 1;
19739        let mut review = review_round(true, 0, 1, 1, false, true);
19740        review.head = head.clone();
19741        review.verified_head = Some(head.clone());
19742        runner.state.reviews = vec![review];
19743        runner.state.gate = vec![CommandOutcome {
19744            command: "old gate".into(),
19745            code: Some(1),
19746            output_tail: "old failure".into(),
19747            duration_ms: 0,
19748            resource_blocked: false,
19749            ..Default::default()
19750        }];
19751        runner.state.gate_head = Some(head.clone());
19752        runner.state.gate_ran = true;
19753        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
19754            agent: "fixture".into(),
19755            failed: runner.state.gate.clone(),
19756            notes: "spent".into(),
19757            committed: false,
19758            error: None,
19759        }];
19760        runner.state.land_approval = Some(crate::run::LandApproval {
19761            question: "old approval".into(),
19762            head: head.clone(),
19763        });
19764        runner.state.status = RunStatus::Blocked;
19765        (tmp, runner, head)
19766    }
19767
19768    #[cfg(unix)]
19769    #[tokio::test]
19770    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
19771        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
19772        runner.sync_to_base().await.unwrap();
19773        let winner = runner.state.winner().unwrap().clone();
19774        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
19775        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
19776        assert_ne!(head, base);
19777        runner.state.config.verify.e2e = vec![format!(
19778            "git update-ref refs/remotes/origin/main {head} && false"
19779        )];
19780        let wait = repository_wait(&runner.state, None);
19781        assert!(
19782            !verify_current_head(&mut runner.state, &winner, &wait)
19783                .await
19784                .unwrap()
19785        );
19786        assert_eq!(
19787            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
19788                .await
19789                .unwrap(),
19790            head
19791        );
19792        assert_eq!(
19793            runner
19794                .state
19795                .head_e2e
19796                .as_ref()
19797                .unwrap()
19798                .base_commit
19799                .as_deref(),
19800            Some(base.as_str())
19801        );
19802    }
19803
19804    #[cfg(unix)]
19805    #[tokio::test]
19806    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
19807        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
19808            let (tmp, mut runner, old) = resumed_gate_fixture().await;
19809            let phases = tmp.path().join("phases");
19810            runner.state.config.verify.e2e = vec![format!(
19811                "echo e2e >> '{}'; {}",
19812                phases.display(),
19813                if e2e_ok {
19814                    "true"
19815                } else {
19816                    "echo new-e2e-failure; false"
19817                }
19818            )];
19819            runner.state.config.verify.gate = vec![format!(
19820                "echo gate >> '{}'; {}",
19821                phases.display(),
19822                if gate_ok {
19823                    "true"
19824                } else {
19825                    "echo new-gate-failure; false"
19826                }
19827            )];
19828            runner.state.save().unwrap();
19829            runner.state = RunState::load(&runner.state.id).unwrap();
19830            runner.sync_to_base().await.unwrap();
19831            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19832            assert_ne!(head, old);
19833            // Reentry after Git updated but before verification was invalidated.
19834            runner.state = RunState::load(&runner.state.id).unwrap();
19835            runner.execute_graph().await.unwrap();
19836            assert_eq!(runner.state.gate_fixes.len(), 1);
19837            assert_eq!(runner.state.reviews.len(), 1);
19838            assert_eq!(runner.state.reviews[0].head, old);
19839            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
19840            assert_eq!(runner.state.verification_history.len(), 1);
19841            let history = &runner.state.verification_history[0];
19842            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
19843            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19844            assert!(history.archived_at.is_some());
19845            assert_eq!(history.fixes_spent, Some(1));
19846            assert_eq!(history.gate[0].output_tail, "old failure");
19847            let archive_events: Vec<_> = runner
19848                .state
19849                .events
19850                .iter()
19851                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
19852                .collect();
19853            assert_eq!(archive_events.len(), 1);
19854            assert!(archive_events[0].message.contains(&short(&old)));
19855            assert!(archive_events[0].message.contains(&short(&head)));
19856            assert!(
19857                archive_events[0]
19858                    .message
19859                    .contains("1 gate-fix round(s) already spent stay spent")
19860            );
19861            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19862            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19863            if e2e_ok {
19864                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19865                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19866            } else {
19867                assert!(!runner.state.gate_ran);
19868            }
19869            assert_eq!(
19870                runner.state.status,
19871                if e2e_ok && gate_ok {
19872                    RunStatus::Ready
19873                } else {
19874                    RunStatus::Blocked
19875                }
19876            );
19877            if !e2e_ok || !gate_ok {
19878                let cause = runner.state.verification_blocking_cause().unwrap();
19879                assert!(cause.contains(&head));
19880                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19881                // A later successful progress event must not become the cause.
19882                runner.state.event("land", "rebased successfully");
19883                let notice = crate::notices::run_ended(&runner.state).unwrap();
19884                assert!(!format!("{notice:?}").contains("rebased successfully"));
19885                assert!(runner.state.merge.is_none());
19886            }
19887            let before = std::fs::read_to_string(&phases).unwrap();
19888            runner.state.save().unwrap();
19889            runner.state = RunState::load(&runner.state.id).unwrap();
19890            runner.review_loop().await.unwrap();
19891            runner.gate().await.unwrap();
19892            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19893            assert_eq!(runner.state.verification_history.len(), 1);
19894            let history = &runner.state.verification_history[0];
19895            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19896            assert!(history.archived_at.is_some());
19897            assert_eq!(history.fixes_spent, Some(1));
19898        }
19899    }
19900
19901    #[cfg(unix)]
19902    #[tokio::test]
19903    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19904        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19905        let marker = tmp.path().join("gate-ran");
19906        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19907        runner.review_loop().await.unwrap();
19908        runner.gate().await.unwrap();
19909        assert_eq!(runner.state.status, RunStatus::Blocked);
19910        assert!(!marker.exists());
19911        assert!(runner.state.verification_history.is_empty());
19912        runner.state.gate_head = None;
19913        runner.gate().await.unwrap();
19914        assert!(marker.exists());
19915        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19916        assert_eq!(runner.state.verification_history.len(), 1);
19917        assert_eq!(runner.state.gate_fixes.len(), 1);
19918    }
19919
19920    #[cfg(unix)]
19921    #[tokio::test]
19922    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19923        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19924        runner.sync_to_base().await.unwrap();
19925        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19926        runner.state.reconcile_verification_head(&head);
19927        // Both crash-before-command and resource wait are unresolved evidence.
19928        for outcomes in [
19929            Vec::new(),
19930            vec![CommandOutcome {
19931                command: "true".into(),
19932                code: None,
19933                output_tail: "cache unavailable".into(),
19934                duration_ms: 0,
19935                resource_blocked: true,
19936                ..Default::default()
19937            }],
19938        ] {
19939            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19940                head.clone(),
19941                false,
19942                outcomes,
19943            ));
19944            runner.state.gate_ran = false;
19945            runner.state.gate.clear();
19946            runner.state.save().unwrap();
19947            runner.state = RunState::load(&runner.state.id).unwrap();
19948            runner.merge().await.unwrap();
19949            assert!(runner.state.merge.is_none());
19950            runner.review_loop().await.unwrap();
19951            runner.gate().await.unwrap();
19952            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19953            assert!(runner.state.gate_allows_progress());
19954            assert_eq!(runner.state.gate_fixes.len(), 1);
19955            assert!(runner.state.merge.is_none());
19956        }
19957        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19958        git::git(
19959            &runner.state.repo,
19960            &["commit", "--allow-empty", "-m", "external update"],
19961        )
19962        .await
19963        .unwrap();
19964        runner.merge().await.unwrap();
19965        assert!(runner.state.merge.is_none());
19966        assert_eq!(runner.state.status, RunStatus::Blocked);
19967    }
19968
19969    #[cfg(unix)]
19970    #[tokio::test]
19971    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19972        for waiting_on_gate in [false, true] {
19973            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19974            runner.sync_to_base().await.unwrap();
19975            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19976            runner.state.reconcile_verification_head(&head);
19977            if waiting_on_gate {
19978                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19979                    head.clone(),
19980                    true,
19981                    Vec::new(),
19982                ));
19983            }
19984            let cache = tmp.path().join("cache");
19985            runner.state.config.verify.e2e =
19986                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19987            runner.state.config.verify.gate = vec!["true".into()];
19988            runner.state.config.graph.timeout_resource_wait = 1;
19989            let owner =
19990                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19991            let guard =
19992                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19993                    crate::cache::AcquireOutcome::Acquired(g) => g,
19994                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19995                };
19996            runner.review_loop().await.unwrap();
19997            runner.gate().await.unwrap();
19998            assert!(!runner.state.gate_ran);
19999            assert_eq!(runner.state.gate_fixes.len(), 1);
20000            assert!(runner.state.resource_block.is_some());
20001            runner.merge().await.unwrap();
20002            assert!(runner.state.merge.is_none());
20003            drop(guard);
20004            runner.state = RunState::load(&runner.state.id).unwrap();
20005            // The driver clears the previous pass's resource stop on resume.
20006            runner.state.resource_block = None;
20007            runner.review_loop().await.unwrap();
20008            runner.gate().await.unwrap();
20009            assert!(runner.state.gate_allows_progress());
20010            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20011            assert_eq!(runner.state.gate_fixes.len(), 1);
20012        }
20013    }
20014
20015    #[cfg(unix)]
20016    #[tokio::test]
20017    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
20018        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20019        runner.sync_to_base().await.unwrap();
20020        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20021        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
20022        // Verification passes before pre_gate and fails on the mechanically changed head.
20023        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
20024        runner.review_loop().await.unwrap();
20025        runner.gate().await.unwrap();
20026        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20027        assert_ne!(before, after);
20028        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
20029        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
20030        assert!(!runner.state.gate_allows_progress());
20031        runner.merge().await.unwrap();
20032        assert!(runner.state.merge.is_none());
20033        assert!(
20034            runner
20035                .state
20036                .verification_history
20037                .iter()
20038                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
20039        );
20040
20041        // An incomplete review is still an independent hold on a changed head.
20042        runner.state.reviews[0].clean = false;
20043        runner.state.reviews[0].answered = 0;
20044        runner.state.config.verify.e2e = vec!["true".into()];
20045        runner.review_loop().await.unwrap();
20046        runner.gate().await.unwrap();
20047        runner.merge().await.unwrap();
20048        assert_eq!(runner.state.status, RunStatus::Blocked);
20049        assert!(runner.state.merge.is_none());
20050        assert!(
20051            runner
20052                .state
20053                .verification_blocking_cause()
20054                .unwrap()
20055                .contains("review blocked")
20056        );
20057    }
20058
20059    #[cfg(unix)]
20060    #[tokio::test]
20061    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
20062        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20063        runner.state.gate_head = None;
20064        runner.state.config.verify.gate =
20065            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20066        runner.review_loop().await.unwrap();
20067        runner.gate().await.unwrap();
20068        assert_ne!(
20069            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20070            old
20071        );
20072        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20073        assert!(!runner.state.gate_allows_progress());
20074        assert_eq!(runner.state.status, RunStatus::Blocked);
20075        runner.merge().await.unwrap();
20076        assert!(runner.state.merge.is_none());
20077    }
20078
20079    #[cfg(unix)]
20080    #[tokio::test]
20081    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20082        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20083        let mut old_review = review_round(true, 0, 1, 1, false, true);
20084        old_review.head = head.clone();
20085        old_review.verified_head = Some(head.clone());
20086        runner.state.reviews = vec![old_review];
20087        runner.state.gate = vec![CommandOutcome {
20088            command: "old gate".into(),
20089            code: None,
20090            output_tail: "timed out after 2400s".into(),
20091            duration_ms: 2_400_000,
20092            resource_blocked: false,
20093            ..Default::default()
20094        }];
20095        runner.state.gate_ran = true;
20096        runner.state.gate_head = Some(head.clone());
20097        runner.state.land_approval = Some(crate::run::LandApproval {
20098            question: "old-head-approval".into(),
20099            head: head.clone(),
20100        });
20101        runner.state.authorize_base_sync(&task).unwrap();
20102        runner.sync_to_base().await.unwrap();
20103        assert!(!runner.state.base_sync_blocked());
20104        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20105        assert_ne!(head, fresh);
20106        assert_eq!(runner.state.reviews.len(), 1);
20107        assert!(!runner.state.gate_ran);
20108        let saved = &runner.state.base_sync_recovery.authorizations[0];
20109        assert_eq!(saved.reviews[0].head, head);
20110        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20111        assert!(saved.gate_ran);
20112        assert!(!saved.gate[0].ok());
20113        runner.review_loop().await.unwrap();
20114        runner.gate().await.unwrap();
20115        assert_eq!(runner.state.reviews[0].head, head);
20116        assert_eq!(
20117            runner.state.reviews[0].verified_head.as_deref(),
20118            Some(head.as_str())
20119        );
20120        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20121        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20122        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20123        assert!(runner.state.gate_ran);
20124        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20125        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20126        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20127        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20128        assert_eq!(
20129            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20130            "retained change"
20131        );
20132    }
20133
20134    #[cfg(unix)]
20135    #[tokio::test]
20136    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20137        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20138        let queue = crate::queue::Queue::open();
20139        let mut owner = queue.get(&task).unwrap();
20140        owner.release_operator("test-resume", None);
20141        queue.put(&mut owner).unwrap();
20142        let generation = owner.resumption.as_ref().unwrap().generation;
20143        runner.state.task_instruction = Some(owner.instruction.clone());
20144        runner.state.driver_exited = true;
20145        runner.state.save().unwrap();
20146        let home = crate::run::home();
20147        let _claim = queue.claim(&task).unwrap();
20148        owner.resumption.as_mut().unwrap().at =
20149            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20150        queue.put(&mut owner).unwrap();
20151        assert!(
20152            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20153                .await
20154                .is_err(),
20155            "an approval from before the stop grants nothing"
20156        );
20157        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20158        queue.put(&mut owner).unwrap();
20159        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20160            .await
20161            .unwrap();
20162        assert!(
20163            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20164                .await
20165                .is_err()
20166        );
20167        runner.state = RunState::load(&runner.state.id).unwrap();
20168        assert_eq!(
20169            runner.state.base_sync_recovery.authorizations[0].generation,
20170            Some(generation)
20171        );
20172        runner.sync_to_base().await.unwrap();
20173        let repo = runner.state.repo.clone();
20174        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20175        git::git(&repo, &["checkout", "main"]).await.unwrap();
20176        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20177        git::git(&repo, &["add", "."]).await.unwrap();
20178        git::git(&repo, &["commit", "-m", "move base again"])
20179            .await
20180            .unwrap();
20181        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20182        git::git(&repo, &["checkout", "fix/retained"])
20183            .await
20184            .unwrap();
20185        runner.sync_to_base().await.unwrap();
20186        assert!(!runner.state.base_sync_blocked());
20187        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20188        assert_eq!(runner.state.base_episode_used(), 2);
20189        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20190        assert_ne!(fresh, head);
20191        assert!(!runner.state.base_recovery_pending());
20192        // Even replaying the generation with a later timestamp grants nothing.
20193        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20194        queue.put(&mut owner).unwrap();
20195        assert!(
20196            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20197                .await
20198                .is_err()
20199        );
20200        runner.state = RunState::load(&runner.state.id).unwrap();
20201        runner.sync_to_base().await.unwrap();
20202        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20203        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20204        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20205    }
20206
20207    #[cfg(unix)]
20208    #[tokio::test]
20209    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20210        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20211        runner.state.base_sync = None;
20212        runner.state.status = RunStatus::Blocked;
20213        let mut second = runner.state.candidates[0].clone();
20214        second.label = 'B';
20215        runner.state.candidates.push(second);
20216        assert!(runner.state.votes.is_empty());
20217        assert!(runner.state.deliberation.is_empty());
20218        runner.deliberate().await.unwrap();
20219        runner.vote().await.unwrap();
20220        assert_eq!(runner.state.status, RunStatus::Blocked);
20221        assert!(runner.state.votes.is_empty());
20222        assert!(runner.state.deliberation.is_empty());
20223    }
20224
20225    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20226    /// reads nothing else off it.
20227    fn runner_at(status: RunStatus) -> Runner {
20228        let mut state = RunState::new(
20229            PathBuf::from("/nonexistent/repo"),
20230            "main".to_owned(),
20231            "deadbeef".to_owned(),
20232            "task".to_owned(),
20233            Config::default(),
20234        );
20235        // These fixtures test execution flow, independent of host disk capacity.
20236        state.config.disk.min_free_bytes = 0;
20237        // These fixtures share one home and save concurrently. Short clock
20238        // IDs can collide, making an ownership test read another test's run.
20239        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20240        state.id = format!(
20241            "20000101-000000-{:04x}",
20242            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20243        );
20244        state.status = status;
20245        Runner {
20246            state,
20247            roles: ResolvedRoles {
20248                implementers: Vec::new(),
20249                judges: Vec::new(),
20250                reviewers: Vec::new(),
20251                fixer: None,
20252                conductor: conductor(),
20253                implementer_roster: Vec::new(),
20254                judge_roster: Vec::new(),
20255                reviewer_roster: Vec::new(),
20256            },
20257            sem: Arc::new(Semaphore::new(1)),
20258            pause: Pause::new(),
20259            interrupt: Pause::new(),
20260        }
20261    }
20262
20263    #[tokio::test]
20264    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20265        crate::run::pin_test_home();
20266        let home = crate::run::home();
20267        let mut runner = runner_at(RunStatus::Ready);
20268        runner.state.driver_exited = true;
20269        runner.state.save().unwrap();
20270        let id = runner.state.id.clone();
20271        let path = runner.state.dir().join("run.json");
20272        let ids = ["R1-1-1".into()];
20273        let lease = crate::driver::maintenance(&home, &id).unwrap();
20274        for (guard, expected) in [
20275            (Some(lease), "currently being worked on"),
20276            (None, "ownership is being updated"),
20277        ] {
20278            let owner = if guard.is_none() {
20279                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20280            } else {
20281                None
20282            };
20283            let before = std::fs::read(&path).unwrap();
20284            let err = runner
20285                .fix_selected(&ids, "ownership conflict", false)
20286                .await
20287                .unwrap_err();
20288            assert!(format!("{err:#}").contains(expected), "{err:#}");
20289            assert_eq!(std::fs::read(&path).unwrap(), before);
20290            assert!(!runner.state.dir().join("fix.lock").exists());
20291            drop(owner);
20292            drop(guard);
20293        }
20294        let mut disk = RunState::load(&id).unwrap();
20295        disk.driver_exited = false;
20296        disk.driver_pid = Some(std::process::id());
20297        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20298        disk.save().unwrap();
20299        assert_eq!(
20300            disk.liveness_under(&home, false),
20301            crate::run::Liveness::Live
20302        );
20303        let before = std::fs::read(&path).unwrap();
20304        let err = runner
20305            .fix_selected(&ids, "live driver", false)
20306            .await
20307            .unwrap_err();
20308        assert!(
20309            err.to_string().contains("currently being worked on"),
20310            "{err:#}"
20311        );
20312        assert_eq!(std::fs::read(&path).unwrap(), before);
20313        assert!(!runner.state.dir().join("fix.lock").exists());
20314        disk.driver_exited = true;
20315        disk.driver_pid = None;
20316        disk.driver_started_at = None;
20317        disk.status = RunStatus::Reviewing;
20318        disk.save().unwrap();
20319        let before = std::fs::read(&path).unwrap();
20320        let err = runner
20321            .fix_selected(&ids, "stale state", false)
20322            .await
20323            .unwrap_err();
20324        assert!(
20325            err.to_string().contains("run changed since it was loaded"),
20326            "{err:#}"
20327        );
20328        assert_eq!(std::fs::read(&path).unwrap(), before);
20329        assert!(!runner.state.dir().join("fix.lock").exists());
20330        assert!(runner.state.operator_fixes.is_empty());
20331    }
20332
20333    #[tokio::test]
20334    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20335        use std::future::Future;
20336        use std::task::Poll;
20337
20338        crate::run::pin_test_home();
20339        let home = crate::run::home();
20340        let repo = tempfile::tempdir().unwrap();
20341        let mut runner = runner_at(RunStatus::Ready);
20342        runner.state.repo = repo.path().to_path_buf();
20343        runner.state.driver_exited = true;
20344        runner.state.candidates.push(Candidate {
20345            index: 0,
20346            label: 'A',
20347            agent: "mock".into(),
20348            branch: "magi/test/A".into(),
20349            worktree: repo.path().join("wt"),
20350            summary: String::new(),
20351            stat: String::new(),
20352            files: 0,
20353            commits: 0,
20354            empty: false,
20355            failed: None,
20356            verified_noop: None,
20357            duration_ms: 0,
20358            folded: false,
20359        });
20360        runner.state.tally = Some(Tally {
20361            first_choice: BTreeMap::from([('A', 1)]),
20362            borda: BTreeMap::new(),
20363            winner: 'A',
20364            rankings: 1,
20365            unanimous_initial: true,
20366            deliberated: false,
20367            changed_votes: 0,
20368            unanimous_final: true,
20369            tie_break: None,
20370            judges: 1,
20371            present: 1,
20372            quorum: 1,
20373            met_quorum: true,
20374            uncontested: None,
20375        });
20376        runner.state.save().unwrap();
20377        let id = runner.state.id.clone();
20378        let dir = runner.state.dir();
20379        let before = std::fs::read(dir.join("run.json")).unwrap();
20380        let ids = ["R1-1-1".into()];
20381        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20382        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20383            Poll::Pending => Poll::Ready(()),
20384            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20385        })
20386        .await;
20387        assert!(FixClaim::acquire(&dir).is_err());
20388        assert!(crate::driver::maintenance(&home, &id).is_err());
20389        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20390        drop(fix);
20391        assert!(FixClaim::acquire(&dir).is_ok());
20392        assert!(crate::driver::maintenance(&home, &id).is_ok());
20393        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20394    }
20395
20396    #[tokio::test]
20397    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20398        crate::run::pin_test_home();
20399        let temp = tempfile::tempdir().unwrap();
20400        let root = temp.path().canonicalize().unwrap();
20401        let repo = root.join("repo");
20402        std::fs::create_dir(&repo).unwrap();
20403        init_repo(&repo);
20404        git::git(&repo, &["config", "core.autocrlf", "false"])
20405            .await
20406            .unwrap();
20407        let mut runner = runner_at(RunStatus::Blocked);
20408        runner.state.repo = repo.clone();
20409        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20410        runner.state.config.agents = vec![conductor()];
20411        runner.state.config.graph.selected_implementer = Some("conductor".into());
20412        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20413        let (shell, command, setup_output) = if cfg!(windows) {
20414            (
20415                vec!["cmd".into(), "/C".into()],
20416                "echo ready>seat-ready",
20417                "ready\r\n",
20418            )
20419        } else {
20420            (
20421                vec!["sh".into(), "-c".into()],
20422                "printf ready > seat-ready",
20423                "ready",
20424            )
20425        };
20426        runner.state.config.verify.shell = Some(shell);
20427        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20428            run: Some(command.into()),
20429            ..Default::default()
20430        }];
20431        runner.state.save().unwrap();
20432        let path = runner.state.worktree_root().join("judge-1");
20433        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20434            .await
20435            .unwrap();
20436        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20437        git::git(&path, &["add", "."]).await.unwrap();
20438        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20439        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20440            .await
20441            .unwrap();
20442        git::git(&path, &["checkout", "--detach", &head])
20443            .await
20444            .unwrap();
20445        let evidence = crate::fold_evidence::snapshot(
20446            &runner.state,
20447            &crate::run::home().canonicalize().unwrap(),
20448            &head,
20449            64 * 1024 * 1024,
20450        )
20451        .await
20452        .unwrap();
20453        let mut contents = BTreeMap::new();
20454        contents.insert(
20455            repo.join("logs/HEAD"),
20456            format!("{head} {head} fixture\n").into_bytes(),
20457        );
20458        let record = serde_json::json!({
20459            "version":1, "run":runner.state.id, "source":path, "head":head,
20460            "evidence":evidence, "admin":{}, "admin_contents":contents,
20461            "history":{head.clone():evidence}, "phase":"evicted"
20462        });
20463        std::fs::write(
20464            runner.state.dir().join("artifacts/eviction-judge-1.json"),
20465            serde_json::to_vec(&record).unwrap(),
20466        )
20467        .unwrap();
20468        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
20469        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
20470            .await
20471            .unwrap();
20472        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
20473        assert!(
20474            !git::git_raw(&repo, &["cat-file", "-e", &head])
20475                .await
20476                .unwrap()
20477                .ok()
20478        );
20479        let mut resumed = Runner::resume(&runner.state.id).unwrap();
20480        let error = resumed.execute().await.unwrap_err();
20481        assert!(
20482            error
20483                .to_string()
20484                .contains("selected implementation is held"),
20485            "{error:#}"
20486        );
20487        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
20488        assert_eq!(
20489            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
20490            setup_output
20491        );
20492        assert_eq!(
20493            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
20494            "unrelated seat"
20495        );
20496        let error = resumed.execute().await.unwrap_err();
20497        assert!(
20498            error
20499                .to_string()
20500                .contains("selected implementation is held"),
20501            "{error:#}"
20502        );
20503        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
20504        git::git(&path, &["add", "."]).await.unwrap();
20505        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
20506        let next = git::git(
20507            &path,
20508            &[
20509                "commit-tree",
20510                &next_tree,
20511                "-p",
20512                &head,
20513                "-m",
20514                "next review checkpoint",
20515            ],
20516        )
20517        .await
20518        .unwrap();
20519        git::git(&path, &["checkout", "--detach", &next])
20520            .await
20521            .unwrap();
20522        resumed.state.reviews.push(
20523            serde_json::from_value(serde_json::json!({
20524                "round":1, "head":next, "reviews":[]
20525            }))
20526            .unwrap(),
20527        );
20528        resumed.state.save().unwrap();
20529        let error = resumed.execute().await.unwrap_err();
20530        assert!(
20531            error
20532                .to_string()
20533                .contains("selected implementation is held"),
20534            "{error:#}"
20535        );
20536        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
20537    }
20538
20539    #[tokio::test]
20540    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
20541        crate::run::pin_test_home();
20542        let mut runner = runner_at(RunStatus::Gating);
20543        runner.state.save().unwrap();
20544        let id = runner.state.id.clone();
20545        let passes = runner.state.passes.len();
20546        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20547        let mut claiming = Box::pin(runner.claim_driver(None));
20548        std::future::poll_fn(|cx| {
20549            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
20550            std::task::Poll::Ready(())
20551        })
20552        .await;
20553        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
20554        drop(owner);
20555        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
20556            .await
20557            .unwrap()
20558            .unwrap();
20559        assert_eq!(execution.runner.state.passes.len(), passes + 1);
20560        assert!(execution.runner.state.resource_block.is_none());
20561        assert_eq!(
20562            execution.runner.state.liveness(false),
20563            crate::run::Liveness::Live
20564        );
20565        drop(execution);
20566        assert!(RunState::load(&id).unwrap().driver_exited);
20567    }
20568
20569    #[tokio::test]
20570    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
20571        crate::run::pin_test_home();
20572        let mut runner = runner_at(RunStatus::Gating);
20573        runner.state.save().unwrap();
20574        // run.json can commit, but the subsequent lease metadata write fails.
20575        // Cleanup must run after releasing the short ownership lock.
20576        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
20577        assert!(runner.claim_driver(None).await.is_err());
20578        assert!(runner.state.driver_exited);
20579        assert_eq!(runner.state.driver_pid, None);
20580        let disk = RunState::load(&runner.state.id).unwrap();
20581        assert!(disk.driver_exited);
20582        assert_eq!(disk.driver_pid, None);
20583        assert_eq!(disk.status, RunStatus::Gating);
20584    }
20585
20586    #[tokio::test]
20587    async fn an_early_graph_error_releases_its_driver() {
20588        crate::run::pin_test_home();
20589        let mut runner = runner_at(RunStatus::Blocked);
20590        runner.state.config.graph.selected_implementer = Some("selected".into());
20591        runner.state.save().unwrap();
20592        assert!(runner.execute().await.is_err());
20593        let disk = RunState::load(&runner.state.id).unwrap();
20594        assert!(disk.driver_exited);
20595        assert_eq!(disk.driver_pid, None);
20596        assert_eq!(disk.status, RunStatus::Blocked);
20597    }
20598
20599    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
20600        crate::run::MergeRepair {
20601            question: "repair-question".into(),
20602            head: "old-head".into(),
20603            pr: "https://github.com/o/r/pull/42".into(),
20604            reviews: vec![review_round(false, 1, 1, 1, false, true)],
20605            gate: vec![outcome(Some(0), false)],
20606            gate_head: Some("old-head".into()),
20607            gate_fixes: Vec::new(),
20608            pre_gate: Vec::new(),
20609            phase,
20610            failure: None,
20611        }
20612    }
20613
20614    #[tokio::test]
20615    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
20616        crate::run::pin_test_home();
20617        let mut runner = runner_at(RunStatus::Landing);
20618        runner.state.merge_repairs.push(merge_repair_request(
20619            crate::run::MergeRepairPhase::Requested,
20620        ));
20621        runner.state.save().unwrap();
20622        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
20623        assert!(
20624            runner
20625                .execute()
20626                .await
20627                .unwrap_err()
20628                .to_string()
20629                .contains("already running")
20630        );
20631        assert_eq!(
20632            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20633            crate::run::MergeRepairPhase::Requested
20634        );
20635        drop(claim);
20636        let mut disk = runner.state.clone();
20637        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
20638        disk.save().unwrap();
20639        assert!(
20640            runner
20641                .execute()
20642                .await
20643                .unwrap_err()
20644                .to_string()
20645                .contains("decision changed")
20646        );
20647        assert_eq!(
20648            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20649            crate::run::MergeRepairPhase::Complete
20650        );
20651    }
20652
20653    #[test]
20654    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
20655        crate::run::pin_test_home();
20656        let mut runner = runner_at(RunStatus::Landing);
20657        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
20658        runner.state.reviews = request.reviews.clone();
20659        runner.state.gate = request.gate.clone();
20660        runner.state.gate_ran = true;
20661        runner.state.land_approval = Some(crate::run::LandApproval {
20662            question: "old".into(),
20663            head: "old-head".into(),
20664        });
20665        runner.state.merge_repairs.push(request);
20666        runner.begin_merge_repair_review(0).unwrap();
20667        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
20668        assert!(!runner.state.gate_status().ok());
20669        assert!(runner.state.land_approval.is_none());
20670        let disk = RunState::load(&runner.state.id).unwrap();
20671        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
20672        assert!(disk.merge_repairs[0].gate[0].ok());
20673        assert_eq!(
20674            disk.merge_repairs[0].phase,
20675            crate::run::MergeRepairPhase::Reviewing
20676        );
20677        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
20678        assert!(disk.reviews.is_empty());
20679    }
20680
20681    #[tokio::test]
20682    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
20683        crate::run::pin_test_home();
20684        for phase in [
20685            crate::run::MergeRepairPhase::Fixing,
20686            crate::run::MergeRepairPhase::Requested,
20687        ] {
20688            let mut runner = runner_at(RunStatus::Landing);
20689            runner.state.config.graph.land_rounds = 0;
20690            runner.state.merge_repairs.push(merge_repair_request(phase));
20691            runner.state.save().unwrap();
20692            assert!(!runner.repair_merge_review().await.unwrap());
20693            assert_eq!(runner.state.status, RunStatus::Blocked);
20694            assert_eq!(
20695                runner.state.merge_repairs[0].phase,
20696                crate::run::MergeRepairPhase::Failed
20697            );
20698            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
20699            assert!(
20700                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
20701                    "interrupted"
20702                } else {
20703                    "budget exhausted"
20704                })
20705            );
20706            assert!(runner.state.merge.is_none());
20707        }
20708    }
20709
20710    /// `park_here` folding in the reason `Pause::park_because` recorded -
20711    /// this is what lets an operator reading a run's events tell an
20712    /// interrupt-driven park from an ordinary shutdown park.
20713    #[test]
20714    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
20715        crate::run::pin_test_home();
20716        let mut runner = runner_at(RunStatus::Implementing);
20717        let interrupt = Pause::new();
20718        runner.watch_interrupt(interrupt.clone());
20719
20720        interrupt.park_because("task a1b2 asked to run first");
20721
20722        assert!(runner.park_here().expect("park_here"));
20723        assert!(runner.state.parked);
20724        let last = runner.state.events.last().expect("a park event");
20725        assert_eq!(last.node, "park");
20726        assert!(
20727            last.message.contains("task a1b2 asked to run first"),
20728            "expected the interrupt reason in {:?}",
20729            last.message
20730        );
20731    }
20732
20733    /// The cause is stored on the pass when it parks, and the first cause a
20734    /// shared pause was given is the one that stays.
20735    #[test]
20736    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
20737        crate::run::pin_test_home();
20738        let mut runner = runner_at(RunStatus::Implementing);
20739        runner.state.begin_pass();
20740        let shutdown = Pause::new();
20741        runner.on_pause(shutdown.clone());
20742        let upgrade = ParkCause::Upgrade {
20743            from: "0.121.0".to_owned(),
20744            to: Some("0.121.1".to_owned()),
20745        };
20746        shutdown.park_for(upgrade.clone());
20747        shutdown.park_for(ParkCause::Operator);
20748
20749        assert!(runner.park_here().expect("park_here"));
20750        assert_eq!(
20751            runner.state.passes[0].end,
20752            Some(crate::run::PassEnd::Parked { cause: upgrade })
20753        );
20754        let last = runner.state.events.last().expect("a park event");
20755        assert!(last.message.contains("0.121.0"), "{}", last.message);
20756    }
20757
20758    #[tokio::test]
20759    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
20760        crate::run::pin_test_home();
20761        let mut runner = runner_at(RunStatus::Reviewing);
20762        runner.state.save().unwrap();
20763        let mut execution = runner.claim_driver(None).await.expect("first execution");
20764        assert_eq!(execution.runner.state.passes.len(), 1);
20765        execution
20766            .driver
20767            .finish(&mut execution.runner.state)
20768            .await
20769            .unwrap();
20770    }
20771
20772    #[tokio::test]
20773    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
20774        crate::run::pin_test_home();
20775        let mut runner = runner_at(RunStatus::Reviewing);
20776        runner.state.config.agents = vec![conductor()];
20777        runner.state.config.graph.timeout_resource_wait = 0;
20778        runner.state.save().unwrap();
20779        let id = runner.state.id.clone();
20780        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20781        assert!(runner.claim_driver(None).await.is_err());
20782        drop(owner);
20783        drop(runner);
20784        let mut resumed = Runner::resume(&id).unwrap();
20785        assert_eq!(resumed.state.driver_claimed, Some(false));
20786        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
20787        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
20788        let mut execution = resumed
20789            .claim_driver(None)
20790            .await
20791            .expect("retry initial claim after reload");
20792        assert_eq!(execution.runner.state.driver_claimed, Some(true));
20793        assert_eq!(execution.runner.state.passes.len(), 1);
20794        execution
20795            .driver
20796            .finish(&mut execution.runner.state)
20797            .await
20798            .unwrap();
20799    }
20800
20801    #[tokio::test]
20802    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
20803        crate::run::pin_test_home();
20804        let mut runner = runner_at(RunStatus::Reviewing);
20805        runner.state.config.agents = vec![conductor()];
20806        runner.state.save().unwrap();
20807        let id = runner.state.id.clone();
20808        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
20809        let mut resumed = Runner::resume(&id).unwrap();
20810        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
20811        assert!(resumed.claim_driver(None).await.is_err());
20812        assert!(RunState::load(&id).unwrap().passes.is_empty());
20813        drop(lease);
20814        let mut execution = resumed.claim_driver(None).await.unwrap();
20815        execution
20816            .driver
20817            .finish(&mut execution.runner.state)
20818            .await
20819            .unwrap();
20820    }
20821
20822    #[tokio::test]
20823    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
20824        crate::run::pin_test_home();
20825        let mut runner = runner_at(RunStatus::Reviewing);
20826        let state = &mut runner.state;
20827        state.config.agents = vec![conductor()];
20828        state.driver_claimed = None;
20829        state.driver_pid = Some(std::process::id());
20830        state.driver_started_at = None;
20831        state.begin_pass();
20832        state.save().unwrap();
20833        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
20834        std::fs::write(
20835            state.dir().join("driver.json"),
20836            serde_json::to_vec(&serde_json::json!({
20837                "pid": state.driver_pid, "started_at": null,
20838                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
20839            }))
20840            .unwrap(),
20841        )
20842        .unwrap();
20843        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
20844        drop(lease);
20845        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
20846        let mut resumed = Runner::resume(&state.id).unwrap();
20847        assert!(!resumed.state.driver_exited);
20848        let mut execution = resumed
20849            .claim_driver(None)
20850            .await
20851            .expect("lease proves previous execution ended");
20852        assert_eq!(execution.runner.state.passes.len(), 2);
20853        execution
20854            .driver
20855            .finish(&mut execution.runner.state)
20856            .await
20857            .unwrap();
20858    }
20859
20860    #[tokio::test]
20861    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
20862        crate::run::pin_test_home();
20863        let mut runner = runner_at(RunStatus::Reviewing);
20864        let mut json = serde_json::to_value(&runner.state).unwrap();
20865        json.as_object_mut().unwrap().remove("driver_claimed");
20866        runner.state = serde_json::from_value(json).unwrap();
20867        assert_eq!(runner.state.driver_claimed, None);
20868        runner.state.save().unwrap();
20869        let mut execution = runner
20870            .claim_driver(None)
20871            .await
20872            .expect("the execution lease, not a missing marker, excludes a second driver");
20873        assert_eq!(execution.runner.state.passes.len(), 1);
20874        execution
20875            .driver
20876            .finish(&mut execution.runner.state)
20877            .await
20878            .unwrap();
20879    }
20880
20881    #[tokio::test]
20882    async fn driver_admission_refuses_a_proven_live_driver() {
20883        crate::run::pin_test_home();
20884        let mut runner = runner_at(RunStatus::Reviewing);
20885        let pid = std::process::id();
20886        runner.state.driver_pid = Some(pid);
20887        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20888        assert!(runner.state.driver_started_at.is_some());
20889        runner.state.save().unwrap();
20890        let error = runner
20891            .claim_driver(None)
20892            .await
20893            .err()
20894            .expect("a live driver must refuse");
20895        let message = error.to_string();
20896        assert!(
20897            message.starts_with("run already has a live driver: "),
20898            "{message}"
20899        );
20900        assert!(message.contains(&format!("pid={pid}")), "{message}");
20901        assert!(
20902            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
20903            "{message}"
20904        );
20905        let saved = RunState::load(&runner.state.id).unwrap();
20906        assert_eq!(saved.driver_pid, Some(pid));
20907        assert_eq!(saved.status, RunStatus::Reviewing);
20908        assert!(saved.passes.is_empty());
20909    }
20910
20911    #[tokio::test]
20912    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
20913        crate::run::pin_test_home();
20914        let home = crate::run::home();
20915        let mut runner = runner_at(RunStatus::Reviewing);
20916        runner.state.driver_exited = true;
20917        runner.state.driver_pid = None;
20918        runner.state.driver_started_at = None;
20919        runner.state.save().unwrap();
20920
20921        let queue = crate::queue::Queue::at(home.join("queue"));
20922        let mut task = crate::queue::Task::new(
20923            "task".into(),
20924            "task".into(),
20925            runner.state.repo.clone(),
20926            crate::queue::Source::Human,
20927        );
20928        task.runs.push(runner.state.id.clone());
20929        queue.put(&mut task).unwrap();
20930        let payload = serde_json::json!({
20931            "queue": home.join("queue"),
20932            "task": task.id,
20933            "opts": crate::daemon::Opts::default(),
20934            "standalone": false,
20935        });
20936        let (job, lease) =
20937            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
20938
20939        let error = runner
20940            .claim_driver(None)
20941            .await
20942            .err()
20943            .expect("another active worker claim must refuse");
20944        let message = error.to_string();
20945        assert!(
20946            message.starts_with("run already has a live driver: worker claim"),
20947            "{message}"
20948        );
20949        assert!(message.contains(&job.id), "{message}");
20950        assert!(message.contains("status=running"), "{message}");
20951        assert!(message.contains("live.lock held"), "{message}");
20952
20953        drop(lease);
20954        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
20955    }
20956
20957    #[test]
20958    fn parking_resource_halt_persists_the_pass_once() {
20959        crate::run::pin_test_home();
20960        let mut runner = runner_at(RunStatus::Reviewing);
20961        runner.state.begin_pass();
20962        runner.state.resource_block = Some(crate::run::ResourceBlock {
20963            node: "fix".into(),
20964            kind: "shared build cache".into(),
20965            detail: "cancelled".into(),
20966            at: Timestamp::now(),
20967            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20968        });
20969        let cause = ParkCause::Upgrade {
20970            from: "old".into(),
20971            to: Some("new".into()),
20972        };
20973        runner.pause.park_for(cause.clone());
20974        // Both direct fixer exits and graph resource boundaries must complete
20975        // parking, rather than returning a stale Reviewing record.
20976        runner.stop_for_resource().unwrap();
20977        assert!(runner.resource_halt().unwrap());
20978        assert!(runner.park_here().unwrap());
20979        let saved = RunState::load(&runner.state.id).unwrap();
20980        assert!(saved.parked);
20981        assert_eq!(saved.status, RunStatus::Reviewing);
20982        assert!(saved.passes[0].ended_at.is_some());
20983        assert_eq!(
20984            saved.passes[0].end,
20985            Some(crate::run::PassEnd::Parked {
20986                cause: cause.clone()
20987            })
20988        );
20989        assert_eq!(
20990            saved.resource_block.unwrap().cause,
20991            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20992        );
20993        assert_eq!(
20994            saved
20995                .events
20996                .iter()
20997                .filter(|event| event.node == "park")
20998                .count(),
20999            1
21000        );
21001    }
21002
21003    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
21004    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
21005    /// cleared) must not make a *different* run - one only watching its own,
21006    /// unshared interrupt `Pause` - see itself as parked. If a future change
21007    /// ever collapsed these back into one handle, the interrupt scheduler
21008    /// would park every run for the rest of the daemon's life, not just the
21009    /// one it meant to interrupt.
21010    #[test]
21011    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
21012        crate::run::pin_test_home();
21013        let mut runner = runner_at(RunStatus::Implementing);
21014        let shutdown = Pause::new();
21015        runner.on_pause(shutdown.clone());
21016        let interrupt = Pause::new();
21017        runner.watch_interrupt(interrupt.clone());
21018
21019        // Nobody has asked for anything yet.
21020        assert!(!runner.park_here().expect("park_here"));
21021        assert!(!runner.state.parked);
21022
21023        // Only the interrupt handle fires; the shutdown handle stays clear.
21024        interrupt.park_because("test");
21025        assert!(!shutdown.parked());
21026        assert!(runner.park_here().expect("park_here"));
21027    }
21028
21029    /// The property every prior attempt at this feature failed to pin down:
21030    /// asking a run to park while one of its nodes has a real, in-flight
21031    /// async operation running (an agent call, in production) must not cut
21032    /// that operation short. `park_here` is only ever consulted *between*
21033    /// `execute`'s node calls - see its own doc - so nothing inside a node
21034    /// can observe a park request until the node itself returns. This proves
21035    /// that structurally, with real `tokio` concurrency and a channel
21036    /// handshake (never a sleep, which would only prove "usually", not
21037    /// "cannot"): the "node" below reports that it has genuinely started,
21038    /// and only then is the park requested; the node still has to be told to
21039    /// finish before `park_here` is ever called, exactly mirroring every
21040    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
21041    /// in `execute`.
21042    #[tokio::test]
21043    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
21044        crate::run::pin_test_home();
21045        let mut runner = runner_at(RunStatus::Implementing);
21046        let interrupt = Pause::new();
21047        runner.watch_interrupt(interrupt.clone());
21048
21049        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
21050        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
21051
21052        // Stands in for one node's in-flight agent call: it proves it has
21053        // genuinely started, then blocks - exactly as a spawned CLI process
21054        // does - until told to finish.
21055        let node = async move {
21056            started_tx.send(()).expect("send started");
21057            finish_rx.await.expect("recv finish");
21058            "node finished"
21059        };
21060
21061        let interrupter = async move {
21062            started_rx.await.expect("recv started");
21063            // The call is now genuinely in flight. Ask it to park.
21064            interrupt.park_because("higher-priority task waiting");
21065            // Nothing the node does can observe this yet - there is no
21066            // check inside it, by construction - so let the executor run
21067            // anything pending and then let the node finish on its own.
21068            tokio::task::yield_now().await;
21069            finish_tx.send(()).expect("send finish");
21070        };
21071
21072        let (node_result, ()) = tokio::join!(node, interrupter);
21073        assert_eq!(
21074            node_result, "node finished",
21075            "the in-flight call ran to completion"
21076        );
21077
21078        // Only now, at the boundary the real `execute` would check right
21079        // after this node, does the park take effect.
21080        assert!(runner.park_here().expect("park_here"));
21081        assert!(runner.state.parked);
21082    }
21083
21084    /// A run parked mid-competition carries every field it had accumulated
21085    /// through the exact same disk round-trip an ordinary resume uses -
21086    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21087    /// Nothing about parking for an interrupt is a special case of that path;
21088    /// this is what proves it rather than assuming it.
21089    #[test]
21090    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21091        crate::run::pin_test_home();
21092        let mut runner = runner_at(RunStatus::Judging);
21093        // `Runner::resume` re-resolves roles from the saved config, which
21094        // refuses an empty roster - give it the same minimal one `conductor`
21095        // itself uses.
21096        runner.state.config.agents = vec![conductor()];
21097        runner.state.candidates = vec![Candidate {
21098            index: 0,
21099            label: 'A',
21100            agent: "alpha".to_owned(),
21101            branch: "magi/x/A".to_owned(),
21102            worktree: PathBuf::from("/nonexistent/worktree"),
21103            summary: "did the thing".to_owned(),
21104            stat: "1 file changed".to_owned(),
21105            files: 1,
21106            commits: 1,
21107            empty: false,
21108            failed: None,
21109            verified_noop: None,
21110            duration_ms: 1234,
21111            folded: false,
21112        }];
21113        let run_id = runner.state.id.clone();
21114
21115        let interrupt = Pause::new();
21116        runner.watch_interrupt(interrupt.clone());
21117        interrupt.park_because("task c3d4 asked to run first");
21118        assert!(runner.park_here().expect("park_here"));
21119
21120        let resumed = Runner::resume(&run_id).expect("resume");
21121        assert_eq!(resumed.state.candidates.len(), 1);
21122        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21123        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21124        assert_eq!(resumed.state.status, runner.state.status);
21125        assert!(
21126            resumed.state.parked,
21127            "still parked until `execute` actually walks the graph again"
21128        );
21129        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21130    }
21131
21132    /// A fresh open question on `run`, stored and handed back for assertions.
21133    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21134        let mut q = ask::Question::new(
21135            run.to_owned(),
21136            "implement".to_owned(),
21137            "impl-A".to_owned(),
21138            "Which storage backend should the cache use?".to_owned(),
21139            String::new(),
21140            vec!["SQLite".to_owned(), "Redis".to_owned()],
21141        );
21142        store.put(&mut q).unwrap();
21143        q
21144    }
21145
21146    #[test]
21147    fn a_failed_runs_open_question_is_abandoned() {
21148        ask_test_home();
21149        let store = ask::Questions::open();
21150        let mut runner = runner_at(RunStatus::Failed);
21151        let run = runner.state.id.clone();
21152        let q = ask_open_question(&store, &run);
21153
21154        runner.settle_questions();
21155
21156        let back = store.get(&q.id).unwrap();
21157        assert!(
21158            !back.status.open(),
21159            "the seat that asked died with the run; nobody is left to read an answer"
21160        );
21161        assert!(
21162            back.detail.contains(&run) && back.detail.contains("failed"),
21163            "the reason names what the run became, not just that it is gone: {}",
21164            back.detail
21165        );
21166    }
21167
21168    #[test]
21169    fn a_merged_runs_open_question_is_abandoned_too() {
21170        ask_test_home();
21171        let store = ask::Questions::open();
21172        // A run that finishes cleanly still leaves nobody to read an answer -
21173        // this is not only a failure-path cleanup.
21174        for status in [RunStatus::Merged, RunStatus::Ready] {
21175            let mut runner = runner_at(status);
21176            let run = runner.state.id.clone();
21177            let q = ask_open_question(&store, &run);
21178
21179            runner.settle_questions();
21180
21181            let back = store.get(&q.id).unwrap();
21182            assert!(
21183                !back.status.open(),
21184                "{status:?} run's question must not outlive the run"
21185            );
21186        }
21187    }
21188
21189    #[test]
21190    fn a_still_resumable_runs_open_question_is_left_alone() {
21191        ask_test_home();
21192        let store = ask::Questions::open();
21193        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21194        // review round and the seat sessions are all still on disk — so a
21195        // question asked mid-round may yet get a real answer from a real
21196        // resume. Sweeping it here would be exactly the failure mode this
21197        // whole feature exists to avoid on the other side.
21198        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21199            let mut runner = runner_at(status);
21200            let run = runner.state.id.clone();
21201            let q = ask_open_question(&store, &run);
21202
21203            runner.settle_questions();
21204
21205            let back = store.get(&q.id).unwrap();
21206            assert!(
21207                back.status.open(),
21208                "{status:?} is still alive; the question must still be waiting"
21209            );
21210        }
21211    }
21212
21213    #[test]
21214    fn settle_questions_never_touches_an_already_answered_question() {
21215        ask_test_home();
21216        let store = ask::Questions::open();
21217        let mut runner = runner_at(RunStatus::Failed);
21218        let run = runner.state.id.clone();
21219        let mut q = ask_open_question(&store, &run);
21220        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21221            .unwrap();
21222        store.put(&mut q).unwrap();
21223
21224        // Called twice, the way a crash-recovered daemon reclaim and the
21225        // graph's own cleanup both can for the same run — `abandon_for_run`
21226        // only ever touches what is still open, so this must be inert both
21227        // times, not merely the second.
21228        runner.settle_questions();
21229        runner.settle_questions();
21230
21231        let back = store.get(&q.id).unwrap();
21232        assert_eq!(
21233            back.status,
21234            ask::QuestionStatus::Answered,
21235            "a real answer is a decision on record, never overwritten by a sweep"
21236        );
21237    }
21238
21239    #[tokio::test]
21240    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21241        let tmp = tempfile::tempdir().unwrap();
21242        let home = tmp.path().join("home");
21243        let repo = tmp.path().join("repo");
21244        std::fs::create_dir(&home).unwrap();
21245        std::fs::create_dir(&repo).unwrap();
21246        init_repo(&repo);
21247
21248        let mut config = Config::default();
21249        config.graph.worktree_root = Some(tmp.path().join("wt"));
21250        config.verify.build_cache = crate::config::BuildCache::Isolated;
21251        let mut state = RunState::new(
21252            repo.clone(),
21253            "main".into(),
21254            "base".into(),
21255            "fold fixture".into(),
21256            config,
21257        );
21258        let root = state.worktree_root();
21259        let mut outputs = Vec::new();
21260        for name in ["idle", "busy"] {
21261            let checkout = root.join(name);
21262            git::worktree_add_detached(&repo, &checkout, "main")
21263                .await
21264                .unwrap();
21265            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21266            let output = target.join("generated");
21267            std::fs::write(&output, name).unwrap();
21268            outputs.push((target, output));
21269        }
21270        let unknown = crate::build_target::root(&home)
21271            .join("00000000-0000-0000-0000-000000000000")
21272            .join("target");
21273        std::fs::create_dir_all(&unknown).unwrap();
21274        let unowned = unknown.join("generated");
21275        std::fs::write(&unowned, "keep").unwrap();
21276        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21277        let crate::cache::AcquireOutcome::Acquired(_lease) =
21278            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21279        else {
21280            panic!("fixture target must be free");
21281        };
21282
21283        fold_run(&mut state, true, &home).await.unwrap();
21284        assert!(!root.exists());
21285        assert!(!outputs[0].1.exists());
21286        assert!(outputs[1].1.is_file());
21287        assert!(unowned.is_file());
21288    }
21289
21290    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21291    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21292    /// without merging, whose winner is still the operator's answer to read.
21293    /// Nothing previously called `fold_run` itself with a real `tally`, so
21294    /// this is the first test to pin down the one distinction the whole
21295    /// automatic-fold feature depends on: the winner's worktree and branch
21296    /// must survive, everything else sharing the run's worktree bay - a
21297    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21298    /// second sweep treats every non-winner directory under the bay alike -
21299    /// must not.
21300    #[tokio::test]
21301    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21302        crate::run::pin_test_home();
21303        let tmp = tempfile::tempdir().expect("tempdir");
21304        let repo = tmp.path().join("repo");
21305        std::fs::create_dir_all(&repo).unwrap();
21306        init_repo(&repo);
21307
21308        let mut config = Config::default();
21309        config.graph.worktree_root = Some(tmp.path().join("wt"));
21310
21311        let mut state = RunState::new(
21312            repo.clone(),
21313            "main".to_owned(),
21314            "deadbeef".to_owned(),
21315            "task".to_owned(),
21316            config,
21317        );
21318        let root = state.worktree_root();
21319        let wt_a = root.join("cand-A");
21320        let wt_b = root.join("cand-B");
21321        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21322            .await
21323            .expect("worktree A");
21324        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21325            .await
21326            .expect("worktree B");
21327
21328        state.candidates = vec![
21329            Candidate {
21330                index: 0,
21331                label: 'A',
21332                agent: "alpha".to_owned(),
21333                branch: "magi/x/A".to_owned(),
21334                worktree: wt_a.clone(),
21335                summary: String::new(),
21336                stat: String::new(),
21337                files: 0,
21338                commits: 0,
21339                empty: false,
21340                failed: None,
21341                verified_noop: None,
21342                duration_ms: 0,
21343                folded: false,
21344            },
21345            Candidate {
21346                index: 1,
21347                label: 'B',
21348                agent: "beta".to_owned(),
21349                branch: "magi/x/B".to_owned(),
21350                worktree: wt_b.clone(),
21351                summary: String::new(),
21352                stat: String::new(),
21353                files: 0,
21354                commits: 0,
21355                empty: false,
21356                failed: None,
21357                verified_noop: None,
21358                duration_ms: 0,
21359                folded: false,
21360            },
21361        ];
21362        state.tally = Some(Tally {
21363            first_choice: BTreeMap::from([('A', 1)]),
21364            borda: BTreeMap::new(),
21365            winner: 'A',
21366            rankings: 1,
21367            unanimous_initial: true,
21368            deliberated: false,
21369            changed_votes: 0,
21370            unanimous_final: true,
21371            tie_break: None,
21372            judges: 1,
21373            present: 1,
21374            quorum: 1,
21375            met_quorum: true,
21376            uncontested: None,
21377        });
21378        state.status = RunStatus::Ready;
21379
21380        fold_run(&mut state, false, &crate::run::home())
21381            .await
21382            .expect("fold_run");
21383
21384        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21385        assert!(
21386            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21387            "the unmerged winner's branch survives"
21388        );
21389        assert!(
21390            !state.candidates[0].folded,
21391            "the winner is not marked folded"
21392        );
21393
21394        assert!(!wt_b.exists(), "the loser's worktree is removed");
21395        assert!(
21396            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
21397            "the loser's branch is removed"
21398        );
21399        assert!(state.candidates[1].folded, "the loser is marked folded");
21400    }
21401
21402    #[tokio::test]
21403    #[cfg(unix)]
21404    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
21405        use std::os::fd::AsRawFd as _;
21406        use std::time::Duration;
21407
21408        let tmp = tempfile::tempdir().unwrap();
21409        let repo = tmp.path().join("repo");
21410        std::fs::create_dir_all(&repo).unwrap();
21411        init_repo(&repo);
21412        let common = repo.join(".git");
21413        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
21414        let home = tmp.path().join("home");
21415        let mut config = Config::default();
21416        config.coordination = crate::config::test_coordination();
21417        config.graph.worktree_root = Some(tmp.path().join("wt"));
21418        config.graph.timeout_resource_wait = 1;
21419        let mut state = RunState::new(
21420            repo.clone(),
21421            "main".into(),
21422            "deadbeef".into(),
21423            "task".into(),
21424            config,
21425        );
21426        let root = state.worktree_root();
21427        let candidate = root.join("cand-A");
21428        let reviewer = root.join("review-1");
21429        let branch = state.branch_for('A');
21430        git::worktree_add_branch(&repo, &candidate, &branch, "main")
21431            .await
21432            .unwrap();
21433        git::worktree_add_detached(&repo, &reviewer, "main")
21434            .await
21435            .unwrap();
21436        git::acquire_worktree_config(&repo).await.unwrap();
21437        state.enabled_worktree_config = true;
21438        state.status = RunStatus::Ready;
21439        state.candidates.push(Candidate {
21440            index: 0,
21441            label: 'A',
21442            agent: "implement".into(),
21443            branch: branch.clone(),
21444            worktree: candidate.clone(),
21445            summary: String::new(),
21446            stat: String::new(),
21447            files: 0,
21448            commits: 0,
21449            empty: false,
21450            failed: None,
21451            verified_noop: None,
21452            duration_ms: 0,
21453            folded: false,
21454        });
21455        state.save_under(&home).unwrap();
21456        let config_before = std::fs::read(common.join("config")).unwrap();
21457        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
21458            .await
21459            .unwrap();
21460        // A separate OS handle bypasses the launcher's local gate, exactly as
21461        // an external updater does, and must still prevent all folding work.
21462        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
21463        assert_eq!(
21464            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
21465            0
21466        );
21467        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21468        assert!(
21469            tokio::time::timeout(Duration::from_millis(200), &mut fold)
21470                .await
21471                .is_err()
21472        );
21473        assert!(candidate.exists());
21474        assert!(reviewer.exists());
21475        assert!(git::branch_exists(&repo, &branch).await.unwrap());
21476        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21477        assert_eq!(
21478            git::git(&repo, &["worktree", "list", "--porcelain"])
21479                .await
21480                .unwrap(),
21481            worktrees_before
21482        );
21483        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
21484            .await
21485            .unwrap()
21486            .unwrap_err();
21487        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
21488        drop(fold);
21489        assert!(candidate.exists() && reviewer.exists());
21490        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
21491        assert_eq!(
21492            state.resource_block.as_ref().unwrap().kind,
21493            "repository coordination"
21494        );
21495        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21496        drop(external);
21497        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21498        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
21499            .await
21500            .unwrap()
21501            .unwrap();
21502        drop(fold);
21503        assert!(removed.contains(&branch));
21504        assert!(!root.exists());
21505        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
21506        assert!(state.candidates[0].folded);
21507        assert!(!state.enabled_worktree_config);
21508        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
21509        let enabled = git::git_raw(
21510            &repo,
21511            &["config", "--local", "--get", "extensions.worktreeConfig"],
21512        )
21513        .await
21514        .unwrap();
21515        assert!(!enabled.ok(), "the last config reference was released");
21516    }
21517
21518    /// A branch handed to a later run is that run's (and its pull request's):
21519    /// folding the run that released it must not delete it.
21520    #[tokio::test]
21521    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
21522        let tmp = tempfile::tempdir().expect("tempdir");
21523        let repo = tmp.path().join("repo");
21524        std::fs::create_dir_all(&repo).unwrap();
21525        init_repo(&repo);
21526        let home = tmp.path().join("home");
21527
21528        let mut config = Config::default();
21529        config.graph.worktree_root = Some(tmp.path().join("wt"));
21530        let mut state = RunState::new(
21531            repo.clone(),
21532            "main".to_owned(),
21533            "deadbeef".to_owned(),
21534            "task".to_owned(),
21535            config,
21536        );
21537        // The worktree is already gone (released); the branch survives.
21538        git::git(&repo, &["branch", "magi/x/A", "main"])
21539            .await
21540            .expect("branch");
21541        state.candidates = vec![Candidate {
21542            index: 0,
21543            label: 'A',
21544            agent: "alpha".to_owned(),
21545            branch: "magi/x/A".to_owned(),
21546            worktree: state.worktree_root().join("cand-A"),
21547            summary: String::new(),
21548            stat: String::new(),
21549            files: 0,
21550            commits: 0,
21551            empty: false,
21552            failed: None,
21553            verified_noop: None,
21554            duration_ms: 0,
21555            folded: true,
21556        }];
21557        state.released_to = Some("20260901-000000-new1".to_owned());
21558        state.released_branches = vec!["magi/x/A".to_owned()];
21559
21560        fold_run(&mut state, true, &home).await.expect("fold_run");
21561        state.status = RunStatus::Merged;
21562        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
21563        state.merge = Some(crate::run::MergeOutcome {
21564            mode: MergeMode::Pr,
21565            ok: true,
21566            detail: "confirmed merged".into(),
21567            empty: false,
21568        });
21569        fold_run(&mut state, true, &home)
21570            .await
21571            .expect("merged fold");
21572
21573        assert!(
21574            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21575            "the handed-over branch survives a fold"
21576        );
21577    }
21578
21579    /// A winner with nothing ahead of the base is caught before `gh` is ever
21580    /// asked for a pull request, and the message carries what the task's
21581    /// references resolved to.
21582    #[tokio::test]
21583    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
21584        let tmp = tempfile::tempdir().expect("tempdir");
21585        let repo = tmp.path().join("repo");
21586        std::fs::create_dir_all(&repo).unwrap();
21587        init_repo(&repo);
21588        let run = |args: &[&str]| {
21589            let out = std::process::Command::new("git")
21590                .quiet()
21591                .args(args)
21592                .current_dir(&repo)
21593                .output()
21594                .expect("spawn git");
21595            assert!(out.status.success(), "git {args:?}");
21596        };
21597        run(&["branch", "magi/x/A"]);
21598        run(&["checkout", "-q", "-b", "magi/x/B"]);
21599        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
21600        run(&["add", "-A"]);
21601        run(&["commit", "-q", "-m", "work"]);
21602        run(&["checkout", "-q", "main"]);
21603
21604        // A pull request is compared against the remote's base, so the
21605        // fixture needs one. Before it exists nothing can be read, and the
21606        // answer must be "not empty".
21607        let probe = RunState::new(
21608            repo.clone(),
21609            "main".to_owned(),
21610            "deadbeef".to_owned(),
21611            "task".to_owned(),
21612            Config::default(),
21613        );
21614        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
21615        let bare = tmp.path().join("origin.git");
21616        let out = std::process::Command::new("git")
21617            .quiet()
21618            .args(["init", "-q", "--bare"])
21619            .arg(&bare)
21620            .output()
21621            .expect("spawn git");
21622        assert!(out.status.success(), "git init --bare");
21623        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
21624        run(&["push", "-q", "origin", "main"]);
21625
21626        let mut state = RunState::new(
21627            repo.clone(),
21628            "main".to_owned(),
21629            "deadbeef".to_owned(),
21630            "task".to_owned(),
21631            Config::default(),
21632        );
21633        state.seeds = vec![refs::Seed {
21634            token: "magi/27b2/A".to_owned(),
21635            kind: refs::SeedKind::Unresolved,
21636            sha: String::new(),
21637            branch: true,
21638            detail: "no branch or commit named magi/27b2/A".to_owned(),
21639        }];
21640
21641        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
21642        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
21643        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
21644        let detail = empty_candidate_detail(&state, "main");
21645        assert!(detail.starts_with("empty candidate"), "{detail}");
21646        assert!(!detail.contains("magi/27b2/A"), "{detail}");
21647        assert!(detail.contains("--start-from"), "{detail}");
21648    }
21649
21650    /// `status == Ready` used to be read as "this is the harmless
21651    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
21652    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
21653    /// run's PR was closed without merging — and reentering `merge` with
21654    /// `mode` still `Pr` does not know the difference, so it pushed and
21655    /// opened a second pull request. `mode == Local` reproduces the same
21656    /// blind spot without a network call: reentry must not attempt another
21657    /// git merge once this node has already recorded an outcome.
21658    #[tokio::test]
21659    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
21660        let tmp = tempfile::tempdir().expect("tempdir");
21661        let repo = tmp.path().join("repo");
21662        std::fs::create_dir_all(&repo).unwrap();
21663        init_repo(&repo);
21664
21665        let mut config = Config::default();
21666        config.merge.mode = MergeMode::Local;
21667
21668        let mut state = RunState::new(
21669            repo.clone(),
21670            "main".to_owned(),
21671            "deadbeef".to_owned(),
21672            "task".to_owned(),
21673            config,
21674        );
21675        state.candidates = vec![Candidate {
21676            index: 0,
21677            label: 'A',
21678            agent: "alpha".to_owned(),
21679            branch: "does-not-exist".to_owned(),
21680            worktree: repo.clone(),
21681            summary: String::new(),
21682            stat: String::new(),
21683            files: 0,
21684            commits: 0,
21685            empty: false,
21686            failed: None,
21687            verified_noop: None,
21688            duration_ms: 0,
21689            folded: false,
21690        }];
21691        state.tally = Some(Tally {
21692            first_choice: BTreeMap::from([('A', 1)]),
21693            borda: BTreeMap::new(),
21694            winner: 'A',
21695            rankings: 1,
21696            unanimous_initial: true,
21697            deliberated: false,
21698            changed_votes: 0,
21699            unanimous_final: true,
21700            tie_break: None,
21701            judges: 0,
21702            present: 0,
21703            quorum: 0,
21704            met_quorum: true,
21705            uncontested: Some("only candidate A produced a change".to_owned()),
21706        });
21707        state.reviews = vec![ReviewRound {
21708            round: 1,
21709            head: "deadbeef".to_owned(),
21710            verified_head: None,
21711            verified_at: None,
21712            reviews: Vec::new(),
21713            e2e: Vec::new(),
21714            fix: None,
21715            blocking: 0,
21716            answered: 0,
21717            expected: 0,
21718            clean: true,
21719            verify_retried: false,
21720            e2e_deferred: false,
21721            e2e_defer_reason: None,
21722            progressed: false,
21723            vote_split: false,
21724            reconsideration: Vec::new(),
21725            verdict: None,
21726        }];
21727        state.gate = vec![CommandOutcome {
21728            command: "test".to_owned(),
21729            code: Some(0),
21730            output_tail: String::new(),
21731            duration_ms: 0,
21732            resource_blocked: false,
21733            ..Default::default()
21734        }];
21735        state.gate_ran = true;
21736        // Reached its conclusion already — e.g. `land` closing the PR without
21737        // merging it, which (like the honest `MergeMode::None` path) leaves
21738        // `status` at `Ready`. The recorded outcome is what actually marks
21739        // this node done.
21740        state.status = RunStatus::Ready;
21741        state.merge = Some(MergeOutcome {
21742            mode: MergeMode::Local,
21743            ok: false,
21744            detail: "already concluded".to_owned(),
21745            empty: false,
21746        });
21747
21748        let mut runner = Runner {
21749            state,
21750            roles: ResolvedRoles {
21751                implementers: Vec::new(),
21752                judges: Vec::new(),
21753                reviewers: Vec::new(),
21754                fixer: None,
21755                conductor: conductor(),
21756                implementer_roster: Vec::new(),
21757                judge_roster: Vec::new(),
21758                reviewer_roster: Vec::new(),
21759            },
21760            sem: Arc::new(Semaphore::new(1)),
21761            pause: Pause::new(),
21762            interrupt: Pause::new(),
21763        };
21764
21765        runner.merge().await.expect("merge");
21766
21767        assert_eq!(
21768            runner.state.status,
21769            RunStatus::Ready,
21770            "a concluded run's status must not change on reentry"
21771        );
21772        assert_eq!(
21773            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
21774            Some("already concluded"),
21775            "merge must not run again once the node already recorded an outcome"
21776        );
21777    }
21778
21779    /// `gate` leaves `state.gate_ran` false both before it has ever run and
21780    /// when its last attempt was resource-blocked (the shared build cache
21781    /// could not be acquired or confirmed fresh in time - see
21782    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
21783    /// `Vec` this also leaves behind used to read as "nothing failed" and let
21784    /// a run merge a tree the gate never actually checked - exactly the case
21785    /// a contended cache produces on every retry until it clears. `merge`
21786    /// must refuse until `gate` has actually recorded an attempt.
21787    #[tokio::test]
21788    async fn merge_refuses_a_gate_that_has_not_actually_run() {
21789        let tmp = tempfile::tempdir().expect("tempdir");
21790        let repo = tmp.path().join("repo");
21791        std::fs::create_dir_all(&repo).unwrap();
21792        init_repo(&repo);
21793
21794        let mut config = Config::default();
21795        config.merge.mode = MergeMode::Local;
21796
21797        let mut state = RunState::new(
21798            repo.clone(),
21799            "main".to_owned(),
21800            "deadbeef".to_owned(),
21801            "task".to_owned(),
21802            config,
21803        );
21804        state.candidates = vec![Candidate {
21805            index: 0,
21806            label: 'A',
21807            agent: "alpha".to_owned(),
21808            branch: "does-not-exist".to_owned(),
21809            worktree: repo.clone(),
21810            summary: String::new(),
21811            stat: String::new(),
21812            files: 0,
21813            commits: 0,
21814            empty: false,
21815            failed: None,
21816            verified_noop: None,
21817            duration_ms: 0,
21818            folded: false,
21819        }];
21820        state.tally = Some(Tally {
21821            first_choice: BTreeMap::from([('A', 1)]),
21822            borda: BTreeMap::new(),
21823            winner: 'A',
21824            rankings: 1,
21825            unanimous_initial: true,
21826            deliberated: false,
21827            changed_votes: 0,
21828            unanimous_final: true,
21829            tie_break: None,
21830            judges: 0,
21831            present: 0,
21832            quorum: 0,
21833            met_quorum: true,
21834            uncontested: Some("only candidate A produced a change".to_owned()),
21835        });
21836        state.reviews = vec![ReviewRound {
21837            round: 1,
21838            head: "deadbeef".to_owned(),
21839            verified_head: None,
21840            verified_at: None,
21841            reviews: Vec::new(),
21842            e2e: Vec::new(),
21843            fix: None,
21844            blocking: 0,
21845            answered: 0,
21846            expected: 0,
21847            clean: true,
21848            verify_retried: false,
21849            e2e_deferred: false,
21850            e2e_defer_reason: None,
21851            progressed: false,
21852            vote_split: false,
21853            reconsideration: Vec::new(),
21854            verdict: None,
21855        }];
21856        // The point: `gate` has not recorded anything yet.
21857        state.gate = Vec::new();
21858        state.gate_ran = false;
21859        state.status = RunStatus::Gating;
21860
21861        let mut runner = Runner {
21862            state,
21863            roles: ResolvedRoles {
21864                implementers: Vec::new(),
21865                judges: Vec::new(),
21866                reviewers: Vec::new(),
21867                fixer: None,
21868                conductor: conductor(),
21869                implementer_roster: Vec::new(),
21870                judge_roster: Vec::new(),
21871                reviewer_roster: Vec::new(),
21872            },
21873            sem: Arc::new(Semaphore::new(1)),
21874            pause: Pause::new(),
21875            interrupt: Pause::new(),
21876        };
21877
21878        runner.merge().await.expect("merge");
21879
21880        assert!(
21881            runner.state.merge.is_none(),
21882            "an empty gate must never be read as a passing one: {:?}",
21883            runner.state.merge
21884        );
21885    }
21886
21887    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
21888    /// commands configured and `merge.mode` is `none` (a review-only run).
21889    /// `gate` must still record a real attempt — zero commands, vacuously
21890    /// passed — rather than leaving `state.gate` empty in a way `merge`
21891    /// cannot tell apart from "never ran"; otherwise the run reaches
21892    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
21893    #[tokio::test]
21894    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
21895        let tmp = tempfile::tempdir().expect("tempdir");
21896        let repo = tmp.path().join("repo");
21897        std::fs::create_dir_all(&repo).unwrap();
21898        init_repo(&repo);
21899
21900        // Default config: `verify.gate` empty, `merge.mode` is `none`.
21901        let config = Config::default();
21902
21903        let mut state = RunState::new(
21904            repo.clone(),
21905            "main".to_owned(),
21906            "deadbeef".to_owned(),
21907            "task".to_owned(),
21908            config,
21909        );
21910        state.candidates = vec![Candidate {
21911            index: 0,
21912            label: 'A',
21913            agent: "alpha".to_owned(),
21914            branch: "does-not-exist".to_owned(),
21915            worktree: repo.clone(),
21916            summary: String::new(),
21917            stat: String::new(),
21918            files: 0,
21919            commits: 0,
21920            empty: false,
21921            failed: None,
21922            verified_noop: None,
21923            duration_ms: 0,
21924            folded: false,
21925        }];
21926        state.tally = Some(Tally {
21927            first_choice: BTreeMap::from([('A', 1)]),
21928            borda: BTreeMap::new(),
21929            winner: 'A',
21930            rankings: 1,
21931            unanimous_initial: true,
21932            deliberated: false,
21933            changed_votes: 0,
21934            unanimous_final: true,
21935            tie_break: None,
21936            judges: 0,
21937            present: 0,
21938            quorum: 0,
21939            met_quorum: true,
21940            uncontested: Some("only candidate A produced a change".to_owned()),
21941        });
21942        state.reviews = vec![ReviewRound {
21943            round: 1,
21944            head: "deadbeef".to_owned(),
21945            verified_head: None,
21946            verified_at: None,
21947            reviews: Vec::new(),
21948            e2e: Vec::new(),
21949            fix: None,
21950            blocking: 0,
21951            answered: 0,
21952            expected: 0,
21953            clean: true,
21954            verify_retried: false,
21955            e2e_deferred: false,
21956            e2e_defer_reason: None,
21957            progressed: false,
21958            vote_split: false,
21959            reconsideration: Vec::new(),
21960            verdict: None,
21961        }];
21962
21963        let mut runner = Runner {
21964            state,
21965            roles: ResolvedRoles {
21966                implementers: Vec::new(),
21967                judges: Vec::new(),
21968                reviewers: Vec::new(),
21969                fixer: None,
21970                conductor: conductor(),
21971                implementer_roster: Vec::new(),
21972                judge_roster: Vec::new(),
21973                reviewer_roster: Vec::new(),
21974            },
21975            sem: Arc::new(Semaphore::new(1)),
21976            pause: Pause::new(),
21977            interrupt: Pause::new(),
21978        };
21979
21980        runner.gate().await.expect("gate");
21981        assert!(
21982            runner.state.gate_ran,
21983            "zero configured commands is still a real attempt, not an unrun gate"
21984        );
21985        assert!(runner.state.gate.is_empty());
21986        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21987        assert_ne!(
21988            runner.state.status,
21989            RunStatus::Blocked,
21990            "a gate with nothing to check must not read as failed"
21991        );
21992
21993        runner.merge().await.expect("merge");
21994        assert_eq!(
21995            runner.state.status,
21996            RunStatus::Ready,
21997            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21998        );
21999    }
22000
22001    /// `Config::cache_dir` is derived from `verify.e2e` as well as
22002    /// `verify.gate` (so the e2e leg and the final gate never build against
22003    /// different directories). With zero `verify.gate` commands but a
22004    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
22005    /// that lease before discovering it had nothing to run - so a repo with
22006    /// no gate commands could come back `resource_blocked` (and therefore
22007    /// still `gate_ran == false`) on nothing but an unrelated run holding the
22008    /// cache, exactly the contention this run's own zero commands could
22009    /// never have touched. `gate` must recognise there is nothing to check
22010    /// before it ever asks for the lease.
22011    #[tokio::test]
22012    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
22013        crate::run::pin_test_home();
22014        let home = crate::run::home();
22015
22016        let tmp = tempfile::tempdir().expect("tempdir");
22017        let repo = tmp.path().join("repo");
22018        std::fs::create_dir_all(&repo).unwrap();
22019        init_repo(&repo);
22020        // Unique to this test, so holding its lease cannot collide with
22021        // another test sharing the same process-wide `home`.
22022        let cache_dir = tmp.path().join("target");
22023
22024        let mut config = Config::default();
22025        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
22026        // `verify.gate` stays empty (the default). Any accidental cache
22027        // acquisition must report contention immediately, regardless of how
22028        // long unrelated Git subprocesses take under parallel test load.
22029        config.graph.timeout_verify = Some(2);
22030        config.graph.timeout_resource_wait = 0;
22031
22032        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22033        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22034            .expect("no io error acquiring directly")
22035        {
22036            crate::cache::AcquireOutcome::Acquired(g) => g,
22037            crate::cache::AcquireOutcome::Busy(b) => {
22038                panic!("expected the direct acquire to win the lease first: {b:?}")
22039            }
22040        };
22041
22042        let mut state = RunState::new(
22043            repo.clone(),
22044            "main".to_owned(),
22045            "deadbeef".to_owned(),
22046            "task".to_owned(),
22047            config,
22048        );
22049        state.candidates = vec![Candidate {
22050            index: 0,
22051            label: 'A',
22052            agent: "alpha".to_owned(),
22053            branch: "does-not-exist".to_owned(),
22054            worktree: repo.clone(),
22055            summary: String::new(),
22056            stat: String::new(),
22057            files: 0,
22058            commits: 0,
22059            empty: false,
22060            failed: None,
22061            verified_noop: None,
22062            duration_ms: 0,
22063            folded: false,
22064        }];
22065        state.tally = Some(Tally {
22066            first_choice: BTreeMap::from([('A', 1)]),
22067            borda: BTreeMap::new(),
22068            winner: 'A',
22069            rankings: 1,
22070            unanimous_initial: true,
22071            deliberated: false,
22072            changed_votes: 0,
22073            unanimous_final: true,
22074            tie_break: None,
22075            judges: 0,
22076            present: 0,
22077            quorum: 0,
22078            met_quorum: true,
22079            uncontested: Some("only candidate A produced a change".to_owned()),
22080        });
22081        state.reviews = vec![ReviewRound {
22082            round: 1,
22083            head: "deadbeef".to_owned(),
22084            verified_head: None,
22085            verified_at: None,
22086            reviews: Vec::new(),
22087            e2e: Vec::new(),
22088            fix: None,
22089            blocking: 0,
22090            answered: 0,
22091            expected: 0,
22092            clean: true,
22093            verify_retried: false,
22094            e2e_deferred: false,
22095            e2e_defer_reason: None,
22096            progressed: false,
22097            vote_split: false,
22098            reconsideration: Vec::new(),
22099            verdict: None,
22100        }];
22101
22102        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22103        state.reviews[0].e2e = vec![CommandOutcome {
22104            command: state.config.verify.e2e[0].clone(),
22105            code: Some(0),
22106            output_tail: String::new(),
22107            duration_ms: 0,
22108            resource_blocked: false,
22109            ..Default::default()
22110        }];
22111        let mut runner = Runner {
22112            state,
22113            roles: ResolvedRoles {
22114                implementers: Vec::new(),
22115                judges: Vec::new(),
22116                reviewers: Vec::new(),
22117                fixer: None,
22118                conductor: conductor(),
22119                implementer_roster: Vec::new(),
22120                judge_roster: Vec::new(),
22121                reviewer_roster: Vec::new(),
22122            },
22123            sem: Arc::new(Semaphore::new(1)),
22124            pause: Pause::new(),
22125            interrupt: Pause::new(),
22126        };
22127
22128        runner.gate().await.expect("gate");
22129        assert!(runner.state.resource_block.is_none());
22130        assert!(
22131            !runner
22132                .state
22133                .events
22134                .iter()
22135                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22136            "a gate with nothing to run must never request the held cache lease"
22137        );
22138        assert!(
22139            runner.state.gate_ran,
22140            "zero commands is still a real, immediate attempt"
22141        );
22142        assert!(runner.state.gate.is_empty());
22143        assert_ne!(
22144            runner.state.status,
22145            RunStatus::Blocked,
22146            "must not read as resource-blocked on a lease it never asked for"
22147        );
22148    }
22149
22150    /// A separate process carries a live worker's environment throughout all
22151    /// verification entry points; the parallel harness never changes its env.
22152    #[cfg(unix)]
22153    #[tokio::test]
22154    async fn verification_is_standalone_inside_a_live_worker() {
22155        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22156        if std::env::var_os(CHILD).is_none() {
22157            let home = tempfile::tempdir().unwrap();
22158            let generation = crate::worker::pin_current(home.path()).unwrap();
22159            let output = std::process::Command::new(std::env::current_exe().unwrap())
22160                .args([
22161                    "--exact",
22162                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22163                    "--nocapture",
22164                ])
22165                .env(CHILD, "1")
22166                .env("MAGI_HOME", home.path())
22167                .env("MAGI_WORKER_HOME", home.path())
22168                .env("MAGI_WORKER_ID", "abcdef")
22169                .env("MAGI_WORKER_GENERATION", &generation.id)
22170                .env("MAGI_WORKER_EXE", &generation.executable)
22171                .env("MAGI_RUN", "verification-parent")
22172                .env("MAGI_NODE", "gate")
22173                .env("MAGI_SEAT", "worker-fixture")
22174                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22175                .env("MAGI_NO_AUTOUPDATE", "0")
22176                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22177                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22178                .env(
22179                    "VERIFY_EXPECT_TOOLCHAIN",
22180                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22181                )
22182                .env(
22183                    "VERIFY_EXPECT_CACHE",
22184                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22185                )
22186                .output()
22187                .unwrap();
22188            assert!(
22189                output.status.success()
22190                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22191                "{}\n{}",
22192                String::from_utf8_lossy(&output.stdout),
22193                String::from_utf8_lossy(&output.stderr)
22194            );
22195            return;
22196        }
22197        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22198        let home = crate::run::home();
22199        let directory = home.join("workers/jobs/abcdef");
22200        std::fs::create_dir_all(&directory).unwrap();
22201        let job = crate::worker::Job {
22202            id: "abcdef".into(),
22203            sequence: 1,
22204            kind: "task".into(),
22205            key: "task:verification".into(),
22206            payload: serde_json::json!({}),
22207            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22208            version: Some(env!("CARGO_PKG_VERSION").into()),
22209            status: crate::worker::Status::Running,
22210            result: None,
22211            pid: Some(std::process::id()),
22212            created_at: 0,
22213            finished_at: None,
22214        };
22215        std::fs::write(
22216            directory.join("job.json"),
22217            serde_json::to_vec(&job).unwrap(),
22218        )
22219        .unwrap();
22220        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22221        let assert_worker = || {
22222            assert_eq!(
22223                crate::worker::current_job(&home).unwrap().unwrap().id,
22224                job.id
22225            );
22226            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22227            assert_eq!(
22228                crate::worker::helper_executable(&home).unwrap(),
22229                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22230            );
22231            assert!(
22232                crate::updater::Checker::new(&crate::config::Update {
22233                    mode: crate::config::UpdateMode::Notify,
22234                    interval: None,
22235                    auto_restart: false,
22236                })
22237                .is_none(),
22238                "the driver remains pinned, even while tests are standalone"
22239            );
22240        };
22241        assert_worker();
22242        let repo = home.join("repo");
22243        std::fs::create_dir_all(&repo).unwrap();
22244        init_repo(&repo);
22245        // Keep storage, seat/control context, containment and tool lookup.
22246        // No inherited values (or credentials) are printed on success.
22247        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22248            test -z "${MAGI_WORKER_GENERATION+x}" &&
22249            test -z "${MAGI_WORKER_HOME+x}" &&
22250            test -z "${MAGI_WORKER_EXE+x}" &&
22251            test "$MAGI_HOME/repo" -ef . &&
22252            test "$MAGI_RUN" = verification-parent &&
22253            test "$MAGI_NODE" = gate &&
22254            test "$MAGI_SEAT" = worker-fixture &&
22255            test -n "$MAGI_PROCESS_OWNER" &&
22256            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22257            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22258            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22259            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22260        // Negative control: an ordinary child inherits the contamination.
22261        assert!(
22262            !std::process::Command::new("sh")
22263                .args(["-c", probe])
22264                .current_dir(&repo)
22265                .status()
22266                .unwrap()
22267                .success()
22268        );
22269        let unrelated_home = tempfile::tempdir().unwrap();
22270        assert!(
22271            crate::worker::current_job(unrelated_home.path()).is_err(),
22272            "an inherited worker id cannot be resolved in a unit fixture's home"
22273        );
22274        let mut runner = runner_at(RunStatus::Gating);
22275        runner.state.repo = repo.clone();
22276        runner.state.config.disk.min_free_bytes = 0;
22277        runner.state.config.coordination = crate::config::test_coordination();
22278        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
22279        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
22280        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
22281        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
22282        let winner = Candidate {
22283            index: 0,
22284            label: 'A',
22285            agent: "fixture".into(),
22286            branch: "main".into(),
22287            worktree: repo.clone(),
22288            summary: String::new(),
22289            stat: String::new(),
22290            files: 0,
22291            commits: 0,
22292            empty: false,
22293            failed: None,
22294            verified_noop: None,
22295            duration_ms: 0,
22296            folded: false,
22297        };
22298        let (e2e, retried, pids) = run_e2e_with_retry(
22299            &mut runner.state,
22300            &["sh".into(), "-c".into()],
22301            &[format!("{probe} && printf initial")],
22302            &repo,
22303            Duration::from_secs(10),
22304            "initial",
22305            None,
22306        )
22307        .await;
22308        assert!(!retried && pids.is_empty());
22309        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
22310        assert_eq!(e2e[0].output_tail, "initial");
22311        let gate = runner.run_gate(&winner).await.unwrap();
22312        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
22313        // An interrupted repair must recheck e2e from saved state. Landing
22314        // reuses that state and must run both pre-gate and gate again.
22315        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
22316            git::rev_parse(&repo, "HEAD").await.unwrap(),
22317            false,
22318            Vec::new(),
22319        ));
22320        runner.state.save().unwrap();
22321        let mut resumed = RunState::load(&runner.state.id).unwrap();
22322        let wait = crate::repo_lock::WaitPolicy::default();
22323        assert!(matches!(
22324            check_gate_repair_e2e(&mut resumed, &winner, &wait)
22325                .await
22326                .unwrap(),
22327            GateFix::Retry
22328        ));
22329        let saved = RunState::load(&resumed.id).unwrap();
22330        let repair = saved.gate_repair_e2e.unwrap();
22331        assert!(repair.passed);
22332        assert_eq!(repair.outcomes.len(), 1);
22333        assert!(repair.outcomes[0].ok());
22334        let landing = run_landing_gate(&mut resumed, &winner, &wait)
22335            .await
22336            .unwrap();
22337        assert_eq!(landing.len(), 1);
22338        assert!(landing[0].ok(), "{landing:?}");
22339        assert_eq!(
22340            std::fs::read_to_string(repo.join("phases")).unwrap(),
22341            "pre\ngate\ne2e\npre\ngate\n"
22342        );
22343        assert_worker();
22344    }
22345
22346    #[cfg(unix)]
22347    #[tokio::test]
22348    async fn verification_keeps_the_panic_and_the_full_output() {
22349        crate::run::pin_test_home();
22350        let tmp = tempfile::tempdir().unwrap();
22351        let mut config = Config::default();
22352        config.disk.min_free_bytes = 0;
22353        let mut state = RunState::new(
22354            tmp.path().to_owned(),
22355            "main".into(),
22356            "base".into(),
22357            "verification evidence".into(),
22358            config,
22359        );
22360        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
22361                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
22362                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
22363        let mut names = Vec::new();
22364        for _ in 0..2 {
22365            let (outcomes, _) = run_commands(
22366                &mut state,
22367                "gate",
22368                "gate",
22369                0,
22370                &["sh".into(), "-c".into()],
22371                &[script.into()],
22372                tmp.path(),
22373                Duration::from_secs(60),
22374            )
22375            .await;
22376            let tail = &outcomes[0].output_tail;
22377            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
22378            assert!(tail.contains("boom assertion"));
22379            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
22380            let line = tail.lines().next().unwrap();
22381            names.push(line.to_owned());
22382        }
22383        assert_ne!(names[0], names[1], "the second run must not overwrite");
22384        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
22385        assert!(full.len() > 500_000 && full.contains("boom assertion"));
22386        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
22387
22388        // Storage failures are evidence too; preserve the command's verdict.
22389        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
22390        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
22391        let (outcomes, _) = run_commands(
22392            &mut state,
22393            "gate",
22394            "gate",
22395            0,
22396            &["sh".into(), "-c".into()],
22397            &["echo failure-output; exit 7".into()],
22398            tmp.path(),
22399            Duration::from_secs(10),
22400        )
22401        .await;
22402        assert_eq!(outcomes[0].code, Some(7));
22403        assert!(state.events.iter().any(|e| {
22404            e.node == "gate" && e.message.contains("could not save the full gate output:")
22405        }));
22406    }
22407
22408    #[cfg(unix)]
22409    #[tokio::test]
22410    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
22411        crate::run::pin_test_home();
22412        let tmp = tempfile::tempdir().unwrap();
22413        let mut config = Config::default();
22414        config.disk.min_free_bytes = 0;
22415        let mut state = RunState::new(
22416            tmp.path().to_owned(),
22417            "main".into(),
22418            "base".into(),
22419            "verification evidence".into(),
22420            config,
22421        );
22422        let (outcomes, pids) = run_commands(
22423            &mut state,
22424            "gate",
22425            "gate",
22426            1,
22427            &["sh".into(), "-c".into()],
22428            &[
22429                "printf before-timeout; exec sleep 30".into(),
22430                "kill -TERM $$".into(),
22431                "exit 7".into(),
22432                "printf success".into(),
22433            ],
22434            tmp.path(),
22435            Duration::from_secs(1),
22436        )
22437        .await;
22438        wait_for_timed_out_children_to_die(&pids).await;
22439        assert_eq!(
22440            pids.len(),
22441            1,
22442            "unleased timeout retains its death-check PID"
22443        );
22444        assert_eq!(outcomes.len(), 4);
22445        assert_eq!(outcomes[0].code, None);
22446        assert!(outcomes[0].output_tail.contains("before-timeout"));
22447        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
22448        assert_eq!(outcomes[1].code, None);
22449        assert!(outcomes[1].output_tail.contains("command terminated:"));
22450        assert!(!outcomes[1].output_tail.contains("timed out"));
22451        assert_eq!(outcomes[2].code, Some(7));
22452        assert!(!outcomes[2].output_tail.contains("timed out"));
22453        assert_eq!(outcomes[3].code, Some(0));
22454        assert_eq!(outcomes[3].output_tail, "success");
22455        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
22456    }
22457
22458    /// The addendum's second gap: a `verify.gate` command running for real
22459    /// wall-clock time had nothing at all to show for it in `active` before
22460    /// `run_commands` learned to record it — a run could sit in `Gating` for
22461    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
22462    /// what was actually happening. Proven with a genuinely still-running
22463    /// command, not just a before/after check on the final state: a poller
22464    /// task reads the same `run.json` `gate()` is writing, the same way the
22465    /// phone or `magi show` would, while the shell command is still blocked
22466    /// on its own release marker.
22467    #[tokio::test]
22468    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
22469        crate::run::pin_test_home();
22470
22471        let tmp = tempfile::tempdir().expect("tempdir");
22472        let repo = tmp.path().join("repo");
22473        std::fs::create_dir_all(&repo).unwrap();
22474        init_repo(&repo);
22475
22476        let mut config = Config::default();
22477        config.disk.min_free_bytes = 0;
22478        config.verify.gate = vec![
22479            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
22480             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
22481                .to_owned(),
22482        ];
22483
22484        let mut state = RunState::new(
22485            repo.clone(),
22486            "main".to_owned(),
22487            "deadbeef".to_owned(),
22488            "task".to_owned(),
22489            config,
22490        );
22491        let run_id = state.id.clone();
22492        state.candidates = vec![Candidate {
22493            index: 0,
22494            label: 'A',
22495            agent: "alpha".to_owned(),
22496            branch: "does-not-exist".to_owned(),
22497            worktree: repo.clone(),
22498            summary: String::new(),
22499            stat: String::new(),
22500            files: 0,
22501            commits: 0,
22502            empty: false,
22503            failed: None,
22504            verified_noop: None,
22505            duration_ms: 0,
22506            folded: false,
22507        }];
22508        state.tally = Some(Tally {
22509            first_choice: BTreeMap::from([('A', 1)]),
22510            borda: BTreeMap::new(),
22511            winner: 'A',
22512            rankings: 1,
22513            unanimous_initial: true,
22514            deliberated: false,
22515            changed_votes: 0,
22516            unanimous_final: true,
22517            tie_break: None,
22518            judges: 0,
22519            present: 0,
22520            quorum: 0,
22521            met_quorum: true,
22522            uncontested: Some("only candidate A produced a change".to_owned()),
22523        });
22524        state.reviews = vec![ReviewRound {
22525            round: 1,
22526            head: "deadbeef".to_owned(),
22527            verified_head: None,
22528            verified_at: None,
22529            reviews: Vec::new(),
22530            e2e: Vec::new(),
22531            fix: None,
22532            blocking: 0,
22533            answered: 0,
22534            expected: 0,
22535            clean: true,
22536            verify_retried: false,
22537            e2e_deferred: false,
22538            e2e_defer_reason: None,
22539            progressed: false,
22540            vote_split: false,
22541            reconsideration: Vec::new(),
22542            verdict: None,
22543        }];
22544
22545        let mut runner = Runner {
22546            state,
22547            roles: ResolvedRoles {
22548                implementers: Vec::new(),
22549                judges: Vec::new(),
22550                reviewers: Vec::new(),
22551                fixer: None,
22552                conductor: conductor(),
22553                implementer_roster: Vec::new(),
22554                judge_roster: Vec::new(),
22555                reviewer_roster: Vec::new(),
22556            },
22557            sem: Arc::new(Semaphore::new(1)),
22558            pause: Pause::new(),
22559            interrupt: Pause::new(),
22560        };
22561
22562        let started_marker = repo.join("started.marker");
22563        let release_marker = repo.join("release.marker");
22564        let observe = async {
22565            loop {
22566                if started_marker.exists()
22567                    && let Ok(s) = crate::run::RunState::load(&run_id)
22568                    && let Some(a) = s.active.get("gate")
22569                {
22570                    std::fs::write(&release_marker, b"go").expect("release marker");
22571                    break a.clone();
22572                }
22573                tokio::time::sleep(Duration::from_millis(50)).await;
22574            }
22575        };
22576        let captured = {
22577            let gate = runner.gate();
22578            tokio::pin!(gate);
22579            let captured = tokio::select! {
22580                observed = observe => observed,
22581                result = &mut gate => panic!(
22582                    "gate exited before its in-flight entry was observed: {result:?}"
22583                ),
22584            };
22585            gate.await.expect("gate");
22586            captured
22587        };
22588
22589        assert_eq!(captured.task.as_deref(), Some("gate"));
22590        assert_eq!(captured.node, "gate");
22591        assert_eq!(captured.index, Some(1));
22592        assert_eq!(captured.total, Some(1));
22593        assert!(
22594            captured
22595                .command
22596                .as_deref()
22597                .is_some_and(|c| c.contains("started.marker")),
22598            "{captured:?}"
22599        );
22600
22601        assert!(
22602            runner.state.active.is_empty(),
22603            "the entry must be cleared once the command actually finished: {:?}",
22604            runner.state.active
22605        );
22606        assert!(runner.state.gate_ran);
22607        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
22608    }
22609
22610    /// The hand-off over a blocking finding a reviewer rejected on leaves a
22611    /// record for `land`; one with only a Minor, or no reject, leaves none.
22612    #[tokio::test]
22613    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
22614        use crate::verdict::{Finding, ReviewVote, Severity};
22615        crate::run::pin_test_home();
22616        let tmp = tempfile::tempdir().expect("tempdir");
22617        let repo = tmp.path().join("repo");
22618        std::fs::create_dir_all(&repo).unwrap();
22619        init_repo(&repo);
22620
22621        for (severity, vote, expect) in [
22622            (Severity::Major, ReviewVote::Reject, true),
22623            (Severity::Minor, ReviewVote::Reject, false),
22624            (Severity::Major, ReviewVote::Approve, false),
22625        ] {
22626            let mut round = review_round(false, 1, 1, 1, false, true);
22627            round.reviews = vec![ReviewRecord {
22628                reviewer: 1,
22629                agent: "alpha".to_owned(),
22630                summary: String::new(),
22631                findings: vec![Finding {
22632                    id: "R1-1-1".to_owned(),
22633                    severity,
22634                    file: None,
22635                    line: None,
22636                    title: "t".to_owned(),
22637                    detail: String::new(),
22638                }],
22639                vote: Some(vote),
22640                failed: None,
22641                duration_ms: 0,
22642                attempts: 0,
22643            }];
22644            let mut state = RunState::new(
22645                repo.clone(),
22646                "main".to_owned(),
22647                "deadbeef".to_owned(),
22648                "task".to_owned(),
22649                Config::default(),
22650            );
22651            state.reviews = vec![round];
22652            let mut runner = Runner {
22653                state,
22654                roles: ResolvedRoles {
22655                    implementers: Vec::new(),
22656                    judges: Vec::new(),
22657                    reviewers: Vec::new(),
22658                    fixer: None,
22659                    conductor: conductor(),
22660                    implementer_roster: Vec::new(),
22661                    judge_roster: Vec::new(),
22662                    reviewer_roster: Vec::new(),
22663                },
22664                sem: Arc::new(Semaphore::new(1)),
22665                pause: Pause::new(),
22666                interrupt: Pause::new(),
22667            };
22668            let shell = runner.state.config.shell();
22669            runner
22670                .stop_reviewing("round budget spent", &shell, &repo)
22671                .await
22672                .expect("stop_reviewing");
22673            assert_eq!(runner.state.status, RunStatus::Gating);
22674            assert_eq!(
22675                runner.state.contested_handoff.is_some(),
22676                expect,
22677                "{severity:?} + {vote:?}"
22678            );
22679        }
22680    }
22681
22682    /// The shape the incident this whole fix responds to actually had: the
22683    /// round budget spent, the last round's own e2e blocked on the shared
22684    /// build cache (held here by a live pid — this test process — exactly
22685    /// `cache`'s own unit tests' pattern for "another owner, still alive"
22686    /// without forking a process). `stop_reviewing` must retry it — not
22687    /// silently leave the round looking untouched (the catch-up-only half of
22688    /// the bug), and not read the contention as a red `e2e` and block the
22689    /// run on it (the other half). Called directly, the same way
22690    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
22691    /// above exercises `gate`, so this never needs a real cargo build to
22692    /// reach: the lease is never released, so `with_cache_lease` never gets
22693    /// past acquiring it into anything that would need a real workspace.
22694    #[tokio::test]
22695    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
22696        crate::run::pin_test_home();
22697        let home = crate::run::home();
22698
22699        let tmp = tempfile::tempdir().expect("tempdir");
22700        let repo = tmp.path().join("repo");
22701        std::fs::create_dir_all(&repo).unwrap();
22702        init_repo(&repo);
22703        let head = crate::git::rev_parse(&repo, "HEAD")
22704            .await
22705            .expect("rev-parse");
22706        // Unique to this test, so holding its lease cannot collide with
22707        // another test sharing the same process-wide `home`.
22708        let cache_dir = tmp.path().join("target");
22709
22710        let mut config = Config::default();
22711        config.verify.e2e = vec![format!(
22712            "CARGO_TARGET_DIR='{}' test -f README.md",
22713            cache_dir.display()
22714        )];
22715        config.graph.review_rounds = 1;
22716        // Bounded so a regression that does start waiting fails the test in
22717        // seconds, not hangs it.
22718        config.graph.timeout_verify = Some(2);
22719        config.graph.timeout_resource_wait = 2;
22720
22721        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22722        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22723            .expect("no io error acquiring directly")
22724        {
22725            crate::cache::AcquireOutcome::Acquired(g) => g,
22726            crate::cache::AcquireOutcome::Busy(b) => {
22727                panic!("expected the direct acquire to win the lease first: {b:?}")
22728            }
22729        };
22730
22731        let mut state = RunState::new(
22732            repo.clone(),
22733            "main".to_owned(),
22734            head.clone(),
22735            "task".to_owned(),
22736            config,
22737        );
22738        state.candidates = vec![Candidate {
22739            index: 0,
22740            label: 'A',
22741            agent: "alpha".to_owned(),
22742            branch: "does-not-exist".to_owned(),
22743            worktree: repo.clone(),
22744            summary: String::new(),
22745            stat: String::new(),
22746            files: 0,
22747            commits: 0,
22748            empty: false,
22749            failed: None,
22750            verified_noop: None,
22751            duration_ms: 0,
22752            folded: false,
22753        }];
22754        state.tally = Some(Tally {
22755            first_choice: BTreeMap::from([('A', 1)]),
22756            borda: BTreeMap::new(),
22757            winner: 'A',
22758            rankings: 1,
22759            unanimous_initial: true,
22760            deliberated: false,
22761            changed_votes: 0,
22762            unanimous_final: true,
22763            tie_break: None,
22764            judges: 0,
22765            present: 0,
22766            quorum: 0,
22767            met_quorum: true,
22768            uncontested: Some("only candidate A produced a change".to_owned()),
22769        });
22770        // The round budget's last round, deferred: `needs_catchup_run`'s
22771        // other trigger. `stop_reviewing`'s retry machinery must treat this
22772        // exactly like a resource-blocked attempt once it actually runs.
22773        state.reviews = vec![ReviewRound {
22774            round: 1,
22775            head: head.clone(),
22776            verified_head: None,
22777            verified_at: None,
22778            reviews: Vec::new(),
22779            e2e: Vec::new(),
22780            fix: None,
22781            blocking: 1,
22782            answered: 1,
22783            expected: 1,
22784            clean: false,
22785            verify_retried: false,
22786            e2e_deferred: true,
22787            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
22788            progressed: false,
22789            vote_split: false,
22790            reconsideration: Vec::new(),
22791            verdict: None,
22792        }];
22793
22794        let mut runner = Runner {
22795            state,
22796            roles: ResolvedRoles {
22797                implementers: Vec::new(),
22798                judges: Vec::new(),
22799                reviewers: Vec::new(),
22800                fixer: None,
22801                conductor: conductor(),
22802                implementer_roster: Vec::new(),
22803                judge_roster: Vec::new(),
22804                reviewer_roster: Vec::new(),
22805            },
22806            sem: Arc::new(Semaphore::new(1)),
22807            pause: Pause::new(),
22808            interrupt: Pause::new(),
22809        };
22810
22811        let shell = runner.state.config.shell();
22812        runner
22813            .stop_reviewing("round budget spent", &shell, &repo)
22814            .await
22815            .expect("stop_reviewing");
22816
22817        let last = runner.state.reviews.last().expect("round record");
22818        assert_eq!(
22819            last.e2e_status(),
22820            E2eStatus::ResourceBlocked,
22821            "the shared cache is still held; the attempt must read as blocked, not deferred or \
22822             failed: {last:?}"
22823        );
22824        assert_eq!(
22825            last.verified_head.as_deref(),
22826            Some(head.as_str()),
22827            "which commit this attempt targeted is known even though nothing finished checking \
22828             it"
22829        );
22830        let first_attempt_at = last
22831            .verified_at
22832            .expect("when this attempt ran is known too");
22833        assert_ne!(
22834            runner.state.status,
22835            RunStatus::Blocked,
22836            "contention is evidence about the machine, not the patch — it must not settle the \
22837             run as blocked: {:?}",
22838            runner.state.status
22839        );
22840        assert!(
22841            !runner
22842                .state
22843                .events
22844                .iter()
22845                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
22846            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
22847            runner.state.events
22848        );
22849
22850        // The cache is still held: a later reentry must retry the same
22851        // round's verification again — not leave it looking exactly as
22852        // untouched as the first blocked attempt, which is indistinguishable
22853        // from never having tried again at all.
22854        runner
22855            .stop_reviewing("round budget spent", &shell, &repo)
22856            .await
22857            .expect("stop_reviewing retry");
22858        assert_eq!(
22859            runner.state.reviews.len(),
22860            1,
22861            "no new round was started: {:?}",
22862            runner.state.reviews
22863        );
22864        let last = runner.state.reviews.last().expect("round record");
22865        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
22866        assert!(
22867            last.verified_at.expect("still known") > first_attempt_at,
22868            "a second reentry must be a fresh attempt, not a stale copy of the first"
22869        );
22870        assert_ne!(runner.state.status, RunStatus::Blocked);
22871
22872        held.release();
22873    }
22874
22875    #[cfg(unix)]
22876    #[tokio::test]
22877    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
22878        ask_test_home();
22879        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
22880            let tmp = tempfile::tempdir().unwrap();
22881            let repo = tmp.path().join("repo");
22882            std::fs::create_dir(&repo).unwrap();
22883            init_repo(&repo);
22884            let run_git = |args: &[&str]| {
22885                let out = std::process::Command::new("git")
22886                    .args(args)
22887                    .current_dir(&repo)
22888                    .output()
22889                    .unwrap();
22890                assert!(
22891                    out.status.success(),
22892                    "{args:?}: {}",
22893                    String::from_utf8_lossy(&out.stderr)
22894                );
22895            };
22896            let origin = tmp.path().join("origin.git");
22897            run_git(&["init", "--bare", origin.to_str().unwrap()]);
22898            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
22899            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
22900            run_git(&["add", "spec.rs"]);
22901            run_git(&["commit", "-m", "initial spec"]);
22902            run_git(&["push", "origin", "main"]);
22903            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
22904            run_git(&["checkout", "-b", "fix/review"]);
22905            std::fs::write(
22906                repo.join("check.rs"),
22907                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
22908            )
22909            .unwrap();
22910            run_git(&["add", "check.rs"]);
22911            run_git(&["commit", "-m", "use spec"]);
22912            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
22913            run_git(&["checkout", "main"]);
22914            std::fs::write(
22915                repo.join("spec.rs"),
22916                "struct AgentSpec { max_turn_secs: u64 }\n",
22917            )
22918            .unwrap();
22919            run_git(&["add", "spec.rs"]);
22920            run_git(&["commit", "-m", "extend spec"]);
22921            run_git(&["push", "origin", "main"]);
22922            run_git(&["checkout", "fix/review"]);
22923
22924            let mut runner = runner_at(RunStatus::Reviewing);
22925            runner.state.repo = repo.clone();
22926            runner.state.base_commit = base;
22927            runner.state.pr_head = Some("fix/review".into());
22928            runner.state.config.graph.review_rounds = max_rounds;
22929            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22930            runner.state.config.graph.sessions = false;
22931            runner.state.config.disk.min_free_bytes = 0;
22932            runner.state.config.verify.e2e =
22933                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22934            runner.state.candidates = vec![Candidate {
22935                index: 0,
22936                label: 'A',
22937                agent: "fixture".into(),
22938                branch: "fix/review".into(),
22939                worktree: repo.clone(),
22940                summary: String::new(),
22941                stat: String::new(),
22942                files: 1,
22943                commits: 1,
22944                empty: false,
22945                failed: None,
22946                verified_noop: None,
22947                duration_ms: 0,
22948                folded: false,
22949            }];
22950            runner.state.tally = Some(Tally {
22951                first_choice: BTreeMap::new(),
22952                borda: BTreeMap::new(),
22953                winner: 'A',
22954                rankings: 0,
22955                unanimous_initial: true,
22956                deliberated: false,
22957                changed_votes: 0,
22958                unanimous_final: true,
22959                tie_break: None,
22960                judges: 0,
22961                present: 0,
22962                quorum: 0,
22963                met_quorum: true,
22964                uncontested: Some("review-only".into()),
22965            });
22966            let mut last = review_round(false, 0, 1, 1, false, false);
22967            last.head = reviewed.clone();
22968            last.e2e_deferred = true;
22969            last.e2e[0].resource_blocked = true;
22970            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22971            if max_rounds == 1 {
22972                last.e2e.clear();
22973            }
22974            runner.state.reviews = vec![last];
22975            let calls = tmp.path().join("fix-calls");
22976            let mut fixer = spec("repair");
22977            fixer
22978                .env
22979                .insert("FIX_CALLS".into(), calls.display().to_string());
22980            fixer.command = vec!["sh".into(), "-c".into(), r#"
22981                echo fix >> "$FIX_CALLS"
22982                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22983                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22984                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22985                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22986            "#.into()];
22987            let mut reviewer = spec("reviewer");
22988            reviewer.command = vec![
22989                "sh".into(),
22990                "-c".into(),
22991                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22992                    .into(),
22993            ];
22994            runner.roles.fixer = Some(vec![fixer]);
22995            runner.roles.reviewers = vec![reviewer];
22996
22997            runner.sync_to_base().await.unwrap();
22998            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22999            assert_ne!(rebased, reviewed);
23000            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
23001            if reentry {
23002                // Simulate a crash after catch-up evidence was saved but before
23003                // dispatching the fixer. No dedicated pending-repair field exists.
23004                let shell = runner.state.config.shell();
23005                runner
23006                    .stop_unresolved_review("deferred verification", &shell, &repo)
23007                    .await
23008                    .unwrap();
23009                assert!(runner.catchup_repairable());
23010                assert!(!calls.exists());
23011                runner.state = RunState::load(&runner.state.id).unwrap();
23012                assert!(runner.catchup_repairable());
23013            }
23014            runner.review_loop().await.unwrap();
23015            let first = &runner.state.reviews[0];
23016            assert_eq!(first.head, reviewed);
23017            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
23018            assert!(
23019                first.verify_retried,
23020                "a reproduced build failure gets exactly one retry: {:?}",
23021                first.e2e
23022            );
23023            assert!(first.e2e[0].output_tail.contains("E0063"));
23024            assert!(!runner.catchup_repairable());
23025            if max_rounds == 2 {
23026                assert_eq!(
23027                    runner.state.status,
23028                    RunStatus::Gating,
23029                    "{}",
23030                    crate::report::run(&runner.state)
23031                );
23032                assert_eq!(runner.state.reviews.len(), 2);
23033                assert!(first.fix.as_ref().unwrap().committed);
23034                assert!(runner.state.reviews[1].clean);
23035                assert_eq!(
23036                    runner
23037                        .state
23038                        .reviews
23039                        .iter()
23040                        .filter(|r| r.fix.is_some())
23041                        .count(),
23042                    1
23043                );
23044                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
23045                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
23046            } else {
23047                assert_eq!(runner.state.status, RunStatus::Blocked);
23048                assert!(first.fix.is_none());
23049                assert!(!calls.exists());
23050                let recovery = crate::recovery::assess(
23051                    "prior",
23052                    Some(&runner.state),
23053                    &runner.landing_base(),
23054                    crate::recovery::Relation::Diverged,
23055                );
23056                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
23057                let reasons = recovery.reasons.join("\n");
23058                assert!(
23059                    reasons.contains(&reviewed) && reasons.contains(&rebased),
23060                    "{reasons}"
23061                );
23062                assert!(
23063                    reasons.contains("base sync to")
23064                        && reasons.contains("additional review is required"),
23065                    "{reasons}"
23066                );
23067            }
23068        }
23069    }
23070
23071    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23072    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23073    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23074    /// own top-of-function fast path (`review_conclusion`) correctly reads
23075    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23076    /// own `for` range is empty once the round budget is spent, so
23077    /// `review_loop` must retry the check itself rather than silently doing
23078    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23079    /// above exercises directly, but through `review_loop`'s own entry point
23080    /// this time, proving the wiring between the two rather than just the
23081    /// retry logic in isolation.
23082    #[tokio::test]
23083    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23084        crate::run::pin_test_home();
23085        let home = crate::run::home();
23086
23087        let tmp = tempfile::tempdir().expect("tempdir");
23088        let repo = tmp.path().join("repo");
23089        std::fs::create_dir_all(&repo).unwrap();
23090        init_repo(&repo);
23091        let head = crate::git::rev_parse(&repo, "HEAD")
23092            .await
23093            .expect("rev-parse");
23094        let cache_dir = tmp.path().join("target");
23095
23096        let mut config = Config::default();
23097        config.verify.e2e = vec![format!(
23098            "CARGO_TARGET_DIR='{}' test -f README.md",
23099            cache_dir.display()
23100        )];
23101        config.graph.review_rounds = 1;
23102        config.graph.timeout_verify = Some(2);
23103        config.graph.timeout_resource_wait = 2;
23104
23105        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23106        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23107            .expect("no io error acquiring directly")
23108        {
23109            crate::cache::AcquireOutcome::Acquired(g) => g,
23110            crate::cache::AcquireOutcome::Busy(b) => {
23111                panic!("expected the direct acquire to win the lease first: {b:?}")
23112            }
23113        };
23114
23115        let mut state = RunState::new(
23116            repo.clone(),
23117            "main".to_owned(),
23118            head.clone(),
23119            "task".to_owned(),
23120            config,
23121        );
23122        state.candidates = vec![Candidate {
23123            index: 0,
23124            label: 'A',
23125            agent: "alpha".to_owned(),
23126            branch: "does-not-exist".to_owned(),
23127            worktree: repo.clone(),
23128            summary: String::new(),
23129            stat: String::new(),
23130            files: 0,
23131            commits: 0,
23132            empty: false,
23133            failed: None,
23134            verified_noop: None,
23135            duration_ms: 0,
23136            folded: false,
23137        }];
23138        state.tally = Some(Tally {
23139            first_choice: BTreeMap::from([('A', 1)]),
23140            borda: BTreeMap::new(),
23141            winner: 'A',
23142            rankings: 1,
23143            unanimous_initial: true,
23144            deliberated: false,
23145            changed_votes: 0,
23146            unanimous_final: true,
23147            tie_break: None,
23148            judges: 0,
23149            present: 0,
23150            quorum: 0,
23151            met_quorum: true,
23152            uncontested: Some("only candidate A produced a change".to_owned()),
23153        });
23154        // The exact shape a prior process's `stop_reviewing` would have left
23155        // on disk: the round budget's last round, a real attempt already
23156        // made and already resource-blocked.
23157        state.reviews = vec![ReviewRound {
23158            round: 1,
23159            head: head.clone(),
23160            verified_head: Some(head.clone()),
23161            verified_at: Some(jiff::Timestamp::now()),
23162            reviews: Vec::new(),
23163            e2e: vec![CommandOutcome {
23164                command: format!(
23165                    "CARGO_TARGET_DIR='{}' test -f README.md",
23166                    cache_dir.display()
23167                ),
23168                code: None,
23169                output_tail: "waiting for the shared build cache".to_owned(),
23170                duration_ms: 0,
23171                resource_blocked: true,
23172                ..Default::default()
23173            }],
23174            fix: None,
23175            blocking: 1,
23176            answered: 1,
23177            expected: 1,
23178            clean: false,
23179            verify_retried: false,
23180            e2e_deferred: false,
23181            e2e_defer_reason: None,
23182            progressed: false,
23183            vote_split: false,
23184            reconsideration: Vec::new(),
23185            verdict: None,
23186        }];
23187
23188        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23189        let mut runner = Runner {
23190            state,
23191            roles: ResolvedRoles {
23192                implementers: Vec::new(),
23193                judges: Vec::new(),
23194                reviewers: Vec::new(),
23195                fixer: None,
23196                conductor: conductor(),
23197                implementer_roster: Vec::new(),
23198                judge_roster: Vec::new(),
23199                reviewer_roster: Vec::new(),
23200            },
23201            sem: Arc::new(Semaphore::new(1)),
23202            pause: Pause::new(),
23203            interrupt: Pause::new(),
23204        };
23205
23206        // The lease is still held throughout, so this reentry's own retry is
23207        // also contended — proving `review_loop` actually tried again (not
23208        // that it happened to succeed) is what the timestamp comparison
23209        // below is for.
23210        runner.review_loop().await.expect("review_loop");
23211
23212        assert_eq!(
23213            runner.state.reviews.len(),
23214            1,
23215            "no new round was started on top of the unresolved one: {:?}",
23216            runner.state.reviews
23217        );
23218        let last = &runner.state.reviews[0];
23219        assert_eq!(
23220            last.e2e_status(),
23221            E2eStatus::ResourceBlocked,
23222            "still contended: {last:?}"
23223        );
23224        assert!(
23225            last.verified_at.expect("still known") > first_attempt_at,
23226            "review_loop must have actually retried the check, not left it exactly as found"
23227        );
23228        assert_ne!(
23229            runner.state.status,
23230            RunStatus::Blocked,
23231            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
23232            runner.state.status
23233        );
23234
23235        held.release();
23236    }
23237
23238    #[tokio::test]
23239    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
23240        crate::run::pin_test_home();
23241        for status in [RunStatus::Blocked, RunStatus::Gating] {
23242            let mut runner = runner_at(status);
23243            runner.state.config.graph.land = true;
23244            runner.state.gate_ran = true;
23245            runner.state.merge = Some(MergeOutcome {
23246                mode: MergeMode::Pr,
23247                ok: false,
23248                detail: "the fixer produced no commit".into(),
23249                empty: false,
23250            });
23251            let url = "https://example.invalid/o/r/pull/1";
23252            runner.state.pr = Some(crate::run::PrRecord {
23253                url: url.into(),
23254                number: 1,
23255                state: "open".into(),
23256                checks: "red".into(),
23257                round: 1,
23258                rounds: 1,
23259                red_at_merge: Vec::new(),
23260            });
23261            runner.state.save().unwrap();
23262            // The nonexistent repository makes observation fail before a forge
23263            // command can run. We still must reach land, rather than silently
23264            // return from the graph with its old gate and merge records.
23265            runner.execute_graph().await.unwrap();
23266            assert_eq!(runner.state.status, RunStatus::Blocked);
23267            assert!(runner.state.land_sync_pending);
23268            assert!(runner.state.events.iter().any(|event|
23269                event.node == "land" && event.message == format!("watching {url}")));
23270            assert_eq!(
23271                runner.state.merge.as_ref().unwrap().detail,
23272                "the fixer produced no commit"
23273            );
23274        }
23275    }
23276
23277    #[tokio::test]
23278    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
23279        crate::run::pin_test_home();
23280        let tmp = tempfile::tempdir().expect("tempdir");
23281        let repo = tmp.path().join("repo");
23282        std::fs::create_dir_all(&repo).unwrap();
23283        init_repo(&repo);
23284
23285        let mut config = Config::default();
23286        config.merge.mode = MergeMode::Pr;
23287        config.graph.land = true;
23288        config.graph.land_approval = false;
23289
23290        let mut state = RunState::new(
23291            repo.clone(),
23292            "main".to_owned(),
23293            "deadbeef".to_owned(),
23294            "task".to_owned(),
23295            config,
23296        );
23297        state.candidates = vec![Candidate {
23298            index: 0,
23299            label: 'A',
23300            agent: "alpha".to_owned(),
23301            branch: "does-not-exist".to_owned(),
23302            worktree: repo.clone(),
23303            summary: String::new(),
23304            stat: String::new(),
23305            files: 0,
23306            commits: 0,
23307            empty: false,
23308            failed: None,
23309            verified_noop: None,
23310            duration_ms: 0,
23311            folded: false,
23312        }];
23313        state.tally = Some(Tally {
23314            first_choice: BTreeMap::from([('A', 1)]),
23315            borda: BTreeMap::new(),
23316            winner: 'A',
23317            rankings: 1,
23318            unanimous_initial: true,
23319            deliberated: false,
23320            changed_votes: 0,
23321            unanimous_final: true,
23322            tie_break: None,
23323            judges: 0,
23324            present: 0,
23325            quorum: 0,
23326            met_quorum: true,
23327            uncontested: Some("only candidate A produced a change".to_owned()),
23328        });
23329        state.reviews = vec![ReviewRound {
23330            round: 1,
23331            head: "deadbeef".to_owned(),
23332            verified_head: None,
23333            verified_at: None,
23334            reviews: Vec::new(),
23335            e2e: Vec::new(),
23336            fix: None,
23337            blocking: 0,
23338            answered: 0,
23339            expected: 0,
23340            clean: true,
23341            verify_retried: false,
23342            e2e_deferred: false,
23343            e2e_defer_reason: None,
23344            progressed: false,
23345            vote_split: false,
23346            reconsideration: Vec::new(),
23347            verdict: None,
23348        }];
23349        state.gate = vec![CommandOutcome {
23350            command: "test".to_owned(),
23351            code: Some(0),
23352            output_tail: String::new(),
23353            duration_ms: 0,
23354            resource_blocked: false,
23355            ..Default::default()
23356        }];
23357        state.gate_ran = true;
23358        // A first pass through `merge` already pushed and opened this pull
23359        // request; `status` is `Landing` because a previous call into `land`
23360        // parked or was interrupted before it reached a terminal outcome.
23361        state.status = RunStatus::Landing;
23362        state.merge = Some(MergeOutcome {
23363            mode: MergeMode::Pr,
23364            ok: true,
23365            detail: "https://example.invalid/x/y/pull/1".to_owned(),
23366            empty: false,
23367        });
23368
23369        // The Landing-resume shortcut calls `run_land` directly rather than
23370        // through `merge`, which is exactly the call site that used to skip
23371        // `settle_questions` - see the fixture below.
23372        ask_test_home();
23373        // A real resume loads a persisted run; driver ownership is checked
23374        // against that record before the Landing shortcut is entered.
23375        state.save().expect("save landing run");
23376        let store = ask::Questions::open();
23377        let q = ask_open_question(&store, &state.id);
23378
23379        let mut runner = Runner {
23380            state,
23381            roles: ResolvedRoles {
23382                implementers: Vec::new(),
23383                judges: Vec::new(),
23384                reviewers: Vec::new(),
23385                fixer: None,
23386                conductor: conductor(),
23387                implementer_roster: Vec::new(),
23388                judge_roster: Vec::new(),
23389                reviewer_roster: Vec::new(),
23390            },
23391            sem: Arc::new(Semaphore::new(1)),
23392            pause: Pause::new(),
23393            interrupt: Pause::new(),
23394        };
23395
23396        // `execute`, not `merge` directly: the Landing-resume shortcut lives
23397        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
23398        // exactly because `review_loop` would otherwise clobber the marker
23399        // first.
23400        runner.execute().await.expect("execute");
23401
23402        assert_eq!(
23403            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
23404            Some("https://example.invalid/x/y/pull/1"),
23405            "reentry must not push again or open a second pull request over the \
23406             one `land` is already watching"
23407        );
23408        assert_ne!(
23409            runner.state.status,
23410            RunStatus::Landing,
23411            "land could not actually reach the fake pull request, so it must \
23412             have given up rather than left the run silently parked forever"
23413        );
23414        // `land` could not reach the fake pull request, so it gave up into
23415        // `Blocked` - still resumable, so the question must not have been
23416        // swept just because this branch now also calls `settle_questions`.
23417        assert_eq!(runner.state.status, RunStatus::Blocked);
23418        assert!(
23419            store.get(&q.id).unwrap().status.open(),
23420            "Blocked is still alive; settle_questions must have been a no-op here"
23421        );
23422    }
23423
23424    fn state_with_round(round: ReviewRound) -> RunState {
23425        let mut s = RunState::new(
23426            PathBuf::from("/repo"),
23427            "main".to_owned(),
23428            "abc1234".to_owned(),
23429            "add retries".to_owned(),
23430            Config::default(),
23431        );
23432        s.reviews = vec![round];
23433        s
23434    }
23435
23436    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
23437        crate::verdict::Finding {
23438            id: id.to_owned(),
23439            severity,
23440            file: None,
23441            line: None,
23442            title: title.to_owned(),
23443            detail: String::new(),
23444        }
23445    }
23446
23447    #[test]
23448    fn pr_body_names_open_findings_and_declined_ones() {
23449        let round = ReviewRound {
23450            round: 2,
23451            head: "deadbee".to_owned(),
23452            verified_head: None,
23453            verified_at: None,
23454            reviews: vec![ReviewRecord {
23455                attempts: 0,
23456                reviewer: 1,
23457                agent: "alpha".to_owned(),
23458                summary: String::new(),
23459                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
23460                vote: None,
23461                failed: None,
23462                duration_ms: 0,
23463            }],
23464            e2e: vec![CommandOutcome {
23465                command: "cargo test".to_owned(),
23466                code: Some(0),
23467                output_tail: String::new(),
23468                duration_ms: 0,
23469                resource_blocked: false,
23470                ..Default::default()
23471            }],
23472            verify_retried: false,
23473            e2e_deferred: false,
23474            e2e_defer_reason: None,
23475            fix: Some(FixRecord {
23476                agent: "alpha".to_owned(),
23477                addressed: Vec::new(),
23478                rejected: vec![crate::verdict::Rejection {
23479                    id: "R1-1-1".to_owned(),
23480                    why: "not reachable from any caller".to_owned(),
23481                }],
23482                notes: String::new(),
23483                committed: true,
23484                failed: None,
23485                duration_ms: 0,
23486                continuation: None,
23487            }),
23488            blocking: 0,
23489            answered: 1,
23490            expected: 1,
23491            clean: false,
23492            progressed: true,
23493            vote_split: false,
23494            reconsideration: Vec::new(),
23495            verdict: None,
23496        };
23497        let state = state_with_round(round);
23498        let body = pr_message(&state, 'A').body;
23499
23500        assert!(body.contains("add retries"), "the task must still be there");
23501        assert!(body.contains("R2-1-1"), "{body}");
23502        assert!(!body.contains("unused import"), "{body}");
23503        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
23504        assert!(
23505            !body.contains("not reachable from any caller"),
23506            "the reason it was declined: {body}"
23507        );
23508    }
23509
23510    #[test]
23511    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
23512        let round = ReviewRound {
23513            round: 1,
23514            head: "deadbee".to_owned(),
23515            verified_head: None,
23516            verified_at: None,
23517            reviews: vec![ReviewRecord {
23518                attempts: 0,
23519                reviewer: 1,
23520                agent: "alpha".to_owned(),
23521                summary: String::new(),
23522                findings: Vec::new(),
23523                vote: None,
23524                failed: None,
23525                duration_ms: 0,
23526            }],
23527            e2e: Vec::new(),
23528            verify_retried: false,
23529            e2e_deferred: false,
23530            e2e_defer_reason: None,
23531            fix: None,
23532            blocking: 0,
23533            answered: 1,
23534            expected: 1,
23535            clean: true,
23536            progressed: false,
23537            vote_split: false,
23538            reconsideration: Vec::new(),
23539            verdict: None,
23540        };
23541        let state = state_with_round(round);
23542        let body = pr_message(&state, 'A').body;
23543        assert!(!body.contains("Open review findings"), "{body}");
23544        assert!(!body.contains("Declined"), "{body}");
23545    }
23546
23547    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
23548        let mut state = RunState::new(
23549            PathBuf::from("/repo"),
23550            "main".to_owned(),
23551            "abc1234".to_owned(),
23552            instruction.to_owned(),
23553            Config::default(),
23554        );
23555        // These fixtures test execution flow, independent of host disk capacity.
23556        state.config.disk.min_free_bytes = 0;
23557        state.candidates.push(Candidate {
23558            index: 0,
23559            label: 'A',
23560            agent: "alpha".to_owned(),
23561            branch: "magi/x/A".to_owned(),
23562            worktree: PathBuf::from("/wt"),
23563            summary: summary.to_owned(),
23564            stat: String::new(),
23565            files: 1,
23566            commits: 1,
23567            empty: false,
23568            failed: None,
23569            verified_noop: None,
23570            folded: false,
23571            duration_ms: 0,
23572        });
23573        state
23574    }
23575
23576    fn review_state(subjects: &[&str]) -> RunState {
23577        let mut state = state_with_summary(
23578            "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",
23579            "",
23580        );
23581        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
23582        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
23583        state
23584    }
23585
23586    /// A branch rebased onto a main that moved past the recorded
23587    /// `base_commit` is titled from its own first commit, never main's.
23588    #[tokio::test]
23589    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
23590        ask_test_home();
23591        let tmp = tempfile::tempdir().unwrap();
23592        let repo = tmp.path().join("repo");
23593        std::fs::create_dir_all(&repo).unwrap();
23594        init_repo(&repo);
23595        let origin = tmp.path().join("origin.git");
23596        let g = |dir: &Path, args: &[&str]| {
23597            let out = std::process::Command::new("git")
23598                .args(args)
23599                .current_dir(dir)
23600                .quiet()
23601                .output()
23602                .expect("spawn git");
23603            assert!(
23604                out.status.success(),
23605                "git {args:?}: {}",
23606                String::from_utf8_lossy(&out.stderr)
23607            );
23608        };
23609        g(
23610            tmp.path(),
23611            &[
23612                "clone",
23613                "--bare",
23614                "-q",
23615                repo.to_str().unwrap(),
23616                origin.to_str().unwrap(),
23617            ],
23618        );
23619        g(
23620            &repo,
23621            &["remote", "add", "origin", origin.to_str().unwrap()],
23622        );
23623        let c1 = git::rev_parse(&repo, "main").await.unwrap();
23624
23625        // Main moves on; the branch is built on top of the new main.
23626        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
23627        g(&repo, &["add", "-A"]);
23628        g(
23629            &repo,
23630            &["commit", "-q", "-m", "chore(deps): update a crate"],
23631        );
23632        g(&repo, &["push", "-q", "origin", "main"]);
23633        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
23634        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23635        g(&repo, &["add", "-A"]);
23636        g(
23637            &repo,
23638            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
23639        );
23640        g(&repo, &["checkout", "-q", "main"]);
23641
23642        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
23643        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
23644        // Without a readable tracking ref the recorded base's merge base is used.
23645        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
23646        assert_eq!(fallback, c1);
23647
23648        let mut state = review_state(&[
23649            "chore(deps): update a crate",
23650            "fix(daemon): apply a chosen action",
23651        ]);
23652        state.repo = repo.clone();
23653        state.base_branch = "main".to_owned();
23654        state.base_commit = c1;
23655        refresh_reviewed_commits(&mut state, "feat/own").await;
23656        assert_eq!(
23657            state.reviewed_commits,
23658            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
23659        );
23660        assert_eq!(
23661            review_title(&state).as_deref(),
23662            Some("fix(daemon): apply a chosen action")
23663        );
23664        assert_eq!(
23665            leaked_subjects(&state, "feat/own").await,
23666            Some(vec!["chore(deps): update a crate".to_owned()])
23667        );
23668        // A stale tracking ref is still used when the fetch fails, but the
23669        // leak list is withheld.
23670        state.config.merge.remote = "nowhere".to_owned();
23671        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
23672    }
23673
23674    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
23675    /// with `origin/main` one commit behind it, and a summarizing agent that
23676    /// prints whatever `reply` holds.
23677    struct SummaryFixture {
23678        _tmp: tempfile::TempDir,
23679        repo: PathBuf,
23680        reply: PathBuf,
23681        runner: Runner,
23682    }
23683
23684    fn summary_fixture() -> SummaryFixture {
23685        ask_test_home();
23686        let tmp = tempfile::tempdir().unwrap();
23687        let repo = tmp.path().join("repo");
23688        std::fs::create_dir_all(&repo).unwrap();
23689        init_repo(&repo);
23690        let origin = tmp.path().join("origin.git");
23691        let g = |args: &[&str]| {
23692            let out = std::process::Command::new("git")
23693                .args(args)
23694                .current_dir(&repo)
23695                .quiet()
23696                .output()
23697                .expect("spawn git");
23698            assert!(
23699                out.status.success(),
23700                "git {args:?}: {}",
23701                String::from_utf8_lossy(&out.stderr)
23702            );
23703        };
23704        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
23705        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
23706        g(&["push", "-q", "origin", "main"]);
23707        g(&["checkout", "-q", "-b", "feat/own"]);
23708        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23709        g(&["add", "-A"]);
23710        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
23711        let reply = tmp.path().join("reply.txt");
23712        std::fs::write(
23713            &reply,
23714            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
23715        )
23716        .unwrap();
23717        let mut runner = runner_at(RunStatus::Gating);
23718        let mut state = review_state(&["feat(own): add the own file"]);
23719        state.repo = repo.clone();
23720        state.base_branch = "main".to_owned();
23721        state.candidates[0].branch = "feat/own".to_owned();
23722        state.candidates[0].worktree = repo.clone();
23723        let mut author = spec("alpha");
23724        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
23725        author
23726            .env
23727            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
23728        state.config.agents = vec![author];
23729        runner.state = state;
23730        SummaryFixture {
23731            _tmp: tmp,
23732            repo,
23733            reply,
23734            runner,
23735        }
23736    }
23737
23738    async fn posted(f: &mut SummaryFixture) -> PrMessage {
23739        let winner = f.runner.state.candidates[0].clone();
23740        f.runner
23741            .guarded_pr_message(&winner, None, true)
23742            .await
23743            .unwrap()
23744            .expect("an English description never parks")
23745    }
23746
23747    fn clean_round_with_minor_findings() -> ReviewRound {
23748        let mut round = passing_round(2, None);
23749        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
23750        round.reviews = vec![ReviewRecord {
23751            attempts: 0,
23752            reviewer: 1,
23753            agent: "alpha".into(),
23754            summary: "内部レビュー".into(),
23755            findings: vec![
23756                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
23757                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
23758            ],
23759            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
23760            failed: None,
23761            duration_ms: 0,
23762        }];
23763        round
23764    }
23765
23766    #[tokio::test]
23767    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
23768        for review_only in [false, true] {
23769            let mut f = summary_fixture();
23770            if !review_only {
23771                f.runner.state.candidates[0].agent = "alpha".into();
23772            }
23773            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
23774            assert!(f.runner.state.reviews[0].clean);
23775            assert!(f.runner.state.reviews[0].fix.is_none());
23776            assert!(f.runner.state.open_findings().is_empty());
23777            assert_eq!(
23778                crate::pr_outcome::required_finding_ids(&f.runner.state),
23779                ["R2-1-1", "R2-1-2"]
23780            );
23781            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23782            let evidence = crate::pr_outcome::summary_evidence(
23783                &f.runner.state,
23784                crate::pr_outcome::FinalHead::At(&head),
23785            );
23786            assert!(
23787                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
23788            );
23789            // The ordinary reply omits both IDs: no cached description is adopted.
23790            let omitted = posted(&mut f).await;
23791            assert!(omitted.body.contains("No description"));
23792            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
23793            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
23794            assert!(f.runner.state.change_summary.is_none());
23795            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();
23796            let described = posted(&mut f).await;
23797            assert!(described.body.contains("improve documentation for callers"));
23798            assert!(described.body.contains("remaining edge case"));
23799            assert!(described.body.contains("## Open review findings"));
23800            assert!(!described.body.contains("未修正"));
23801        }
23802    }
23803
23804    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
23805        let mut f = summary_fixture();
23806        if !review_only {
23807            f.runner.state.candidates[0].agent = "alpha".into();
23808        }
23809        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23810        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
23811        fixed
23812            .fix
23813            .as_mut()
23814            .unwrap()
23815            .rejected
23816            .push(crate::verdict::Rejection {
23817                id: "R1-1-1".into(),
23818                why: "呼び出されないコードのため辞退".into(),
23819            });
23820        let mut clean = clean_round_with_minor_findings();
23821        clean.verified_head = Some(head.clone());
23822        f.runner.state.reviews = vec![fixed, clean];
23823        ok_gate(&mut f.runner.state, Some(&head));
23824        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
23825        f.runner.state.config.agents.push(scripted("beta", reply));
23826        f.runner.state.config.roles.language_judge =
23827            Some(crate::config::AgentChoice::One("beta".into()));
23828        f
23829    }
23830
23831    #[tokio::test]
23832    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
23833        for review_only in [false, true] {
23834            let mut f = rewrite_fixture_with_findings(review_only,
23835                "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;
23836            let m = posted(&mut f).await;
23837            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23838            let expected =
23839                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
23840            assert!(m.body.contains(&expected));
23841            assert!(m.body.contains("## Review rounds"));
23842            assert!(
23843                m.body
23844                    .contains("Gate (`verify.gate`): passed on the final commit")
23845            );
23846            assert!(
23847                m.body
23848                    .contains("Tests (`verify.e2e`): passed on the final commit")
23849            );
23850            let c = f.runner.state.change_summary.as_ref().unwrap();
23851            assert!(
23852                m.body
23853                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
23854            );
23855            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23856            assert!(crate::pr_outcome::covers_required_findings(
23857                &f.runner.state,
23858                &m.body
23859            ));
23860            assert!(m.body.contains("documentation remains incomplete"));
23861            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
23862            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
23863            assert!(f.runner.state.github_text.is_none());
23864        }
23865    }
23866
23867    #[tokio::test]
23868    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
23869        for review_only in [false, true] {
23870            for reply in [
23871                "TITLE: fix: public description\nA short English description.",
23872                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
23873            ] {
23874                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
23875                let winner = f.runner.state.candidates[0].clone();
23876                let posted = f
23877                    .runner
23878                    .guarded_pr_message(&winner, None, true)
23879                    .await
23880                    .unwrap();
23881                assert!(posted.is_none());
23882                assert!(f.runner.state.parked);
23883                let withheld = f.runner.state.github_text.as_ref().unwrap();
23884                assert!(
23885                    withheld.rewrite.is_none(),
23886                    "an incomplete rewrite must not be selectable"
23887                );
23888                let q = ask::Questions::open()
23889                    .get(withheld.question.as_ref().unwrap())
23890                    .unwrap();
23891                assert!(
23892                    !q.choices
23893                        .contains(&crate::github_text::USE_REWRITE.to_owned())
23894                );
23895                assert!(
23896                    q.detail.contains("R1-1-1")
23897                        && q.detail.contains("R2-1-1")
23898                        && q.detail.contains("R2-1-2")
23899                );
23900            }
23901        }
23902    }
23903
23904    #[tokio::test]
23905    async fn japanese_reports_stay_local_in_both_public_run_modes() {
23906        for review_only in [false, true] {
23907            let mut f = summary_fixture();
23908            if !review_only {
23909                f.runner.state.candidates[0].agent = "alpha".into();
23910            }
23911            f.runner.state.instruction = "内部タスクの説明".into();
23912            f.runner.state.candidates[0].summary = "内部の候補報告".into();
23913            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23914            f.runner.state.reviews = vec![
23915                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
23916                round_with_notes(2, Some("二回目の内部修正報告です。")),
23917                passing_round(3, Some(&head)),
23918            ];
23919            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
23920            ok_gate(&mut f.runner.state, Some(&head));
23921            let captured = f.repo.join("public-prompt.txt");
23922            let author = &mut f.runner.state.config.agents[0];
23923            author.command = vec![
23924                "sh".into(),
23925                "-c".into(),
23926                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23927            ];
23928            author.env.insert(
23929                "PROMPT_FILE".into(),
23930                captured.to_string_lossy().into_owned(),
23931            );
23932            let m = posted(&mut f).await;
23933            assert!(m.body.contains("Adds `own.txt`"));
23934            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23935            assert!(m.body.contains("R1-1-1"));
23936            assert!(
23937                m.body
23938                    .contains("Gate (`verify.gate`): passed on the final commit")
23939            );
23940            assert!(
23941                m.body
23942                    .contains("Tests (`verify.e2e`): passed on the final commit")
23943            );
23944            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23945            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23946            let prompt = std::fs::read_to_string(captured).unwrap();
23947            assert!(prompt.contains(&format!(
23948                "git diff {} {head}",
23949                f.runner.state.change_summary.as_ref().unwrap().base
23950            )));
23951            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23952            assert_eq!(
23953                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23954                "二回目の内部修正報告です。"
23955            );
23956        }
23957    }
23958
23959    #[tokio::test]
23960    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23961        for review_only in [false, true] {
23962            let mut f = summary_fixture();
23963            if !review_only {
23964                f.runner.state.candidates[0].agent = "alpha".into();
23965            }
23966            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23967            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23968            std::fs::write(&f.reply, "no usable description").unwrap();
23969            let failed = posted(&mut f).await;
23970            assert!(
23971                failed
23972                    .body
23973                    .contains("No description of what this change does could be generated")
23974            );
23975            assert!(failed.body.is_ascii());
23976            assert!(f.runner.state.github_text.is_none());
23977            assert!(f.runner.state.change_summary.is_none());
23978            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23979            let evidence = crate::pr_outcome::summary_evidence(
23980                &f.runner.state,
23981                crate::pr_outcome::FinalHead::At(&head),
23982            );
23983            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23984            assert!(
23985                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23986                    .exists()
23987            );
23988            f.runner.state =
23989                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23990            std::fs::write(
23991                &f.reply,
23992                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23993            )
23994            .unwrap();
23995            let retried = posted(&mut f).await;
23996            assert!(retried.body.contains("Adds the committed own file."));
23997            assert_eq!(
23998                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23999                "日本語の修正報告"
24000            );
24001        }
24002    }
24003
24004    #[tokio::test]
24005    async fn same_head_verification_and_findings_invalidate_public_prose() {
24006        let mut f = summary_fixture();
24007        posted(&mut f).await;
24008        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24009        let original = f
24010            .runner
24011            .state
24012            .change_summary
24013            .as_ref()
24014            .unwrap()
24015            .evidence
24016            .clone();
24017        ok_gate(&mut f.runner.state, Some(&head));
24018        std::fs::write(
24019            &f.reply,
24020            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
24021        )
24022        .unwrap();
24023        let verified = posted(&mut f).await;
24024        assert!(verified.body.contains("now verified"));
24025        assert_ne!(
24026            f.runner.state.change_summary.as_ref().unwrap().evidence,
24027            original
24028        );
24029        let mut round = round_with_notes(1, Some("内部報告"));
24030        round.reviews.push(ReviewRecord {
24031            attempts: 0,
24032            reviewer: 1,
24033            agent: "alpha".into(),
24034            summary: "内部レビュー".into(),
24035            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
24036            vote: None,
24037            failed: None,
24038            duration_ms: 0,
24039        });
24040        round
24041            .fix
24042            .as_mut()
24043            .unwrap()
24044            .rejected
24045            .push(crate::verdict::Rejection {
24046                id: "R1-1-1".into(),
24047                why: "呼び出し元から到達できない".into(),
24048            });
24049        f.runner.state.reviews = vec![round];
24050        // A description omitting the required ID is unusable, even with a title.
24051        let omitted = posted(&mut f).await;
24052        assert!(omitted.body.contains("No description"));
24053        assert!(omitted.body.contains("R1-1-1"));
24054        assert!(!omitted.body.contains("到達"));
24055        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();
24056        let described = posted(&mut f).await;
24057        assert!(described.body.contains("unreachable from callers"));
24058        assert!(described.body.contains("R1-1-1"));
24059        assert!(!described.body.contains("到達"));
24060        let evidence = f
24061            .runner
24062            .state
24063            .change_summary
24064            .as_ref()
24065            .unwrap()
24066            .evidence
24067            .clone();
24068        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24069        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24070        assert!(posted(&mut f).await.body.contains("rationale updated"));
24071        assert_ne!(
24072            f.runner.state.change_summary.as_ref().unwrap().evidence,
24073            evidence
24074        );
24075        // Old serialized summaries have no evidence fingerprint and must regenerate.
24076        f.runner
24077            .state
24078            .change_summary
24079            .as_mut()
24080            .unwrap()
24081            .evidence
24082            .clear();
24083        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24084        assert!(posted(&mut f).await.body.contains("current specification"));
24085    }
24086
24087    #[tokio::test]
24088    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24089        let mut f = summary_fixture();
24090        let m = posted(&mut f).await;
24091        assert_eq!(m.title, "feat(own): add the own file");
24092        assert!(
24093            m.body
24094                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24095            "{}",
24096            m.body
24097        );
24098        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24099        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24100        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24101        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24102        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24103        let kept = f.runner.state.change_summary.as_ref().unwrap();
24104        assert_eq!(
24105            (kept.head.as_str(), kept.base.as_str()),
24106            (head.as_str(), base.as_str())
24107        );
24108        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24109    }
24110
24111    #[tokio::test]
24112    async fn review_only_summary_receives_the_configured_github_language() {
24113        let mut f = summary_fixture();
24114        f.runner.state.config.graph.github_language = "ja".into();
24115        let captured = f.repo.join("summary-prompt.txt");
24116        let author = &mut f.runner.state.config.agents[0];
24117        author.command = vec![
24118            "sh".into(),
24119            "-c".into(),
24120            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24121        ];
24122        author.env.insert(
24123            "PROMPT_FILE".into(),
24124            captured.to_string_lossy().into_owned(),
24125        );
24126        std::fs::write(
24127            &f.reply,
24128            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24129        )
24130        .unwrap();
24131        let m = posted(&mut f).await;
24132        let prompt = std::fs::read_to_string(captured).unwrap();
24133        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24134        assert!(!prompt.contains("in English"));
24135        assert_eq!(m.title, "feat(own): ファイルを追加");
24136        assert!(m.body.contains("own.txt を追加します。"));
24137    }
24138
24139    #[tokio::test]
24140    async fn review_fixes_come_after_the_whole_change_summary() {
24141        let mut f = summary_fixture();
24142        f.runner.state.reviews = vec![
24143            round_with_notes(1, Some("handled the PATH case")),
24144            round_with_notes(2, None),
24145        ];
24146        let m = posted(&mut f).await;
24147        let summary = m.body.find("## Summary").expect("summary");
24148        let fixes = m.body.find("## Review rounds").expect("review rounds");
24149        assert!(summary < fixes, "{}", m.body);
24150        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24151        assert!(m.body.contains("## Final verification"), "{}", m.body);
24152    }
24153
24154    #[tokio::test]
24155    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24156        let mut f = summary_fixture();
24157        let first = posted(&mut f).await;
24158        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24159        // The same head reuses the record: a different reply is not read.
24160        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24161        let again = posted(&mut f).await;
24162        assert_eq!((again.title, again.body), (first.title, first.body));
24163
24164        let g = |args: &[&str]| {
24165            let out = std::process::Command::new("git")
24166                .args(args)
24167                .current_dir(&f.repo)
24168                .quiet()
24169                .output()
24170                .expect("spawn git");
24171            assert!(out.status.success(), "git {args:?}");
24172        };
24173        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24174        g(&["add", "-A"]);
24175        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24176        let second = posted(&mut f).await;
24177        let kept = f.runner.state.change_summary.clone().unwrap();
24178        assert_ne!(kept.head, first_head);
24179        assert!(second.body.contains("Not read yet."), "{}", second.body);
24180        assert!(!second.body.contains("so the first summary is read"));
24181        assert_eq!(second.title, "feat(own): other");
24182    }
24183
24184    #[tokio::test]
24185    async fn an_unavailable_summary_is_stated_and_never_invented() {
24186        let mut f = summary_fixture();
24187        std::fs::write(&f.reply, "no title line here").unwrap();
24188        let m = posted(&mut f).await;
24189        assert!(
24190            m.body
24191                .contains("No description of what this change does could be generated"),
24192            "{}",
24193            m.body
24194        );
24195        assert!(m.body.contains("internal reports remain in local records"));
24196        assert!(f.runner.state.change_summary.is_none());
24197        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24198        // A preview asks nobody and claims nothing.
24199        let winner = f.runner.state.candidates[0].clone();
24200        let preview = f
24201            .runner
24202            .guarded_pr_message(&winner, None, false)
24203            .await
24204            .unwrap()
24205            .unwrap();
24206        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24207    }
24208
24209    #[test]
24210    fn pr_message_review_single_commit_uses_its_subject() {
24211        let state = review_state(&["feat(nats): per-role user"]);
24212        let m = pr_message(&state, 'A');
24213        assert_eq!(m.title, "feat(nats): per-role user");
24214        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24215        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24216    }
24217
24218    #[test]
24219    fn pr_message_review_multi_commit_takes_the_oldest() {
24220        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24221        let m = pr_message(&state, 'A');
24222        assert_eq!(m.title, "feat: the change");
24223        for s in ["feat: the change", "fix: typo", "fix: again"] {
24224            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24225        }
24226    }
24227
24228    #[test]
24229    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
24230        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
24231            let mut state = review_state(&[first, "fix: later fixup"]);
24232            state.candidates[0].branch = "機能/ログイン".to_owned();
24233            let m = pr_message(&state, 'A');
24234            assert!(
24235                m.title.starts_with("chore: land candidate A of run"),
24236                "{}",
24237                m.title
24238            );
24239        }
24240    }
24241
24242    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
24243        BranchFacts {
24244            commits: commits
24245                .iter()
24246                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
24247                .collect(),
24248            stat: stat.to_owned(),
24249        }
24250    }
24251
24252    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
24253        let mut r = review_round(true, 0, 1, 1, true, true);
24254        r.round = round;
24255        r.fix = notes.map(|n| FixRecord {
24256            agent: "fixer".to_owned(),
24257            addressed: Vec::new(),
24258            rejected: Vec::new(),
24259            notes: n.to_owned(),
24260            committed: true,
24261            failed: None,
24262            duration_ms: 0,
24263            continuation: None,
24264        });
24265        r
24266    }
24267
24268    #[test]
24269    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
24270        let state = review_state(&["ignored"]);
24271        let f = facts(
24272            &[
24273                (
24274                    "fix(login): resolve PATH on macOS",
24275                    "Login shells skip rc files.",
24276                ),
24277                ("fix: address review", ""),
24278            ],
24279            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
24280        );
24281        let m = pr_message_with(&state, 'A', Some(&f));
24282        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
24283        assert!(
24284            m.body
24285                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
24286            "{}",
24287            m.body
24288        );
24289        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
24290        assert!(m.body.contains("## Diff stat"), "{}", m.body);
24291        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
24292        for banned in [
24293            "Review the work already",
24294            "no task statement",
24295            "Original task",
24296        ] {
24297            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
24298        }
24299        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
24300    }
24301
24302    #[test]
24303    fn pr_message_review_truncates_a_huge_first_commit_body() {
24304        let state = review_state(&["ignored"]);
24305        let f = facts(
24306            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
24307            "s",
24308        );
24309        let m = pr_message_with(&state, 'A', Some(&f));
24310        assert!(m.body.len() < 30_000, "{}", m.body.len());
24311        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
24312        assert!(
24313            m.body.contains("- ... 1 more commit(s)"),
24314            "{}",
24315            m.body.len()
24316        );
24317        assert!(m.body.ends_with("magi:candidate-a\n"));
24318    }
24319
24320    #[test]
24321    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
24322        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
24323        assert_eq!(m.title, "feat: x");
24324        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
24325        assert!(!m.body.contains("Diff stat"), "{}", m.body);
24326        assert!(!m.body.contains("no task statement"), "{}", m.body);
24327    }
24328
24329    #[test]
24330    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
24331        let mut state = review_state(&["日本語の件名"]);
24332        state.candidates[0].branch = "fix/macos-login-path".to_owned();
24333        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
24334        state.candidates[0].branch = "機能/ログイン".to_owned();
24335        assert!(
24336            pr_message(&state, 'A')
24337                .title
24338                .starts_with("chore: land candidate A")
24339        );
24340    }
24341
24342    #[test]
24343    fn pr_message_review_fixes_survive_a_clean_final_round() {
24344        let mut state = review_state(&["feat: x"]);
24345        state.reviews = vec![
24346            round_with_notes(1, Some("handled the PATH case")),
24347            round_with_notes(2, None),
24348        ];
24349        let body = pr_message(&state, 'A').body;
24350        assert!(
24351            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
24352            "{body}"
24353        );
24354        assert!(body.contains("### Round 1"), "{body}");
24355
24356        state.reviews = vec![
24357            round_with_notes(1, Some("first fix")),
24358            round_with_notes(2, Some("")),
24359            round_with_notes(3, Some("second fix")),
24360            round_with_notes(4, None),
24361        ];
24362        let body = pr_message(&state, 'A').body;
24363        assert!(
24364            body.contains("### Round 1") && !body.contains("first fix"),
24365            "{body}"
24366        );
24367        assert!(
24368            body.contains("### Round 3") && !body.contains("second fix"),
24369            "{body}"
24370        );
24371        assert!(body.contains("### Round 2"), "{body}");
24372    }
24373
24374    const FINAL: &str = "abcdef1234567890";
24375
24376    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
24377        let mut r = round_with_notes(round, None);
24378        r.verified_head = verified.map(str::to_owned);
24379        r
24380    }
24381
24382    fn ok_gate(state: &mut RunState, head: Option<&str>) {
24383        state.gate = vec![CommandOutcome {
24384            command: "gate".to_owned(),
24385            code: Some(0),
24386            output_tail: String::new(),
24387            duration_ms: 0,
24388            resource_blocked: false,
24389            ..Default::default()
24390        }];
24391        state.gate_ran = true;
24392        state.gate_head = head.map(str::to_owned);
24393    }
24394
24395    fn body_at(state: &RunState) -> String {
24396        pr_message_raw(
24397            state,
24398            'A',
24399            None,
24400            crate::pr_outcome::FinalHead::At(FINAL),
24401            ChangeNote::NotAsked,
24402        )
24403        .body
24404    }
24405
24406    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
24407
24408    #[test]
24409    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
24410        let mut state = review_state(&["feat: x"]);
24411        state.reviews = vec![
24412            round_with_notes(1, Some(SANDBOXED)),
24413            passing_round(2, Some(FINAL)),
24414        ];
24415        ok_gate(&mut state, Some(FINAL));
24416        let body = body_at(&state);
24417        assert!(!body.contains("Handled the PATH case."), "{body}");
24418        assert!(!body.contains("could not commit"), "{body}");
24419        assert!(!body.contains("could not run"), "{body}");
24420        assert!(
24421            body.contains("The fix is committed on the branch"),
24422            "{body}"
24423        );
24424        assert!(!body.contains("sandbox"), "{body}");
24425        assert!(
24426            body.contains("Tests (`verify.e2e`): passed on the final commit"),
24427            "{body}"
24428        );
24429        assert!(
24430            body.contains("Gate (`verify.gate`): passed on the final commit"),
24431            "{body}"
24432        );
24433        // The raw report is untouched in the record.
24434        assert!(
24435            state.reviews[0]
24436                .fix
24437                .as_ref()
24438                .unwrap()
24439                .notes
24440                .contains("could not commit")
24441        );
24442    }
24443
24444    #[test]
24445    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
24446        let mut state = review_state(&["feat: x"]);
24447        let mut r1 = round_with_notes(1, Some(SANDBOXED));
24448        r1.fix.as_mut().unwrap().committed = false;
24449        let mut r2 = passing_round(2, Some(FINAL));
24450        r2.e2e[0].code = Some(1);
24451        state.reviews = vec![r1, r2];
24452        let body = body_at(&state);
24453        assert!(!body.contains("could not commit"), "{body}");
24454        assert!(!body.contains("could not run"), "{body}");
24455        assert!(body.contains("This round produced no commit"), "{body}");
24456        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
24457        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
24458        assert!(!body.contains("passed"), "{body}");
24459    }
24460
24461    #[test]
24462    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
24463        let mut state = review_state(&["feat: x"]);
24464        state.reviews = vec![
24465            round_with_notes(1, Some(SANDBOXED)),
24466            passing_round(2, Some("0123456789abcdef")),
24467        ];
24468        ok_gate(&mut state, Some("0123456789abcdef"));
24469        let body = body_at(&state);
24470        assert!(!body.contains("HTTP tests could not run"), "{body}");
24471        // The commit claim is still settled by the structured record.
24472        assert!(!body.contains("could not commit"), "{body}");
24473        assert!(
24474            body.contains("passed on an earlier commit (`0123456`)"),
24475            "{body}"
24476        );
24477        assert!(!body.contains("passed on the final commit"), "{body}");
24478
24479        // A gate recorded before `gate_head` existed is "not recorded".
24480        ok_gate(&mut state, None);
24481        let body = body_at(&state);
24482        assert!(
24483            body.contains("passed on a commit that was not recorded"),
24484            "{body}"
24485        );
24486    }
24487
24488    #[test]
24489    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
24490        let state = state_with_summary(
24491            "add retries to the client",
24492            "TITLE: feat: retries\n\nDid it.",
24493        );
24494        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
24495        assert_eq!(m.title, "feat: retries");
24496        assert!(
24497            m.body.contains("<summary>Original task</summary>"),
24498            "{}",
24499            m.body
24500        );
24501        assert!(!m.body.contains("Commits under review"), "{}", m.body);
24502        assert!(
24503            m.body
24504                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
24505            "{}",
24506            m.body
24507        );
24508    }
24509
24510    #[test]
24511    fn pr_message_review_bounds_a_long_english_subject() {
24512        let long = format!("feat: {}", "word ".repeat(100));
24513        let m = pr_message(&review_state(&[&long]), 'A');
24514        assert!(m.title.starts_with("feat: word"), "{}", m.title);
24515        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24516    }
24517
24518    #[test]
24519    fn pr_message_implementation_run_is_unchanged_by_review_support() {
24520        let state = state_with_summary("add retries\n\ndetails", "- did some things");
24521        let m = pr_message(&state, 'A');
24522        assert_eq!(m.title, "add retries");
24523        assert!(m.body.contains("<summary>Original task</summary>"));
24524        assert!(!m.body.contains("Commits under review"));
24525        assert_eq!(landing_subject_source(&state), state.instruction);
24526    }
24527
24528    #[test]
24529    fn review_run_squash_subject_is_the_change_not_the_prompt() {
24530        let state = review_state(&["feat: the change", "fix: typo"]);
24531        let source = landing_subject_source(&state);
24532        assert_eq!(land::merge_subject("", &source), "feat: the change");
24533        assert_eq!(
24534            land::merge_subject("magi: candidate A (uncommitted work)", &source),
24535            "feat: the change"
24536        );
24537        // An operator's rename still wins.
24538        assert_eq!(
24539            land::merge_subject("feat: renamed by hand", &source),
24540            "feat: renamed by hand"
24541        );
24542        let blank = review_state(&["日本語"]);
24543        assert!(
24544            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
24545        );
24546    }
24547
24548    #[test]
24549    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
24550        let state = review_state(&["feat: the change"]);
24551        let source = landing_subject_source(&state);
24552        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
24553        assert_eq!(
24554            land::merge_subject(landing_title(&state, old), &source),
24555            "feat: the change"
24556        );
24557        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
24558        let task = state_with_summary("add retries", "");
24559        assert_eq!(landing_title(&task, old), old);
24560    }
24561
24562    #[test]
24563    fn pr_message_describes_the_change_not_the_task() {
24564        let state = state_with_summary(
24565            "今回やってほしいこと: results projector を直す",
24566            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
24567        );
24568        let m = pr_message(&state, 'A');
24569        assert_eq!(m.title, "fix(web): batch the runs list reads");
24570        assert!(
24571            m.body.starts_with("## Summary\n\n- reads run.json once"),
24572            "{}",
24573            m.body
24574        );
24575        assert!(!m.body.contains("TITLE:"), "{}", m.body);
24576        let task_at = m.body.find("今回やってほしいこと").unwrap();
24577        let details_at = m.body.find("<details>").unwrap();
24578        assert!(
24579            details_at < task_at,
24580            "the task lives inside <details>: {}",
24581            m.body
24582        );
24583        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
24584        assert!(m.body.contains("magi:candidate-a"));
24585    }
24586
24587    #[test]
24588    fn pr_message_falls_back_to_the_task_without_a_title_line() {
24589        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
24590        let m = pr_message(&state, 'A');
24591        assert_eq!(m.title, "add retries");
24592        assert!(
24593            m.body.contains("## Summary\n\n- did some things"),
24594            "{}",
24595            m.body
24596        );
24597
24598        let none = RunState::new(
24599            PathBuf::from("/repo"),
24600            "main".to_owned(),
24601            "abc1234".to_owned(),
24602            "add retries".to_owned(),
24603            Config::default(),
24604        );
24605        let m = pr_message(&none, 'A');
24606        assert_eq!(m.title, "add retries");
24607        assert!(!m.body.contains("## Summary"), "{}", m.body);
24608    }
24609
24610    #[test]
24611    fn pr_message_refuses_the_candidate_commit_subject() {
24612        for bad in [
24613            "TITLE: magi: candidate A (uncommitted work)",
24614            "TITLE: chore: stuff (uncommitted work)",
24615            "TITLE:   ",
24616        ] {
24617            let state = state_with_summary("add retries", bad);
24618            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
24619        }
24620    }
24621
24622    #[test]
24623    fn pr_message_bounds_a_very_long_task_and_title() {
24624        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
24625        let state = state_with_summary(&long, "- nothing");
24626        let m = pr_message(&state, 'A');
24627        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24628        assert!(!m.title.contains('\n'));
24629
24630        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
24631        let m = pr_message(&state, 'A');
24632        assert!(m.title.starts_with("feat: "));
24633        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24634        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
24635    }
24636
24637    fn long_title_of(instruction: &str) -> String {
24638        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
24639    }
24640
24641    #[test]
24642    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
24643        let first = "Make the landing path keep a readable title for long tasks";
24644        let line = format!(
24645            "{first}. {}",
24646            "And then keep going with more words ".repeat(20)
24647        );
24648        let t = long_title_of(&line);
24649        assert_eq!(t, first);
24650        assert!(!t.starts_with("chore: land"));
24651    }
24652
24653    #[test]
24654    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
24655        let line = "word ".repeat(200);
24656        let t = long_title_of(&line);
24657        assert!(t.ends_with("word..."), "{t}");
24658        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
24659    }
24660
24661    #[test]
24662    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
24663        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
24664            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
24665        }
24666    }
24667
24668    #[test]
24669    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
24670        let mut state = state_with_summary("再試行を追加する", "- nothing");
24671        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
24672        state.config.graph.github_language = "ja".into();
24673        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
24674    }
24675
24676    #[test]
24677    fn pr_message_title_limit_is_exact() {
24678        let at = "a".repeat(PR_TITLE_MAX);
24679        assert_eq!(long_title_of(&at), at);
24680        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
24681        assert!(over.ends_with("..."), "{over}");
24682        assert_eq!(over.chars().count(), PR_TITLE_MAX);
24683    }
24684
24685    #[test]
24686    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
24687        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
24688        let t = long_title_of(&line);
24689        assert!(t.ends_with("..."), "{t}");
24690        assert!(t.is_ascii(), "{t}");
24691    }
24692
24693    #[test]
24694    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
24695        let line = format!(
24696            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
24697            "plus more filler words ".repeat(20)
24698        );
24699        let t = long_title_of(&line);
24700        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
24701    }
24702
24703    #[test]
24704    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
24705        let line = format!("\n\n# {}", "title words ".repeat(40));
24706        let state = state_with_summary(&line, "- nothing");
24707        let m = pr_message(&state, 'A');
24708        assert!(m.title.starts_with("title words"), "{}", m.title);
24709        assert_eq!(
24710            land::merge_subject(&m.title, &landing_subject_source(&state)),
24711            m.title
24712        );
24713        // An operator's rename wins untouched.
24714        assert_eq!(
24715            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
24716            "feat: renamed by hand"
24717        );
24718    }
24719
24720    #[tokio::test]
24721    async fn github_text_rewrite_is_bounded_and_falls_back() {
24722        crate::run::pin_test_home();
24723        for (reply, accepted) in [
24724            (
24725                "TITLE: fix: retries\nAdd retries for failed requests.",
24726                true,
24727            ),
24728            (
24729                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
24730                false,
24731            ),
24732            (
24733                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
24734                true,
24735            ),
24736            (
24737                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
24738                true,
24739            ),
24740            (
24741                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
24742                true,
24743            ),
24744            (
24745                "TITLE: fix: retries\n日本語の説明です。 token=secret",
24746                false,
24747            ),
24748            ("TITLE: fix: retries\n", false),
24749        ] {
24750            let dir = tempfile::tempdir().unwrap();
24751            let mut runner = runner_at(RunStatus::Gating);
24752            runner.state = state_with_summary(
24753                "add retries",
24754                "TITLE: fix: retries\n日本語の説明を書きます。",
24755            );
24756            runner.state.repo = dir.path().to_owned();
24757            runner.state.candidates[0].worktree = dir.path().to_owned();
24758            let mut author = spec("alpha");
24759            author.command = vec![
24760                "sh".into(),
24761                "-c".into(),
24762                "printf '%s' \"$REWRITE_REPLY\"".into(),
24763            ];
24764            author.env.insert("REWRITE_REPLY".into(), reply.into());
24765            runner.state.config.agents = vec![author];
24766            seed_public_summary(&mut runner);
24767            let winner = runner.state.candidates[0].clone();
24768            let first = runner
24769                .guarded_pr_message(&winner, None, true)
24770                .await
24771                .unwrap();
24772            let message = if accepted {
24773                first.expect("a passing rewrite never asks")
24774            } else {
24775                // Withheld: the run parks on a question and posts nothing yet.
24776                assert!(first.is_none());
24777                assert!(runner.state.parked);
24778                let store = ask::Questions::open();
24779                let asked: Vec<_> = store
24780                    .list()
24781                    .into_iter()
24782                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24783                    .collect();
24784                assert_eq!(asked.len(), 1);
24785                assert!(!asked[0].detail.contains("secret"));
24786                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
24787                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
24788                assert_eq!(
24789                    asked[0]
24790                        .choices
24791                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
24792                    rewrite.is_some()
24793                );
24794                // Silence: the question lapses and the neutral text is used,
24795                // without a second rewrite call or a second question.
24796                store
24797                    .update(&asked[0].id, |q| {
24798                        q.abandon("test");
24799                        Ok(())
24800                    })
24801                    .unwrap();
24802                let again = runner
24803                    .guarded_pr_message(&winner, None, true)
24804                    .await
24805                    .unwrap()
24806                    .expect("an abandoned question falls back");
24807                let n = store
24808                    .list()
24809                    .into_iter()
24810                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24811                    .count();
24812                assert_eq!(n, 1, "asked once per rejected text");
24813                again
24814            };
24815            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
24816            assert!(!message.body.contains("secret"));
24817            assert!(!message.body.contains("prefix"));
24818            assert!(!message.title.contains("secret"));
24819            assert_eq!(
24820                message.body.contains("Add retries for failed requests."),
24821                accepted
24822            );
24823            assert_eq!(
24824                runner.state.seats["github-text-rewrite"].turns, 1,
24825                "only one rewrite invocation"
24826            );
24827            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
24828            if accepted {
24829                assert!(runner.state.github_text.is_none());
24830                assert!(!runner.state.parked);
24831                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
24832                assert!(message.body.contains("## Final verification"));
24833                assert!(message.body.contains("Evidence: final diff"));
24834                assert!(
24835                    message
24836                        .body
24837                        .contains(&format!("magi:run/{}", runner.state.id))
24838                );
24839            }
24840            if !accepted {
24841                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24842                assert!(
24843                    message
24844                        .body
24845                        .contains(&format!("magi:run/{}", runner.state.id))
24846                );
24847            }
24848        }
24849    }
24850
24851    fn scripted(id: &str, reply: &str) -> AgentSpec {
24852        let mut a = spec(id);
24853        a.command = vec![
24854            "sh".into(),
24855            "-c".into(),
24856            "printf '%s' \"$REWRITE_REPLY\"".into(),
24857        ];
24858        a.env.insert("REWRITE_REPLY".into(), reply.into());
24859        a
24860    }
24861
24862    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
24863    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
24864
24865    /// Gate tests inject generated public output, not internal reports.
24866    fn seed_public_summary(runner: &mut Runner) {
24867        let repo = &runner.state.repo;
24868        let g = |args: &[&str]| {
24869            let out = std::process::Command::new("git")
24870                .args(args)
24871                .current_dir(repo)
24872                .quiet()
24873                .output()
24874                .unwrap();
24875            assert!(out.status.success(), "git {args:?}");
24876            String::from_utf8_lossy(&out.stdout).trim().to_owned()
24877        };
24878        g(&["init", "-q", "-b", "main"]);
24879        g(&[
24880            "-c",
24881            "user.name=Test",
24882            "-c",
24883            "user.email=test@example.invalid",
24884            "commit",
24885            "-q",
24886            "--allow-empty",
24887            "-m",
24888            "feat: fixture",
24889        ]);
24890        let head = g(&["rev-parse", "HEAD"]);
24891        g(&["update-ref", "refs/remotes/origin/main", &head]);
24892        let evidence = crate::pr_outcome::summary_evidence(
24893            &runner.state,
24894            crate::pr_outcome::FinalHead::At(&head),
24895        );
24896        let generated = &runner.state.candidates[0].summary;
24897        runner.state.change_summary = Some(crate::run::ChangeSummary {
24898            base: head.clone(),
24899            head,
24900            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
24901            title: summary_title(generated).unwrap(),
24902            body: summary_without_title(generated),
24903        });
24904    }
24905
24906    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
24907        let mut runner = runner_at(RunStatus::Gating);
24908        runner.state = state_with_summary("add retries", JA_SUMMARY);
24909        if review_only {
24910            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24911        }
24912        runner.state.repo = dir.to_owned();
24913        runner.state.candidates[0].worktree = dir.to_owned();
24914        runner.state.config.agents = agents;
24915        seed_public_summary(&mut runner);
24916        runner
24917    }
24918
24919    fn gate_questions(runner: &Runner) -> usize {
24920        ask::Questions::open()
24921            .list()
24922            .into_iter()
24923            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24924            .count()
24925    }
24926
24927    #[tokio::test]
24928    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24929        crate::run::pin_test_home();
24930        let dir = tempfile::tempdir().unwrap();
24931        let mut runner = rewrite_runner(
24932            dir.path(),
24933            true,
24934            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24935        );
24936        runner.state.config.roles.language_judge =
24937            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24938        let winner = runner.state.candidates[0].clone();
24939        let msg = runner
24940            .guarded_pr_message(&winner, None, true)
24941            .await
24942            .unwrap()
24943            .expect("an English rewrite posts without asking");
24944        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24945        assert!(msg.body.contains("<details>kept</details>"));
24946        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24947        assert_eq!(gate_questions(&runner), 0);
24948        assert!(runner.state.github_text.is_none());
24949        assert!(!runner.state.seats.contains_key("impl-A"));
24950        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24951    }
24952
24953    #[tokio::test]
24954    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24955        crate::run::pin_test_home();
24956        let dir = tempfile::tempdir().unwrap();
24957        let mut runner = rewrite_runner(
24958            dir.path(),
24959            false,
24960            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24961        );
24962        runner.state.config.roles.language_judge =
24963            Some(crate::config::AgentChoice::One("beta".into()));
24964        runner.state.seats.insert(
24965            "impl-A".into(),
24966            SeatState::new("impl-A", "alpha", runner.state.seed),
24967        );
24968        let winner = runner.state.candidates[0].clone();
24969        let msg = runner
24970            .guarded_pr_message(&winner, None, true)
24971            .await
24972            .unwrap()
24973            .expect("rewritten");
24974        assert!(msg.body.contains("<details>kept</details>"));
24975        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24976        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24977        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24978    }
24979
24980    #[tokio::test]
24981    async fn rewrite_reuses_a_resumable_implementer_session() {
24982        crate::run::pin_test_home();
24983        let dir = tempfile::tempdir().unwrap();
24984        let mut runner = rewrite_runner(
24985            dir.path(),
24986            false,
24987            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24988        );
24989        runner.state.config.roles.language_judge =
24990            Some(crate::config::AgentChoice::One("beta".into()));
24991        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24992        seat.turns = 1;
24993        runner.state.seats.insert("impl-A".into(), seat);
24994        let winner = runner.state.candidates[0].clone();
24995        runner
24996            .guarded_pr_message(&winner, None, true)
24997            .await
24998            .unwrap()
24999            .expect("rewritten");
25000        assert_eq!(runner.state.seats["impl-A"].turns, 2);
25001        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
25002    }
25003
25004    #[tokio::test]
25005    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
25006        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
25007        // session, was out of quota, and nothing else was asked.
25008        crate::run::pin_test_home();
25009        let dir = tempfile::tempdir().unwrap();
25010        let mut exhausted = spec("alpha");
25011        exhausted.command = vec!["false".into()];
25012        let mut runner = rewrite_runner(
25013            dir.path(),
25014            false,
25015            vec![exhausted, scripted("beta", EN_REWRITE)],
25016        );
25017        // The implementer's own agent is in the role too: it is not asked twice.
25018        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25019            "alpha".into(),
25020            "beta".into(),
25021        ]));
25022        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25023        seat.turns = 1;
25024        runner.state.seats.insert("impl-A".into(), seat);
25025        let winner = runner.state.candidates[0].clone();
25026        let msg = runner
25027            .guarded_pr_message(&winner, None, true)
25028            .await
25029            .unwrap()
25030            .expect("the role rewrites after the implementer fails");
25031        assert!(msg.body.contains("`src/net.rs`"));
25032        assert_eq!(
25033            runner.state.seats["impl-A"].turns, 2,
25034            "the implementer was tried once"
25035        );
25036        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25037        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25038    }
25039
25040    #[tokio::test]
25041    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
25042        crate::run::pin_test_home();
25043        let dir = tempfile::tempdir().unwrap();
25044        let mut broken = spec("bad");
25045        broken.command = vec!["false".into()];
25046        let mut runner = rewrite_runner(
25047            dir.path(),
25048            true,
25049            vec![
25050                broken,
25051                scripted("noformat", "Add retries."),
25052                scripted("good", EN_REWRITE),
25053            ],
25054        );
25055        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25056            "bad".into(),
25057            "noformat".into(),
25058            "good".into(),
25059        ]));
25060        let winner = runner.state.candidates[0].clone();
25061        let msg = runner
25062            .guarded_pr_message(&winner, None, true)
25063            .await
25064            .unwrap()
25065            .expect("the third agent rewrites");
25066        assert!(msg.body.contains("`src/net.rs`"));
25067        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25068        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25069    }
25070
25071    #[tokio::test]
25072    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25073        crate::run::pin_test_home();
25074        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25075        for (agents, role, saved) in [
25076            (
25077                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25078                Some("beta"),
25079                true,
25080            ),
25081            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25082            (Vec::new(), None, false),
25083        ] {
25084            let dir = tempfile::tempdir().unwrap();
25085            let mut runner = rewrite_runner(dir.path(), true, agents);
25086            runner.state.config.roles.language_judge =
25087                role.map(|r| crate::config::AgentChoice::One(r.into()));
25088            let winner = runner.state.candidates[0].clone();
25089            let first = runner
25090                .guarded_pr_message(&winner, None, true)
25091                .await
25092                .unwrap();
25093            assert!(first.is_none(), "withheld text parks the run");
25094            assert!(runner.state.parked);
25095            assert_eq!(gate_questions(&runner), 1);
25096            let g = runner.state.github_text.as_ref().unwrap();
25097            assert_eq!(g.rewrite.is_some(), saved);
25098            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25099        }
25100    }
25101
25102    #[tokio::test]
25103    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25104        crate::run::pin_test_home();
25105        let dir = tempfile::tempdir().unwrap();
25106        let mut runner = runner_at(RunStatus::Gating);
25107        runner.state =
25108            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25109        runner.state.repo = dir.path().to_owned();
25110        runner.state.candidates[0].worktree = dir.path().to_owned();
25111        let mut author = spec("alpha");
25112        author.command = vec![
25113            "sh".into(),
25114            "-c".into(),
25115            "printf '%s' \"$REWRITE_REPLY\"".into(),
25116        ];
25117        author.env.insert(
25118            "REWRITE_REPLY".into(),
25119            format!(
25120                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25121                "English sentence. ".repeat(600)
25122            ),
25123        );
25124        runner.state.config.agents = vec![author];
25125        seed_public_summary(&mut runner);
25126        let winner = runner.state.candidates[0].clone();
25127        assert!(
25128            runner
25129                .guarded_pr_message(&winner, None, true)
25130                .await
25131                .unwrap()
25132                .is_none()
25133        );
25134        let record = runner.state.github_text.clone().unwrap();
25135        let rewrite = record.rewrite.clone().unwrap();
25136        assert_eq!(rewrite.failed, ["body-language"]);
25137        assert!(
25138            rewrite
25139                .body
25140                .ends_with(&format!("magi:run/{}", runner.state.id))
25141        );
25142        let store = ask::Questions::open();
25143        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25144        assert!(
25145            q.choices
25146                .contains(&crate::github_text::USE_REWRITE.to_owned())
25147        );
25148        for label in [
25149            "ORIGINAL",
25150            "FALLBACK",
25151            "REWRITE",
25152            "Rules still failed: body-language",
25153            "truncated",
25154        ] {
25155            assert!(q.detail.contains(label), "{label}");
25156        }
25157        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25158            &runner.state,
25159            &crate::github_text::artifact_name(&record.fingerprint),
25160        ))
25161        .unwrap();
25162        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25163        // Restart from serialized state, then retry after a bad owner title.
25164        runner.state =
25165            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25166        store
25167            .update(&q.id, |q| {
25168                q.say("まだ日本語")?;
25169                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25170            })
25171            .unwrap();
25172        assert!(
25173            runner
25174                .guarded_pr_message(&winner, None, true)
25175                .await
25176                .unwrap()
25177                .is_none()
25178        );
25179        let retry = runner.state.github_text.as_ref().unwrap();
25180        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25181        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25182        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25183        assert!(
25184            q.posting_comparison
25185                .as_ref()
25186                .unwrap()
25187                .matches_detail(&q.detail)
25188        );
25189        store
25190            .update(&q.id, |q| {
25191                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25192            })
25193            .unwrap();
25194        let message = runner
25195            .guarded_pr_message(&winner, None, true)
25196            .await
25197            .unwrap()
25198            .unwrap();
25199        assert_eq!(message.title, rewrite.title);
25200        assert_eq!(message.body, rewrite.body);
25201        assert_eq!(
25202            runner.state.github_text.as_ref().unwrap().choice,
25203            Some(GithubTextChoice::Rewrite)
25204        );
25205        let again = runner
25206            .guarded_pr_message(&winner, None, true)
25207            .await
25208            .unwrap()
25209            .unwrap();
25210        assert_eq!(again.title, message.title);
25211        assert_eq!(again.body, message.body);
25212        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25213        assert!(
25214            !runner
25215                .state
25216                .events
25217                .iter()
25218                .any(|e| e.message.contains(&rewrite.title)
25219                    || e.message.contains("English sentence."))
25220        );
25221    }
25222
25223    #[tokio::test]
25224    async fn historical_posting_reply_never_expires_into_fallback() {
25225        crate::run::pin_test_home();
25226        let dir = tempfile::tempdir().unwrap();
25227        let mut runner = runner_at(RunStatus::Gating);
25228        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25229        runner.state.repo = dir.path().to_owned();
25230        runner.state.candidates[0].worktree = dir.path().to_owned();
25231        seed_public_summary(&mut runner);
25232        let winner = runner.state.candidates[0].clone();
25233        assert!(
25234            runner
25235                .guarded_pr_message(&winner, None, true)
25236                .await
25237                .unwrap()
25238                .is_none()
25239        );
25240        let id = runner
25241            .state
25242            .github_text
25243            .as_ref()
25244            .unwrap()
25245            .question
25246            .clone()
25247            .unwrap();
25248        let store = ask::Questions::open();
25249        let mut q = store.get(&id).unwrap();
25250        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
25251        q.answer(ask::Answer::Choice(
25252            crate::github_text::POST_ORIGINAL.into(),
25253        ))
25254        .unwrap();
25255        q.answer_delivered = true;
25256        store.put(&mut q).unwrap();
25257        let source = std::fs::read(store.path_of(&id)).unwrap();
25258        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
25259        std::fs::create_dir_all(&migration).unwrap();
25260        std::fs::write(
25261            migration.join("state.json"),
25262            serde_json::to_vec(&serde_json::json!({
25263                "schema": 1, "sources": [id], "pending": [id]
25264            }))
25265            .unwrap(),
25266        )
25267        .unwrap();
25268        for _ in 0..2 {
25269            assert!(
25270                runner
25271                    .guarded_pr_message(&winner, None, true)
25272                    .await
25273                    .unwrap()
25274                    .is_none()
25275            );
25276            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25277            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25278        }
25279        let home = crate::run::home();
25280        crate::task_chat::sweep(
25281            &crate::queue::Queue::at(home.join("queue")),
25282            &crate::talk::Talks::at(home.join("talks")),
25283            &store,
25284            &home,
25285        );
25286        let outbox = crate::task_inquiry::Outbox::at(&home);
25287        outbox
25288            .update_decision(&id, |d| {
25289                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
25290                d.source_answer_at = q.answered_at;
25291                Ok(true)
25292            })
25293            .unwrap();
25294        outbox
25295            .settle(
25296                &id,
25297                "owner-chat",
25298                "Owner confirms no publication remains necessary",
25299                None,
25300            )
25301            .unwrap();
25302        assert!(
25303            runner
25304                .guarded_pr_message(&winner, None, true)
25305                .await
25306                .unwrap()
25307                .is_none()
25308        );
25309        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25310        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25311    }
25312
25313    #[tokio::test]
25314    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
25315        crate::run::pin_test_home();
25316        let dir = tempfile::tempdir().unwrap();
25317        let mut runner = runner_at(RunStatus::Gating);
25318        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25319        runner.state.repo = dir.path().to_owned();
25320        runner.state.candidates[0].worktree = dir.path().to_owned();
25321        seed_public_summary(&mut runner);
25322        let winner = runner.state.candidates[0].clone();
25323        assert!(
25324            runner
25325                .guarded_pr_message(&winner, None, true)
25326                .await
25327                .unwrap()
25328                .is_none()
25329        );
25330        let record = runner.state.github_text.as_ref().unwrap();
25331        assert!(record.rewrite.is_none());
25332        // Records written before the additive field deserialize with no rewrite.
25333        let mut old = serde_json::to_value(record).unwrap();
25334        old.as_object_mut().unwrap().remove("rewrite");
25335        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
25336        assert!(old.rewrite.is_none());
25337        let id = record.question.clone().unwrap();
25338        ask::Questions::open()
25339            .update(&id, |q| {
25340                q.choices.push(crate::github_text::USE_REWRITE.into());
25341                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25342            })
25343            .unwrap();
25344        let message = runner
25345            .guarded_pr_message(&winner, None, true)
25346            .await
25347            .unwrap()
25348            .unwrap();
25349        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25350        assert_eq!(
25351            runner.state.github_text.as_ref().unwrap().choice,
25352            Some(GithubTextChoice::Fallback)
25353        );
25354    }
25355
25356    #[tokio::test]
25357    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
25358        crate::run::pin_test_home();
25359        let dir = tempfile::tempdir().unwrap();
25360        let mut runner = runner_at(RunStatus::Gating);
25361        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
25362        runner.state.repo = dir.path().to_owned();
25363        runner.state.candidates[0].worktree = dir.path().to_owned();
25364        seed_public_summary(&mut runner);
25365        let winner = runner.state.candidates[0].clone();
25366        assert!(
25367            runner
25368                .guarded_pr_message(&winner, None, true)
25369                .await
25370                .unwrap()
25371                .is_none()
25372        );
25373        let store = ask::Questions::open();
25374        let find = |run: &str| {
25375            store
25376                .list()
25377                .into_iter()
25378                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
25379                .unwrap()
25380        };
25381        let run = runner.state.id.clone();
25382        let q = find(&run);
25383        let fp = runner
25384            .state
25385            .github_text
25386            .as_ref()
25387            .unwrap()
25388            .fingerprint
25389            .clone();
25390        let name = crate::github_text::artifact_name(&fp);
25391        let path = crate::run::artifact_path(&runner.state, &name);
25392        assert!(q.detail.contains(&path.display().to_string()));
25393        assert!(q.detail.contains("title-language: title"));
25394        let saved = std::fs::read_to_string(&path).expect("artifact written");
25395        assert!(saved.contains("日本語のタイトル"));
25396        assert!(q.cwd.is_none());
25397        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
25398        // A bad replacement is refused and asked about once more.
25399        let say = |id: &str, text: &str, choice: &str| {
25400            store
25401                .update(id, |q| {
25402                    q.thread.push(ask::Turn {
25403                        who: ask::Who::Operator,
25404                        body: text.to_owned(),
25405                        at: jiff::Timestamp::now(),
25406                        note: None,
25407                    });
25408                    q.answer(ask::Answer::Choice(choice.to_owned()))
25409                })
25410                .unwrap();
25411        };
25412        say(&q.id, "まだ日本語", "use my text");
25413        assert!(
25414            runner
25415                .guarded_pr_message(&winner, None, true)
25416                .await
25417                .unwrap()
25418                .is_none()
25419        );
25420        let second = find(&run);
25421        assert_ne!(second.id, q.id);
25422        assert!(second.detail.contains("did not pass"));
25423        // The retry still compares the original text; the rejected
25424        // replacement is named by category only.
25425        assert!(second.detail.contains("日本語のタイトル"));
25426        assert!(!second.detail.contains("まだ日本語"));
25427        assert!(second.detail.contains(&path.display().to_string()));
25428        say(&second.id, "fix: retry failed requests", "use my text");
25429        let message = runner
25430            .guarded_pr_message(&winner, None, true)
25431            .await
25432            .unwrap()
25433            .expect("a vetted replacement is posted");
25434        assert_eq!(message.title, "fix: retry failed requests");
25435        assert_eq!(
25436            runner
25437                .state
25438                .github_text
25439                .as_ref()
25440                .unwrap()
25441                .chosen_title
25442                .as_deref(),
25443            Some("fix: retry failed requests")
25444        );
25445        assert!(runner.state.github_text.as_ref().unwrap().resolved);
25446        // Resumed again: the saved decision is applied, nothing is re-asked.
25447        let again = runner
25448            .guarded_pr_message(&winner, None, true)
25449            .await
25450            .unwrap()
25451            .unwrap();
25452        assert_eq!(again.title, message.title);
25453        assert_eq!(
25454            store
25455                .list()
25456                .into_iter()
25457                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
25458                .count(),
25459            2
25460        );
25461    }
25462
25463    #[test]
25464    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
25465        // What magi itself writes stays English under any configured language,
25466        // so a future localisation of these headings fails here. (The agents'
25467        // own text is also checked by the posting gate.)
25468        let mut state = state_with_summary(
25469            "add retries",
25470            "TITLE: fix(web): batch reads\n- reads run.json once",
25471        );
25472        state.config.graph.language = "ja".to_owned();
25473        let m = pr_message(&state, 'A');
25474        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
25475        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
25476
25477        // The task is the operator's own text: it goes in untouched, and the
25478        // fallback title (no summary) may be in its language too.
25479        let task = "今回やってほしいこと: results projector を直す";
25480        let mut state = state_with_summary(task, "- no title line");
25481        state.config.graph.language = "ja".to_owned();
25482        let m = pr_message(&state, 'A');
25483        assert_eq!(
25484            m.title,
25485            format!("chore: land candidate A of run {}", state.id)
25486        );
25487        assert!(
25488            m.body.contains(&format!(
25489                "<summary>Original task</summary>\n\n{task}\n\n</details>"
25490            )),
25491            "{}",
25492            m.body
25493        );
25494    }
25495
25496    #[test]
25497    fn pr_message_scrubs_home_paths_and_addresses() {
25498        let state = state_with_summary(
25499            "fix it in /Users/someone/src/x",
25500            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
25501        );
25502        let m = pr_message(&state, 'A');
25503        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
25504            assert!(!m.body.contains(leak), "{}", m.body);
25505        }
25506        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
25507    }
25508
25509    #[test]
25510    fn pr_message_survives_a_task_that_closes_details() {
25511        let state = state_with_summary("a </details> b", "TITLE: fix: x");
25512        let m = pr_message(&state, 'A');
25513        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
25514    }
25515
25516    #[test]
25517    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
25518        let cmd = manual_merge_command(
25519            MergeStyle::Squash,
25520            Path::new("/repo"),
25521            "b",
25522            "fix: \"quoted\" $(x) `y`\n\nbody",
25523        );
25524        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
25525    }
25526
25527    #[test]
25528    fn manual_merge_command_matches_the_configured_style() {
25529        let repo = Path::new("/repo");
25530        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
25531
25532        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
25533        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
25534
25535        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
25536        assert_eq!(
25537            squash,
25538            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
25539             \"Merge magi run 0832 (candidate A)\""
25540        );
25541
25542        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
25543        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
25544    }
25545
25546    #[test]
25547    fn a_nudge_gets_a_quarter_of_the_budget() {
25548        // The judge and implement budgets magi ships with.
25549        assert_eq!(retry_budget(secs(1200), true), secs(300));
25550        assert_eq!(retry_budget(secs(3600), true), secs(900));
25551    }
25552
25553    #[test]
25554    fn a_resent_prompt_keeps_the_whole_budget() {
25555        // The seat kept no context, so the retry is the original job again and
25556        // shortening it would only guarantee a second failure.
25557        assert_eq!(retry_budget(secs(1200), false), secs(1200));
25558        assert_eq!(retry_budget(secs(60), false), secs(60));
25559    }
25560
25561    #[test]
25562    fn the_floor_never_exceeds_the_original_budget() {
25563        // A short configured timeout must not be *raised* by the floor: the
25564        // operator asked for a bound, and a retry may not outlast the attempt
25565        // it is retrying.
25566        assert_eq!(retry_budget(secs(60), true), secs(60));
25567        assert_eq!(retry_budget(secs(480), true), secs(120));
25568        assert_eq!(retry_budget(secs(0), true), secs(0));
25569    }
25570
25571    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
25572        agent::CommandEvidence {
25573            id: "item1".to_owned(),
25574            description: "cargo test".to_owned(),
25575            exit_code,
25576            result_summary: String::new(),
25577            source: "codex".to_owned(),
25578        }
25579    }
25580
25581    #[test]
25582    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
25583        // No evidence is not the same fact as unconfirmed evidence: a
25584        // backend with no adapter, or a reply that ran no commands at all,
25585        // must not be misread as carrying a dangling job.
25586        assert!(!has_unconfirmed_command(&[]));
25587    }
25588
25589    #[test]
25590    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
25591        // Deliberately not a check on the exit code's *value*: a fixer
25592        // legitimately runs something that fails mid-iteration before it
25593        // succeeds, and that must never by itself reopen a valid report.
25594        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
25595        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
25596        assert!(!has_unconfirmed_command(&[
25597            evidence(Some(0)),
25598            evidence(Some(101))
25599        ]));
25600    }
25601
25602    #[test]
25603    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
25604        assert!(has_unconfirmed_command(&[
25605            evidence(Some(0)),
25606            evidence(None)
25607        ]));
25608    }
25609
25610    fn evidence_with(
25611        description: &str,
25612        exit_code: Option<i32>,
25613        result_summary: &str,
25614    ) -> agent::CommandEvidence {
25615        agent::CommandEvidence {
25616            id: "item1".to_owned(),
25617            description: description.to_owned(),
25618            exit_code,
25619            result_summary: result_summary.to_owned(),
25620            source: "codex".to_owned(),
25621        }
25622    }
25623
25624    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
25625        format!(
25626            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":[]}}"#
25627        )
25628    }
25629
25630    #[test]
25631    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
25632        let text = valid_noop_summary("b32cfc4", "retry_test");
25633        let claim = verified_noop_claim(true, &[], &text)
25634            .expect("valid structured report with no CommandEvidence must be accepted");
25635        assert!(claim.contains("b32cfc4"), "{claim}");
25636        assert!(claim.contains("retry_test"), "{claim}");
25637    }
25638
25639    #[test]
25640    fn operational_regression_and_legacy_noop_claims_are_rejected() {
25641        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
25642        assert!(verified_noop_claim(true, &[], regression).is_none());
25643        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
25644        assert!(err.contains("single JSON object"), "{err}");
25645
25646        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
25647        assert!(verified_noop_claim(true, &[], legacy).is_none());
25648    }
25649
25650    #[test]
25651    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
25652        // A timeout or a bad exit code reads as the ordinary loss it is,
25653        // whatever the reply's own structured JSON claims.
25654        let text = valid_noop_summary("b32cfc4", "retry_test");
25655        assert!(verified_noop_claim(false, &[], &text).is_none());
25656    }
25657
25658    #[test]
25659    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
25660        let text = valid_noop_summary("b32cfc4", "retry_test");
25661        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
25662        // A matching confirmed command alongside the marker is fine.
25663        assert!(
25664            verified_noop_claim(
25665                true,
25666                &[evidence_with(
25667                    "cargo test --lib retry_test",
25668                    Some(0),
25669                    "1 passed"
25670                )],
25671                &text
25672            )
25673            .is_some()
25674        );
25675    }
25676
25677    #[test]
25678    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
25679     {
25680        let text = valid_noop_summary("b32cfc4", "retry_test");
25681
25682        // Unrelated passing command cannot substantiate a claimed test run.
25683        let err = evaluate_noop_claim(
25684            true,
25685            &[evidence_with("git status", Some(0), "nothing to commit")],
25686            &text,
25687        )
25688        .unwrap_err();
25689        assert!(err.contains("no matching command was recorded"), "{err}");
25690
25691        // Final matching command exited non-zero -> rejected even if an
25692        // unrelated command succeeded afterward.
25693        let err = evaluate_noop_claim(
25694            true,
25695            &[
25696                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
25697                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
25698                evidence_with("rg retry_test src", Some(0), "retry_test"),
25699            ],
25700            &text,
25701        )
25702        .unwrap_err();
25703        assert!(err.contains("exited with"), "{err}");
25704
25705        // A different invocation containing the entire method is not a rerun.
25706        let err = evaluate_noop_claim(
25707            true,
25708            &[evidence_with(
25709                "echo 'cargo test --lib retry_test'",
25710                Some(0),
25711                "retry_test",
25712            )],
25713            &text,
25714        )
25715        .unwrap_err();
25716        assert!(err.contains("no matching command was recorded"), "{err}");
25717
25718        // Mid-investigation failure followed by a passing re-run -> accepted!
25719        assert!(
25720            verified_noop_claim(
25721                true,
25722                &[
25723                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
25724                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
25725                ],
25726                &text
25727            )
25728            .is_some()
25729        );
25730    }
25731
25732    #[test]
25733    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
25734        let text = valid_noop_summary("b32cfc4", "retry_test");
25735        let method = "cargo test --lib retry_test";
25736        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
25737        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
25738        let failed =
25739            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
25740        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
25741        for output in [empty, ignored, failed] {
25742            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
25743                .unwrap_err();
25744            assert!(err.contains("failure or no passing tests"), "{err}");
25745        }
25746        // Multiple harnesses can legitimately include a filtered-out suite.
25747        let mixed = format!("{passed}\n{empty}");
25748        assert!(
25749            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
25750        );
25751        // A later real rerun of the same command can establish success.
25752        assert!(
25753            verified_noop_claim(
25754                true,
25755                &[
25756                    evidence_with(method, Some(0), empty),
25757                    evidence_with(method, Some(0), passed),
25758                ],
25759                &text,
25760            )
25761            .is_some()
25762        );
25763    }
25764
25765    #[test]
25766    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
25767        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":[]}"#;
25768        let failed = evidence_with("rg expected README.md", Some(1), "");
25769        let unrelated = evidence_with("cat README.md", Some(0), "README");
25770        let err =
25771            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
25772        assert!(err.contains("exited with"), "{err}");
25773        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
25774        assert!(
25775            evaluate_noop_claim(
25776                true,
25777                &[
25778                    failed,
25779                    evidence_with("rg expected README.md", Some(0), "expected header"),
25780                ],
25781                text,
25782            )
25783            .unwrap()
25784            .is_some()
25785        );
25786    }
25787
25788    #[test]
25789    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
25790        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
25791        assert!(matches!(
25792            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
25793            Ok(None)
25794        ));
25795    }
25796
25797    #[tokio::test]
25798    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
25799        let tmp = tempfile::tempdir().unwrap();
25800        let repo = tmp.path().join("repo");
25801        std::fs::create_dir_all(&repo).unwrap();
25802        let run_git = |args: &[&str]| {
25803            let out = std::process::Command::new("git")
25804                .args(args)
25805                .current_dir(&repo)
25806                .output()
25807                .unwrap();
25808            assert!(out.status.success(), "git {args:?} failed");
25809            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25810        };
25811        run_git(&["init", "-b", "main"]);
25812        run_git(&["config", "user.name", "test"]);
25813        run_git(&["config", "user.email", "test@example.com"]);
25814        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
25815        run_git(&["add", "-A"]);
25816        run_git(&["commit", "-m", "base commit"]);
25817        let base = run_git(&["rev-parse", "HEAD"]);
25818
25819        // Create a commit on a side branch not on `base`.
25820        run_git(&["checkout", "-b", "side"]);
25821        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
25822        run_git(&["add", "-A"]);
25823        run_git(&["commit", "-m", "side commit"]);
25824        let side = run_git(&["rev-parse", "HEAD"]);
25825        run_git(&["checkout", "main"]);
25826
25827        // Valid commit on base + existing path -> Accepted.
25828        let valid = format!(
25829            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":[]}}"#
25830        );
25831        assert!(matches!(
25832            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
25833            NoopClaimVerdict::Accepted
25834        ));
25835
25836        // Non-existent commit SHA -> Rejected.
25837        let missing_sha = valid.replace(&base, "deadbeef");
25838        assert!(matches!(
25839            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
25840            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
25841        ));
25842
25843        // Commit on unmerged side branch -> Rejected.
25844        let side_sha = valid.replace(&base, &side);
25845        assert!(matches!(
25846            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
25847            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
25848        ));
25849
25850        // Missing file path -> Rejected.
25851        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
25852        assert!(matches!(
25853            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
25854            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
25855        ));
25856    }
25857
25858    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
25859    /// pair, in order, labelled A, B, C, ...
25860    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
25861        runner.state.candidates = shape
25862            .iter()
25863            .enumerate()
25864            .map(|(i, &(empty, verified))| {
25865                let (summary, verified_noop) = match verified {
25866                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
25867                    None => (String::new(), None),
25868                };
25869                Candidate {
25870                    index: i,
25871                    label: (b'A' + i as u8) as char,
25872                    agent: "sonnet".to_owned(),
25873                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
25874                    worktree: PathBuf::from(format!("/wt/{i}")),
25875                    summary,
25876                    stat: String::new(),
25877                    files: 0,
25878                    commits: 0,
25879                    empty,
25880                    failed: None,
25881                    verified_noop,
25882                    duration_ms: 0,
25883                    folded: false,
25884                }
25885            })
25886            .collect();
25887    }
25888
25889    #[test]
25890    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
25891        ask_test_home();
25892        let mut runner = runner_at(RunStatus::Implementing);
25893        let a = valid_noop_summary("b32cfc4", "test_a");
25894        let b = valid_noop_summary("b32cfc4", "test_b");
25895        set_candidates(
25896            &mut runner,
25897            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
25898        );
25899
25900        runner
25901            .after_implement()
25902            .expect("a verified no-op is not an error");
25903
25904        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
25905    }
25906
25907    #[test]
25908    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
25909        ask_test_home();
25910        let mut runner = runner_at(RunStatus::Implementing);
25911        let a = valid_noop_summary("b32cfc4", "test_a");
25912        // Candidate A declares a verified no-op; candidate B simply wrote
25913        // nothing and said nothing about why. One candidate's claim is not
25914        // the whole run's agreement.
25915        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
25916
25917        let err = runner
25918            .after_implement()
25919            .expect_err("an unverified empty candidate must still fail the run");
25920
25921        assert!(
25922            err.to_string().contains("no candidate produced a change"),
25923            "{err}"
25924        );
25925        assert_eq!(runner.state.status, RunStatus::Failed);
25926    }
25927
25928    #[test]
25929    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
25930        ask_test_home();
25931        let mut runner = runner_at(RunStatus::Implementing);
25932        // Simulate a saved incomplete run that stored a legacy/incomplete
25933        // `verified_noop` string before this build's strict contract.
25934        set_candidates(
25935            &mut runner,
25936            &[(
25937                true,
25938                Some(
25939                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
25940                ),
25941            )],
25942        );
25943
25944        let err = runner
25945            .after_implement()
25946            .expect_err("invalid saved noop claim must fail the run");
25947        assert!(
25948            err.to_string().contains("no candidate produced a change"),
25949            "{err}"
25950        );
25951        assert_eq!(runner.state.status, RunStatus::Failed);
25952        assert!(runner.state.candidates[0].verified_noop.is_none());
25953        assert!(runner.state.candidates[0].failed.is_some());
25954        assert!(runner.state.events.iter().any(|e| {
25955            e.message
25956                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
25957        }));
25958    }
25959
25960    #[test]
25961    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
25962        ask_test_home();
25963        let mut runner = runner_at(RunStatus::Implementing);
25964        let a = valid_noop_summary("b32cfc4", "test_a");
25965        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
25966        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
25967
25968        let err = runner
25969            .after_implement()
25970            .expect_err("a failed candidate must never settle as verified no-op");
25971        assert!(err.to_string().contains("no candidate produced a change"));
25972        assert_eq!(runner.state.status, RunStatus::Failed);
25973        assert!(runner.state.candidates[0].verified_noop.is_none());
25974    }
25975
25976    #[test]
25977    fn after_implement_still_fails_an_ordinary_all_empty_run() {
25978        ask_test_home();
25979        let mut runner = runner_at(RunStatus::Implementing);
25980        set_candidates(&mut runner, &[(true, None), (true, None)]);
25981
25982        let err = runner
25983            .after_implement()
25984            .expect_err("no candidate declared anything; this is an ordinary failure");
25985
25986        assert!(
25987            err.to_string().contains("no candidate produced a change"),
25988            "{err}"
25989        );
25990        assert_eq!(runner.state.status, RunStatus::Failed);
25991    }
25992}
25993
25994/// A graft rollback whose restore could not be confirmed (see
25995/// [`Runner::graft`]).
25996#[derive(Debug)]
25997struct GraftRestoreFailed(String);
25998
25999impl std::fmt::Display for GraftRestoreFailed {
26000    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26001        write!(
26002            f,
26003            "could not restore the winner to its pre-graft commit: {}",
26004            self.0
26005        )
26006    }
26007}
26008
26009impl std::error::Error for GraftRestoreFailed {}
26010
26011/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
26012/// not the agent: they never draw on an agent's own timeout, and running out of
26013/// them never reads as an agent failure.
26014#[cfg(test)]
26015mod resource_wait_tests {
26016    use super::*;
26017    use std::collections::BTreeMap;
26018
26019    fn sh(id: &str, script: &str) -> AgentSpec {
26020        AgentSpec {
26021            id: id.to_owned(),
26022            kind: crate::config::AgentKind::Command,
26023            model: None,
26024            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
26025            extra_args: Vec::new(),
26026            env: BTreeMap::new(),
26027            prompt_delivery: None,
26028            max_turn_secs: None,
26029        }
26030    }
26031
26032    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
26033        SeatJob {
26034            seat: SeatState::new("impl-A", &spec.id, 1),
26035            spec,
26036            cwd: dir.to_path_buf(),
26037            prompt: "do it".to_owned(),
26038            timeout,
26039            allow_write: true,
26040            sessions: false,
26041            artifacts: dir.join("art"),
26042            stem: "impl-A".to_owned(),
26043            handover: None,
26044        }
26045    }
26046
26047    fn state(resource_wait_secs: u64) -> RunState {
26048        let mut config = Config::default();
26049        config.graph.timeout_resource_wait = resource_wait_secs;
26050        RunState::new(
26051            PathBuf::from("/repo"),
26052            "main".to_owned(),
26053            "abc1234".to_owned(),
26054            "task".to_owned(),
26055            config,
26056        )
26057    }
26058
26059    fn hold(cache: &Path) -> crate::cache::Guard {
26060        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
26061        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
26062            crate::cache::AcquireOutcome::Acquired(g) => g,
26063            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26064        }
26065    }
26066
26067    async fn run(
26068        jobs: Vec<SeatJob>,
26069        sem: Arc<Semaphore>,
26070        cache: Option<&Path>,
26071        st: &mut RunState,
26072    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26073        let prompts = Prompts::default();
26074        let ctx = WaveCtx {
26075            run: "r",
26076            node: "implement",
26077            prompts: &prompts,
26078            cache,
26079            round: None,
26080            carry_seats: false,
26081            pauses: None,
26082        };
26083        wave(jobs, sem, &ctx, st, 0).await
26084    }
26085
26086    #[tokio::test]
26087    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26088        crate::run::pin_test_home();
26089        let home = crate::run::home();
26090        let tmp = tempfile::tempdir().unwrap();
26091        let repo = tmp.path().join("repo");
26092        let checkout = tmp.path().join("checkout");
26093        std::fs::create_dir(&repo).unwrap();
26094        git::git(&repo, &["init"]).await.unwrap();
26095        git::git(
26096            &repo,
26097            &[
26098                "-c",
26099                "user.name=Fixture",
26100                "-c",
26101                "user.email=fixture@example.invalid",
26102                "commit",
26103                "--allow-empty",
26104                "-m",
26105                "initial",
26106            ],
26107        )
26108        .await
26109        .unwrap();
26110        git::worktree_add_detached(&repo, &checkout, "HEAD")
26111            .await
26112            .unwrap();
26113        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26114        let target_lease = hold(&target);
26115        let shared = tmp.path().join("unrelated");
26116        let _shared_lease = hold(&shared);
26117        let mut st = state(0);
26118        st.repo = repo.clone();
26119        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26120        st.config.verify.e2e = vec![format!(
26121            "CARGO_TARGET_DIR='{}' cargo test",
26122            git::path_arg(&shared)
26123        )];
26124        let config = tmp.path().join("config.toml");
26125        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26126        let prompts = Prompts::default();
26127        let run_id = st.id.clone();
26128        let ctx = WaveCtx {
26129            run: &run_id,
26130            node: "implement",
26131            prompts: &prompts,
26132            cache: None,
26133            round: None,
26134            carry_seats: false,
26135            pauses: None,
26136        };
26137        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26138        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26139        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26140        assert_eq!(results[0].1.turns, 0);
26141        let saved = RunState::load_under(&run_id, &home).unwrap();
26142        let block = saved.resource_block.unwrap();
26143        assert!(matches!(
26144            block.cause,
26145            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
26146                if actual == &target
26147        ));
26148        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
26149        let mut task = crate::queue::Task::new(
26150            "build".into(),
26151            "build".into(),
26152            repo,
26153            crate::queue::Source::Human,
26154        );
26155        task.runs.push(run_id);
26156        task.hold_machine(Some(format!(
26157            "{}{}",
26158            crate::cache::RESOURCE_HOLD,
26159            block.description()
26160        )));
26161        queue.put(&mut task).unwrap();
26162        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
26163        let triage =
26164            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
26165        let pending = triage();
26166        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
26167        assert_eq!(
26168            queue.get(&task.id).unwrap().status,
26169            crate::queue::TaskStatus::Held
26170        );
26171        drop(target_lease);
26172        assert_eq!(triage().resumed, vec![task.id.clone()]);
26173        assert_eq!(
26174            queue.get(&task.id).unwrap().status,
26175            crate::queue::TaskStatus::Queued
26176        );
26177        assert!(crate::cache::in_use(&home, &shared));
26178    }
26179
26180    #[tokio::test]
26181    async fn verification_cache_wait_preserves_the_command_budget() {
26182        crate::run::pin_test_home();
26183        let tmp = tempfile::tempdir().unwrap();
26184        let cache = tmp.path().join("target");
26185        let guard = hold(&cache);
26186        let release = tokio::spawn(async move {
26187            tokio::time::sleep(Duration::from_millis(100)).await;
26188            guard.release();
26189        });
26190        let mut st = state(10);
26191        let budget = Duration::from_millis(50);
26192        let wait = repository_wait(&st, None);
26193        let (outcomes, _) = with_cache_lease(
26194            &mut st,
26195            Some(&cache),
26196            "gate",
26197            "gate",
26198            tmp.path(),
26199            "abc1234",
26200            budget,
26201            "test gate",
26202            &wait,
26203            |_, available| async move {
26204                assert_eq!(
26205                    available, budget,
26206                    "contention must not shorten verification"
26207                );
26208                (Vec::new(), false, Vec::new())
26209            },
26210        )
26211        .await
26212        .unwrap();
26213        release.await.unwrap();
26214        assert!(outcomes.is_empty(), "{outcomes:?}");
26215        assert!(
26216            st.events
26217                .iter()
26218                .any(|event| event.message.contains("waiting for"))
26219        );
26220        assert!(st.resource_wait.is_none());
26221        // The verification body no longer owns the lease after returning.
26222        hold(&cache).release();
26223    }
26224
26225    #[tokio::test]
26226    async fn verification_cache_wait_expires_without_starting_commands() {
26227        crate::run::pin_test_home();
26228        let tmp = tempfile::tempdir().unwrap();
26229        let cache = tmp.path().join("target");
26230        let _held = hold(&cache);
26231        let mut st = state(0);
26232        let wait = repository_wait(&st, None);
26233        let (outcomes, _) = with_cache_lease(
26234            &mut st,
26235            Some(&cache),
26236            "gate",
26237            "gate",
26238            tmp.path(),
26239            "abc1234",
26240            Duration::from_secs(60),
26241            "test gate",
26242            &wait,
26243            |_, _| async { panic!("commands must not start without the cache lease") },
26244        )
26245        .await
26246        .unwrap();
26247        assert_eq!(outcomes.len(), 1);
26248        assert!(outcomes[0].resource_blocked);
26249        assert!(st.resource_wait.is_none());
26250        assert!(matches!(
26251            st.resource_block.unwrap().cause,
26252            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
26253        ));
26254    }
26255
26256    #[tokio::test]
26257    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
26258        crate::run::pin_test_home();
26259        let tmp = tempfile::tempdir().unwrap();
26260        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
26261        let cache = tmp.path().join("cache");
26262        let mut state = state(21600);
26263        let wait = repository_wait(&state, None);
26264        let (outcomes, _) = with_cache_lease(
26265            &mut state,
26266            Some(&cache),
26267            "gate",
26268            "gate",
26269            tmp.path(),
26270            "head",
26271            Duration::from_secs(60),
26272            "gate",
26273            &wait,
26274            |_, _| async { panic!("freshness failure must not start verification") },
26275        )
26276        .await
26277        .unwrap();
26278        assert_eq!(outcomes.len(), 1);
26279        assert!(outcomes[0].resource_blocked);
26280        let block = state.resource_block.unwrap();
26281        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
26282        assert!(!block.description().contains("timed out"));
26283    }
26284
26285    #[tokio::test]
26286    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
26287        crate::run::pin_test_home();
26288        let tmp = tempfile::tempdir().unwrap();
26289        let cache = tmp.path().join("cache");
26290        let _held = hold(&cache);
26291        let mut state = state(21600);
26292        let pause = Pause::new();
26293        let interrupt = Pause::new();
26294        let cause = ParkCause::Operator;
26295        pause.park_for(cause.clone());
26296        let prompts = Prompts::default();
26297        let ctx = WaveCtx {
26298            run: "test",
26299            node: "fix",
26300            prompts: &prompts,
26301            cache: Some(&cache),
26302            round: None,
26303            carry_seats: false,
26304            pauses: Some((&pause, &interrupt)),
26305        };
26306        let result = wave(
26307            vec![job(
26308                sh("writer", "exit 99"),
26309                tmp.path(),
26310                Duration::from_secs(1),
26311            )],
26312            Arc::new(Semaphore::new(1)),
26313            &ctx,
26314            &mut state,
26315            0,
26316        )
26317        .await;
26318        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
26319        assert_eq!(result[0].1.turns, 0);
26320        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26321        assert_eq!(
26322            state.resource_block.unwrap().cause,
26323            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
26324        );
26325        assert!(state.active.is_empty());
26326    }
26327
26328    #[tokio::test]
26329    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
26330        crate::run::pin_test_home();
26331        let tmp = tempfile::tempdir().unwrap();
26332        let cache = tmp.path().join("target-a");
26333        let guard = hold(&cache);
26334        // Held for longer than the agent's whole 1s budget.
26335        tokio::spawn(async move {
26336            tokio::time::sleep(Duration::from_millis(1500)).await;
26337            guard.release();
26338        });
26339        let mut st = state(60);
26340        let results = run(
26341            vec![job(
26342                sh("alpha", "echo ok"),
26343                tmp.path(),
26344                Duration::from_secs(1),
26345            )],
26346            Arc::new(Semaphore::new(1)),
26347            Some(&cache),
26348            &mut st,
26349        )
26350        .await;
26351        assert!(
26352            matches!(results[0].2, AgentOutcome::Ok(_)),
26353            "the wait must not be charged to the agent"
26354        );
26355        assert!(st.resource_block.is_none());
26356        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26357        assert!(st.resource_wait.is_none() && st.active.is_empty());
26358    }
26359
26360    #[tokio::test]
26361    #[cfg(unix)]
26362    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
26363        use std::os::fd::AsRawFd as _;
26364        crate::run::pin_test_home();
26365        let tmp = tempfile::tempdir().unwrap();
26366        crate::git::git(tmp.path(), &["init"]).await.unwrap();
26367        let common = tmp.path().join(".git");
26368        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
26369        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
26370        assert_eq!(
26371            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
26372            0
26373        );
26374        let mut st = state(1);
26375        st.config.coordination = crate::config::test_coordination();
26376        let mut reader = job(
26377            sh("reader", "echo must-not-run"),
26378            tmp.path(),
26379            Duration::from_secs(30),
26380        );
26381        reader.allow_write = false;
26382        let results = run(
26383            vec![reader.clone()],
26384            Arc::new(Semaphore::new(1)),
26385            None,
26386            &mut st,
26387        )
26388        .await;
26389        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26390        assert_eq!(results[0].1.turns, 0);
26391        assert!(FailClass::of(&results[0].2).is_none());
26392        assert_eq!(
26393            st.resource_block.as_ref().unwrap().kind,
26394            "repository coordination"
26395        );
26396        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26397        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26398        drop(external);
26399        let editor = crate::repo_lock::SeatLease::for_checkout(
26400            tmp.path(),
26401            true,
26402            crate::config::test_coordination().as_ref(),
26403        )
26404        .await
26405        .unwrap();
26406        let pause = Pause::new();
26407        let interrupt = Pause::new();
26408        let prompts = Prompts::default();
26409        let ctx = WaveCtx {
26410            run: "r",
26411            node: "review",
26412            prompts: &prompts,
26413            cache: None,
26414            round: None,
26415            carry_seats: false,
26416            pauses: Some((&pause, &interrupt)),
26417        };
26418        let (results, ()) = tokio::join!(
26419            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
26420            async {
26421                tokio::time::sleep(Duration::from_millis(50)).await;
26422                pause.park();
26423            }
26424        );
26425        assert!(
26426            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
26427        );
26428        assert_eq!(results[0].1.turns, 0);
26429        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26430        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26431        drop(editor);
26432    }
26433
26434    #[tokio::test]
26435    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
26436        crate::run::pin_test_home();
26437        let tmp = tempfile::tempdir().unwrap();
26438        let cache = tmp.path().join("target-b");
26439        let _held = hold(&cache);
26440        let mut st = state(1);
26441        let results = run(
26442            vec![job(
26443                sh("alpha", "echo ok"),
26444                tmp.path(),
26445                Duration::from_secs(1),
26446            )],
26447            Arc::new(Semaphore::new(1)),
26448            Some(&cache),
26449            &mut st,
26450        )
26451        .await;
26452        let (_, seat, out) = &results[0];
26453        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
26454        assert!(wave_blocked(&results));
26455        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
26456        assert_eq!(seat.turns, 0, "nothing was asked");
26457        assert!(
26458            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
26459            "no agent was spawned"
26460        );
26461        assert!(FailClass::of(out).is_none(), "not a failure class");
26462        let block = st.resource_block.as_ref().expect("recorded for the resume");
26463        assert_eq!(block.kind, "shared build cache");
26464        assert!(matches!(
26465            block.cause,
26466            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
26467        ));
26468        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26469        assert!(st.active.is_empty());
26470    }
26471
26472    #[tokio::test]
26473    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
26474        crate::run::pin_test_home();
26475        let tmp = tempfile::tempdir().unwrap();
26476        let mut st = state(1);
26477        let results = run(
26478            vec![job(
26479                sh("alpha", "echo ok"),
26480                tmp.path(),
26481                Duration::from_secs(1),
26482            )],
26483            Arc::new(Semaphore::new(0)),
26484            None,
26485            &mut st,
26486        )
26487        .await;
26488        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26489        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
26490        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
26491    }
26492
26493    #[tokio::test]
26494    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
26495        crate::run::pin_test_home();
26496        let tmp = tempfile::tempdir().unwrap();
26497        let mut st = state(60);
26498        let results = run(
26499            vec![job(
26500                sh("alpha", "sleep 30"),
26501                tmp.path(),
26502                Duration::from_secs(1),
26503            )],
26504            Arc::new(Semaphore::new(1)),
26505            None,
26506            &mut st,
26507        )
26508        .await;
26509        let out = &results[0].2;
26510        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
26511        let class = FailClass::of(out).expect("a failure");
26512        assert_eq!(class, FailClass::Timeout);
26513        assert!(should_hand_over(None, &class), "existing handover policy");
26514        assert!(st.resource_block.is_none());
26515    }
26516}