Skip to main content

magi/
graph.rs

1//! The competition graph.
2//!
3//! ```text
4//! prep ──► implement ×N ──► judge ×M (blind) ──► split? ──► deliberate ──► vote (private)
5//!                                                   │                          │
6//!                                                   └──── unanimous ───────────┤
7//!                                                                              ▼
8//!   merge ◄── gate ◄── review ×R + E2E, fix, repeat ◄── fold losers ◄──────── tally
9//! ```
10//!
11//! Every node persists before the next one starts, so a run can be resumed
12//! after a crash, a rate limit, or a reboot without re-spending the work that
13//! already landed.
14//!
15//! The design decision that matters most is *where the facilitator lives*.
16//! There is no moderator agent: magi assigns the labels, decides the
17//! presentation order, relays the transcript, and collects the final votes
18//! one-to-one. A moderator that never learns an author cannot leak one.
19use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use anyhow::{Context as _, Result, bail};
26use jiff::Timestamp;
27use tokio::sync::Semaphore;
28
29use crate::advise;
30use crate::agent::{self, AgentOutput, Invocation, SeatState};
31use crate::ask;
32use crate::blind;
33use crate::bump;
34use crate::config::{
35    AgentSpec, Config, IncompleteReviewPolicy, LeakPolicy, MergeMode, MergeStyle, Prompts,
36    ResolvedRoles,
37};
38use crate::fixer;
39use crate::git;
40use crate::graft;
41use crate::land;
42use crate::proc::Quiet as _;
43use crate::prompt::{
44    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
45};
46use crate::queue;
47#[cfg(test)]
48use crate::refs;
49use crate::run::{
50    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
51    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord,
52    GithubTextChoice, GraftOutcome, GraftRecord, Handover, JobRecord, JobStatus, Judgement,
53    MergeOutcome, OperatorFixFinding, OperatorFixOutcome, OperatorFixRequest, Origin, ParkCause,
54    QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState, RunStatus, SeatHistory,
55    Tally, VoteRecord, summarize_verify, write_artifact,
56};
57use crate::verdict::{
58    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
59    ReviewVote, Severity,
60};
61
62/// Fixed commit message for graph-owned mechanical `verify.pre_gate` commits.
63pub const PRE_GATE_COMMIT_MESSAGE: &str = "magi: pre_gate (mechanical fixes)";
64
65/// Event node recorded by [`Runner::run_pre_gate`].
66pub(crate) const PRE_GATE_EVENT_NODE: &str = "pre_gate";
67
68/// Durable event text logged when [`Runner::run_pre_gate`] commits mechanical changes.
69pub(crate) fn pre_gate_commit_event(head: &str) -> String {
70    format!("committed mechanical fixes ({head})")
71}
72use crate::worktree_setup;
73
74/// Bytes of a failing command's output kept in an event, so the reason a run
75/// stopped is readable from the report without opening `run.json`.
76const EVENT_OUTPUT_TAIL: usize = 2_000;
77
78/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
79/// command's pid before releasing the build cache's lease.
80const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
81
82/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
83/// command's pid to actually exit before giving up and releasing anyway.
84///
85/// A timeout means the process was asked to die (`kill_on_drop`,
86/// `start_kill`), not that it already has — on Windows in particular that can
87/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
88/// the instant the command returns would let the very next acquirer (this
89/// run's own next round, another run's verification, the janitor's prune)
90/// start touching the same directory while it might still be writing to it,
91/// so this polls the actual pid — real confirmation, not a fixed guess —
92/// until it is gone or this ceiling is reached. It is still not full
93/// process-tree reaping: a grandchild the timed-out process spawned and that
94/// outlives it independently is invisible to a pid check, and continuing to
95/// observe and collect *that* stays a different piece of work with its own
96/// owner. Set generously because the common case returns early the moment
97/// the pid is confirmed gone, not because every timeout pays this in full.
98const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
99
100/// Consecutive review rounds with no tree progress (see
101/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
102/// instead of spending the rest of the round budget.
103///
104/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
105/// legitimately finds nothing left to change (its previous round's fix already
106/// covered it, and this round's reviewers re-raised only nits) looks the same
107/// as one that is spinning, for exactly one round. Two in a row is where the
108/// two stop being distinguishable, and a review round on this workload has
109/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
110/// third attempt at a tree that has not moved twice running is pure cost.
111/// This does not touch `review_rounds` itself, which stays the operator's
112/// call.
113pub(crate) const STAGNANT_LIMIT: usize = 2;
114
115/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
116/// a base that moved before giving up and leaving the run `Blocked` for a
117/// person.
118///
119/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
120/// that keeps moving faster than a run can catch it is not something more
121/// rebasing fixes, it is a person's call. Not the same *number as*
122/// `land_rounds` - this budget is spent before a pull request exists, land's
123/// after - but bounded for the identical reason, so it uses the same
124/// default. Counted across both call sites in [`Runner::finish_after_tally`]
125/// (once before review, once before the gate), because either one finding
126/// the base still moving is the same signal.
127pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
128
129/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
130/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
131/// reply held no [`FixReport`].
132///
133/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
134/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
135/// "I'll pause here until the `cargo make check` background run reports
136/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
137/// No `FixReport` was ever collected from that seat, and the run moved on to
138/// the next review round regardless.
139///
140/// Bounded independently of `review_rounds` and `graph.retries`: this
141/// recovers one seat's missing report mid-round, not a new round of review or
142/// an ordinary parse retry, and must not itself become the unbounded wait the
143/// rest of this module exists to avoid.
144const MAX_FIX_CONTINUATIONS: usize = 2;
145
146/// One queued agent invocation.
147///
148/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
149/// CLI hung up on its own stream is asked again from the same job rather than
150/// rebuilt from scratch. See [`Runner::resume_undelivered`].
151#[derive(Clone)]
152struct SeatJob {
153    spec: AgentSpec,
154    seat: SeatState,
155    cwd: PathBuf,
156    prompt: String,
157    timeout: Duration,
158    allow_write: bool,
159    sessions: bool,
160    artifacts: PathBuf,
161    stem: String,
162    /// The prompt for a seat that has been handed to another roster agent
163    /// (a fresh session): everything the original seat would have
164    /// remembered. `None` when `prompt` already carries it, as the first
165    /// ranking and the implement prompt do. Never a resume-style prompt.
166    handover: Option<String>,
167}
168
169/// How the graph reads one agent invocation.
170///
171/// Quota is split out from an ordinary failure on purpose: a rate-limited call
172/// is known to fail again if retried now, so the retry loop must not spend an
173/// attempt on it. `Dropped` is split out for the opposite reason: unlike
174/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
175/// error JSON, never the agent's answer — a caller that matched only
176/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
177/// left to read that JSON as if it were usable output. `resume_undelivered`
178/// is the only caller that acts on it; everywhere else it is reported like an
179/// ordinary failure.
180enum AgentOutcome {
181    /// A usable output.
182    Ok(AgentOutput),
183    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
184    Quota(AgentOutput),
185    /// The CLI hung up on its own stream after billed work. See
186    /// [`agent::AgentOutput::work_undelivered`].
187    Dropped(AgentOutput),
188    /// Any other failure: a timeout, a bad exit code, an empty reply.
189    Failed(String),
190    /// A resource prevented admission or interrupted execution. Not an agent
191    /// failure: never advance a fallback chain or spend an attempt on it.
192    /// Post-spawn interruptions carry a typed error into wave, which records
193    /// implementation preservation before returning this outcome. This outcome
194    /// alone is not proof that no source changes were made.
195    /// [`RunState::resource_block`] says why.
196    ResourceBlocked(String),
197}
198
199/// A request to park the run at its next node boundary.
200///
201/// Cloning is how the request travels: the loop keeps one handle and hands a
202/// clone to each [`Runner`], and every clone points at the same flag. There
203/// is no channel because there is nothing to send - the only message is
204/// "park", it is idempotent, and a flag cannot be missed by a receiver that
205/// was not listening yet.
206///
207/// The boundary is what makes this cheap. Every node writes the run's state
208/// before the next one starts, and every node skips what is already recorded:
209/// `prep` returns early once candidates exist, `implement` asks only the seats
210/// with nothing on disk, `judge` returns early once judgements exist. So a
211/// parked run resumes into exactly the node it stopped before, and no agent
212/// work is thrown away. Killing the process mid-node, by contrast, loses
213/// whatever the seats in flight had not yet written - which for an implement
214/// wave is an hour of paid work.
215///
216/// A [`Runner`] watches two independent handles of this type - see
217/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
218/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
219/// clone covering the whole daemon's lifetime and is never asked to un-park,
220/// which is correct exactly because nothing is dispatched after it fires.
221/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
222/// that parks for an interrupted task must go on to run other tasks
223/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
224/// reusing the daemon-wide one.
225#[derive(Debug, Clone, Default)]
226pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
227
228impl Pause {
229    /// A pause nobody has asked for yet.
230    #[must_use]
231    pub fn new() -> Self {
232        Self::default()
233    }
234
235    /// Ask the run to park at its next node boundary. Idempotent.
236    pub fn park(&self) {
237        self.0.store(true, Ordering::SeqCst);
238    }
239
240    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
241    /// fold into the run's own `park` event - so an operator reading the run
242    /// later knows this was a deliberate interrupt rather than a shutdown or
243    /// a binary swap. The first reason recorded wins; a park already in
244    /// flight is not relabelled by a second, unrelated request.
245    pub fn park_because(&self, reason: impl Into<String>) {
246        self.park_for(ParkCause::Interrupt {
247            reason: reason.into(),
248        });
249    }
250
251    /// [`Pause::park`], recording the structured cause. The first cause
252    /// recorded wins, like [`Pause::park_because`].
253    pub fn park_for(&self, cause: ParkCause) {
254        let mut reason_guard = self
255            .1
256            .lock()
257            .unwrap_or_else(std::sync::PoisonError::into_inner);
258        if reason_guard.is_none() {
259            *reason_guard = Some(cause);
260        }
261        drop(reason_guard);
262        self.park();
263    }
264
265    /// Has a park been asked for?
266    #[must_use]
267    pub fn parked(&self) -> bool {
268        self.0.load(Ordering::SeqCst)
269    }
270
271    /// Why the park was asked for, when the caller used [`Pause::park_because`].
272    #[must_use]
273    pub fn reason(&self) -> Option<String> {
274        self.cause().map(|c| c.label())
275    }
276
277    /// The structured cause, when one was recorded.
278    #[must_use]
279    pub fn cause(&self) -> Option<ParkCause> {
280        self.1
281            .lock()
282            .unwrap_or_else(std::sync::PoisonError::into_inner)
283            .clone()
284    }
285}
286
287/// Drives one run.
288pub struct Runner {
289    /// Run state; public so the CLI can report on it.
290    pub state: RunState,
291    roles: ResolvedRoles,
292    sem: Arc<Semaphore>,
293    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
294    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
295    /// this is never the same handle as `interrupt`.
296    pause: Pause,
297    /// Set when `magi serve`'s interrupt scheduler wants this specific run
298    /// parked at its next node boundary, to let a task marked
299    /// [`crate::queue::Task::interrupt`] run alone before this one carries
300    /// on. Unlike `pause`, a fresh, unshared handle per run - see
301    /// [`Runner::watch_interrupt`].
302    interrupt: Pause,
303}
304
305/// Where the branch's own commits start: its merge base with the base branch
306/// as the remote has it now, else with the recorded `base_commit`. A branch
307/// rebased onto a base that moved past `base_commit` would otherwise count
308/// the base's commits as its own under `base_commit..branch`.
309async fn review_base(
310    repo: &Path,
311    remote: &str,
312    base_branch: &str,
313    base_commit: &str,
314    branch: &str,
315) -> String {
316    review_base_checked(repo, remote, base_branch, base_commit, branch)
317        .await
318        .0
319}
320
321/// [`review_base`] plus whether the base was read from a freshly fetched
322/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
323/// never older than `base_commit`'s view of the base), but the answer is then
324/// not trusted to rewrite a pull request's title.
325async fn review_base_checked(
326    repo: &Path,
327    remote: &str,
328    base_branch: &str,
329    base_commit: &str,
330    branch: &str,
331) -> (String, bool) {
332    let tracking = format!("{remote}/{base_branch}");
333    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
334    if git::rev_exists(repo, &tracking).await
335        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
336        && !mb.is_empty()
337    {
338        return (mb, fresh);
339    }
340    let mb = git::merge_base(repo, base_commit, branch)
341        .await
342        .ok()
343        .filter(|mb| !mb.is_empty())
344        .unwrap_or_else(|| base_commit.to_owned());
345    (mb, false)
346}
347
348/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
349/// when git cannot say or finds nothing: a stale list is better than a wrong
350/// or empty one.
351pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
352    if !is_review_run(state) {
353        return;
354    }
355    let base = review_base(
356        &state.repo,
357        &state.config.merge.remote,
358        &state.base_branch,
359        &state.base_commit,
360        branch,
361    )
362    .await;
363    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
364        && !subjects.is_empty()
365        && state.reviewed_commits.as_ref() != Some(&subjects)
366    {
367        state.reviewed_commits = Some(subjects);
368        state.save().ok();
369    }
370}
371
372/// Subjects of the base's commits between the recorded start and the branch's
373/// merge base: what a stale `base_commit..branch` would have mistaken for the
374/// branch's own work.
375async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
376    let (base, trusted) = review_base_checked(
377        &state.repo,
378        &state.config.merge.remote,
379        &state.base_branch,
380        &state.base_commit,
381        branch,
382    )
383    .await;
384    if !trusted {
385        return None;
386    }
387    git::subjects(&state.repo, &state.base_commit, &base)
388        .await
389        .ok()
390}
391
392/// May an adopted pull request's title be replaced with `computed`? Only when
393/// it is empty, magi's own shape, or a base commit's subject that leaked in;
394/// a title a person wrote stays. Never when `computed` is itself a leak.
395pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
396    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
397    if is_leak(computed) {
398        return false;
399    }
400    let cur = current.trim();
401    cur.is_empty()
402        || cur.starts_with(REVIEW_PROMPT_OPENING)
403        || cur.starts_with("chore: land candidate")
404        || cur.starts_with("magi: candidate")
405        || is_leak(cur)
406}
407
408/// The commit a run branches from: the base branch as the remote has it.
409///
410/// Two failures this replaces. A run used to branch off `HEAD` and so refused
411/// to start on a dirty tree, which made `magi serve` decline every task for as
412/// long as the operator had work in progress - most of the time. Branching off
413/// the *local* base branch fixed that and introduced a worse one: `land` merges
414/// the winner on GitHub, nothing updates the local ref, and the next run
415/// branches off a base missing everything the previous runs landed. Two tasks
416/// in a row from a phone would have had the second silently re-implementing
417/// against stale code and opening a pull request that reverted the first.
418///
419/// Only refs move here - no checkout, no local branch, no merge - so it is safe
420/// with uncommitted work in the tree. A machine with no network still starts:
421/// the fetch may fail and the local tip is used with a warning, because
422/// refusing to run offline is a worse failure than running against a base the
423/// operator can see for themselves.
424///
425/// One function, called by both entry points. Two answers to "where does a run
426/// branch from" is the kind of drift nobody notices until a diff is wrong.
427/// Bring the local `branch` in line with `<remote>/<branch>` before a review
428/// checks it out.
429///
430/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
431/// anything other than plain `git push` from this checkout (a jj colocated
432/// workspace, another clone) moves only the remote-tracking ref - so the local
433/// one can be a stale placeholder. It moves only when local is behind the remote or is an
434/// empty placeholder that diverged from it; unpushed local work is kept, and a real
435/// divergence is refused rather than guessed at.
436async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
437    let tracking = format!("{remote}/{branch}");
438    let fetched = git::fetch(repo, remote, branch).await;
439    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
440    let local_exists = git::branch_exists(repo, branch).await?;
441    if !fresh {
442        if !local_exists {
443            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
444        }
445        tracing::warn!(
446            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
447        );
448        return Ok(());
449    }
450    let remote_sha = git::rev_parse(repo, &tracking).await?;
451    if !local_exists {
452        git::git(repo, &["branch", branch, &tracking]).await?;
453        return Ok(());
454    }
455    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
456    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
457        return Ok(());
458    }
459    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
460        // Diverged. `reconcile` settles it only when it can prove nothing is
461        // lost: a local tip that is the remote's change rebased is pushed over
462        // it (lease pinned to the tip read here), a tip whose every extra
463        // commit is empty is a placeholder the remote's work replaced, and
464        // anything else is two different changes - a question for a person.
465        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
466            .await?
467        {
468            crate::reconcile::Reconciliation::Pushed => {
469                tracing::warn!(
470                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
471                    short(&local_sha),
472                    short(&remote_sha)
473                );
474                return Ok(());
475            }
476            crate::reconcile::Reconciliation::Placeholder => {}
477            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
478        }
479    }
480    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
481    if !out.ok() {
482        bail!(
483            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
484            short(&local_sha),
485            short(&remote_sha),
486            out.stderr
487        );
488    }
489    tracing::warn!(
490        "local `{branch}` was stale: fast-forwarded {} -> {}",
491        short(&local_sha),
492        short(&remote_sha)
493    );
494    Ok(())
495}
496
497async fn resolve_base(
498    repo: &Path,
499    base_branch: &str,
500    remote: &str,
501    coordination: Option<&crate::config::Coordination>,
502) -> Result<crate::run::FetchedBase> {
503    let _lease = crate::repo_lock::SeatLease::operation_with(
504        repo,
505        coordination,
506        &crate::repo_lock::WaitPolicy::current(),
507    )
508    .await?;
509    let tracking = format!("{remote}/{base_branch}");
510    let fetched = git::fetch(repo, remote, base_branch).await;
511    if let Ok(out) = &fetched
512        && out.ok()
513        && git::rev_exists(repo, &tracking).await
514    {
515        return Ok(crate::run::FetchedBase {
516            remote: remote.to_owned(),
517            branch: base_branch.to_owned(),
518            commit: git::rev_parse(repo, &tracking).await?,
519            fetched_at: jiff::Timestamp::now(),
520        });
521    }
522    let why = match &fetched {
523        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
524        Ok(_) => format!("{remote} has no {base_branch}"),
525        Err(e) => e.to_string(),
526    };
527    // No fallback to the local branch: it may be behind, and branching off an
528    // old commit is the stale-checkout bug this check exists to prevent.
529    bail!(
530        "cannot read {tracking} ({why}); refusing to branch off the local \
531         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
532         base / remote in magi.toml. This is launcher preparation: check the \
533         launcher's network, Git access and repository coordination before \
534         retrying"
535    )
536}
537
538/// Outcome of the shared fixer chain, before caller-owned stop policy.
539enum FixStep {
540    Resource,
541    Recorded { report_lost: bool },
542}
543
544/// Exclusive claim shared by targeted repairs and repository reassignment.
545/// Held before asynchronous fix preflight and released on every return or panic.
546///
547/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
548/// manual `magi fix` invocations against the same run are otherwise
549/// invisible to each other and would race to remove and recreate the same
550/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
551/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
552/// which is only ever reclaimed later, out of band, by
553/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
554/// `magi fix` invocation is not necessarily running under either of those, so
555/// nothing would ever sweep a lock a killed or crashed process left behind.
556/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
557/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
558/// lease use: an unreadable or unparsable pid, or a liveness query the
559/// platform cannot answer, reads as alive and the lock is left in place.
560pub(crate) struct FixClaim {
561    path: PathBuf,
562}
563
564impl FixClaim {
565    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
566        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
567        let path = dir.join("fix.lock");
568        let retry = crate::lock_file::Retry::new(None);
569        match Self::create(&path, retry) {
570            Ok(claim) => Ok(claim),
571            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
572                if Self::reclaim_if_dead(&path) {
573                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
574                } else {
575                    bail!(
576                        "another repair or `magi fix` is already running for this run ({} exists)",
577                        path.display()
578                    )
579                }
580            }
581            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
582        }
583    }
584
585    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
586        let mut f = retry.create(path)?;
587        use std::io::Write as _;
588        // Read back by `reclaim_if_dead` on a later, stuck invocation.
589        writeln!(f, "{}", std::process::id())?;
590        Ok(Self {
591            path: path.to_owned(),
592        })
593    }
594
595    /// True if the lock named a process confirmed dead, in which case it was
596    /// also removed. Never true on an unreadable file, an unparsable pid, or
597    /// a liveness query the platform cannot answer — see this type's own doc.
598    fn reclaim_if_dead(path: &Path) -> bool {
599        let dead = std::fs::read_to_string(path)
600            .ok()
601            .and_then(|body| body.trim().parse::<u32>().ok())
602            .is_some_and(|pid| !crate::proc::pid_alive(pid));
603        dead && std::fs::remove_file(path).is_ok()
604    }
605}
606
607impl Drop for FixClaim {
608    fn drop(&mut self) {
609        let _ = std::fs::remove_file(&self.path);
610    }
611}
612
613#[doc(hidden)]
614pub struct ExecutionLeaseGuard {
615    _lease: crate::driver::ExecutionLease,
616}
617
618#[doc(hidden)]
619pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
620    Ok(ExecutionLeaseGuard {
621        _lease: crate::driver::maintenance(home, run_id)?,
622    })
623}
624
625/// Holds the mutable runner as well as its durable lease: cancellation must
626/// clear both copies of ownership, including state a caller may save later.
627struct DriverExecution<'a> {
628    runner: &'a mut Runner,
629    driver: crate::driver::DriverGuard,
630}
631
632impl Drop for DriverExecution<'_> {
633    fn drop(&mut self) {
634        self.driver.release_local(&mut self.runner.state);
635    }
636}
637
638fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
639    if let Some(startup) = &mut state.startup {
640        startup.stage = stage.to_owned();
641    }
642    state.save()
643}
644
645/// Keep a reservation visible as blocked until startup finishes. A killed process
646/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
647struct StartupGuard {
648    id: String,
649    armed: bool,
650}
651
652impl StartupGuard {
653    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
654        state.startup = Some(crate::run::Startup {
655            kind: kind.to_owned(),
656            branch: branch.map(str::to_owned),
657            stage: "reserved".to_owned(),
658            complete: false,
659            failure: None,
660        });
661        state.status = RunStatus::Blocked;
662        state.reserve()?;
663        Ok(Self {
664            id: state.id.clone(),
665            armed: true,
666        })
667    }
668
669    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
670        startup_stage(state, stage)
671    }
672
673    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
674        let result = result.and_then(|()| {
675            state.startup.as_mut().expect("reserved startup").complete = true;
676            state.save()
677        });
678        self.armed = false;
679        match result {
680            Ok(()) => Ok(()),
681            Err(error) => {
682                let startup = state.startup.as_mut().expect("reserved startup");
683                startup.complete = false;
684                startup.failure = Some(format!("{error:#}"));
685                let context = crate::run::StartupFailure {
686                    run: state.id.clone(),
687                    stage: startup.stage.clone(),
688                };
689                // Repository assets may remain. Never infer that a failed startup
690                // is safe to resume or that an earlier owner has been restored.
691                state.status = RunStatus::Failed;
692                state.driver_exited = true;
693                state.event(
694                    "startup-failed",
695                    format!("{context}: {error:#}; retained assets require inspection"),
696                );
697                if let Err(save) = state.save() {
698                    tracing::warn!(
699                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
700                        state.id
701                    );
702                }
703                Err(error.context(context))
704            }
705        }
706    }
707}
708
709impl Drop for StartupGuard {
710    fn drop(&mut self) {
711        if self.armed
712            && let Ok(mut state) = RunState::load(&self.id)
713        {
714            state.status = RunStatus::Blocked;
715            state.driver_exited = true;
716            if let Some(startup) = &mut state.startup {
717                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
718            }
719            state.event(
720                "startup-interrupted",
721                "startup did not finish; inspect retained assets before recovery",
722            );
723            if let Err(error) = state.save() {
724                tracing::error!(
725                    "could not record interrupted startup {}: {error:#}",
726                    self.id
727                );
728            }
729        }
730    }
731}
732
733impl Runner {
734    /// A queue-side failure after construction must not strand an unexecuted run.
735    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
736        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
737            return error;
738        }
739        if let Some(startup) = &mut self.state.startup {
740            startup.stage = stage.to_owned();
741        } else {
742            // A resumed run already has execution history: do not rewrite it.
743            return error;
744        }
745        StartupGuard {
746            id: self.state.id.clone(),
747            armed: true,
748        }
749        .finish(&mut self.state, Err(error))
750        .expect_err("startup failed")
751    }
752
753    /// Start a fresh run against `repo`.
754    pub async fn start(
755        repo: &Path,
756        instruction: String,
757        config: Config,
758        origin: Origin,
759    ) -> Result<Self> {
760        Self::start_naming(repo, instruction, "", config, origin).await
761    }
762
763    /// [`Runner::start`] for a queued task. Titles and instructions never
764    /// select implementation sources. The title argument is retained for callers.
765    pub async fn start_naming(
766        repo: &Path,
767        instruction: String,
768        _also_scan: &str,
769        config: Config,
770        origin: Origin,
771    ) -> Result<Self> {
772        let repo = git::toplevel(repo).await?;
773        let missing = agent::missing_programs(&config.agents);
774        if !missing.is_empty() {
775            bail!(
776                "these agent programs are not on PATH: {}. Fix the roster in \
777                 magi.toml or install them.",
778                missing.join(", ")
779            );
780        }
781        let base_branch =
782            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
783                .await?;
784        let fetched_base = resolve_base(
785            &repo,
786            &base_branch,
787            &config.merge.remote,
788            config.coordination.as_ref(),
789        )
790        .await?;
791        let base_commit = fetched_base.commit.clone();
792        let roles = config.resolve_roles()?;
793        let max_parallel = config.graph.max_parallel.max(1);
794        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
795        // Capture task identity and repository assignment before the first
796        // save, so publication scope survives crashes and later task moves.
797        state.fetched_base = Some(fetched_base);
798        state.set_origin(origin)?;
799        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
800        state.status = RunStatus::Prep;
801        state.event("start", format!("run {} created", state.id));
802        startup.finish(&mut state, Ok(()))?;
803        Ok(Self {
804            state,
805            roles,
806            sem: Arc::new(Semaphore::new(max_parallel)),
807            pause: Pause::new(),
808            interrupt: Pause::new(),
809        })
810    }
811
812    /// Open a review-only run against work that already exists on `branch`.
813    ///
814    /// The expensive half of the graph is the implement wave — measured at
815    /// 111 and 134 internal tool-loop turns on this repository, against a
816    /// handful for a judge or a reviewer. The cheap half is worth running on
817    /// hand-written work too, and there was no way to reach it.
818    ///
819    /// No new state and no schema change are needed: a run with **one** viable
820    /// candidate and a tally already decided degrades `execute` to exactly
821    /// review → gate → merge, because `judge` skips a single-candidate field,
822    /// `deliberate` has fewer than two first choices to reconcile, `vote`
823    /// returns early, `tally` is already present and `fold_losers` has no
824    /// losers. Resuming such a run therefore does the right thing as well.
825    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
826        Self::review_taking_over(repo, branch, config, None, origin).await
827    }
828
829    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
830    /// at the same task still has `branch` checked out, its worktree is
831    /// released first if that is safe (see [`crate::handover`]), and the
832    /// review refuses with the reason if it is not. `None` is a hand-run
833    /// review: it has no earlier attempts, so only a worktree of a dead run
834    /// magi recorded itself can be released.
835    pub async fn review_taking_over(
836        repo: &Path,
837        branch: &str,
838        config: Config,
839        takeover: Option<crate::handover::Takeover>,
840        origin: Origin,
841    ) -> Result<Self> {
842        let repo = git::toplevel(repo).await?;
843        let missing = agent::missing_programs(&config.agents);
844        if !missing.is_empty() {
845            bail!(
846                "these agent programs are not on PATH: {}. Fix the roster in \
847                 magi.toml or install them.",
848                missing.join(", ")
849            );
850        }
851        let base_branch =
852            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
853                .await?;
854        if base_branch == branch {
855            bail!("`{branch}` is the base branch; there is nothing to review against");
856        }
857        let fetched_base = resolve_base(
858            &repo,
859            &base_branch,
860            &config.merge.remote,
861            config.coordination.as_ref(),
862        )
863        .await?;
864        let base_commit = fetched_base.commit.clone();
865
866        let roles = config.resolve_roles()?;
867        let max_parallel = config.graph.max_parallel.max(1);
868        let mut state = RunState::new(
869            repo.clone(),
870            base_branch,
871            base_commit.clone(),
872            format!("Review the work already on branch `{branch}`."),
873            config,
874        );
875        state.fetched_base = Some(fetched_base);
876        state.set_origin(origin)?;
877        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
878        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
879        let opened = async {
880            startup.stage(&mut state, "handover")?;
881
882            // Released before anything else touches the branch: a stale local
883            // branch is moved with `git branch -f`, which git refuses while an
884            // earlier attempt's worktree still has it checked out. Everything
885            // after this point that can fail puts the old run back.
886            // A hand-run review has no task, hence no earlier attempts, but a
887            // worktree of a dead run magi made may still be released.
888            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
889                earlier: Vec::new(),
890                home: crate::run::home(),
891                choice: None,
892                task_instruction: None,
893            });
894            let wait = repository_wait(&state, None);
895            let coordination_config = state.config.coordination.clone();
896            let coordination =
897                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
898                    .await?;
899            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
900            if let Some(released) = &released {
901                state.event(
902                    "release",
903                    format!(
904                        "took `{branch}` over from run {}: its worktree was released: {}",
905                        crate::run::short_of(&released.old_id),
906                        released.audit
907                    ),
908                );
909            }
910            let opened = async {
911                startup.stage(&mut state, "review-preflight")?;
912                // The owner's answer to an earlier divergence question is applied
913                // here: after the release (git will not move a checked-out branch)
914                // and before the sync that would otherwise ask again.
915                state.foreign_checkout = crate::handover::preflight_review(
916                    &repo,
917                    branch,
918                    &takeover.home,
919                    &state.config.merge.remote,
920                )
921                .await?;
922                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
923                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
924                }
925                if let Some(choice) = takeover.choice.as_ref()
926                    && let Err(e) =
927                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
928                            .await
929                {
930                    return Err(e.context("applying the owner's answer about the diverged branch"));
931                }
932                // An earlier attempt of this task that published the task head, and
933                // whose work is the branch under review, hands that head over: the
934                // review run updates the same pull request. Without one (a legacy
935                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
936                // own head and its own open pull request is adopted as before.
937                for id in takeover.earlier.iter().rev() {
938                    if let Ok(old) = RunState::load_under(id, &takeover.home)
939                        && let Some(head) = old.pr_head.clone()
940                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
941                    {
942                        state.pr_head = Some(head);
943                        break;
944                    }
945                }
946                drop(coordination);
947                startup.stage(&mut state, "open-review")?;
948                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
949            }
950            .await;
951            if opened.is_err()
952                && let Some(released) = &released
953            {
954                // Restoration is ownership checked and best effort. Keep the original
955                // startup cause even if reacquiring coordination is no longer possible.
956                match crate::repo_lock::SeatLease::operation_with(
957                    &repo,
958                    coordination_config.as_ref(),
959                    &wait,
960                )
961                .await
962                {
963                    Ok(_coordination) => {
964                        released.restore(&repo, branch).await;
965                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
966                            .map(|old| {
967                                format!(
968                                    "predecessor released_to={:?}; candidate path exists={}",
969                                    old.released_to,
970                                    old.candidates.iter().any(|c| {
971                                        c.branch == branch && c.worktree.exists()
972                                    }),
973                                )
974                            })
975                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
976                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
977                    }
978                    Err(error) => {
979                        tracing::warn!(
980                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
981                            state.id
982                        );
983                        state.event(
984                            "startup-restore",
985                            format!("restoration not attempted: {error:#}"),
986                        );
987                    }
988                }
989            }
990            opened
991        }
992        .await;
993        startup.finish(&mut state, opened)?;
994        Ok(Self {
995            state,
996            roles,
997            sem: Arc::new(Semaphore::new(max_parallel)),
998            pause: Pause::new(),
999            interrupt: Pause::new(),
1000        })
1001    }
1002
1003    /// Recover exactly the operator-selected public implementation, without touching old sources.
1004    pub async fn recover_pr(
1005        repo: &Path,
1006        task: &str,
1007        selection: crate::pr_recovery::Selection,
1008        mut config: Config,
1009    ) -> Result<Self> {
1010        selection.configure(&mut config)?;
1011        let assignment = crate::run::task_assignment_for(task)?;
1012        match crate::queue::Queue::open().get(task) {
1013            Ok(owner) => selection.check_retained_task(&owner, &crate::run::home())?,
1014            Err(_) => selection.check_task_assignment(task, &selection.instruction, assignment)?,
1015        }
1016        let base_branch =
1017            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1018                .await?;
1019        let fetched_base = resolve_base(
1020            repo,
1021            &base_branch,
1022            &config.merge.remote,
1023            config.coordination.as_ref(),
1024        )
1025        .await?;
1026        let base_commit = fetched_base.commit.clone();
1027        selection
1028            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1029            .await?;
1030        Box::pin(selection.verify_source(repo)).await?;
1031        if let Some(proof) = &selection.source_proof {
1032            anyhow::ensure!(
1033                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1034                "source rebase base is outside the fetched landing base"
1035            );
1036        }
1037        let roles = config.resolve_roles()?;
1038        let max_parallel = config.graph.max_parallel.max(1);
1039        let mut state = RunState::new(
1040            repo.to_path_buf(),
1041            base_branch,
1042            base_commit.clone(),
1043            selection.instruction.clone(),
1044            config,
1045        );
1046        state.fetched_base = Some(fetched_base);
1047        state.set_origin(crate::run::Origin::queue(task))?;
1048        state.pr_head = Some(selection.branch.clone());
1049        state.pr_recovery = Some(selection.clone());
1050        state.stale_pr_recovery = selection.disposition
1051            == Some(crate::pr_recovery::Disposition::Land)
1052            && !git::is_ancestor(repo, &base_commit, &selection.head).await
1053            && crate::queue::Queue::open().get(task).is_ok_and(|task| {
1054                task.execution_runs().iter().any(|id| {
1055                    RunState::load(id).is_ok_and(|old| {
1056                        old.status == RunStatus::Ready
1057                            && !old.released()
1058                            && old.retired_to.is_none()
1059                            && old.pr_taken_over_by.is_none()
1060                            && task.assignment_accepts(&old)
1061                            && old.pr_branch() == Some(selection.branch.as_str())
1062                            && old
1063                                .pr
1064                                .as_ref()
1065                                .is_some_and(|pr| pr.state == "open" && pr.url == selection.url)
1066                    })
1067                })
1068            });
1069        if state.stale_pr_recovery {
1070            state.event("recovery", "stale public PR: a content conflict requires an explicit base-conflict repair grant");
1071        }
1072        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1073    }
1074
1075    async fn open_selected(
1076        repo: &Path,
1077        mut state: RunState,
1078        roles: ResolvedRoles,
1079        max_parallel: usize,
1080        base_commit: String,
1081        selection: crate::pr_recovery::Selection,
1082    ) -> Result<Self> {
1083        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1084        let opened = async {
1085            startup.stage(&mut state, "predecessors")?;
1086            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1087            startup.stage(&mut state, "open-selected")?;
1088            let branch = state.branch_for('A');
1089            let wait = repository_wait(&state, None);
1090            let prepared = async {
1091                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1092                git::git(repo, &["branch", &branch, selection.source()]).await?;
1093                drop(coordination);
1094                anyhow::Ok(())
1095            }
1096            .await;
1097            prepared?;
1098            state.event(
1099                "recovery",
1100                format!(
1101                    "selected implementation {} for {} (public lease {})",
1102                    selection.source(),
1103                    selection.url,
1104                    selection.head
1105                ),
1106            );
1107            let takeover = crate::handover::Takeover {
1108                earlier: Vec::new(),
1109                home: crate::run::home(),
1110                choice: None,
1111                task_instruction: Some(selection.instruction.clone()),
1112            };
1113            state.save()?;
1114            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1115        }
1116        .await;
1117        startup.finish(&mut state, opened)?;
1118        Ok(Self {
1119            state,
1120            roles,
1121            sem: Arc::new(Semaphore::new(max_parallel)),
1122            pause: Pause::new(),
1123            interrupt: Pause::new(),
1124        })
1125    }
1126
1127    /// What the newest earlier attempt that reviewed `branch` leaves for this
1128    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1129    /// no earlier attempts. Reads the earlier record only: ownership of its
1130    /// worktree and branch is [`crate::handover`]'s business.
1131    async fn inherit(
1132        repo: &Path,
1133        branch: &str,
1134        base_commit: &str,
1135        takeover: &crate::handover::Takeover,
1136    ) -> Option<crate::recovery::RecoveryRecord> {
1137        use crate::recovery::{Relation, assess};
1138        let newest = takeover.earlier.last()?;
1139        let mut chosen = None;
1140        for id in takeover.earlier.iter().rev() {
1141            if let Ok(old) = RunState::load_under(id, &takeover.home)
1142                && !old.reviews.is_empty()
1143                && (old.winner().is_some_and(|w| w.branch == branch)
1144                    || old.pr_head.as_deref() == Some(branch))
1145            {
1146                chosen = Some(old);
1147                break;
1148            }
1149        }
1150        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1151            .await
1152            .unwrap_or_default();
1153        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1154            Some(last) if last.head == tip => Relation::Same,
1155            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1156            _ => Relation::Diverged,
1157        };
1158        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1159        Some(assess(from, chosen.as_ref(), base_commit, relation))
1160    }
1161
1162    /// The half of [`Runner::review_taking_over`] that can fail after an
1163    /// earlier attempt's worktree was released.
1164    async fn open_review(
1165        repo: &Path,
1166        branch: &str,
1167        state: &mut RunState,
1168        base_commit: String,
1169        takeover: &crate::handover::Takeover,
1170    ) -> Result<()> {
1171        startup_stage(state, "review-sync")?;
1172        let wait = repository_wait(state, None);
1173        let _coordination = coordinate_operation(state, repo, &wait).await?;
1174        if state.foreign_checkout.is_some() {
1175            // Never reconcile or force-move a ref checked out by the operator.
1176            if state.pr_head.is_none() {
1177                state.pr_head = Some(branch.to_owned());
1178            }
1179        } else if state.pr_recovery.is_none() {
1180            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1181        }
1182        // The commit subjects are the closest thing to a task statement that
1183        // existing work carries, and the reviewers are told as much.
1184        let start = review_base(
1185            repo,
1186            &state.config.merge.remote,
1187            &state.base_branch,
1188            &base_commit,
1189            branch,
1190        )
1191        .await;
1192        let log = git::log_oneline(repo, &start, branch)
1193            .await
1194            .unwrap_or_default();
1195        let log_text = if log.trim().is_empty() {
1196            "(no commit messages)"
1197        } else {
1198            log.trim()
1199        };
1200        let mut instruction = format!(
1201            "Review the work already on branch `{branch}`. There is no task \
1202             statement: what the change claims to do is whatever its commits \
1203             say.\n\n{log_text}"
1204        );
1205        // A retry of a task whose earlier attempt left reviews behind carries
1206        // that attempt's evidence, and the task's own statement with it: the
1207        // completion criteria are the task's, not whatever the commits claim.
1208        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1209            if let Some(task) = takeover
1210                .task_instruction
1211                .as_deref()
1212                .filter(|t| !t.trim().is_empty())
1213                && rec.reviewed_head.is_some()
1214            {
1215                instruction = format!(
1216                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1217                    task.trim()
1218                );
1219                rec.criteria_inherited = true;
1220            }
1221            state.event("recovery", rec.summary());
1222            state.recovery = Some(rec);
1223        }
1224        if let Some(selected) = &state.pr_recovery {
1225            instruction = selected.instruction.clone();
1226        }
1227        state.task_instruction = takeover.task_instruction.clone();
1228        state.instruction = instruction;
1229        state.reviewed_commits = Some(
1230            git::subjects(repo, &start, branch)
1231                .await
1232                .unwrap_or_default(),
1233        );
1234
1235        // A takeover must not forget a hold that a previous review observed,
1236        // even if repairs have since removed it from the branch.
1237        for id in &takeover.earlier {
1238            if let Ok(old) = RunState::load_under(id, &takeover.home)
1239                && old.repo == state.repo
1240                && (old.pr_head.as_deref() == Some(branch)
1241                    || old.winner().is_some_and(|w| w.branch == branch))
1242            {
1243                for hold in old.branch_owner_holds {
1244                    if !state.branch_owner_holds.contains(&hold) {
1245                        state.event(
1246                            "approval-policy",
1247                            format!(
1248                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1249                                hold.control.key(),
1250                                hold.file,
1251                                hold.head
1252                            ),
1253                        );
1254                        state.branch_owner_holds.push(hold);
1255                    }
1256                }
1257            }
1258        }
1259        // Select the actual review tip before observing owner policy. A foreign
1260        // checkout can lag its remote descendant, and repairs must not erase
1261        // holds introduced only on that selected commit.
1262        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1263            let tracking = format!("{}/{branch}", state.config.merge.remote);
1264            // A surviving tracking ref is not evidence that the remote still
1265            // offers this tip. Adopt it only after a successful fetch here.
1266            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1267            let mut head = checkout.synced_head.clone();
1268            if matches!(fetched, Ok(out) if out.ok()) {
1269                let remote = git::rev_parse(repo, &tracking).await?;
1270                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1271                    head = remote;
1272                }
1273            }
1274            head
1275        } else {
1276            git::rev_parse(repo, branch).await?
1277        };
1278        state.observe_branch_owner_holds(&reviewed_head).await;
1279
1280        // An attached worktree, so the fixer's commits land on the branch under
1281        // review rather than on a detached head nobody will look at again.
1282        let worktree = state.worktree_root().join("under-review");
1283        if let Some(parent) = worktree.parent() {
1284            tokio::fs::create_dir_all(parent).await.ok();
1285        }
1286        let path = worktree.to_string_lossy().to_string();
1287        let review_branch = if state.foreign_checkout.is_some() {
1288            let shadow = format!("magi/{}/review", state.short());
1289            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1290            shadow
1291        } else {
1292            branch.to_owned()
1293        };
1294        startup_stage(state, "review-checkout")?;
1295        git::git(repo, &["worktree", "add", &path, &review_branch])
1296            .await
1297            .with_context(|| {
1298                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1299            })?;
1300
1301        startup_stage(state, "worktree-setup")?;
1302        let setup = match ensure_setup_config(state, repo).await {
1303            Ok(()) => {
1304                worktree_setup::prepare_with(
1305                    &state.config,
1306                    repo,
1307                    &worktree,
1308                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1309                )
1310                .await
1311            }
1312            Err(e) => Err(e),
1313        };
1314        if let Err(e) = setup {
1315            git::worktree_remove_clean(repo, &worktree).await.ok();
1316            return Err(e);
1317        }
1318        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1319            .await
1320            .unwrap_or(0);
1321        if commits == 0 {
1322            git::worktree_remove_clean(repo, &worktree).await.ok();
1323            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1324        }
1325        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1326            .await
1327            .map(|f| f.len())
1328            .unwrap_or(0);
1329        if files == 0
1330            && let (Ok(head_tree), Ok(base_tree)) = (
1331                git::tree_of(&worktree, "HEAD").await,
1332                git::tree_of(&worktree, &base_commit).await,
1333            )
1334            && head_tree == base_tree
1335        {
1336            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1337            git::worktree_remove_clean(repo, &worktree).await.ok();
1338            bail!(
1339                "`{branch}` at {} has a tree identical to base {}; this usually means \
1340                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1341                 against `{}/{branch}`) rather than an empty change",
1342                short(&head),
1343                short(&base_commit),
1344                state.config.merge.remote
1345            );
1346        }
1347        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1348            .await
1349            .unwrap_or_default();
1350
1351        state.candidates.push(Candidate {
1352            index: 0,
1353            label: 'A',
1354            // Not an agent id on purpose: nothing in the roster wrote this, and
1355            // the stats tables must not credit anyone with a win for it.
1356            agent: EXISTING_BRANCH.to_owned(),
1357            branch: review_branch,
1358            worktree,
1359            summary: String::new(),
1360            stat,
1361            files,
1362            commits,
1363            empty: false,
1364            failed: None,
1365            verified_noop: None,
1366            duration_ms: 0,
1367            folded: false,
1368        });
1369        state.tally = Some(Tally {
1370            first_choice: BTreeMap::from([('A', 0)]),
1371            borda: BTreeMap::new(),
1372            winner: 'A',
1373            rankings: 0,
1374            unanimous_initial: false,
1375            deliberated: false,
1376            changed_votes: 0,
1377            unanimous_final: false,
1378            tie_break: None,
1379            // No panel sat, so no quorum applies. Zero judges is the correct
1380            // number for work that never competed, and must not be reported as
1381            // a collapsed panel.
1382            judges: 0,
1383            present: 0,
1384            quorum: 0,
1385            met_quorum: true,
1386            uncontested: Some("review-only run: nothing competed".to_owned()),
1387        });
1388        state.status = RunStatus::Reviewing;
1389        state.prep_complete = Some(true);
1390        state.event(
1391            "start",
1392            format!(
1393                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1394                state.id
1395            ),
1396        );
1397        Ok(())
1398    }
1399
1400    /// Authorize one bounded synchronization interval, under the caller's queue task
1401    /// claim and the same owner/execution locks used by run maintenance.
1402    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1403        Self::authorize_base_recovery_request(home, id, task, false, None, None).await
1404    }
1405
1406    /// Authorize a known preparation failure against the inspected evidence.
1407    pub async fn authorize_base_preparation_recovery(
1408        home: &Path,
1409        id: &str,
1410        task: &str,
1411        digest: &str,
1412    ) -> Result<()> {
1413        Self::authorize_base_recovery_request(home, id, task, false, None, Some(digest)).await
1414    }
1415
1416    /// Queue release uses its durable approval generation exactly once.
1417    pub(crate) async fn authorize_base_recovery_from_resumption(
1418        home: &Path,
1419        id: &str,
1420        task: &str,
1421    ) -> Result<()> {
1422        Self::authorize_base_recovery_request(home, id, task, true, None, None).await
1423    }
1424
1425    pub(crate) async fn authorize_base_recovery_control(
1426        home: &Path,
1427        task: &str,
1428        control: &mut crate::base_recovery_control::Transaction,
1429    ) -> Result<()> {
1430        let id = control.request.run.clone();
1431        Self::authorize_base_recovery_request(home, &id, task, false, Some(control), None).await
1432    }
1433
1434    async fn authorize_base_recovery_request(
1435        home: &Path,
1436        id: &str,
1437        task: &str,
1438        resumption: bool,
1439        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1440        terminal_digest: Option<&str>,
1441    ) -> Result<()> {
1442        let _owner = crate::pr_head::owner_lock(home, id)?;
1443        let mut state = RunState::load_under(id, home)?;
1444        crate::pr_head::ensure_owner(&state)?;
1445        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1446        anyhow::ensure!(
1447            queued.execution_runs().last().is_some_and(|run| run == id)
1448                && queued.assignment_accepts(&state)
1449                && queued.status != crate::queue::TaskStatus::Done
1450                && !queued.fresh_start
1451                && queued.review_branch.is_none(),
1452            "run task ownership changed"
1453        );
1454        anyhow::ensure!(
1455            state
1456                .origin
1457                .as_ref()
1458                .and_then(|o| o.task.as_deref())
1459                .is_none_or(|owner| owner == task),
1460            "run belongs to another task"
1461        );
1462        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1463        anyhow::ensure!(
1464            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1465            "run is live or its ownership is unknown"
1466        );
1467        // Judge the previous driver's lease before acquiring our maintenance
1468        // lease. The owner lock excludes new driver claims across both steps.
1469        let _execution = crate::driver::maintenance(home, id)?;
1470        anyhow::ensure!(
1471            state.status.resumable()
1472                && state.released_to.is_none()
1473                && state.retired_to.is_none()
1474                && state.pr_taken_over_by.is_none(),
1475            "run ownership is final"
1476        );
1477        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1478        anyhow::ensure!(
1479            !state.pr_publication_pending
1480                && !crate::handover::landing_checkpoint(&state)
1481                && state.merge_decision.is_none(),
1482            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1483        );
1484        let winner = state.winner().context("run has no retained winner")?;
1485        anyhow::ensure!(
1486            git::is_clean(&winner.worktree).await?,
1487            "retained worktree has uncommitted changes"
1488        );
1489        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1490        anyhow::ensure!(
1491            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1492            "retained worktree does not match the winner branch"
1493        );
1494        if let Some(control) = control.as_ref() {
1495            anyhow::ensure!(
1496                head.starts_with(&control.request.head),
1497                "retained HEAD changed since the owner request"
1498            );
1499            anyhow::ensure!(
1500                state
1501                    .base_sync_recovery
1502                    .stop
1503                    .as_ref()
1504                    .is_none_or(|stop| stop.head == head),
1505                "retained HEAD differs from the recorded stop head; inspect it first"
1506            );
1507        }
1508        anyhow::ensure!(
1509            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1510            "{}",
1511            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1512        );
1513        state.ensure_base_episode();
1514        state.record_base_sync_stop(&head);
1515        let preparation = state.unknown_preparation_stop(&head);
1516        anyhow::ensure!(
1517            state
1518                .base_sync_recovery
1519                .stop
1520                .as_ref()
1521                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted)
1522                || (preparation && !resumption),
1523            "base recovery refused: missing eligible movement-exhaustion or preparation-stop evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1524        );
1525        let fetched =
1526            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1527        anyhow::ensure!(
1528            fetched.ok(),
1529            "cannot authorize base recovery without a fetched base"
1530        );
1531        let approved_tip = git::rev_parse(
1532            &state.repo,
1533            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1534        )
1535        .await?;
1536        let preparation_digest = state.preparation_digest(&head);
1537        anyhow::ensure!(
1538            preparation
1539                || (terminal_digest.is_none()
1540                    && control
1541                        .as_ref()
1542                        .is_none_or(|c| c.request.evidence_digest.is_none())),
1543            "preparation evidence digest does not name an eligible preparation stop"
1544        );
1545        if preparation {
1546            anyhow::ensure!(
1547                crate::daemon::compatible_run_instruction(&state, &queued),
1548                "task instruction does not match the retained run"
1549            );
1550            if let Some(control) = control.as_ref() {
1551                anyhow::ensure!(
1552                    control.request.head == head
1553                        && control.request.evidence_digest.is_some()
1554                        && control.request.evidence_digest == preparation_digest
1555                        && control.request.decision.is_none(),
1556                    "preparation stop requires the full HEAD and current inspected evidence digest"
1557                );
1558            } else {
1559                anyhow::ensure!(
1560                    terminal_digest.is_some() && terminal_digest == preparation_digest.as_deref(),
1561                    "preparation stop requires the current inspected evidence digest"
1562                );
1563            }
1564            let stop = state.base_sync_recovery.stop.as_ref().unwrap();
1565            anyhow::ensure!(
1566                git::is_ancestor(&state.repo, &stop.tip, &approved_tip).await,
1567                "current base does not descend from the stopped base"
1568            );
1569            git::probe_rebase_preparation(
1570                &state,
1571                &head,
1572                &home.join("runs").join(id),
1573                &repository_wait(&state, None),
1574            )
1575            .await?;
1576        }
1577        if let Some(control) = control.as_deref_mut() {
1578            let queue = crate::queue::Queue::at(home.join("queue"));
1579            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1580            if let Some(prior) = state
1581                .base_sync_recovery
1582                .authorizations
1583                .iter()
1584                .find(|a| a.request.as_deref() == Some(&control.key()))
1585            {
1586                anyhow::ensure!(
1587                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1588                    "recovery request was consumed or invalidated; it cannot queue again"
1589                );
1590                return control.enqueue(&queue);
1591            }
1592        }
1593        if resumption {
1594            anyhow::ensure!(
1595                crate::daemon::compatible_run_instruction(&state, &queued),
1596                "resumption instruction does not match the retained run"
1597            );
1598            let approval = queued
1599                .resumption
1600                .as_ref()
1601                .context("no operator resumption")?;
1602            anyhow::ensure!(
1603                approval.instruction == queued.instruction,
1604                "resumption approval does not match the current task instruction"
1605            );
1606            state.authorize_base_sync_resumption(task, approval)?;
1607        } else {
1608            state.authorize_base_sync(task)?;
1609        }
1610        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1611        state
1612            .base_sync_recovery
1613            .authorizations
1614            .last_mut()
1615            .unwrap()
1616            .scope = Some(crate::base_sync_recovery::Scope {
1617            tip: approved_tip,
1618            instruction: queued.instruction.clone(),
1619            episode,
1620            preparation_digest,
1621        });
1622        if let Some(control) = control.as_deref_mut() {
1623            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1624            authorization.request = Some(control.key());
1625            authorization.generation = control.generation();
1626            authorization.decision = control.decision();
1627            authorization.question = control
1628                .request
1629                .decision
1630                .as_ref()
1631                .map(|_| control.request.request.clone());
1632        }
1633        state.event(
1634            "base-recovery",
1635            if preparation {
1636                "owner authorized the proven preparation-stop recovery; remaining budget retained; fresh verification required"
1637            } else {
1638                "owner authorized a bounded base synchronization interval; fresh verification required"
1639            },
1640        );
1641        state.save_under(home)?;
1642        if let Some(control) = control {
1643            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1644        }
1645        Ok(())
1646    }
1647
1648    /// Reopen an existing run.
1649    pub fn resume(id: &str) -> Result<Self> {
1650        let state = RunState::load(id)?;
1651        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1652        if state.startup.as_ref().is_some_and(|s| !s.complete)
1653            || (state.status == RunStatus::Prep
1654                && state.instruction.trim().is_empty()
1655                && state.candidates.is_empty()
1656                && state.prep_complete == Some(false))
1657        {
1658            bail!(
1659                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1660            );
1661        }
1662        crate::pr_head::ensure_owner(&state)?;
1663        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1664            bail!(
1665                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1666            );
1667        }
1668        if let Some(to) = &state.released_to {
1669            bail!(
1670                "run {} cannot be resumed: its worktree was released to run {}",
1671                state.short(),
1672                crate::run::short_of(to)
1673            );
1674        }
1675        let roles = state.config.resolve_roles()?;
1676        if let Some(id) = &state.config.graph.selected_implementer
1677            && state.candidates.iter().any(|c| c.agent != *id)
1678        {
1679            bail!(
1680                "replacement implementer pin does not match the saved candidates; task must stay held"
1681            );
1682        }
1683        let max_parallel = state.config.graph.max_parallel.max(1);
1684        Ok(Self {
1685            state,
1686            roles,
1687            sem: Arc::new(Semaphore::new(max_parallel)),
1688            pause: Pause::new(),
1689            interrupt: Pause::new(),
1690        })
1691    }
1692
1693    /// Walk the graph to a terminal state, skipping nodes already recorded.
1694    ///
1695    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1696    /// the phone - ends here, so this is the one place a run that ended
1697    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1698    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1699    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1700        // Allocate before polling: boxing inside an async wrapper would still
1701        // retain its construction frame while the nested graph is polled.
1702        Box::pin(self.execute_inner(None))
1703    }
1704
1705    pub(crate) async fn execute_sync_only(
1706        &mut self,
1707        request: crate::base_sync_only::Request,
1708    ) -> Result<()> {
1709        Box::pin(self.execute_inner(Some(request))).await
1710    }
1711
1712    async fn execute_inner(
1713        &mut self,
1714        sync_only: Option<crate::base_sync_only::Request>,
1715    ) -> Result<()> {
1716        anyhow::ensure!(
1717            self.state.startup.as_ref().is_none_or(|s| s.complete),
1718            "startup incomplete; inspect retained evidence before explicit recovery"
1719        );
1720        if let Some(selection) = &self.state.pr_recovery
1721            && (selection.source_proof.is_some() || selection.source_run.is_some())
1722        {
1723            Box::pin(selection.verify_source(&self.state.repo)).await?;
1724        }
1725        // Queue claims cover daemon work; this also serializes manual drivers
1726        // consuming a repair answer, including the new review and decision.
1727        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1728            || self.state.land_approval.is_some()
1729            || self.state.merge_decision.is_some()
1730            || !self.state.merge_repairs.is_empty()
1731            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1732        {
1733            let claim = FixClaim::acquire(&self.state.dir())?;
1734            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1735            let disk = RunState::load(&self.state.id)?;
1736            let checkpoint = |s: &RunState| {
1737                (
1738                    s.merge_repairs.len(),
1739                    s.merge_repairs
1740                        .last()
1741                        .map(|r| (r.question.clone(), r.phase)),
1742                    s.land_approval
1743                        .as_ref()
1744                        .map(|a| (a.question.clone(), a.head.clone())),
1745                )
1746            };
1747            if checkpoint(&disk) != checkpoint(&self.state) {
1748                bail!(
1749                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1750                );
1751            }
1752            Some(claim)
1753        } else {
1754            None
1755        };
1756        let base_only = sync_only.is_some();
1757        let mut execution = self.claim_driver(sync_only).await?;
1758        let runner = &mut *execution.runner;
1759        let wait = runner.repository_wait();
1760        // Keep the graph's large future off the callers' stack, including
1761        // standalone task attempts running on a default-sized test thread.
1762        let result = if base_only {
1763            wait.scope(Box::pin(async {
1764                let repo = runner.state.repo.clone();
1765                let result = async {
1766                    let _coordination = runner.coordinate(&repo).await?;
1767                    anyhow::ensure!(
1768                        !runner.pause.parked() && !runner.interrupt.parked(),
1769                        "paused before base synchronization"
1770                    );
1771                    crate::base_sync_only::sync(&mut runner.state).await
1772                }
1773                .await;
1774                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1775                pass.result = match result {
1776                    Ok(outcome) => outcome,
1777                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1778                };
1779                let summary = pass.summary();
1780                runner.state.event("base-sync-only", summary);
1781                runner.state.save()
1782            }))
1783            .await
1784        } else {
1785            wait.scope(Box::pin(runner.execute_graph())).await
1786        };
1787        let result = match result {
1788            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1789                record_repository_block(&mut runner.state, &e);
1790                runner.park_here()?;
1791                Ok(())
1792            }
1793            other => other,
1794        };
1795        execution.driver.finish(&mut runner.state).await?;
1796        let ended = if result.is_err() {
1797            Some({
1798                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1799                if let Err(error) = &result {
1800                    notice.message = format!(
1801                        "Run {} stopped with an error: {}",
1802                        runner.state.id,
1803                        error.to_string().lines().next().unwrap_or("unknown error")
1804                    );
1805                }
1806                notice
1807            })
1808        } else {
1809            crate::notices::run_ended(&runner.state)
1810        };
1811        if let Some(notice) = ended {
1812            crate::notices::raise(notice);
1813        }
1814        result
1815    }
1816
1817    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1818        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1819    }
1820
1821    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1822        let wait = self.repository_wait();
1823        coordinate_operation(&mut self.state, cwd, &wait).await
1824    }
1825
1826    /// Validate ownership and persist the driver claim in one critical section.
1827    async fn claim_driver(
1828        &mut self,
1829        sync_only: Option<crate::base_sync_only::Request>,
1830    ) -> Result<DriverExecution<'_>> {
1831        let owner = match crate::pr_head::owner_lock_wait(
1832            &crate::run::home(),
1833            &self.state.id,
1834            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1835        )
1836        .await
1837        {
1838            Ok(owner) => owner,
1839            Err(error) => {
1840                let detail = format!("worktree maintenance or ownership update: {error:#}");
1841                // Admission did not own run.json: retain this resource outcome
1842                // in memory for queue settlement without overwriting a concurrent
1843                // retirement or publication transaction.
1844                self.state.resource_block = Some(crate::run::ResourceBlock {
1845                    cause: crate::run::ResourceBlockCause::Other,
1846                    node: "start".into(),
1847                    kind: "worktree maintenance".into(),
1848                    detail: detail.clone(),
1849                    at: Timestamp::now(),
1850                });
1851                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1852            }
1853        };
1854        let disk = RunState::load(&self.state.id)?;
1855        crate::pr_head::ensure_owner(&disk)?;
1856        let now = Timestamp::now();
1857        let home = crate::run::home();
1858        let claim = crate::daemon::other_claim_for_run(&home, &disk.id, now)?;
1859        let assessment = disk.assess_liveness_under(&home, claim, now);
1860        // Only proven-live ownership refuses here. Unknown records (legacy runs
1861        // with no claim marker or process identity) fall through to the
1862        // exclusive execution lease taken just below, which is what actually
1863        // keeps a second driver out.
1864        anyhow::ensure!(
1865            assessment.verdict != crate::run::Liveness::Live,
1866            "{}",
1867            assessment.live_driver_refusal()
1868        );
1869        if let Some(to) = &disk.released_to {
1870            bail!(
1871                "run {} cannot continue: its worktree was released to run {}",
1872                self.state.short(),
1873                crate::run::short_of(to)
1874            );
1875        }
1876        anyhow::ensure!(
1877            serde_json::to_value(&disk.base_sync_recovery)?
1878                == serde_json::to_value(&self.state.base_sync_recovery)?,
1879            "base recovery changed since this run was loaded; reload the saved run"
1880        );
1881        anyhow::ensure!(
1882            disk.sync_only_passes == self.state.sync_only_passes,
1883            "base-only synchronization changed since this run was loaded; reload the saved run"
1884        );
1885        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1886        let mut execution = DriverExecution {
1887            runner: self,
1888            driver,
1889        };
1890        // Declare after the execution guard: on any claim error this short
1891        // lock must drop before that guard reloads and releases ownership.
1892        let _owner = owner;
1893        if let Some(request) = sync_only {
1894            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1895            anyhow::ensure!(
1896                request.run == disk.id,
1897                "sync-base-only request targets a different run"
1898            );
1899            let state = &mut execution.runner.state;
1900            let task_entry = state.next_pass_task_entry;
1901            *state = disk;
1902            state.next_pass_task_entry = task_entry;
1903            if state.pending_sync_only().is_some() {
1904                let pass_index = state.passes.len();
1905                let pass = state.sync_only_passes.last_mut().unwrap();
1906                anyhow::ensure!(
1907                    pass.request == request,
1908                    "interrupted base-only synchronization belongs to a different request"
1909                );
1910                pass.pass_index = pass_index;
1911            } else {
1912                let pass = crate::base_sync_only::Pass::new(request, state);
1913                state.sync_only_passes.push(pass);
1914            }
1915            if state.status == RunStatus::Failed {
1916                state.status = RunStatus::Blocked;
1917            }
1918        } else {
1919            anyhow::ensure!(
1920                disk.pending_sync_only().is_none(),
1921                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1922            );
1923            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1924                .await?;
1925        }
1926        let state = &mut execution.runner.state;
1927        // Moving again, so it is no longer parked. Set before the walk rather
1928        // than in `resume`, so every way of re-entering the graph clears it
1929        // and a card cannot claim a run is waiting to be resumed while the
1930        // agents are already working.
1931        state.parked = false;
1932        state.resource_wait = None;
1933        state.resource_block = None;
1934        // Any seat this state still lists as answering belongs to whatever
1935        // process last drove this run — this one included, if it crashed
1936        // mid-wave. Cleared and flushed immediately, before anything else
1937        // runs, so a resume can never show a seat as live when nothing is
1938        // asking it anything yet; the node that actually dispatches the next
1939        // wave repopulates it.
1940        state.clear_active();
1941        // Recorded in the same spot, and flushed together with the clear
1942        // above: this is the pid a reader checks (`RunState::liveness`) when
1943        // no daemon claim exists to answer "is a process still driving this
1944        // run" — a plain `magi run` / `magi review` typed into a terminal
1945        // claims nothing there. Always overwritten, never only-if-absent, so
1946        // a resumed run's stale pid from a previous, possibly-dead process
1947        // can never survive into this one's own report. Unlike
1948        // `clear_active`, this changes on every single `execute()` call, so
1949        // the save below is now unconditional rather than only-if-cleared.
1950        //
1951        // `driver_started_at` is recorded in the same breath, from this same
1952        // pid, so `liveness` can tell a live pid that is genuinely still us
1953        // apart from one the OS has since handed to an unrelated process —
1954        // see that field's own doc for why the pid alone is not enough.
1955        let pid = std::process::id();
1956        state.driver_pid = Some(pid);
1957        state.driver_started_at = crate::proc::process_started_at(pid);
1958        state.driver_exited = false;
1959        state.driver_claimed = Some(true);
1960        state.begin_pass();
1961        execution.driver.bind(state);
1962        state.save()?;
1963        execution.driver.record(state)?;
1964        Ok(execution)
1965    }
1966
1967    /// No conflict checkpoint proves dispatch was never reached. End that
1968    /// consumed generation so an owner can explicitly authorize a fresh one.
1969    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1970        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1971        if let Err(error) = &result
1972            && !error.is::<crate::repo_lock::ResourceBlocked>()
1973            && self
1974                .state
1975                .repair_grants
1976                .last()
1977                .is_some_and(|g| g.conflict.is_none())
1978        {
1979            self.state.repair_grants.last_mut().unwrap().phase =
1980                crate::repair_budget::Phase::Complete;
1981            self.state.status = RunStatus::Blocked;
1982            self.state.save()?;
1983            bail!(
1984                "{error:#}. The consumed reservation ended before editing-seat dispatch. Inspect its scratch tree, then authorize a new base-conflict grant with a new request ID and current --expect-pass {}; the old request will not dispatch again",
1985                self.state.passes.last().map_or(0, |p| p.index)
1986            );
1987        }
1988        result
1989    }
1990
1991    /// A grant owns only these repair attempts. Confirmation reviews cannot
1992    /// create another fixer allowance, and every operation is restart-checkpointed.
1993    async fn execute_granted_repair(&mut self) -> Result<()> {
1994        use crate::repair_budget::{Kind, Phase};
1995        let index = self.state.repair_grants.len() - 1;
1996        let winner = self
1997            .state
1998            .winner()
1999            .cloned()
2000            .context("repair winner missing")?;
2001        loop {
2002            let grant = self.state.repair_grants[index].clone();
2003            match grant.phase {
2004                Phase::Pending => {
2005                    if grant.spent >= grant.receipt.request.rounds {
2006                        self.state.repair_grants[index].phase = Phase::Complete;
2007                        self.state.status = RunStatus::Blocked;
2008                        self.state.save()?;
2009                        return Ok(());
2010                    }
2011                    if grant.spent == 0 && grant.receipt.request.kind == Kind::Review {
2012                        crate::repair_budget::verify_initial_review_grant(&self.state, &grant)
2013                            .await?;
2014                    }
2015                    // Reserve before dispatch. A crash can consume an attempt,
2016                    // but can never duplicate it or reset saved fixer history.
2017                    self.state.repair_grants[index].spent += 1;
2018                    self.state.repair_grants[index].phase = Phase::Fixing;
2019                    self.state.save()?;
2020                    match grant.receipt.request.kind {
2021                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
2022                        Kind::Gate => {
2023                            let failed = self.state.gate.clone();
2024                            let _ = self.gate_fix_round(&winner, &failed).await?;
2025                        }
2026                        Kind::Review => {
2027                            let mut record = self
2028                                .state
2029                                .reviews
2030                                .last()
2031                                .cloned()
2032                                .context("review failure missing")?;
2033                            let round = record.round;
2034                            let step = self.run_fix_round(&winner, &mut record).await?;
2035                            self.state.reviews[round - 1] = record;
2036                            if matches!(step, FixStep::Recorded { report_lost: true }) {
2037                                self.state.repair_grants[index].phase = Phase::Complete;
2038                                self.state.status = RunStatus::Blocked;
2039                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
2040                                self.state.save()?;
2041                                return Ok(());
2042                            }
2043                            if matches!(step, FixStep::Resource) {
2044                                self.stop_for_resource()?;
2045                                return Ok(());
2046                            }
2047                            self.state.save()?;
2048                        }
2049                    }
2050                    if self.resource_halt()? {
2051                        return Ok(());
2052                    }
2053                }
2054                Phase::Fixing => {
2055                    if grant.receipt.request.kind == Kind::BaseConflict {
2056                        self.repair_base_conflict(false).await?;
2057                    }
2058                    // Interrupted fixers may have left source changes or an
2059                    // unpushed commit. Preserve them before fresh assessment.
2060                    let _coordination = self.coordinate(&winner.worktree).await?;
2061                    let rescued = git::rescue_commit(
2062                        &winner.worktree,
2063                        "magi: preserve interrupted granted repair",
2064                    )
2065                    .await?;
2066                    self.state.note_withheld("repair-grant", &rescued.withheld);
2067                    // Fresh checks must supersede even a same-head failure.
2068                    // Archive rather than erase failure evidence or counters.
2069                    self.state
2070                        .verification_history
2071                        .push(crate::run::VerificationEvidence {
2072                            superseded_by: None,
2073                            archived_at: Some(Timestamp::now()),
2074                            fixes_spent: Some(self.state.gate_fixes.len()),
2075                            gate_head: self.state.gate_head.take(),
2076                            gate_ran: std::mem::take(&mut self.state.gate_ran),
2077                            gate: std::mem::take(&mut self.state.gate),
2078                            e2e: self.state.head_e2e.take(),
2079                        });
2080                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
2081                        self.state
2082                            .verification_history
2083                            .push(crate::run::VerificationEvidence {
2084                                superseded_by: None,
2085                                archived_at: Some(Timestamp::now()),
2086                                fixes_spent: Some(self.state.gate_fixes.len()),
2087                                gate_head: None,
2088                                gate_ran: false,
2089                                gate: Vec::new(),
2090                                e2e: Some(e2e),
2091                            });
2092                    }
2093                    self.state.repair_grants[index].review_start = self.state.reviews.len();
2094                    self.state.repair_grants[index].head =
2095                        git::rev_parse(&winner.worktree, "HEAD").await?;
2096                    self.state.repair_grants[index].phase = Phase::Reviewing;
2097                    if grant.receipt.request.kind == Kind::BaseConflict {
2098                        self.state.base_sync_recovery.stop = None;
2099                        if let Some(sync) = &mut self.state.base_sync {
2100                            sync.tip = grant
2101                                .receipt
2102                                .request
2103                                .tip
2104                                .clone()
2105                                .context("repair base tip missing")?;
2106                            sync.conflict = None;
2107                            sync.behind = 0;
2108                        }
2109                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2110                    }
2111                    self.state.save()?;
2112                }
2113                Phase::Reviewing => {
2114                    self.review_loop_pass().await?;
2115                    if self.resource_halt()? {
2116                        return Ok(());
2117                    }
2118                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2119                    let reviewed = (self.state.reviews.len() > grant.review_start)
2120                        .then(|| self.state.reviews.last())
2121                        .flatten();
2122                    let review_passed = reviewed.is_some_and(|r| {
2123                        r.clean
2124                            && r.expected > 0
2125                            && r.answered == r.expected
2126                            && matches!(
2127                                r.e2e_status(),
2128                                E2eStatus::Passed | E2eStatus::NotConfigured
2129                            )
2130                            && ((r.e2e_status() == E2eStatus::NotConfigured
2131                                && self.state.config.verify.e2e.is_empty())
2132                                || r.verified_head.as_deref() == Some(head.as_str()))
2133                    });
2134                    let clean = review_passed && reviewed.is_some_and(|r| r.head == head);
2135                    if !clean {
2136                        let next = if review_passed
2137                            && let Some(r) = reviewed
2138                            && r.head != head
2139                        {
2140                            crate::repair_budget::prove_mechanical_pre_gate_commit(
2141                                &self.state,
2142                                r,
2143                                &head,
2144                            )
2145                            .await
2146                            .map(|_| Some(Phase::Reviewing))
2147                        } else if grant.receipt.request.kind == Kind::Review
2148                            && grant.spent < grant.receipt.request.rounds
2149                        {
2150                            crate::repair_budget::prove_review_target(&self.state, &head)
2151                                .await
2152                                .map(|_| Some(Phase::Pending))
2153                        } else {
2154                            Ok(None)
2155                        };
2156                        let next = match next {
2157                            Ok(next) => next,
2158                            Err(error) => {
2159                                if self.state.repair_grants[index]
2160                                    .checkpoint_provenance_retry(&head, &error)
2161                                {
2162                                    self.state.status = RunStatus::Blocked;
2163                                    self.state.event("repair-grant", format!(
2164                                        "pre-gate provenance unavailable; resume confirmation without spending repair budget: {error:#}"
2165                                    ));
2166                                    self.state.save()?;
2167                                    return Ok(());
2168                                }
2169                                None
2170                            }
2171                        };
2172                        if next == Some(Phase::Reviewing) {
2173                            self.state.repair_grants[index].review_start = self.state.reviews.len();
2174                            self.state.repair_grants[index].head = head;
2175                            self.state.repair_grants[index].phase = Phase::Reviewing;
2176                            self.state.status = RunStatus::Blocked;
2177                            self.state.event(
2178                                "repair-grant",
2179                                "pre-gate changed the reviewed head; resume for fresh review before publication",
2180                            );
2181                            self.state.save()?;
2182                            return Ok(());
2183                        }
2184                        // A confirmation review carries no additional fix budget.
2185                        self.state.repair_grants[index].phase = if next == Some(Phase::Pending) {
2186                            self.state.repair_grants[index].head = head;
2187                            Phase::Pending
2188                        } else {
2189                            Phase::Complete
2190                        };
2191                        self.state.status = RunStatus::Blocked;
2192                        self.state.event(
2193                            "repair-grant",
2194                            "fresh review did not clear the repaired head; no publication",
2195                        );
2196                        self.state.save()?;
2197                        if self.state.repair_grants[index].phase == Phase::Pending {
2198                            continue;
2199                        }
2200                        return Ok(());
2201                    }
2202                    self.state.repair_grants[index].phase = Phase::Gating;
2203                    self.state.save()?;
2204                }
2205                Phase::Gating => {
2206                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2207                    self.state.reconcile_verification_head(&head);
2208                    let wait = self.repository_wait();
2209                    if self
2210                        .state
2211                        .reviews
2212                        .last()
2213                        .is_none_or(|r| r.head != head || !r.clean)
2214                    {
2215                        self.state.status = RunStatus::Blocked;
2216                        self.state.repair_grants[index].phase = Phase::Complete;
2217                        self.state.event(
2218                            "repair-grant",
2219                            "head changed since fresh review; repair held",
2220                        );
2221                        self.state.save()?;
2222                        return Ok(());
2223                    }
2224                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2225                        return Ok(());
2226                    }
2227                    let outcomes = self.run_gate(&winner).await?;
2228                    if verify_inconclusive(&outcomes) {
2229                        return Ok(());
2230                    }
2231                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2232                    if after != head {
2233                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2234                        self.state.repair_grants[index].head = after;
2235                        self.state.repair_grants[index].phase = Phase::Reviewing;
2236                        self.state.status = RunStatus::Blocked;
2237                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2238                        self.state.save()?;
2239                        return Ok(());
2240                    }
2241                    let passed = outcomes.iter().all(CommandOutcome::ok);
2242                    // Follow-up grants owe the same guarded checkout delivery
2243                    // as the conflict repair that introduced the new head.
2244                    if passed
2245                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2246                    {
2247                        return Ok(());
2248                    }
2249                    self.state.repair_grants[index].succeeded = passed;
2250                    self.state.gate = outcomes;
2251                    self.state.gate_ran = true;
2252                    self.state.status = if passed {
2253                        RunStatus::Gating
2254                    } else {
2255                        RunStatus::Blocked
2256                    };
2257                    self.state.repair_grants[index].phase = if !passed
2258                        && grant.receipt.request.kind == Kind::Gate
2259                        && grant.spent < grant.receipt.request.rounds
2260                    {
2261                        Phase::Pending
2262                    } else {
2263                        Phase::Complete
2264                    };
2265                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2266                        // Persist publication debt with the successful checkpoint.
2267                        self.state.pr_publication_pending = true;
2268                    } else if passed {
2269                        self.state.status = RunStatus::Ready;
2270                    }
2271                    self.state.save()?;
2272                    if !passed {
2273                        continue;
2274                    }
2275                    // Existing PR ownership and push lease stay in place. The
2276                    // normal publisher owes the new reviewed/gated SHA, and
2277                    // land's fresh owner approval remains mandatory.
2278                    if self.state.config.merge.mode != MergeMode::Pr {
2279                        self.state.status = RunStatus::Ready;
2280                        self.state.event(
2281                            "repair-grant",
2282                            "repair verified locally; grant carries no merge authorization",
2283                        );
2284                        self.state.save()?;
2285                        return Ok(());
2286                    }
2287                    return self.merge().await;
2288                }
2289                Phase::Complete => return Ok(()),
2290            }
2291        }
2292    }
2293
2294    async fn execute_graph(&mut self) -> Result<()> {
2295        // Even a terminal run may reenter through an explicit recovery action.
2296        // Restore before prep shortcuts, saved conversations or graph nodes use
2297        // a disposable path; GC may already have removed its original objects.
2298        let archive_home = crate::run::home().canonicalize()?;
2299        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2300            let repo = self.state.repo.clone();
2301            let _coordination = self.coordinate(&repo).await?;
2302            ensure_setup_config(&mut self.state, &repo).await?;
2303            crate::retention::restore_execution_seats(
2304                &archive_home,
2305                &self.state,
2306                _coordination.as_ref(),
2307            )
2308            .await?;
2309        }
2310        self.state.configure_recovery_resume()?;
2311        // A revision is not reviewed until its own repair completes. No
2312        // other resume checkpoint may reuse the preceding instruction's review.
2313        if let Some(revision) = self.state.unfinished_instruction_revision() {
2314            if self.state.merge_repairs.last().is_some_and(|repair| {
2315                repair.question == revision.repair
2316                    && matches!(
2317                        repair.phase,
2318                        crate::run::MergeRepairPhase::Requested
2319                            | crate::run::MergeRepairPhase::Fixing
2320                            | crate::run::MergeRepairPhase::Reviewing
2321                    )
2322            }) {
2323                if self.repair_merge_review().await? {
2324                    self.run_land().await?;
2325                }
2326                self.settle_questions();
2327            } else {
2328                self.state.status = RunStatus::Blocked;
2329                self.state.parked = false;
2330                self.state.event("repair", "instruction revision repair did not complete; normal resume cannot land it. Inspect the retained branch and explicitly recover the PR for a fresh review of the revised instruction");
2331                self.state.save()?;
2332            }
2333            return Ok(());
2334        }
2335        if self
2336            .state
2337            .repair_grants
2338            .last()
2339            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2340        {
2341            return self.execute_granted_repair().await;
2342        }
2343        if self
2344            .state
2345            .repair_grants
2346            .last()
2347            .is_some_and(|g| !g.succeeded)
2348        {
2349            self.state.status = RunStatus::Blocked;
2350            self.state.save()?;
2351            return Ok(());
2352        }
2353        // Preservation may invalidate an old empty classification. Resolve it
2354        // before any resume shortcut can reuse a verdict or publish a branch.
2355        self.persist_candidates().await?;
2356        // A saved base stop outranks stage markers, including legacy Voting.
2357        // Recovery never reenters implementation, deliberation or voting.
2358        if self.state.base_sync_blocked() {
2359            self.sync_to_base().await?;
2360            if !self.state.base_sync_blocked()
2361                && self.state.status != RunStatus::AlreadyInBase
2362                && !self.resource_halt()?
2363            {
2364                self.finish_after_tally().await?;
2365            }
2366            return Ok(());
2367        }
2368        if self
2369            .state
2370            .merge_decision
2371            .as_ref()
2372            .is_some_and(|decision| !decision.closed)
2373            && self.state.status != RunStatus::Landing
2374        {
2375            if crate::merge_decision::resumable_hold(&self.state) {
2376                self.state.merge = Some(MergeOutcome {
2377                    mode: MergeMode::Pr,
2378                    ok: false,
2379                    detail: self
2380                        .state
2381                        .merge_decision
2382                        .as_ref()
2383                        .unwrap()
2384                        .target
2385                        .pr
2386                        .clone(),
2387                    empty: false,
2388                });
2389                self.run_land().await?;
2390                self.settle_questions();
2391                return Ok(());
2392            }
2393            bail!(
2394                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2395            );
2396        }
2397        if self.state.config.graph.selected_implementer.is_some()
2398            && self.state.status == RunStatus::Blocked
2399            && self.state.tally.is_none()
2400            && self.state.candidate_preservation.is_empty()
2401            && self.state.interrupted_implementations.is_empty()
2402        {
2403            bail!(
2404                "selected implementation is held; explicitly release the owning task to retry it"
2405            );
2406        }
2407
2408        if self.state.merge_repairs.last().is_some_and(|r| {
2409            matches!(
2410                r.phase,
2411                crate::run::MergeRepairPhase::Requested
2412                    | crate::run::MergeRepairPhase::Fixing
2413                    | crate::run::MergeRepairPhase::Reviewing
2414            )
2415        }) {
2416            if self.repair_merge_review().await? {
2417                self.run_land().await?;
2418            }
2419            self.settle_questions();
2420            return Ok(());
2421        }
2422        // Publication already passed review and gate. Resume only that node:
2423        // syncing to a newer base here could change the verified commit.
2424        if self.state.pr_publication_pending {
2425            self.merge().await?;
2426            if self.resource_halt()? {
2427                return Ok(());
2428            }
2429            self.state.save()?;
2430            self.settle_questions();
2431            return Ok(());
2432        }
2433        // A run that already lost its quorum never resumes into the verdict
2434        // machinery: `deliberate` and `vote` would otherwise clobber the
2435        // stalled marker back to Voting and the run would keep going past a
2436        // verdict that is no longer trustworthy. Everything already recorded is
2437        // kept, so the run stays resumable (or foldable) for a human to pick up.
2438        //
2439        // On --resume the run gets one chance to repair itself: the seats a
2440        // rate limit took out are re-asked. If their quota has since reset and
2441        // the quorum is restored, the run picks up and finishes; otherwise it
2442        // stays stale and still-resumable for a later retry. If it does not
2443        // recover, the returned status stays `Stalled` and nothing was
2444        // clobbered (the recovery only mutates entries for the lost seats).
2445        if self.state.status == RunStatus::Stalled {
2446            if self.recover_stall().await? {
2447                self.finish_after_tally().await?;
2448            } else {
2449                // Still below quorum: persist the marker and stay resumable.
2450                self.state.save()?;
2451            }
2452            return Ok(());
2453        }
2454        // A run parked inside `land` - watching CI, mid fix-round, or
2455        // waiting on the owner's merge approval - resumes directly into it,
2456        // never back through `prep`. Everything before `merge` already
2457        // concluded; that is the only way `status` reaches `Landing` in the
2458        // first place. Re-walking `review_loop` first would also be actively
2459        // wrong: its own status recomputation (see its doc) treats any
2460        // clean round as reason to set `status` to `Gating`, which would
2461        // clobber this marker before `merge` ever ran, and this run would
2462        // never find its way back into `land` at all.
2463        if self.state.status == RunStatus::Landing
2464            || crate::handover::landing_checkpoint(&self.state)
2465        {
2466            self.state.land_sync_pending = true;
2467            self.state.save()?;
2468            self.run_land().await?;
2469            // `run_land` may have settled the run right here - CI came back
2470            // green and the PR merged, say - without ever passing back
2471            // through `merge`'s own trailing call. Whatever it left `status`
2472            // as is what this has to read.
2473            self.settle_questions();
2474            return Ok(());
2475        }
2476        // A run parked at `merge` on the owner's word about a withheld PR text
2477        // resumes straight into `merge`. Re-walking the tail would sync to the
2478        // base again (possibly rebasing, possibly spending the fixer) after the
2479        // gate had passed, and then push a tree nobody reviewed or gated.
2480        if self.state.github_text.is_some()
2481            && self.state.merge.is_none()
2482            && self.state.status == RunStatus::Gating
2483        {
2484            self.merge().await?;
2485            if self.resource_halt()? {
2486                return Ok(());
2487            }
2488            self.state.save()?;
2489            return Ok(());
2490        }
2491        // A resource stop left the reserved synchronization unfinished. Reconcile
2492        // its exact HEAD and base before starting any earlier graph stage.
2493        if self.state.pending_base_operation().is_some() {
2494            return self.finish_after_tally().await;
2495        }
2496        if let Err(e) = self.prep().await {
2497            if e.is::<crate::repo_lock::ResourceBlocked>() {
2498                return Err(e);
2499            }
2500            self.state.status = RunStatus::Blocked;
2501            self.state
2502                .prep_failure
2503                .get_or_insert_with(|| format!("{e:#}"));
2504            self.state
2505                .event("prep", format!("preparation stopped: {e:#}"));
2506            self.state.save()?;
2507            return Err(e);
2508        }
2509        if self.park_here()? {
2510            return Ok(());
2511        }
2512        self.advise().await?;
2513        if self.park_here()? {
2514            return Ok(());
2515        }
2516        self.implement().await?;
2517        if self.park_here()? {
2518            return Ok(());
2519        }
2520        // `after_implement` already saved the state and settled any open
2521        // questions when it set this; nothing later in the graph has
2522        // anything to judge.
2523        if self.state.status == RunStatus::VerifiedNoop {
2524            return Ok(());
2525        }
2526        self.judge().await?;
2527        if self.park_here()? {
2528            return Ok(());
2529        }
2530        self.deliberate().await?;
2531        if self.park_here()? {
2532            return Ok(());
2533        }
2534        self.vote().await?;
2535        if self.park_here()? {
2536            return Ok(());
2537        }
2538        self.tally()?;
2539        // A verdict that lost its quorum is not trustworthy: do not review,
2540        // gate, or merge on it. Everything already done is kept, so the run
2541        // stays resumable (or foldable); the human can replace the agent that
2542        // ran out of quota and pick it up.
2543        if self.state.status == RunStatus::Stalled {
2544            // Persist the stalled marker now — the normal end-of-execute save
2545            // below is below this early return, and without it a resumed run
2546            // would reload a pre-tally status and keep going.
2547            self.state.save()?;
2548            return Ok(());
2549        }
2550        self.finish_after_tally().await?;
2551        Ok(())
2552    }
2553
2554    /// A wave could not start its agents because a shared resource stayed busy
2555    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2556    /// resumable. Unstarted seats have no result; completed peers retain
2557    /// their saved candidate state.
2558    fn stop_for_resource(&mut self) -> Result<()> {
2559        // Resource acquisition observes cancellation inside a node. Complete
2560        // the same durable park as every other node boundary before returning.
2561        if self.pause.parked() || self.interrupt.parked() {
2562            self.park_here()?;
2563            return Ok(());
2564        }
2565        if self.state.resource_block.is_some() {
2566            self.state.status = RunStatus::Blocked;
2567        }
2568        self.state.save()
2569    }
2570
2571    /// Stop walking the graph if a node ended on a resource block.
2572    fn resource_halt(&mut self) -> Result<bool> {
2573        if self.state.resource_block.is_none() {
2574            return Ok(false);
2575        }
2576        self.stop_for_resource()?;
2577        Ok(true)
2578    }
2579
2580    /// Park here if asked to, recording it in the run's own timeline.
2581    ///
2582    /// Returns whether the caller should stop walking the graph. The state is
2583    /// saved either way by the node that just finished; this adds the event so
2584    /// the operator's card says why a run that is neither finished nor moving
2585    /// is sitting where it is.
2586    fn park_here(&mut self) -> Result<bool> {
2587        let parking = self.pause.parked() || self.interrupt.parked();
2588        if !parking && self.state.resource_block.is_some() {
2589            self.stop_for_resource()?;
2590            return Ok(true);
2591        }
2592        // Either handle asking is enough - see `Pause`'s own doc for why
2593        // they are never the same one. `interrupt` is checked second so a
2594        // reason it carries is preferred in the message below over a plain
2595        // shutdown park racing it at the same boundary.
2596        if !self.pause.parked() && !self.interrupt.parked() {
2597            return Ok(false);
2598        }
2599        if self.state.parked {
2600            return Ok(true);
2601        }
2602        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2603        if let Some(block) = &mut self.state.resource_block
2604            && matches!(
2605                block.cause,
2606                crate::run::ResourceBlockCause::Cancelled { .. }
2607            )
2608        {
2609            block.cause = crate::run::ResourceBlockCause::Cancelled {
2610                park: cause.clone(),
2611            };
2612        }
2613        let why = match cause.as_ref().map(ParkCause::label) {
2614            Some(reason) => format!(
2615                "parked after `{}` ({reason}) — resume to carry on from here",
2616                self.state.status.as_str()
2617            ),
2618            None => format!(
2619                "parked after `{}` — resume to carry on from here",
2620                self.state.status.as_str()
2621            ),
2622        };
2623        self.state.event("park", why);
2624        self.state
2625            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2626        self.state.parked = true;
2627        self.state.save()?;
2628        Ok(true)
2629    }
2630
2631    /// Only a new explicit operator approval may retry failed preparation.
2632    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2633        if self.state.prep_failure.is_none() {
2634            return Ok(());
2635        }
2636        let failed_at = self
2637            .state
2638            .events
2639            .iter()
2640            .rev()
2641            .find(|event| event.node == "prep")
2642            .map_or(self.state.updated_at, |event| event.at);
2643        anyhow::ensure!(
2644            approval_at > failed_at,
2645            "preparation retry requires a new explicit release after the failure"
2646        );
2647        self.state.prep_failure = None;
2648        self.state.prep_complete = Some(false);
2649        self.state
2650            .event("prep-retry", "operator approved retry of preparation");
2651        Ok(())
2652    }
2653
2654    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2655    pub fn on_pause(&mut self, pause: Pause) {
2656        self.pause = pause;
2657    }
2658
2659    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2660    /// scheduler asking this one run - and no other - to park so a task
2661    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2662    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2663    /// handle.
2664    pub fn watch_interrupt(&mut self, pause: Pause) {
2665        self.interrupt = pause;
2666    }
2667
2668    /// Abandon this run's own open questions, once `status` has actually
2669    /// settled rather than merely paused.
2670    ///
2671    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2672    /// either back up with the candidates, the review round and the seat
2673    /// sessions already on disk, so a question an implementer asked mid-round
2674    /// may still get a real answer read by a real resume. Only the statuses
2675    /// `resumable` excludes are actually final: the run merged, it reached
2676    /// `Ready` with nothing left to do, it failed outright with no
2677    /// established point to continue from, or every candidate agreed, with
2678    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2679    /// every one of those the seat that asked is gone for good, exactly like
2680    /// the run being deleted under `magi run rm` - so the same cleanup
2681    /// applies, worded for what actually happened instead of "the run was
2682    /// deleted".
2683    ///
2684    /// Best-effort and silent on success: called from every place `status`
2685    /// can land on one of those three, including ones a resumed run revisits,
2686    /// so it must cost nothing when there was nothing open to begin with.
2687    fn settle_questions(&mut self) {
2688        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2689            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2690        }
2691    }
2692
2693    /// The tail of the graph after a trustworthy tally: fold losers, review,
2694    /// gate, merge, and persist.
2695    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2696        Box::pin(self.finish_after_tally_inner())
2697    }
2698
2699    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2700        // Before the losers are folded: their branches are what the graft
2701        // reads from.
2702        self.graft().await?;
2703        if self.resource_halt()? {
2704            return Ok(());
2705        }
2706        self.fold_losers().await?;
2707        // Before review starts, and again right before the gate: a run's
2708        // review rounds can themselves take long enough for the base to move
2709        // a second time, and the gate is the one node whose "green" gets
2710        // acted on.
2711        self.sync_to_base().await?;
2712        if self.hold_base_sync().await? || self.resource_halt()? {
2713            return Ok(());
2714        }
2715        if self.state.status == RunStatus::AlreadyInBase {
2716            return Ok(());
2717        }
2718        self.review_loop().await?;
2719        if self.resource_halt()? {
2720            return Ok(());
2721        }
2722        self.sync_to_base().await?;
2723        if self.hold_base_sync().await? || self.resource_halt()? {
2724            return Ok(());
2725        }
2726        if self.state.status == RunStatus::AlreadyInBase {
2727            return Ok(());
2728        }
2729        self.gate().await?;
2730        self.merge().await?;
2731        if self.resource_halt()? {
2732            return Ok(());
2733        }
2734        self.state.save()?;
2735        Ok(())
2736    }
2737
2738    // ---------------------------------------------------------------- prep
2739
2740    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2741    /// run with the step and its output in the event; it is never swallowed.
2742    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2743    /// resume starts over instead of finding candidates and missing seats.
2744    async fn setup_seat_worktree(
2745        &mut self,
2746        repo: &Path,
2747        wt: &Path,
2748        in_prep: bool,
2749        coordination: Option<&crate::repo_lock::SeatLease>,
2750    ) -> Result<()> {
2751        let result = match ensure_setup_config(&mut self.state, repo).await {
2752            Ok(()) => {
2753                worktree_setup::prepare_with(
2754                    &self.state.config,
2755                    repo,
2756                    wt,
2757                    crate::build_target::Coordination::Held(coordination),
2758                )
2759                .await
2760            }
2761            Err(e) => Err(e),
2762        };
2763        if let Err(e) = result {
2764            git::worktree_remove_clean(repo, wt).await.ok();
2765            if in_prep {
2766                self.rollback_prep(repo).await;
2767            }
2768            self.state.status = RunStatus::Blocked;
2769            self.state.event(
2770                "setup",
2771                format!("worktree setup failed in {}: {e:#}", wt.display()),
2772            );
2773            self.state.save()?;
2774            return Err(e);
2775        }
2776        Ok(())
2777    }
2778
2779    /// Undo everything `prep` created, so a resume re-runs it whole.
2780    async fn rollback_prep(&mut self, repo: &Path) {
2781        let root = self.state.worktree_root();
2782        for c in std::mem::take(&mut self.state.candidates) {
2783            if matches!(
2784                git::worktree_remove_clean(repo, &c.worktree).await,
2785                Ok(true)
2786            ) {
2787                git::branch_delete(repo, &c.branch).await.ok();
2788            } else {
2789                self.state.candidates.push(c);
2790            }
2791        }
2792        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2793        for j in 1..=seats {
2794            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2795                .await
2796                .ok();
2797        }
2798        for k in 1..=self.state.config.graph.advisors {
2799            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2800                .await
2801                .ok();
2802        }
2803    }
2804
2805    async fn prep(&mut self) -> Result<()> {
2806        if let Some(reason) = &self.state.prep_failure {
2807            bail!(
2808                "candidate preparation previously failed: {reason}; correct the source before retrying"
2809            );
2810        }
2811        if self
2812            .state
2813            .prep_complete
2814            .unwrap_or(!self.state.candidates.is_empty())
2815        {
2816            return Ok(());
2817        }
2818        let repo = self.state.repo.clone();
2819        // Includes rollback, config, refs, checkout creation and setup. No
2820        // repository mutation may precede the real shared lock acquisition.
2821        let _coordination = self.coordinate(&repo).await?;
2822        let base = self.state.base_commit.clone();
2823        let plan = self.state.sources.plan(&repo, &base).await?;
2824        self.rollback_prep(&repo).await;
2825        if !self.state.candidates.is_empty() {
2826            bail!(
2827                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2828            );
2829        }
2830        self.state.prep_complete = Some(false);
2831        self.state.status = RunStatus::Prep;
2832        self.state.save()?;
2833        let repo = self.state.repo.clone();
2834        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2835        let root = self.state.worktree_root();
2836        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2837
2838        // The hook is the write-time half of the blindness contract; the
2839        // presentation filter in `blind` is the half that cannot be bypassed.
2840        let hooks_dir = self.state.dir().join("hooks");
2841        if self.state.config.blind.commit_msg_hook {
2842            std::fs::create_dir_all(&hooks_dir)
2843                .with_context(|| format!("create {}", hooks_dir.display()))?;
2844            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2845            let path = hooks_dir.join("commit-msg");
2846            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2847            make_executable(&path)?;
2848            // Ref-counted rather than a plain idempotent set: with more than
2849            // one run able to be in flight in the same repository at once
2850            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2851            // true?" check cannot tell "another run of mine still needs
2852            // this" from "nobody does", and the run that happens to finish
2853            // first would disable the hook out from under a sibling still
2854            // relying on it.
2855            git::acquire_worktree_config(&repo).await?;
2856            self.state.enabled_worktree_config = true;
2857        }
2858
2859        // `[worktree] setup` hides its products per worktree, which needs the
2860        // same per-worktree config the hook does. Held until fold, like it.
2861        ensure_setup_config(&mut self.state, &repo).await?;
2862
2863        for (index, (spec, label)) in self
2864            .roles
2865            .implementers
2866            .clone()
2867            .into_iter()
2868            .zip(labels)
2869            .enumerate()
2870        {
2871            let branch = self.state.branch_for(label);
2872            let worktree = root.join(format!("cand-{label}"));
2873            // Persist intent before Git can leave a partially created tree.
2874            // Candidate registration follows setup, so it cannot inventory
2875            // crashes or refusals during creation itself.
2876            self.state.event(
2877                "prep-intent",
2878                serde_json::json!({
2879                    "branch": branch,
2880                    "worktree": worktree,
2881                    "start": start,
2882                    "picks": plan.picks,
2883                })
2884                .to_string(),
2885            );
2886            self.state.save()?;
2887            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2888            if self.state.config.blind.commit_msg_hook {
2889                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2890            }
2891            git::local_exclude(&worktree, "/.magi/").await?;
2892            if let Err(e) = worktree_setup::prepare_with(
2893                &self.state.config,
2894                &repo,
2895                &worktree,
2896                crate::build_target::Coordination::Held(_coordination.as_ref()),
2897            )
2898            .await
2899            {
2900                // Nothing of this prep may survive: a resume must start over,
2901                // not find half the candidates and skip the rest.
2902                git::worktree_remove_clean(&repo, &worktree).await.ok();
2903                git::branch_delete(&repo, &branch).await.ok();
2904                self.rollback_prep(&repo).await;
2905                self.state.status = RunStatus::Blocked;
2906                self.state
2907                    .event("prep", format!("worktree setup failed: {e:#}"));
2908                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2909                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2910                }
2911                self.state.save()?;
2912                return Err(e);
2913            }
2914            self.state.candidates.push(Candidate {
2915                index,
2916                label,
2917                agent: spec.id.clone(),
2918                branch,
2919                worktree,
2920                summary: String::new(),
2921                stat: String::new(),
2922                files: 0,
2923                commits: 0,
2924                empty: false,
2925                failed: None,
2926                verified_noop: None,
2927                duration_ms: 0,
2928                folded: false,
2929            });
2930            self.state.save()?;
2931            for pick in &plan.picks {
2932                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2933                {
2934                    self.state.status = RunStatus::Blocked;
2935                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2936                    self.state
2937                        .event("prep", format!("cannot apply referenced commit: {e}"));
2938                    self.state.save()?;
2939                    return Err(e);
2940                }
2941            }
2942        }
2943
2944        for j in 1..=self.roles.judges.len() {
2945            let wt = root.join(format!("judge-{j}"));
2946            if !wt.exists() {
2947                git::worktree_add_detached(&repo, &wt, &base).await?;
2948                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2949                    .await?;
2950            }
2951        }
2952
2953        // Disposable, detached checkouts for the design-deliberation stage's
2954        // advisor seats — the same shape as the judges' above, at the same
2955        // base commit, since advisors also only ever read. Sized off the
2956        // configured count directly rather than a resolved roster: unlike
2957        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2958        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2959        // `prep` has no `ResolvedRoles` field to read a count from here.
2960        if self.state.config.graph.advise {
2961            for k in 1..=self.state.config.graph.advisors {
2962                let wt = root.join(format!("advisor-{k}"));
2963                if !wt.exists() {
2964                    git::worktree_add_detached(&repo, &wt, &base).await?;
2965                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2966                        .await?;
2967                }
2968            }
2969        }
2970
2971        // A judge cannot tell it is looking at its own patch — the seats keep
2972        // separate conversations — but a panel that shares agents with the
2973        // field is less independent than it looks, and that is worth saying out
2974        // loud once per run rather than leaving it in the config.
2975        let authors: Vec<&str> = self
2976            .roles
2977            .implementers
2978            .iter()
2979            .map(|a| a.id.as_str())
2980            .collect();
2981        let overlap: Vec<String> = self
2982            .roles
2983            .judges
2984            .iter()
2985            .enumerate()
2986            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2987            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2988            .collect();
2989        if !overlap.is_empty() {
2990            let note = format!(
2991                "{} also authored a candidate; blind, but the panel is less \
2992                 independent than {} distinct agents would be",
2993                overlap.join(", "),
2994                self.roles.judges.len()
2995            );
2996            self.state.event("prep", note);
2997        }
2998
2999        self.state.event(
3000            "prep",
3001            format!(
3002                "{} candidates, {} judges, base {} ({})",
3003                self.state.candidates.len(),
3004                self.roles.judges.len(),
3005                &self.state.base_commit[..7.min(self.state.base_commit.len())],
3006                self.state.base_branch
3007            ),
3008        );
3009        self.state.prep_complete = Some(true);
3010        self.state.status = RunStatus::Implementing;
3011        self.state.save()?;
3012        Ok(())
3013    }
3014
3015    // -------------------------------------------------------------- advise
3016
3017    /// The design-deliberation stage: independent, read-only advisor seats
3018    /// each sketch a design before any implementer touches the repository,
3019    /// and (when at least one produced a usable proposal) a synthesis seat
3020    /// blends them into a brief `implement` carries in every candidate's
3021    /// prompt.
3022    ///
3023    /// `[graph] advise` is the on/off switch, on by default; `[graph]
3024    /// advisors` is the proposal count. Everything here is best-effort and
3025    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
3026    /// that cannot reach quota, or a synthesis seat that produced nothing
3027    /// usable all leave `implement` exactly as it was before this stage
3028    /// existed — the task instruction alone — rather than failing the whole
3029    /// competition over an enrichment stage. Every outcome is still recorded
3030    /// as an event, so a run that got nothing from this stage says why.
3031    ///
3032    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
3033    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
3034    /// resumed run whose stage failed would re-run it, and re-spend the
3035    /// agent calls, on every reentry before `implement`.
3036    ///
3037    /// Also skipped once any candidate shows implementation progress — the
3038    /// exact predicate `implement` itself uses to decide a candidate is no
3039    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
3040    /// is not enough: a run created by an older binary that predates this
3041    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
3042    /// an already-`Implementing`-or-later run under this build would
3043    /// otherwise walk straight back through `prep` (a no-op once candidates
3044    /// exist) into this node and spawn every advisor seat against worktrees
3045    /// `prep` never recreated — after implementation has already started,
3046    /// which is exactly the invariant this stage exists to guarantee.
3047    async fn advise(&mut self) -> Result<()> {
3048        let implement_untouched = self
3049            .state
3050            .candidates
3051            .iter()
3052            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
3053        if !self.state.config.graph.advise || self.state.advise_attempted {
3054            return Ok(());
3055        }
3056        if !implement_untouched {
3057            self.state.event(
3058                "advise",
3059                "skipping the design-deliberation stage: at least one \
3060                 candidate already shows implementation progress, so this \
3061                 run is past the point the stage exists to run before"
3062                    .to_owned(),
3063            );
3064            self.state.advise_attempted = true;
3065            self.state.save()?;
3066            return Ok(());
3067        }
3068        let run_id = self.state.id.clone();
3069        let prompts = self.state.config.prompts.clone();
3070        let instruction = self.state.instruction.clone();
3071        let language = self.state.config.graph.language.clone();
3072        let root = self.state.worktree_root();
3073        let n = self.state.config.graph.advisors;
3074        let where_recorded = self.state.dir().join("run.json");
3075
3076        let seats = match self.state.config.advisors() {
3077            Ok(seats) if !seats.is_empty() => seats,
3078            Ok(_) => {
3079                self.state.event(
3080                    "advise",
3081                    format!(
3082                        "[graph] advisors is 0; skipping the design-deliberation \
3083                         stage and continuing without a synthesis brief (see {})",
3084                        where_recorded.display()
3085                    ),
3086                );
3087                self.state.advise_attempted = true;
3088                self.state.save()?;
3089                return Ok(());
3090            }
3091            Err(e) => {
3092                self.state.event(
3093                    "advise",
3094                    format!(
3095                        "could not resolve advisor seats ({e:#}); continuing \
3096                         without a design-deliberation brief (see {})",
3097                        where_recorded.display()
3098                    ),
3099                );
3100                self.state.advise_attempted = true;
3101                self.state.save()?;
3102                return Ok(());
3103            }
3104        };
3105
3106        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3107        let artifacts = agent::artifacts_dir(&self.state.dir());
3108        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
3109
3110        let mut jobs = Vec::new();
3111        for (i, spec) in seats.iter().cloned().enumerate() {
3112            let seat_key = format!("advisor-{}", i + 1);
3113            let seat = self.seat(&seat_key, &spec.id);
3114            jobs.push(SeatJob {
3115                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
3116                spec,
3117                seat,
3118                cwd: worktrees[i % worktrees.len()].clone(),
3119                timeout,
3120                allow_write: false,
3121                sessions: false,
3122                artifacts: artifacts.clone(),
3123                stem: seat_key,
3124                handover: None,
3125            });
3126        }
3127
3128        self.state.event(
3129            "advise",
3130            format!(
3131                "{} advisor seat(s) sketching a design in parallel",
3132                jobs.len()
3133            ),
3134        );
3135        let mut quota_losses = Vec::new();
3136        let cache = self.state.config.cache_dir();
3137        let ctx = WaveCtx {
3138            carry_seats: false,
3139            pauses: Some((&self.pause, &self.interrupt)),
3140            run: &run_id,
3141            node: "advise",
3142            prompts: &prompts,
3143            cache: cache.as_deref(),
3144            round: None,
3145        };
3146        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
3147        let results = ask_json_wave::<Proposal>(
3148            jobs,
3149            Arc::clone(&self.sem),
3150            self.state.config.graph.retries,
3151            &advisor_roster,
3152            &ctx,
3153            &mut quota_losses,
3154            &mut self.state,
3155            &|p: &Proposal| p.validate(),
3156        )
3157        .await;
3158        if self.state.resource_block.is_some() {
3159            return self.stop_for_resource();
3160        }
3161        self.state.quota.extend(quota_losses);
3162
3163        let mut records = Vec::with_capacity(results.len());
3164        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
3165            let agent_id = seat.agent.clone();
3166            self.state.seats.insert(seat.key.clone(), seat);
3167            match res {
3168                Ok((proposal, out)) => {
3169                    self.state
3170                        .event("advise", format!("advisor-{} proposed a design", i + 1));
3171                    records.push(advise::AdvisorRecord::proposed(
3172                        i + 1,
3173                        agent_id,
3174                        proposal,
3175                        out.duration_ms,
3176                    ));
3177                }
3178                Err(e) => {
3179                    self.state.event(
3180                        "advise",
3181                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3182                    );
3183                    records.push(advise::AdvisorRecord::failed(
3184                        i + 1,
3185                        agent_id,
3186                        e.to_string(),
3187                    ));
3188                }
3189            }
3190        }
3191
3192        let mut advice = advise::Advice {
3193            records,
3194            synthesis: None,
3195        };
3196        if advice.proposals().is_empty() {
3197            self.state.event(
3198                "advise",
3199                "no advisor produced a usable proposal; continuing without a \
3200                 synthesis brief"
3201                    .to_owned(),
3202            );
3203        } else {
3204            match self
3205                .synthesize_brief(
3206                    &advice,
3207                    &instruction,
3208                    &language,
3209                    &worktrees[0],
3210                    &artifacts,
3211                    &run_id,
3212                    &prompts,
3213                    cache.as_deref(),
3214                )
3215                .await
3216            {
3217                Ok(Some(text)) => {
3218                    self.state.event(
3219                        "advise",
3220                        "synthesized a design brief for the implementer".to_owned(),
3221                    );
3222                    advice.synthesis = Some(text);
3223                }
3224                Ok(None) => {
3225                    self.state.event(
3226                        "advise",
3227                        "the synthesis seat produced nothing usable; continuing \
3228                         without a design brief"
3229                            .to_owned(),
3230                    );
3231                }
3232                Err(e) => {
3233                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3234                        return Err(e);
3235                    }
3236                    self.state.event(
3237                        "advise",
3238                        format!("could not synthesize a design brief: {e:#}"),
3239                    );
3240                }
3241            }
3242        }
3243        advise::apply_reflection(&mut advice);
3244
3245        self.state.advice = Some(advice);
3246        self.state.advise_attempted = true;
3247        self.state.save()?;
3248        Ok(())
3249    }
3250
3251    /// The synthesis seat: reads every advisor's proposal and blends them
3252    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3253    /// out of [`Runner::advise`] only for readability — it is not called
3254    /// anywhere else.
3255    ///
3256    /// Picked the same way [`crate::talk`]'s standing conversation and
3257    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3258    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3259    /// order (a claude seat, else the first runnable agent in roster order)
3260    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3261    /// in [`crate::config`] for why a dedicated field exists here at all.
3262    #[allow(clippy::too_many_arguments)]
3263    async fn synthesize_brief(
3264        &mut self,
3265        advice: &advise::Advice,
3266        instruction: &str,
3267        language: &str,
3268        cwd: &Path,
3269        artifacts: &Path,
3270        run_id: &str,
3271        prompts: &Prompts,
3272        cache: Option<&Path>,
3273    ) -> Result<Option<String>> {
3274        let chain = agent::pick_chain(
3275            &self.state.config.agents,
3276            self.state.config.roles.synthesizer.as_ref(),
3277            &agent::installed,
3278            "synthesizer",
3279        )?;
3280        let proposals = advice.proposals();
3281        let mut prompt = prompt::with_overlay(
3282            prompt::synthesize_brief(instruction, &proposals, language),
3283            prompts.overlay("advise"),
3284        );
3285        if cache.is_some() {
3286            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3287            // below — see `prompt::build_cache_note`'s doc for why telling a
3288            // read-only seat to build through the shared cache is exactly how
3289            // a sandbox's write refusal gets misread as a defect.
3290            prompt.push('\n');
3291            prompt.push_str(&prompt::build_cache_note("advise", false));
3292        }
3293        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3294        // Each id is tried once, in order; a quota hit, error or unusable
3295        // answer moves to the next. The seat is single-turn (`sessions:
3296        // false`) and the prompt is the whole context, so a fallback agent
3297        // needs nothing carried over.
3298        let mut last = None;
3299        for (n, spec) in chain.iter().enumerate() {
3300            if n > 0 {
3301                self.state
3302                    .event("advise", format!("synthesis falling back to {}", spec.id));
3303            }
3304            let mut seat = self.seat("advise-synthesis", &spec.id);
3305            let wait = self.repository_wait();
3306            let outcome = wait
3307                .scope(agent::invoke(
3308                    spec,
3309                    &mut seat,
3310                    &Invocation {
3311                        coordination: self.state.config.coordination.as_ref(),
3312                        fetched_base: None,
3313                        cwd,
3314                        prompt: &prompt,
3315                        timeout,
3316                        allow_write: false,
3317                        sessions: false,
3318                        artifacts,
3319                        stem: &if n == 0 {
3320                            "advise-synthesis".to_owned()
3321                        } else {
3322                            format!("advise-synthesis-{}", spec.id)
3323                        },
3324                        run: run_id,
3325                        node: "advise",
3326                        cache_dir: None,
3327                        attachments: &[],
3328                        writable: &[],
3329                    },
3330                ))
3331                .await;
3332            if outcome.is_ok() {
3333                self.state.seats.insert(seat.key.clone(), seat);
3334            }
3335            let advance = agent::chain_advances(&outcome);
3336            last = Some(outcome);
3337            if !advance {
3338                break;
3339            }
3340        }
3341        // Exhausted: the last attempt's result is what a single failed seat
3342        // would have produced.
3343        let out = last.expect("a chain holds at least one agent")?;
3344        if !out.usable() {
3345            return Ok(None);
3346        }
3347        let text =
3348            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3349        Ok((!text.trim().is_empty()).then_some(text))
3350    }
3351
3352    // ----------------------------------------------------------- implement
3353
3354    async fn implement(&mut self) -> Result<()> {
3355        self.persist_candidates().await?;
3356        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3357        // agent files with `magi task add` name the run that paid for it. The
3358        // prompt overlay is cloned alongside it because the waves borrow it
3359        // while `self` is mutably borrowed by the node's own bookkeeping.
3360        let run_id = self.state.id.clone();
3361        let prompts = self.state.config.prompts.clone();
3362        let todo: Vec<usize> = self
3363            .state
3364            .candidates
3365            .iter()
3366            .enumerate()
3367            .filter(|(_, c)| {
3368                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3369                    && c.failed.is_none()
3370                    && !c.empty
3371            })
3372            .map(|(i, _)| i)
3373            .collect();
3374        if todo.is_empty() {
3375            return self.after_implement();
3376        }
3377        self.state.status = RunStatus::Implementing;
3378
3379        let language = self.state.config.graph.language.clone();
3380        let github_language = self.state.config.graph.github_language.clone();
3381        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3382        let sessions = self.state.config.graph.sessions;
3383        let artifacts = agent::artifacts_dir(&self.state.dir());
3384        // The design-deliberation stage's blended brief, when `advise` found
3385        // one — carried into every implementer's prompt the same way
3386        // regardless of which candidate it is.
3387        let brief = self
3388            .state
3389            .advice
3390            .as_ref()
3391            .and_then(|a| a.synthesis.as_deref())
3392            .map(str::to_owned);
3393        let attachments = self.state.attachments.clone();
3394
3395        let mut jobs = Vec::new();
3396        for &i in &todo {
3397            let (index, label, worktree) = {
3398                let c = &self.state.candidates[i];
3399                (c.index, c.label, c.worktree.clone())
3400            };
3401            let spec = self.roles.implementers[index].clone();
3402            let seat_key = format!("impl-{label}");
3403            let seat = self.seat(&seat_key, &spec.id);
3404            let instruction = seeded_instruction(&self.state);
3405            jobs.push(SeatJob {
3406                spec,
3407                seat,
3408                prompt: prompt::implement_in(
3409                    &instruction,
3410                    &worktree.to_string_lossy(),
3411                    &language,
3412                    &github_language,
3413                    brief.as_deref(),
3414                    &attachments,
3415                ),
3416                cwd: worktree,
3417                timeout,
3418                allow_write: true,
3419                sessions,
3420                artifacts: artifacts.clone(),
3421                stem: format!("impl-{label}"),
3422                handover: None,
3423            });
3424        }
3425
3426        self.state.event(
3427            "implement",
3428            format!("{} candidates in parallel", jobs.len()),
3429        );
3430        // Kept so a seat whose CLI hung up can be asked again from the same
3431        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3432        // can update a seat's own entry once a fallback agent takes it over —
3433        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3434        // whichever agent actually answered, not the one that quota'd out.
3435        let mut sent = jobs.clone();
3436        // Where each seat's checkout stood before its turn. A reply is judged
3437        // against this, never against the run's base: a tree that carries an
3438        // inherited patch is ahead of the base before the seat does anything.
3439        let mut baselines = Vec::with_capacity(sent.len());
3440        for (job, &i) in sent.iter().zip(&todo) {
3441            baselines.push((
3442                self.state.candidates[i].label,
3443                git::rev_parse(&job.cwd, "HEAD").await.ok(),
3444            ));
3445        }
3446        let cache = self.state.config.cache_dir();
3447        let ctx = WaveCtx {
3448            carry_seats: false,
3449            pauses: Some((&self.pause, &self.interrupt)),
3450            run: &run_id,
3451            node: "implement",
3452            prompts: &prompts,
3453            cache: cache.as_deref(),
3454            round: None,
3455        };
3456        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3457        if !wave_blocked(&results) {
3458            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3459                .await;
3460            self.retry_unstarted(&mut results, &sent, &baselines, &prompts, &run_id)
3461                .await?;
3462            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3463                .await?;
3464            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3465                .await;
3466        }
3467        // Do not finalize failed candidates when the entire wave needs machine
3468        // recovery: leaving them pending resumes this node with its work intact.
3469        if !results.is_empty()
3470            && results
3471                .iter()
3472                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3473        {
3474            let losses: Vec<_> = results
3475                .iter()
3476                .map(|(_, seat, out)| {
3477                    let AgentOutcome::Quota(o) = out else {
3478                        unreachable!()
3479                    };
3480                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3481                })
3482                .collect();
3483            self.state.quota.extend(losses.clone());
3484            for (_, seat, _) in results {
3485                self.state.seats.insert(seat.key.clone(), seat);
3486            }
3487            for &i in &todo {
3488                let label = self.state.candidates[i].label;
3489                self.state.interrupted_implementations.insert(label);
3490                self.state
3491                    .candidate_preservation
3492                    .insert(label, "machine outage awaiting persistence".into());
3493            }
3494            // Preserve partial edits too, while keeping every interrupted seat
3495            // pending even when its tree already contains an inherited patch.
3496            block_machine_outage(&mut self.state, "implement", &losses);
3497            self.state.save()?;
3498            self.persist_candidates().await?;
3499            for &i in &todo {
3500                self.state
3501                    .interrupted_implementations
3502                    .insert(self.state.candidates[i].label);
3503            }
3504            return self.stop_for_resource();
3505        }
3506        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3507
3508        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3509            && results
3510                .iter()
3511                .any(|(_, _, out)| FailClass::of(out).is_some());
3512        let base_commit = self.state.base_commit.clone();
3513        let blind_cfg = self.state.config.blind.clone();
3514        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3515        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3516            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3517                // Executed turns interrupted by disk pressure already carry
3518                // a preservation barrier from wave. Admission-only waits do
3519                // not. Keep the interrupted seat's session for recovery too.
3520                if self
3521                    .state
3522                    .candidate_preservation
3523                    .contains_key(&self.state.candidates[i].label)
3524                {
3525                    self.state.seats.insert(seat.key.clone(), seat);
3526                }
3527                continue;
3528            }
3529            let seat_key = seat.key.clone();
3530            // A quota fallback (`resume_seat_handovers`) may have handed this
3531            // seat to a different agent than the one `prep` recorded on the
3532            // candidate; the stats tables and any later fixer-defaults-to-
3533            // winner's-author lookup must credit whoever actually answered —
3534            // unless every fallback also quota'd out, in which case nobody
3535            // actually answered and crediting the last agent tried would
3536            // erase every earlier agent's own quota loss from the stats
3537            // tables instead of just this one seat's.
3538            let agent = seat.agent.clone();
3539            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3540            self.state.seats.insert(seat.key.clone(), seat);
3541            let label = self.state.candidates[i].label;
3542            let worktree = self.state.candidates[i].worktree.clone();
3543            self.state.interrupted_implementations.remove(&label);
3544
3545            let (sanitized_summary, duration, failed, verified_claim) = match out {
3546                AgentOutcome::Ok(o) => {
3547                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3548                    let failed = (!o.usable()).then(|| {
3549                        if o.timed_out {
3550                            "agent timed out".to_owned()
3551                        } else {
3552                            format!(
3553                                "agent exited with {}",
3554                                crate::notices::exit_status(o.exit_code)
3555                            )
3556                        }
3557                    });
3558                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3559                    let verified_claim = match verified_noop_claim_in_worktree(
3560                        failed.is_none(),
3561                        &o.commands,
3562                        &text,
3563                        &worktree,
3564                        &base_commit,
3565                    )
3566                    .await
3567                    {
3568                        NoopClaimVerdict::Accepted => {
3569                            if matches!(
3570                                verdict::parse_verified_noop(&sanitized_summary),
3571                                Some(Ok(_))
3572                            ) {
3573                                Some(sanitized_summary.clone())
3574                            } else {
3575                                rejected_noops.push((
3576                                    label,
3577                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3578                                ));
3579                                None
3580                            }
3581                        }
3582                        NoopClaimVerdict::Rejected(reason) => {
3583                            rejected_noops.push((label, reason));
3584                            None
3585                        }
3586                        NoopClaimVerdict::Absent => None,
3587                    };
3588                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3589                }
3590                // Left un-resumed by `resume_undelivered` (a dirty tree
3591                // already rescues the work, or there was no session left to
3592                // resume into) — reported like the ordinary failure it is,
3593                // never as if `o.text` (the CLI's raw error JSON) were an
3594                // answer.
3595                AgentOutcome::Dropped(o) => {
3596                    let why = o
3597                        .dropped
3598                        .as_ref()
3599                        .map(|d| d.why.as_str())
3600                        .unwrap_or("the CLI ended the stream without delivering its answer");
3601                    (
3602                        String::new(),
3603                        o.duration_ms,
3604                        Some(format!("the CLI dropped the stream ({why})")),
3605                        None,
3606                    )
3607                }
3608                AgentOutcome::Quota(o) => {
3609                    self.state.quota.push(QuotaLoss::from_report(
3610                        seat_key,
3611                        "implement",
3612                        o.quota.as_ref(),
3613                    ));
3614                    (
3615                        String::new(),
3616                        o.duration_ms,
3617                        Some("rate limited (quota); produced no change".to_owned()),
3618                        None,
3619                    )
3620                }
3621                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3622                    (String::new(), 0, Some(e), None)
3623                }
3624            };
3625
3626            // Save every completed turn before any fallible Git operation. A failed
3627            // rescue must not erase the reply or prevent collection of other seats.
3628            let c = &mut self.state.candidates[i];
3629            if !exhausted_the_fallback_chain {
3630                c.agent = agent;
3631            }
3632            c.summary = sanitized_summary;
3633            c.duration_ms = duration;
3634            c.failed = failed;
3635            c.verified_noop = verified_claim;
3636            self.state
3637                .candidate_preservation
3638                .insert(label, "awaiting persistence".to_owned());
3639        }
3640        self.state.save()?;
3641        self.persist_candidates().await?;
3642
3643        let mut recorded_rejection = false;
3644        for (label, reason) in rejected_noops {
3645            if self.state.interrupted_implementations.contains(&label) {
3646                continue;
3647            }
3648            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3649                && c.empty
3650            {
3651                c.verified_noop = None;
3652                c.failed
3653                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3654                self.state.event(
3655                    "implement",
3656                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3657                );
3658                recorded_rejection = true;
3659            }
3660        }
3661        if recorded_rejection {
3662            self.state.save()?;
3663        }
3664
3665        if resource_blocked {
3666            return self.stop_for_resource();
3667        }
3668        if selected_failed {
3669            self.state.status = RunStatus::Blocked;
3670            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3671            self.state.save()?;
3672            bail!(
3673                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3674            );
3675        }
3676        self.after_implement()
3677    }
3678
3679    /// Retry only persistence after a completed implementation turn.
3680    async fn persist_candidates(&mut self) -> Result<()> {
3681        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3682        for label in labels {
3683            let i = self
3684                .state
3685                .candidates
3686                .iter()
3687                .position(|c| c.label == label)
3688                .context("pending candidate is missing")?;
3689            let c = self.state.candidates[i].clone();
3690            let interrupted = self.state.interrupted_implementations.contains(&label);
3691            let result = async {
3692                let wait = crate::repo_lock::WaitPolicy::new(
3693                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3694                    || false,
3695                );
3696                let _coordination =
3697                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3698                // Best effort evidence requires no index writes. A successful snapshot
3699                // never authorizes removal of a tree whose rescue failed.
3700                if let Err(e) = git::snapshot_uncommitted(
3701                    &c.worktree,
3702                    &self
3703                        .state
3704                        .dir()
3705                        .join("artifacts")
3706                        .join(format!("candidate-{label}-recovery")),
3707                )
3708                .await
3709                {
3710                    self.state.event(
3711                        "preserve",
3712                        format!("candidate {label} snapshot incomplete: {e:#}"),
3713                    );
3714                }
3715                let rescued = git::rescue_commit(
3716                    &c.worktree,
3717                    &format!("magi: candidate {label} (uncommitted work)"),
3718                )
3719                .await?;
3720                self.state.note_withheld("implement", &rescued.withheld);
3721                let base = &self.state.base_commit;
3722                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3723                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3724                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3725                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3726                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3727                if c.empty && commits > 0 && !patch.trim().is_empty()
3728                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3729                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3730                        || self.state.tally.is_some())
3731                {
3732                    // Keep the old classification and pending marker so every
3733                    // retry stops too. Retain decisions as recovery evidence;
3734                    // only a supported recovery operation may replace them.
3735                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3736                }
3737                let c = &mut self.state.candidates[i];
3738                c.commits = commits;
3739                c.stat = stat;
3740                c.files = files;
3741                let no_changes = commits == 0 || patch.trim().is_empty();
3742                c.empty = no_changes && !interrupted;
3743                if interrupted && no_changes {
3744                    c.failed = None;
3745                    c.verified_noop = None;
3746                }
3747                if !c.empty {
3748                    c.failed = None;
3749                    c.verified_noop = None;
3750                }
3751                self.state.event(
3752                    "preserve",
3753                    format!("candidate {label}: {files} files, {commits} commits"),
3754                );
3755                Ok::<_, anyhow::Error>(())
3756            }
3757            .await;
3758            match result {
3759                Ok(()) => {
3760                    self.state.candidate_preservation.remove(&label);
3761                    if !interrupted || self.state.candidates[i].files > 0 {
3762                        self.state.interrupted_implementations.remove(&label);
3763                    }
3764                }
3765                Err(e) => {
3766                    let reason = format!("candidate {label} preservation failed: {e:#}");
3767                    self.state.event("preserve", &reason);
3768                    self.state.candidate_preservation.insert(label, reason);
3769                }
3770            }
3771            if self.state.candidate_preservation.is_empty()
3772                && self.state.status == RunStatus::Blocked
3773                && self.state.candidates.iter().all(|c| c.failed.is_none())
3774            {
3775                // Persist the recovered phase with the cleared pending marker;
3776                // a crash between saves must not turn this into a selected-seat
3777                // failure hold on the next resume.
3778                self.state.status = RunStatus::Implementing;
3779                self.state.event(
3780                    "preserve",
3781                    "candidate persistence recovered; implementation can continue",
3782                );
3783            }
3784            self.state.save()?;
3785        }
3786        if !self.state.candidate_preservation.is_empty() {
3787            self.state.status = RunStatus::Blocked;
3788            self.state.save()?;
3789            bail!(
3790                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3791            );
3792        }
3793        Ok(())
3794    }
3795
3796    /// Ask again, once, for work a CLI did and then failed to hand over.
3797    ///
3798    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3799    /// status with an empty response and a usage report showing output tokens,
3800    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3801    /// seven minutes and 14,267 output tokens that arrived as an empty
3802    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3803    ///
3804    /// Two conditions, and both matter:
3805    ///
3806    /// - **Only when the tree is untouched.** Often the agent has already
3807    ///   written its files and only the closing message was lost; the rescue
3808    ///   commit below picks that up and there is nothing to ask for. Re-asking
3809    ///   then would pay for a second implementation of work already on disk.
3810    /// - **Once.** A CLI that drops one stream can drop the next, and this
3811    ///   node is the most expensive in the graph.
3812    ///
3813    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3814    /// dropped reply still carried its `conversation_id`, so the seat is asked
3815    /// to finish what it was doing rather than sent the whole task again. It
3816    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3817    /// node's - for the same reason a re-ranked judge does: restating finished
3818    /// work is not the work.
3819    ///
3820    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3821    /// same way until it resets, while an abandoned conversation is still
3822    /// there to be picked up.
3823    async fn resume_undelivered(
3824        &mut self,
3825        results: &mut [(usize, SeatState, AgentOutcome)],
3826        sent: &[SeatJob],
3827        prompts: &Prompts,
3828        run_id: &str,
3829    ) {
3830        for (wi, seat, out) in results.iter_mut() {
3831            let Some(dropped) = (match &*out {
3832                AgentOutcome::Dropped(o) => o.dropped.clone(),
3833                _ => None,
3834            }) else {
3835                continue;
3836            };
3837            let Some(job) = sent.get(*wi) else { continue };
3838            // Already on disk? Then only the closing message was lost.
3839            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3840                self.state.event(
3841                    "implement",
3842                    format!(
3843                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3844                         work is in the tree",
3845                        seat.key, dropped.output_tokens, dropped.why
3846                    ),
3847                );
3848                continue;
3849            }
3850            // The re-ask only makes sense as a resume: `resume_after_drop`
3851            // says nothing about the task, trusting the seat to still hold it.
3852            // Without a session to resume — sessions disabled, or this CLI's
3853            // drop shape happened not to carry a session id — that prompt
3854            // would open a brand-new conversation with no context at all,
3855            // which is worse than leaving this as the ordinary failure it
3856            // already is.
3857            if !has_context(&job.spec, seat, job.sessions) {
3858                self.state.event(
3859                    "implement",
3860                    format!(
3861                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3862                         is no session left to resume",
3863                        seat.key, dropped.output_tokens, dropped.why
3864                    ),
3865                );
3866                continue;
3867            }
3868            self.state.event(
3869                "implement",
3870                format!(
3871                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3872                     conversation",
3873                    seat.key, dropped.output_tokens, dropped.why
3874                ),
3875            );
3876            let mut retry = job.clone();
3877            retry.seat = seat.clone();
3878            retry.prompt = prompt::resume_after_drop(&dropped.why);
3879            retry.timeout = retry_budget(job.timeout, true);
3880            retry.stem = format!("{}-resume", job.stem);
3881            let cache = self.state.config.cache_dir();
3882            let ctx = WaveCtx {
3883                carry_seats: false,
3884                pauses: Some((&self.pause, &self.interrupt)),
3885                run: run_id,
3886                node: "implement",
3887                prompts,
3888                cache: cache.as_deref(),
3889                round: None,
3890            };
3891            let (resumed_seat, resumed) =
3892                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3893            *seat = resumed_seat;
3894            *out = resumed;
3895        }
3896    }
3897
3898    /// Fall an implement seat through to the next untried agent in the
3899    /// implementer roster when it lost to quota — or, since the handover was
3900    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3901    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3902    /// quota path itself being unchanged — instead of leaving the
3903    /// seat's loss final the moment one agent's account runs dry.
3904    ///
3905    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3906    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3907    /// truncates to the single slot rotation picked, so a solo task whose one
3908    /// implementer hits quota mid-run used to have nothing else to try. This
3909    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3910    /// unrotated roster — which is the only place the *other* candidates in
3911    /// the machine's roster still exist once `implementers` has been cut down
3912    /// to size.
3913    ///
3914    /// Walks forward from just past the seat's own original position in the
3915    /// roster, never wrapping back to the front: a later candidate slot (say
3916    /// `beta`, the roster's second entry) must fall through to the *next*
3917    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3918    /// almost certainly a different candidate's own agent already — and once
3919    /// the roster's tail is exhausted there is nothing left to fall through
3920    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3921    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3922    /// let this retry that id forever. The loop keeps falling through until
3923    /// an attempt lands something other than `Quota` or the roster's tail
3924    /// runs out of untried ids, at which point the seat is left exactly as
3925    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3926    /// `QuotaLoss` recorded, the candidate failed/empty.
3927    ///
3928    /// `sent` is taken mutably and updated with the fallback agent's spec:
3929    /// `resume_unconfirmed_commands`, which runs after this and also reads
3930    /// `sent`, must see whichever agent actually ended up answering the seat
3931    /// — reading the stale, original spec there would check session
3932    /// eligibility against the wrong CLI and could hand a fallback agent's
3933    /// session id to the agent that just lost the seat to quota.
3934    ///
3935    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3936    /// — `self.seat` only reuses state when the agent id is unchanged, so
3937    /// handing it a different id already gets this for free. Reusing the old
3938    /// seat would resume a different CLI's session as if it were a
3939    /// continuation of this one.
3940    ///
3941    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3942    /// a quota loss cuts an agent off mid-turn, so anything already in the
3943    /// tree is unfinished work, not a completed candidate a re-ask would pay
3944    /// for twice. A dirty tree is rescued into a commit first (the same
3945    /// neutral-identity rescue `implement`'s own outcome loop gives every
3946    /// candidate) so the next agent starts clean.
3947    ///
3948    /// The new agent gets the implementer's full prompt and full
3949    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3950    /// it has no session and no context, and is implementing the task from
3951    /// nothing, unlike a resumed drop which is only restating work already
3952    /// done.
3953    ///
3954    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3955    /// `implement` event, never into `self.state.quota` — that is what
3956    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3957    /// go unspent, and a seat that ultimately recovered on its second or
3958    /// third agent is not the stalled panel that check exists to catch. Only
3959    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3960    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3961    /// outcome loop already has — this helper never pushes to it itself.
3962    async fn resume_seat_handovers(
3963        &mut self,
3964        results: &mut [(usize, SeatState, AgentOutcome)],
3965        sent: &mut [SeatJob],
3966        prompts: &Prompts,
3967        run_id: &str,
3968    ) -> Result<()> {
3969        let instruction = seeded_instruction(&self.state);
3970        let language = self.state.config.graph.language.clone();
3971        let github_language = self.state.config.graph.github_language.clone();
3972        let brief = self
3973            .state
3974            .advice
3975            .as_ref()
3976            .and_then(|a| a.synthesis.as_deref())
3977            .map(str::to_owned);
3978        let attachments = self.state.attachments.clone();
3979        for (wi, seat, out) in results.iter_mut() {
3980            // Who holds the other candidate seats of this wave right now
3981            // (earlier handovers already written back to `sent`).
3982            let others: BTreeSet<String> = sent
3983                .iter()
3984                .enumerate()
3985                .filter(|(j, _)| j != wi)
3986                .map(|(_, j)| j.spec.id.clone())
3987                .collect();
3988            let Some(job) = sent.get_mut(*wi) else {
3989                continue;
3990            };
3991            // Where the seat's own original agent sits in the roster — the
3992            // fallback walk starts just past here, never at the front, so a
3993            // later candidate slot's quota loss does not fall back onto an
3994            // earlier slot's own agent.
3995            let start = self
3996                .roles
3997                .implementer_roster
3998                .iter()
3999                .position(|s| s.id == job.spec.id)
4000                .unwrap_or(0);
4001            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
4002            let mut fallback_attempt = 0usize;
4003            let mut prev: Option<FailClass> = None;
4004            while let Some(cur) = FailClass::of(&*out) {
4005                if !should_hand_over(prev.as_ref(), &cur) {
4006                    break;
4007                }
4008                let Some(next) =
4009                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
4010                        .cloned()
4011                else {
4012                    break;
4013                };
4014                tried.insert(next.id.clone());
4015                fallback_attempt += 1;
4016
4017                let coordination = self.coordinate(&job.cwd).await?;
4018                if let Ok(r) = git::rescue_commit(
4019                    &job.cwd,
4020                    &format!(
4021                        "magi: candidate {} (uncommitted work before {} fallback)",
4022                        seat.key,
4023                        if cur == FailClass::Quota {
4024                            "quota"
4025                        } else {
4026                            "handover"
4027                        }
4028                    ),
4029                )
4030                .await
4031                {
4032                    self.state.note_withheld("implement", &r.withheld);
4033                }
4034                drop(coordination);
4035
4036                record_handover(
4037                    &mut self.state,
4038                    "implement",
4039                    &seat.key,
4040                    &seat.agent,
4041                    &next.id,
4042                    &cur,
4043                    &fail_reason(&*out),
4044                );
4045                prev = Some(cur.clone());
4046
4047                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
4048                self.state.seats.insert(seat.key.clone(), new_seat.clone());
4049                // Kept in sync on `sent` itself, not just the local retry: a
4050                // later helper (`resume_unconfirmed_commands`) reads `sent`
4051                // after this one returns and must see whichever agent is now
4052                // occupying the seat, not the one that just quota'd out —
4053                // otherwise it would judge session/continuation eligibility
4054                // by the wrong CLI and could resend a fallback's session id
4055                // to the agent that lost it the seat in the first place.
4056                job.spec = next.clone();
4057                let mut retry = job.clone();
4058                retry.seat = new_seat;
4059                retry.prompt = prompt::implement_in(
4060                    &instruction,
4061                    &job.cwd.to_string_lossy(),
4062                    &language,
4063                    &github_language,
4064                    brief.as_deref(),
4065                    &attachments,
4066                );
4067                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
4068                let cache = self.state.config.cache_dir();
4069                let ctx = WaveCtx {
4070                    carry_seats: false,
4071                    pauses: Some((&self.pause, &self.interrupt)),
4072                    run: run_id,
4073                    node: "implement",
4074                    prompts,
4075                    cache: cache.as_deref(),
4076                    round: None,
4077                };
4078                let (fallback_seat, fallback_out) = run_one(
4079                    retry,
4080                    Arc::clone(&self.sem),
4081                    &ctx,
4082                    &mut self.state,
4083                    fallback_attempt,
4084                )
4085                .await;
4086                *seat = fallback_seat;
4087                *out = fallback_out;
4088            }
4089        }
4090        Ok(())
4091    }
4092
4093    /// Ask an implement seat's own CLI to confirm what it started, once, when
4094    /// its reply reported a command whose completion status it never
4095    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
4096    /// that does and does not mean.
4097    ///
4098    /// The completion contract this task asks for, extended to `implement`
4099    /// with the same signal `continue_fix_report` reads for the fixer,
4100    /// rather than a keyword search over the reply or a hard requirement on
4101    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
4102    /// a candidate's CLI turn ended cleanly while a test run it had started
4103    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
4104    /// named in it at all is untouched by this: `commands` is empty, so
4105    /// there is nothing to be unconfirmed.
4106    ///
4107    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
4108    /// this is not about recovering edits that might already be on disk, it
4109    /// is about a result the seat itself never vouched for, which resuming
4110    /// asks for regardless of what the tree already holds. Bounded to one
4111    /// attempt for the same reason `resume_undelivered` is — this is the
4112    /// most expensive node in the graph — and a seat that still cannot
4113    /// confirm on that attempt is left as whatever its (possibly still
4114    /// unconfirmed) reply says; this does not invent a new "failed" reason
4115    /// for a candidate that otherwise produced a real, committed change.
4116    async fn resume_unconfirmed_commands(
4117        &mut self,
4118        results: &mut [(usize, SeatState, AgentOutcome)],
4119        sent: &[SeatJob],
4120        prompts: &Prompts,
4121        run_id: &str,
4122    ) {
4123        for (wi, seat, out) in results.iter_mut() {
4124            let AgentOutcome::Ok(o) = &*out else {
4125                continue;
4126            };
4127            if !has_unconfirmed_command(&o.commands) {
4128                continue;
4129            }
4130            let Some(job) = sent.get(*wi) else { continue };
4131            if !has_context(&job.spec, seat, job.sessions) {
4132                self.state.event(
4133                    "implement",
4134                    format!(
4135                        "{}: the reply named a command whose own CLI never confirmed the exit \
4136                         status of, but there is no session left to resume",
4137                        seat.key
4138                    ),
4139                );
4140                continue;
4141            }
4142            self.state.event(
4143                "implement",
4144                format!(
4145                    "{}: the reply named a command whose own CLI never confirmed the exit \
4146                     status of; resuming the conversation",
4147                    seat.key
4148                ),
4149            );
4150            let mut retry = job.clone();
4151            retry.seat = seat.clone();
4152            retry.prompt = prompt::resume_incomplete(
4153                "a command in your last reply had no confirmed exit status",
4154            );
4155            retry.timeout = retry_budget(job.timeout, true);
4156            retry.stem = format!("{}-confirm", job.stem);
4157            let cache = self.state.config.cache_dir();
4158            let ctx = WaveCtx {
4159                carry_seats: false,
4160                pauses: Some((&self.pause, &self.interrupt)),
4161                run: run_id,
4162                node: "implement",
4163                prompts,
4164                cache: cache.as_deref(),
4165                round: None,
4166            };
4167            let (resumed_seat, resumed) =
4168                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4169            *seat = resumed_seat;
4170            *out = resumed;
4171        }
4172    }
4173
4174    /// Ask an implement seat again, once per candidate and run, when its
4175    /// turn ended cleanly without starting the work.
4176    ///
4177    /// The shape behind 86f0, 3ce0 and eca7: the model's first response was a
4178    /// final answer ("Implementation incomplete. No files were changed...")
4179    /// after six to twelve seconds, with no tool call and no change. That is
4180    /// a usable exit-0 reply, so none of the other recoveries sees it — it is
4181    /// not a dropped stream, not a failure and names no unconfirmed command —
4182    /// and the candidate was recorded as an ordinary empty one.
4183    ///
4184    /// Decided on evidence, never on the reply's wording (see
4185    /// [`ended_unstarted`]), and never for a reply whose `NO CHANGE NEEDED`
4186    /// claim verifies: that one did answer the task.
4187    ///
4188    /// The seat's own conversation is resumed with [`prompt::resume_unstarted`]
4189    /// when it has one; without a session the whole prompt goes out again.
4190    /// Either way the budget is the full `timeout_implement`, not a nudge's
4191    /// quarter: nothing was done yet, so this is the job itself.
4192    ///
4193    /// Bounded by [`RunState::unstarted_retries`], saved before the agent is
4194    /// asked so a restart cannot grant a second retry. A seat that ends the
4195    /// same way again becomes an ordinary failure with [`UNSTARTED_TWICE`] as
4196    /// its reason, which `resume_seat_handovers` (run next) may hand to the
4197    /// next roster agent like any other failure.
4198    async fn retry_unstarted(
4199        &mut self,
4200        results: &mut [(usize, SeatState, AgentOutcome)],
4201        sent: &[SeatJob],
4202        baselines: &[(char, Option<String>)],
4203        prompts: &Prompts,
4204        run_id: &str,
4205    ) -> Result<()> {
4206        for (wi, seat, out) in results.iter_mut() {
4207            let (Some(job), Some((label, before))) = (sent.get(*wi), baselines.get(*wi)) else {
4208                continue;
4209            };
4210            if !self.unstarted(out, before.as_deref(), &job.cwd).await {
4211                continue;
4212            }
4213            if !self.state.unstarted_retries.insert(*label) {
4214                self.state
4215                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4216                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4217                continue;
4218            }
4219            let resumed = has_context(&job.spec, seat, job.sessions);
4220            self.state.event(
4221                "implement",
4222                format!(
4223                    "{}: the turn ended without starting the work (no tool call, worktree \
4224                     unchanged); {}",
4225                    seat.key,
4226                    if resumed {
4227                        "resuming the conversation once"
4228                    } else {
4229                        "sending the task once more"
4230                    }
4231                ),
4232            );
4233            self.state.save()?;
4234            let mut retry = job.clone();
4235            retry.seat = seat.clone();
4236            if resumed {
4237                retry.prompt = prompt::resume_unstarted();
4238            }
4239            retry.stem = format!("{}-unstarted", job.stem);
4240            let cache = self.state.config.cache_dir();
4241            let ctx = WaveCtx {
4242                carry_seats: false,
4243                pauses: Some((&self.pause, &self.interrupt)),
4244                run: run_id,
4245                node: "implement",
4246                prompts,
4247                cache: cache.as_deref(),
4248                round: None,
4249            };
4250            let (answered_seat, answer) =
4251                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4252            *seat = answered_seat;
4253            *out = answer;
4254            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
4255                // No agent was spawned, so the retry was not spent.
4256                self.state.unstarted_retries.remove(label);
4257                continue;
4258            }
4259            if self.unstarted(out, before.as_deref(), &job.cwd).await {
4260                self.state
4261                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4262                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4263            }
4264        }
4265        Ok(())
4266    }
4267
4268    /// Whether `out` is a clean reply from a seat that never started the
4269    /// work in `cwd`, and whose reply does not verify as a no-op either.
4270    async fn unstarted(&self, out: &AgentOutcome, before: Option<&str>, cwd: &Path) -> bool {
4271        let AgentOutcome::Ok(o) = out else {
4272            return false;
4273        };
4274        // The CLI's own record first: most replies stop here without git.
4275        if o.tool_calls != Some(0) {
4276            return false;
4277        }
4278        let after = git::rev_parse(cwd, "HEAD").await.ok();
4279        let clean = git::is_clean(cwd).await.ok();
4280        if !ended_unstarted(o, before, after.as_deref(), clean) {
4281            return false;
4282        }
4283        let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
4284        verified_noop_claim_in_worktree(true, &o.commands, &text, cwd, &self.state.base_commit)
4285            .await
4286            != NoopClaimVerdict::Accepted
4287    }
4288
4289    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
4290    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
4291    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
4292    /// that motivated this.
4293    ///
4294    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
4295    /// own nudge loop already covers for judge/review/vote seats, and not a
4296    /// dropped stream, which [`Runner::resume_undelivered`] covers for
4297    /// implement seats: here the CLI turn genuinely finished while the node's
4298    /// own work — the fixer's account of what it did — had not. Gated purely
4299    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
4300    /// reply, never on any wording in it, so a fixer whose valid, first-try
4301    /// `FixReport` happens to mention having waited on a background test is
4302    /// never resumed — the `Ok(report)` branch at the call site returns
4303    /// before this is ever invoked.
4304    ///
4305    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4306    /// attempt ([`retry_budget`]), nothing attempted once the session is
4307    /// gone, and a quota hit ends the loop immediately rather than retrying a
4308    /// rate limit that fails the same way again.
4309    async fn continue_fix_report(
4310        &mut self,
4311        mut seat: SeatState,
4312        parse_err: String,
4313        job: &SeatJob,
4314        prompts: &Prompts,
4315        run_id: &str,
4316        round: usize,
4317    ) -> (
4318        SeatState,
4319        Option<FixReport>,
4320        Option<String>,
4321        ContinuationRecord,
4322    ) {
4323        let mut last_err = parse_err;
4324        let mut cumulative_wait_ms = 0u64;
4325        let mut attempts = 0usize;
4326        loop {
4327            if !has_context(&job.spec, &seat, job.sessions) {
4328                self.state.event(
4329                    "fix",
4330                    format!(
4331                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4332                         session left to resume into"
4333                    ),
4334                );
4335                let outcome = if attempts == 0 {
4336                    ContinuationOutcome::NoSession
4337                } else {
4338                    ContinuationOutcome::Exhausted
4339                };
4340                return (
4341                    seat,
4342                    None,
4343                    Some(format!("unparsable fix report: {last_err}")),
4344                    ContinuationRecord {
4345                        attempts,
4346                        cumulative_wait_ms,
4347                        outcome,
4348                    },
4349                );
4350            }
4351            if attempts >= MAX_FIX_CONTINUATIONS {
4352                self.state.event(
4353                    "fix",
4354                    format!(
4355                        "round {round}: fixer's reply still had no adoption report after \
4356                         {attempts} continuation(s) ({last_err}); giving up"
4357                    ),
4358                );
4359                return (
4360                    seat,
4361                    None,
4362                    Some(format!(
4363                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4364                    )),
4365                    ContinuationRecord {
4366                        attempts,
4367                        cumulative_wait_ms,
4368                        outcome: ContinuationOutcome::Exhausted,
4369                    },
4370                );
4371            }
4372            attempts += 1;
4373            self.state.event(
4374                "fix",
4375                format!(
4376                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4377                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4378                ),
4379            );
4380            let mut retry = job.clone();
4381            retry.seat = seat.clone();
4382            retry.prompt = prompt::resume_incomplete(&last_err);
4383            retry.timeout = retry_budget(job.timeout, true);
4384            retry.stem = format!("{}-continue{attempts}", job.stem);
4385            let cache = self.state.config.cache_dir();
4386            let ctx = WaveCtx {
4387                carry_seats: false,
4388                pauses: Some((&self.pause, &self.interrupt)),
4389                run: run_id,
4390                node: "fix",
4391                prompts,
4392                cache: cache.as_deref(),
4393                round: Some(round),
4394            };
4395            let (resumed_seat, resumed_out) = run_one(
4396                retry,
4397                Arc::clone(&self.sem),
4398                &ctx,
4399                &mut self.state,
4400                attempts,
4401            )
4402            .await;
4403            seat = resumed_seat;
4404            match resumed_out {
4405                AgentOutcome::Ok(o) => {
4406                    cumulative_wait_ms += o.duration_ms;
4407                    match verdict::extract_json::<FixReport>(&o.text) {
4408                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4409                            self.state.event(
4410                                "fix",
4411                                format!(
4412                                    "round {round}: fixer's adoption report recovered after \
4413                                     {attempts} continuation(s)"
4414                                ),
4415                            );
4416                            return (
4417                                seat,
4418                                Some(report),
4419                                None,
4420                                ContinuationRecord {
4421                                    attempts,
4422                                    cumulative_wait_ms,
4423                                    outcome: ContinuationOutcome::Resumed,
4424                                },
4425                            );
4426                        }
4427                        // The report parsed, but this same reply's own
4428                        // CommandEvidence — the identical record `state.jobs`
4429                        // renders — names a command whose CLI never
4430                        // confirmed an exit status. Read together, that is
4431                        // not a resolved answer: keep nudging rather than
4432                        // accept a report standing next to a command the
4433                        // seat's own CLI cannot vouch for.
4434                        Ok(_) => {
4435                            last_err = "the reply parsed, but it reported a command whose own CLI \
4436                                 never confirmed an exit status"
4437                                .to_owned();
4438                        }
4439                        Err(e) => last_err = e.to_string(),
4440                    }
4441                }
4442                AgentOutcome::Quota(o) => {
4443                    cumulative_wait_ms += o.duration_ms;
4444                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4445                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4446                    self.state.quota.push(loss);
4447                    self.state.event(
4448                        "fix",
4449                        format!(
4450                            "round {round}: continuation rate limited (quota); not retrying now"
4451                        ),
4452                    );
4453                    return (
4454                        seat,
4455                        None,
4456                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4457                        ContinuationRecord {
4458                            attempts,
4459                            cumulative_wait_ms,
4460                            outcome: ContinuationOutcome::QuotaLost,
4461                        },
4462                    );
4463                }
4464                AgentOutcome::Dropped(o) => {
4465                    cumulative_wait_ms += o.duration_ms;
4466                    let why = o
4467                        .dropped
4468                        .as_ref()
4469                        .map(|d| d.why.as_str())
4470                        .unwrap_or("the CLI ended the stream without delivering its answer");
4471                    last_err = format!("the CLI dropped the stream ({why})");
4472                }
4473                AgentOutcome::Failed(e) => last_err = e,
4474                // The continuation was never started; the report stays lost
4475                // and the caller records that, without any handover.
4476                AgentOutcome::ResourceBlocked(e) => {
4477                    return (
4478                        seat,
4479                        None,
4480                        Some(format!("the continuation was not started: {e}")),
4481                        ContinuationRecord {
4482                            attempts: attempts.saturating_sub(1),
4483                            cumulative_wait_ms,
4484                            outcome: ContinuationOutcome::NoSession,
4485                        },
4486                    );
4487                }
4488            }
4489        }
4490    }
4491
4492    fn after_implement(&mut self) -> Result<()> {
4493        if !self.state.candidate_preservation.is_empty() {
4494            bail!("candidate preservation incomplete; judging is unsafe");
4495        }
4496        // Scan every candidate patch once the set is complete.
4497        if self.state.leaks.is_empty() {
4498            let cfg = self.state.config.blind.clone();
4499            let mut leaks = Vec::new();
4500            for c in &self.state.candidates {
4501                let Some(patch) =
4502                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4503                else {
4504                    continue;
4505                };
4506                leaks.extend(blind::scan(
4507                    &format!("candidate {} patch", c.label),
4508                    &patch,
4509                    &cfg.vendor_tokens,
4510                ));
4511            }
4512            if !leaks.is_empty() {
4513                let summary = leaks
4514                    .iter()
4515                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4516                    .collect::<Vec<_>>()
4517                    .join(", ");
4518                match cfg.on_leak {
4519                    LeakPolicy::Fail => {
4520                        self.state.status = RunStatus::Failed;
4521                        self.state
4522                            .event("blind", format!("vendor text in a patch: {summary}"));
4523                        self.state.leaks = leaks;
4524                        self.state.save()?;
4525                        self.settle_questions();
4526                        bail!(
4527                            "blind.on_leak = \"fail\" and vendor text reached a \
4528                             judged patch: {summary}"
4529                        );
4530                    }
4531                    LeakPolicy::Redact => self.state.event(
4532                        "blind",
4533                        format!("redacting vendor text for judging: {summary}"),
4534                    ),
4535                    LeakPolicy::Warn => self.state.event(
4536                        "blind",
4537                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4538                    ),
4539                }
4540                self.state.leaks = leaks;
4541            }
4542        }
4543
4544        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4545        // incomplete or inconsistent saved state cannot bypass the strict contract.
4546        let mut invalidated = Vec::new();
4547        for c in &mut self.state.candidates {
4548            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4549                c.verified_noop = None;
4550                if c.empty && c.failed.is_none() {
4551                    c.failed = Some(
4552                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4553                            .to_owned(),
4554                    );
4555                }
4556                invalidated.push(c.label);
4557            }
4558        }
4559        for label in invalidated {
4560            self.state.event(
4561                "implement",
4562                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4563            );
4564        }
4565
4566        if self.state.viable().is_empty() {
4567            if self.state.all_candidates_verified_noop() {
4568                // Every candidate agreed, with evidence the adoption guard
4569                // accepted, that nothing belongs in this worktree. That is
4570                // not the same fact as a candidate that simply failed to
4571                // write anything, and settling it as an ordinary `Failed`
4572                // (see `SCHEMA`'s doc for schema 10) is what let two of
4573                // task 391f's attempts burn a retry each re-discovering the
4574                // same already-landed fix. Terminal either way, so `judge`
4575                // must never run over an empty candidate set — unlike the
4576                // `Failed` branch below this returns `Ok`, not an error:
4577                // nothing here failed.
4578                self.state.status = RunStatus::VerifiedNoop;
4579                self.state.save()?;
4580                self.settle_questions();
4581                return Ok(());
4582            }
4583            self.state.status = RunStatus::Failed;
4584            self.state.save()?;
4585            self.settle_questions();
4586            bail!("no candidate produced a change; nothing to judge");
4587        }
4588        self.state.status = RunStatus::Judging;
4589        self.state.save()?;
4590        Ok(())
4591    }
4592
4593    // --------------------------------------------------------------- judge
4594
4595    async fn judge(&mut self) -> Result<()> {
4596        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4597        // agent files with `magi task add` name the run that paid for it. The
4598        // prompt overlay is cloned alongside it because the waves borrow it
4599        // while `self` is mutably borrowed by the node's own bookkeeping.
4600        let run_id = self.state.id.clone();
4601        let prompts = self.state.config.prompts.clone();
4602        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4603            return Ok(());
4604        }
4605        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4606        if viable.len() == 1 {
4607            // Recorded so this is a one-time event: `judgements` stays empty
4608            // either way, which without this flag is indistinguishable from
4609            // "not yet judged" on the next reentry — and status is left
4610            // untouched, so a later node's conclusion (e.g. `Blocked` after
4611            // the review budget ran out) survives a resume instead of being
4612            // clobbered back to `Judging` by this node running again.
4613            self.state.judge_skipped = true;
4614            self.state.event(
4615                "judge",
4616                format!(
4617                    "only candidate {} produced a change; judging skipped",
4618                    viable[0].label
4619                ),
4620            );
4621            self.state.save()?;
4622            return Ok(());
4623        }
4624        self.state.status = RunStatus::Judging;
4625
4626        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4627        let language = self.state.config.graph.language.clone();
4628        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4629        let sessions = self.state.config.graph.sessions;
4630        let artifacts = agent::artifacts_dir(&self.state.dir());
4631        let root = self.state.worktree_root();
4632        let base_short = short(&self.state.base_commit);
4633
4634        let mut jobs = Vec::new();
4635        let mut orders = Vec::new();
4636        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4637            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4638            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4639            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4640            let seat_key = format!("judge-{}", j + 1);
4641            let seat = self.seat(&seat_key, &spec.id);
4642            jobs.push(SeatJob {
4643                prompt: prompt::judge(
4644                    &self.state.instruction,
4645                    &views,
4646                    self.roles.judges.len(),
4647                    &base_short,
4648                    &language,
4649                ),
4650                spec,
4651                seat,
4652                cwd: root.join(format!("judge-{}", j + 1)),
4653                timeout,
4654                allow_write: false,
4655                sessions,
4656                artifacts: artifacts.clone(),
4657                stem: format!("judge-{}", j + 1),
4658                handover: None,
4659            });
4660        }
4661
4662        self.state.event(
4663            "judge",
4664            format!(
4665                "{} judges ranking {} candidates blind",
4666                jobs.len(),
4667                viable.len()
4668            ),
4669        );
4670        let labels_for_check = labels.clone();
4671        let mut quota_losses = Vec::new();
4672        let cache = self.state.config.cache_dir();
4673        let ctx = WaveCtx {
4674            carry_seats: false,
4675            pauses: Some((&self.pause, &self.interrupt)),
4676            run: &run_id,
4677            node: "judge",
4678            prompts: &prompts,
4679            cache: cache.as_deref(),
4680            round: None,
4681        };
4682        let results = ask_json_wave::<Ranking>(
4683            jobs,
4684            Arc::clone(&self.sem),
4685            self.state.config.graph.retries,
4686            &self.roles.judge_roster,
4687            &ctx,
4688            &mut quota_losses,
4689            &mut self.state,
4690            &move |r: &Ranking| r.validate(&labels_for_check),
4691        )
4692        .await;
4693        if self.state.resource_block.is_some() {
4694            return self.stop_for_resource();
4695        }
4696        self.state.quota.extend(quota_losses);
4697
4698        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4699            let agent_id = seat.agent.clone();
4700            self.state.seats.insert(seat.key.clone(), seat);
4701            let mut record = Judgement {
4702                judge: j + 1,
4703                seat: format!("judge-{}", j + 1),
4704                agent: agent_id,
4705                ranking: Vec::new(),
4706                reasons: BTreeMap::new(),
4707                confidence: None,
4708                strengths: BTreeMap::new(),
4709                order: orders[j].clone(),
4710                failed: None,
4711                duration_ms: 0,
4712            };
4713            match res {
4714                Ok((ranking, out)) => {
4715                    record.ranking = ranking.normalized();
4716                    record.reasons = ranking.reasons;
4717                    record.strengths = ranking.strengths;
4718                    record.confidence = ranking.confidence;
4719                    record.duration_ms = out.duration_ms;
4720                    self.state.event(
4721                        "judge",
4722                        format!(
4723                            "judge {} ranked {}",
4724                            j + 1,
4725                            record.ranking.iter().collect::<String>()
4726                        ),
4727                    );
4728                }
4729                Err(e) => {
4730                    record.failed = Some(e.to_string());
4731                    self.state
4732                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4733                }
4734            }
4735            self.state.judgements.push(record);
4736            self.state.save()?;
4737        }
4738        Ok(())
4739    }
4740
4741    // ---------------------------------------------------------- deliberate
4742
4743    async fn deliberate(&mut self) -> Result<()> {
4744        if self.hold_base_sync().await? {
4745            return Ok(());
4746        }
4747        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4748        // agent files with `magi task add` name the run that paid for it. The
4749        // prompt overlay is cloned alongside it because the waves borrow it
4750        // while `self` is mutably borrowed by the node's own bookkeeping.
4751        let run_id = self.state.id.clone();
4752        let prompts = self.state.config.prompts.clone();
4753        let rounds = self.state.config.graph.deliberate_rounds;
4754        // Resume unfinished rounds after an outage, but never reopen a tally.
4755        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4756            return Ok(());
4757        }
4758        let tops: Vec<char> = self
4759            .state
4760            .judgements
4761            .iter()
4762            .filter_map(|j| j.ranking.first().copied())
4763            .collect();
4764        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4765            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4766                self.state.event(
4767                    "deliberate",
4768                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4769                );
4770            }
4771            self.state.status = RunStatus::Voting;
4772            self.state.save()?;
4773            return Ok(());
4774        }
4775
4776        self.state.status = RunStatus::Deliberating;
4777        self.state.event(
4778            "deliberate",
4779            format!(
4780                "split: first choices were {} — opening {rounds} round(s)",
4781                tops.iter().collect::<String>()
4782            ),
4783        );
4784
4785        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4786        let language = self.state.config.graph.language.clone();
4787        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4788        let sessions = self.state.config.graph.sessions;
4789        let artifacts = agent::artifacts_dir(&self.state.dir());
4790        let root = self.state.worktree_root();
4791        let base_short = short(&self.state.base_commit);
4792
4793        // Judges argue in sequence so that a turn can answer the one before it;
4794        // that is the difference between deliberation and three parallel
4795        // monologues.
4796        for round in self.state.deliberation.len() + 1..=rounds {
4797            let mut turns: Vec<DeliberationTurn> = Vec::new();
4798            let mut round_losses = Vec::new();
4799            let mut asked = 0;
4800            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4801                if self.state.judgements[j].failed.is_some() {
4802                    continue;
4803                }
4804                let seat_key = format!("judge-{}", j + 1);
4805                let spec = self.occupant(&seat_key, spec);
4806                let mut seat = self.seat(&seat_key, &spec.id);
4807                let transcript = self.transcript(&turns, j);
4808                let build = |context: Option<&str>| {
4809                    prompt::deliberate(
4810                        &self.state.instruction,
4811                        context,
4812                        &transcript,
4813                        round,
4814                        rounds,
4815                        &language,
4816                    )
4817                };
4818                let block = self.candidate_block(&viable, &base_short);
4819                let full = build(Some(&block));
4820                let text = if has_context(&spec, &seat, sessions) {
4821                    build(None)
4822                } else {
4823                    full.clone()
4824                };
4825                let job = SeatJob {
4826                    spec,
4827                    seat: seat.clone(),
4828                    prompt: text,
4829                    cwd: root.join(format!("judge-{}", j + 1)),
4830                    timeout,
4831                    allow_write: false,
4832                    sessions,
4833                    artifacts: artifacts.clone(),
4834                    stem: format!("delib-{round}-judge-{}", j + 1),
4835                    handover: Some(full),
4836                };
4837                let cache = self.state.config.cache_dir();
4838                let ctx = WaveCtx {
4839                    carry_seats: false,
4840                    pauses: Some((&self.pause, &self.interrupt)),
4841                    run: &run_id,
4842                    node: "deliberate",
4843                    prompts: &prompts,
4844                    cache: cache.as_deref(),
4845                    round: None,
4846                };
4847                // A turn is never nudged (`retries` 0): a failed seat is
4848                // handed to the next roster agent, which gets the full
4849                // context. An empty answer is a turn, not a failure.
4850                let mut losses = Vec::new();
4851                asked += 1;
4852                let mut results = ask_wave_with::<String>(
4853                    vec![job],
4854                    Arc::clone(&self.sem),
4855                    0,
4856                    &self.roles.judge_roster,
4857                    &ctx,
4858                    &mut losses,
4859                    &mut self.state,
4860                    &|text: &str| {
4861                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4862                    },
4863                )
4864                .await;
4865                if self.state.resource_block.is_some() {
4866                    return self.stop_for_resource();
4867                }
4868                round_losses.extend(losses.iter().cloned());
4869                self.state.quota.extend(losses);
4870                let (updated, res, _) = results.pop().expect("one job in, one result out");
4871                seat = updated;
4872                let agent_id = seat.agent.clone();
4873                self.state.seats.insert(seat.key.clone(), seat);
4874                let body = match res {
4875                    Ok((body, _)) => body,
4876                    // Skip the seat; a CLI's raw error JSON is never read as
4877                    // this judge's position.
4878                    Err(e) => {
4879                        self.state
4880                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4881                        continue;
4882                    }
4883                };
4884                let tentative = verdict::extract_json::<Position>(&body)
4885                    .ok()
4886                    .and_then(|p| p.tentative)
4887                    .and_then(|s| s.trim().chars().next())
4888                    .map(|c| c.to_ascii_uppercase());
4889                self.state.event(
4890                    "deliberate",
4891                    format!(
4892                        "round {round}: judge {} now favours {}",
4893                        j + 1,
4894                        tentative.map_or("—".to_owned(), |c| c.to_string())
4895                    ),
4896                );
4897                turns.push(DeliberationTurn {
4898                    judge: j + 1,
4899                    agent: agent_id,
4900                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4901                    tentative,
4902                });
4903            }
4904            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4905                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4906                return self.stop_for_resource();
4907            }
4908            self.state
4909                .deliberation
4910                .push(DeliberationRound { round, turns });
4911            self.state.save()?;
4912        }
4913
4914        self.state.status = RunStatus::Voting;
4915        self.state.save()?;
4916        Ok(())
4917    }
4918
4919    // ---------------------------------------------------------------- vote
4920
4921    async fn vote(&mut self) -> Result<()> {
4922        if self.hold_base_sync().await? {
4923            return Ok(());
4924        }
4925        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4926        // agent files with `magi task add` name the run that paid for it. The
4927        // prompt overlay is cloned alongside it because the waves borrow it
4928        // while `self` is mutably borrowed by the node's own bookkeeping.
4929        let run_id = self.state.id.clone();
4930        let prompts = self.state.config.prompts.clone();
4931        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4932            return Ok(());
4933        }
4934        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4935        if viable.len() == 1 {
4936            return Ok(());
4937        }
4938        self.state.status = RunStatus::Voting;
4939
4940        let language = self.state.config.graph.language.clone();
4941        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4942        let sessions = self.state.config.graph.sessions;
4943        let artifacts = agent::artifacts_dir(&self.state.dir());
4944        let root = self.state.worktree_root();
4945        let base_short = short(&self.state.base_commit);
4946        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4947
4948        let mut jobs = Vec::new();
4949        let mut seats_at = Vec::new();
4950        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4951            if self
4952                .state
4953                .judgements
4954                .get(j)
4955                .is_some_and(|r| r.failed.is_some())
4956            {
4957                continue;
4958            }
4959            let seat_key = format!("judge-{}", j + 1);
4960            let spec = self.occupant(&seat_key, spec);
4961            let seat = self.seat(&seat_key, &spec.id);
4962            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4963            let text = if has_context(&spec, &seat, sessions) {
4964                prompt::final_vote(&viable, &language)
4965            } else {
4966                full.clone()
4967            };
4968            jobs.push(SeatJob {
4969                spec,
4970                seat,
4971                prompt: text,
4972                cwd: root.join(format!("judge-{}", j + 1)),
4973                timeout,
4974                allow_write: false,
4975                sessions,
4976                artifacts: artifacts.clone(),
4977                stem: format!("vote-judge-{}", j + 1),
4978                handover: Some(full),
4979            });
4980            seats_at.push(j);
4981        }
4982
4983        self.state.event(
4984            "vote",
4985            format!(
4986                "collecting {} final votes one by one, privately",
4987                jobs.len()
4988            ),
4989        );
4990        let allowed = viable.clone();
4991        let mut quota_losses = Vec::new();
4992        let cache = self.state.config.cache_dir();
4993        let ctx = WaveCtx {
4994            carry_seats: false,
4995            pauses: Some((&self.pause, &self.interrupt)),
4996            run: &run_id,
4997            node: "vote",
4998            prompts: &prompts,
4999            cache: cache.as_deref(),
5000            round: None,
5001        };
5002        let results = ask_json_wave::<FinalVote>(
5003            jobs,
5004            Arc::clone(&self.sem),
5005            self.state.config.graph.retries,
5006            &self.roles.judge_roster,
5007            &ctx,
5008            &mut quota_losses,
5009            &mut self.state,
5010            &move |v: &FinalVote| match v.label() {
5011                Some(c) if allowed.contains(&c) => Ok(()),
5012                other => bail!("vote {other:?} is not one of {allowed:?}"),
5013            },
5014        )
5015        .await;
5016        if self.state.resource_block.is_some() {
5017            return self.stop_for_resource();
5018        }
5019        self.state.quota.extend(quota_losses);
5020
5021        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
5022            let agent_id = seat.agent.clone();
5023            self.state.seats.insert(seat.key.clone(), seat);
5024            let initial = self
5025                .state
5026                .judgements
5027                .get(j)
5028                .and_then(|r| r.ranking.first().copied());
5029            let mut record = VoteRecord {
5030                judge: j + 1,
5031                agent: agent_id,
5032                vote: None,
5033                reason: String::new(),
5034                changed: false,
5035            };
5036            match res {
5037                Ok((v, _)) => {
5038                    record.vote = v.label();
5039                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5040                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
5041                    self.state.event(
5042                        "vote",
5043                        format!(
5044                            "judge {} voted {}{}",
5045                            j + 1,
5046                            record.vote.unwrap_or('?'),
5047                            if record.changed { " (changed)" } else { "" }
5048                        ),
5049                    );
5050                }
5051                Err(e) => {
5052                    self.state
5053                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
5054                }
5055            }
5056            self.state.votes.push(record);
5057            self.state.save()?;
5058        }
5059        Ok(())
5060    }
5061
5062    // --------------------------------------------------------------- tally
5063
5064    fn tally(&mut self) -> Result<()> {
5065        if self.state.tally.is_some() {
5066            return Ok(());
5067        }
5068        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
5069        let tops: Vec<char> = self
5070            .state
5071            .judgements
5072            .iter()
5073            .filter_map(|j| j.ranking.first().copied())
5074            .collect();
5075        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
5076
5077        // A judge whose private vote failed still counted once, in the initial
5078        // ranking; using it beats discarding a whole seat.
5079        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5080        let mut cast: Vec<char> = Vec::new();
5081        for (i, j) in self.state.judgements.iter().enumerate() {
5082            let vote = self
5083                .state
5084                .votes
5085                .iter()
5086                .find(|v| v.judge == i + 1)
5087                .and_then(|v| v.vote)
5088                .or_else(|| j.ranking.first().copied());
5089            if let Some(v) = vote {
5090                *first_choice.entry(v).or_insert(0) += 1;
5091                cast.push(v);
5092            }
5093        }
5094
5095        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5096        for j in &self.state.judgements {
5097            let n = j.ranking.len();
5098            for (pos, label) in j.ranking.iter().enumerate() {
5099                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
5100            }
5101        }
5102
5103        let best = first_choice.values().copied().max().unwrap_or(0);
5104        let mut leaders: Vec<char> = first_choice
5105            .iter()
5106            .filter(|(_, v)| **v == best)
5107            .map(|(k, _)| *k)
5108            .collect();
5109        let mut tie_break = None;
5110        if leaders.len() > 1 {
5111            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
5112            let borda_leaders: Vec<char> = leaders
5113                .iter()
5114                .copied()
5115                .filter(|l| borda[l] == top_borda)
5116                .collect();
5117            tie_break = Some(if borda_leaders.len() == 1 {
5118                format!(
5119                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
5120                    leaders.len()
5121                )
5122            } else {
5123                format!(
5124                    "{} way tie on both first-choice votes and Borda points, broken by label order",
5125                    leaders.len()
5126                )
5127            });
5128            leaders = borda_leaders;
5129            leaders.sort_unstable();
5130        }
5131        let winner = *leaders
5132            .first()
5133            .or(viable.first())
5134            .context("no candidate to declare a winner from")?;
5135
5136        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
5137        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
5138        let deliberated = !self.state.deliberation.is_empty();
5139
5140        // Whose verdict is this? A rate-limited seat is absent even if it
5141        // ranked before the limit hit, so presence is measured against the
5142        // recorded losses, not just "did a ranking ever appear".
5143        let quota_seats: std::collections::BTreeSet<&str> =
5144            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5145        let mut present = 0usize;
5146        for (i, j) in self.state.judgements.iter().enumerate() {
5147            if quota_seats.contains(j.seat.as_str()) {
5148                continue;
5149            }
5150            let ranked = !j.ranking.is_empty() && j.failed.is_none();
5151            let voted = self
5152                .state
5153                .votes
5154                .iter()
5155                .any(|v| v.judge == i + 1 && v.vote.is_some());
5156            if ranked || voted {
5157                present += 1;
5158            }
5159        }
5160        // Strict majority of the configured panel. A bare majority is real
5161        // signal we can act on, while a minority verdict must never stand in
5162        // for a healthy one. A one-candidate run needs no panel at all, and
5163        // `judges` stays `0` rather than the roster size a panel that never
5164        // sat would otherwise be credited with.
5165        let needs_quorum = viable.len() > 1;
5166        let judges_total = if needs_quorum {
5167            self.roles.judges.len()
5168        } else {
5169            0
5170        };
5171        let quorum = if needs_quorum {
5172            judges_total / 2 + 1
5173        } else {
5174            0
5175        };
5176        let met_quorum = !needs_quorum || present >= quorum;
5177        let uncontested = (!needs_quorum).then(|| {
5178            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
5179        });
5180
5181        self.state.event(
5182            "tally",
5183            match &uncontested {
5184                Some(reason) => format!("winner {winner} — {reason}"),
5185                None => format!(
5186                    "winner {winner} — votes {} | initial {} | {} changed | \
5187                     {present}/{judges_total} judges{}",
5188                    first_choice
5189                        .iter()
5190                        .map(|(k, v)| format!("{k}:{v}"))
5191                        .collect::<Vec<_>>()
5192                        .join(" "),
5193                    if unanimous_initial {
5194                        "unanimous"
5195                    } else {
5196                        "split"
5197                    },
5198                    changed_votes,
5199                    if met_quorum {
5200                        String::new()
5201                    } else {
5202                        format!(" — below quorum ({quorum} required)")
5203                    },
5204                ),
5205            },
5206        );
5207        if !met_quorum {
5208            self.state.event(
5209                "stall",
5210                format!(
5211                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
5212                     the run stops here, resumable"
5213                ),
5214            );
5215        }
5216        self.state.tally = Some(Tally {
5217            first_choice,
5218            borda,
5219            winner,
5220            rankings: tops.len(),
5221            unanimous_initial,
5222            deliberated,
5223            changed_votes,
5224            unanimous_final,
5225            tie_break,
5226            judges: judges_total,
5227            present,
5228            quorum,
5229            met_quorum,
5230            uncontested,
5231        });
5232        self.state.status = if met_quorum {
5233            RunStatus::Reviewing
5234        } else {
5235            RunStatus::Stalled
5236        };
5237        self.state.save()?;
5238        Ok(())
5239    }
5240
5241    // ------------------------------------------------------------- recover
5242
5243    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
5244    /// resumed toward completion once the transient cause clears.
5245    ///
5246    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
5247    /// it toward the quorum, which is exactly the set of seats whose absence
5248    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
5249    /// not depend on which node happened to hit the limit), or an ordinary
5250    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
5251    /// seat is never disturbed.
5252    ///
5253    /// A seat that now answers with a usable ranking is "recovered": its
5254    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
5255    /// `tally` counts it present again), and its vote re-collected. A seat that
5256    /// still fails keeps its loss and stays absent.
5257    ///
5258    /// Returns `true` when the re-tally restores the quorum (the run may proceed
5259    /// to review/gate/merge), `false` when it is still below quorum (the run
5260    /// stays `Stalled`, still resumable for a later retry).
5261    #[allow(clippy::too_many_lines)]
5262    async fn recover_stall(&mut self) -> Result<bool> {
5263        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
5264        // agent files with `magi task add` name the run that paid for it. The
5265        // prompt overlay is cloned alongside it because the waves borrow it
5266        // while `self` is mutably borrowed by the node's own bookkeeping.
5267        let run_id = self.state.id.clone();
5268        let prompts = self.state.config.prompts.clone();
5269        // Absent seats = quota-lost at any node, or failed outright. Mirroring
5270        // `tally`'s presence test (rather than the old quota-judge/vote filter)
5271        // is what keeps a non-quota collapse — or a quota loss recorded at the
5272        // deliberate node — from being a permanent dead-end on `--resume`.
5273        let quota_seats: BTreeSet<&str> =
5274            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5275        let absent: Vec<String> = self
5276            .state
5277            .judgements
5278            .iter()
5279            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
5280            .map(|j| j.seat.clone())
5281            .collect();
5282        if absent.is_empty() {
5283            return Ok(false);
5284        }
5285        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
5286        if viable.len() <= 1 {
5287            return Ok(false);
5288        }
5289        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
5290        let language = self.state.config.graph.language.clone();
5291        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
5292        let sessions = self.state.config.graph.sessions;
5293        let artifacts = agent::artifacts_dir(&self.state.dir());
5294        let root = self.state.worktree_root();
5295        let base_short = short(&self.state.base_commit);
5296        let candidates: Vec<Candidate> = viable.clone();
5297
5298        // Map each absent seat key to its 0-based position in `roles.judges`.
5299        let mut positions: Vec<usize> = absent
5300            .iter()
5301            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5302            .collect();
5303        if positions.is_empty() {
5304            return Ok(false);
5305        }
5306        positions.sort_unstable();
5307        positions.dedup();
5308
5309        // Re-rank the lost seats, one blind prompt each.
5310        let mut judge_jobs = Vec::new();
5311        for &j in &positions {
5312            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5313            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5314            let seat_key = format!("judge-{}", j + 1);
5315            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5316            let seat = self.seat(&seat_key, &spec.id);
5317            judge_jobs.push(SeatJob {
5318                spec,
5319                seat,
5320                prompt: prompt::judge(
5321                    &self.state.instruction,
5322                    &views,
5323                    self.roles.judges.len(),
5324                    &base_short,
5325                    &language,
5326                ),
5327                cwd: root.join(seat_key),
5328                timeout,
5329                allow_write: false,
5330                sessions,
5331                artifacts: artifacts.clone(),
5332                stem: format!("judge-{}-recover", j + 1),
5333                handover: None,
5334            });
5335        }
5336
5337        let labels_for_check = labels.clone();
5338        let mut judge_losses = Vec::new();
5339        let retries = self.state.config.graph.retries;
5340        let cache = self.state.config.cache_dir();
5341        let ctx = WaveCtx {
5342            carry_seats: false,
5343            pauses: Some((&self.pause, &self.interrupt)),
5344            run: &run_id,
5345            node: "judge",
5346            prompts: &prompts,
5347            cache: cache.as_deref(),
5348            round: None,
5349        };
5350        let results = ask_json_wave::<Ranking>(
5351            judge_jobs,
5352            Arc::clone(&self.sem),
5353            retries,
5354            &self.roles.judge_roster,
5355            &ctx,
5356            &mut judge_losses,
5357            &mut self.state,
5358            &move |r: &Ranking| r.validate(&labels_for_check),
5359        )
5360        .await;
5361        if self.state.resource_block.is_some() {
5362            self.stop_for_resource()?;
5363            return Ok(false);
5364        }
5365
5366        // Refresh the judgement of every seat that ranked again.
5367        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5368        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5369            let agent_id = seat.agent.clone();
5370            self.state.seats.insert(seat.key.clone(), seat);
5371            let record = &mut self.state.judgements[j];
5372            match res {
5373                Ok((ranking, out)) => {
5374                    record.agent = agent_id;
5375                    record.ranking = ranking.normalized();
5376                    record.reasons = ranking.reasons;
5377                    record.strengths = ranking.strengths;
5378                    record.confidence = ranking.confidence;
5379                    record.failed = None;
5380                    record.duration_ms = out.duration_ms;
5381                    recovered.insert(j);
5382                    self.state.event(
5383                        "recover",
5384                        format!("judge {} ranked again after the limit", j + 1),
5385                    );
5386                }
5387                Err(e) => {
5388                    self.state
5389                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5390                }
5391            }
5392        }
5393
5394        // Re-ask the votes of the seats that recovered a ranking.
5395        let mut vote_jobs = Vec::new();
5396        let mut vote_pos: Vec<usize> = Vec::new();
5397        for &j in &recovered {
5398            let seat_key = format!("judge-{}", j + 1);
5399            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5400            let seat = self.seat(&seat_key, &spec.id);
5401            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5402            let text = if has_context(&spec, &seat, sessions) {
5403                prompt::final_vote(&labels, &language)
5404            } else {
5405                full.clone()
5406            };
5407            vote_jobs.push(SeatJob {
5408                spec,
5409                seat,
5410                prompt: text,
5411                cwd: root.join(seat_key),
5412                timeout,
5413                allow_write: false,
5414                sessions,
5415                artifacts: artifacts.clone(),
5416                stem: format!("vote-judge-{}-recover", j + 1),
5417                handover: Some(full),
5418            });
5419            vote_pos.push(j);
5420        }
5421        let allowed = labels.clone();
5422        let mut vote_losses = Vec::new();
5423        let vote_retries = self.state.config.graph.retries;
5424        let vote_cache = self.state.config.cache_dir();
5425        let ctx = WaveCtx {
5426            carry_seats: false,
5427            pauses: Some((&self.pause, &self.interrupt)),
5428            run: &run_id,
5429            node: "vote",
5430            prompts: &prompts,
5431            cache: vote_cache.as_deref(),
5432            round: None,
5433        };
5434        let votes = ask_json_wave::<FinalVote>(
5435            vote_jobs,
5436            Arc::clone(&self.sem),
5437            vote_retries,
5438            &self.roles.judge_roster,
5439            &ctx,
5440            &mut vote_losses,
5441            &mut self.state,
5442            &move |v: &FinalVote| match v.label() {
5443                Some(c) if allowed.contains(&c) => Ok(()),
5444                other => bail!("vote {other:?} is not one of {allowed:?}"),
5445            },
5446        )
5447        .await;
5448        if self.state.resource_block.is_some() {
5449            self.stop_for_resource()?;
5450            return Ok(false);
5451        }
5452        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5453            let agent_id = seat.agent.clone();
5454            self.state.seats.insert(seat.key.clone(), seat);
5455            match res {
5456                Ok((v, _)) => {
5457                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5458                        rec.vote = v.label();
5459                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5460                    } else {
5461                        self.state.votes.push(VoteRecord {
5462                            judge: j + 1,
5463                            agent: agent_id,
5464                            vote: v.label(),
5465                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5466                            changed: false,
5467                        });
5468                    }
5469                    self.state.event(
5470                        "recover",
5471                        format!("judge {} voted again after the limit", j + 1),
5472                    );
5473                }
5474                Err(e) => {
5475                    self.state
5476                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5477                }
5478            }
5479        }
5480
5481        // A seat that ranked again is present even if its re-vote failed —
5482        // `tally` falls back to the initial ranking's first choice — so clear
5483        // its quota loss. Seats that still fail keep theirs and stay absent.
5484        let recovered_keys: BTreeSet<String> = recovered
5485            .iter()
5486            .map(|&j| format!("judge-{}", j + 1))
5487            .collect();
5488        self.state
5489            .quota
5490            .retain(|q| !recovered_keys.contains(&q.seat));
5491        // A seat that hit the limit again is a fresh loss, not the old one:
5492        // replace the stale entry so the history stays one-per-seat and the
5493        // daemon can tell this attempt's loss from a previous session's.
5494        for loss in judge_losses.into_iter().chain(vote_losses) {
5495            if recovered_keys.contains(&loss.seat) {
5496                continue;
5497            }
5498            self.state.quota.retain(|q| q.seat != loss.seat);
5499            self.state.quota.push(loss);
5500        }
5501
5502        // Recompute the verdict from the refreshed panel.
5503        self.state.tally = None;
5504        self.tally()?;
5505        Ok(self
5506            .state
5507            .tally
5508            .as_ref()
5509            .map(|t| t.met_quorum)
5510            .unwrap_or(false))
5511    }
5512
5513    // ---------------------------------------------------------------- graft
5514
5515    /// Port the strengths the judges attributed to the losing candidates onto
5516    /// the winner, once, between the tally and the review loop.
5517    ///
5518    /// Best-effort by construction: it returns nothing and fails nothing. A
5519    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5520    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5521    /// the run carries on as if the phase were off. See [`graft`] for the
5522    /// decisions and `AGENTS.md` for the invariants.
5523    ///
5524    /// The one exception is a rollback that could not be confirmed: the
5525    /// rejected commit may still be the winner's tip, so the run is blocked
5526    /// (resumable; the record stays `Running`, which makes a resume retry the
5527    /// restore) instead of reviewing, gating and merging it.
5528    async fn graft(&mut self) -> Result<()> {
5529        let Err(e) = self.graft_inner().await else {
5530            return Ok(());
5531        };
5532        if e.is::<crate::repo_lock::ResourceBlocked>() {
5533            return Err(e);
5534        }
5535        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5536            self.state.status = RunStatus::Blocked;
5537            self.state.event("graft", format!("blocked: {e:#}"));
5538            self.state.save()?;
5539            return Err(e);
5540        }
5541        // An error after the `Running` record was saved may have left the
5542        // fixer's work in the tree: the record must not stay unsettled
5543        // (a later resume would reset past the review fixes), so confirm the
5544        // restore now, or block.
5545        if let Some(rec) = self.state.graft.clone()
5546            && !rec.outcome.settled()
5547        {
5548            if let Some(winner) = self.state.winner().cloned() {
5549                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5550                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5551                        return Err(re);
5552                    }
5553                    self.state.status = RunStatus::Blocked;
5554                    self.state.event("graft", format!("blocked: {re:#}"));
5555                    self.state.save()?;
5556                    return Err(re);
5557                }
5558            }
5559            if let Some(g) = self.state.graft.as_mut() {
5560                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5561            }
5562        }
5563        self.state.event("graft", format!("skipped: {e:#}"));
5564        if let Err(e) = self.state.save() {
5565            tracing::warn!("save after graft: {e:#}");
5566        }
5567        Ok(())
5568    }
5569
5570    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5571    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5572    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5573        let _coordination = self.coordinate(wt).await?;
5574        crate::recovery::restore_repair(wt, pre)
5575            .await
5576            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5577    }
5578
5579    /// A skip is a run event, recorded once however often the node is re-entered.
5580    fn graft_skipped(&mut self, why: &str) {
5581        let message = format!("skipped: {why}");
5582        if !self
5583            .state
5584            .events
5585            .iter()
5586            .any(|e| e.node == "graft" && e.message == message)
5587        {
5588            self.state.event("graft", message);
5589        }
5590    }
5591
5592    async fn graft_inner(&mut self) -> Result<()> {
5593        // A round that was started and never finished (crash, kill): the
5594        // fixer may have left anything in the tree, so put the winner back.
5595        if let Some(rec) = self.state.graft.clone()
5596            && !rec.outcome.settled()
5597        {
5598            // Reviews exist only if the graft ended without its record being
5599            // settled (a swallowed error): the tree has moved on since, and
5600            // a reset to `pre` would discard the review fixes.
5601            if self.state.reviews.is_empty()
5602                && let Some(winner) = self.state.winner().cloned()
5603            {
5604                self.graft_restore(&winner.worktree, &rec.pre).await?;
5605            }
5606            if rec.outcome == GraftOutcome::WaitingForRestore {
5607                self.state.graft = None;
5608                self.state.save()?;
5609            } else {
5610                if let Some(g) = self.state.graft.as_mut() {
5611                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5612                }
5613                self.state.event(
5614                    "graft",
5615                    "rolled back: the previous round was interrupted; the winner is untouched",
5616                );
5617                self.state.save()?;
5618                return Ok(());
5619            }
5620        }
5621        let plan = match graft::plan(&self.state) {
5622            Ok(plan) => plan,
5623            Err(skip) => {
5624                if skip != graft::Skip::AlreadyDone {
5625                    self.graft_skipped(skip.reason());
5626                    self.state.save()?;
5627                }
5628                return Ok(());
5629            }
5630        };
5631        let Some(winner) = self.state.winner().cloned() else {
5632            return Ok(());
5633        };
5634        let wt = winner.worktree.clone();
5635        if !git::is_clean(&wt).await? {
5636            self.graft_skipped("the winner's worktree has uncommitted changes");
5637            self.state.save()?;
5638            return Ok(());
5639        }
5640        let pre = git::rev_parse(&wt, "HEAD").await?;
5641        // Saved before the fixer is called: a stop from here on is repaired
5642        // by the branch above on the next entry.
5643        self.state.graft = Some(GraftRecord {
5644            pre: pre.clone(),
5645            post: None,
5646            lines: None,
5647            limit: None,
5648            agent: None,
5649            outcome: GraftOutcome::Running,
5650            requested: graft::requested(&plan),
5651            adoption: None,
5652            adoption_error: None,
5653        });
5654        self.state.event(
5655            "graft",
5656            format!(
5657                "porting strengths of candidate(s) {} onto {}",
5658                plan.strengths
5659                    .iter()
5660                    .map(|(l, _, _)| l.to_string())
5661                    .collect::<Vec<_>>()
5662                    .join(", "),
5663                plan.winner
5664            ),
5665        );
5666        self.state.save()?;
5667
5668        let fix_prompt = prompt::graft(
5669            &self.state.instruction,
5670            plan.winner,
5671            &plan.strengths,
5672            &self.state.config.graph.language,
5673        );
5674        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5675        let sessions = self.state.config.graph.sessions;
5676        let artifacts = agent::artifacts_dir(&self.state.dir());
5677        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5678        let (_, seat, out) = self
5679            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5680                SeatJob {
5681                    prompt: fix_prompt.clone(),
5682                    spec,
5683                    seat,
5684                    cwd: wt.clone(),
5685                    timeout,
5686                    allow_write: true,
5687                    sessions,
5688                    artifacts: artifacts.clone(),
5689                    stem: "graft".to_owned(),
5690                    handover: None,
5691                }
5692            })
5693            .await;
5694        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5695            // Preserve the need to restore earlier fallback edits without
5696            // confusing an unstarted seat with an interrupted invocation.
5697            self.state.graft.as_mut().expect("graft record").outcome =
5698                GraftOutcome::WaitingForRestore;
5699            return self.stop_for_resource();
5700        }
5701        let mut why: Option<String> = None;
5702        match &out {
5703            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5704                why = Some("the fixer produced nothing usable".to_owned());
5705            }
5706            AgentOutcome::Ok(_) => {}
5707            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5708            AgentOutcome::Quota(o) => {
5709                self.state.quota.push(QuotaLoss::from_report(
5710                    seat.key.clone(),
5711                    "graft",
5712                    o.quota.as_ref(),
5713                ));
5714                why = Some("rate limited (quota)".to_owned());
5715            }
5716            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5717                why = Some(format!(
5718                    "the fixer failed: {}",
5719                    e.lines()
5720                        .next()
5721                        .unwrap_or("")
5722                        .chars()
5723                        .take(160)
5724                        .collect::<String>()
5725                ));
5726            }
5727        }
5728        let agent_id = seat.agent.clone();
5729        self.state.seats.insert(seat.key.clone(), seat);
5730
5731        let mut post = None;
5732        let mut lines = None;
5733        let _coordination = self.coordinate(&wt).await?;
5734        if why.is_none() {
5735            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5736            if let Ok(r) = &rescued {
5737                self.state.note_withheld("graft", &r.withheld);
5738            }
5739            let head = git::rev_parse(&wt, "HEAD").await?;
5740            // What is measured must be what gets reviewed and gated: a failed
5741            // rescue, or anything still uncommitted (withheld lockfiles
5742            // aside, which are never part of the tree), rejects the graft.
5743            let dirty = match &rescued {
5744                Ok(r) => git::status_porcelain(&wt)
5745                    .await
5746                    .map(|st| {
5747                        st.lines().any(|l| {
5748                            !r.withheld
5749                                .iter()
5750                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5751                        })
5752                    })
5753                    .unwrap_or(true),
5754                Err(_) => true,
5755            };
5756            if dirty {
5757                why = Some("the fixer left changes that could not be committed".to_owned());
5758            } else if head == pre {
5759                why = Some("the fixer changed nothing".to_owned());
5760            } else {
5761                lines = git::changed_lines(&wt, &pre, &head).await;
5762                post = Some(head);
5763            }
5764        }
5765        let (adoption, adoption_error) = match &out {
5766            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5767            _ => (None, None),
5768        };
5769        let requested = graft::requested(&plan);
5770        let outcome = match why {
5771            None => {
5772                self.state.event(
5773                    "graft",
5774                    format!(
5775                        "applied: {}",
5776                        lines.map_or_else(
5777                            || "changed lines unavailable".to_owned(),
5778                            |n| format!("{n} changed lines")
5779                        )
5780                    ),
5781                );
5782                GraftOutcome::Applied
5783            }
5784            Some(why) => {
5785                // Not settled until the restore is confirmed: the record
5786                // stays `Running`, so a resume retries it.
5787                crate::recovery::restore_repair(&wt, &pre)
5788                    .await
5789                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5790                self.state.event(
5791                    "graft",
5792                    format!("rolled back: {why}; the winner is untouched"),
5793                );
5794                GraftOutcome::RolledBack(why)
5795            }
5796        };
5797        self.state.graft = Some(GraftRecord {
5798            pre,
5799            post,
5800            lines,
5801            limit: None,
5802            agent: Some(agent_id),
5803            outcome,
5804            requested,
5805            adoption,
5806            adoption_error,
5807        });
5808        self.state.save()?;
5809        Ok(())
5810    }
5811
5812    // ----------------------------------------------------------------- fold
5813
5814    async fn fold_losers(&mut self) -> Result<()> {
5815        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5816            return Ok(());
5817        };
5818        if !self.state.candidate_preservation.is_empty() {
5819            bail!("candidate preservation incomplete; refusing cleanup");
5820        }
5821        let repo = self.state.repo.clone();
5822        let _coordination = self.coordinate(&repo).await?;
5823        let home = crate::run::home();
5824        let root = self.state.worktree_root();
5825        let isolated = crate::build_target::isolated(&self.state.config);
5826        let mut folded = Vec::new();
5827        for i in 0..self.state.candidates.len() {
5828            let c = &self.state.candidates[i];
5829            if c.label == winner || c.folded {
5830                continue;
5831            }
5832            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5833            let target = fold_target(&home, &root, &wt, isolated);
5834            remove_preserved_worktree(&repo, &wt).await?;
5835            reclaim_fold_target(&home, target);
5836            if git::branch_exists(&repo, &branch).await?
5837                && !git::branch_delete(&repo, &branch).await?
5838            {
5839                bail!("candidate branch removal refused");
5840            }
5841            self.state.candidates[i].folded = true;
5842            self.state.save()?;
5843            folded.push(label.to_string());
5844        }
5845        // The judges are finished; their checkouts are pure cost from here.
5846        for j in 1..=self.roles.judges.len() {
5847            let wt = root.join(format!("judge-{j}"));
5848            if wt.exists() {
5849                let target = fold_target(&home, &root, &wt, isolated);
5850                remove_read_seat_worktree(&mut self.state, &wt).await?;
5851                reclaim_fold_target(&home, target);
5852                self.state.save()?;
5853            }
5854        }
5855        // The design-deliberation stage is finished by the time a tally
5856        // exists — same reasoning as the judges above.
5857        if self.state.config.graph.advise {
5858            for k in 1..=self.state.config.graph.advisors {
5859                let wt = root.join(format!("advisor-{k}"));
5860                if wt.exists() {
5861                    let target = fold_target(&home, &root, &wt, isolated);
5862                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5863                    reclaim_fold_target(&home, target);
5864                    self.state.save()?;
5865                }
5866            }
5867        }
5868        if !folded.is_empty() {
5869            self.state
5870                .event("fold", format!("folded candidates {}", folded.join(", ")));
5871            self.state.save()?;
5872        }
5873        Ok(())
5874    }
5875
5876    // ------------------------------------------------------------ base sync
5877
5878    async fn hold_base_sync(&mut self) -> Result<bool> {
5879        self.hold_base_sync_as(None).await
5880    }
5881
5882    async fn hold_base_sync_kind(
5883        &mut self,
5884        kind: crate::base_sync_recovery::StopKind,
5885    ) -> Result<()> {
5886        self.hold_base_sync_as(Some(kind)).await?;
5887        Ok(())
5888    }
5889
5890    async fn hold_base_sync_as(
5891        &mut self,
5892        kind: Option<crate::base_sync_recovery::StopKind>,
5893    ) -> Result<bool> {
5894        if !self.state.base_sync_blocked() {
5895            self.state.base_sync_recovery.stop = None;
5896            return Ok(false);
5897        }
5898        let head = match self.state.winner() {
5899            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5900                .await
5901                .unwrap_or_default(),
5902            None => String::new(),
5903        };
5904        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5905            && !authorization.consumed
5906            && authorization.stop.head != head
5907        {
5908            authorization.refuse(format!(
5909                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5910                authorization.stop.head
5911            ));
5912        }
5913        self.state.record_base_sync_stop(&head);
5914        if let Some(kind) = kind {
5915            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5916            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5917                stop.kind = kind;
5918            }
5919        }
5920        self.state.save()?;
5921        Ok(true)
5922    }
5923
5924    async fn resume_legacy_sequencer_stop(
5925        &mut self,
5926        winner: &Candidate,
5927        scratch: &Path,
5928        head: &str,
5929    ) -> Result<()> {
5930        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5931
5932        if !resumable_sequencer_stop(&self.state)
5933            || legacy_sequencer_head(&self.state) != Some(head)
5934            || self.state.base_recovery_pending()
5935            || self
5936                .state
5937                .repair_grants
5938                .iter()
5939                .any(|grant| !grant.succeeded)
5940        {
5941            return Ok(());
5942        }
5943        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5944            return Ok(());
5945        };
5946        let owner = crate::queue::Queue::open().get(task)?;
5947        if owner.execution_runs().last() != Some(&self.state.id)
5948            || owner.status == crate::queue::TaskStatus::Done
5949            || owner.fresh_start
5950            || owner.review_branch.is_some()
5951            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5952        {
5953            return Ok(());
5954        }
5955
5956        let repo = self.state.repo.clone();
5957        let wait = repository_wait(&self.state, None);
5958        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5959        let common = crate::repo_lock::common_dir(&repo).await?;
5960        let op = self.state.base_sync_recovery.operations.last().unwrap();
5961        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5962            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5963            || git::current_branch(&winner.worktree).await?.as_deref()
5964                != Some(winner.branch.as_str())
5965            || common.is_none()
5966            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5967            || crate::repo_lock::common_dir(&owner.repo).await? != common
5968            || !git::is_clean(&winner.worktree).await?
5969        {
5970            return Ok(());
5971        }
5972        if scratch.try_exists()? {
5973            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5974            if admin.join("locked").try_exists()?
5975                || !git::git(
5976                    scratch,
5977                    &[
5978                        "status",
5979                        "--porcelain",
5980                        "--untracked-files=all",
5981                        "--ignored",
5982                    ],
5983                )
5984                .await?
5985                .is_empty()
5986            {
5987                return Ok(());
5988            }
5989            if git::checked_rebase_in_progress(scratch).await? {
5990                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5991                    || crate::rebase::rebase_target(scratch).await? != op.tip
5992                    || !git::unmerged_paths(scratch).await?.is_empty()
5993                {
5994                    return Ok(());
5995                }
5996            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5997                || git::rev_parse(scratch, "HEAD").await? != head
5998            {
5999                return Ok(());
6000            }
6001        }
6002
6003        self.state
6004            .base_sync_recovery
6005            .operations
6006            .last_mut()
6007            .unwrap()
6008            .finished = false;
6009        let diagnostic = self
6010            .state
6011            .base_sync
6012            .as_mut()
6013            .unwrap()
6014            .conflict
6015            .take()
6016            .unwrap();
6017        self.state.base_sync_recovery.stop = None;
6018        self.state.event(
6019            "rebase",
6020            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
6021        );
6022        self.state.save()
6023    }
6024
6025    /// Land the winner's tree on the current tip of `<remote>/<base>` before
6026    /// anything verifies it.
6027    ///
6028    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
6029    /// read whatever is checked out in the winner's worktree. Left alone that
6030    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
6031    /// it when the run *branched* - and a run takes long enough that the base
6032    /// has usually moved by the time it gets here. A gate that ran there
6033    /// answers "green on the commit this run started from", not "green on
6034    /// what is about to land", and the difference showed up three times in
6035    /// one day as a green run whose merge would have reverted a file another
6036    /// pull request had already landed.
6037    ///
6038    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
6039    /// `land::Step::Rebase` calls, rather than a second implementation of the
6040    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
6041    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
6042    /// doc warns about ("two answers to a question nobody notices until a
6043    /// diff is wrong").
6044    ///
6045    /// Foreign-checkout reviews instead merge the base into the owned shadow
6046    /// worktree, preserving the ancestry required for fast-forward delivery.
6047    /// A conflicting merge is aborted and held for operator resolution.
6048    ///
6049    /// A conflict is not the end of the road: the standing rebase is handed
6050    /// to the fixer seat, at most `graph.review_rounds` times, counted in
6051    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
6052    /// land). Once it finishes, review and the gate run as usual on the
6053    /// rebased tree, which is where a breakage the new base caused is caught
6054    /// by the ordinary gate-fix round. magi resolves nothing itself.
6055    ///
6056    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
6057    /// the current durable recovery interval, bounds how often the base is
6058    /// synchronized during active recovery (lifetime attempts remain evidence).
6059    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
6060    /// rebase the branch is restored, `state.base_sync.conflict` is set with
6061    /// what was tried (rounds spent, paths still conflicted) and the branch
6062    /// and worktree stay exactly as they were - untouched, for a person to
6063    /// look at - which is also what makes re-entering this function
6064    /// afterwards a no-op instead of a second attempt at the same wall. A
6065    /// push failure ends the same way.
6066    async fn sync_to_base(&mut self) -> Result<()> {
6067        if self.state.status == RunStatus::AlreadyInBase {
6068            return Ok(());
6069        }
6070        self.hold_base_sync().await?;
6071        let Some(winner) = self.state.winner().cloned() else {
6072            return Ok(());
6073        };
6074
6075        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
6076
6077        let repo = self.state.repo.clone();
6078        let remote = self.state.config.merge.remote.clone();
6079        let base_branch = self.state.base_branch.clone();
6080        let tracking = format!("{remote}/{base_branch}");
6081
6082        let fetched_base =
6083            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
6084        if !fetched_base
6085            && self
6086                .state
6087                .base_sync_recovery
6088                .stop
6089                .as_ref()
6090                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
6091        {
6092            self.state.event(
6093                "land",
6094                "cannot recheck recorded public branch divergence without a fresh base",
6095            );
6096            self.state.save()?;
6097            return Ok(());
6098        }
6099        // No network, or the remote never had this branch: the run already
6100        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
6101        // otherwise), and one that got this far is not blocked by a fetch
6102        // that fails now. It just has no newer tip to compare against.
6103        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
6104            return Ok(());
6105        };
6106
6107        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
6108        self.state.ensure_base_episode();
6109        let scratch = self.state.dir().join("base-sync");
6110        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
6111            .await?;
6112        let conflicted = self
6113            .state
6114            .base_sync
6115            .as_ref()
6116            .is_some_and(|s| s.conflict.is_some());
6117        let mut pending = self.state.pending_base_operation().cloned();
6118        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
6119        {
6120            Ok(active) => active,
6121            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
6122            Err(error) => return Err(error),
6123        };
6124        if in_progress {
6125            // Older resource stops predate operation reservations. Import the
6126            // standing Git operation, never retarget it to today's main.
6127            if pending.is_none()
6128                && self.state.base_sync_recovery.operations.is_empty()
6129                && !conflicted
6130                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
6131                    .await
6132                    .ok()
6133                    .as_deref()
6134                    == Some(head.as_str())
6135                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6136                && git::is_clean(&winner.worktree).await?
6137            {
6138                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
6139                if self.state.base_sync.is_none() {
6140                    self.state.base_sync = Some(BaseSync {
6141                        tip: saved_tip.clone(),
6142                        behind: 0,
6143                        attempts: 0,
6144                        conflict: None,
6145                        already_in: None,
6146                    });
6147                }
6148                self.state.reserve_base_operation(&head, &saved_tip);
6149                self.state.event(
6150                    "base-recovery",
6151                    "imported standing legacy rebase as a spent synchronization reservation",
6152                );
6153                self.state.save()?;
6154                pending = self.state.base_sync_recovery.operations.last().cloned();
6155            }
6156            let expected = pending.as_ref().map(|op| op.tip.as_str());
6157            if expected.is_none()
6158                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
6159            {
6160                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
6161                if self.state.base_sync.is_none() {
6162                    self.state.base_sync = Some(BaseSync {
6163                        tip: tip.clone(),
6164                        behind: 0,
6165                        attempts: 0,
6166                        conflict: None,
6167                        already_in: None,
6168                    });
6169                }
6170                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
6171                self.state.event("land", why);
6172                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6173                    .await?;
6174                return Ok(());
6175            }
6176        }
6177        if let Some(op) = &pending {
6178            // A replay may add the pinned base's commits, never foreign work.
6179            let mut replay_proven =
6180                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
6181            if !replay_proven && !in_progress && scratch.try_exists()? {
6182                let wait = repository_wait(&self.state, None);
6183                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6184                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
6185                    Ok(true) => {
6186                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
6187                        self.state.save()?;
6188                        git::worktree_remove(&repo, &scratch).await.ok();
6189                        replay_proven = true;
6190                    }
6191                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
6192                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
6193                }
6194            }
6195            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
6196                if self.state.foreign_checkout.is_some() {
6197                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
6198                        .await
6199                        .ok()
6200                        .as_deref()
6201                        == Some(op.head.as_str())
6202                        && git::rev_parse(&repo, &format!("{head}^2"))
6203                            .await
6204                            .ok()
6205                            .as_deref()
6206                            == Some(op.tip.as_str());
6207                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
6208                    .await
6209                    .is_ok_and(|m| m.is_empty())
6210                    && let Ok(added) =
6211                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
6212                {
6213                    replay_proven = true;
6214                    for commit in added {
6215                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
6216                            replay_proven = false;
6217                            break;
6218                        }
6219                    }
6220                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
6221                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
6222                }
6223            }
6224            // Never retarget an operation across a crash, even if main moved.
6225            // sync_to_head resets and cleans with -x, so even ignored untracked
6226            // files must stop recovery independently of the old tracked tree.
6227            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6228                || (head != op.head
6229                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
6230                        .await?
6231                        .is_empty())
6232                || (!git::is_clean(&winner.worktree).await?
6233                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
6234                        .await
6235                        .is_ok_and(|o| o.ok()))
6236                || !replay_proven
6237            {
6238                let why = format!(
6239                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
6240                    op.id
6241                );
6242                let sync = self
6243                    .state
6244                    .base_sync
6245                    .as_mut()
6246                    .context("reserved synchronization has no lifetime accounting")?;
6247                sync.conflict = Some(why.clone());
6248                self.state.event("land", why);
6249                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6250                    .await?;
6251                return Ok(());
6252            }
6253            if head != op.head {
6254                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6255            }
6256            tip = op.tip.clone();
6257        }
6258        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
6259        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
6260        if pending.is_none()
6261            && !conflicted
6262            && fetched_base
6263            && self
6264                .state
6265                .base_sync_recovery
6266                .episodes
6267                .last()
6268                .is_some_and(|e| e.boundary.is_some())
6269            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
6270            && let Ok(owner) = crate::queue::Queue::open().get(&task)
6271            && owner.execution_runs().last() == Some(&self.state.id)
6272            && owner.status != crate::queue::TaskStatus::Done
6273            && !owner.fresh_start
6274            && owner.review_branch.is_none()
6275            && crate::daemon::compatible_run_instruction(&self.state, &owner)
6276            && let Some(approval) = owner.resumption.as_ref()
6277            && approval.instruction == owner.instruction
6278            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6279            && git::is_clean(&winner.worktree).await?
6280            && self.state.renew_base_episode(&task, approval, &head, &tip)
6281        {
6282            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
6283            self.state.save()?;
6284        }
6285
6286        // Before any rebase, and before a recorded conflict is honoured: a
6287        // branch whose change reached the base under other commit ids has
6288        // nothing to rebase and nothing to conflict with, and a run that
6289        // already stopped on that phantom conflict recovers here on resume.
6290        // `behind == 0` with head == tip is a branch the base has since taken
6291        // in whole, whether or not a conflict was ever recorded: the ancestry
6292        // proof must still run (`classify` ignores a head still on the start
6293        // commit).
6294        if (behind > 0 || conflicted || head == tip)
6295            && self
6296                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
6297                .await?
6298        {
6299            return Ok(());
6300        }
6301        if conflicted && self.state.base_recovery_pending() {
6302            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6303            let owner =
6304                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6305            let owner_valid = owner.as_ref().is_ok_and(|t| {
6306                t.execution_runs().last() == Some(&self.state.id)
6307                    && t.assignment_accepts(&self.state)
6308                    && t.status != crate::queue::TaskStatus::Done
6309                    && !t.fresh_start
6310                    && t.review_branch.is_none()
6311            });
6312            let invalidation = if !owner_valid {
6313                Some("latest task ownership changed")
6314            } else if !owner.as_ref().is_ok_and(|t| {
6315                authorization
6316                    .generation
6317                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6318            }) {
6319                Some("owner approval generation changed")
6320            } else if authorization.question.as_ref().is_some_and(|question| {
6321                !crate::base_recovery_control::decision_current(
6322                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6323                    &self.state,
6324                    &authorization.task,
6325                    question,
6326                )
6327            }) {
6328                Some("recovery decision ownership, routing or stop evidence changed")
6329            } else if authorization.request.is_some()
6330                && !owner
6331                    .as_ref()
6332                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6333            {
6334                Some("owner decision changed")
6335            } else if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown
6336                && !authorization.scope.as_ref().is_some_and(|scope| {
6337                    scope.preparation_digest.is_some()
6338                        && scope.preparation_digest == self.state.preparation_digest(&head)
6339                })
6340            {
6341                Some("scratch preparation stop evidence changed")
6342            } else if let Some(scope) = &authorization.scope {
6343                if scope.tip != tip {
6344                    Some("fetched base changed")
6345                } else if !self
6346                    .state
6347                    .base_sync_recovery
6348                    .episodes
6349                    .last()
6350                    .is_some_and(|e| e.id == scope.episode)
6351                {
6352                    Some("active synchronization interval changed")
6353                } else if !owner
6354                    .as_ref()
6355                    .is_ok_and(|t| t.instruction == scope.instruction)
6356                {
6357                    Some("task instruction changed")
6358                } else {
6359                    None
6360                }
6361            } else {
6362                None
6363            };
6364            if let Some(reason) = invalidation {
6365                let authorization = self
6366                    .state
6367                    .base_sync_recovery
6368                    .authorizations
6369                    .last_mut()
6370                    .unwrap();
6371                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6372                self.state.save()?;
6373                return Ok(());
6374            }
6375            if !fetched_base
6376                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6377                || !git::is_clean(&winner.worktree).await?
6378                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6379            {
6380                return Ok(());
6381            }
6382            if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown {
6383                git::check_rebase_preparation(&self.state, &head, &self.state.dir()).await?;
6384            }
6385        }
6386        let recovery = conflicted && self.state.consume_base_recovery(&head);
6387        if conflicted {
6388            // Consumption (including a refused changed HEAD) is durable before Git.
6389            self.state.save()?;
6390            if !recovery {
6391                return Ok(());
6392            }
6393        }
6394
6395        if behind == 0 {
6396            // A fixer-finished rebase moves the branch ref before the
6397            // winner's worktree is told (`sync_to_head` below). A run that
6398            // died in between resumes here with `behind == 0` and a tree still
6399            // holding the pre-rebase files, which review and the gate would
6400            // then read. That state is exactly: HEAD moved off the tip the
6401            // rebase started from, yet the tree is still identical to that
6402            // tip. A tree with edits of its own differs from it, so nothing
6403            // is thrown away.
6404            if let Some(from) = self
6405                .state
6406                .rebase_fixes
6407                .iter()
6408                .rev()
6409                .find_map(|r| r.from.clone())
6410                && from != head
6411                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6412                    .await
6413                    .is_ok_and(|o| o.ok())
6414            {
6415                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6416            }
6417            // An earlier attempt may have rebased the branch locally and died
6418            // before pushing it (only the fresh-rebase arm below pushes).
6419            // Publish it now, so the plain push at PR time is not refused as
6420            // a non-fast-forward. A run already holding a recorded conflict
6421            // never reaches here; that case is out of scope.
6422            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6423            if let Some(why) = &conflict {
6424                self.state.status = RunStatus::Blocked;
6425                self.state.event("land", why.clone());
6426            }
6427            self.state.base_sync = Some(BaseSync {
6428                tip,
6429                behind: 0,
6430                attempts,
6431                conflict,
6432                already_in: None,
6433            });
6434            if pending.is_some() {
6435                self.state.finish_base_operation(Some(&head));
6436            }
6437            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6438                .await?;
6439            self.state.save()?;
6440            return Ok(());
6441        }
6442
6443        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6444            let why = format!(
6445                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6446                 synchronization(s); synchronizing again would only race it",
6447                winner.branch
6448            );
6449            self.state.status = RunStatus::Blocked;
6450            self.state.base_sync = Some(BaseSync {
6451                tip,
6452                behind,
6453                attempts,
6454                conflict: Some(why.clone()),
6455                already_in: None,
6456            });
6457            self.state.event("land", why);
6458            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6459                .await?;
6460            self.state.save()?;
6461            return Ok(());
6462        }
6463
6464        if self.state.foreign_checkout.is_some() {
6465            // Delivery to the operator's checkout is fast-forward only. A
6466            // rebase here would discard its saved head from our ancestry.
6467            let wait = repository_wait(&self.state, None);
6468            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6469            if self.state.base_sync.is_none() {
6470                self.state.base_sync = Some(BaseSync {
6471                    tip: tip.clone(),
6472                    behind,
6473                    attempts: 0,
6474                    conflict: None,
6475                    already_in: None,
6476                });
6477            }
6478            self.state.reserve_base_operation(&head, &tip);
6479            self.state.save()?;
6480            let merged = git::git_raw(
6481                &winner.worktree,
6482                &[
6483                    "-c",
6484                    "core.hooksPath=/dev/null",
6485                    "merge",
6486                    "--no-ff",
6487                    "--no-autostash",
6488                    "--no-edit",
6489                    "-m",
6490                    &format!("Merge {tracking} before verifying"),
6491                    &tip,
6492                ],
6493            )
6494            .await?;
6495            let conflict = if merged.ok() {
6496                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6497                self.state.event(
6498                    "land",
6499                    format!("merged {tracking} into {} before verifying", winner.branch),
6500                );
6501                None
6502            } else {
6503                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6504                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6505                }
6506                let why = format!(
6507                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6508                    winner.branch,
6509                    merged.stderr.chars().take(600).collect::<String>()
6510                );
6511                self.state.status = RunStatus::Blocked;
6512                self.state.event("land", &why);
6513                Some(why)
6514            };
6515            let synced = conflict.is_none();
6516            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6517            self.state
6518                .finish_base_operation(synced.then_some(fresh.as_str()));
6519            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6520            self.state.base_sync = Some(BaseSync {
6521                tip,
6522                behind: if synced { 0 } else { behind },
6523                attempts,
6524                conflict,
6525                already_in: None,
6526            });
6527            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6528                .await?;
6529            self.state.save()?;
6530            return Ok(());
6531        }
6532
6533        self.state.event(
6534            "land",
6535            format!(
6536                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6537                winner.branch
6538            ),
6539        );
6540        self.state.save()?;
6541
6542        // The remote's copy of the branch, read now and only if the fetch
6543        // really succeeded (a stale tracking ref must never pin a lease). It is
6544        // pushed over after a rebase only when it is a commit this branch
6545        // already contains, by ancestry or by patch (an earlier rebase of ours
6546        // that never reached the remote): anything else is somebody else's work.
6547        let branch_tracking = format!("{remote}/{}", winner.branch);
6548        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6549        let remote_tip = if self.state.task_pr_branch().is_none()
6550            && matches!(&fetched_branch, Ok(o) if o.ok())
6551        {
6552            git::rev_parse(&repo, &branch_tracking).await.ok()
6553        } else {
6554            None
6555        };
6556        // A remote tip this branch does not contain is somebody else's work:
6557        // rebasing would leave a local tip that can never be pushed. Stop
6558        // before touching anything and say so.
6559        if let Some(theirs) = &remote_tip
6560            && !git::is_ancestor(&repo, theirs, &head).await
6561            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6562                .await
6563                .is_ok_and(|missing| missing.is_empty())
6564        {
6565            let why = format!(
6566                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6567                 them",
6568                short(theirs),
6569                winner.branch
6570            );
6571            self.state.status = RunStatus::Blocked;
6572            self.state.base_sync = Some(BaseSync {
6573                tip,
6574                behind,
6575                attempts,
6576                conflict: Some(why.clone()),
6577                already_in: None,
6578            });
6579            self.state.event("land", why);
6580            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6581                .await?;
6582            self.state.save()?;
6583            return Ok(());
6584        }
6585
6586        if self.state.base_sync.is_none() {
6587            self.state.base_sync = Some(BaseSync {
6588                tip: tip.clone(),
6589                behind,
6590                attempts: 0,
6591                conflict: None,
6592                already_in: None,
6593            });
6594        }
6595        let scratch = self.state.dir().join("base-sync");
6596        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6597        {
6598            if error.is::<crate::repo_lock::ResourceBlocked>() {
6599                return Ok(());
6600            }
6601            return Err(error);
6602        }
6603        self.state.reserve_base_operation(&head, &tip);
6604        self.state.save()?;
6605        let rebased =
6606            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6607                .await
6608            {
6609                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6610                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6611                Err(e) => Err(e),
6612            };
6613        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6614        let stop_kind = match &rebased {
6615            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6616            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6617            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6618        };
6619        match rebased {
6620            Ok(None) => {
6621                // The branch ref moved, but a worktree that already had it
6622                // checked out (the winner's) was not told; sync its index and
6623                // files before anything reads them.
6624                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6625                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6626                self.state.finish_base_operation(Some(&fresh));
6627                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6628                let mut conflict = None;
6629                if let Some(pinned) = &remote_tip {
6630                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6631                    match pushed {
6632                        Ok(o) if o.ok() => self.state.event(
6633                            "land",
6634                            format!("pushed rebased {} to {remote}", winner.branch),
6635                        ),
6636                        Ok(o) => {
6637                            conflict = Some(format!(
6638                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6639                                winner.branch,
6640                                short(pinned),
6641                                o.stderr.chars().take(600).collect::<String>()
6642                            ));
6643                        }
6644                        Err(e) => {
6645                            conflict = Some(format!(
6646                                "rebased {} locally but could not push it: {e:#}",
6647                                winner.branch
6648                            ));
6649                        }
6650                    }
6651                }
6652                if let Some(why) = &conflict {
6653                    self.state.status = RunStatus::Blocked;
6654                    self.state.event("land", why.clone());
6655                }
6656                self.state.base_sync = Some(BaseSync {
6657                    tip: tip.clone(),
6658                    behind: 0,
6659                    attempts,
6660                    conflict,
6661                    already_in: None,
6662                });
6663                self.state
6664                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6665            }
6666            Ok(Some(conflict)) => {
6667                self.state.finish_base_operation(None);
6668                let why = format!(
6669                    "{} conflicts with {tracking} and did not rebase: {}",
6670                    winner.branch,
6671                    conflict.chars().take(600).collect::<String>()
6672                );
6673                self.state.status = RunStatus::Blocked;
6674                self.state.base_sync = Some(BaseSync {
6675                    tip,
6676                    behind,
6677                    attempts,
6678                    conflict: Some(why.clone()),
6679                    already_in: None,
6680                });
6681                self.state.event("land", why);
6682            }
6683            // A refused Git write or a busy repository: nothing is wrong with
6684            // the branch. The scratch rebase stays standing and the run
6685            // resumes into it (`base_sync` must not claim a conflict).
6686            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6687                self.state.save()?;
6688                return Ok(());
6689            }
6690            Err(e) => {
6691                self.state.finish_base_operation(None);
6692                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6693                self.state.status = RunStatus::Blocked;
6694                self.state.base_sync = Some(BaseSync {
6695                    tip,
6696                    behind,
6697                    attempts,
6698                    conflict: Some(why.clone()),
6699                    already_in: None,
6700                });
6701                self.state.event("land", why);
6702            }
6703        }
6704        if !self.state.base_sync_blocked() {
6705            self.state.base_sync_recovery.stop = None;
6706        }
6707        self.hold_base_sync_kind(stop_kind).await?;
6708        self.state.save()?;
6709        Ok(())
6710    }
6711
6712    /// Push a branch an earlier attempt rebased locally but never published,
6713    /// pinned to the remote tip read right after a successful fetch. Returns
6714    /// the reason when the run must stop; `None` when there was nothing to do
6715    /// (no remote copy, the same tip, or a remote copy this branch already
6716    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6717    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6718        // Task competitions publish only after the PR text gate, to their
6719        // public head; never resurrect a candidate branch on the remote.
6720        if self.state.task_pr_branch().is_some() {
6721            return None;
6722        }
6723        let repo = self.state.repo.clone();
6724        let remote = self.state.config.merge.remote.clone();
6725        let fetched = git::fetch(&repo, &remote, branch).await;
6726        if !matches!(&fetched, Ok(o) if o.ok()) {
6727            return None;
6728        }
6729        let branch_tracking = format!("{remote}/{branch}");
6730        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6731        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6732            return None;
6733        }
6734        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6735            .await
6736            .is_ok_and(|missing| missing.is_empty())
6737        {
6738            return Some(format!(
6739                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6740                 them",
6741                short(&theirs)
6742            ));
6743        }
6744        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6745            Ok(o) if o.ok() => {
6746                self.state
6747                    .event("land", format!("pushed rebased {branch} to {remote}"));
6748                None
6749            }
6750            Ok(o) => Some(format!(
6751                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6752                 someone may have pushed): {}",
6753                short(&theirs),
6754                o.stderr.chars().take(600).collect::<String>()
6755            )),
6756            Err(e) => Some(format!(
6757                "{branch} is rebased locally but could not be pushed: {e:#}"
6758            )),
6759        }
6760    }
6761
6762    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6763    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6764    /// whether it did.
6765    ///
6766    /// Checked only when the base is ahead of the branch. A failing check is
6767    /// "not proven" - the ordinary rebase path then decides - never a reason to
6768    /// stop the run.
6769    ///
6770    /// The remote copy of the branch is held to the same standard as the local
6771    /// one: if it carries a tip this worktree does not, that tip must itself be
6772    /// proven in the base, or nothing is settled (a pull request would
6773    /// otherwise be closed over commits nobody checked). The pull request is
6774    /// closed *before* the terminal status is saved; if that fails for a
6775    /// reason other than a refusal (no network, a `gh` error) the run is left
6776    /// `Blocked` with the reason as its conflict, which a resume retries -
6777    /// the same recovery a phantom conflict gets.
6778    async fn settle_already_in(
6779        &mut self,
6780        branch: &str,
6781        tip: &str,
6782        head: &str,
6783        attempts: usize,
6784        behind: usize,
6785    ) -> Result<bool> {
6786        let repo = self.state.repo.clone();
6787        let remote = self.state.config.merge.remote.clone();
6788        let start = self.state.base_commit.clone();
6789        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6790            Ok(Some(e)) => e,
6791            Ok(None) => return Ok(false),
6792            Err(e) => {
6793                tracing::warn!("already-in-base check for {branch}: {e:#}");
6794                return Ok(false);
6795            }
6796        };
6797        let mut verified = vec![head.to_owned()];
6798        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6799        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6800        let divergence = self
6801            .state
6802            .base_sync_recovery
6803            .stop
6804            .as_ref()
6805            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6806        if matches!(&fetched, Ok(o) if o.ok()) {
6807            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6808                Ok(theirs) if theirs != head => {
6809                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6810                        Ok(Some(_)) => verified.push(theirs),
6811                        _ => return Ok(false),
6812                    }
6813                }
6814                Err(_) if divergence => return Ok(false),
6815                _ => {}
6816            }
6817        } else if divergence
6818            && !matches!(
6819                git::remote_has_branch(&repo, &remote, &public_branch).await,
6820                Ok(false)
6821            )
6822        {
6823            // A failed fetch cannot discharge a recorded divergence.
6824            return Ok(false);
6825        }
6826        let base_branch = self.state.base_branch.clone();
6827        let message = format!(
6828            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6829             land",
6830            evidence.names(),
6831            evidence.proof.as_str()
6832        );
6833        let closed =
6834            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6835                .await;
6836        match closed {
6837            Ok(Ok(url)) => self
6838                .state
6839                .event("land", format!("closed {url}: superseded on {base_branch}")),
6840            Ok(Err(why)) => self
6841                .state
6842                .event("land", format!("did not close a pull request: {why}")),
6843            Err(e) => {
6844                let why = format!(
6845                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6846                     not be closed ({e:#}); resume to retry"
6847                );
6848                self.state.status = RunStatus::Blocked;
6849                self.state.base_sync = Some(BaseSync {
6850                    tip: tip.to_owned(),
6851                    behind,
6852                    attempts,
6853                    conflict: Some(why.clone()),
6854                    already_in: None,
6855                });
6856                self.state.event("land", why);
6857                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6858                    .await?;
6859                self.state.save()?;
6860                return Ok(true);
6861            }
6862        }
6863        self.state.status = RunStatus::AlreadyInBase;
6864        self.state.base_sync_recovery.stop = None;
6865        self.state.base_sync = Some(BaseSync {
6866            tip: tip.to_owned(),
6867            behind,
6868            attempts,
6869            conflict: None,
6870            already_in: Some(evidence),
6871        });
6872        self.state.event("land", message);
6873        self.state.save()?;
6874        self.settle_questions();
6875        Ok(true)
6876    }
6877
6878    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6879    /// last landed the winner on, once it has run, else the commit the run
6880    /// branched from.
6881    ///
6882    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6883    /// and `vote` all happen before there is a winner to rebase, so they
6884    /// compare every candidate against the branch point on purpose, and a
6885    /// base that moves after they are already done cannot change an answer
6886    /// they already gave.
6887    fn landing_base(&self) -> String {
6888        self.state
6889            .base_sync
6890            .as_ref()
6891            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6892    }
6893
6894    // ------------------------------------------------------- operator fix
6895
6896    /// Route specific, already-recorded review findings to a fixer for a
6897    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6898    /// entry point.
6899    ///
6900    /// Distinct from `review_loop`'s own fix step in three ways: it never
6901    /// runs a reviewer wave, it never spends review-round budget, and what
6902    /// happened is recorded as an [`OperatorFixRequest`] appended to
6903    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6904    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6905    /// and vote must never be rewritten to look like a manufactured blocking
6906    /// verdict.
6907    ///
6908    /// Only meaningful once review has actually concluded: `Ready` (handed
6909    /// off with findings still open, or simply concluded clean while minor
6910    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6911    /// gate failed). Everything else is refused: a run still in progress
6912    /// should simply be resumed, and a `Merged` run's branch has already
6913    /// landed — reopening *this* run's own record cannot change that, so the
6914    /// answer there is a fresh `magi review <branch>`.
6915    ///
6916    /// A real commit here re-verifies through a fresh, ordinary review-only
6917    /// run on the same branch ([`Self::review`]) rather than reopening this
6918    /// run's own `review_loop`: once any round in this run's history went
6919    /// clean, `review_conclusion` treats that as permanent by design (the
6920    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6921    /// way to force one more genuine reviewer wave out of *this* run without
6922    /// either rewriting history or weakening that guarantee for every other
6923    /// caller. A review-only run costs nothing extra — no implementation, no
6924    /// judging, no vote — and exercises the exact same review → verify →
6925    /// gate → (human) merge path, unmodified.
6926    pub async fn fix_selected(
6927        &mut self,
6928        ids: &[String],
6929        reason: &str,
6930        allow_stale: bool,
6931    ) -> Result<()> {
6932        let reason = reason.trim();
6933        if reason.is_empty() {
6934            bail!("a fix request needs a reason — that is the operator's own record of why");
6935        }
6936        if ids.is_empty() {
6937            bail!("no finding id given");
6938        }
6939        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6940            bail!(
6941                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6942                 has already concluded — can be given a targeted fix. A run still \
6943                 in progress should simply be resumed; a `merged` run's branch has \
6944                 already landed, so its answer is a fresh `magi review <branch>`, \
6945                 not reopening this run's own record",
6946                self.state.id,
6947                self.state.status.as_str()
6948            );
6949        }
6950        // Reassignment shares this claim through its atomic task save. Check
6951        // the canonical run identity inside it, before preflight or any await.
6952        let _claim = FixClaim::acquire(&self.state.dir())?;
6953        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6954        let home = crate::run::home();
6955        // The ordinary driver takes these same locks at admission. Keep the
6956        // execution lease through the fix, but never the owner lock across Git
6957        // or agent awaits.
6958        let execution = {
6959            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6960            let disk = RunState::load(&self.state.id)?;
6961            crate::pr_head::ensure_owner(&disk)?;
6962            anyhow::ensure!(
6963                disk.status == self.state.status && disk.released_to.is_none(),
6964                "run changed since it was loaded; reload before fixing"
6965            );
6966            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6967            anyhow::ensure!(
6968                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6969                "run {} is currently being worked on or its ownership is unknown",
6970                disk.id
6971            );
6972            let lease = crate::driver::maintenance(&home, &disk.id).context(
6973                "run is currently being worked on or its execution lease is unavailable",
6974            )?;
6975            self.state = disk;
6976            lease
6977        };
6978        let Some(winner) = self.state.winner().cloned() else {
6979            bail!("run {} has no winning candidate to fix", self.state.id);
6980        };
6981        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6982            bail!(
6983                "branch `{}` no longer exists; this run cannot be extended",
6984                winner.branch
6985            );
6986        }
6987        // Resolve every id before spending anything — an unknown id refuses
6988        // the whole request rather than silently dropping it — and dedup
6989        // while keeping the operator's own order.
6990        let mut seen = BTreeSet::new();
6991        let mut findings = Vec::new();
6992        let mut missing = Vec::new();
6993        for id in ids {
6994            if !seen.insert(id.clone()) {
6995                continue;
6996            }
6997            match self.state.finding(id) {
6998                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6999                    id: f.id.clone(),
7000                    severity: f.severity,
7001                    reviewer_vote: rec.vote,
7002                    round: round.round,
7003                    round_head: round.head.clone(),
7004                    reviewer: rec.reviewer,
7005                    agent: rec.agent.clone(),
7006                    file: f.file.clone(),
7007                    line: f.line,
7008                    title: f.title.clone(),
7009                    detail: f.detail.clone(),
7010                    outcome: OperatorFixOutcome::Pending,
7011                }),
7012                None => missing.push(id.clone()),
7013            }
7014        }
7015        if !missing.is_empty() {
7016            bail!(
7017                "unknown finding id(s): {}; nothing was changed",
7018                missing.join(", ")
7019            );
7020        }
7021
7022        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
7023        let stale_details: Vec<(String, String)> = findings
7024            .iter()
7025            .filter(|f| f.round_head != head_at_request)
7026            .map(|f| (f.id.clone(), f.round_head.clone()))
7027            .collect();
7028        let stale = !stale_details.is_empty();
7029        if stale && !allow_stale {
7030            bail!(
7031                "the branch has moved since some finding(s) were raised — {} — now \
7032                 at {}; pass --allow-stale to fix anyway, or re-run review first",
7033                stale_details
7034                    .iter()
7035                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
7036                    .collect::<Vec<_>>()
7037                    .join(", "),
7038                short(&head_at_request)
7039            );
7040        }
7041
7042        let request = OperatorFixRequest {
7043            requested_at: Timestamp::now(),
7044            reason: reason.to_owned(),
7045            findings,
7046            head_at_request: head_at_request.clone(),
7047            allow_stale,
7048            stale,
7049            fix: None,
7050            result_head: None,
7051            follow_up_review_run: None,
7052        };
7053        self.state.event(
7054            "fix",
7055            format!(
7056                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
7057                request.findings.len(),
7058                request
7059                    .findings
7060                    .iter()
7061                    .map(|f| f.id.as_str())
7062                    .collect::<Vec<_>>()
7063                    .join(", "),
7064            ),
7065        );
7066        // Recorded now, before any worktree work or the fixer call itself —
7067        // and re-saved at each checkpoint below: a crash at any point after
7068        // this (mid fixer call, mid follow-up review) must not lose the fact
7069        // that this was requested, for which findings, and why. Everything
7070        // past this point reads and writes through `request_index` rather
7071        // than a local variable, since `request` itself is moved here.
7072        self.state.operator_fixes.push(request);
7073        self.state.save()?;
7074        let request_index = self.state.operator_fixes.len() - 1;
7075
7076        // A fresh, dedicated worktree for this one call, never the winner's
7077        // own worktree in place: that one may already be gone (folded away),
7078        // and reusing it in place would leave the branch checked out there
7079        // when the follow-up review below tries to check it out again. Freed
7080        // immediately after, either way — but only once confirmed clean:
7081        // `worktree_remove` is a `git worktree remove --force`, which would
7082        // otherwise discard uncommitted work left there by the operator or
7083        // another process before this had a chance to even look at it.
7084        let repo = self.state.repo.clone();
7085        let coordination = self.coordinate(&repo).await?;
7086        if winner.worktree.exists() {
7087            // Lockfiles a rescue commit withheld stay untracked on purpose and
7088            // are already recorded; they are not the operator's work to protect.
7089            let dirty = git::git(
7090                &winner.worktree,
7091                &["status", "--porcelain", "--untracked-files=all"],
7092            )
7093            .await?;
7094            let only_withheld = dirty.lines().all(|l| {
7095                l.strip_prefix("?? ")
7096                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
7097            });
7098            if !only_withheld {
7099                bail!(
7100                    "`{}` has uncommitted changes; refusing to touch it — commit or \
7101                     discard them first",
7102                    winner.worktree.display()
7103                );
7104            }
7105            git::worktree_remove(&self.state.repo, &winner.worktree)
7106                .await
7107                .ok();
7108        }
7109        let fix_worktree = self.state.worktree_root().join("operator-fix");
7110        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
7111        git::git(
7112            &self.state.repo,
7113            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
7114        )
7115        .await
7116        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
7117        if !git::is_clean(&fix_worktree).await? {
7118            git::worktree_remove(&self.state.repo, &fix_worktree)
7119                .await
7120                .ok();
7121            bail!(
7122                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
7123                winner.branch
7124            );
7125        }
7126        let repo_for_setup = self.state.repo.clone();
7127        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
7128            Ok(()) => {
7129                worktree_setup::prepare_with(
7130                    &self.state.config,
7131                    &repo_for_setup,
7132                    &fix_worktree,
7133                    crate::build_target::Coordination::Held(coordination.as_ref()),
7134                )
7135                .await
7136            }
7137            Err(e) => Err(e),
7138        };
7139        if let Err(e) = setup {
7140            git::worktree_remove(&self.state.repo, &fix_worktree)
7141                .await
7142                .ok();
7143            return Err(e);
7144        }
7145
7146        // This explicit operator request retries availability independently
7147        // of execute(); the previous call has already saved and cleaned up.
7148        self.state.resource_block = None;
7149
7150        let run_id = self.state.id.clone();
7151        let prompts = self.state.config.prompts.clone();
7152        let language = self.state.config.graph.language.clone();
7153        let sessions = self.state.config.graph.sessions;
7154        let artifacts = agent::artifacts_dir(&self.state.dir());
7155        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
7156            .findings
7157            .iter()
7158            .map(|f| Finding {
7159                id: f.id.clone(),
7160                severity: f.severity,
7161                file: f.file.clone(),
7162                line: f.line,
7163                title: f.title.clone(),
7164                detail: f.detail.clone(),
7165            })
7166            .collect();
7167        let fix_prompt = prompt::operator_fix_in(
7168            &self.state.instruction,
7169            &finding_list,
7170            reason,
7171            &stale_details,
7172            &head_at_request,
7173            &language,
7174            &self.state.config.graph.github_language,
7175        );
7176        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7177        drop(coordination);
7178        let (job, seat, out) = self
7179            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
7180                prompt: fix_prompt.clone(),
7181                spec,
7182                seat,
7183                cwd: fix_worktree.clone(),
7184                timeout,
7185                allow_write: true,
7186                sessions,
7187                artifacts: artifacts.clone(),
7188                stem: "operator-fix".to_owned(),
7189                handover: None,
7190            })
7191            .await;
7192        let agent_id = seat.agent.clone();
7193
7194        let mut fix = FixRecord {
7195            agent: agent_id,
7196            addressed: Vec::new(),
7197            rejected: Vec::new(),
7198            notes: String::new(),
7199            committed: false,
7200            failed: None,
7201            duration_ms: 0,
7202            continuation: None,
7203        };
7204        let mut final_seat = seat.clone();
7205        match out {
7206            AgentOutcome::Ok(o) => {
7207                fix.duration_ms = o.duration_ms;
7208                let parsed = verdict::extract_json::<FixReport>(&o.text);
7209                let incomplete_reason = match &parsed {
7210                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
7211                        "the reply parsed, but it reported a command whose own CLI \
7212                         never confirmed an exit status"
7213                            .to_owned(),
7214                    ),
7215                    Ok(_) => None,
7216                    Err(e) => Some(e.to_string()),
7217                };
7218                match incomplete_reason {
7219                    None => {
7220                        let report = parsed.expect("checked Ok above");
7221                        fix.addressed = report.addressed;
7222                        fix.rejected = report.rejected;
7223                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
7224                    }
7225                    Some(reason) => {
7226                        let (resumed_seat, resolved, failure, cont) = self
7227                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
7228                            .await;
7229                        fix.duration_ms += cont.cumulative_wait_ms;
7230                        fix.continuation = Some(cont);
7231                        final_seat = resumed_seat;
7232                        match resolved {
7233                            Some(report) => {
7234                                fix.addressed = report.addressed;
7235                                fix.rejected = report.rejected;
7236                                fix.notes =
7237                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
7238                            }
7239                            None => fix.failed = failure,
7240                        }
7241                    }
7242                }
7243            }
7244            AgentOutcome::Dropped(o) => {
7245                fix.duration_ms = o.duration_ms;
7246                let why = o
7247                    .dropped
7248                    .as_ref()
7249                    .map(|d| d.why.as_str())
7250                    .unwrap_or("the CLI ended the stream without delivering its answer");
7251                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
7252            }
7253            AgentOutcome::Quota(o) => {
7254                self.state.quota.push(QuotaLoss::from_report(
7255                    final_seat.key.clone(),
7256                    "fix",
7257                    o.quota.as_ref(),
7258                ));
7259                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
7260            }
7261            AgentOutcome::Failed(e) => fix.failed = Some(e),
7262            AgentOutcome::ResourceBlocked(e) => {
7263                fix.failed = Some(format!("the fixer was not started: {e}"));
7264            }
7265        }
7266        // Even a deferred call must rescue edits, release the worktree and
7267        // finalize its record below so an explicit `magi fix` can retry.
7268        if fix.continuation.is_none() {
7269            fix.continuation = Some(ContinuationRecord::not_needed());
7270        }
7271        self.state.seats.insert(final_seat.key.clone(), final_seat);
7272
7273        let rescue_message = format!(
7274            "magi: operator-selected fix ({}) (uncommitted work)",
7275            self.state.operator_fixes[request_index]
7276                .findings
7277                .iter()
7278                .map(|f| f.id.as_str())
7279                .collect::<Vec<_>>()
7280                .join(", ")
7281        );
7282        let repo = self.state.repo.clone();
7283        let coordination = self.coordinate(&repo).await?;
7284        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
7285            self.state.note_withheld("fix", &r.withheld);
7286        }
7287        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
7288        fix.committed = after != head_at_request;
7289        git::worktree_remove(&self.state.repo, &fix_worktree)
7290            .await
7291            .ok();
7292        drop(coordination);
7293
7294        self.state.event(
7295            "fix",
7296            match &fix.failed {
7297                Some(reason) => format!(
7298                    "operator fix: adoption report was lost ({reason}); {}",
7299                    if fix.committed {
7300                        "committed"
7301                    } else {
7302                        "NO new commit"
7303                    }
7304                ),
7305                None => format!(
7306                    "operator fix: {} addressed, {} rejected, {}",
7307                    fix.addressed.len(),
7308                    fix.rejected.len(),
7309                    if fix.committed {
7310                        "committed"
7311                    } else {
7312                        "NO new commit"
7313                    }
7314                ),
7315            },
7316        );
7317
7318        // Every selected finding gets an outcome — never left `Pending` once
7319        // the fixer's own turn is over. A report that never came back at all
7320        // marks every one of them `Unreported`, not silently "not addressed":
7321        // quota, a dropped stream, or an exhausted continuation are gaps in
7322        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7323        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7324        for f in &mut self.state.operator_fixes[request_index].findings {
7325            f.outcome = if fix.failed.is_some() {
7326                OperatorFixOutcome::Unreported
7327            } else if fix.addressed.contains(&f.id) {
7328                OperatorFixOutcome::Addressed
7329            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7330                OperatorFixOutcome::Rejected { why: r.why.clone() }
7331            } else {
7332                OperatorFixOutcome::Unreported
7333            };
7334        }
7335
7336        let committed = fix.committed;
7337        if committed {
7338            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7339        }
7340        self.state.operator_fixes[request_index].fix = Some(fix);
7341        // Saved again now that the fixer's own outcome is final, on top of
7342        // the save right after the request was first pushed above.
7343        self.state.save()?;
7344        if self.state.resource_block.is_some() {
7345            return self.stop_for_resource();
7346        }
7347
7348        if committed {
7349            self.state.event(
7350                "fix",
7351                format!(
7352                    "operator fix committed {}; opening a follow-up review-only run",
7353                    short(&after)
7354                ),
7355            );
7356            self.state.save()?;
7357            drop(execution);
7358            // The new review owns its own execution. Update only its audit link
7359            // afterwards, since publication may have changed the old record.
7360            let event_count = self.state.events.len();
7361            let save_follow_up = |state: &mut RunState| -> Result<()> {
7362                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7363                let _execution = crate::driver::maintenance(&home, &state.id)?;
7364                let mut disk = RunState::load(&state.id)?;
7365                disk.events.extend(state.events.drain(event_count..));
7366                let follow_up = state.operator_fixes[request_index]
7367                    .follow_up_review_run
7368                    .clone();
7369                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7370                disk.save()?;
7371                *state = disk;
7372                Ok(())
7373            };
7374            // The operator asked for the fix, and the follow-up serves whatever
7375            // task the run it follows served.
7376            let origin =
7377                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7378            match Self::review(
7379                &self.state.repo,
7380                &winner.branch,
7381                self.state.config.clone(),
7382                origin,
7383            )
7384            .await
7385            {
7386                Ok(mut follow_up) => {
7387                    follow_up.state.event(
7388                        "start",
7389                        format!(
7390                            "requested by an operator fix on run {} for finding(s) {}",
7391                            self.state.id,
7392                            self.state.operator_fixes[request_index]
7393                                .findings
7394                                .iter()
7395                                .map(|f| f.id.as_str())
7396                                .collect::<Vec<_>>()
7397                                .join(", "),
7398                        ),
7399                    );
7400                    // A follow-up reviews the predecessor's work, not a new
7401                    // task instruction. Preserve its authored generation even
7402                    // if the queue instruction has since been edited.
7403                    if let Some(id) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) {
7404                        let authored = crate::queue::Queue::open()
7405                            .get(id)
7406                            .ok()
7407                            .filter(|task| {
7408                                crate::daemon::compatible_run_instruction(&self.state, task)
7409                            })
7410                            .map(|task| task.instruction);
7411                        follow_up.state.task_instruction = authored
7412                            .or_else(|| self.state.task_instruction.clone())
7413                            .or_else(|| Some(self.state.instruction.clone()));
7414                        follow_up.state.task_instruction_rev =
7415                            Some(self.state.task_instruction_rev.unwrap_or(0));
7416                    }
7417                    follow_up.state.save()?;
7418                    let follow_up_id = follow_up.state.id.clone();
7419                    // The follow-up is a run like any other: it belongs to the
7420                    // task of the run it follows, or to one filed for it.
7421                    let adopted = match crate::direct::adopt(
7422                        &follow_up.state,
7423                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7424                    ) {
7425                        Ok(a) => a,
7426                        Err(e) => {
7427                            // An ownerless run must not spend agent calls; it
7428                            // stays saved, and `magi run --resume` adopts it.
7429                            self.state.event(
7430                                "fix",
7431                                format!(
7432                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7433                                ),
7434                            );
7435                            save_follow_up(&mut self.state)?;
7436                            return Ok(());
7437                        }
7438                    };
7439                    let executed = follow_up.execute().await;
7440                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7441                    if let Some(a) = adopted {
7442                        a.finish(&follow_up.state, executed);
7443                    }
7444                    if let Some(e) = failure {
7445                        self.state.event(
7446                            "fix",
7447                            format!(
7448                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7449                            ),
7450                        );
7451                    }
7452                    self.state.operator_fixes[request_index].follow_up_review_run =
7453                        Some(follow_up_id);
7454                }
7455                Err(e) => {
7456                    self.state.event(
7457                        "fix",
7458                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7459                    );
7460                }
7461            }
7462            save_follow_up(&mut self.state)?;
7463        }
7464
7465        Ok(())
7466    }
7467
7468    // --------------------------------------------------------------- review
7469
7470    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7471    /// names, in order, each at most once, moving on only when the call
7472    /// advances (an error, a quota hit or nothing usable - the same decision
7473    /// point `agent::chain_advances` is for the other chained roles).
7474    ///
7475    /// Each agent gets its own seat from `Runner::seat`: the same agent
7476    /// continues its conversation (the winner's own implementer seat when it
7477    /// is the winner's author, now that the competition is over), another
7478    /// takes a fresh one so the full prompt is sent again. A handover is
7479    /// recorded under `node`, which is what makes the fallback stick for the
7480    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7481    /// is returned, so an exhausted chain reads exactly like a single failed
7482    /// fixer: one quota loss, the same wording, the same refund. An earlier
7483    /// attempt's edits are left in the tree and judged, with the final
7484    /// attempt's, by what git says afterwards.
7485    ///
7486    /// Returns the job that produced the outcome, for `continue_fix_report`.
7487    async fn ask_fixer(
7488        &mut self,
7489        winner: &Candidate,
7490        node: &'static str,
7491        round: Option<usize>,
7492        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7493    ) -> (SeatJob, SeatState, AgentOutcome) {
7494        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7495        self.ask_fixer_among(attempts, node, round, None, build)
7496            .await
7497    }
7498
7499    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7500    /// worktree and a commit: before the next agent is asked after one that
7501    /// did not satisfy the call, the worktree is put back on that commit, so
7502    /// a failed agent's partial edits are not carried into the next one.
7503    async fn ask_fixer_among(
7504        &mut self,
7505        attempts: Vec<(AgentSpec, String)>,
7506        node: &'static str,
7507        round: Option<usize>,
7508        restore: Option<(&Path, &str)>,
7509        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7510    ) -> (SeatJob, SeatState, AgentOutcome) {
7511        let run_id = self.state.id.clone();
7512        let prompts = self.state.config.prompts.clone();
7513        let cache = self.state.config.cache_dir();
7514        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7515        let mut last = None;
7516        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7517            let seat = self.seat(&key, &spec.id);
7518            let mut job = build(spec.clone(), seat);
7519            if i > 0 {
7520                job.stem = format!("{}-{}", job.stem, spec.id);
7521            }
7522            let ctx = WaveCtx {
7523                carry_seats: false,
7524                pauses: Some((&self.pause, &self.interrupt)),
7525                run: &run_id,
7526                node,
7527                prompts: &prompts,
7528                cache: cache.as_deref(),
7529                round,
7530            };
7531            let (seat, out) =
7532                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7533            // A resource block never advances the chain: the chosen agent
7534            // was not asked, so it must be the one asked again on resume.
7535            let advances = match &out {
7536                AgentOutcome::Ok(o) => agent::output_advances(o),
7537                AgentOutcome::ResourceBlocked(_) => false,
7538                _ => true,
7539            };
7540            if let Some(next) = ids.get(i + 1)
7541                && advances
7542            {
7543                self.state.seats.insert(seat.key.clone(), seat.clone());
7544                let class =
7545                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7546                let reason = match &out {
7547                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7548                    other => fail_reason(other),
7549                };
7550                // A failed agent's edits must not reach the next one, and a
7551                // restore that did not work ends the chain: the call fails
7552                // and the caller's own (confirmed) restore decides.
7553                if let Some((wt, rev)) = restore
7554                    && let Err(e) = self.graft_restore(wt, rev).await
7555                {
7556                    let why =
7557                        format!("could not restore the worktree before the next fixer: {e:#}");
7558                    tracing::warn!("{why}");
7559                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7560                        AgentOutcome::ResourceBlocked(why)
7561                    } else {
7562                        AgentOutcome::Failed(why)
7563                    };
7564                    last = Some((job, seat, out));
7565                    break;
7566                }
7567                record_handover(
7568                    &mut self.state,
7569                    node,
7570                    &seat.key,
7571                    &spec.id,
7572                    next,
7573                    &class,
7574                    &reason,
7575                );
7576                continue;
7577            }
7578            last = Some((job, seat, out));
7579            break;
7580        }
7581        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7582        if let AgentOutcome::Quota(output) = &out
7583            && node != "graft"
7584        {
7585            // Graft is best effort: its caller records the loss and restores
7586            // the pre-graft tree, then proceeds to review and gate.
7587            // Every fallback was tried. Machine outages cannot be repaired by
7588            // spending a fix round; use each caller's resumable resource path.
7589            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7590            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7591            self.state.quota.push(loss);
7592            self.state.seats.insert(seat.key.clone(), seat.clone());
7593            self.state.status = RunStatus::Blocked;
7594            return (
7595                job,
7596                seat,
7597                AgentOutcome::ResourceBlocked(
7598                    "fixer unavailable; restore agent availability and resume".into(),
7599                ),
7600            );
7601        }
7602        (job, seat, out)
7603    }
7604
7605    /// The one repair a verification-only failure earns (see
7606    /// [`crate::recovery`]), before the first review round of a run that took
7607    /// a branch over.
7608    ///
7609    /// Saved as started *before* the fixer is called, so a resume never
7610    /// repairs twice; a start found on re-entry is rolled back to the commit
7611    /// it began from. A failed or unusable fixer leaves the tree as it was and
7612    /// the review goes on over it, so the first round's own verification
7613    /// reports the failure again. The failure is never carried into a round as
7614    /// a result: verification is re-run on whatever commit this leaves.
7615    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7616        use crate::recovery::{Mode, Repair};
7617        if !self.state.reviews.is_empty() {
7618            return Ok(());
7619        }
7620        let Some(mut rec) = self.state.recovery.clone() else {
7621            return Ok(());
7622        };
7623        if rec.mode != Mode::VerifyRepair {
7624            return Ok(());
7625        }
7626        let wt = winner.worktree.clone();
7627        let mut head = git::rev_parse(&wt, "HEAD").await?;
7628        match rec.repair.clone() {
7629            Repair::Done { .. } => return Ok(()),
7630            Repair::WaitingForRestore { before } => {
7631                self.graft_restore(&wt, &before).await?;
7632                head = before;
7633                rec.repair = Repair::NotStarted;
7634                self.state.recovery = Some(rec.clone());
7635                self.state.save()?;
7636            }
7637            Repair::Started { before } => {
7638                // Interrupted: the unfinished edits are not trusted.
7639                // An unconfirmed rollback blocks the run with `Started` kept,
7640                // so a resume retries it; the tree is never reviewed as is.
7641                if let Err(e) = self.graft_restore(&wt, &before).await {
7642                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7643                        return Err(e);
7644                    }
7645                    return self
7646                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7647                        .await;
7648                }
7649                rec.repair = Repair::Done {
7650                    before: before.clone(),
7651                    after: before,
7652                    committed: false,
7653                    failed: Some("interrupted; rolled back".to_owned()),
7654                };
7655                self.state
7656                    .event("recovery", "the repair was interrupted and rolled back");
7657                self.state.recovery = Some(rec);
7658                self.state.save()?;
7659                return Ok(());
7660            }
7661            Repair::NotStarted => {}
7662        }
7663        if crate::recovery::recheck(&mut rec, &head) {
7664            self.state.event("recovery", rec.summary());
7665            self.state.recovery = Some(rec);
7666            self.state.save()?;
7667            return Ok(());
7668        }
7669        rec.repair = Repair::Started {
7670            before: head.clone(),
7671        };
7672        self.state.recovery = Some(rec.clone());
7673        self.state.save()?;
7674
7675        let language = self.state.config.graph.language.clone();
7676        let sessions = self.state.config.graph.sessions;
7677        let artifacts = agent::artifacts_dir(&self.state.dir());
7678        let fix_prompt = prompt::recovery_fix(
7679            &self.state.instruction,
7680            &rec,
7681            self.state.config.graph.review_rounds,
7682            &language,
7683        );
7684        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7685        self.state.event(
7686            "recovery",
7687            format!(
7688                "repair: the fixer starts from the failed verification on {}",
7689                short(&head)
7690            ),
7691        );
7692        let (_job, seat, out) = self
7693            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7694                prompt: fix_prompt.clone(),
7695                spec,
7696                seat,
7697                cwd: wt.clone(),
7698                timeout,
7699                allow_write: true,
7700                sessions,
7701                artifacts: artifacts.clone(),
7702                stem: "fix-recovery".to_owned(),
7703                handover: None,
7704            })
7705            .await;
7706        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7707            rec.repair = Repair::WaitingForRestore { before: head };
7708            self.state.recovery = Some(rec);
7709            return self.stop_for_resource();
7710        }
7711        let failed = match &out {
7712            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7713            AgentOutcome::Quota(o) => {
7714                self.state.quota.push(QuotaLoss::from_report(
7715                    seat.key.clone(),
7716                    "fix",
7717                    o.quota.as_ref(),
7718                ));
7719                Some("rate limited (quota); the fixer could not run".to_owned())
7720            }
7721            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7722            AgentOutcome::Failed(e) => Some(e.clone()),
7723        };
7724        self.state.seats.insert(seat.key.clone(), seat);
7725        let coordination = self.coordinate(&wt).await?;
7726        let failed = match failed {
7727            // The agent's partial edits are not kept.
7728            Some(why) => {
7729                if let Err(e) = git::restore_to(&wt, &head).await {
7730                    return self
7731                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7732                        .await;
7733                }
7734                Some(why)
7735            }
7736            None => {
7737                if let Ok(r) = git::rescue_commit(
7738                    &wt,
7739                    "magi: recovery repair of the failed verification (uncommitted work)",
7740                )
7741                .await
7742                {
7743                    self.state.note_withheld("fix", &r.withheld);
7744                }
7745                None
7746            }
7747        };
7748        let after = git::rev_parse(&wt, "HEAD").await?;
7749        drop(coordination);
7750        self.state.event(
7751            "recovery",
7752            match &failed {
7753                Some(why) => format!("repair: nothing kept ({why})"),
7754                None if after != head => {
7755                    format!("repair: committed {}", short(&after))
7756                }
7757                None => "repair: the fixer made no commit".to_owned(),
7758            },
7759        );
7760        rec.repair = Repair::Done {
7761            before: head.clone(),
7762            committed: after != head,
7763            after,
7764            failed,
7765        };
7766        self.state.recovery = Some(rec);
7767        self.state.save()?;
7768        Ok(())
7769    }
7770
7771    /// A repair whose rollback could not be confirmed: the run is blocked and
7772    /// resumable, and the unconfirmed state is never reviewed.
7773    async fn stop_recovery(
7774        &mut self,
7775        mut rec: crate::recovery::RecoveryRecord,
7776        head: &str,
7777        why: String,
7778    ) -> Result<()> {
7779        // `Started` stays recorded: a resume retries the restore.
7780        rec.repair = crate::recovery::Repair::Started {
7781            before: head.to_owned(),
7782        };
7783        self.state.recovery = Some(rec);
7784        self.state
7785            .event("recovery", format!("repair could not be undone: {why}"));
7786        self.state.status = RunStatus::Blocked;
7787        self.state.save()?;
7788        bail!("recovery repair could not be rolled back: {why}")
7789    }
7790
7791    async fn review_loop(&mut self) -> Result<()> {
7792        if self.hold_base_sync().await? {
7793            return Ok(());
7794        }
7795        loop {
7796            if self
7797                .state
7798                .base_sync
7799                .as_ref()
7800                .is_some_and(|s| s.conflict.is_some())
7801            {
7802                return Ok(());
7803            }
7804            if self.catchup_repairable() {
7805                let record = self.state.reviews.last().expect("repairable round").clone();
7806                let winner = self
7807                    .state
7808                    .winner()
7809                    .cloned()
7810                    .context("catch-up repair has no winner")?;
7811                if !self.fix_review_round(&winner, record).await? {
7812                    return Ok(());
7813                }
7814            }
7815            self.review_loop_pass().await?;
7816            if !self.catchup_repairable() {
7817                return Ok(());
7818            }
7819        }
7820    }
7821
7822    /// Derive an owed catch-up repair from durable round evidence, including
7823    /// reentry after a crash before the fixer was dispatched.
7824    fn catchup_repairable(&self) -> bool {
7825        self.state.reviews.len() < self.state.config.graph.review_rounds
7826            && self.state.reviews.last().is_some_and(|r| {
7827                !r.clean
7828                    && r.blocking == 0
7829                    && r.fix.is_none()
7830                    && r.e2e_status() == E2eStatus::Failed
7831            })
7832    }
7833
7834    async fn review_loop_pass(&mut self) -> Result<()> {
7835        // A base that would not rebase is a person's decision, not a review
7836        // round: nothing here would change the answer, and reviewers and a
7837        // fixer would be spending real budget on a tree that cannot land
7838        // regardless of what they find.
7839        if self
7840            .state
7841            .base_sync
7842            .as_ref()
7843            .is_some_and(|s| s.conflict.is_some())
7844        {
7845            return Ok(());
7846        }
7847        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7848        // agent files with `magi task add` name the run that paid for it. The
7849        // prompt overlay is cloned alongside it because the waves borrow it
7850        // while `self` is mutably borrowed by the node's own bookkeeping.
7851        let run_id = self.state.id.clone();
7852        let prompts = self.state.config.prompts.clone();
7853        let Some(winner) = self.state.winner().cloned() else {
7854            return Ok(());
7855        };
7856        let granted_review = self
7857            .state
7858            .repair_grants
7859            .last()
7860            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7861            .cloned();
7862        let fresh_review = granted_review
7863            .as_ref()
7864            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7865        let max_rounds = granted_review
7866            .as_ref()
7867            .map_or(self.state.config.graph.review_rounds, |g| {
7868                g.review_start.saturating_add(1)
7869            });
7870        // A clean round, an exhausted round budget, or a stalled tree (see
7871        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7872        // they are recorded — recomputed here, not read off `status`, so a
7873        // reentry into a run that already stopped restates the identical
7874        // verdict instead of silently handing back whatever an earlier node
7875        // in this same walk clobbered `status` to (a solo-candidate
7876        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7877        // below runs an empty range once the budget is spent, and would
7878        // otherwise fall through without touching `status` at all.
7879        if let Some(status) =
7880            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7881        {
7882            // A reentry after a crash between the last round's save and
7883            // `stop_reviewing` reaches the hand-off here, not there.
7884            if status == RunStatus::Gating {
7885                self.record_contested_handoff();
7886            }
7887            self.state.status = status;
7888            self.state.save()?;
7889            return Ok(());
7890        }
7891        self.state.status = RunStatus::Reviewing;
7892        // A last recorded round whose own verification never resolved
7893        // (`ResourceBlocked` — the shared build cache, not the patch) is
7894        // never a concluded round, whatever the round budget says: starting
7895        // a fresh round on top of it would spend a whole new reviewer wave
7896        // re-reading an unchanged patch instead of just retrying the one
7897        // check that actually needs it, and once the budget is spent the
7898        // loop below has nothing left to do at all (its range is empty).
7899        // Retry that check directly instead, exactly the same retry
7900        // `stop_reviewing` already does for its own catch-up case.
7901        if !fresh_review
7902            && self.state.reviews.last().is_some_and(|r| {
7903                r.e2e_status() == E2eStatus::ResourceBlocked
7904                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7905            })
7906        {
7907            let shell = self.state.config.shell();
7908            return self
7909                .stop_unresolved_review(
7910                    "the last round's own verification never resolved",
7911                    &shell,
7912                    &winner.worktree,
7913                )
7914                .await;
7915        }
7916
7917        if granted_review.is_none() {
7918            self.recovery_repair(&winner).await?;
7919        }
7920        if self.resource_halt()? {
7921            return Ok(());
7922        }
7923
7924        let repo = self.state.repo.clone();
7925        let root = self.state.worktree_root();
7926        let language = self.state.config.graph.language.clone();
7927        let sessions = self.state.config.graph.sessions;
7928        let artifacts = self.merge_repair_artifacts();
7929        let base = self.landing_base();
7930        let base_short = short(&base);
7931        let reviewers = self.roles.reviewers.clone();
7932        let shell = self.state.config.shell();
7933
7934        for round in (self.state.reviews.len() + 1)..=max_rounds {
7935            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7936            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7937            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7938            // The prior round's own record, already persisted — never a
7939            // hand-carried variable of just its failing output: that is
7940            // exactly what let a round's e2e result drift out of sync with
7941            // which commit it was actually about (see `SCHEMA`'s doc for
7942            // schema 8). Judged against `head`, the commit reviewers are
7943            // about to look at now, so the summary always reads as "an
7944            // earlier head" here — this round's own patch has not been
7945            // checked yet.
7946            let prev_verification = self
7947                .state
7948                .reviews
7949                .last()
7950                .and_then(|r| r.verification_summary(&head));
7951            // Only the first round of a run that took a branch over: later
7952            // rounds have this run's own history.
7953            let prior_section = match (&self.state.recovery, round) {
7954                (Some(rec), 1) if self.state.reviews.is_empty() => {
7955                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7956                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7957                            Some(crate::recovery::head_of(
7958                                &git::diff(&winner.worktree, reviewed, "HEAD")
7959                                    .await
7960                                    .unwrap_or_default(),
7961                                crate::recovery::SINCE_DIFF_MAX,
7962                            ))
7963                        }
7964                        _ => None,
7965                    };
7966                    Some(prompt::recovery_review(rec, since.as_deref()))
7967                }
7968                _ => None,
7969            };
7970
7971            // Each reviewer gets its own detached checkout of exactly this
7972            // commit: nobody can perturb the winner's tree, and the fixer can
7973            // keep working without racing a reviewer.
7974            let mut jobs = Vec::new();
7975            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7976                self.coordinate(&repo).await?
7977            } else {
7978                None
7979            };
7980            for (r, spec) in reviewers.iter().cloned().enumerate() {
7981                let wt = root.join(format!("review-{}", r + 1));
7982                // `clean -fdx` in a reset wipes setup's products, so every
7983                // round sets the seat up again.
7984                if wt.exists() {
7985                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7986                } else {
7987                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7988                        None
7989                    } else {
7990                        self.coordinate(&repo).await?
7991                    };
7992                    git::worktree_add_detached(&repo, &wt, &head).await?;
7993                }
7994                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7995                    None
7996                } else {
7997                    self.coordinate(&repo).await?
7998                };
7999                self.setup_seat_worktree(
8000                    &repo,
8001                    &wt,
8002                    false,
8003                    coordination.as_ref().or(_setup_lease.as_ref()),
8004                )
8005                .await?;
8006                let seat_key = format!("review-{}", r + 1);
8007                // The seat starts the round on whoever answered it last, not
8008                // on the agent the spec names, so a failure is not re-paid.
8009                let spec = pick_start_spec(
8010                    &self.roles.reviewer_roster,
8011                    spec,
8012                    self.state.seat_history.get(&seat_key),
8013                );
8014                let seat = self.seat(&seat_key, &spec.id);
8015                jobs.push(SeatJob {
8016                    prompt: prompt::review(&prompt::ReviewCtx {
8017                        instruction: &self.state.instruction,
8018                        branch: &winner.branch,
8019                        base_short: &base_short,
8020                        stat: &stat,
8021                        patch: &patch,
8022                        verification: prev_verification.as_ref(),
8023                        prior: prior_section.as_deref(),
8024                        reviewers: reviewers.len(),
8025                        round,
8026                        rounds: max_rounds,
8027                        // A review-only run has no rankings, so nothing
8028                        // competed for this patch and the reviewer is told so.
8029                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
8030                        lens: Lens::for_seat(r),
8031                        language: &language,
8032                        github_language: &self.state.config.graph.github_language,
8033                    }),
8034                    spec,
8035                    seat,
8036                    cwd: wt,
8037                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8038                    allow_write: false,
8039                    sessions,
8040                    artifacts: artifacts.clone(),
8041                    stem: format!("review-{round}-{}", r + 1),
8042                    handover: None,
8043                });
8044            }
8045
8046            drop(coordination);
8047            self.state.event(
8048                "review",
8049                format!(
8050                    "round {round}: {} reviewers on {}",
8051                    jobs.len(),
8052                    short(&head)
8053                ),
8054            );
8055            let mut quota_losses = Vec::new();
8056            let review_retries = self.state.config.graph.retries;
8057            let review_cache = self.state.config.cache_dir();
8058            let ctx = WaveCtx {
8059                carry_seats: true,
8060                pauses: Some((&self.pause, &self.interrupt)),
8061                run: &run_id,
8062                node: "review",
8063                prompts: &prompts,
8064                cache: review_cache.as_deref(),
8065                round: Some(round),
8066            };
8067            let results = ask_json_wave::<Review>(
8068                jobs,
8069                Arc::clone(&self.sem),
8070                review_retries,
8071                &self.roles.reviewer_roster,
8072                &ctx,
8073                &mut quota_losses,
8074                &mut self.state,
8075                &|_: &Review| Ok(()),
8076            )
8077            .await;
8078            if self.state.resource_block.is_some() {
8079                return self.stop_for_resource();
8080            }
8081            // Counted before the move below: how many of *this* round's
8082            // reviewer seats were lost to their own rate limit, as opposed to
8083            // a crash, a timeout, or unparsable output — see `round_is_clean`.
8084            let round_quota_missing = quota_losses.len();
8085            self.state.quota.extend(quota_losses);
8086
8087            let mut records = Vec::new();
8088            let mut all_findings = Vec::new();
8089            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
8090                let agent_id = seat.agent.clone();
8091                self.state.seats.insert(seat.key.clone(), seat);
8092                let mut record = ReviewRecord {
8093                    reviewer: r + 1,
8094                    agent: agent_id,
8095                    summary: String::new(),
8096                    findings: Vec::new(),
8097                    vote: None,
8098                    failed: None,
8099                    duration_ms: 0,
8100                    // Set for both outcomes: `failed: Some(_)` with
8101                    // `attempts > 0` is a seat every retry still lost, not a
8102                    // recovered one — only `failed: None` with `attempts > 0`
8103                    // reads as "answered after a nudge" (see this field's own
8104                    // doc).
8105                    attempts,
8106                };
8107                match res {
8108                    Ok((review, out)) => {
8109                        // Sanitized here, at the point every other piece of
8110                        // agent prose in this file is (candidate summaries,
8111                        // deliberation turns, vote reasons): a reviewer's own
8112                        // words are the one thing about it that could name
8113                        // it, and reconsideration below broadcasts this same
8114                        // summary and these same findings to every other
8115                        // seat on the panel.
8116                        record.summary =
8117                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
8118                        record.vote = Some(review.vote);
8119                        record.duration_ms = out.duration_ms;
8120                        for (n, mut f) in review.findings.into_iter().enumerate() {
8121                            // ids are magi's, never the agent's: the fixer's
8122                            // adoption report is keyed by them.
8123                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
8124                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
8125                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
8126                            // `file` is agent-supplied prose too, never
8127                            // checked against the real tree — the same
8128                            // exposure `title`/`detail` above have, just in
8129                            // a field easy to forget because it looks like a
8130                            // path rather than free text.
8131                            f.file = f
8132                                .file
8133                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
8134                            all_findings.push(f.clone());
8135                            record.findings.push(f);
8136                        }
8137                        self.state.event(
8138                            "review",
8139                            format!(
8140                                "round {round}: reviewer {} voted {} with {} finding(s)",
8141                                r + 1,
8142                                review.vote.label(),
8143                                record.findings.len()
8144                            ),
8145                        );
8146                    }
8147                    Err(e) => {
8148                        record.failed = Some(e.to_string());
8149                        self.state.event(
8150                            "review",
8151                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
8152                        );
8153                    }
8154                }
8155                records.push(record);
8156            }
8157
8158            // Tally the round's votes and, if they split, spend the one
8159            // round of reconsideration the split -> deliberate -> revote
8160            // shape `judge`/`vote` use for the panel, sized down to what a
8161            // read-only review round can afford: one round, and a revote
8162            // rather than an argument, because the panel already wrote its
8163            // reasoning down as findings the first time around.
8164            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
8165            let vote_split =
8166                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
8167            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
8168            if vote_split {
8169                self.state.event(
8170                    "review",
8171                    format!(
8172                        "round {round}: votes split ({}) — one round of reconsideration",
8173                        initial_votes
8174                            .iter()
8175                            .map(|v| v.label())
8176                            .collect::<Vec<_>>()
8177                            .join(", ")
8178                    ),
8179                );
8180                // Seats read every seat's findings and votes, still numbered
8181                // and never named — the same anonymity `review` itself keeps.
8182                let panel: Vec<ReviewSeatReport<'_>> = records
8183                    .iter()
8184                    .filter_map(|r| {
8185                        r.vote.map(|vote| ReviewSeatReport {
8186                            reviewer: r.reviewer,
8187                            vote,
8188                            summary: &r.summary,
8189                            findings: &r.findings,
8190                        })
8191                    })
8192                    .collect();
8193
8194                let mut jobs = Vec::new();
8195                let mut seats_at = Vec::new();
8196                for (r, spec) in reviewers.iter().cloned().enumerate() {
8197                    // A seat with no initial vote has nothing to reconsider
8198                    // from and stays absent, the same as it stayed absent
8199                    // from `panel` above.
8200                    if records[r].vote.is_none() {
8201                        continue;
8202                    }
8203                    let wt = root.join(format!("review-{}", r + 1));
8204                    let seat_key = format!("review-{}", r + 1);
8205                    let spec = self.occupant(&seat_key, spec);
8206                    let seat = self.seat(&seat_key, &spec.id);
8207                    // A seat with no live session has already forgotten the
8208                    // initial review's prompt — restate the patch it is
8209                    // voting on, the same as `deliberate`/`vote` do for a
8210                    // judge in the same position.
8211                    // The panel already carries this seat's own review and
8212                    // vote, so restating the patch makes the prompt whole for
8213                    // a seat handed to another agent.
8214                    let build = |with_patch: bool| {
8215                        prompt::review_reconsider(&ReviewReconsiderCtx {
8216                            instruction: &self.state.instruction,
8217                            reviewer: r + 1,
8218                            lens: Lens::for_seat(r),
8219                            panel: &panel,
8220                            patch: with_patch.then_some(ReviewPatch {
8221                                branch: &winner.branch,
8222                                base_short: &base_short,
8223                                stat: &stat,
8224                                patch: &patch,
8225                            }),
8226                            round,
8227                            rounds: max_rounds,
8228                            language: &language,
8229                        })
8230                    };
8231                    let full = build(true);
8232                    let prompt = if has_context(&spec, &seat, sessions) {
8233                        build(false)
8234                    } else {
8235                        full.clone()
8236                    };
8237                    jobs.push(SeatJob {
8238                        prompt,
8239                        spec,
8240                        seat,
8241                        cwd: wt,
8242                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8243                        allow_write: false,
8244                        sessions,
8245                        artifacts: artifacts.clone(),
8246                        stem: format!("review-{round}-reconsider-{}", r + 1),
8247                        handover: Some(full),
8248                    });
8249                    seats_at.push(r);
8250                }
8251
8252                let mut recon_quota_losses = Vec::new();
8253                let recon_cache = self.state.config.cache_dir();
8254                let recon_ctx = WaveCtx {
8255                    carry_seats: true,
8256                    pauses: Some((&self.pause, &self.interrupt)),
8257                    run: &run_id,
8258                    node: "review",
8259                    prompts: &prompts,
8260                    cache: recon_cache.as_deref(),
8261                    round: Some(round),
8262                };
8263                let recon_results = ask_json_wave::<ReviewRevote>(
8264                    jobs,
8265                    Arc::clone(&self.sem),
8266                    review_retries,
8267                    &self.roles.reviewer_roster,
8268                    &recon_ctx,
8269                    &mut recon_quota_losses,
8270                    &mut self.state,
8271                    &|_: &ReviewRevote| Ok(()),
8272                )
8273                .await;
8274                if self.state.resource_block.is_some() {
8275                    return self.stop_for_resource();
8276                }
8277                self.state.quota.extend(recon_quota_losses);
8278
8279                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
8280                    let agent_id = seat.agent.clone();
8281                    self.state.seats.insert(seat.key.clone(), seat);
8282                    let mut rec = ReviewRevoteRecord {
8283                        reviewer: r + 1,
8284                        agent: agent_id,
8285                        vote: None,
8286                        reason: String::new(),
8287                        failed: None,
8288                    };
8289                    match res {
8290                        Ok((rv, _)) => {
8291                            rec.vote = Some(rv.vote);
8292                            rec.reason =
8293                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
8294                            self.state.event(
8295                                "review",
8296                                format!(
8297                                    "round {round}: reviewer {} revoted {}",
8298                                    r + 1,
8299                                    rv.vote.label()
8300                                ),
8301                            );
8302                        }
8303                        Err(e) => {
8304                            rec.failed = Some(e.to_string());
8305                            self.state.event(
8306                                "review",
8307                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
8308                            );
8309                        }
8310                    }
8311                    reconsideration.push(rec);
8312                }
8313            } else if initial_votes.len() > 1 {
8314                self.state.event(
8315                    "review",
8316                    format!(
8317                        "round {round}: votes agreed ({}) — no reconsideration",
8318                        initial_votes[0].label()
8319                    ),
8320                );
8321            }
8322
8323            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
8324            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8325            // A round that already has a blocking finding and a round left to
8326            // try is going back to the fixer no matter what `verify.e2e`
8327            // says, so running it first only spends the loop's slowest step
8328            // (minutes, for a Rust repo's full test suite) on a head about
8329            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8330            // runs once a round has no blocking findings left (see
8331            // `round_is_clean`, which a deferred — empty — `e2e` can never
8332            // satisfy since `blocking` is nonzero whenever this branch is
8333            // taken), and `stop_reviewing` forces a real run before it will
8334            // ever read a deferred round as green.
8335            let defer_e2e =
8336                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8337            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8338                let reason =
8339                    format!("{blocking} blocking finding(s) already required a fix this round");
8340                self.state.event(
8341                    "verify",
8342                    format!(
8343                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8344                         {}); it will run once a round has none left",
8345                        short(&head)
8346                    ),
8347                );
8348                (Vec::new(), false, true, Some(reason))
8349            } else {
8350                let e2e_commands = self.state.config.verify.e2e.clone();
8351                let cache_dir = self.state.config.cache_dir();
8352                let context = format!("round {round}");
8353                let wait = self.repository_wait();
8354                let (e2e, verify_retried) = with_cache_lease(
8355                    &mut self.state,
8356                    cache_dir.as_deref(),
8357                    "e2e",
8358                    "e2e",
8359                    &winner.worktree,
8360                    &head,
8361                    verify_timeout,
8362                    &context,
8363                    &wait,
8364                    |state, budget| {
8365                        let shell = shell.clone();
8366                        let e2e_commands = e2e_commands.clone();
8367                        let worktree = winner.worktree.clone();
8368                        let context = context.clone();
8369                        let winner = winner.clone();
8370                        async move {
8371                            if !e2e_commands.is_empty() {
8372                                // The suite certifies one SHA. Format before it
8373                                // runs, or the commit `pre_gate` makes at the
8374                                // gate owes the whole suite again.
8375                                Self::run_pre_gate(state, &winner).await;
8376                            }
8377                            run_e2e_with_retry(
8378                                state,
8379                                &shell,
8380                                &e2e_commands,
8381                                &worktree,
8382                                budget,
8383                                &context,
8384                                Some(round),
8385                            )
8386                            .await
8387                        }
8388                    },
8389                )
8390                .await?;
8391                (e2e, verify_retried, false, None)
8392            };
8393
8394            let expected = records.len();
8395            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8396            let incomplete = answered < expected;
8397            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8398            let policy = self.state.config.graph.incomplete_review;
8399            let clean = round_is_clean(
8400                blocking,
8401                e2e_ok,
8402                answered,
8403                expected,
8404                round_quota_missing,
8405                policy,
8406            );
8407
8408            let mut round_record = ReviewRound {
8409                round,
8410                head: head.clone(),
8411                verified_head: None,
8412                verified_at: None,
8413                reviews: records,
8414                e2e,
8415                verify_retried,
8416                e2e_deferred,
8417                e2e_defer_reason,
8418                fix: None,
8419                blocking,
8420                answered,
8421                expected,
8422                clean,
8423                progressed: false,
8424                vote_split,
8425                reconsideration,
8426                verdict: None,
8427            };
8428            // The final vote per seat is its revote where reconsideration
8429            // ran and answered, its initial vote otherwise — the same
8430            // fallback `tally` uses for a judge whose private vote failed.
8431            round_record.verdict = ReviewVote::worst(
8432                round_record
8433                    .final_votes()
8434                    .into_iter()
8435                    .map(|(_, _, vote)| vote),
8436            );
8437            // Which commit and when magi actually attempted to check —
8438            // known the moment a command was dispatched against `head`,
8439            // whether or not it finished: a resource-blocked attempt still
8440            // targeted a specific commit at a specific time, and leaving
8441            // that unrecorded is exactly what made `verification_summary`
8442            // report a fresh attempt as "commit unknown ... recorded before
8443            // this was tracked", indistinguishable from a genuinely old,
8444            // untracked record. Only a deferred or unconfigured round never
8445            // ran at all and has nothing to record — see
8446            // `ReviewRound::verified_head`'s own doc.
8447            if !matches!(
8448                round_record.e2e_status(),
8449                E2eStatus::Deferred | E2eStatus::NotConfigured
8450            ) {
8451                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8452                // mechanical fixes before the commands ran.
8453                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8454                round_record.verified_at = Some(Timestamp::now());
8455            }
8456
8457            if incomplete {
8458                let missing: Vec<String> = round_record
8459                    .reviews
8460                    .iter()
8461                    .filter(|r| r.failed.is_some())
8462                    .map(|r| format!("review-{}", r.reviewer))
8463                    .collect();
8464                self.state.event(
8465                    "review",
8466                    format!(
8467                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8468                        missing.join(", ")
8469                    ),
8470                );
8471            }
8472
8473            if clean {
8474                self.state.event(
8475                    "review",
8476                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8477                        format!(
8478                            "round {round}: clean (warn policy, incomplete panel) — no \
8479                             blocking findings from the seats that answered, verification green"
8480                        )
8481                    } else if incomplete {
8482                        format!(
8483                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8484                             quorum) — no blocking findings from the seats that answered, \
8485                             verification green",
8486                            expected - answered
8487                        )
8488                    } else {
8489                        format!("round {round}: clean — no blocking findings, verification green")
8490                    },
8491                );
8492                self.state.reviews.push(round_record);
8493                self.state.status = RunStatus::Gating;
8494                self.state.save()?;
8495                return Ok(());
8496            }
8497
8498            // Nothing was raised and verification passed, but not every seat
8499            // answered and `round_is_clean` still refused to call it clean —
8500            // either a seat is missing for a reason other than its own quota
8501            // (a crash, a timeout, unparsable output — worth another try), or
8502            // every seat that could have answered lost its quota and nobody
8503            // is left to decide on: re-review rather than send the fixer
8504            // after a round with nothing to fix.
8505            if incomplete && blocking == 0 && e2e_ok {
8506                self.state.reviews.push(round_record);
8507                self.state.save()?;
8508                if round == max_rounds {
8509                    self.state.status = RunStatus::Blocked;
8510                    self.state.event(
8511                        "review",
8512                        format!(
8513                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8514                             refusing to call it clean",
8515                            expected - answered
8516                        ),
8517                    );
8518                    return Ok(());
8519                }
8520                continue;
8521            }
8522
8523            // Nothing for the fixer to act on (`blocking == 0`) and the only
8524            // reason this round is not clean is that magi itself never got
8525            // a command to run — the shared build cache, not the patch (see
8526            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8527            // the fixer would invite a change to appease contention that has
8528            // nothing to do with the diff, and would leave this attempt
8529            // sitting in the next round's prompt as if it were about an
8530            // earlier, superseded commit rather than what it actually is:
8531            // the same head, still waiting to be checked. Wait for it the
8532            // same way the final round's own contention is already handled,
8533            // whatever round this happens to be.
8534            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8535                self.state.reviews.push(round_record);
8536                return self
8537                    .stop_unresolved_review(
8538                        "the round's own verification could not run",
8539                        &shell,
8540                        &winner.worktree,
8541                    )
8542                    .await;
8543            }
8544
8545            if round == max_rounds {
8546                self.state.reviews.push(round_record);
8547                return self
8548                    .stop_reviewing(
8549                        &format!(
8550                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8551                        ),
8552                        &shell,
8553                        &winner.worktree,
8554                    )
8555                    .await;
8556            }
8557
8558            if !self.fix_review_round(&winner, round_record).await? {
8559                return Ok(());
8560            }
8561        }
8562        Ok(())
8563    }
8564
8565    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8566    /// False means admission or continuation policy stopped the review loop.
8567    async fn fix_review_round(
8568        &mut self,
8569        winner: &Candidate,
8570        mut round_record: ReviewRound,
8571    ) -> Result<bool> {
8572        let round = round_record.round;
8573        let shell = self.state.config.shell();
8574        let step = self.run_fix_round(winner, &mut round_record).await?;
8575        if matches!(step, FixStep::Resource) {
8576            self.stop_for_resource()?;
8577            return Ok(false);
8578        }
8579        if self.state.reviews.len() < round {
8580            self.state.reviews.push(round_record);
8581        } else {
8582            self.state.reviews[round - 1] = round_record;
8583        }
8584        self.state.save()?;
8585
8586        // The fixer's own report never came back this round, even after
8587        // `continue_fix_report`'s own budget was spent on it — not an
8588        // ordinary "no report" (dropped stream, quota, plain failure),
8589        // which already reads that way and is left to the existing round
8590        // budget. Stopping here, rather than opening another round, is
8591        // what keeps a next reviewer/fixer wave from ever being
8592        // dispatched onto `winner.worktree` while whatever the seat's
8593        // last call may still have running there is unaccounted for: no
8594        // process liveness check exists (and none is being added — see
8595        // AGENTS.md/this task's own scope), so the only way to honour
8596        // "nothing starts before a valid report returns" is to not start
8597        // anything further on this worktree from this run at all.
8598        if matches!(step, FixStep::Recorded { report_lost: true }) {
8599            self.stop_reviewing(
8600                "the fixer's adoption report never came back, even after resuming its \
8601                         own seat; refusing to start another round against the same worktree \
8602                         while that is unresolved",
8603                &shell,
8604                &winner.worktree,
8605            )
8606            .await?;
8607            return Ok(false);
8608        }
8609
8610        let streak = self
8611            .state
8612            .reviews
8613            .iter()
8614            .rev()
8615            .take_while(|r| !r.progressed)
8616            .count();
8617        if streak >= STAGNANT_LIMIT {
8618            self.stop_reviewing(
8619                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8620                &shell,
8621                &winner.worktree,
8622            )
8623            .await?;
8624            return Ok(false);
8625        }
8626        Ok(true)
8627    }
8628
8629    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8630    async fn run_fix_round(
8631        &mut self,
8632        winner: &Candidate,
8633        round_record: &mut ReviewRound,
8634    ) -> Result<FixStep> {
8635        let round = round_record.round;
8636        let max_rounds = self.state.config.graph.review_rounds;
8637        let run_id = self.state.id.clone();
8638        let prompts = self.state.config.prompts.clone();
8639        let language = self.state.config.graph.language.clone();
8640        let sessions = self.state.config.graph.sessions;
8641        let artifacts = self.merge_repair_artifacts();
8642        let base = self.landing_base();
8643        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8644        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8645        let this_round_verification = round_record.verification_summary(&head);
8646        let all_findings: Vec<_> = round_record
8647            .reviews
8648            .iter()
8649            .flat_map(|r| r.findings.iter().cloned())
8650            .collect();
8651        // Fix. The winner's own implementer seat continues its conversation:
8652        // the competition is over, so context is pure benefit now.
8653        let blocking_findings: Vec<_> = all_findings
8654            .iter()
8655            .filter(|f| f.severity.blocks())
8656            .cloned()
8657            .collect();
8658        let fix_prompt = prompt::fix_in(
8659            &self.state.instruction,
8660            &blocking_findings,
8661            this_round_verification.as_ref(),
8662            round,
8663            max_rounds,
8664            &language,
8665            &self.state.config.graph.github_language,
8666        );
8667        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8668        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8669        let (job, seat, out) = self
8670            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8671                prompt: fix_prompt.clone(),
8672                spec,
8673                seat,
8674                cwd: winner.worktree.clone(),
8675                timeout,
8676                allow_write: true,
8677                sessions,
8678                artifacts: artifacts.clone(),
8679                stem: format!("fix-{round}"),
8680                handover: None,
8681            })
8682            .await;
8683        // Not asked: the round is not recorded (so a resume repeats it),
8684        // no fixer was handed over to, and the seat is left as it was.
8685        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8686            return Ok(FixStep::Resource);
8687        }
8688        let agent_id = seat.agent.clone();
8689
8690        let mut fix = FixRecord {
8691            agent: agent_id,
8692            addressed: Vec::new(),
8693            rejected: Vec::new(),
8694            notes: String::new(),
8695            committed: false,
8696            failed: None,
8697            duration_ms: 0,
8698            continuation: None,
8699        };
8700        let mut continuation = ContinuationRecord::not_needed();
8701        let mut final_seat = seat.clone();
8702        match out {
8703            AgentOutcome::Ok(o) => {
8704                fix.duration_ms = o.duration_ms;
8705                let parsed = verdict::extract_json::<FixReport>(&o.text);
8706                // A parsed report standing next to a command this same
8707                // reply's own CLI never confirmed the exit status of is
8708                // not a resolved answer — the identical `CommandEvidence`
8709                // `state.jobs` renders, read here instead of only on
8710                // display, per the completion judgment and the shown
8711                // record needing to agree.
8712                let incomplete_reason = match &parsed {
8713                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8714                        "the reply parsed, but it reported a command whose own CLI never \
8715                             confirmed an exit status"
8716                            .to_owned(),
8717                    ),
8718                    Ok(_) => None,
8719                    Err(e) => Some(e.to_string()),
8720                };
8721                match incomplete_reason {
8722                    None => {
8723                        let report = parsed.expect("checked Ok above");
8724                        fix.addressed = report.addressed;
8725                        fix.rejected = report.rejected;
8726                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8727                    }
8728                    Some(reason) => {
8729                        let (resumed_seat, resolved, failure, cont) = self
8730                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8731                            .await;
8732                        fix.duration_ms += cont.cumulative_wait_ms;
8733                        continuation = cont;
8734                        final_seat = resumed_seat;
8735                        match resolved {
8736                            Some(report) => {
8737                                fix.addressed = report.addressed;
8738                                fix.rejected = report.rejected;
8739                                fix.notes =
8740                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8741                            }
8742                            None => fix.failed = failure,
8743                        }
8744                    }
8745                }
8746            }
8747            // The CLI's raw error JSON is not a fix report to parse.
8748            AgentOutcome::Dropped(o) => {
8749                fix.duration_ms = o.duration_ms;
8750                let why = o
8751                    .dropped
8752                    .as_ref()
8753                    .map(|d| d.why.as_str())
8754                    .unwrap_or("the CLI ended the stream without delivering its answer");
8755                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8756            }
8757            AgentOutcome::Quota(o) => {
8758                self.state.quota.push(QuotaLoss::from_report(
8759                    final_seat.key.clone(),
8760                    "fix",
8761                    o.quota.as_ref(),
8762                ));
8763                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8764            }
8765            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8766        }
8767        if self.state.resource_block.is_some() {
8768            self.state.seats.insert(final_seat.key.clone(), final_seat);
8769            return Ok(FixStep::Resource);
8770        }
8771        fix.continuation = Some(continuation);
8772        self.state.seats.insert(final_seat.key.clone(), final_seat);
8773        let coordination = self.coordinate(&winner.worktree).await?;
8774        if let Ok(r) = git::rescue_commit(
8775            &winner.worktree,
8776            &format!("magi: review round {round} fixes (uncommitted work)"),
8777        )
8778        .await
8779        {
8780            self.state.note_withheld("fix", &r.withheld);
8781        }
8782        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8783        fix.committed = after != before;
8784        // Judged by what `git` says moved against base, never by the
8785        // fixer's own `addressed`/`rejected` count — see
8786        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8787        // `patch` snapshot above: swallowing this error would default
8788        // `diff_after` to empty, which almost always differs from a
8789        // non-empty `patch` and reads as "progressed" — exactly backwards
8790        // for a `git` failure the stagnation check cannot see through.
8791        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8792        drop(coordination);
8793        let progressed = diff_after != patch;
8794        let commit_note = if fix.committed {
8795            "committed"
8796        } else {
8797            "NO new commit"
8798        };
8799        let tree_note = if progressed {
8800            "changed vs base"
8801        } else {
8802            "unchanged vs base"
8803        };
8804        self.state.event(
8805            "fix",
8806            match &fix.failed {
8807                // Distinct on purpose from "0 addressed, 0 rejected": the
8808                // fixer's own diff still landed (blocking counts do keep
8809                // falling round over round), only its adoption report did
8810                // not come back, so this must never read like every
8811                // finding was reviewed and declined.
8812                Some(reason) => {
8813                    format!(
8814                        "round {round}: fixer's adoption report was lost ({reason}); \
8815                             {commit_note}, tree {tree_note}"
8816                    )
8817                }
8818                None => format!(
8819                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8820                         {tree_note}{}",
8821                    fix.addressed.len(),
8822                    fix.rejected.len(),
8823                    if continuation.outcome == ContinuationOutcome::Resumed {
8824                        format!(
8825                            " (adoption report recovered after {} continuation(s))",
8826                            continuation.attempts
8827                        )
8828                    } else {
8829                        String::new()
8830                    },
8831                ),
8832            },
8833        );
8834        round_record.fix = Some(fix);
8835        round_record.progressed = progressed;
8836        Ok(FixStep::Recorded {
8837            report_lost: matches!(
8838                continuation.outcome,
8839                ContinuationOutcome::Exhausted
8840                    | ContinuationOutcome::QuotaLost
8841                    | ContinuationOutcome::NoSession
8842            ),
8843        })
8844    }
8845
8846    /// Decide, from the last recorded round's own verification, whether
8847    /// stopping the review loop is a hand-off or a genuine block.
8848    ///
8849    /// Called once the loop has given up trying — the round budget is spent,
8850    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8851    /// findings still open, never while a round is still clean or the
8852    /// incomplete-panel case handled inline above. Gate and e2e are facts
8853    /// about the tree; a lingering review finding is an opinion, and this
8854    /// workload's own `magi stats` puts reviewer precision low enough
8855    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8856    /// must not by itself stand between a green, verified change and the
8857    /// human who decides what to do with it. A red e2e is not an opinion, so
8858    /// that case still blocks, with the failing command and a tail of its
8859    /// output recorded here rather than left in `run.json` for someone to go
8860    /// find.
8861    ///
8862    /// A round that deferred its own e2e (see [`Config::graph`]'s
8863    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8864    /// only because nothing ran, and treating an empty list as a passing one
8865    /// here is exactly the "deferred painted green" bug this function exists
8866    /// to not have. When the last round's own verification never resolved —
8867    /// deferred on purpose, or a real attempt the shared build cache blocked
8868    /// — this makes (or retries) the real run, on the actual worktree this
8869    /// loop is about to stop touching, before deciding anything. A
8870    /// resource-blocked attempt is likewise never read as either green or
8871    /// red: it is evidence about the machine, not the patch (see
8872    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8873    /// blocked cache leaves this call without deciding rather than guessing
8874    /// — the caller retries on a later reentry.
8875    /// Record, once, that the review loop handed off over a blocking finding
8876    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8877    /// `land` asks the owner even with `land_approval` off. Called from every
8878    /// path that concludes `Gating`; a reentry keeps the first record.
8879    fn record_contested_handoff(&mut self) {
8880        if self.state.contested_handoff.is_some() {
8881            return;
8882        }
8883        let Some(contested) = self
8884            .state
8885            .reviews
8886            .last()
8887            .and_then(ReviewRound::contested_handoff)
8888        else {
8889            return;
8890        };
8891        self.state.event(
8892            "review",
8893            format!(
8894                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8895                 wait for the owner's approval",
8896                contested.findings.len(),
8897                contested.rejecters.len()
8898            ),
8899        );
8900        self.state.contested_handoff = Some(contested);
8901    }
8902
8903    async fn stop_unresolved_review(
8904        &mut self,
8905        why: &str,
8906        shell: &[String],
8907        worktree: &Path,
8908    ) -> Result<()> {
8909        self.stop_reviewing_inner(why, shell, worktree, true).await
8910    }
8911
8912    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8913        self.stop_reviewing_inner(why, shell, worktree, false).await
8914    }
8915
8916    async fn stop_reviewing_inner(
8917        &mut self,
8918        why: &str,
8919        shell: &[String],
8920        worktree: &Path,
8921        repairable: bool,
8922    ) -> Result<()> {
8923        let round_idx = self.state.reviews.len() - 1;
8924        // A deferred round and a resource-blocked one are the same shape
8925        // here: neither has a real result yet, and both get one more
8926        // attempt. Read off `e2e_status` — the single source for this —
8927        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8928        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8929        // still retries instead of being read as a settled result the
8930        // instant it stops being empty.
8931        let needs_catchup_run = matches!(
8932            self.state.reviews[round_idx].e2e_status(),
8933            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8934        );
8935        if needs_catchup_run {
8936            let round = self.state.reviews[round_idx].round;
8937            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8938            let commands = self.state.config.verify.e2e.clone();
8939            let before_head = git::rev_parse(worktree, "HEAD").await?;
8940            let winner = self.state.winner().cloned();
8941            let cache_dir = self.state.config.cache_dir();
8942            let context = format!(
8943                "round {round}: verification unresolved, catching up before the final decision"
8944            );
8945            let wait = self.repository_wait();
8946            let (outcomes, verify_retried) = with_cache_lease(
8947                &mut self.state,
8948                cache_dir.as_deref(),
8949                "e2e",
8950                "e2e",
8951                worktree,
8952                &before_head,
8953                timeout,
8954                &context,
8955                &wait,
8956                |state, budget| {
8957                    let shell = shell.to_vec();
8958                    let commands = commands.clone();
8959                    let context = context.clone();
8960                    async move {
8961                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8962                            // Same reason as in the round itself: format before
8963                            // the suite, not after it.
8964                            Self::run_pre_gate(state, &winner).await;
8965                        }
8966                        run_e2e_with_retry(
8967                            state,
8968                            &shell,
8969                            &commands,
8970                            worktree,
8971                            budget,
8972                            &context,
8973                            Some(round),
8974                        )
8975                        .await
8976                    }
8977                },
8978            )
8979            .await?;
8980            // After `pre_gate`: the commit the commands actually ran against.
8981            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8982            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8983                self.state.record_base_progress(&attempted_head);
8984            }
8985            let last = &mut self.state.reviews[round_idx];
8986            last.e2e = outcomes;
8987            last.verify_retried = verify_retried;
8988            // Always the commit and time this attempt actually targeted,
8989            // whether or not it happens to equal the reviewed `head` and
8990            // whether or not a command finished — see
8991            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8992            // attempt is recorded too, so a later reader sees "attempted
8993            // again at T2" rather than silence.
8994            last.verified_head = Some(attempted_head);
8995            last.verified_at = Some(Timestamp::now());
8996            if verify_inconclusive(&last.e2e) {
8997                // Still not a real result: `e2e_deferred` is left exactly
8998                // as it was, so `needs_catchup_run` above reads
8999                // `ResourceBlocked` (via `e2e_status`, which checks
9000                // `resource_blocked` before `e2e_deferred`) and retries
9001                // again on the next reentry, rather than recording
9002                // contention as a red e2e and blocking the run on it.
9003                self.state.save()?;
9004                return Ok(());
9005            }
9006            last.e2e_deferred = false;
9007            // A complete panel may have been saved as unclean solely because
9008            // verification could not run. Refresh that verdict with the new
9009            // outcomes before a granted repair consumes the round's result.
9010            // Incomplete panels retain their original policy/quota decision.
9011            if last.answered == last.expected {
9012                last.clean = round_is_clean(
9013                    last.blocking,
9014                    last.e2e.iter().all(CommandOutcome::ok),
9015                    last.answered,
9016                    last.expected,
9017                    0,
9018                    self.state.config.graph.incomplete_review,
9019                );
9020            }
9021        }
9022        let last = &self.state.reviews[round_idx];
9023        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
9024
9025        match last.e2e_status() {
9026            E2eStatus::Failed => {
9027                let red: Vec<String> = last
9028                    .e2e
9029                    .iter()
9030                    .filter(|o| !o.ok())
9031                    .map(|o| {
9032                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
9033                            .map(|c| format!(" ({c})"))
9034                            .unwrap_or_default();
9035                        format!(
9036                            "`{}` -> {:?}{comparison}\n{}",
9037                            o.command,
9038                            o.code,
9039                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9040                        )
9041                    })
9042                    .collect();
9043                let can_repair = last.blocking == 0 && last.fix.is_none();
9044                self.state.reviews[round_idx].clean = false;
9045                self.state
9046                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
9047                self.state.status = RunStatus::Blocked;
9048                if repairable
9049                    && can_repair
9050                    && self.state.reviews.len() < self.state.config.graph.review_rounds
9051                {
9052                    self.state.status = RunStatus::Reviewing;
9053                }
9054            }
9055            // `needs_catchup_run` above already retried once this call; if
9056            // it is still blocked, this is magi's own admission it could
9057            // not get a command to run, never a verdict on the patch — the
9058            // run is left exactly where a later reentry can retry again.
9059            E2eStatus::ResourceBlocked => {
9060                self.state.event(
9061                    "review",
9062                    format!(
9063                        "{why}; e2e could not run (resource unavailable); not \
9064                         deciding yet"
9065                    ),
9066                );
9067            }
9068            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
9069                self.state.event(
9070                    "review",
9071                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
9072                );
9073                self.record_contested_handoff();
9074                self.state.status = RunStatus::Gating;
9075            }
9076        }
9077        self.state.save()?;
9078        Ok(())
9079    }
9080
9081    // ----------------------------------------------------------------- gate
9082
9083    async fn gate(&mut self) -> Result<()> {
9084        if self.hold_base_sync().await? {
9085            return Ok(());
9086        }
9087        // Judged by the review record itself, not by `status`: a solo
9088        // candidate's `judge`/`deliberate` skip rewrites `status` on every
9089        // reentry (see `judge`), and trusting it here is exactly how a run
9090        // that exhausted its review budget got gated and merged a second
9091        // time around. `review_conclusion` recomputes the review loop's own
9092        // verdict from the round records themselves — `Gating` for a clean
9093        // round or a hand-off (see `stop_reviewing`), anything else means the
9094        // loop is still going or genuinely blocked.
9095        // A base the winner could not be replayed onto is a decision, not a
9096        // round: there is no landing tree to gate. Read as its own record for
9097        // the same reason the review verdict is.
9098        if self.state.status == RunStatus::Failed
9099            || self
9100                .state
9101                .base_sync
9102                .as_ref()
9103                .is_some_and(|s| s.conflict.is_some())
9104            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9105                != Some(RunStatus::Gating)
9106        {
9107            return Ok(());
9108        }
9109        let Some(winner) = self.state.winner().cloned() else {
9110            return Ok(());
9111        };
9112        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9113        self.state.reconcile_verification_head(&head);
9114        self.state.save()?;
9115        let wait = self.repository_wait();
9116        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9117            return Ok(());
9118        }
9119        if self.state.gate_ran {
9120            // `review_loop` derives its conclusion from the clean review
9121            // record on every reentry and therefore puts a completed run back
9122            // in `Gating`. A recorded gate is a stronger, terminal fact:
9123            // retain its original command output (or lack of any, for a repo
9124            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
9125            // doc) and restore `Blocked` on a real failure rather than
9126            // pretending the command is still running or running it a second
9127            // time. `gate_ran == false` remains the only shape — unattempted,
9128            // or a resource-blocked retry — that may still need to execute a
9129            // command.
9130            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
9131                self.state.status = RunStatus::Blocked;
9132                self.state.save()?;
9133            }
9134            return Ok(());
9135        }
9136        self.state.status = RunStatus::Gating;
9137        let mut outcomes = self.run_gate(&winner).await?;
9138        let mut attempted_head = self.state.gate_head.clone();
9139        loop {
9140            // A resource-blocked outcome means the gate command never actually
9141            // ran - the shared build cache could not be acquired or confirmed
9142            // fresh in time - which is evidence about the machine, not about
9143            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
9144            // Recording it as a red gate would mark a run `Blocked` on nothing
9145            // but contention magi has already logged; leaving `self.state.gate`
9146            // empty and `self.state.gate_ran` false instead keeps the shape
9147            // this function already treats as "still needs to run" (see the
9148            // early-return above), so the next call retries the command
9149            // rather than concluding anything.
9150            if verify_inconclusive(&outcomes) {
9151                self.state.save()?;
9152                return Ok(());
9153            }
9154            if outcomes.iter().all(CommandOutcome::ok) {
9155                break;
9156            }
9157            let fixes_before = self.state.gate_fixes.len();
9158            match self.gate_fix_round(&winner, &outcomes).await? {
9159                GateFix::Retry => {
9160                    outcomes = self.run_gate(&winner).await?;
9161                    attempted_head = self.state.gate_head.clone();
9162                }
9163                GateFix::Stop => {
9164                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
9165                    if self.state.gate_fixes.len() > fixes_before
9166                        && attempted_head.as_deref() != Some(current.as_str())
9167                        && verify_current_head(&mut self.state, &winner, &wait).await?
9168                    {
9169                        // A new SHA owes a gate even when a spent fixer changed only
9170                        // commit metadata. This does not grant another repair round.
9171                        outcomes = self.run_gate(&winner).await?;
9172                        attempted_head = self.state.gate_head.clone();
9173                    } else {
9174                        break;
9175                    }
9176                }
9177                GateFix::Defer => {
9178                    self.state.save()?;
9179                    return Ok(());
9180                }
9181            }
9182        }
9183        let passed = outcomes.iter().all(CommandOutcome::ok);
9184        self.state.gate = outcomes;
9185        self.state.gate_ran = true;
9186        self.state.gate_head = attempted_head;
9187        if !self.state.gate.is_empty()
9188            && !verify_inconclusive(&self.state.gate)
9189            && let Some(head) = self.state.gate_head.clone()
9190        {
9191            self.state.record_base_progress(&head);
9192        }
9193        self.state.save()?;
9194        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9195            return Ok(());
9196        }
9197        if !passed {
9198            self.state.status = RunStatus::Blocked;
9199            let spent = self.state.gate_fixes.len();
9200            self.state.event(
9201                "gate",
9202                if spent == 0 {
9203                    "gate failed; not merging".to_owned()
9204                } else {
9205                    format!("gate failed after {spent} gate-fix round(s); not merging")
9206                },
9207            );
9208        }
9209        self.state.save()?;
9210        Ok(())
9211    }
9212
9213    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
9214    /// changed into one commit. Runs before `verify.e2e` in the review loop
9215    /// and again before the gate commands, always on the winner and never on
9216    /// a candidate awaiting judging.
9217    ///
9218    /// Before e2e as well as before the gate because command evidence belongs
9219    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
9220    /// commit e2e never saw, and the suite ran again for a formatter's diff -
9221    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
9222    /// own call then finds nothing left to change. The commands must be
9223    /// idempotent; one that is not makes a commit per call.
9224    ///
9225    /// Never fails the run: a non-zero exit or timeout is a warning and a
9226    /// recorded outcome, and the gate remains the single arbiter. Nothing
9227    /// configured means nothing happens - no event, no commit. `commit_all`
9228    /// commits any leftover change under the neutral identity and returns
9229    /// `false` when the tree is clean, so no empty commit is ever made.
9230    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
9231        let commands = state.config.verify.pre_gate.clone();
9232        if commands.is_empty() {
9233            return;
9234        }
9235        let shell = state.config.shell();
9236        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
9237        let (outcomes, _) = run_commands(
9238            state,
9239            "pre_gate",
9240            "pre_gate",
9241            0,
9242            &shell,
9243            &commands,
9244            &winner.worktree,
9245            timeout,
9246        )
9247        .await;
9248        for o in &outcomes {
9249            if !o.ok() {
9250                tracing::warn!(
9251                    "pre_gate `{}` failed ({:?}); the gate decides",
9252                    o.command,
9253                    o.code
9254                );
9255            }
9256            state.event(
9257                "pre_gate",
9258                format!(
9259                    "`{}` -> {}",
9260                    o.command,
9261                    if o.ok() {
9262                        "pass".to_owned()
9263                    } else {
9264                        format!(
9265                            "FAIL ({:?})\n{}",
9266                            o.code,
9267                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9268                        )
9269                    }
9270                ),
9271            );
9272        }
9273        state.pre_gate = outcomes;
9274        match git::commit_all(&winner.worktree, PRE_GATE_COMMIT_MESSAGE).await {
9275            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
9276                Ok(head) => {
9277                    state.event(PRE_GATE_EVENT_NODE, pre_gate_commit_event(&head));
9278                    state.pre_gate_commit = Some(head);
9279                }
9280                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
9281            },
9282            Ok(false) => {}
9283            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
9284        }
9285        if let Err(e) = state.save() {
9286            tracing::warn!("could not persist the pre_gate record: {e:#}");
9287        }
9288    }
9289
9290    /// Run `verify.gate` once against the winner's current tree, logging one
9291    /// event per command. Empty when nothing is configured.
9292    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
9293        let wait = self.repository_wait();
9294        run_landing_gate(&mut self.state, winner, &wait).await
9295    }
9296
9297    /// One bounded fix round for a failing gate.
9298    ///
9299    /// The fixer is told the failure came from the gate itself, not from a
9300    /// reviewer, and is shown the failed commands, their exit codes and a tail
9301    /// of their output - whatever `[verify].gate` holds, nothing here knows
9302    /// what those commands run. Only a normal non-zero exit that printed
9303    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
9304    /// command or a full disk says nothing about the code, and a fixer sent
9305    /// after it can only appease the machine. The round is judged by what git
9306    /// says moved, never by the fixer's own report, and `verify.e2e` runs
9307    /// again before the gate does, so a fix cannot trade a green gate for a
9308    /// red e2e unnoticed.
9309    async fn gate_fix_round(
9310        &mut self,
9311        winner: &Candidate,
9312        outcomes: &[CommandOutcome],
9313    ) -> Result<GateFix> {
9314        let cap = if self.state.repair_grants.last().is_some_and(|g| {
9315            g.phase == crate::repair_budget::Phase::Fixing
9316                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
9317        }) {
9318            self.state.gate_fixes.len().saturating_add(1)
9319        } else {
9320            self.state.config.graph.gate_fix_rounds
9321        };
9322        let spent = self.state.gate_fixes.len();
9323        if spent >= cap {
9324            if cap > 0 {
9325                self.state.event(
9326                    "gate",
9327                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
9328                );
9329            }
9330            return Ok(GateFix::Stop);
9331        }
9332        if !gate_fixable(outcomes) {
9333            self.state.event(
9334                "gate",
9335                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9336                 command or similar); not spending a fix round on it",
9337            );
9338            return Ok(GateFix::Stop);
9339        }
9340        let min_free = self.state.config.disk.min_free_bytes;
9341        if min_free > 0 {
9342            match crate::disk::free_bytes(&winner.worktree) {
9343                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9344                Ok(free) => {
9345                    self.state.event(
9346                        "gate",
9347                        format!(
9348                            "only {free} bytes free ({min_free} required by `[disk] \
9349                             min_free_bytes`); not spending a fix round on a failure the disk \
9350                             may explain"
9351                        ),
9352                    );
9353                    return Ok(GateFix::Stop);
9354                }
9355                Err(e) => {
9356                    self.state.event(
9357                        "gate",
9358                        format!("free disk space could not be measured ({e:#}); no fix round"),
9359                    );
9360                    return Ok(GateFix::Stop);
9361                }
9362            }
9363        }
9364
9365        let attempt = spent + 1;
9366        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9367        let base = self.landing_base();
9368        let fix_prompt = prompt::gate_fix_in(
9369            &self.state.instruction,
9370            &failed,
9371            attempt,
9372            cap,
9373            &self.state.config.graph.language,
9374            &self.state.config.graph.github_language,
9375        );
9376        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9377        let sessions = self.state.config.graph.sessions;
9378        let artifacts = self.merge_repair_artifacts();
9379        self.state.event(
9380            "gate",
9381            format!("gate failed; gate-fix round {attempt} of {cap}"),
9382        );
9383        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9384        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9385        // Persist before invoking the fixer: it may commit and then be
9386        // interrupted before its result (or the following e2e) is saved.
9387        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9388            before.clone(),
9389            false,
9390            Vec::new(),
9391        ));
9392        self.state.save()?;
9393        let (_, seat, out) = self
9394            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9395                prompt: fix_prompt.clone(),
9396                spec,
9397                seat,
9398                cwd: winner.worktree.clone(),
9399                timeout,
9400                allow_write: true,
9401                sessions,
9402                artifacts: artifacts.clone(),
9403                stem: format!("gate-fix-{attempt}"),
9404                handover: None,
9405            })
9406            .await;
9407        // The fixer was never asked: no round is spent (nothing is recorded)
9408        // and a later reentry asks the same agent again.
9409        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9410            return Ok(GateFix::Defer);
9411        }
9412        let mut record = GateFixRecord {
9413            agent: seat.agent.clone(),
9414            failed,
9415            notes: String::new(),
9416            committed: false,
9417            error: None,
9418        };
9419        match out {
9420            AgentOutcome::Ok(o) => {
9421                // A missing report is not a failed fix: the round is judged
9422                // by the tree below, and the report only carries prose.
9423                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9424                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9425                }
9426            }
9427            AgentOutcome::Dropped(_) => {
9428                record.error = Some("the CLI dropped the stream".to_owned());
9429            }
9430            AgentOutcome::Quota(o) => {
9431                self.state.quota.push(QuotaLoss::from_report(
9432                    seat.key.clone(),
9433                    "gate-fix",
9434                    o.quota.as_ref(),
9435                ));
9436                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9437            }
9438            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9439        }
9440        self.state.seats.insert(seat.key.clone(), seat);
9441        let coordination = self.coordinate(&winner.worktree).await?;
9442        if let Ok(r) = git::rescue_commit(
9443            &winner.worktree,
9444            &format!("magi: gate fix {attempt} (uncommitted work)"),
9445        )
9446        .await
9447        {
9448            self.state.note_withheld("gate-fix", &r.withheld);
9449        }
9450        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9451        record.committed = after != before;
9452        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9453        let note = record.error.clone();
9454        self.state.gate_fixes.push(record);
9455        self.state.save()?;
9456        if !changed {
9457            self.state.event(
9458                "gate",
9459                match note {
9460                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9461                    None => format!("gate-fix round {attempt}: the tree did not change"),
9462                },
9463            );
9464            return Ok(GateFix::Stop);
9465        }
9466        self.state.event(
9467            "gate",
9468            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9469        );
9470
9471        drop(coordination);
9472        let wait = self.repository_wait();
9473        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9474    }
9475
9476    // ---------------------------------------------------------------- merge
9477
9478    /// One read-only rewrite by the summary's author; a text the gate still
9479    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9480    /// applies on their word or on silence. `None` means the run is parked on
9481    /// that question and nothing may be pushed or opened yet.
9482    async fn guarded_pr_message(
9483        &mut self,
9484        winner: &Candidate,
9485        facts: Option<&BranchFacts>,
9486        posting: bool,
9487    ) -> Result<Option<PrMessage>> {
9488        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9489        let head = match final_head.as_deref() {
9490            Some(h) => crate::pr_outcome::FinalHead::At(h),
9491            None => crate::pr_outcome::FinalHead::Unknown,
9492        };
9493        // Only a pull request that is about to be posted pays for a summary.
9494        let summarized = if posting {
9495            Some(self.summarize_change(winner, final_head.as_deref()).await)
9496        } else {
9497            None
9498        };
9499        // A busy shared resource is not a permanent cause: publishing an
9500        // "unavailable" description would stick (a later head move never
9501        // edits the body). Stop before anything is pushed or opened; the
9502        // run is `Blocked` and a resume asks the summary again.
9503        if self.state.resource_block.is_some() {
9504            self.state.event(
9505                "pr-summary",
9506                "a shared resource was busy; nothing was published, resume to summarize again",
9507            );
9508            return Ok(None);
9509        }
9510        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9511            anyhow::bail!(
9512                "the final commit moved during public description generation; retry before publishing"
9513            );
9514        }
9515        let note = match (&summarized, &self.state.change_summary) {
9516            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9517            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9518            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9519            (None, _) => ChangeNote::NotAsked,
9520        };
9521        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9522        if !posting {
9523            let identity = crate::scrub::Identity::current();
9524            return Ok(Some(PrMessage {
9525                title: crate::scrub::scrub(&pr.title, &identity),
9526                body: crate::scrub::scrub(&pr.body, &identity),
9527            }));
9528        }
9529        // This very text was already rejected and asked about: no second
9530        // judge call, rewrite or question, just carry the record on.
9531        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9532        if let Some(known) = self
9533            .state
9534            .github_text
9535            .clone()
9536            .filter(|g| g.fingerprint == raw_fp)
9537        {
9538            return self.settle_withheld(winner, &pr, known).await;
9539        }
9540        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9541        let mut violations =
9542            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9543        let identity = crate::scrub::Identity::current();
9544        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9545            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9546            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9547        {
9548            violations.push(crate::github_text::Violation::SensitiveData);
9549        }
9550        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9551        // only a language violation starts one; sensitive data alone goes
9552        // straight to the owner, with the redacted text as the fallback.
9553        let has_language = violations
9554            .iter()
9555            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9556        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9557            self.state.event(
9558                "github-text",
9559                if has_language {
9560                    format!("description rejected: {violations:?}; requesting one rewrite")
9561                } else {
9562                    format!("description rejected: {violations:?}; asking the owner")
9563                },
9564            );
9565            let mut rewritten = false;
9566            let mut rejected_rewrite = None;
9567            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9568            {
9569                let output = text;
9570                if let Some(title) = summary_title(&output) {
9571                    // Judge the redacted candidate that will actually be posted.
9572                    // Sensitive data alone must not discard a useful rewrite.
9573                    let raw_body = summary_without_title(&output);
9574                    let clean_title = crate::scrub::scrub(&title, &identity);
9575                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9576                    let redacted = clean_title != title || body != raw_body;
9577                    let title = clean_title;
9578                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9579                    if !complete {
9580                        self.state.event(
9581                            "github-text",
9582                            "description rewrite omitted required findings",
9583                        );
9584                    }
9585                    if !body.trim().is_empty() {
9586                        body.push_str("\n\n");
9587                        body.push_str(&public_pr_evidence(&self.state, head));
9588                    }
9589                    let marker = format!("magi:run/{}", self.state.id);
9590                    if !body.trim().is_empty() && !body.contains(&marker) {
9591                        body.push_str(&format!("\n\n{marker}"));
9592                    }
9593                    let rewrite = PrMessage {
9594                        title: title.clone(),
9595                        body: body.clone(),
9596                    };
9597                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9598                    let mut failed = crate::github_text::check_for(
9599                        &self.state.config.graph,
9600                        &title,
9601                        &body,
9602                        redecision,
9603                    );
9604                    if (!crate::github_text::shareable(&title)
9605                        || !crate::github_text::shareable(&body))
9606                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9607                    {
9608                        failed.push(crate::github_text::Violation::SensitiveData);
9609                    }
9610                    if complete
9611                        && !title.trim().is_empty()
9612                        && !body.trim().is_empty()
9613                        && !failed.is_empty()
9614                    {
9615                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9616                            title: title.clone(),
9617                            body: body.clone(),
9618                            failed: failed
9619                                .iter()
9620                                .map(|v| crate::github_text::category(*v).to_owned())
9621                                .collect(),
9622                        });
9623                    }
9624                    if complete
9625                        && !title.trim().is_empty()
9626                        && !raw_body.trim().is_empty()
9627                        && failed.is_empty()
9628                    {
9629                        decision = redecision;
9630                        pr = PrMessage { title, body };
9631                        rewritten = true;
9632                        self.state
9633                            .event("github-text", "description rewrite passed");
9634                        if redacted {
9635                            self.state.event(
9636                                "github-text",
9637                                "sensitive data removed from description rewrite",
9638                            );
9639                        }
9640                    }
9641                }
9642            }
9643            if !rewritten {
9644                self.state.event(
9645                    "github-text",
9646                    "description rewrite unavailable or rejected; asking the owner",
9647                );
9648                if let Some(w) =
9649                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9650                {
9651                    // A different text than the one asked about before: that
9652                    // question no longer describes anything.
9653                    self.retire_github_text_question("the withheld text changed");
9654                    let record = crate::run::GithubTextAsk {
9655                        rewrite: rejected_rewrite,
9656                        fingerprint: raw_fp,
9657                        title: w.title,
9658                        body: w.body,
9659                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9660                        question: None,
9661                        asks: 0,
9662                        resolved: false,
9663                        chosen_title: None,
9664                        choice: None,
9665                        publication: None,
9666                    };
9667                    return self.settle_withheld(winner, &pr, record).await;
9668                }
9669            }
9670        }
9671        let (title, body) =
9672            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9673        Ok(Some(PrMessage { title, body }))
9674    }
9675
9676    /// Describe the whole change from its final diff in either run mode.
9677    ///
9678    /// The summary is tied to the final commit and to the merge base of the
9679    /// resolved remote base; a record for any other pair is dropped and the
9680    /// agent asked again, so a description never outlives the diff it was
9681    /// written from. The seat is read-only and the prompt tells it to read the
9682    /// diff and the code around it. `[roles] synthesizer` selects the agents
9683    /// (unset: the default pick), each asked at most once, advancing on an
9684    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9685    /// carries the reason it is unavailable; nothing is invented then.
9686    async fn summarize_change(
9687        &mut self,
9688        winner: &Candidate,
9689        head: Option<&str>,
9690    ) -> std::result::Result<(), String> {
9691        let Some(head) = head else {
9692            return Err("the final commit could not be read".to_owned());
9693        };
9694        let remote = self.state.config.merge.remote.clone();
9695        let tracking = format!("{remote}/{}", self.state.base_branch);
9696        if !git::rev_exists(&winner.worktree, &tracking).await {
9697            return Err(format!("the remote base `{tracking}` could not be read"));
9698        }
9699        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9700            Ok(b) if !b.is_empty() => b,
9701            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9702        };
9703        let evidence = crate::pr_outcome::summary_evidence(
9704            &self.state,
9705            crate::pr_outcome::FinalHead::At(head),
9706        );
9707        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9708        if self
9709            .state
9710            .change_summary
9711            .as_ref()
9712            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9713        {
9714            return Ok(());
9715        }
9716        if self.state.change_summary.take().is_some() {
9717            self.state.event(
9718                "pr-summary",
9719                "the final diff or evidence changed; the earlier change summary was discarded",
9720            );
9721        }
9722        // Save the source snapshot even if no generation agent is available.
9723        if let Err(e) = write_artifact(
9724            &self.state,
9725            &format!("public-description-{fingerprint}.md"),
9726            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9727        ) {
9728            tracing::warn!("could not save public description evidence: {e:#}");
9729        }
9730        let chain = match agent::pick_chain(
9731            &self.state.config.agents,
9732            self.state.config.roles.synthesizer.as_ref(),
9733            &agent::installed,
9734            "synthesizer",
9735        ) {
9736            Ok(chain) => chain,
9737            Err(e) => {
9738                tracing::warn!("no agent for the change summary: {e:#}");
9739                self.state.event("pr-summary", "no summary agent available");
9740                return Err("no agent was available to summarize it".to_owned());
9741            }
9742        };
9743        let subjects = git::subjects(&winner.worktree, &base, head)
9744            .await
9745            .unwrap_or_default();
9746        let stat = git::diff_stat(&winner.worktree, &base, head)
9747            .await
9748            .unwrap_or_default();
9749        let stat: String = stat.chars().take(6_000).collect();
9750        let mut prompt = crate::prompt::change_summary_in(
9751            &base,
9752            head,
9753            &subjects,
9754            stat.trim(),
9755            &self.state.config.graph.github_language,
9756        );
9757        prompt.push_str(&format!("\n\n# Final-state evidence\n{evidence}\n\nUse these records as evidence, not public text to copy. Paraphrase every open or declined finding and its reason in the requested GitHub language, retaining its exact ID and severity when available. Do not translate or quote internal operator reports. Explain unresolved risks for a reviewer without the task conversation. Historical sandbox or commit failures are not the final state. Verification is appended from these records; do not make additional validation claims."));
9758        let sessions = self.state.config.graph.sessions;
9759        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9760        let prompts = self.state.config.prompts.clone();
9761        let cache = self.state.config.cache_dir();
9762        let run = self.state.id.clone();
9763        for (i, spec) in chain.into_iter().enumerate() {
9764            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9765            let github_spec = match agent::for_github_text(
9766                &spec,
9767                &self.state.config.graph.github_language,
9768                &winner.worktree,
9769            ) {
9770                Ok(spec) => spec,
9771                Err(e) => {
9772                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9773                    continue;
9774                }
9775            };
9776            let job = SeatJob {
9777                spec: github_spec,
9778                seat,
9779                cwd: winner.worktree.clone(),
9780                prompt: prompt.clone(),
9781                timeout,
9782                allow_write: false,
9783                sessions,
9784                artifacts: agent::artifacts_dir(&self.state.dir()),
9785                stem: if i == 0 {
9786                    "change-summary".to_owned()
9787                } else {
9788                    format!("change-summary-{}", spec.id)
9789                },
9790                handover: None,
9791            };
9792            let ctx = WaveCtx {
9793                run: &run,
9794                node: "pr-summary",
9795                prompts: &prompts,
9796                cache: cache.as_deref(),
9797                round: None,
9798                carry_seats: false,
9799                pauses: Some((&self.pause, &self.interrupt)),
9800            };
9801            let (seat, outcome) =
9802                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9803            self.state.seats.insert(seat.key.clone(), seat);
9804            let text = match outcome {
9805                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9806                AgentOutcome::ResourceBlocked(why) => {
9807                    // No agent was asked: the run stops resumably before
9808                    // anything is published (see `guarded_pr_message`).
9809                    if self.state.resource_block.is_none() {
9810                        self.state.resource_block = Some(crate::run::ResourceBlock {
9811                            cause: crate::run::ResourceBlockCause::Other,
9812                            node: "pr-summary".to_owned(),
9813                            kind: "shared resource".to_owned(),
9814                            detail: why,
9815                            at: Timestamp::now(),
9816                        });
9817                    }
9818                    return Err("a shared resource was busy".to_owned());
9819                }
9820                _ => continue,
9821            };
9822            let blind = &self.state.config.blind;
9823            let Some(title) = summary_title(&text) else {
9824                continue;
9825            };
9826            let body: String = summary_without_title(&text)
9827                .lines()
9828                .filter(|l| !l.contains("magi:run/"))
9829                .collect::<Vec<_>>()
9830                .join("\n");
9831            let body = blind::sanitize_prose(body.trim(), blind);
9832            let title = blind::sanitize_prose(&title, blind);
9833            if body.trim().is_empty() || title.trim().is_empty() {
9834                continue;
9835            }
9836            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9837                continue;
9838            }
9839            // The branch must still be the one the agent was shown.
9840            if git::rev_parse(&winner.worktree, "HEAD")
9841                .await
9842                .ok()
9843                .as_deref()
9844                != Some(head)
9845            {
9846                return Err("the branch moved while the summary was written".to_owned());
9847            }
9848            if git::merge_base(&winner.worktree, &tracking, head)
9849                .await
9850                .ok()
9851                .as_deref()
9852                != Some(base.as_str())
9853                || crate::pr_outcome::summary_evidence(
9854                    &self.state,
9855                    crate::pr_outcome::FinalHead::At(head),
9856                ) != evidence
9857            {
9858                return Err("the summary evidence changed while it was written".to_owned());
9859            }
9860            self.state.change_summary = Some(crate::run::ChangeSummary {
9861                head: head.to_owned(),
9862                base,
9863                evidence: fingerprint,
9864                title,
9865                body,
9866            });
9867            self.state.event(
9868                "pr-summary",
9869                format!("change summary written by {} for the final diff", spec.id),
9870            );
9871            if let Err(e) = self.state.save() {
9872                tracing::warn!("could not save the change summary: {e:#}");
9873            }
9874            return Ok(());
9875        }
9876        self.state
9877            .event("pr-summary", "no agent produced a change summary");
9878        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9879    }
9880
9881    /// One read-only rewrite request for a withheld description. The
9882    /// implementer's own conversation is tried first when it exists and can be
9883    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9884    /// writes it in a separate conversation, skipping the implementer's agent.
9885    /// The prompt carries the whole text, so no agent needs any memory. Each
9886    /// agent is asked at most once and the chain advances on an error, quota,
9887    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9888    /// that has run out of quota must not end the rewrite. Nothing is recorded
9889    /// as a handover.
9890    async fn rewrite_pr_text(
9891        &mut self,
9892        winner: &Candidate,
9893        pr: &PrMessage,
9894        violations: &[crate::github_text::Violation],
9895    ) -> Option<String> {
9896        let prompt = format!(
9897            "Rewrite only the following pull request description into English. The posting gate reported {violations:?}. Keep every substantive detail (file names, commands, numbers, findings, code blocks and <details> sections) and translate the prose. Remove all machine or operator identifying data and secrets. Do not edit files or run commands. Return TITLE: followed by the title, then the rewritten description. Include an explanation of every open or declined finding with its exact ID. Omit the generated Review rounds, Final verification and Open review findings sections, the Evidence line and run markers: magi appends those from its records.\n\nTITLE: {}\n{}",
9898            pr.title, pr.body
9899        );
9900        let sessions = self.state.config.graph.sessions;
9901        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9902        // (spec, the resumed implementer's seat). A fallback seat is created
9903        // only when its turn comes, so an unused fallback leaves no record.
9904        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9905        let key = format!("impl-{}", winner.label);
9906        if let Some(spec) = self
9907            .state
9908            .config
9909            .agents
9910            .iter()
9911            .find(|a| a.id == winner.agent)
9912            .cloned()
9913            && let Some(existing) = self.state.seats.get(&key)
9914            && existing.agent == spec.id
9915            && agent::has_session(spec.kind, existing, sessions)
9916        {
9917            attempts.push((spec, Some(existing.clone())));
9918        }
9919        match agent::pick_chain(
9920            &self.state.config.agents,
9921            self.state.config.roles.language_judge.as_ref(),
9922            &agent::installed,
9923            "language_judge",
9924        ) {
9925            Ok(chain) => {
9926                for spec in chain {
9927                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9928                        continue;
9929                    }
9930                    attempts.push((spec, None));
9931                }
9932            }
9933            Err(e) if attempts.is_empty() => {
9934                tracing::warn!("no agent for the description rewrite: {e:#}");
9935                self.state
9936                    .event("github-text", "no rewrite agent available");
9937                return None;
9938            }
9939            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9940        }
9941        let prompts = self.state.config.prompts.clone();
9942        let cache = self.state.config.cache_dir();
9943        let run = self.state.id.clone();
9944        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9945            let resumed = resumed_seat.is_some();
9946            let seat = resumed_seat.unwrap_or_else(|| {
9947                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9948            });
9949            let github_spec = match agent::for_github_text(
9950                &spec,
9951                &self.state.config.graph.github_language,
9952                &winner.worktree,
9953            ) {
9954                Ok(spec) => spec,
9955                Err(e) => {
9956                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9957                    continue;
9958                }
9959            };
9960            let job = SeatJob {
9961                spec: github_spec,
9962                seat,
9963                cwd: winner.worktree.clone(),
9964                prompt: prompt.clone(),
9965                timeout: retry_budget(timeout_full, resumed),
9966                allow_write: false,
9967                sessions,
9968                artifacts: agent::artifacts_dir(&self.state.dir()),
9969                stem: if i == 0 {
9970                    "github-text-rewrite".to_owned()
9971                } else {
9972                    format!("github-text-rewrite-{}", spec.id)
9973                },
9974                handover: None,
9975            };
9976            let ctx = WaveCtx {
9977                run: &run,
9978                node: "github-text",
9979                prompts: &prompts,
9980                cache: cache.as_deref(),
9981                round: None,
9982                carry_seats: false,
9983                pauses: Some((&self.pause, &self.interrupt)),
9984            };
9985            let (seat, outcome) =
9986                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9987            self.state.seats.insert(seat.key.clone(), seat);
9988            match outcome {
9989                AgentOutcome::Ok(o)
9990                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9991                {
9992                    return Some(o.text);
9993                }
9994                AgentOutcome::ResourceBlocked(_) => return None,
9995                _ => {}
9996            }
9997        }
9998        None
9999    }
10000
10001    /// Abandon the standing posting-gate question, if any.
10002    fn retire_github_text_question(&mut self, why: &str) {
10003        let Some(id) = self
10004            .state
10005            .github_text
10006            .as_ref()
10007            .and_then(|g| g.question.clone())
10008        else {
10009            return;
10010        };
10011        let _ = ask::Questions::open().update(&id, |q| {
10012            q.abandon(why);
10013            Ok(())
10014        });
10015    }
10016
10017    /// Carry a withheld text to its end: file the question, park while it is
10018    /// open, and on an answer, silence or timeout pick the text to post. The
10019    /// decision is saved before it is used, so it applies once.
10020    async fn settle_withheld(
10021        &mut self,
10022        winner: &Candidate,
10023        pr: &PrMessage,
10024        mut g: crate::run::GithubTextAsk,
10025    ) -> Result<Option<PrMessage>> {
10026        use crate::github_text as gt;
10027        let store = ask::Questions::open();
10028        let timeout = self.state.config.graph.answer_timeout;
10029        if !g.resolved {
10030            let mut standing = g
10031                .question
10032                .as_ref()
10033                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
10034            if let Some(q) = standing.as_ref()
10035                && q.status.open()
10036                && !store.held_reply(&q.id)
10037                && gt::expired(q, timeout)
10038            {
10039                let why = format!("no answer within {}s of asking", timeout.max(1));
10040                standing = store
10041                    .update(&q.id, |q| {
10042                        q.abandon(&why);
10043                        Ok(())
10044                    })
10045                    .ok()
10046                    .map(|(q, ())| q);
10047            }
10048            let mut ask_again: Option<Option<Vec<String>>> = None;
10049            match standing {
10050                // Recorded but never written (a stop between the two saves),
10051                // or removed: ask again without spending the retry.
10052                None if g.asks <= 1 => {
10053                    g.asks = 0;
10054                    ask_again = Some(None);
10055                }
10056                None => {
10057                    g.resolved = true;
10058                    g.chosen_title = None;
10059                    g.choice = Some(GithubTextChoice::Fallback);
10060                }
10061                Some(q) if q.status.open() => {
10062                    self.park_on_github_text(&g)?;
10063                    return Ok(None);
10064                }
10065                Some(q) => match gt::read_reply(&q) {
10066                    gt::Reply::Fallback => {
10067                        g.resolved = true;
10068                        g.chosen_title = None;
10069                        g.choice = Some(GithubTextChoice::Fallback);
10070                    }
10071                    gt::Reply::Original => {
10072                        g.resolved = true;
10073                        g.chosen_title = None;
10074                        g.choice = Some(GithubTextChoice::Original);
10075                    }
10076                    gt::Reply::Rewrite => {
10077                        g.resolved = true;
10078                        g.chosen_title = None;
10079                        g.choice = Some(if g.rewrite.is_some() {
10080                            GithubTextChoice::Rewrite
10081                        } else {
10082                            GithubTextChoice::Fallback
10083                        });
10084                    }
10085                    gt::Reply::Title(text) => {
10086                        let first = text
10087                            .lines()
10088                            .map(str::trim)
10089                            .find(|l| !l.is_empty())
10090                            .unwrap_or("");
10091                        let decision = if first.is_empty() {
10092                            None
10093                        } else {
10094                            let candidate = PrMessage {
10095                                title: first.to_owned(),
10096                                body: String::new(),
10097                            };
10098                            self.judge_pr_language(&winner.worktree, &candidate).await
10099                        };
10100                        match gt::vet_title(
10101                            &text,
10102                            decision,
10103                            self.state.config.graph.github_english(),
10104                        ) {
10105                            Ok(title) => {
10106                                g.resolved = true;
10107                                g.chosen_title = Some(title);
10108                                g.choice = Some(GithubTextChoice::MyTitle);
10109                            }
10110                            Err(cats) if g.asks < 2 => {
10111                                ask_again = Some(Some(
10112                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
10113                                ))
10114                            }
10115                            Err(_) => {
10116                                g.resolved = true;
10117                                g.chosen_title = None;
10118                                g.choice = Some(GithubTextChoice::Fallback);
10119                            }
10120                        }
10121                    }
10122                },
10123            }
10124            if let Some(rejected) = ask_again {
10125                // A retry (after a rejected replacement title) is still about
10126                // the original text: the same ORIGINAL / FALLBACK comparison.
10127                let w = gt::Withheld {
10128                    title: g.title,
10129                    body: g.body,
10130                    categories: g.categories.clone(),
10131                };
10132                // Named by the original text's fingerprint alone, so a resume
10133                // rewrites the same file and the detail stays identical.
10134                let artifact = match crate::run::write_artifact(
10135                    &self.state,
10136                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
10137                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
10138                ) {
10139                    Ok(p) => Some(p),
10140                    Err(e) => {
10141                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
10142                        None
10143                    }
10144                };
10145                let (detail, comparison) = gt::question_content(
10146                    &w,
10147                    &pr.title,
10148                    &pr.body,
10149                    &self.state.id,
10150                    rejected.as_deref(),
10151                    artifact.as_deref(),
10152                    g.rewrite.as_ref(),
10153                );
10154                let mut q = ask::Question::new(
10155                    self.state.id.clone(),
10156                    gt::ASK_NODE.to_owned(),
10157                    gt::ASK_SEAT.to_owned(),
10158                    gt::question_summary(&self.state.config.graph.language, &w),
10159                    detail,
10160                    gt::question_choices(&w, g.rewrite.as_ref()),
10161                );
10162                q.posting_comparison = Some(comparison);
10163                q.answer_timeout = timeout;
10164                // Recorded before it is written: a stop in between leaves a
10165                // record naming a question the resume then files again.
10166                g.question = Some(q.id.clone());
10167                g.asks += 1;
10168                self.state.github_text = Some(g.clone());
10169                self.state.event(
10170                    "github-text",
10171                    format!("asking the owner about the withheld text ({})", q.short()),
10172                );
10173                self.state.save()?;
10174                store
10175                    .put_executable(&mut q)
10176                    .context("file the posting-gate question")?;
10177                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
10178                    tracing::warn!(
10179                        "could not notify about posting-gate question {}: {e:#}",
10180                        q.short()
10181                    );
10182                }
10183                self.park_on_github_text(&g)?;
10184                return Ok(None);
10185            }
10186        }
10187        let resolved = g.chosen_title.clone();
10188        let original = g.choice == Some(GithubTextChoice::Original);
10189        // Field names only: the event log never records the text.
10190        self.state.event(
10191            "github-text",
10192            if original {
10193                format!(
10194                    "posting the original text for: {}",
10195                    match (g.title, g.body) {
10196                        (true, true) => "title, description",
10197                        (true, false) => "title",
10198                        _ => "description",
10199                    }
10200                )
10201            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
10202                "posting the saved rewrite title and description".to_owned()
10203            } else if resolved.is_some() {
10204                "posting the owner's replacement title".to_owned()
10205            } else {
10206                "posting the neutral text for the withheld fields".to_owned()
10207            },
10208        );
10209        self.state.github_text = Some(g.clone());
10210        self.state.save()?;
10211        if g.choice == Some(GithubTextChoice::Rewrite)
10212            && let Some(r) = g.rewrite.as_ref()
10213        {
10214            return Ok(Some(PrMessage {
10215                title: r.title.clone(),
10216                body: r.body.clone(),
10217            }));
10218        }
10219        let w = gt::Withheld {
10220            title: g.title,
10221            body: g.body,
10222            categories: g.categories.clone(),
10223        };
10224        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
10225        if let Some(t) = resolved {
10226            title = t;
10227        }
10228        // Every withheld field is now neutral or vetted English.
10229        let english = gt::LanguageDecision {
10230            title_english: true,
10231            body_english: true,
10232            body_complete: true,
10233        };
10234        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
10235        if original {
10236            // The owner's explicit choice overrides the gate for the fields it
10237            // was made for; the others keep what the gate produced.
10238            if g.title {
10239                title = pr.title.clone();
10240            }
10241            if g.body {
10242                body = pr.body.clone();
10243            }
10244        }
10245        Ok(Some(PrMessage { title, body }))
10246    }
10247
10248    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
10249        self.state.github_text = Some(g.clone());
10250        self.state.end_pass_parked(ParkCause::Question);
10251        self.state.parked = true;
10252        self.state.event(
10253            "github-text",
10254            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
10255        );
10256        self.state.save()
10257    }
10258
10259    /// Ask `[roles] language_judge` about this text and record which source
10260    /// decided; the text itself is never recorded.
10261    async fn judge_pr_language(
10262        &mut self,
10263        cwd: &Path,
10264        pr: &PrMessage,
10265    ) -> Option<crate::github_text::LanguageDecision> {
10266        self.state.config.roles.language_judge.as_ref()?;
10267        if !self.state.config.graph.language_gate() {
10268            return None;
10269        }
10270        let decision =
10271            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
10272        self.state.event(
10273            "github-text",
10274            if decision.is_some() {
10275                "language decided by the language judge"
10276            } else {
10277                "language judge unavailable; using built-in heuristics"
10278            },
10279        );
10280        decision
10281    }
10282
10283    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10284        Box::pin(self.merge_inner())
10285    }
10286
10287    async fn merge_inner(&mut self) -> Result<()> {
10288        if self.resource_halt()? || self.hold_base_sync().await? {
10289            return Ok(());
10290        }
10291        // Same reasoning as `gate`: ask the review and gate records directly
10292        // rather than `status`, which a solo-candidate `judge`/`deliberate`
10293        // skip can rewrite on reentry to something that no longer says
10294        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
10295        // so a hand-off (open findings, green verification) reaches merge
10296        // exactly like a genuinely clean round does.
10297        //
10298        // A run resumed mid-`land` never reaches here at all: `execute`
10299        // recognises `RunStatus::Landing` before it even calls `prep`, and
10300        // routes straight to `run_land` instead. That has to happen a level
10301        // up from this function, not with a check in here, because
10302        // `review_loop`'s own status recomputation (see its doc) runs
10303        // *before* `merge` on every reentry and would otherwise overwrite
10304        // the `Landing` marker with `Gating` before this node ever saw it.
10305        if self
10306            .state
10307            .base_sync
10308            .as_ref()
10309            .is_some_and(|s| s.conflict.is_some())
10310            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10311                != Some(RunStatus::Gating)
10312            // `gate_ran == false` is not "passed" - `gate` leaves it false
10313            // both before it has ever run and when its last attempt was
10314            // resource-blocked (see `Runner::gate`'s own doc), and neither is
10315            // permission to merge on nothing but the review record. Only a
10316            // gate that actually ran may proceed; an intentional local
10317            // review can also finish with verification explicitly not configured.
10318            // `RunState::gate_status` computes that distinction.
10319            || !self.state.gate_allows_progress()
10320        {
10321            return Ok(());
10322        }
10323        // This node's own record, not `status`: `status == Ready` is not
10324        // unique to the harmless `MergeMode::None` path this line was
10325        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
10326        // run's PR was closed without merging — and on that run `mode` is
10327        // still `Pr`, so a reentry that fell through here would push and
10328        // open a second pull request. `self.state.merge` is set exactly once
10329        // this node (or `land`) has already produced a verdict, under every
10330        // mode, which is what "already done" actually means here.
10331        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10332            return Ok(());
10333        }
10334        let Some(winner) = self.state.winner().cloned() else {
10335            return Ok(());
10336        };
10337        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10338        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10339            self.state.status = RunStatus::Blocked;
10340            self.state.event(
10341                "gate",
10342                "winner changed after gate; fresh verification required",
10343            );
10344            self.state.save()?;
10345            return Ok(());
10346        }
10347        let wait = self.repository_wait();
10348        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10349            return Ok(());
10350        }
10351        let repo = self.state.repo.clone();
10352        let base = self.state.base_branch.clone();
10353        let mode = self.state.config.merge.mode;
10354        let style = self.state.config.merge.style;
10355        let facts = if is_review_run(&self.state) {
10356            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10357            let start = review_base(
10358                &repo,
10359                &self.state.config.merge.remote,
10360                &base,
10361                &self.state.base_commit,
10362                &winner.branch,
10363            )
10364            .await;
10365            branch_facts(&repo, &start, &winner.branch).await
10366        } else {
10367            None
10368        };
10369        // `None` when the base could not be freshly read: then an adopted
10370        // pull request's title is left alone.
10371        let leaked = if is_review_run(&self.state) {
10372            leaked_subjects(&self.state, &winner.branch).await
10373        } else {
10374            Some(Vec::new())
10375        };
10376        // `None`: parked on the owner's word about a withheld title or body.
10377        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10378        // the resume arrives here again.
10379        let Some(pr) = self
10380            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10381            .await?
10382        else {
10383            return Ok(());
10384        };
10385        let message = pr.commit_message();
10386
10387        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10388        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10389            return Ok(());
10390        }
10391        let outcome = match mode {
10392            MergeMode::None => MergeOutcome {
10393                mode,
10394                ok: true,
10395                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10396                empty: false,
10397            },
10398            MergeMode::Pr | MergeMode::Local
10399                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10400            {
10401                MergeOutcome {
10402                    mode,
10403                    ok: false,
10404                    detail: empty_candidate_detail(&self.state, &base),
10405                    empty: true,
10406                }
10407            }
10408            MergeMode::Local => {
10409                let on = git::current_branch(&repo).await?;
10410                if on.as_deref() != Some(base.as_str()) {
10411                    MergeOutcome {
10412                        mode,
10413                        ok: false,
10414                        detail: format!(
10415                            "{} has {} checked out, not the base branch {base}",
10416                            repo.display(),
10417                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10418                        ),
10419                        empty: false,
10420                    }
10421                } else if !git::is_clean(&repo).await? {
10422                    MergeOutcome {
10423                        mode,
10424                        ok: false,
10425                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10426                        empty: false,
10427                    }
10428                } else {
10429                    let out = match style {
10430                        MergeStyle::Merge => {
10431                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10432                        }
10433                        MergeStyle::Squash => {
10434                            git::merge_squash(&repo, &winner.branch, &message).await?
10435                        }
10436                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10437                    };
10438                    MergeOutcome {
10439                        mode,
10440                        ok: out.ok(),
10441                        detail: if out.ok() { out.stdout } else { out.stderr },
10442                        empty: false,
10443                    }
10444                }
10445            }
10446            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10447                self.state.pr_publication_pending = true;
10448                self.state.save()?;
10449                let out =
10450                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10451                self.state.pr_publication_pending = out.is_err();
10452                MergeOutcome {
10453                    mode,
10454                    ok: out.is_ok(),
10455                    detail: match out {
10456                        Ok(url) => url,
10457                        Err(e) => format!("{e:#}"),
10458                    },
10459                    empty: false,
10460                }
10461            }
10462            MergeMode::Pr => {
10463                let remote = self.state.config.merge.remote.clone();
10464                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10465                let pushed = if self.state.foreign_checkout.is_some() {
10466                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10467                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10468                } else {
10469                    git::push(&winner.worktree, &remote, &winner.branch).await?
10470                };
10471                if !pushed.ok() {
10472                    MergeOutcome {
10473                        mode,
10474                        ok: false,
10475                        detail: pushed.stderr,
10476                        empty: false,
10477                    }
10478                } else {
10479                    if self.state.foreign_checkout.is_some() {
10480                        self.state.pr_pushed_head = Some(delivery_head.clone());
10481                        self.state.land_sync_checkpoint = None;
10482                    }
10483                    // A retry or resume of a run whose branch already has an
10484                    // open pull request adopts it rather than failing on a
10485                    // duplicate. Only this winner branch into this base:
10486                    // `branch_for` derives the name from the run id, so a
10487                    // different run's pull request never matches.
10488                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10489                    let out = match pr_merge_plan(found) {
10490                        PrPlan::Create => {
10491                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10492                                .await
10493                        }
10494                        PrPlan::Adopt { url, title } => {
10495                            self.state
10496                                .event("merge", format!("Pr: adopted open pull request {url}"));
10497                            if self.state.explicit_github_text_selection() {
10498                                // An explicit publication selection applies the prepared
10499                                // payload; acceptance alone is not publication proof.
10500                                land::set_pr_text_verbatim(
10501                                    &winner.worktree,
10502                                    &url,
10503                                    &pr.title,
10504                                    &pr.body,
10505                                )
10506                                .await
10507                                .map(|()| url)
10508                            } else {
10509                                if title != pr.title
10510                                    && (!is_review_run(&self.state)
10511                                        || leaked
10512                                            .as_deref()
10513                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10514                                    && let Err(e) =
10515                                        if self.state.github_text.as_ref().is_some_and(|g| {
10516                                            g.resolved
10517                                                && g.title
10518                                                && g.choice == Some(GithubTextChoice::Original)
10519                                        }) {
10520                                            // The owner chose to post this title unmodified.
10521                                            land::set_pr_title_verbatim(
10522                                                &winner.worktree,
10523                                                &url,
10524                                                &pr.title,
10525                                            )
10526                                            .await
10527                                        } else {
10528                                            land::set_pr_title(
10529                                                &mut self.state,
10530                                                &winner.worktree,
10531                                                &url,
10532                                                &pr.title,
10533                                            )
10534                                            .await
10535                                        }
10536                                {
10537                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10538                                    self.state
10539                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10540                                }
10541                                Ok(url)
10542                            }
10543                        }
10544                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10545                    };
10546                    match out {
10547                        Ok(url) => MergeOutcome {
10548                            mode,
10549                            ok: true,
10550                            detail: url,
10551                            empty: false,
10552                        },
10553                        Err(e) => MergeOutcome {
10554                            mode,
10555                            ok: false,
10556                            detail: e.to_string(),
10557                            empty: false,
10558                        },
10559                    }
10560                }
10561            }
10562        };
10563
10564        self.state.status = match (mode, outcome.ok) {
10565            (MergeMode::None, _) => RunStatus::Ready,
10566            (_, true) if outcome.empty => RunStatus::Ready,
10567            (MergeMode::Pr, true) => RunStatus::Ready,
10568            (_, true) => RunStatus::Merged,
10569            (_, false) => RunStatus::Blocked,
10570        };
10571        self.state.event(
10572            "merge",
10573            format!(
10574                "{:?}: {}",
10575                mode,
10576                outcome.detail.lines().next().unwrap_or("")
10577            ),
10578        );
10579        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10580            self.state.record_github_text_publication(&outcome.detail);
10581        }
10582        self.state.merge = Some(outcome);
10583        self.state.save()?;
10584
10585        // The PR is open and the run would historically stop here, leaving the
10586        // operator to watch checks, feed review comments back to a fixer, and
10587        // merge. That was done by hand six times in one session before this
10588        // existed. Opt-in, because merging is the one irreversible thing magi
10589        // can do to a repository.
10590        if self.state.config.graph.land
10591            && mode == MergeMode::Pr
10592            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10593        {
10594            self.run_land().await?;
10595        }
10596        // `run_land` may have left `status` at `Landing` - still waiting on
10597        // CI or the owner's approval, not actually settled - so this has to
10598        // read whatever `status` ended up as here, not the `Merged` this
10599        // function set a few lines up.
10600        self.settle_questions();
10601        Ok(())
10602    }
10603
10604    /// Enter `land`.
10605    ///
10606    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10607    /// a resumed run's re-entry. `land::land` itself is what serialises the
10608    /// two git-mutating moments inside the loop — the rebase push and
10609    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10610    /// to hold a lock across the whole call, and doing so would serialise
10611    /// this run's CI wait against a *different* run's land-approval resume
10612    /// in the same repository, which is exactly the "must not wait on
10613    /// another task" property the daemon's slot-freeing exists to give.
10614    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10615        Box::pin(self.run_land_inner())
10616    }
10617
10618    async fn run_land_inner(&mut self) -> Result<()> {
10619        crate::pr_head::ensure_owner(&self.state)?;
10620        let url = self
10621            .state
10622            .pr
10623            .as_ref()
10624            .map(|pr| pr.url.clone())
10625            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10626            .unwrap_or_default();
10627        let url = url.lines().next().unwrap_or("").trim().to_owned();
10628        if !url.starts_with("http") {
10629            return Ok(());
10630        }
10631        // A land failure is not a lost run: the work is on a branch and the
10632        // pull request is open, which is exactly where a human takes over.
10633        loop {
10634            match land::land(&mut self.state, &url).await {
10635                Ok(_)
10636                    if self
10637                        .state
10638                        .merge_repairs
10639                        .last()
10640                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10641                {
10642                    if self.repair_merge_review().await? {
10643                        continue;
10644                    }
10645                }
10646                Ok(_) if self.state.resource_block.is_some() => {
10647                    return self.stop_for_resource();
10648                }
10649                Ok(pr) if self.state.parked => {
10650                    // `land` already saved the parked marker; nothing here
10651                    // overrides `status` back to a terminal value while an
10652                    // approval is still outstanding.
10653                    let _ = pr;
10654                }
10655                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10656                    self.state.status = RunStatus::Superseded;
10657                    self.state.save()?;
10658                }
10659                Ok(pr) => {
10660                    self.state.status = match pr.state {
10661                        land::PrLifecycle::Merged => RunStatus::Merged,
10662                        _ => RunStatus::Blocked,
10663                    };
10664                    // Downstream of a confirmed merge only - see
10665                    // `bump::should_release_bump`'s own doc for why this one
10666                    // check covers all three of `land`'s success paths.
10667                    // Best-effort: the run already landed, so a failure here
10668                    // (the decision call, `gh`, `cargo`) is recorded and never
10669                    // turns a landed run into a failed one.
10670                    if bump::should_release_bump(self.state.status)
10671                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10672                    {
10673                        // The event is the run's own record. Not-eligible cases
10674                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10675                        // `Err` is a bump that was tried and failed:
10676                        // `after_merge` itself raises the operator notice for
10677                        // that, whether or not a release PR exists yet.
10678                        self.state
10679                            .event("bump", format!("release bump skipped: {e:#}"));
10680                    }
10681                    // Independent of the bump, and best-effort in the same way:
10682                    // findings the merge left open become follow-up tasks.
10683                    if self.state.status == RunStatus::Merged {
10684                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10685                    }
10686                    self.state.save()?;
10687                }
10688                Err(e) => {
10689                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10690                        return Err(e);
10691                    }
10692                    self.state.status = RunStatus::Blocked;
10693                    self.state.event("land", format!("gave up: {e}"));
10694                    self.state.save()?;
10695                }
10696            }
10697            break;
10698        }
10699        Ok(())
10700    }
10701
10702    /// One repair cycle stays under the existing driver/task claim. An
10703    /// interrupted fixer is rolled back and held rather than run twice.
10704    async fn repair_merge_review(&mut self) -> Result<bool> {
10705        use crate::run::MergeRepairPhase as Phase;
10706        crate::pr_head::ensure_owner(&self.state)?;
10707        let i = self.state.merge_repairs.len() - 1;
10708        let request = self.state.merge_repairs[i].clone();
10709        if request.phase == Phase::Fixing {
10710            let restored = match self.state.winner().cloned() {
10711                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10712                None => Err(anyhow::anyhow!("repair has no winning branch")),
10713            };
10714            let why = match restored {
10715                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10716                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10717                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10718            };
10719            self.hold_merge_repair(i, why)?;
10720            return Ok(false);
10721        }
10722        // A completed repair gate is a publication checkpoint. On reentry,
10723        // reject external changes before the ordinary gate path can replace
10724        // that evidence by verifying a new head. Requested repairs still
10725        // start their own review generation below.
10726        if request.phase == Phase::Reviewing && self.state.gate_ran {
10727            let winner = self
10728                .state
10729                .winner()
10730                .context("repair has no winning branch")?;
10731            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10732            if self.state.gate_head.as_deref() != Some(head.as_str())
10733                || !git::is_clean(&winner.worktree).await?
10734            {
10735                self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10736                return Ok(false);
10737            }
10738        }
10739        let failure = if i >= self.state.config.graph.land_rounds
10740            || self.state.config.graph.review_rounds == 0
10741        {
10742            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10743        } else {
10744            None
10745        };
10746        if let Some(why) = failure {
10747            self.hold_merge_repair(i, why)?;
10748            return Ok(false);
10749        }
10750        if request.phase == Phase::Requested {
10751            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10752                Ok(pr) => pr,
10753                Err(e) => {
10754                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10755                    return Ok(false);
10756                }
10757            };
10758            self.state.merge_repairs[i].phase = Phase::Fixing;
10759            self.state.land_approval = None;
10760            self.state.land_armed_head = None;
10761            self.state.save()?;
10762            let reason = land::merge_repair_reason(&self.state, &request)?;
10763            let budget = self.state.config.graph.land_rounds;
10764            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10765            match result {
10766                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10767                Ok(land::Fixed::Deferred) => {
10768                    // An unavailable fixer did not spend this repair request.
10769                    // Restore partial fallback work before retrying it, as for
10770                    // an interrupted repair, without closing the request.
10771                    let worktree = self
10772                        .state
10773                        .winner()
10774                        .context("repair has no winning branch")?
10775                        .worktree
10776                        .clone();
10777                    self.graft_restore(&worktree, &request.head).await?;
10778                    self.state.merge_repairs[i].phase = Phase::Requested;
10779                    self.stop_for_resource()?;
10780                    return Ok(false);
10781                }
10782                Ok(land::Fixed::Failed(why)) => {
10783                    self.hold_merge_repair(
10784                        i,
10785                        format!(
10786                            "repair failed: {why}; inspect the branch and run an explicit review"
10787                        ),
10788                    )?;
10789                    return Ok(false);
10790                }
10791                Err(e) => {
10792                    self.hold_merge_repair(
10793                        i,
10794                        format!(
10795                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10796                        ),
10797                    )?;
10798                    return Ok(false);
10799                }
10800            }
10801            // Even no change gets a real new reviewer wave. The previous
10802            // evidence remains in the request; a former clean/concluded round
10803            // cannot short-circuit the new review or gate.
10804            self.begin_merge_repair_review(i)?;
10805        }
10806        self.review_loop().await?;
10807        self.gate().await?;
10808        if self.resource_halt()? || self.state.parked {
10809            return Ok(false);
10810        }
10811        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10812            != Some(RunStatus::Gating)
10813            || !self.state.gate_allows_progress()
10814        {
10815            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10816            return Ok(false);
10817        }
10818        // Review and gate may have added commits after the initial repair.
10819        // Publish exactly their final head to the existing PR, with a lease.
10820        let winner = self
10821            .state
10822            .winner()
10823            .cloned()
10824            .context("repair has no winning branch")?;
10825        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10826        if self.state.gate_head.as_deref() != Some(after.as_str())
10827            || !git::is_clean(&winner.worktree).await?
10828        {
10829            self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10830            return Ok(false);
10831        }
10832        let expected = self
10833            .state
10834            .pr_pushed_head
10835            .as_deref()
10836            .unwrap_or(&request.head)
10837            .to_owned();
10838        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10839        // Push the checked commit itself: a local ref moving after the check
10840        // must not change which commit the forge receives.
10841        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10842            return Ok(false);
10843        }
10844        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10845        let refspec = format!("{after}:refs/heads/{public}");
10846        // Saved before the push: lease, verified commit and branch. A forge
10847        // that still shows the leased head afterwards is then recognisably
10848        // this run's own lagging view, not someone else's push.
10849        let publication = crate::run::PrPublication {
10850            previous: expected.clone(),
10851            head: after.clone(),
10852            branch: public.clone(),
10853        };
10854        let already_published =
10855            Box::pin(land::repair_publication_observed(&self.state, &publication)).await?;
10856        self.state.pr_publication = Some(publication);
10857        self.state.save()?;
10858        if !already_published {
10859            let push = git::git_raw(
10860                &winner.worktree,
10861                &["push", &lease, &self.state.config.merge.remote, &refspec],
10862            )
10863            .await;
10864            match push {
10865                Ok(out) if out.ok() => {}
10866                Ok(out) => {
10867                    self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10868                    return Ok(false);
10869                }
10870                Err(e) => {
10871                    self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10872                    return Ok(false);
10873                }
10874            }
10875        }
10876        self.state.pr_pushed_head = Some(after);
10877        self.state.land_sync_checkpoint = None;
10878        self.state.merge_repairs[i].phase = Phase::Complete;
10879        self.state.status = RunStatus::Landing;
10880        self.state.event(
10881            "repair",
10882            "new review and gate completed; fresh owner merge decision required",
10883        );
10884        self.state.save()?;
10885        Ok(true)
10886    }
10887
10888    fn merge_repair_artifacts(&self) -> PathBuf {
10889        let artifacts = agent::artifacts_dir(&self.state.dir());
10890        match self
10891            .state
10892            .merge_repairs
10893            .last()
10894            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10895        {
10896            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10897            None => artifacts,
10898        }
10899    }
10900
10901    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10902        if let Some(e2e) = self.state.head_e2e.take() {
10903            self.state
10904                .verification_history
10905                .push(crate::run::VerificationEvidence {
10906                    superseded_by: None,
10907                    archived_at: Some(Timestamp::now()),
10908                    fixes_spent: Some(self.state.gate_fixes.len()),
10909                    gate_head: None,
10910                    gate_ran: false,
10911                    gate: Vec::new(),
10912                    e2e: Some(e2e),
10913                });
10914        }
10915        self.state.reviews.clear();
10916        self.state.gate.clear();
10917        self.state.gate_ran = false;
10918        self.state.gate_head = None;
10919        self.state.gate_fixes.clear();
10920        self.state.gate_repair_e2e = None;
10921        self.state.pre_gate.clear();
10922        self.state.pre_gate_commit = None;
10923        self.state.contested_handoff = None;
10924        self.state.land_reruns = None;
10925        self.state.land_approval = None;
10926        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10927        self.state.status = RunStatus::Reviewing;
10928        self.state.save()
10929    }
10930
10931    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10932        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10933        self.state.merge_repairs[index].failure = Some(why.clone());
10934        self.state.status = RunStatus::Blocked;
10935        self.state.event("repair", why);
10936        self.state.save()
10937    }
10938
10939    // -------------------------------------------------------------- helpers
10940
10941    /// Fetch or create a seat, keeping its conversation across nodes.
10942    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10943        if let Some(existing) = self.state.seats.get(key)
10944            && existing.agent == agent
10945        {
10946            return existing.clone();
10947        }
10948        // A seat that changes agent mints its session id from the agent too,
10949        // like a handover: the old agent's uuid is already taken by the CLI.
10950        let fresh = if self.state.seats.contains_key(key) {
10951            handover_seat(key, agent, self.state.next_seat_seed())
10952        } else {
10953            SeatState::new(key, agent, self.state.seed)
10954        };
10955        self.state.seats.insert(key.to_owned(), fresh.clone());
10956        fresh
10957    }
10958
10959    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10960    /// seat to another roster agent, in which case that agent. Nodes that
10961    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10962    /// reconsideration) must keep talking to whoever answered it, not slip
10963    /// back to the agent that failed it.
10964    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10965        match self.state.seats.get(key) {
10966            Some(s) if s.agent != spec.id => {
10967                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10968            }
10969            _ => spec,
10970        }
10971    }
10972
10973    /// A candidate rendered for judging, with the leak policy applied.
10974    fn view(&self, c: &Candidate) -> CandidateView {
10975        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10976            .unwrap_or_default();
10977        let (patch, _) = blind::sanitize_patch(
10978            &format!("candidate {} patch", c.label),
10979            &raw,
10980            &self.state.config.blind,
10981        );
10982        CandidateView {
10983            label: c.label,
10984            branch: c.branch.clone(),
10985            summary: c.summary.clone(),
10986            stat: c.stat.clone(),
10987            patch,
10988        }
10989    }
10990
10991    /// The full candidate set as prompt text, for seats with no live session.
10992    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10993        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10994        prompt::judge(
10995            "(see above)",
10996            &views,
10997            self.roles.judges.len(),
10998            base_short,
10999            "en",
11000        )
11001    }
11002
11003    /// The final-vote prompt with everything a seat that has no session of its
11004    /// own needs: the candidates, the seat's own ranking and reasons, and the
11005    /// anonymised deliberation it took part in (only when there was one, so a
11006    /// handed-over seat never sees more than the seat it replaces did). The
11007    /// `Final vote` heading stays first.
11008    fn vote_prompt_full(
11009        &self,
11010        j: usize,
11011        labels: &[char],
11012        language: &str,
11013        candidates: &[Candidate],
11014        base_short: &str,
11015    ) -> String {
11016        let mut text = format!(
11017            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
11018            prompt::final_vote(labels, language),
11019            self.state.instruction,
11020            self.candidate_block(candidates, base_short)
11021        );
11022        if let Some(own) = self
11023            .state
11024            .judgements
11025            .get(j)
11026            .filter(|r| !r.ranking.is_empty())
11027        {
11028            let reasons = own
11029                .reasons
11030                .iter()
11031                .map(|(k, v)| format!("- {k}: {v}"))
11032                .collect::<Vec<_>>()
11033                .join("\n");
11034            text.push_str(&format!(
11035                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
11036                own.ranking.iter().collect::<String>(),
11037                if reasons.is_empty() {
11038                    ""
11039                } else {
11040                    ", because:\n"
11041                }
11042            ));
11043        }
11044        if !self.state.deliberation.is_empty() {
11045            text.push_str("\n# What was argued before this vote\n");
11046            for t in self.transcript(&[], j) {
11047                text.push_str(&format!(
11048                    "\n## {}{}\n\n{}\n",
11049                    t.who,
11050                    if t.is_self { " (you)" } else { "" },
11051                    t.body.trim()
11052                ));
11053            }
11054        }
11055        text
11056    }
11057
11058    /// Anonymised transcript for judge `self_idx`.
11059    ///
11060    /// The initial rankings are always the opening statements. Seeding them
11061    /// only when no turn had been taken yet meant every judge after the first
11062    /// argued against a single voice instead of against the actual split — the
11063    /// disagreement is the information, so it is always on the table.
11064    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
11065        let mut turns = Vec::new();
11066        for j in &self.state.judgements {
11067            if j.ranking.is_empty() {
11068                continue;
11069            }
11070            let reasons = j
11071                .reasons
11072                .iter()
11073                .map(|(k, v)| format!("- {k}: {v}"))
11074                .collect::<Vec<_>>()
11075                .join("\n");
11076            turns.push(Turn {
11077                who: format!("Judge {} (opening ranking)", j.judge),
11078                is_self: j.judge == self_idx + 1,
11079                body: format!(
11080                    "Ranked {}{}{reasons}",
11081                    j.ranking.iter().collect::<String>(),
11082                    if reasons.is_empty() {
11083                        ""
11084                    } else {
11085                        ", because:\n"
11086                    }
11087                ),
11088            });
11089        }
11090        for t in self
11091            .state
11092            .deliberation
11093            .iter()
11094            .flat_map(|r| r.turns.iter())
11095            .chain(current)
11096        {
11097            turns.push(Turn {
11098                who: format!("Judge {}", t.judge),
11099                is_self: t.judge == self_idx + 1,
11100                body: t.body.clone(),
11101            });
11102        }
11103        turns
11104    }
11105}
11106
11107/// Does this seat still hold the context a follow-up prompt would rely on?
11108fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
11109    agent::has_session(spec.kind, seat, sessions)
11110}
11111
11112/// The next entry in `roster` after `start`, never wrapping back to the
11113/// front, whose id is not in `tried` yet.
11114///
11115/// Starts one past `start` rather than at the front of `roster`: `start` is
11116/// the seat's own original position, and a seat whose candidate slot already
11117/// sits on the roster's second entry must fall through to the third next, not
11118/// restart at the first — which is very likely a different candidate's own
11119/// agent already. Never wraps back past `start`, for the same reason: an
11120/// entry earlier in the roster than the seat's own position is almost
11121/// certainly some *other* candidate slot's own agent, and once the tail of
11122/// the roster is exhausted there are no more untried agents for *this* seat
11123/// to fall through to — the caller's fallback chain ends there, exactly as
11124/// "no further untried agents remain in the list for that seat" asks for.
11125///
11126/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
11127/// the same id twice (an operator's `roles.implementers` typo, or a
11128/// `[[agents]]` list reused across roles) must not let
11129/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
11130/// over `roster` either finds an untried id or runs out, so this always
11131/// terminates regardless of duplicates.
11132fn next_untried_in_roster<'a>(
11133    roster: &'a [AgentSpec],
11134    start: usize,
11135    tried: &BTreeSet<String>,
11136) -> Option<&'a AgentSpec> {
11137    roster
11138        .get(start + 1..)?
11139        .iter()
11140        .find(|s| !tried.contains(&s.id))
11141}
11142
11143/// The successor for a seat, shared by all four seat kinds (implement, judge,
11144/// review, advise). `others` holds the ids that *currently* occupy the other
11145/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
11146/// sees them), so roster entries beyond the seat count act as spares: a failed
11147/// seat goes to an agent no other seat holds whenever the roster permits.
11148///
11149/// `carried` is `Some` only for the review loop's carried failure history.
11150/// Order: (1) forward from `start`, never wrapping, untried, not a carried
11151/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
11152/// whole roster: untried and not another seat's occupant; (3) the plain walk
11153/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
11154/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
11155/// a better outcome than an empty seat, and it keeps the answer to "is there
11156/// a successor at all" exactly what it was before occupants were considered,
11157/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
11158/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
11159/// carried failure is a cheaper bet than doubling an agent on the panel, and
11160/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
11161/// the same round are handled one at a time, so a seat later in the batch
11162/// sees an earlier one's new occupant but not yet its own freed agent.
11163fn pick_successor<'a>(
11164    roster: &'a [AgentSpec],
11165    start: usize,
11166    tried: &BTreeSet<String>,
11167    carried: Option<&BTreeSet<String>>,
11168    others: &BTreeSet<String>,
11169) -> Option<&'a AgentSpec> {
11170    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
11171    roster
11172        .get(start + 1..)
11173        .and_then(|tail| {
11174            tail.iter()
11175                .filter(free)
11176                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
11177        })
11178        .or_else(|| {
11179            carried
11180                .is_some()
11181                .then(|| roster.iter().find(free))
11182                .flatten()
11183        })
11184        .or_else(|| match carried {
11185            Some(c) => next_for_seat(roster, start, tried, c),
11186            None => next_untried_in_roster(roster, start, tried),
11187        })
11188}
11189
11190/// The next agent for a seat that carries its failure history across rounds
11191/// (the review loop). `round_tried` is this round's own bound and starts
11192/// empty every round; `carried_failed` only decides priority.
11193///
11194/// First: an id walking forward from `start`, never wrapping, that is neither
11195/// tried this round nor failed in an earlier one. Only when that is exhausted
11196/// does it rescue: the first roster id (in roster order, so this one *does*
11197/// look before `start`) not yet tried this round, which is by then a carried
11198/// failure. Each id is rescued at most once per round, so it cannot loop.
11199fn next_for_seat<'a>(
11200    roster: &'a [AgentSpec],
11201    start: usize,
11202    round_tried: &BTreeSet<String>,
11203    carried_failed: &BTreeSet<String>,
11204) -> Option<&'a AgentSpec> {
11205    roster
11206        .get(start + 1..)?
11207        .iter()
11208        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
11209        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
11210}
11211
11212/// Where a reviewer seat starts a round: the agent that last answered it when
11213/// it is still on the roster and not marked failed, else the spec's own agent
11214/// unless it failed, else the next roster agent that has not failed, else the
11215/// spec's own agent again (the whole roster failed). Ids no longer on the
11216/// roster are ignored. An empty roster has no handover, so the spec stands.
11217fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
11218    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
11219        return spec;
11220    };
11221    let ok = |id: &str| !h.failed.contains(id);
11222    if let Some(last) = h.last_ok.as_deref()
11223        && ok(last)
11224        && let Some(s) = roster.iter().find(|s| s.id == last)
11225    {
11226        return s.clone();
11227    }
11228    if ok(&spec.id) {
11229        return spec;
11230    }
11231    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
11232    roster
11233        .get(from + 1..)
11234        .into_iter()
11235        .flatten()
11236        .chain(roster.iter())
11237        .find(|s| ok(&s.id))
11238        .cloned()
11239        .unwrap_or(spec)
11240}
11241
11242/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
11243/// seed so a CLI that mints its session id up front (`--session-id`) never
11244/// reuses the uuid the previous agent already opened under the same seat key.
11245pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
11246    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
11247}
11248
11249/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
11250/// so the classifier below and the code that builds the message cannot drift.
11251const TIMED_OUT: &str = "timed out";
11252
11253impl FailClass {
11254    /// `None` for an answer; otherwise how the turn failed.
11255    fn of(out: &AgentOutcome) -> Option<Self> {
11256        match out {
11257            AgentOutcome::Ok(_) => None,
11258            AgentOutcome::Quota(_) => Some(Self::Quota),
11259            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
11260            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
11261            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
11262            // Not a failure of the agent. Callers check for it first; `None`
11263            // here means "no class to hand over on".
11264            AgentOutcome::ResourceBlocked(_) => None,
11265        }
11266    }
11267
11268    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11269    fn stem_word(&self) -> &'static str {
11270        match self {
11271            Self::Quota => "quota",
11272            _ => "handover",
11273        }
11274    }
11275}
11276
11277/// The message's first line with its variable parts removed — digit runs and
11278/// path-like tokens — so "exit code 2" and "exit code 7" read
11279/// as one kind of failure.
11280fn failure_signature(msg: &str) -> String {
11281    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11282    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11283    // the historical machine key while the process diagnosis uses readable prose.
11284    if let Some(code) = line
11285        .strip_prefix("process exited with no usable output (exit code ")
11286        .and_then(|s| s.strip_suffix(')'))
11287        .and_then(|s| s.parse::<i32>().ok())
11288    {
11289        line = format!("exited with some({code}) and no usable output");
11290    } else if matches!(
11291        line.as_str(),
11292        "process exited with no usable output (no exit code reported)"
11293            | "process exited with no usable output (exit code unavailable)"
11294    ) {
11295        line = "exited with none and no usable output".to_owned();
11296    }
11297    let mut out = Vec::new();
11298    for word in line.split_whitespace() {
11299        if word.contains('/') || word.contains('\\') {
11300            out.push("<path>".to_owned());
11301            continue;
11302        }
11303        let mut w = String::new();
11304        let mut in_digits = false;
11305        for c in word.chars() {
11306            if c.is_ascii_digit() {
11307                if !in_digits {
11308                    w.push('#');
11309                }
11310                in_digits = true;
11311            } else {
11312                in_digits = false;
11313                w.push(c);
11314            }
11315        }
11316        out.push(w);
11317    }
11318    out.join(" ").chars().take(120).collect()
11319}
11320
11321/// Whether a seat that just failed with `cur` may go to the next roster agent.
11322/// A quota or a timeout always may. Any other failure may not when the agent
11323/// before it failed the same way: an error the prompt causes would otherwise
11324/// walk the whole roster. `prev` is the class of the immediately preceding
11325/// agent's failure, so a quota or timeout in between breaks the run of
11326/// identical failures by itself.
11327fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11328    match cur {
11329        FailClass::Quota | FailClass::Timeout => true,
11330        FailClass::Other(_) => prev != Some(cur),
11331    }
11332}
11333
11334/// A short human reason for a failed outcome, for the handover record.
11335fn fail_reason(out: &AgentOutcome) -> String {
11336    match out {
11337        AgentOutcome::Ok(_) => String::new(),
11338        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11339        AgentOutcome::Dropped(o) => format!(
11340            "the CLI dropped the stream ({})",
11341            o.dropped
11342                .as_ref()
11343                .map(|d| d.why.as_str())
11344                .unwrap_or("it ended without delivering its answer")
11345        ),
11346        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11347            e.lines().next().unwrap_or("").chars().take(160).collect()
11348        }
11349    }
11350}
11351
11352/// Note one handover in the run: the structured record and, in the timeline,
11353/// the sentence a person reads. A quota keeps the wording it always had.
11354pub(crate) fn record_handover(
11355    state: &mut RunState,
11356    node: &str,
11357    seat: &str,
11358    from: &str,
11359    to: &str,
11360    class: &FailClass,
11361    reason: &str,
11362) {
11363    let message = if *class == FailClass::Quota {
11364        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11365    } else {
11366        format!("{seat}: handed over {from} -> {to} ({reason})")
11367    };
11368    state.event(node, message);
11369    state.handovers.push(Handover {
11370        at: Timestamp::now(),
11371        node: node.to_owned(),
11372        seat: seat.to_owned(),
11373        from: from.to_owned(),
11374        to: to.to_owned(),
11375        reason: reason.to_owned(),
11376    });
11377}
11378
11379/// Did this reply report running a command whose own CLI never confirmed an
11380/// exit status?
11381///
11382/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11383/// command *finished* (see that type's own doc), so this can only be `true`
11384/// for a command whose completion event carried no readable exit code — not
11385/// for one that simply is not mentioned at all. That is the one signal this
11386/// crate can read, from the same record `state.jobs` renders, about a reply
11387/// standing next to work its own CLI cannot vouch for finishing; it is
11388/// deliberately not a check on the exit code's *value* (a fixer legitimately
11389/// runs a command that fails mid-iteration before it succeeds) and not a
11390/// guess at a command still running in the background (which emits no event
11391/// at all, and so leaves no evidence here to find).
11392fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11393    commands.iter().any(|c| c.exit_code.is_none())
11394}
11395
11396/// The reason recorded for a candidate, and named in a handover, when an
11397/// implement seat ended its turn without starting the work and did so again
11398/// on its one retry. See [`Runner::retry_unstarted`].
11399const UNSTARTED_TWICE: &str = "the agent ended its turn without starting the work (no tool call, \
11400                               worktree unchanged), and again when asked once more";
11401
11402/// Did this turn end cleanly without the seat having started the work?
11403///
11404/// Every part is positive evidence, and a missing one means "no": a usable
11405/// reply; a CLI whose stream reports tool calls and reported none
11406/// (`tool_calls` is `None` for a backend that does not report them, which is
11407/// unknown, never zero); no command evidence; and a checkout whose `HEAD` is
11408/// the one recorded before the turn (`before`) with nothing uncommitted. A
11409/// dirty tree, a moved `HEAD` or an unreadable repository never authorizes a
11410/// retry: partial work is the other recoveries' business.
11411///
11412/// The comparison is with the seat's own starting point, not the run's base,
11413/// so a seat that left an inherited patch untouched is unstarted too.
11414fn ended_unstarted(
11415    out: &AgentOutput,
11416    before: Option<&str>,
11417    after: Option<&str>,
11418    clean: Option<bool>,
11419) -> bool {
11420    out.usable()
11421        && out.tool_calls == Some(0)
11422        && out.commands.is_empty()
11423        && before.is_some()
11424        && before == after
11425        && clean == Some(true)
11426}
11427
11428/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11429/// adoption guard.
11430#[derive(Debug, Clone, PartialEq, Eq)]
11431enum NoopClaimVerdict {
11432    /// Reply did not open with `NO CHANGE NEEDED:`.
11433    Absent,
11434    /// Structured evidence passed schema, CLI command, and repository checks.
11435    Accepted,
11436    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11437    /// concrete reason.
11438    Rejected(String),
11439}
11440
11441fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11442    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11443    cmd.description.trim() == check.method.trim()
11444}
11445
11446/// Checks cited by `requirements` plus the final check, deduplicated in order.
11447fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11448    let mut out = report.cited_checks();
11449    if let Some(last) = report.checks.last()
11450        && !out
11451            .iter()
11452            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11453    {
11454        out.push(last);
11455    }
11456    out
11457}
11458
11459/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11460/// when the backend reported commands. Empty `commands` is allowed because not
11461/// every backend emits structured command events.
11462fn check_command_evidence(
11463    report: &verdict::VerifiedNoopReport,
11464    commands: &[agent::CommandEvidence],
11465) -> std::result::Result<(), String> {
11466    if commands.is_empty() {
11467        return Ok(());
11468    }
11469    for check in checks_to_cross_verify(report) {
11470        let matching: Vec<&agent::CommandEvidence> = commands
11471            .iter()
11472            .filter(|cmd| command_matches_check(cmd, check))
11473            .collect();
11474        match check.kind {
11475            verdict::NoopEvidenceKind::Command
11476            | verdict::NoopEvidenceKind::Test
11477            | verdict::NoopEvidenceKind::Path => {
11478                let Some(last_cmd) = matching.last() else {
11479                    return Err(format!(
11480                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11481                         but no matching command was recorded by the CLI",
11482                        check.id.trim(),
11483                        check.kind,
11484                        check.target.trim()
11485                    ));
11486                };
11487                if last_cmd.exit_code != Some(0) {
11488                    return Err(format!(
11489                        "contradictory command evidence: check `{}` claims `{}` passed, \
11490                         but its last recorded CLI command (`{}`) exited with {}",
11491                        check.id.trim(),
11492                        check.target.trim(),
11493                        last_cmd.description.trim(),
11494                        crate::notices::exit_status(last_cmd.exit_code)
11495                    ));
11496                }
11497                if check.kind == verdict::NoopEvidenceKind::Test
11498                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11499                {
11500                    return Err(format!(
11501                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11502                         but its last recorded CLI output reports failure or no passing tests",
11503                        check.id.trim(),
11504                        check.target.trim()
11505                    ));
11506                }
11507            }
11508            verdict::NoopEvidenceKind::Commit => {
11509                if let Some(last_cmd) = matching.last()
11510                    && last_cmd.exit_code != Some(0)
11511                {
11512                    return Err(format!(
11513                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11514                         but its last recorded CLI command (`{}`) exited with {}",
11515                        check.id.trim(),
11516                        check.target.trim(),
11517                        last_cmd.description.trim(),
11518                        crate::notices::exit_status(last_cmd.exit_code)
11519                    ));
11520                }
11521            }
11522        }
11523    }
11524    Ok(())
11525}
11526
11527/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11528/// exit, confirmed commands, strict structured JSON validation, and
11529/// `CommandEvidence` consistency.
11530fn evaluate_noop_claim(
11531    usable: bool,
11532    commands: &[agent::CommandEvidence],
11533    text: &str,
11534) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11535    if !text
11536        .trim_start()
11537        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11538    {
11539        return Ok(None);
11540    }
11541    if !usable {
11542        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11543    }
11544    if has_unconfirmed_command(commands) {
11545        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11546    }
11547    let Some(parsed) = verdict::parse_verified_noop(text) else {
11548        return Ok(None);
11549    };
11550    let report = parsed?;
11551    check_command_evidence(&report, commands)?;
11552    Ok(Some(report))
11553}
11554
11555/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11556/// structured no-op report against the candidate's real Git history and
11557/// worktree. Existence alone never satisfies a requirement (the report still
11558/// had to carry concrete passing checks), while a missing commit/path or a
11559/// commit not on `base_commit` disqualifies the claim.
11560async fn verify_noop_repo_evidence(
11561    report: &verdict::VerifiedNoopReport,
11562    worktree: &Path,
11563    base_commit: &str,
11564) -> std::result::Result<(), String> {
11565    let wt_canon = std::fs::canonicalize(worktree).ok();
11566    for check in checks_to_cross_verify(report) {
11567        match check.kind {
11568            verdict::NoopEvidenceKind::Commit => {
11569                let target = check.target.trim();
11570                let Some(sha) = git::commit_of(worktree, target).await else {
11571                    return Err(format!(
11572                        "check `{}` cites commit `{target}`, which does not exist in git history",
11573                        check.id.trim()
11574                    ));
11575                };
11576                if !git::is_ancestor(worktree, &sha, base_commit).await {
11577                    return Err(format!(
11578                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11579                        check.id.trim(),
11580                        short(base_commit)
11581                    ));
11582                }
11583            }
11584            verdict::NoopEvidenceKind::Path => {
11585                let target = check.target.trim();
11586                let rel = verdict::strip_path_locator(target);
11587                let full = worktree.join(rel);
11588                if !full.exists() {
11589                    return Err(format!(
11590                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11591                        check.id.trim()
11592                    ));
11593                }
11594                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11595                    && !path_canon.starts_with(wt_canon)
11596                {
11597                    return Err(format!(
11598                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11599                        check.id.trim()
11600                    ));
11601                }
11602            }
11603            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11604        }
11605    }
11606    Ok(())
11607}
11608
11609/// Full adoption guard for an implementer reply, including real Git history and
11610/// worktree path verification.
11611async fn verified_noop_claim_in_worktree(
11612    usable: bool,
11613    commands: &[agent::CommandEvidence],
11614    text: &str,
11615    worktree: &Path,
11616    base_commit: &str,
11617) -> NoopClaimVerdict {
11618    let report = match evaluate_noop_claim(usable, commands, text) {
11619        Ok(Some(r)) => r,
11620        Ok(None) => return NoopClaimVerdict::Absent,
11621        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11622    };
11623    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11624        return NoopClaimVerdict::Rejected(reason);
11625    }
11626    NoopClaimVerdict::Accepted
11627}
11628
11629/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11630/// trusted as a verified no-op — the adoption guard's pure text-and-command
11631/// half (repository history/path verification runs in
11632/// [`verified_noop_claim_in_worktree`]).
11633///
11634/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11635/// timed out): a marker only earns the benefit of the doubt from a turn the
11636/// CLI itself vouches for finishing properly, the same house style
11637/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11638/// *fix* report to for `commands`. A candidate that timed out, exited
11639/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11640/// or failed structured validation returns `None`.
11641#[cfg(test)]
11642fn verified_noop_claim(
11643    usable: bool,
11644    commands: &[agent::CommandEvidence],
11645    text: &str,
11646) -> Option<String> {
11647    evaluate_noop_claim(usable, commands, text)
11648        .ok()
11649        .flatten()
11650        .map(|report| report.summary_text())
11651}
11652
11653fn short(commit: &str) -> String {
11654    commit.chars().take(7).collect()
11655}
11656
11657fn make_executable(path: &Path) -> Result<()> {
11658    #[cfg(unix)]
11659    {
11660        use std::os::unix::fs::PermissionsExt as _;
11661        let mut perms = std::fs::metadata(path)?.permissions();
11662        perms.set_mode(0o755);
11663        std::fs::set_permissions(path, perms)?;
11664    }
11665    #[cfg(not(unix))]
11666    {
11667        let _ = path;
11668    }
11669    Ok(())
11670}
11671
11672/// What every seat in one batch shares: where the answers are attributed, the
11673/// prompt overlay they inherit, and the build cache they are told to use.
11674///
11675/// A struct rather than four more parameters: `wave` also needs the run's
11676/// state (to record who is answering right now) and the attempt number, and
11677/// eight positional arguments is both unreadable and a clippy error.
11678struct WaveCtx<'a> {
11679    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11680    /// paid for it.
11681    run: &'a str,
11682    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11683    node: &'a str,
11684    prompts: &'a Prompts,
11685    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11686    cache: Option<&'a Path>,
11687    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11688    /// `JobRecord::round`. `None` for every other node.
11689    round: Option<usize>,
11690    /// Carry each seat's failed-agent history across waves (the review loop
11691    /// only): start-of-round priority and handover choice read
11692    /// [`RunState::seat_history`], and every answer or failure writes it.
11693    carry_seats: bool,
11694    /// The run's park / interrupt requests, so a wait for a shared resource
11695    /// can be abandoned the moment the operator asks to park.
11696    pauses: Option<(&'a Pause, &'a Pause)>,
11697}
11698
11699/// Shared scheduling policy for operations and spawned seat invocations.
11700fn repository_wait(
11701    state: &RunState,
11702    pauses: Option<(&Pause, &Pause)>,
11703) -> crate::repo_lock::WaitPolicy {
11704    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11705    let inherited = crate::repo_lock::WaitPolicy::current();
11706    crate::repo_lock::WaitPolicy::new(
11707        Duration::from_secs(state.config.graph.timeout_resource_wait),
11708        move || {
11709            inherited.cancelled()
11710                || pauses
11711                    .as_ref()
11712                    .is_some_and(|(a, b)| a.parked() || b.parked())
11713        },
11714    )
11715}
11716
11717fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11718    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11719        state.event("resource", timeout.0.description());
11720        state.resource_block = Some(timeout.0.clone());
11721        return;
11722    }
11723    if error.is::<crate::repo_lock::ResourceBlocked>() {
11724        state.resource_block = Some(crate::run::ResourceBlock {
11725            cause: crate::run::ResourceBlockCause::Other,
11726            node: "repository".into(),
11727            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11728                "disk admission"
11729            } else if error.to_string().contains("disk pressure") {
11730                "disk pressure"
11731            } else if error.to_string().contains("disk admission") {
11732                "disk admission"
11733            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11734                "incremental cache admission"
11735            } else {
11736                "repository coordination"
11737            }
11738            .into(),
11739            detail: format!("{error:#}"),
11740            at: Timestamp::now(),
11741        });
11742        state.event("resource", error.to_string());
11743    }
11744}
11745
11746async fn coordinate_operation(
11747    state: &mut RunState,
11748    cwd: &Path,
11749    wait: &crate::repo_lock::WaitPolicy,
11750) -> Result<Option<crate::repo_lock::SeatLease>> {
11751    let result =
11752        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11753            .await;
11754    if let Err(e) = &result {
11755        record_repository_block(state, e);
11756    }
11757    result
11758}
11759
11760/// Run one job, honouring the parallelism budget.
11761async fn run_one(
11762    job: SeatJob,
11763    sem: Arc<Semaphore>,
11764    ctx: &WaveCtx<'_>,
11765    state: &mut RunState,
11766    attempt: usize,
11767) -> (SeatState, AgentOutcome) {
11768    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11769        .await
11770        .pop()
11771        .expect("one job in, one result out");
11772    (seat, out)
11773}
11774
11775/// Run every job concurrently, capped by the semaphore, preserving order.
11776///
11777/// Every seat in the batch is recorded into [`RunState::active`] before the
11778/// wave starts and cleared as each answer lands, so the run's own record says
11779/// who is still being waited on rather than only who finished.
11780async fn wave(
11781    jobs: Vec<SeatJob>,
11782    sem: Arc<Semaphore>,
11783    ctx: &WaveCtx<'_>,
11784    state: &mut RunState,
11785    attempt: usize,
11786) -> Vec<(usize, SeatState, AgentOutcome)> {
11787    let WaveCtx {
11788        run,
11789        node,
11790        prompts,
11791        cache,
11792        round,
11793        carry_seats: _,
11794        pauses,
11795    } = *ctx;
11796    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11797    for job in &jobs {
11798        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11799    }
11800    if let Err(e) = state.save() {
11801        // A failed persist of "who is answering right now" must not abort the
11802        // wave: the seats are already being asked, and the alternative is
11803        // losing the answers to save a status line nobody may even be
11804        // watching.
11805        tracing::warn!("could not persist in-progress seats: {e:#}");
11806    }
11807    // Shared-mode waves keep their existing single lease. Isolated writers
11808    // acquire their own checkout's target at seat admission.
11809    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11810    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11811    // never borrowed from a job's agent budget (and never charged to it either,
11812    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11813    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11814    let cache_guard = if let Some(cache_dir) = cache {
11815        if jobs_had_a_writer {
11816            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11817            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11818            match acquire_cache_lease(
11819                state,
11820                cache_dir,
11821                &owner,
11822                resource_limit,
11823                node,
11824                node,
11825                &cancel,
11826            )
11827            .await
11828            {
11829                Ok(Some(g)) => Some(g),
11830                // Parking: leave without spawning anything. The run parks at
11831                // the next boundary and the seats are asked afresh on resume.
11832                Ok(None) => {
11833                    if let Some(block) = &mut state.resource_block {
11834                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11835                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11836                        };
11837                    }
11838                    return block_wave(
11839                        jobs,
11840                        state,
11841                        node,
11842                        attempt,
11843                        "parked while waiting for the shared build cache",
11844                    );
11845                }
11846                // An unreadable lease is not contention: keep the old
11847                // fallback (no shared cache for this wave's seats).
11848                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11849                Err(e) => {
11850                    // Writing seats may not build into a cache this run does
11851                    // not hold, and an agent that cannot be given one is not
11852                    // asked at all: the run stops resumably instead.
11853                    let why = format!("{e:#}");
11854                    state.event(
11855                        "resource",
11856                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11857                    );
11858                    return block_wave(jobs, state, node, attempt, &why);
11859                }
11860            }
11861        } else {
11862            None
11863        }
11864    } else {
11865        None
11866    };
11867    let cache_guard = cache_guard.map(Arc::new);
11868    // Every job keeps its whole budget: the wait above was not the agent's.
11869    // Restart the seats' clocks so "started" means "being spawned now".
11870    state.seats_spawning(node, attempt);
11871    if let Err(e) = state.save() {
11872        tracing::warn!("could not persist the start of a wave: {e:#}");
11873    }
11874    // Queueing behind this wave's own seats for a parallelism slot is normal
11875    // (each of them is bounded by its own agent timeout); only a wait beyond
11876    // all of them plus the resource limit means the slots never came back.
11877    let slot_limit = resource_limit
11878        + jobs
11879            .iter()
11880            .map(|j| j.timeout)
11881            .max()
11882            .unwrap_or_default()
11883            .saturating_mul(jobs.len() as u32);
11884    let mut set = tokio::task::JoinSet::new();
11885    // Seats announce themselves here the moment they hold a parallelism
11886    // permit, i.e. just before their CLI is spawned.
11887    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11888    let overlay = prompts.overlay(node);
11889    let repository_wait = repository_wait(state, pauses);
11890    for (i, mut job) in jobs.into_iter().enumerate() {
11891        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11892        if cache.is_some() && (!job.allow_write || cache_guard.is_some()) {
11893            job.prompt.push('\n');
11894            job.prompt
11895                .push_str(&prompt::build_cache_note(node, job.allow_write));
11896        }
11897        let sem = Arc::clone(&sem);
11898        let run = run.to_owned();
11899        let node = node.to_owned();
11900        // Only implementers were told about the task's attachments, so only
11901        // their seats get the directory widened for reading.
11902        let attachments = if node == "implement" {
11903            state.attachments.clone()
11904        } else {
11905            Vec::new()
11906        };
11907        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11908        // `prompt::build_cache_note`'s doc for why setting it anyway is
11909        // exactly how a sandboxed reviewer's write refusal got reported as a
11910        // defect in the patch, not a property of its own seat. And a
11911        // write-allowed one is handed it only when the lease above was
11912        // actually acquired: a wave that could not get it (`cache_guard` is
11913        // `None`, see its own comment) must not send seats to build into a
11914        // directory this run does not hold - that is the exact concurrent,
11915        // unmanaged-write race this module exists to prevent, not something
11916        // "proceeding anyway" is allowed to reintroduce.
11917        let cache = cache
11918            .filter(|_| job.allow_write && cache_guard.is_some())
11919            .map(Path::to_path_buf);
11920        let cache_guard = cache_guard.clone();
11921        let spawned_tx = spawned_tx.clone();
11922        let repository_wait = repository_wait.clone();
11923        let coordination = state.config.coordination.clone();
11924        let fetched_base = state.fetched_base.clone();
11925        set.spawn(async move {
11926            // A wait for a parallelism slot is scheduling, not the agent: it
11927            // is bounded by its own limit and ends as a resource block, never
11928            // as a timeout of the agent that was not started.
11929            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11930                Ok(p) => p,
11931                Err(_) => {
11932                    return (
11933                        i,
11934                        job.seat,
11935                        AgentOutcome::ResourceBlocked(format!(
11936                            "no parallel slot became free within {}s",
11937                            slot_limit.as_secs()
11938                        )),
11939                        None,
11940                        false,
11941                    );
11942                }
11943            };
11944            spawned_tx.send(job.seat.key.clone()).ok();
11945            let mut seat = job.seat;
11946            let out = repository_wait
11947                .scope(agent::invoke_in_wave(
11948                    &job.spec,
11949                    &mut seat,
11950                    &Invocation {
11951                        coordination: coordination.as_ref(),
11952                        fetched_base: fetched_base.as_ref(),
11953                        cwd: &job.cwd,
11954                        prompt: &job.prompt,
11955                        timeout: job.timeout,
11956                        allow_write: job.allow_write,
11957                        sessions: job.sessions,
11958                        artifacts: &job.artifacts,
11959                        stem: &job.stem,
11960                        run: &run,
11961                        node: &node,
11962                        cache_dir: cache.as_deref(),
11963                        attachments: &attachments,
11964                        writable: &[],
11965                    },
11966                    cache_guard.as_deref(),
11967                ))
11968                .await;
11969            let cache_block = out
11970                .as_ref()
11971                .err()
11972                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11973                .map(|timeout| timeout.0.clone());
11974            let interrupted = out
11975                .as_ref()
11976                .err()
11977                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11978            let out = match out {
11979                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11980                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11981                // Billed work the CLI failed to hand over is not an ordinary
11982                // failure, but its text is the CLI's raw error JSON, not an
11983                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11984                // read it as one by forgetting to check. `usable()` is always
11985                // false here (dropped implies an empty response), so this has
11986                // to be checked before the catch-all `Failed` below or the
11987                // one shape this exists for is lost with the rest.
11988                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11989                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11990                Ok(o) => AgentOutcome::Failed(format!(
11991                    "process exited with no usable output ({})",
11992                    crate::notices::exit_status(o.exit_code)
11993                )),
11994                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11995                    AgentOutcome::ResourceBlocked(e.to_string())
11996                }
11997                Err(e) => AgentOutcome::Failed(e.to_string()),
11998            };
11999            (i, seat, out, cache_block, interrupted)
12000        });
12001    }
12002    drop(spawned_tx);
12003    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
12004    loop {
12005        let joined = tokio::select! {
12006            Some(key) = spawned_rx.recv() => {
12007                // The clock of this seat starts now, not when it queued.
12008                state.seat_spawned(&key);
12009                if let Err(e) = state.save() {
12010                    tracing::warn!("could not persist a seat's start: {e:#}");
12011                }
12012                continue;
12013            }
12014            joined = set.join_next() => joined,
12015        };
12016        let Some(joined) = joined else {
12017            break;
12018        };
12019        let (i, seat, out, cache_block, interrupted) = match joined {
12020            Ok(v) => v,
12021            // No seat to clear: a panicked task never reported which one it
12022            // was. The defensive sweep below this loop is what stops that
12023            // seat's `active` entry from surviving forever.
12024            Err(e) => {
12025                tracing::error!("agent task panicked: {e}");
12026                continue;
12027            }
12028        };
12029        state.seat_finished(&seat.key);
12030        if interrupted
12031            && node == "implement"
12032            && let Some(label) = state
12033                .candidates
12034                .iter()
12035                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
12036                .map(|candidate| candidate.label)
12037        {
12038            state.candidate_preservation.insert(
12039                label,
12040                "interrupted implementation awaiting persistence".into(),
12041            );
12042            state.interrupted_implementations.insert(label);
12043        }
12044        if let Some(block) = cache_block
12045            && state.resource_block.is_none()
12046        {
12047            state.event("resource", block.description());
12048            state.resource_block = Some(block);
12049        }
12050        if let AgentOutcome::ResourceBlocked(why) = &out
12051            && state.resource_block.is_none()
12052        {
12053            state.resource_block = Some(crate::run::ResourceBlock {
12054                cause: crate::run::ResourceBlockCause::Other,
12055                node: node.to_owned(),
12056                kind: if why.contains("disk pressure") {
12057                    "disk pressure"
12058                } else if why.contains("disk admission") {
12059                    "disk admission"
12060                } else if why.contains(crate::incremental::BLOCKED) {
12061                    "incremental cache admission"
12062                } else if why.contains(crate::build_target::KIND) {
12063                    crate::build_target::KIND
12064                } else if why.contains("repository coordination") {
12065                    "repository coordination"
12066                } else {
12067                    "parallel slot"
12068                }
12069                .to_owned(),
12070                detail: why.clone(),
12071                at: Timestamp::now(),
12072            });
12073            let activity = if interrupted {
12074                "agent execution interrupted"
12075            } else {
12076                "no agent was started"
12077            };
12078            state.event("resource", format!("{node}: {activity} - {why}"));
12079        }
12080        record_jobs(state, node, round, &seat.key, &out);
12081        if let Err(e) = state.save() {
12082            tracing::warn!("could not persist a seat's completion: {e:#}");
12083        }
12084        if collected.len() <= i {
12085            collected.resize_with(i + 1, || None);
12086        }
12087        collected[i] = Some((i, seat, out));
12088    }
12089    // Belt-and-braces for the panic branch above: every seat this exact batch
12090    // started shares this `(node, attempt)` pair, and every seat that finished
12091    // normally already cleared itself, so anything left tagged with it here
12092    // can only be a panicked task's leftover. Cleared unconditionally rather
12093    // than left to read as still answering forever.
12094    if state
12095        .active
12096        .values()
12097        .any(|a| a.node == node && a.attempt == attempt)
12098    {
12099        state
12100            .active
12101            .retain(|_, a| !(a.node == node && a.attempt == attempt));
12102        if let Err(e) = state.save() {
12103            tracing::warn!("could not persist the end of a wave: {e:#}");
12104        }
12105    }
12106    drop(cache_guard);
12107    collected.into_iter().flatten().collect()
12108}
12109
12110/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
12111/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
12112/// this is data collection, not the fix-specific completion contract in
12113/// [`Runner::continue_fix_report`], and applies regardless of which node
12114/// asked.
12115///
12116/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
12117/// evidence from; `Failed` does not, and correctly contributes nothing — a
12118/// timeout or crash is not itself evidence about a command the seat may have
12119/// started.
12120fn record_jobs(
12121    state: &mut RunState,
12122    node: &str,
12123    round: Option<usize>,
12124    seat: &str,
12125    out: &AgentOutcome,
12126) {
12127    let commands: &[agent::CommandEvidence] = match out {
12128        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
12129        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
12130    };
12131    let checked_at = Timestamp::now();
12132    for c in commands {
12133        state.jobs.push(JobRecord {
12134            node: node.to_owned(),
12135            round,
12136            seat: seat.to_owned(),
12137            id: c.id.clone(),
12138            description: c.description.clone(),
12139            checked_at,
12140            status: match c.exit_code {
12141                Some(0) => JobStatus::Completed,
12142                Some(_) => JobStatus::Failed,
12143                None => JobStatus::Unknown,
12144            },
12145            exit_code: c.exit_code,
12146            result_summary: c.result_summary.clone(),
12147            source: c.source.clone(),
12148        });
12149    }
12150}
12151
12152/// Is a review round clean, given how many reviewer seats answered against
12153/// how many the round expected?
12154///
12155/// A seat that never answered (timeout, crash, unparsable output) is not a
12156/// seat that read the patch and found nothing — treating it as such is
12157/// exactly the bug this function exists to close. Under the default `block`
12158/// policy a missing seat can never be clean; `warn` still requires the seats
12159/// that *did* answer to have found nothing blocking and verification to be
12160/// green.
12161///
12162/// `quota_missing` narrows that `block` default for exactly one cause of
12163/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
12164/// a session limit lifts by the very next round buys nothing — the seat is
12165/// asked again with the same quota — so once every missing seat is accounted
12166/// for by a quota loss (and at least one seat *did* answer, so a decision has
12167/// something to rest on) the round is decided on the panel that could answer,
12168/// same as `warn` would. A panel that lost every seat to quota is not
12169/// decided here: `answered == 0` falls through to the existing `block`
12170/// fallback so a fully collapsed panel still waits rather than landing on no
12171/// review at all.
12172fn round_is_clean(
12173    blocking: usize,
12174    e2e_ok: bool,
12175    answered: usize,
12176    expected: usize,
12177    quota_missing: usize,
12178    policy: IncompleteReviewPolicy,
12179) -> bool {
12180    if blocking != 0 || !e2e_ok {
12181        return false;
12182    }
12183    if answered == expected || policy == IncompleteReviewPolicy::Warn {
12184        return true;
12185    }
12186    answered > 0 && expected - answered <= quota_missing
12187}
12188
12189/// The review loop's own conclusion, derived entirely from its persisted
12190/// round records and the round budget that produced them — never from
12191/// `status`, so a reentry (or `gate`/`merge` reading it independently)
12192/// recomputes the identical answer regardless of what an earlier node in the
12193/// same walk, or a previous walk, did to `status`.
12194///
12195/// `None` while more rounds remain to try, including when review never ran
12196/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
12197/// gone clean, or the budget is spent, or the tree has stopped moving (see
12198/// [`STAGNANT_LIMIT`]), the answer is one of two things:
12199///
12200/// - An incomplete panel that raised nothing is missing input, not a
12201///   verified tree — never a hand-off candidate, whatever verification said
12202///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
12203/// - Otherwise, green e2e on the last round hands off (see
12204///   [`Runner::stop_reviewing`]); red e2e blocks.
12205///
12206/// A last round whose own verification is still `ResourceBlocked` — magi
12207/// itself never got a command to run, not evidence the patch is broken —
12208/// is neither: this returns `None` for it too, the same as "more rounds
12209/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
12210/// handling of that shape) instead of this cheap recomputation guessing a
12211/// verdict a real attempt never produced.
12212pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
12213    if max_rounds == 0
12214        || reviews.last().is_some_and(|r| {
12215            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
12216        })
12217    {
12218        return Some(RunStatus::Gating);
12219    }
12220    let last = reviews.last()?;
12221    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
12222    if reviews.len() < max_rounds && !stagnant {
12223        return None;
12224    }
12225    if last.incomplete() && last.blocking == 0 {
12226        return Some(RunStatus::Blocked);
12227    }
12228    if last.e2e_status() == E2eStatus::ResourceBlocked
12229        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
12230    {
12231        return None;
12232    }
12233    Some(if last.e2e.iter().all(CommandOutcome::ok) {
12234        RunStatus::Gating
12235    } else {
12236        RunStatus::Blocked
12237    })
12238}
12239
12240/// How long a re-ask may take, given the budget the first attempt had.
12241///
12242/// A `nudged` retry is a request to restate an answer the seat has already
12243/// worked out: it carries no new work, so it does not deserve the original
12244/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
12245/// 133 seconds while a third sat for over ten minutes on a resumed session
12246/// holding 410 KB of prior output - and because the retry had inherited the
12247/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
12248/// judging round whose other seats were long finished.
12249///
12250/// A quarter of the budget, with a floor so that a deliberately short timeout
12251/// does not collapse to nothing. A retry that re-sends the whole prompt
12252/// (because the seat kept no context) is the original job again, and keeps the
12253/// original budget.
12254pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
12255    if nudged {
12256        (full / 4).max(Duration::from_secs(120)).min(full)
12257    } else {
12258        full
12259    }
12260}
12261
12262/// Run a wave and parse each reply, re-asking the seats whose reply was
12263/// unusable.
12264///
12265/// The re-ask is a nudge rather than the whole prompt again when the seat still
12266/// holds its conversation, which is the difference between a cheap retry and
12267/// paying for the entire candidate set twice.
12268///
12269/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
12270/// successor in `roster` is handed to it instead of being re-asked: the
12271/// handover is the retry. A seat with no successor left (a single-agent
12272/// roster, the roster's tail) is nudged as before, up to `retries` times. So
12273/// the asks to one seat in one node number at most
12274/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
12275/// is asked once (a dropped stream is nudged first), and only the last agent
12276/// of the chain gets the `retries` same-agent nudges. Each roster agent is
12277/// tried at most once per seat, walking forward from the seat's own position and never wrapping
12278/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
12279/// other failure stops the chain when the previous agent failed the same way
12280/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
12281/// [`has_context`] is false and the job's own full prompt and full budget are
12282/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
12283/// intermediate ones are not losses) and is returned as a failure like any
12284/// other absent seat — the caller decides whether the panel still has a
12285/// quorum. An empty `roster` disables handover: failures are nudged as they
12286/// always were, and a quota is simply lost. A reply that fails to parse or
12287/// validate is the prompt's doing and is only ever nudged, never handed over.
12288///
12289/// The returned [`SeatState`] names the agent that answered (or tried last).
12290#[allow(clippy::too_many_arguments)]
12291async fn ask_json_wave<T>(
12292    jobs: Vec<SeatJob>,
12293    sem: Arc<Semaphore>,
12294    retries: usize,
12295    roster: &[AgentSpec],
12296    ctx: &WaveCtx<'_>,
12297    losses: &mut Vec<QuotaLoss>,
12298    state: &mut RunState,
12299    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12300) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12301where
12302    T: serde::de::DeserializeOwned + Send + 'static,
12303{
12304    ask_wave_with(
12305        jobs,
12306        sem,
12307        retries,
12308        roster,
12309        ctx,
12310        losses,
12311        state,
12312        &|text: &str| {
12313            let v = verdict::extract_json::<T>(text)?;
12314            validate(&v)?;
12315            Ok(v)
12316        },
12317    )
12318    .await
12319}
12320
12321/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12322/// a node whose answer is prose (deliberation) shares the same handover,
12323/// failure classification, quota bookkeeping and bounds instead of a copy.
12324///
12325/// A seat handed to another roster agent is sent the job's `handover` prompt
12326/// (when it has one) rather than `prompt`: the new agent has no session, so a
12327/// resume-style prompt would be incomplete. That holds for the handover ask
12328/// and for every nudge to that agent whose `has_context` is false.
12329#[allow(clippy::too_many_arguments)]
12330async fn ask_wave_with<T>(
12331    jobs: Vec<SeatJob>,
12332    sem: Arc<Semaphore>,
12333    retries: usize,
12334    roster: &[AgentSpec],
12335    ctx: &WaveCtx<'_>,
12336    losses: &mut Vec<QuotaLoss>,
12337    state: &mut RunState,
12338    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12339) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12340where
12341    T: Send + 'static,
12342{
12343    let n = jobs.len();
12344    let originals: Vec<SeatJob> = jobs;
12345    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12346    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12347    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12348    // answer, N once it has gone through N nudges. Read back once this
12349    // returns, so a caller building a history record (`ReviewRecord`) can
12350    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12351    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12352    // field's own doc.
12353    let mut nudges: Vec<usize> = vec![0; n];
12354    // The agent now occupying each seat, the ids it has already been through,
12355    // where in the roster the walk began, the class of the last failure, and
12356    // the stem word of a handover not yet asked (full prompt, full budget).
12357    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12358    let mut tried: Vec<BTreeSet<String>> = specs
12359        .iter()
12360        .map(|s| BTreeSet::from([s.id.clone()]))
12361        .collect();
12362    let starts: Vec<usize> = specs
12363        .iter()
12364        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12365        .collect();
12366    let carry = ctx.carry_seats && !roster.is_empty();
12367    // Carried across rounds: ids that failed the seat earlier, and how the
12368    // last failure went (so a repeat of it is not handed over again).
12369    let carried: Vec<BTreeSet<String>> = originals
12370        .iter()
12371        .map(|j| {
12372            state
12373                .seat_history
12374                .get(&j.seat.key)
12375                .filter(|_| carry)
12376                .map(|h| h.failed.clone())
12377                .unwrap_or_default()
12378        })
12379        .collect();
12380    let mut prev: Vec<Option<FailClass>> = originals
12381        .iter()
12382        .map(|j| {
12383            state
12384                .seat_history
12385                .get(&j.seat.key)
12386                .filter(|_| carry)
12387                .and_then(|h| h.last_fail.clone())
12388        })
12389        .collect();
12390    let next_agent =
12391        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12392            let others: BTreeSet<String> = specs
12393                .iter()
12394                .enumerate()
12395                .filter(|(j, _)| *j != i)
12396                .map(|(_, s)| s.id.clone())
12397                .collect();
12398            pick_successor(
12399                roster,
12400                starts[i],
12401                tried,
12402                carry.then(|| &carried[i]),
12403                &others,
12404            )
12405            .cloned()
12406        };
12407    let mut fresh: Vec<Option<String>> = vec![None; n];
12408    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12409    let mut pending: Vec<usize> = (0..n).collect();
12410
12411    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12412    // asks: an agent with a successor is asked once and handed over, and only
12413    // a seat with no successor spends `retries` nudges on the same agent. This
12414    // only guarantees the loop's own termination whatever those say.
12415    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12416    for round in 0..max_rounds {
12417        if pending.is_empty() {
12418            break;
12419        }
12420        let mut batch = Vec::with_capacity(pending.len());
12421        let mut renudged: Vec<&str> = Vec::new();
12422        for &i in &pending {
12423            let src = &originals[i];
12424            // A seat now held by another agent than the job named has no
12425            // session of its own: it gets the full-context prompt whenever
12426            // it is asked in full (the handover ask, a nudge it cannot
12427            // resume).
12428            let full: &str = match &src.handover {
12429                Some(h) if specs[i].id != src.spec.id => h,
12430                _ => &src.prompt,
12431            };
12432            // The prompt and the budget are one decision: a nudge restates
12433            // finished work, a re-sent prompt redoes it.
12434            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12435                (
12436                    full.to_owned(),
12437                    src.timeout,
12438                    format!("{}-{word}-{}", src.stem, specs[i].id),
12439                )
12440            } else if nudges[i] == 0 {
12441                (full.to_owned(), src.timeout, src.stem.clone())
12442            } else {
12443                renudged.push(src.seat.key.as_str());
12444                let why = done[i]
12445                    .as_ref()
12446                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12447                    .unwrap_or_else(|| "no parsable answer".to_owned());
12448                let nudge = prompt::nudge(&why);
12449                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12450                let prompt = if nudged {
12451                    nudge
12452                } else {
12453                    format!("{full}\n\n---\n\n{nudge}")
12454                };
12455                (
12456                    prompt,
12457                    retry_budget(src.timeout, nudged),
12458                    format!("{}-retry{}", src.stem, nudges[i]),
12459                )
12460            };
12461            batch.push(SeatJob {
12462                spec: specs[i].clone(),
12463                seat: seats[i].clone(),
12464                cwd: src.cwd.clone(),
12465                prompt,
12466                timeout,
12467                allow_write: src.allow_write,
12468                sessions: src.sessions,
12469                artifacts: src.artifacts.clone(),
12470                stem,
12471                handover: None,
12472            });
12473        }
12474
12475        if !renudged.is_empty() {
12476            state.event(
12477                ctx.node,
12478                format!("retry {round}: re-asking {}", renudged.join(", ")),
12479            );
12480        }
12481        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12482        let mut still = Vec::new();
12483        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12484            seats[i] = seat;
12485            // No agent was asked: nothing to hand over, nudge, remember or
12486            // charge. The caller sees `resource_block` and stops the node.
12487            if let AgentOutcome::ResourceBlocked(why) = &out {
12488                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12489                continue;
12490            }
12491            let class = FailClass::of(&out);
12492            // A dropped stream is nudged first (the conversation is still
12493            // there to pick up); only a seat whose nudges are spent hands over.
12494            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12495                && nudges[i] < retries
12496                && !roster.is_empty();
12497            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12498                let next = should_hand_over(prev[i].as_ref(), &cur)
12499                    .then(|| next_agent(i, &tried[i], &specs))
12500                    .flatten();
12501                if carry {
12502                    let h = state
12503                        .seat_history
12504                        .entry(originals[i].seat.key.clone())
12505                        .or_default();
12506                    h.failed.insert(specs[i].id.clone());
12507                    h.last_fail = Some(cur.clone());
12508                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12509                        h.last_ok = None;
12510                    }
12511                    // Saved before the next agent is asked, so a restart in
12512                    // between does not forget who failed.
12513                    if let Err(e) = state.save() {
12514                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12515                    }
12516                }
12517                if let Some(next) = next {
12518                    record_handover(
12519                        state,
12520                        ctx.node,
12521                        &originals[i].seat.key,
12522                        &specs[i].id,
12523                        &next.id,
12524                        &cur,
12525                        &fail_reason(&out),
12526                    );
12527                    tried[i].insert(next.id.clone());
12528                    prev[i] = Some(cur.clone());
12529                    seats[i] =
12530                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12531                    specs[i] = next;
12532                    fresh[i] = Some(cur.stem_word().to_owned());
12533                    nudges[i] = 0;
12534                    done[i] = Some(Err(anyhow::anyhow!(
12535                        "handed over after: {}",
12536                        fail_reason(&out)
12537                    )));
12538                    still.push(i);
12539                    continue;
12540                }
12541            }
12542            if carry
12543                && !nudge_first
12544                && let Some(cur) = class.clone()
12545            {
12546                // The chain ended here (no successor, or a repeated failure).
12547                let h = state
12548                    .seat_history
12549                    .entry(originals[i].seat.key.clone())
12550                    .or_default();
12551                h.failed.insert(specs[i].id.clone());
12552                h.last_fail = Some(cur);
12553            }
12554            let parsed = match out {
12555                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12556                AgentOutcome::Quota(o) => {
12557                    last_quota[i] = o.quota.clone();
12558                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12559                }
12560                // Not a parseable answer: the nudge loop re-asks it, which is
12561                // exactly what a dropped stream needs. Just don't hand its raw
12562                // error JSON to `extract_json`.
12563                AgentOutcome::Dropped(o) => {
12564                    let why = o
12565                        .dropped
12566                        .as_ref()
12567                        .map(|d| d.why.as_str())
12568                        .unwrap_or("the CLI ended the stream without delivering its answer");
12569                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12570                }
12571                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12572                    Err(anyhow::anyhow!(e))
12573                }
12574            };
12575            let quota = class == Some(FailClass::Quota);
12576            let failed = parsed.is_err();
12577            if !failed && matches!(ctx.node, "judge" | "vote") {
12578                // A validated answer restores this seat's quorum presence,
12579                // including on the normal path after an all-seat block.
12580                state
12581                    .quota
12582                    .retain(|loss| loss.seat != originals[i].seat.key);
12583            }
12584            done[i] = Some(parsed);
12585            if carry && !failed {
12586                let h = state
12587                    .seat_history
12588                    .entry(originals[i].seat.key.clone())
12589                    .or_default();
12590                h.failed.remove(&specs[i].id);
12591                h.last_ok = Some(specs[i].id.clone());
12592                h.last_fail = None;
12593            }
12594            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12595            // fail the same way; and never re-ask a seat that already parsed.
12596            // A failed agent that still has a successor is not re-asked
12597            // either: the handover was its remedy and has just been refused
12598            // (the chain stops on a repeated failure class). A seat with no
12599            // successor left (a single-agent roster, the roster's tail, or an
12600            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12601            let agent_failure = class.is_some()
12602                && !nudge_first
12603                && !roster.is_empty()
12604                && next_agent(i, &tried[i], &specs).is_some();
12605            if failed && !quota && !agent_failure && nudges[i] < retries {
12606                nudges[i] += 1;
12607                still.push(i);
12608            }
12609        }
12610        pending = still;
12611    }
12612
12613    // One loss per seat whose chain ended on a quota: the intermediate ones
12614    // were absorbed by a handover and are not losses.
12615    for (i, q) in last_quota.into_iter().enumerate() {
12616        if let Some(quota) = q {
12617            losses.push(QuotaLoss::from_report(
12618                originals[i].seat.key.clone(),
12619                ctx.node,
12620                Some(&quota),
12621            ));
12622        }
12623    }
12624
12625    // A stalled quorum already has its own recovery checkpoint. Refresh
12626    // its missing seats before deciding whether it can resume.
12627    if state.status != RunStatus::Stalled
12628        && ctx.node != "deliberate"
12629        && n > 0
12630        && losses.len() == n
12631        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12632    {
12633        block_machine_outage(state, ctx.node, losses);
12634        state.quota.append(losses);
12635    }
12636
12637    seats
12638        .into_iter()
12639        .zip(done)
12640        .zip(nudges)
12641        .map(|((seat, res), attempts)| {
12642            (
12643                seat,
12644                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12645                attempts,
12646            )
12647        })
12648        .collect()
12649}
12650
12651/// A node with no available agent has no task verdict. Preserve the node
12652/// checkpoint and record why a subsequent explicit resume is needed.
12653pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12654    let mut auth: Vec<_> = losses
12655        .iter()
12656        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12657        .map(|loss| loss.agent.clone())
12658        .collect();
12659    auth.sort();
12660    auth.dedup();
12661    let (kind, detail) = if auth.is_empty() {
12662        (
12663            "agent usage limit",
12664            "All seats reached their agent usage limits; resume after usage is available"
12665                .to_owned(),
12666        )
12667    } else {
12668        (
12669            "agent authentication",
12670            format!(
12671                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12672                auth.join(", ")
12673            ),
12674        )
12675    };
12676    state.resource_block = Some(crate::run::ResourceBlock {
12677        node: node.to_owned(),
12678        kind: kind.to_owned(),
12679        cause: crate::run::ResourceBlockCause::Other,
12680        detail: detail.clone(),
12681        at: Timestamp::now(),
12682    });
12683    state.event(node, detail);
12684}
12685
12686/// Did the wave end without asking any agent (see [`block_wave`])?
12687fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12688    results
12689        .iter()
12690        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12691}
12692
12693/// Settle a wave that never spawned anything: every job answers
12694/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12695/// else about the seat (session, history, quota) is touched.
12696fn block_wave(
12697    jobs: Vec<SeatJob>,
12698    state: &mut RunState,
12699    node: &str,
12700    attempt: usize,
12701    why: &str,
12702) -> Vec<(usize, SeatState, AgentOutcome)> {
12703    state.resource_wait = None;
12704    state
12705        .active
12706        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12707    if let Err(e) = state.save() {
12708        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12709    }
12710    jobs.into_iter()
12711        .enumerate()
12712        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12713        .collect()
12714}
12715
12716/// Acquire the shared build cache's lease, waiting out contention within
12717/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12718/// unbounded wait is never acceptable).
12719///
12720/// A first, non-blocking check happens before ever waiting; if it finds the
12721/// lease busy, that fact is logged as a `verify` event *and* flushed with
12722/// [`RunState::save`] immediately — not only once the wait finally succeeds
12723/// or gives up — so a `magi show` run by a different process while this one
12724/// is still waiting reads a `run.json` that says so, rather than whatever it
12725/// looked like before the wait started. The same applies to the terminal
12726/// failure: logged and saved before this returns `Err`, so a caller that
12727/// could not get the lease at all still leaves a legible record of why.
12728async fn acquire_cache_lease(
12729    state: &mut RunState,
12730    cache_dir: &Path,
12731    owner: &crate::cache::Owner,
12732    budget: Duration,
12733    node: &str,
12734    context: &str,
12735    cancel: &(dyn Fn() -> bool + Sync),
12736) -> Result<Option<crate::cache::Guard>> {
12737    let home = crate::run::home();
12738    let kind = if crate::build_target::isolated(&state.config) {
12739        crate::build_target::KIND
12740    } else {
12741        "shared build cache"
12742    };
12743    let started = Instant::now();
12744    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12745        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12746        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12747        Err(e) => {
12748            state.event(
12749                "verify",
12750                format!(
12751                    "{context}: could not check the {kind} at {}: {e:#}",
12752                    cache_dir.display()
12753                ),
12754            );
12755            if let Err(e2) = state.save() {
12756                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12757            }
12758            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12759        }
12760    };
12761    state.event(
12762        "verify",
12763        format!(
12764            "{context}: waiting for the {kind} at {} ({})",
12765            cache_dir.display(),
12766            busy.describe()
12767        ),
12768    );
12769    // Seats of this node are waiting, not running: say so, so the countdown a
12770    // reader sees only ever measures an agent that has been spawned.
12771    state.resource_wait = Some(crate::run::ResourceWait {
12772        node: context.to_owned(),
12773        kind: kind.to_owned(),
12774        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12775        since: Timestamp::now(),
12776        limit_secs: budget.as_secs(),
12777    });
12778    if let Err(e) = state.save() {
12779        tracing::warn!("could not persist a cache wait: {e:#}");
12780    }
12781    let remaining = budget.saturating_sub(started.elapsed());
12782    let waited = crate::cache::wait_for_unless(
12783        &home,
12784        cache_dir,
12785        owner,
12786        remaining,
12787        Duration::from_secs(5),
12788        cancel,
12789    )
12790    .await;
12791    state.resource_wait = None;
12792    let cause = match &waited {
12793        Ok(Some(_)) => None,
12794        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12795        Err(error)
12796            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12797        {
12798            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12799                target: cache_dir.to_owned(),
12800                waited_secs: started.elapsed().as_secs(),
12801                limit_secs: budget.as_secs(),
12802            })
12803        }
12804        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12805            Some(crate::run::ResourceBlockCause::Timeout {
12806                waited_secs: started.elapsed().as_secs(),
12807                limit_secs: budget.as_secs(),
12808            })
12809        }
12810        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12811    };
12812    if let Some(cause) = cause {
12813        let detail = match &waited {
12814            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12815            Err(error) => format!("{error:#}"),
12816        };
12817        state.resource_block = Some(crate::run::ResourceBlock {
12818            cause,
12819            node: node.to_owned(),
12820            kind: kind.into(),
12821            detail: format!("{}: {detail}", cache_dir.display()),
12822            at: Timestamp::now(),
12823        });
12824        state.event(
12825            "resource",
12826            state.resource_block.as_ref().unwrap().description(),
12827        );
12828    }
12829    if let Err(error) = state.save() {
12830        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12831    }
12832    waited
12833}
12834
12835/// The lease state could not be read at all (unreadable lease file, a
12836/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12837/// known to be contended, so a wave degrades to running without a shared cache
12838/// instead of stopping on a hold that [`crate::triage`] could never release.
12839#[derive(Debug)]
12840struct CacheCheckError(String);
12841
12842impl std::fmt::Display for CacheCheckError {
12843    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12844        f.write_str(&self.0)
12845    }
12846}
12847
12848impl std::error::Error for CacheCheckError {}
12849
12850/// Keep a specific acquisition outcome when the caller adds command evidence.
12851fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12852    let kind = if crate::build_target::isolated(&state.config) {
12853        crate::build_target::KIND
12854    } else {
12855        "shared build cache"
12856    };
12857    state
12858        .resource_block
12859        .get_or_insert_with(|| crate::run::ResourceBlock {
12860            cause: crate::run::ResourceBlockCause::Other,
12861            node: node.to_owned(),
12862            kind: kind.into(),
12863            detail: format!("{error:#}"),
12864            at: Timestamp::now(),
12865        });
12866    if let Err(error) = state.save() {
12867        tracing::warn!("could not persist cache resource block: {error:#}");
12868    }
12869}
12870
12871tokio::task_local! {
12872    static VERIFY_TARGET: PathBuf;
12873}
12874
12875/// Run `body` — a verify command batch — while holding the shared build
12876/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12877/// never interleave with another borrower's build against the same
12878/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12879/// timeout, or a human's own `magi review`. See the `cache` module doc for
12880/// why this matters more than Cargo's own per-target locking covers — two
12881/// *different* worktrees building the same package name/version into one
12882/// cache directory is a staleness bug, not a lock contention one.
12883///
12884/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12885/// agent waves do. Repository scheduling also has its own bounded,
12886/// cancellable resource-wait policy. Contention must not consume the
12887/// verification budget: `body` receives the full `budget` after both leases
12888/// are acquired and the cache is fresh. Without a shared cache, only
12889/// repository coordination is acquired before handing over the full budget.
12890///
12891/// A lease that cannot be acquired within the resource wait is reported as a single
12892/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12893/// verification — the same shape a spawn failure already takes in
12894/// [`run_commands`], so a caller need not special-case it.
12895#[allow(clippy::too_many_arguments)]
12896async fn with_cache_lease<'s, F, Fut>(
12897    state: &'s mut RunState,
12898    cache_dir: Option<&Path>,
12899    node: &str,
12900    seat: &str,
12901    worktree: &Path,
12902    head: &str,
12903    budget: Duration,
12904    context: &str,
12905    wait: &crate::repo_lock::WaitPolicy,
12906    body: F,
12907) -> Result<(Vec<CommandOutcome>, bool)>
12908where
12909    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12910    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12911{
12912    // Match editing waves: cache first, repository second. In particular,
12913    // pre_gate must never hold the repository while waiting for a wave's cache.
12914    let started = Instant::now();
12915    let home = crate::run::home();
12916    let isolated = crate::build_target::isolated(&state.config);
12917    let planned_target = if isolated {
12918        let plan = (|| -> Result<PathBuf> {
12919            crate::build_target::supports(&state.config)?;
12920            crate::build_target::resolve(&home, worktree)
12921        })();
12922        match plan {
12923            Ok(path) => Some(path),
12924            Err(error) => {
12925                record_cache_error(state, node, &error);
12926                return Ok((
12927                    vec![CommandOutcome {
12928                        command: "(planning isolated build cache)".into(),
12929                        code: None,
12930                        output_tail: format!("{error:#}"),
12931                        duration_ms: 0,
12932                        resource_blocked: true,
12933                        ..Default::default()
12934                    }],
12935                    false,
12936                ));
12937            }
12938        }
12939    } else {
12940        None
12941    };
12942    let cache_dir = planned_target.as_deref().or(cache_dir);
12943    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12944    let guard = if let Some(cache_dir) = cache_dir {
12945        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12946        match acquire_cache_lease(
12947            state,
12948            cache_dir,
12949            &owner,
12950            resource_limit,
12951            node,
12952            context,
12953            &|| wait.cancelled(),
12954        )
12955        .await
12956        .and_then(|g| {
12957            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12958        }) {
12959            Ok(g) => Some(g),
12960            Err(e) => {
12961                record_cache_error(state, node, &e);
12962                return Ok((
12963                    vec![CommandOutcome {
12964                        command: if isolated {
12965                            "(waiting for the isolated build cache)"
12966                        } else {
12967                            "(waiting for the shared build cache)"
12968                        }
12969                        .into(),
12970                        code: None,
12971                        output_tail: e.to_string(),
12972                        duration_ms: started.elapsed().as_millis() as u64,
12973                        resource_blocked: true,
12974                        ..Default::default()
12975                    }],
12976                    false,
12977                ));
12978            }
12979        }
12980    } else {
12981        None
12982    };
12983    let _coordination = coordinate_operation(state, worktree, wait).await?;
12984    if let Some(path) = &planned_target {
12985        state.event(node, format!("isolated build target: {}", path.display()));
12986    }
12987    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12988        let identity = crate::cache::Identity::new(worktree, head);
12989        let fresh = crate::cache::ensure_fresh(
12990            &home,
12991            cache_dir,
12992            &identity,
12993            &state.config.verify.cargo_manifests(),
12994        );
12995        if let Err(e) = fresh {
12996            record_cache_error(state, node, &e);
12997            state.event(
12998                "verify",
12999                format!(
13000                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
13001                    worktree.display(),
13002                    short(head)
13003                ),
13004            );
13005            if let Some(guard) = guard {
13006                guard.release();
13007            }
13008            return Ok((
13009                vec![CommandOutcome {
13010                    command: "(confirming the build cache is fresh)".into(),
13011                    code: None,
13012                    output_tail: e.to_string(),
13013                    duration_ms: started.elapsed().as_millis() as u64,
13014                    resource_blocked: true,
13015                    ..Default::default()
13016                }],
13017                false,
13018            ));
13019        }
13020    }
13021    let future = body(state, budget);
13022    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
13023        VERIFY_TARGET.scope(target, future).await
13024    } else {
13025        future.await
13026    };
13027    if !timed_out_pids.is_empty() {
13028        wait_for_timed_out_children_to_die(&timed_out_pids).await;
13029    }
13030    // Drop repository coordination before releasing the cache, reversing the
13031    // acquisition order. A cancelled/error future also drops both guards.
13032    drop(_coordination);
13033    if let Some(guard) = guard {
13034        guard.release();
13035    }
13036    Ok((outcomes, retried))
13037}
13038
13039/// Poll `pids` — commands [`run_commands`] reports as still running when its
13040/// own timeout elapsed — until every one is confirmed gone, or
13041/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
13042///
13043/// Real confirmation where confirmation is possible, not a substitute for
13044/// full process-tree observation: a grandchild the timed-out process spawned
13045/// and that survives independently of it is invisible to a pid check the
13046/// same way it always was, and continuing to observe and collect *that*
13047/// stays a different piece of work with its own owner. This only narrows a
13048/// fixed blind wait into an actual check of the pids this process does know
13049/// about.
13050async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
13051    wait_for_pids_with(
13052        pids,
13053        crate::proc::pid_alive,
13054        LEASE_RELEASE_POLL,
13055        LEASE_RELEASE_MAX_WAIT,
13056    )
13057    .await;
13058}
13059
13060/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
13061/// interval and ceiling supplied by the caller, so the polling *logic* -
13062/// returns as soon as every pid reports dead, gives up at the ceiling
13063/// otherwise - is testable on millisecond durations without asking the real
13064/// OS about a pid at all.
13065async fn wait_for_pids_with<F: Fn(u32) -> bool>(
13066    pids: &[u32],
13067    alive: F,
13068    poll: Duration,
13069    max_wait: Duration,
13070) {
13071    let deadline = Instant::now() + max_wait;
13072    loop {
13073        if pids.iter().all(|&pid| !alive(pid)) {
13074            return;
13075        }
13076        if Instant::now() >= deadline {
13077            return;
13078        }
13079        tokio::time::sleep(poll).await;
13080    }
13081}
13082
13083/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
13084/// admission that it could not even get a verify command to run, as opposed
13085/// to evidence the command actually produced? A caller that would otherwise
13086/// read a resource-blocked outcome as a red command must check this first:
13087/// see [`Runner::gate`], which retries rather than records `Blocked` when
13088/// this is true.
13089fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
13090    outcomes.iter().any(|o| o.resource_blocked)
13091}
13092
13093/// What [`Runner::gate_fix_round`] decided.
13094pub(crate) enum GateFix {
13095    /// The tree changed and `verify.e2e` is still green: run the gate again.
13096    Retry,
13097    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
13098    /// last failure stands and the run ends blocked.
13099    Stop,
13100    /// `verify.e2e` could not run after the fix (magi's own contention):
13101    /// decide nothing now, a later reentry retries.
13102    Defer,
13103}
13104
13105/// Is every red command in `outcomes` an ordinary failure the code could
13106/// explain: it ran, exited non-zero, and said something?
13107///
13108/// A timeout, a spawn failure and a killed process all leave `code` `None`;
13109/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
13110/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
13111/// what the command is stays the gate's business.
13112pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
13113    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13114    red.peek().is_some()
13115        && red.all(|o| {
13116            !o.resource_blocked
13117                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13118                && !o.output_tail.trim().is_empty()
13119        })
13120}
13121
13122/// Describe one verify command's outcome for the event log, distinguishing a
13123/// build/link failure — the toolchain never produced a binary to run — from
13124/// an actual test failure, since only the latter is a verdict on the patch.
13125fn e2e_outcome_label(o: &CommandOutcome) -> String {
13126    if o.ok() {
13127        return "pass".to_owned();
13128    }
13129    let reason = if o.build_failed() {
13130        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
13131    } else {
13132        format!("FAIL ({:?})", o.code)
13133    };
13134    format!(
13135        "{reason}\n{}",
13136        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13137    )
13138}
13139
13140/// Does `outcomes` hold a failure worth one more run on the same commit?
13141///
13142/// Only an ordinary test result qualifies: every red command ran, exited
13143/// non-zero and said which way (not a build/link failure, a timeout or kill,
13144/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
13145/// evidence about the machine or the toolchain, never about a flaky test.
13146fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
13147    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13148    red.peek().is_some()
13149        && !verify_inconclusive(outcomes)
13150        && red.all(|o| {
13151            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13152        })
13153}
13154
13155/// Run `verify.e2e`, retrying once if the first attempt could not build or
13156/// link — a build/link failure is frequently a race against a shared
13157/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
13158/// `verify` event per command, tagged with `context` (normally `"round N"`)
13159/// so the call sites that need this — the ordinary per-round leg in
13160/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
13161/// will ever call a round green, `verify_current_head` and the gate-repair
13162/// check — read identically in the event log.
13163///
13164/// A failure that is a test result (see [`rerunnable_failure`]) is believed
13165/// only after the failed commands have run once more on the same commit, in
13166/// the same worktree and — because the caller holds it around this whole
13167/// function — under the same cache lease, with a full `timeout` of their own
13168/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
13169/// flake: the head is verified, the first failure is recorded and filed
13170/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
13171/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
13172/// preserving bounded evidence and artifact references for both attempts;
13173/// it claims a matching reproduction only when both attempts yield identical
13174/// confirmed terminal test failures. One verification is therefore run at most
13175/// three times: the build/link retry, then this one rerun. `round` is the
13176/// review round the verification belongs to, if any.
13177async fn run_e2e_with_retry(
13178    state: &mut RunState,
13179    shell: &[String],
13180    commands: &[String],
13181    worktree: &Path,
13182    timeout: Duration,
13183    context: &str,
13184    round: Option<usize>,
13185) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
13186    let (mut e2e, mut timed_out_pids) = run_commands(
13187        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
13188    )
13189    .await;
13190    for o in &e2e {
13191        state.event(
13192            "verify",
13193            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
13194        );
13195    }
13196    // A build/link failure is not a verdict on the patch — it is frequently a
13197    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
13198    // one retry before letting a red like that decide the round.
13199    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
13200    if verify_retried {
13201        state.event(
13202            "verify",
13203            format!(
13204                "{context}: verify could not build/link, not a test result — retrying once \
13205                 before concluding"
13206            ),
13207        );
13208        let retried = run_commands(
13209            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
13210        )
13211        .await;
13212        e2e = retried.0;
13213        // Both attempts' timeouts matter, not just the last one: the first
13214        // attempt's descendants may still be alive alongside the retry's.
13215        timed_out_pids.extend(retried.1);
13216        for o in &e2e {
13217            state.event(
13218                "verify",
13219                format!(
13220                    "{context}: retry `{}` -> {}",
13221                    o.command,
13222                    e2e_outcome_label(o)
13223                ),
13224            );
13225        }
13226    }
13227    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
13228        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
13229        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
13230        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
13231        state.event(
13232            "verify",
13233            format!(
13234                "{context}: {} failed with a test result — running it once more on the same \
13235                 commit {} before deciding",
13236                rerun_commands
13237                    .iter()
13238                    .map(|c| format!("`{c}`"))
13239                    .collect::<Vec<_>>()
13240                    .join(", "),
13241                short(&head)
13242            ),
13243        );
13244        let (second, pids) = run_commands(
13245            state,
13246            "verify",
13247            "e2e",
13248            1 + usize::from(verify_retried),
13249            shell,
13250            &rerun_commands,
13251            worktree,
13252            timeout,
13253        )
13254        .await;
13255        timed_out_pids.extend(pids);
13256        for o in &second {
13257            state.event(
13258                "verify",
13259                format!(
13260                    "{context}: rerun `{}` -> {}",
13261                    o.command,
13262                    e2e_outcome_label(o)
13263                ),
13264            );
13265        }
13266        for (slot, &i) in failed.iter().enumerate() {
13267            let Some(again) = second.get(slot) else {
13268                break;
13269            };
13270            let first = std::mem::replace(&mut e2e[i], again.clone());
13271            if again.ok() {
13272                let signature = crate::flake::signature(&first.output_tail, first.code);
13273                let flake = crate::run::VerifyFlake {
13274                    round,
13275                    context: context.to_owned(),
13276                    head: head.clone(),
13277                    command: first.command.clone(),
13278                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
13279                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
13280                    at: Timestamp::now(),
13281                    task: None,
13282                    filed: false,
13283                    filing_error: None,
13284                };
13285                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
13286            } else if !again.resource_blocked {
13287                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
13288                let message = crate::verify_evidence::rerun_event_message(
13289                    context,
13290                    &e2e[i].command,
13291                    &comparison,
13292                );
13293                e2e[i].rerun_comparison = Some(comparison);
13294                state.event("verify", message);
13295            }
13296        }
13297    }
13298    (e2e, verify_retried, timed_out_pids)
13299}
13300
13301/// Run configured shell commands in `cwd`, in order. The second element is
13302/// the pid of every command that hit `timeout` and was still running when
13303/// this stopped waiting on it (best-effort: `None` when the platform did not
13304/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13305/// that releases a shared resource afterward needs to know.
13306///
13307/// Records `task` into [`RunState::active`] at every command boundary
13308/// (`RunState::task_command`) and clears it once the whole list has run
13309/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13310/// for minutes with no seat and no output of its own to show for it (see
13311/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13312/// apart from "not yet run" without this), and this is the only place that
13313/// knows which command is running right now and how many are left. Three
13314/// saves per command — start, not per second — matching the same "only at a
13315/// boundary" rule [`wave`] already follows for seats.
13316#[allow(clippy::too_many_arguments)]
13317async fn run_commands(
13318    state: &mut RunState,
13319    node: &str,
13320    task: &str,
13321    attempt: usize,
13322    shell: &[String],
13323    commands: &[String],
13324    cwd: &Path,
13325    timeout: Duration,
13326) -> (Vec<CommandOutcome>, Vec<u32>) {
13327    let isolated = crate::build_target::isolated(&state.config);
13328    if isolated && let Some(block) = &state.resource_block {
13329        return (
13330            vec![CommandOutcome {
13331                command: "(isolated build admission)".into(),
13332                code: None,
13333                output_tail: block.description(),
13334                duration_ms: 0,
13335                resource_blocked: true,
13336                ..Default::default()
13337            }],
13338            Vec::new(),
13339        );
13340    }
13341    if commands.is_empty() {
13342        // Nothing to mark as running and nothing to clear — an empty list
13343        // means "not configured", and touching `active` (or the disk) over
13344        // that would be a write for every round of a repo with no
13345        // `verify.e2e` / `verify.gate` commands at all.
13346        return (Vec::new(), Vec::new());
13347    }
13348    let mut out = Vec::new();
13349    let mut timed_out_pids = Vec::new();
13350    let total = commands.len();
13351    for (idx, command) in commands.iter().enumerate() {
13352        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13353        if let Err(e) = state.save() {
13354            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13355        }
13356        let started = Instant::now();
13357        let mut cmd = tokio::process::Command::new(&shell[0]);
13358        cmd.quiet();
13359        // Verify the checkout as a standalone caller. Worker ownership and
13360        // pinned executable selection belong to this driver, not to tests or
13361        // tools it runs. Preserve home/seat context and Running's containment.
13362        for key in crate::worker::INVOCATION_ENV {
13363            cmd.env_remove(key);
13364        }
13365        cmd.env_remove(crate::build_id::EXPECT_ENV);
13366        cmd.args(&shell[1..])
13367            .current_dir(cwd)
13368            .stdin(std::process::Stdio::null())
13369            .stdout(std::process::Stdio::piped())
13370            .stderr(std::process::Stdio::piped())
13371            .kill_on_drop(true);
13372        let mut outputs = Vec::new();
13373        let mut cache = None;
13374        let home = crate::run::home();
13375        let head = if isolated {
13376            Some(git::rev_parse(cwd, "HEAD").await)
13377        } else {
13378            None
13379        };
13380        let protected = (|| -> Result<()> {
13381            crate::incremental::configure(&mut cmd, cwd)?;
13382            cache = if isolated {
13383                let target = VERIFY_TARGET
13384                    .try_with(Clone::clone)
13385                    .context("isolated verification has no target lease")?;
13386                cmd.arg(crate::build_target::command::normalize(command)?);
13387                crate::build_target::command::configure(&mut cmd, &target)?;
13388                Some(target)
13389            } else {
13390                crate::build_target::command::clear(&mut cmd)?;
13391                cmd.arg(command);
13392                state.config.cache_dir()
13393            };
13394            let mut paths = vec![cwd.to_owned()];
13395            if let Some(cache) = &cache {
13396                paths.push(cache.clone());
13397            }
13398            let admit = if isolated {
13399                crate::retention::OutputLease::admit_isolated
13400            } else {
13401                crate::retention::OutputLease::admit
13402            };
13403            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13404            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13405                outputs.push(guard);
13406            }
13407            if let Some(cache) = &cache {
13408                outputs.push(crate::retention::OutputLease::cache(
13409                    &crate::run::home(),
13410                    cache,
13411                    false,
13412                )?);
13413                if let Some(head) = head {
13414                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13415                    if task == "pre_gate" {
13416                        crate::cache::invalidate_identity(&home, cache);
13417                    }
13418                }
13419            }
13420            Ok(())
13421        })();
13422        if let Err(e) = protected {
13423            let detail = format!("execution admission unavailable: {e:#}");
13424            state.resource_block = Some(crate::run::ResourceBlock {
13425                cause: crate::run::ResourceBlockCause::Other,
13426                node: node.to_owned(),
13427                kind: if detail.contains("disk admission") {
13428                    "disk admission"
13429                } else {
13430                    "output ownership"
13431                }
13432                .to_owned(),
13433                detail: detail.clone(),
13434                at: Timestamp::now(),
13435            });
13436            out.push(CommandOutcome {
13437                command: command.clone(),
13438                code: None,
13439                output_tail: detail,
13440                duration_ms: 0,
13441                resource_blocked: true,
13442                ..Default::default()
13443            });
13444            break;
13445        }
13446        let spawned = if isolated {
13447            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13448        } else {
13449            crate::seat_process::Running::spawn(cmd, None, outputs)
13450        };
13451        let (code, out_text, err_text, body) = match spawned {
13452            Ok(mut running) => {
13453                let pid = running.child().id();
13454                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13455                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13456                let mut paths = vec![cwd.to_owned()];
13457                if let Some(cache) = cache {
13458                    paths.push(cache);
13459                }
13460                let mut pressure = None;
13461                let status = tokio::select! {
13462                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13463                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13464                        pressure = Some(reason); None
13465                    }
13466                };
13467                let (code, failure) = match status {
13468                    Some(Ok(Ok(status))) => (
13469                        status.code(),
13470                        status
13471                            .code()
13472                            .is_none()
13473                            .then(|| format!("command terminated: {status}")),
13474                    ),
13475                    Some(Ok(Err(error))) => {
13476                        (None, Some(format!("failed waiting for command: {error}")))
13477                    }
13478                    Some(Err(_)) => {
13479                        // Leased cleanup confirms process-tree death itself.
13480                        // Unleased commands still need the caller's PID check
13481                        // after kill-on-drop, before releasing cache ownership.
13482                        if !running.coordinated()
13483                            && let Some(pid) = pid
13484                        {
13485                            timed_out_pids.push(pid);
13486                        }
13487                        (
13488                            None,
13489                            Some(format!("timed out after {}s", timeout.as_secs())),
13490                        )
13491                    }
13492                    None => (None, None),
13493                };
13494                running.finish().await;
13495                if let Some(reason) = pressure {
13496                    state.resource_block = Some(crate::run::ResourceBlock {
13497                        cause: crate::run::ResourceBlockCause::Other,
13498                        node: node.to_owned(),
13499                        kind: "disk pressure".to_owned(),
13500                        detail: reason.clone(),
13501                        at: Timestamp::now(),
13502                    });
13503                    out.push(CommandOutcome {
13504                        command: command.clone(),
13505                        code: None,
13506                        output_tail: reason,
13507                        duration_ms: started.elapsed().as_millis() as u64,
13508                        resource_blocked: true,
13509                        ..Default::default()
13510                    });
13511                    break;
13512                }
13513                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13514                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13515                let mut body = out_text.clone();
13516                body.push_str(&err_text);
13517                if let Some(failure) = failure {
13518                    body.push('\n');
13519                    body.push_str(&failure);
13520                }
13521                (code, out_text, err_text, body)
13522            }
13523            Err(e) if isolated => {
13524                let e = anyhow::Error::new(e)
13525                    .context(format!("could not start managed build `{}`", shell[0]));
13526                record_cache_error(state, node, &e);
13527                out.push(CommandOutcome {
13528                    command: command.clone(),
13529                    code: None,
13530                    output_tail: format!("{e:#}"),
13531                    duration_ms: 0,
13532                    resource_blocked: true,
13533                    ..Default::default()
13534                });
13535                break;
13536            }
13537            Err(e) => (
13538                None,
13539                String::new(),
13540                String::new(),
13541                format!("failed to spawn `{}`: {e}", shell[0]),
13542            ),
13543        };
13544        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13545        let mut artifact = None;
13546        if !body.is_empty() {
13547            // The full text is kept whatever the summary dropped. A fresh
13548            // name per command so a resume or retry never overwrites an
13549            // earlier run's output. A failed write changes no verdict.
13550            match crate::run::write_verification_artifact(state, task, &body) {
13551                Ok(name) => {
13552                    let rel = format!("artifacts/{name}");
13553                    if summary != body {
13554                        summary = format!("[full output: {rel}]\n{summary}");
13555                    }
13556                    artifact = Some(rel);
13557                }
13558                Err(e) => {
13559                    let warning = format!("could not save the full {task} output: {e:#}");
13560                    tracing::warn!("{warning}");
13561                    state.event(node, warning);
13562                    if summary != body {
13563                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13564                    }
13565                }
13566            }
13567        }
13568        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13569        let mut outcome = CommandOutcome {
13570            command: command.clone(),
13571            code,
13572            output_tail: summary,
13573            duration_ms: started.elapsed().as_millis() as u64,
13574            resource_blocked,
13575            artifact,
13576            failure_evidence: None,
13577            rerun_comparison: None,
13578        };
13579        if !outcome.ok() && !outcome.resource_blocked {
13580            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13581                code,
13582                outcome.build_failed(),
13583                &out_text,
13584                &err_text,
13585            ));
13586        }
13587        out.push(outcome);
13588        if resource_blocked {
13589            state.resource_block = Some(crate::run::ResourceBlock {
13590                cause: crate::run::ResourceBlockCause::Other,
13591                node: node.to_owned(),
13592                kind: "incremental cache admission".into(),
13593                detail: body,
13594                at: Timestamp::now(),
13595            });
13596            break;
13597        }
13598    }
13599    state.task_finished(task);
13600    if let Err(e) = state.save() {
13601        tracing::warn!("could not persist the end of {task}: {e:#}");
13602    }
13603    (out, timed_out_pids)
13604}
13605
13606/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13607/// section (`report::run`) and in the `merge` event this node records — for
13608/// the operator to run by hand.
13609///
13610/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13611/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13612/// merge commits", or "require linear history") rejects the push a `--no-ff`
13613/// merge would produce, which is exactly the guidance this function replaces.
13614/// `message`'s first line becomes the squash commit's subject, matching the
13615/// note `report::run` prints alongside this command — see that function for
13616/// why an explicit subject is not optional there.
13617fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13618    let repo = repo.display();
13619    match style {
13620        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13621        MergeStyle::Squash => {
13622            // The subject sits inside double quotes, and a title an agent
13623            // wrote may carry the characters that break out of them.
13624            let subject = message
13625                .lines()
13626                .next()
13627                .unwrap_or(branch)
13628                .replace(['\\', '"', '$', '`'], "");
13629            format!(
13630                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13631            )
13632        }
13633        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13634    }
13635}
13636
13637/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13638/// under the hood, rejects a `title` over 256 characters and the whole
13639/// command fails — no PR at all, for a run whose body was otherwise fine
13640/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13641/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13642/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13643/// this bound. It is a margin, not a guarantee — a title packed
13644/// with multi-unit characters could still in principle land close to the
13645/// edge, but a real task title's occasional emoji or accented letter fits
13646/// comfortably inside it.
13647const PR_TITLE_MAX: usize = 240;
13648
13649/// A pull request title from the opening line of `text`, or `None` when that
13650/// line is not English (GitHub text is) or has no letters.
13651///
13652/// A line within `max` is kept as is. A longer one is cut at the end of its
13653/// first sentence when that falls inside `max`, else at a word boundary with a
13654/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13655/// make every merely-truncated title look non-English). The language check
13656/// runs on the kept text before any mark is added, so only what GitHub will
13657/// show is judged: an English opening followed by non-ASCII far past the cut
13658/// still passes.
13659fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13660    let line = queue::first_line(text)?;
13661    let chars: Vec<char> = line.chars().collect();
13662    let (kept, mark) = if chars.len() <= max {
13663        (line.to_owned(), "")
13664    } else if let Some(end) = sentence_end(&chars, max) {
13665        (chars[..end].iter().collect::<String>(), "")
13666    } else {
13667        let room = max.saturating_sub(3);
13668        // Cut at the last space inside the room; when the char just past the
13669        // room is a space the room already ends on a word.
13670        let cut = if chars[room].is_whitespace() {
13671            room
13672        } else {
13673            chars[..room]
13674                .iter()
13675                .rposition(|c| c.is_whitespace())
13676                .unwrap_or(room)
13677        };
13678        let head: String = chars[..cut].iter().collect();
13679        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13680        (head.to_owned(), "...")
13681    };
13682    if kept.is_empty() {
13683        return None;
13684    }
13685    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13686        return None;
13687    }
13688    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13689        return None;
13690    }
13691    Some(format!("{kept}{mark}"))
13692}
13693
13694/// The char length of the first sentence of `chars` when it ends within `max`
13695/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13696/// abbreviations so `e.g. foo` does not end a title early.
13697fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13698    const MIN: usize = 20;
13699    for i in MIN..max.min(chars.len()) {
13700        if !matches!(chars[i], '.' | '!' | '?') {
13701            continue;
13702        }
13703        let Some(&next) = chars.get(i + 1) else {
13704            continue;
13705        };
13706        if !next.is_whitespace() {
13707            continue;
13708        }
13709        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13710        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13711            continue;
13712        }
13713        let word: String = chars[..i]
13714            .iter()
13715            .rev()
13716            .take_while(|c| !c.is_whitespace())
13717            .collect::<Vec<_>>()
13718            .into_iter()
13719            .rev()
13720            .collect();
13721        let word = word.to_ascii_lowercase();
13722        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13723            continue;
13724        }
13725        let end = chars[..i]
13726            .iter()
13727            .rposition(|c| !c.is_whitespace())
13728            .map_or(i, |p| p + 1);
13729        return Some(end);
13730    }
13731    None
13732}
13733
13734/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13735/// change: a title and a body describing what was *implemented*, not the task
13736/// that asked for it. A task reads as a request; a reader of the merged
13737/// history wants the change.
13738struct PrMessage {
13739    title: String,
13740    body: String,
13741}
13742
13743impl PrMessage {
13744    /// Title, blank line, body. The first line is the squash/merge commit
13745    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13746    /// has to stay one sensible line.
13747    fn commit_message(&self) -> String {
13748        format!("{}\n\n{}", self.title, self.body)
13749    }
13750}
13751
13752/// The text after a leading `TITLE:` (any case) on `line`.
13753fn title_marker(line: &str) -> Option<&str> {
13754    let line = line.trim();
13755    let head = line.get(..6)?;
13756    head.eq_ignore_ascii_case("title:")
13757        .then(|| line[6..].trim())
13758}
13759
13760/// The implementer's own one-line title: the `TITLE:` line the implement
13761/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13762/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13763/// source, and a title that says as much is refused here too.
13764fn summary_title(summary: &str) -> Option<String> {
13765    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13766    let raw = title_marker(first)?;
13767    if raw.is_empty() {
13768        return None;
13769    }
13770    let title = queue::title_from(raw, PR_TITLE_MAX);
13771    let lower = title.to_ascii_lowercase();
13772    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13773        return None;
13774    }
13775    Some(title)
13776}
13777
13778/// How `open_review`'s instruction begins; see [`landing_title`].
13779const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13780
13781/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13782pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13783
13784/// Does this run review work that already existed, rather than implement a
13785/// task? Runs recorded before `reviewed_commits` existed carry only the
13786/// candidate marker.
13787pub(crate) fn is_review_run(state: &RunState) -> bool {
13788    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13789}
13790
13791/// The title of a review-only run: the subject of the oldest commit under
13792/// review. Later commits are usually fixups, and `instruction` is the review
13793/// prompt, which says nothing about the change. GitHub text is English, so a
13794/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13795fn review_title(state: &RunState) -> Option<String> {
13796    english_subject(
13797        state.reviewed_commits.as_ref()?.first()?,
13798        state.config.graph.github_english(),
13799    )
13800}
13801
13802/// `raw` as a pull request title, or `None` when it is blank, not English
13803/// (GitHub text is), or one of magi's own candidate commit subjects.
13804fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13805    let raw = raw.trim();
13806    if raw.is_empty() {
13807        return None;
13808    }
13809    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13810        return None;
13811    }
13812    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13813        return None;
13814    }
13815    let title = queue::title_from(raw, PR_TITLE_MAX);
13816    let lower = title.to_ascii_lowercase();
13817    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13818        return None;
13819    }
13820    Some(title)
13821}
13822
13823/// What a review-only run's branch says about itself, read at the moment the
13824/// pull request is opened.
13825#[derive(Debug, Clone, PartialEq, Eq)]
13826struct BranchFacts {
13827    /// `(subject, body)` of each commit, oldest first.
13828    commits: Vec<(String, String)>,
13829    /// Trimmed `git diff --stat`.
13830    stat: String,
13831}
13832
13833/// Longest diff stat shown: this many file lines plus the summary line.
13834const STAT_FILE_LINES: usize = 25;
13835/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13836const COMMITS_MAX_CHARS: usize = 20_000;
13837
13838/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13839/// say or finds nothing, so the caller falls back to what the run recorded.
13840async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13841    let commits = git::commit_log(repo, base, branch).await.ok()?;
13842    if commits.is_empty() {
13843        return None;
13844    }
13845    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13846    let lines: Vec<&str> = stat.lines().collect();
13847    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13848        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13849        let more = format!(" ... {omitted} more file(s)");
13850        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13851        kept.push(&more);
13852        kept.push(lines[lines.len() - 1]);
13853        kept.join("\n")
13854    } else {
13855        lines.join("\n")
13856    };
13857    Some(BranchFacts { commits, stat })
13858}
13859
13860/// Defang what would break the surrounding markdown: a closing `</details>`
13861/// and a code fence.
13862fn markdown_safe(text: &str) -> String {
13863    text.replace("</details>", "&lt;/details&gt;")
13864        .replace("\x60\x60\x60", "~~~")
13865}
13866
13867fn neutral_title(state: &RunState, winner: char) -> String {
13868    format!(
13869        "chore: land candidate {} of run {}",
13870        winner.to_ascii_uppercase(),
13871        state.id
13872    )
13873}
13874
13875/// Reuse the graph's bounded fixer without starting another graph or driver.
13876/// Copy the working state back even on errors so spent rounds remain visible.
13877pub(crate) async fn repair_landing_gate(
13878    state: &mut RunState,
13879    winner: &Candidate,
13880    outcomes: &[CommandOutcome],
13881) -> Result<GateFix> {
13882    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13883        return Ok(GateFix::Stop);
13884    }
13885    let mut runner = Runner {
13886        roles: state.config.resolve_roles()?,
13887        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13888        state: state.clone(),
13889        pause: Pause::new(),
13890        interrupt: Pause::new(),
13891    };
13892    let result = runner.gate_fix_round(winner, outcomes).await;
13893    *state = runner.state;
13894    result
13895}
13896
13897/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13898/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13899pub(crate) async fn verify_current_head(
13900    state: &mut RunState,
13901    winner: &Candidate,
13902    wait: &crate::repo_lock::WaitPolicy,
13903) -> Result<bool> {
13904    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13905    // Preserve the previous record before replacing it, including on crash recovery.
13906    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13907        state
13908            .verification_history
13909            .push(crate::run::VerificationEvidence {
13910                superseded_by: Some(head.clone()),
13911                archived_at: Some(Timestamp::now()),
13912                fixes_spent: Some(state.gate_fixes.len()),
13913                gate_head: None,
13914                gate_ran: false,
13915                gate: Vec::new(),
13916                e2e: state.head_e2e.take(),
13917            });
13918    }
13919    if let Some(e) = &state.head_e2e
13920        && e.head == head
13921    {
13922        if e.passed {
13923            return Ok(true);
13924        }
13925        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13926            state.status = RunStatus::Blocked;
13927            state.save()?;
13928            return Ok(false);
13929        }
13930    } else if state.reviews.last().is_some_and(|r| {
13931        r.verified_head.as_deref() == Some(head.as_str())
13932            && (r.e2e_status() == E2eStatus::Passed
13933                || (r.e2e_status() == E2eStatus::NotConfigured
13934                    && state.config.verify.e2e.is_empty()))
13935    }) || state
13936        .gate_repair_e2e
13937        .as_ref()
13938        .is_some_and(|e| e.head == head && e.passed)
13939    {
13940        return Ok(true);
13941    }
13942    if let Some(e) = &state.gate_repair_e2e
13943        && e.head == head
13944        && !e.passed
13945        && !e.outcomes.is_empty()
13946        && !verify_inconclusive(&e.outcomes)
13947    {
13948        state.status = RunStatus::Blocked;
13949        state.save()?;
13950        return Ok(false);
13951    }
13952    // Bind the result to the base used by the candidate, not a tracking ref
13953    // that the background fetch can advance independently of verification.
13954    let base_commit = state
13955        .base_sync
13956        .as_ref()
13957        .map(|s| s.tip.clone())
13958        .filter(|tip| !tip.is_empty())
13959        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13960    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13961        head.clone(),
13962        false,
13963        Vec::new(),
13964    ));
13965    state.save()?;
13966    let commands = state.config.verify.e2e.clone();
13967    let shell = state.config.shell();
13968    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13969    let cache_dir = state.config.cache_dir();
13970    let outcomes = if commands.is_empty() {
13971        Vec::new()
13972    } else {
13973        let (outcomes, _) = with_cache_lease(
13974            state,
13975            cache_dir.as_deref(),
13976            "e2e",
13977            "e2e",
13978            &winner.worktree,
13979            &head,
13980            timeout,
13981            "current head e2e",
13982            wait,
13983            |state, budget| async move {
13984                run_e2e_with_retry(
13985                    state,
13986                    &shell,
13987                    &commands,
13988                    &winner.worktree,
13989                    budget,
13990                    "current head e2e",
13991                    None,
13992                )
13993                .await
13994            },
13995        )
13996        .await?;
13997        outcomes
13998    };
13999    let unresolved = verify_inconclusive(&outcomes);
14000    let passed = !unresolved
14001        && outcomes.iter().all(CommandOutcome::ok)
14002        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14003    if !outcomes.is_empty() && !unresolved {
14004        state.record_base_progress(&head);
14005    }
14006    let generation = Some(state.verification_history.len());
14007    let pass = state.passes.last().map(|p| p.index);
14008    let recorded_at = Some(Timestamp::now());
14009    let resumption_generation = state.entry_resumption_generation;
14010    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
14011    record.base_commit = base_commit;
14012    record.generation = generation;
14013    record.pass = pass;
14014    record.recorded_at = recorded_at;
14015    record.resumption_generation = resumption_generation;
14016    if !passed && !unresolved {
14017        let detail = state
14018            .head_e2e
14019            .as_ref()
14020            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14021            .map(|d| format!(" ({d})"))
14022            .unwrap_or_default();
14023        state.status = RunStatus::Blocked;
14024        state.event(
14025            "e2e",
14026            format!("verify.e2e failed on head {head}{detail}; nothing published"),
14027        );
14028        record.recorded_events = Some(state.events.len());
14029    }
14030    state.head_e2e = Some(record);
14031    state.save()?;
14032    Ok(passed)
14033}
14034
14035/// Recheck a repair's e2e requirement across failures, resource deferrals and
14036/// process interruptions. A successful result only applies to its exact SHA.
14037pub(crate) async fn check_gate_repair_e2e(
14038    state: &mut RunState,
14039    winner: &Candidate,
14040    wait: &crate::repo_lock::WaitPolicy,
14041) -> Result<GateFix> {
14042    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
14043        return Ok(GateFix::Retry);
14044    }
14045    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14046    if let Some(record) = &state.gate_repair_e2e
14047        && record.head == head
14048    {
14049        if record.passed {
14050            return Ok(GateFix::Retry);
14051        }
14052        if !record.outcomes.is_empty()
14053            && record.outcomes.iter().all(|o| {
14054                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
14055            })
14056        {
14057            return Ok(GateFix::Stop);
14058        }
14059    }
14060    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
14061        head.clone(),
14062        false,
14063        Vec::new(),
14064    ));
14065    state.save()?;
14066    let commands = state.config.verify.e2e.clone();
14067    let outcomes = if commands.is_empty() {
14068        Vec::new()
14069    } else {
14070        let shell = state.config.shell();
14071        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14072        let cache_dir = state.config.cache_dir();
14073        let (outcomes, _) = with_cache_lease(
14074            state,
14075            cache_dir.as_deref(),
14076            "e2e",
14077            "e2e",
14078            &winner.worktree,
14079            &head,
14080            timeout,
14081            "gate repair e2e",
14082            wait,
14083            |state, budget| async move {
14084                run_e2e_with_retry(
14085                    state,
14086                    &shell,
14087                    &commands,
14088                    &winner.worktree,
14089                    budget,
14090                    "gate repair e2e",
14091                    None,
14092                )
14093                .await
14094            },
14095        )
14096        .await?;
14097        outcomes
14098    };
14099    let deferred = verify_inconclusive(&outcomes);
14100    let passed = outcomes.iter().all(CommandOutcome::ok)
14101        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14102    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
14103    state.save()?;
14104    if deferred {
14105        Ok(GateFix::Defer)
14106    } else if !passed {
14107        let detail = state
14108            .gate_repair_e2e
14109            .as_ref()
14110            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14111            .map(|d| format!(" ({d})"))
14112            .unwrap_or_default();
14113        state.event(
14114            "gate",
14115            format!("verify.e2e failed after gate repair{detail}; nothing published"),
14116        );
14117        Ok(GateFix::Stop)
14118    } else {
14119        Ok(GateFix::Retry)
14120    }
14121}
14122
14123/// Run the same configured gate for a landing head and a fresh graph.
14124pub(crate) async fn run_landing_gate(
14125    state: &mut RunState,
14126    winner: &Candidate,
14127    wait: &crate::repo_lock::WaitPolicy,
14128) -> Result<Vec<CommandOutcome>> {
14129    let shell = state.config.shell();
14130    let gate_commands = state.config.verify.gate.clone();
14131    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
14132    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
14133        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
14134        Vec::new()
14135    } else {
14136        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14137        let cache_dir = state.config.cache_dir();
14138        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14139        let (outcomes, _) = with_cache_lease(
14140            state,
14141            cache_dir.as_deref(),
14142            "gate",
14143            "gate",
14144            &winner.worktree,
14145            &head,
14146            timeout,
14147            "final gate",
14148            wait,
14149            |state, budget| {
14150                let shell = shell.clone();
14151                let gate_commands = gate_commands.clone();
14152                let winner = winner.clone();
14153                async move {
14154                    Runner::run_pre_gate(state, &winner).await;
14155                    // Bind command evidence after mechanical fixes, before commands start.
14156                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
14157                    let (outcomes, timed_out_pids) = run_commands(
14158                        state,
14159                        "gate",
14160                        "gate",
14161                        0,
14162                        &shell,
14163                        &gate_commands,
14164                        &winner.worktree,
14165                        budget,
14166                    )
14167                    .await;
14168                    (outcomes, false, timed_out_pids)
14169                }
14170            },
14171        )
14172        .await?;
14173        outcomes
14174    };
14175    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
14176    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
14177        let mut outcomes = outcomes;
14178        outcomes.push(CommandOutcome {
14179            command: "gate head stability".into(), code: None,
14180            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
14181            duration_ms: 0, resource_blocked: false,
14182            ..Default::default()
14183        });
14184        return Ok(outcomes);
14185    }
14186    if outcomes.is_empty() {
14187        // Nothing configured to check — distinct from every other
14188        // silence in this run's event log, since an empty `gate` alone
14189        // no longer says whether the gate ran at all (see
14190        // `RunState::gate_ran`'s own doc).
14191        state.event("gate", "no gate commands configured; not tested");
14192    }
14193    for o in &outcomes {
14194        state.event(
14195            "gate",
14196            format!(
14197                "`{}` -> {}",
14198                o.command,
14199                if o.ok() {
14200                    "pass".to_owned()
14201                } else {
14202                    format!(
14203                        "FAIL ({:?})\n{}",
14204                        o.code,
14205                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
14206                    )
14207                }
14208            ),
14209        );
14210    }
14211    Ok(outcomes)
14212}
14213
14214/// The pull request title to hand to `land::merge_subject`. A review-only run
14215/// opened by an earlier build titled its pull request with the review prompt;
14216/// that title is dropped (empty, so the fallback applies) rather than landed.
14217/// Any other title, including an operator's rename, passes through untouched,
14218/// and so does every title of a run that implements a task.
14219pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
14220    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
14221        ""
14222    } else {
14223        pr_title
14224    }
14225}
14226
14227/// What the squash subject falls back to when the pull request title is empty
14228/// or candidate-shaped: for a review-only run the derived title, never the
14229/// review prompt held in `instruction`.
14230pub fn landing_subject_source(state: &RunState) -> String {
14231    if is_review_run(state) {
14232        let winner = state.candidates.first().map_or('A', |c| c.label);
14233        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
14234    }
14235    state.instruction.clone()
14236}
14237
14238/// `summary` without its `TITLE:` line, which the pull request title already
14239/// carries.
14240fn summary_without_title(summary: &str) -> String {
14241    let mut lines = summary.trim().lines().peekable();
14242    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
14243        lines.next();
14244    }
14245    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
14246}
14247
14248/// The pull request title and body for the winning candidate.
14249///
14250/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
14251/// the task's own opening line via [`queue::title_from`] when there is none.
14252/// `state.instruction` can open with blank lines (`task_text` only rejects a
14253/// body that is blank *entirely*), which `title_from` skips.
14254///
14255/// Publishing uses an independent description generated from the final diff
14256/// and structured evidence. Internal summaries and reports remain local.
14257/// Non-publishing previews may display the original task and candidate summary.
14258/// The footer retains the run and candidate provenance.
14259#[cfg(test)]
14260fn pr_message(state: &RunState, winner: char) -> PrMessage {
14261    pr_message_with(state, winner, None)
14262}
14263
14264/// [`pr_message`] with what the branch of a review-only run says about itself.
14265/// `facts` is ignored for a run that implements a task.
14266#[cfg(test)]
14267fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
14268    let raw = pr_message_raw(
14269        state,
14270        winner,
14271        facts,
14272        crate::pr_outcome::FinalHead::Unreported,
14273        ChangeNote::NotAsked,
14274    );
14275    let id = crate::scrub::Identity::current();
14276    PrMessage {
14277        title: crate::scrub::scrub(&raw.title, &id),
14278        body: crate::scrub::scrub(&raw.body, &id),
14279    }
14280}
14281
14282/// What the public description may say about the change itself.
14283#[derive(Debug, Clone, Copy)]
14284enum ChangeNote<'a> {
14285    /// A local preview or non-publishing merge mode: no public generation needed.
14286    NotAsked,
14287    /// A summary written from the final diff.
14288    Summary(&'a crate::run::ChangeSummary),
14289    /// A summary was asked for and could not be produced; the text says why.
14290    Unavailable(&'a str),
14291}
14292
14293fn pr_message_raw(
14294    state: &RunState,
14295    winner: char,
14296    facts: Option<&BranchFacts>,
14297    head: crate::pr_outcome::FinalHead<'_>,
14298    change: ChangeNote<'_>,
14299) -> PrMessage {
14300    if !matches!(change, ChangeNote::NotAsked) {
14301        let (title, mut body) = match change {
14302            ChangeNote::Summary(c) => (
14303                c.title.clone(),
14304                format!("## Summary\n\n{}\n\n", c.body.trim()),
14305            ),
14306            ChangeNote::Unavailable(why) => (
14307                neutral_title(state, winner),
14308                format!(
14309                    "## 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"
14310                ),
14311            ),
14312            ChangeNote::NotAsked => unreachable!(),
14313        };
14314        body.push_str(&public_pr_evidence(state, head));
14315        body.push_str(&format!(
14316            "\n---\nmagi:run/{} magi:candidate-{}\n",
14317            state.id,
14318            winner.to_ascii_lowercase()
14319        ));
14320        return PrMessage { title, body };
14321    }
14322    pr_preview(state, winner, facts, head)
14323}
14324
14325/// Append public facts from the run records after every prose generation,
14326/// including posting-gate rewrites. The agent cannot drop this provenance.
14327fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14328    let mut body = crate::pr_outcome::review_rounds(state);
14329    body.push_str(&crate::pr_outcome::final_verification(state, head));
14330    let open = state.last_round_findings();
14331    if !open.is_empty() {
14332        body.push_str("## Open review findings\n\n");
14333        for f in open {
14334            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14335        }
14336        body.push('\n');
14337    }
14338    if let Some(c) = state.change_summary.as_ref()
14339        && head == crate::pr_outcome::FinalHead::At(&c.head)
14340    {
14341        body.push_str(&format!(
14342            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14343            c.base, c.head
14344        ));
14345    }
14346    body
14347}
14348
14349/// Local-only preview of the operator's task and candidate summary.
14350fn pr_preview(
14351    state: &RunState,
14352    winner: char,
14353    facts: Option<&BranchFacts>,
14354    head: crate::pr_outcome::FinalHead<'_>,
14355) -> PrMessage {
14356    let summary = state
14357        .candidates
14358        .iter()
14359        .find(|c| c.label == winner)
14360        .map(|c| c.summary.as_str())
14361        .unwrap_or_default();
14362    // The fallback is the operator's own words and may not be English; GitHub
14363    // text always is, so a non-English task gets a neutral title instead.
14364    let review = is_review_run(state);
14365    let title = if review {
14366        facts
14367            .and_then(|f| {
14368                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14369            })
14370            .or_else(|| review_title(state))
14371            .or_else(|| {
14372                state
14373                    .candidates
14374                    .iter()
14375                    .find(|c| c.label == winner)
14376                    .filter(|c| !c.branch.starts_with("magi/"))
14377                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14378            })
14379            .unwrap_or_else(|| neutral_title(state, winner))
14380    } else {
14381        summary_title(summary).unwrap_or_else(|| {
14382            english_title(
14383                &state.instruction,
14384                PR_TITLE_MAX,
14385                state.config.graph.github_english(),
14386            )
14387            .unwrap_or_else(|| neutral_title(state, winner))
14388        })
14389    };
14390
14391    let mut body = String::new();
14392    let what = summary_without_title(summary);
14393    if !what.is_empty() {
14394        body.push_str("## Summary\n\n");
14395        body.push_str(&what);
14396        body.push_str("\n\n");
14397    }
14398
14399    // Review history uses structured facts across all rounds, never reports.
14400    body.push_str(&crate::pr_outcome::review_rounds(state));
14401    body.push_str(&crate::pr_outcome::final_verification(state, head));
14402    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14403
14404    let open = state.open_findings();
14405    if !open.is_empty() {
14406        body.push_str("## Open review findings\n\n");
14407        for f in &open {
14408            body.push_str(&format!(
14409                "- `{}` [{:?}] {}\n",
14410                f.id, f.severity, "Context retained in local review records."
14411            ));
14412        }
14413        body.push('\n');
14414    }
14415
14416    if let Some(fix) = fix
14417        && !fix.rejected.is_empty()
14418    {
14419        body.push_str("## Declined by the fixer\n\n");
14420        for r in &fix.rejected {
14421            body.push_str(&format!(
14422                "- `{}`: {}\n",
14423                r.id, "Reason retained in local review records."
14424            ));
14425        }
14426        body.push('\n');
14427    }
14428
14429    if review {
14430        // The review prompt is not the task; list what the branch carries.
14431        body.push_str("## Commits under review\n\n");
14432        if let Some(facts) = facts {
14433            let mut left = COMMITS_MAX_CHARS;
14434            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14435                let mut entry = format!("- {}\n", markdown_safe(subject));
14436                for l in markdown_safe(text).lines() {
14437                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14438                }
14439                if left == 0 {
14440                    body.push_str(&format!(
14441                        "- ... {} more commit(s)\n",
14442                        facts.commits.len() - i
14443                    ));
14444                    break;
14445                }
14446                if entry.len() > left {
14447                    // Even the first commit is cut: one huge body must not
14448                    // push the whole description past GitHub's limit.
14449                    let mut end = left;
14450                    while !entry.is_char_boundary(end) {
14451                        end -= 1;
14452                    }
14453                    entry.truncate(end);
14454                    entry.push_str("\n  ... (truncated)\n");
14455                    left = 0;
14456                } else {
14457                    left -= entry.len();
14458                }
14459                body.push_str(&entry);
14460            }
14461            if !facts.stat.trim().is_empty() {
14462                body.push_str(&format!(
14463                    "\n## Diff stat\n\n```\n{}\n```\n",
14464                    markdown_safe(facts.stat.trim())
14465                ));
14466            }
14467        } else {
14468            match &state.reviewed_commits {
14469                Some(subjects) => {
14470                    for s in subjects {
14471                        body.push_str(&format!("- {}\n", s.trim()));
14472                    }
14473                }
14474                None => {
14475                    // An older run kept only the prompt, with the commit list
14476                    // after its first paragraph.
14477                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14478                    body.push_str(rest.trim());
14479                    body.push('\n');
14480                }
14481            }
14482        }
14483    } else {
14484        let task = state.instruction.trim();
14485        let task = if task.is_empty() {
14486            "(empty task)"
14487        } else {
14488            task
14489        };
14490        body.push_str(&format!(
14491            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14492            task.replace("</details>", "&lt;/details&gt;")
14493        ));
14494    }
14495
14496    body.push_str(&format!(
14497        "\n---\nmagi:run/{} magi:candidate-{}\n",
14498        state.id,
14499        winner.to_ascii_lowercase()
14500    ));
14501
14502    PrMessage { title, body }
14503}
14504
14505/// Source imports have already been prepared from structured inputs. Legacy
14506/// inferred references must never instruct a seat to reconstruct those imports.
14507fn seeded_instruction(state: &RunState) -> String {
14508    let mut inputs = Vec::new();
14509    if let Some(start) = &state.sources.start_from {
14510        inputs.push(format!(
14511            "Start from `{}` at `{}` (including ancestry).",
14512            start.token, start.sha
14513        ));
14514    }
14515    for pick in &state.sources.pick_commits {
14516        inputs.push(format!(
14517            "Pick `{}` at `{}` (single commit).",
14518            pick.token, pick.sha
14519        ));
14520    }
14521    if inputs.is_empty() {
14522        state.instruction.clone()
14523    } else {
14524        format!(
14525            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14526            state.instruction,
14527            inputs.join("\n")
14528        )
14529    }
14530}
14531
14532/// Does the winner have no commits ahead of the base it would land on?
14533/// Any failure to find out reads as "not empty": the merge then behaves as it
14534/// always did rather than refusing on a guess.
14535async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14536    let base = &state.base_branch;
14537    let mut against = base.clone();
14538    if mode == MergeMode::Pr {
14539        // A pull request lands on the remote's base, never the local branch
14540        // of the same name: if that cannot be read, "not empty" is the safe
14541        // answer.
14542        let remote = &state.config.merge.remote;
14543        let tracking = format!("{remote}/{base}");
14544        let fetched = git::fetch(repo, remote, base).await;
14545        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14546            against = tracking;
14547        } else {
14548            return false;
14549        }
14550    }
14551    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14552}
14553
14554/// Why nothing was opened for an empty winner, with what the task's own
14555/// references resolved to.
14556fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14557    let mut detail = format!(
14558        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14559         nothing to open a pull request for"
14560    );
14561    detail.push_str(
14562        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14563    );
14564    detail
14565}
14566
14567/// What the `Pr` merge does once it knows whether the branch already has an
14568/// open pull request.
14569#[derive(Debug, PartialEq, Eq)]
14570enum PrPlan {
14571    Create,
14572    Adopt { url: String, title: String },
14573    Stop(String),
14574}
14575
14576/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14577/// a failed lookup -> stop with the real reason. Never guesses.
14578fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14579    match found {
14580        Ok(land::OpenPr::None) => PrPlan::Create,
14581        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14582        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14583            "several open pull requests exist for this branch, not picking one: {}",
14584            urls.join(" ")
14585        )),
14586        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14587    }
14588}
14589
14590/// `gh pr create`, returning the PR url.
14591pub(crate) async fn gh_pr_create(
14592    cwd: &Path,
14593    base: &str,
14594    head: &str,
14595    title: &str,
14596    body: &str,
14597) -> Result<String> {
14598    let out = tokio::process::Command::new("gh")
14599        .args([
14600            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14601        ])
14602        .current_dir(cwd)
14603        .quiet()
14604        .stdin(std::process::Stdio::null())
14605        .output()
14606        .await
14607        .context("spawn gh")?;
14608    if out.status.success() {
14609        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14610    } else {
14611        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14612    }
14613}
14614
14615/// Never force deletion of uncommitted work, including unknown legacy trees.
14616async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14617    match std::fs::symlink_metadata(path) {
14618        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14619            // A previous cleanup may have removed the tree before a branch
14620            // deletion or state save failed. Unregister it if still present.
14621            git::worktree_remove_clean(repo, path).await?;
14622            return Ok(());
14623        }
14624        Err(e) => return Err(e.into()),
14625        Ok(_) => {}
14626    }
14627    if !git::is_clean(path).await? {
14628        bail!(
14629            "worktree has uncommitted work; refusing removal: {}",
14630            path.display()
14631        );
14632    }
14633    if !git::worktree_remove_clean(repo, path).await? {
14634        bail!("worktree removal refused: {}", path.display());
14635    }
14636    Ok(())
14637}
14638
14639/// Read seats return replies, not working-tree changes. Only registered,
14640/// detached seats directly inside this run's root may discard those changes.
14641async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14642    if !crate::retention::read_seat(path) || !path.exists() {
14643        return remove_preserved_worktree(&state.repo, path).await;
14644    }
14645    let owned = std::fs::symlink_metadata(path)?.is_dir()
14646        && path.parent().map(Path::canonicalize).transpose()?
14647            == Some(state.worktree_root().canonicalize()?)
14648        && crate::retention::worktrees(state)
14649            .await?
14650            .contains(&path.canonicalize()?);
14651    let common = crate::repo_lock::common_dir(&state.repo).await?;
14652    if !owned
14653        || common.is_none()
14654        || crate::repo_lock::common_dir(path).await? != common
14655        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14656            .await?
14657            .ok()
14658        || state.candidates.iter().any(|c| c.worktree == path)
14659    {
14660        return remove_preserved_worktree(&state.repo, path).await;
14661    }
14662    let changes = git::status_porcelain(path).await?;
14663    if !git::worktree_remove(&state.repo, path).await? {
14664        bail!(
14665            "read-only seat worktree removal refused: {}",
14666            path.display()
14667        );
14668    }
14669    if !changes.is_empty() {
14670        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14671        let paths: String = paths.chars().take(1024).collect();
14672        state.event(
14673            "fold",
14674            format!(
14675                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14676                path.file_name().unwrap_or_default().to_string_lossy(),
14677                changes.lines().count()
14678            ),
14679        );
14680    }
14681    Ok(())
14682}
14683
14684fn fold_target(
14685    home: &Path,
14686    root: &Path,
14687    path: &Path,
14688    isolated: bool,
14689) -> Option<crate::build_target::FoldTarget> {
14690    if !isolated {
14691        return None;
14692    }
14693    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14694        Ok(target) => target,
14695        Err(error) => {
14696            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14697            None
14698        }
14699    }
14700}
14701
14702fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14703    if let Some(target) = target
14704        && let Err(error) = target.reclaim_orphaned_target(home)
14705    {
14706        tracing::warn!(%error, "isolated target retained after fold");
14707    }
14708}
14709
14710/// Why a fold left a run alone. A typed refusal lets the automatic callers
14711/// (`clean::fold_one`, and through it the idle janitor and the busy-time fold
14712/// turn) say *why* in their receipts; it never changes what is deleted.
14713#[derive(Debug, Clone, PartialEq, Eq)]
14714pub enum FoldRefusal {
14715    /// A lease or lock a live owner holds - the run's execution lease or
14716    /// ownership lock, a source's output lease, a Cargo build, the repository's
14717    /// coordination lease - or a live daemon claim on the run.
14718    Live(String),
14719    /// A resumable status: someone may still continue this run.
14720    Resumable,
14721    /// Finished less than the fold grace period ago.
14722    WithinGrace,
14723    /// An explicitly retained recovery source (`pr_recovery`).
14724    Retained(String),
14725    /// The proof that nothing is lost is not complete: startup or candidate
14726    /// preservation unfinished, or the confirmed-merge source proof (Cargo
14727    /// residue, Git checkpoints, the fetched base) could not be established.
14728    ProofIncomplete(String),
14729    /// The run's record is gone, or is not the record that was locked: it was
14730    /// deleted while the fold waited for its locks. Nothing is touched and
14731    /// nothing is recreated.
14732    RecordGone,
14733    /// The record was readable when the caller first looked and cannot be read
14734    /// once the run's locks are held.
14735    Unreadable(String),
14736}
14737
14738impl std::fmt::Display for FoldRefusal {
14739    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14740        match self {
14741            Self::Live(detail) | Self::ProofIncomplete(detail) => f.write_str(detail),
14742            Self::Resumable => f.write_str("refusing fold: the run is resumable"),
14743            Self::WithinGrace => f.write_str("refusing fold: the run finished within its grace"),
14744            Self::Retained(reason) => write!(f, "refusing fold: {reason}"),
14745            Self::RecordGone => f.write_str("refusing fold: record gone"),
14746            Self::Unreadable(detail) => {
14747                write!(
14748                    f,
14749                    "refusing fold: the run record became unreadable: {detail}"
14750                )
14751            }
14752        }
14753    }
14754}
14755
14756impl std::error::Error for FoldRefusal {}
14757
14758/// Is `error` somebody else holding a lock or lease right now? Only
14759/// contention is: any other failure of a lock call is a real failure.
14760pub(crate) fn held_by_live_owner(error: &anyhow::Error) -> bool {
14761    error.chain().any(|cause| {
14762        cause.is::<crate::retention::OutputsInUse>()
14763            || cause.is::<crate::repo_lock::ResourceBlocked>()
14764            || cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
14765                io.kind() == std::io::ErrorKind::WouldBlock
14766                    || cfg!(windows) && io.raw_os_error() == Some(33)
14767            })
14768    })
14769}
14770
14771/// `error`, marked as [`FoldRefusal::Live`] when it is a held lock.
14772///
14773/// The refusal is *added to* the error as context, never substituted for it:
14774/// callers match the error underneath (`repo_lock::ResourceBlocked` for a
14775/// coordination wait, which several of them treat as a resource stop), and the
14776/// receipt's classification reads the refusal. Both downcasts succeed.
14777fn live_or(error: anyhow::Error) -> anyhow::Error {
14778    if held_by_live_owner(&error) {
14779        error.context(FoldRefusal::Live(
14780            "a lock or lease is held by another owner".into(),
14781        ))
14782    } else {
14783        error
14784    }
14785}
14786
14787/// A failure to take a run's owner lock or execution lease. A run directory
14788/// that is not there (deleted, or never was) is `record gone` and is *not*
14789/// created for the lock's sake; contention is `live`; anything else stays a
14790/// failure with its own text.
14791fn lock_refusal(error: anyhow::Error) -> anyhow::Error {
14792    if is_missing(&error) {
14793        FoldRefusal::RecordGone.into()
14794    } else {
14795        live_or(error)
14796    }
14797}
14798
14799fn is_missing(error: &anyhow::Error) -> bool {
14800    error.chain().any(|cause| {
14801        cause
14802            .downcast_ref::<std::io::Error>()
14803            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
14804    })
14805}
14806
14807fn preservation_refusal() -> anyhow::Error {
14808    FoldRefusal::ProofIncomplete("candidate preservation incomplete; refusing cleanup".into())
14809        .into()
14810}
14811
14812/// The record's own preconditions for the explicit recovery-retention override.
14813fn ensure_overridable(state: &RunState) -> Result<()> {
14814    anyhow::ensure!(
14815        state.status.done() && !state.status.resumable(),
14816        "recovery retention override requires a finished, non-resumable run"
14817    );
14818    Ok(())
14819}
14820
14821/// How a failure of the confirmed-merge source verification reaches the fold's
14822/// caller: somebody else holding a lock is `live`; a lock call that failed for
14823/// another reason is a failure of its own (`failed` in the receipt), not
14824/// evidence that the sources are unproven; anything else - missing or changed
14825/// evidence - is an incomplete proof.
14826fn source_proof_failure(error: anyhow::Error) -> anyhow::Error {
14827    if held_by_live_owner(&error) {
14828        live_or(error)
14829    } else if error
14830        .chain()
14831        .any(|cause| cause.is::<crate::retention::LockCallFailed>())
14832    {
14833        error
14834    } else {
14835        FoldRefusal::ProofIncomplete(format!("{error:#}")).into()
14836    }
14837}
14838
14839/// Which loader a fold uses on the record it reads again under its locks.
14840#[derive(Clone, Copy, PartialEq, Eq)]
14841enum Reload {
14842    /// Housekeeping: the record as saved, whatever schema wrote it
14843    /// ([`RunState::load_tolerant_under`]), exactly as `clean::fold_due` has
14844    /// always read it.
14845    Tolerant,
14846    /// An explicit fold (`magi fold`, the phone's route): the migrating loader
14847    /// the caller itself used ([`RunState::load_under`]), whose derived fields
14848    /// the preservation checks and the saved record then rest on.
14849    Strict,
14850}
14851
14852/// Why a record read under the locks is no longer the one that was locked.
14853fn reload_refusal(error: &anyhow::Error) -> FoldRefusal {
14854    if is_missing(error) {
14855        FoldRefusal::RecordGone
14856    } else {
14857        FoldRefusal::Unreadable(format!("{error:#}"))
14858    }
14859}
14860
14861/// What a test does after a fold's first look at the record and before it
14862/// takes the run's locks: where a deletion or a handover falls.
14863#[cfg(test)]
14864type BeforeLocks = Box<dyn FnOnce(&Path, &str)>;
14865
14866#[cfg(test)]
14867thread_local! {
14868    static BEFORE_LOCKS: std::cell::RefCell<Option<BeforeLocks>> =
14869        const { std::cell::RefCell::new(None) };
14870}
14871
14872/// Tear a run's worktrees and branches down.
14873///
14874/// `home` is where the updated `run.json` is saved (via
14875/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14876/// a housekeeping pass already has its own honest `home` handed to it, and
14877/// falling through to the global here would write back through whichever
14878/// directory some other process or test pinned into that `OnceLock` first,
14879/// not the one the caller actually resolved its `runs` and `state` from.
14880///
14881/// Every deletion decision is made on the record as it is on disk once the
14882/// owner lock and execution lease are held, not on the `state` the caller read
14883/// earlier: see [`fold_run_when`].
14884pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14885    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, false).await
14886}
14887
14888/// [`fold_run`] for the automatic callers, which decide whether the run may be
14889/// folded at all, and whether its winner goes too, from the run record.
14890///
14891/// `decide` is called on the caller's earlier read by the caller itself, and
14892/// again here on the record reloaded after taking the run's owner lock and
14893/// execution lease. A handover (`handover::release`) records `released_to` /
14894/// `released_branches` under that owner lock and removes the old worktree while
14895/// keeping the branch; a fold that acted on a record read before the handover
14896/// would delete the branch already given to the successor and save the stale
14897/// record over the handover. A run no longer eligible under the fresh record
14898/// is left alone and the refusal says why. The reload is tolerant of older
14899/// schemas, as `clean::fold_due` always was; the explicit entry points
14900/// ([`fold_run`], [`fold_run_overriding_recovery_retention`]) use the
14901/// migrating loader.
14902pub async fn fold_run_when(
14903    state: &mut RunState,
14904    home: &Path,
14905    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14906) -> Result<Vec<String>> {
14907    fold_run_with_policy(state, home, decide, Reload::Tolerant, false).await
14908}
14909
14910/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14911pub async fn fold_run_overriding_recovery_retention(
14912    state: &mut RunState,
14913    drop_winner: bool,
14914    home: &Path,
14915) -> Result<Vec<String>> {
14916    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, true).await
14917}
14918
14919async fn fold_run_with_policy(
14920    state: &mut RunState,
14921    home: &Path,
14922    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14923    reload: Reload,
14924    override_recovery_retention: bool,
14925) -> Result<Vec<String>> {
14926    // Cheap refusals on the caller's snapshot, before any lock is taken.
14927    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14928        && !override_recovery_retention
14929    {
14930        return Err(FoldRefusal::Retained(reason).into());
14931    }
14932    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14933        return Err(preservation_refusal());
14934    }
14935    // A fold needs the saved record of the run it locks. Nothing below may
14936    // bring a deleted run's directory back, and a fold is never entitled to
14937    // write a record of its own making: the caller's `state` is only a first
14938    // look, and every decision is made on what is read under the locks.
14939    let id = state.id.clone();
14940    let record = home.join("runs").join(&id).join("run.json");
14941    if !record.try_exists()? {
14942        return Err(FoldRefusal::RecordGone.into());
14943    }
14944    #[cfg(test)]
14945    if let Some(hook) = BEFORE_LOCKS.with(|hook| hook.borrow_mut().take()) {
14946        hook(home, &id);
14947    }
14948    // Serialize ordinary folding with the same starts/resumes as target-only
14949    // eviction. Otherwise a second janitor could remove the whole worktree
14950    // around a live output borrower even though target eviction was fenced.
14951    // Deleting a run record takes these same two locks (`clean::delete_run`).
14952    // The lock files are opened where they are and never created in a
14953    // directory that is not there: a refusal changes nothing, and the lock
14954    // files are never unlinked (`pr_head::owner_lock`).
14955    let _owner = crate::pr_head::owner_lock(home, &id).map_err(lock_refusal)?;
14956    // An override must use current durable ownership, not a pre-lock snapshot.
14957    // Its liveness assessment has to be made before this fold holds the
14958    // execution lease itself (a held lease reads as a live driver); the record
14959    // it is made on is checked for identity like every other, and the final
14960    // record, read once both locks are held, is checked again below.
14961    if override_recovery_retention {
14962        let current =
14963            RunState::load_under(&id, home).map_err(|e| anyhow::Error::from(reload_refusal(&e)))?;
14964        if current.id != id {
14965            return Err(FoldRefusal::RecordGone.into());
14966        }
14967        ensure_overridable(&current)?;
14968        let claimed = crate::daemon::is_working_on_other(home, &id, Timestamp::now())?;
14969        anyhow::ensure!(
14970            current.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14971            "run is live or its ownership is unknown"
14972        );
14973    }
14974    let _driver = crate::driver::maintenance(home, &id).map_err(lock_refusal)?;
14975    // Both locks are held, so no handover, driver claim, deletion or other
14976    // fold can change the record from here on: act on it, not on the earlier
14977    // read. There is no fallback to that read - a record that cannot be read
14978    // again, or is not this run's, ends the fold and touches nothing.
14979    let loaded = match reload {
14980        Reload::Tolerant => RunState::load_tolerant_under(&id, home),
14981        Reload::Strict => RunState::load_under(&id, home),
14982    };
14983    match loaded {
14984        Ok(fresh) if fresh.id == id => *state = fresh,
14985        Ok(_) => return Err(FoldRefusal::RecordGone.into()),
14986        Err(e) => return Err(reload_refusal(&e).into()),
14987    }
14988    if override_recovery_retention {
14989        ensure_overridable(state)?;
14990    }
14991    let drop_winner = decide(state)?;
14992    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14993        return Err(preservation_refusal());
14994    }
14995    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14996    if let Some(reason) = &retention_reason
14997        && !override_recovery_retention
14998    {
14999        return Err(FoldRefusal::Retained(reason.clone()).into());
15000    }
15001    let mut output_guards = Vec::new();
15002    for entry in std::fs::read_dir(state.worktree_root())
15003        .into_iter()
15004        .flatten()
15005        .flatten()
15006    {
15007        if entry.path().join(".git").is_file() {
15008            output_guards
15009                .push(crate::retention::OutputLease::take(&entry.path(), true).map_err(live_or)?);
15010        }
15011    }
15012    let repo = state.repo.clone();
15013    // CLI, Web and automatic cleanup all enter here, independently of
15014    // Runner::fold_losers. Protect deletion and shared config release too.
15015    //
15016    // Lock order. A handover (`handover::release`, a review taking a branch
15017    // over) holds repository coordination and then asks for this run's owner
15018    // lock; this fold already holds the owner lock. An automatic fold must not
15019    // *wait* for coordination here: the handover would wait for the owner lock
15020    // while the fold waited for coordination, and neither bound (the handover's
15021    // short retry, the fold's `timeout_resource_wait`) resolves that inversion
15022    // - the handover fails its startup, which costs the task an attempt. So it
15023    // asks once; when the lease is busy it gives way: everything it holds is
15024    // released on return, nothing was changed or saved, and the run is `live`
15025    // for this pass and judged again on a later one. The explicit callers
15026    // (`magi fold`, the phone's route) were asked for by a person and still
15027    // wait, bounded as before.
15028    let _coordination = if reload == Reload::Tolerant {
15029        match crate::repo_lock::SeatLease::operation_with(
15030            &repo,
15031            state.config.coordination.as_ref(),
15032            &crate::repo_lock::WaitPolicy::immediate(),
15033        )
15034        .await
15035        {
15036            Ok(lease) => lease,
15037            Err(e) => return Err(live_or(e)),
15038        }
15039    } else {
15040        let wait = repository_wait(state, None);
15041        match coordinate_operation(state, &repo, &wait).await {
15042            Ok(lease) => lease,
15043            Err(e) => {
15044                state.save_under(home)?;
15045                return Err(live_or(e));
15046            }
15047        }
15048    };
15049    // Confirmed merges dispose of their owned sources after durable evidence
15050    // capture. Preflight every source before removing anything. A failure of
15051    // this stage is, by what the stage is for, an incomplete proof - unless
15052    // it is only a lock somebody else holds.
15053    let _source_outputs = if retention_reason.is_some()
15054        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
15055    {
15056        match verify_merged_fold_sources(state, drop_winner, home).await {
15057            Ok(held) => held,
15058            Err(e) => return Err(source_proof_failure(e)),
15059        }
15060    } else {
15061        Vec::new()
15062    };
15063    if let Some(reason) = retention_reason {
15064        state.event(
15065            "fold",
15066            format!(
15067                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
15068                state.id
15069            ),
15070        );
15071        state.save_under(home)?;
15072    }
15073    let root = state.worktree_root();
15074    let winner = state.tally.as_ref().map(|t| t.winner);
15075    let mut removed = Vec::new();
15076    let isolated = crate::build_target::isolated(&state.config);
15077
15078    for i in 0..state.candidates.len() {
15079        let c = state.candidates[i].clone();
15080        let is_winner = Some(c.label) == winner;
15081        if is_winner && !drop_winner {
15082            continue;
15083        }
15084        let existed = c.worktree.exists();
15085        let target = fold_target(home, &root, &c.worktree, isolated);
15086        // A vanished directory can still have a Git registration that keeps
15087        // its branch checked out. Remove that registration before the branch.
15088        remove_preserved_worktree(&repo, &c.worktree).await?;
15089        reclaim_fold_target(home, target);
15090        if existed {
15091            removed.push(c.worktree.to_string_lossy().into_owned());
15092        }
15093        // A branch handed to a later run (and its pull request) is not this
15094        // run's to delete.
15095        let handed_over = state.released_branches.contains(&c.branch);
15096        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
15097            if !git::branch_delete(&repo, &c.branch).await? {
15098                bail!("candidate branch removal refused");
15099            }
15100            removed.push(c.branch.clone());
15101        }
15102        state.candidates[i].folded = true;
15103    }
15104
15105    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
15106        let path = name.path();
15107        let keep = !drop_winner
15108            && winner.is_some_and(|w| {
15109                path.file_name()
15110                    .is_some_and(|n| n == format!("cand-{w}").as_str())
15111            });
15112        if keep {
15113            continue;
15114        }
15115        let target = fold_target(home, &root, &path, isolated);
15116        remove_read_seat_worktree(state, &path).await?;
15117        reclaim_fold_target(home, target);
15118        removed.push(path.to_string_lossy().into_owned());
15119    }
15120
15121    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
15122    // judge worktrees, so once the loop above has cleared all of them out,
15123    // the parent is a bare directory nobody else was ever going to remove -
15124    // git only ever managed what was inside it. Left alone, one of these
15125    // accumulates per fully-folded run; the operator's own machine had 74.
15126    // `remove_if_empty` re-checks rather than assuming: a run whose winner
15127    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
15128    // so does anything a run never claimed that happens to share the bay.
15129    remove_if_empty(&root);
15130
15131    if state.enabled_worktree_config && drop_winner {
15132        // A release, not a raw disable: some sibling run in this repository
15133        // may still hold its own reference (see `git::acquire_worktree_config`),
15134        // and only the last release actually turns the setting back off.
15135        git::release_worktree_config(&repo).await.ok();
15136        state.enabled_worktree_config = false;
15137    }
15138    // What this fold itself found, written in the same locked save: nothing
15139    // left to remove and no bay on disk (a failed or erroring check is not
15140    // "gone"). The busy-time fold turn skips such a run only while the bay is
15141    // still confirmed absent; any fold that found work clears the mark.
15142    state.fold_settled_at =
15143        (removed.is_empty() && matches!(root.try_exists(), Ok(false))).then(Timestamp::now);
15144    state.save_under(home)?;
15145    Ok(removed)
15146}
15147
15148async fn verify_merged_fold_sources(
15149    state: &RunState,
15150    drop_winner: bool,
15151    home: &Path,
15152) -> Result<Vec<std::fs::File>> {
15153    let winner = state.tally.as_ref().map(|t| t.winner);
15154    let mut heads = BTreeSet::new();
15155    for candidate in &state.candidates {
15156        if Some(candidate.label) == winner && !drop_winner {
15157            continue;
15158        }
15159        anyhow::ensure!(
15160            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
15161            "candidate recovery source is outside the inventoried run root: {}",
15162            candidate.worktree.display()
15163        );
15164        match std::fs::symlink_metadata(&candidate.worktree) {
15165            Ok(_) => {}
15166            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15167            Err(error) => return Err(error.into()),
15168        }
15169        if !state.released_branches.contains(&candidate.branch)
15170            && git::branch_exists(&state.repo, &candidate.branch).await?
15171        {
15172            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
15173        }
15174    }
15175    let mut cargo_guards = Vec::new();
15176    let entries = match std::fs::read_dir(state.worktree_root()) {
15177        Ok(entries) => Some(entries),
15178        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
15179        Err(error) => return Err(error.into()),
15180    };
15181    for entry in entries.into_iter().flatten() {
15182        let path = entry?.path();
15183        let metadata = std::fs::symlink_metadata(&path)?;
15184        anyhow::ensure!(
15185            metadata.is_dir() && !metadata.file_type().is_symlink(),
15186            "non-directory or symlink recovery source retained: {}",
15187            path.display()
15188        );
15189        if !drop_winner
15190            && winner.is_some_and(|w| {
15191                path.file_name()
15192                    .is_some_and(|name| name == format!("cand-{w}").as_str())
15193            })
15194        {
15195            continue;
15196        }
15197        anyhow::ensure!(
15198            path.join(".git").is_file(),
15199            "unregistered recovery source retained: {}",
15200            path.display()
15201        );
15202        anyhow::ensure!(
15203            git::git(
15204                &path,
15205                &[
15206                    "status",
15207                    "--porcelain",
15208                    "--untracked-files=all",
15209                    "--ignored",
15210                    "--",
15211                    ".",
15212                    ":(exclude)target"
15213                ]
15214            )
15215            .await?
15216            .is_empty(),
15217            "source changes or ignored recovery files retained: {}",
15218            path.display()
15219        );
15220        match std::fs::symlink_metadata(path.join("target")) {
15221            Ok(_) => {
15222                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
15223            }
15224            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15225            Err(error) => return Err(error.into()),
15226        }
15227        for checkpoint in [
15228            "rebase-merge",
15229            "rebase-apply",
15230            "sequencer",
15231            "CHERRY_PICK_HEAD",
15232            "MERGE_HEAD",
15233            "REBASE_HEAD",
15234            "REVERT_HEAD",
15235            "BISECT_LOG",
15236            "AUTO_MERGE",
15237            "MERGE_MSG",
15238        ] {
15239            let location = git::git(
15240                &path,
15241                &[
15242                    "rev-parse",
15243                    "--path-format=absolute",
15244                    "--git-path",
15245                    checkpoint,
15246                ],
15247            )
15248            .await?;
15249            anyhow::ensure!(
15250                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
15251                if e.kind() == std::io::ErrorKind::NotFound),
15252                "Git recovery checkpoint retained: {checkpoint}"
15253            );
15254        }
15255        heads.insert(git::rev_parse(&path, "HEAD").await?);
15256    }
15257    crate::fold_evidence::preserve(state, home, &heads).await?;
15258
15259    Ok(cargo_guards)
15260}
15261
15262/// Remove `dir` if it exists and has nothing in it.
15263///
15264/// Best-effort and silent by design: a directory that is not empty (a run
15265/// whose winner is still parked there, a stray file some other process left)
15266/// is exactly the case this must refuse, and a directory that is already gone
15267/// is not a failure worth reporting either. `std::fs::remove_dir` itself
15268/// already refuses a non-empty directory, so the emptiness check below is
15269/// belt, not suspenders - it is what keeps this from ever attempting the
15270/// removal in the case that matters, rather than trusting `remove_dir`'s
15271/// error path to have no side effects if it ever changed.
15272fn remove_if_empty(dir: &Path) {
15273    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
15274        std::fs::remove_dir(dir).ok();
15275    }
15276}
15277
15278/// Severity of the worst open finding in the last review round, for reporting.
15279pub fn worst_open(state: &RunState) -> Option<Severity> {
15280    state
15281        .reviews
15282        .last()?
15283        .reviews
15284        .iter()
15285        .flat_map(|r| r.findings.iter())
15286        .map(|f| f.severity)
15287        .max()
15288}
15289
15290/// `[worktree] setup` hides its products per worktree, which needs
15291/// `extensions.worktreeConfig`. Taken once per run and released with the run's
15292/// worktrees, like the hook's; every place that runs setup calls this first.
15293async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
15294    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
15295        git::acquire_worktree_config(repo).await?;
15296        state.enabled_worktree_config = true;
15297    }
15298    Ok(())
15299}
15300
15301#[cfg(test)]
15302mod tests {
15303    #[tokio::test]
15304    async fn launcher_base_fetch_requires_remote_success() {
15305        let tmp = tempfile::tempdir().unwrap();
15306        let repo = tmp.path().join("repo");
15307        let remote = tmp.path().join("remote");
15308        std::fs::create_dir(&repo).unwrap();
15309        std::fs::create_dir(&remote).unwrap();
15310        git::git(&remote, &["init", "--bare", "-b", "main"])
15311            .await
15312            .unwrap();
15313        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
15314        git::git(
15315            &repo,
15316            &[
15317                "-c",
15318                "user.name=Fixture",
15319                "-c",
15320                "user.email=fixture@example.invalid",
15321                "commit",
15322                "--allow-empty",
15323                "-m",
15324                "fixture",
15325            ],
15326        )
15327        .await
15328        .unwrap();
15329        git::git(
15330            &repo,
15331            &["remote", "add", "origin", remote.to_str().unwrap()],
15332        )
15333        .await
15334        .unwrap();
15335        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
15336        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15337        assert_eq!(
15338            resolve_base(&repo, "main", "origin", None)
15339                .await
15340                .unwrap()
15341                .commit,
15342            head
15343        );
15344        #[cfg(unix)]
15345        {
15346            let policy: crate::config::Coordination = toml::from_str(
15347                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
15348            ).unwrap();
15349            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
15350            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
15351            let held = crate::repo_lock::SeatLease::operation_with(
15352                &repo,
15353                Some(&policy),
15354                &crate::repo_lock::WaitPolicy::default(),
15355            )
15356            .await
15357            .unwrap();
15358            assert!(held.is_some());
15359            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
15360            tokio::pin!(fetch);
15361            assert!(
15362                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
15363                    .await
15364                    .is_err()
15365            );
15366            assert!(
15367                !repo.join(".git/FETCH_HEAD").exists(),
15368                "no fetch before admission"
15369            );
15370            drop(held);
15371            let fetched = fetch.await.unwrap();
15372            assert_eq!(fetched.commit, head);
15373            assert_eq!(fetched.remote, "origin");
15374            assert_eq!(fetched.branch, "main");
15375        }
15376        // A surviving tracking ref is not successful fetch evidence.
15377        git::git(
15378            &repo,
15379            &[
15380                "remote",
15381                "set-url",
15382                "origin",
15383                tmp.path().join("missing").to_str().unwrap(),
15384            ],
15385        )
15386        .await
15387        .unwrap();
15388        let error = resolve_base(&repo, "main", "origin", None)
15389            .await
15390            .unwrap_err()
15391            .to_string();
15392        assert!(error.contains("cannot read origin/main"));
15393        assert!(error.contains("refusing to branch off"));
15394    }
15395
15396    #[test]
15397    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
15398        let leaked = vec!["chore(deps): update a crate".to_owned()];
15399        let own = "fix(daemon): apply a chosen action";
15400        assert!(should_retitle("", own, &leaked));
15401        assert!(should_retitle(
15402            &format!("{REVIEW_PROMPT_OPENING} `x`"),
15403            own,
15404            &leaked
15405        ));
15406        assert!(should_retitle(
15407            "chore: land candidate A of run 1",
15408            own,
15409            &leaked
15410        ));
15411        assert!(should_retitle(
15412            "magi: candidate A (uncommitted work)",
15413            own,
15414            &leaked
15415        ));
15416        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
15417        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
15418        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
15419    }
15420
15421    #[test]
15422    fn pr_merge_plan_creates_adopts_or_stops() {
15423        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
15424        assert_eq!(
15425            pr_merge_plan(Ok(land::OpenPr::One {
15426                url: "u".into(),
15427                title: "t".into()
15428            })),
15429            PrPlan::Adopt {
15430                url: "u".into(),
15431                title: "t".into()
15432            }
15433        );
15434        let PrPlan::Stop(many) =
15435            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
15436        else {
15437            panic!("many must stop");
15438        };
15439        assert!(many.contains('a') && many.contains('b'));
15440        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
15441            panic!("a failed lookup must stop");
15442        };
15443        assert!(err.contains("bad token"));
15444    }
15445
15446    use super::*;
15447    use crate::run::GateStatus;
15448    use std::collections::BTreeMap;
15449    use std::time::Duration;
15450
15451    fn conductor() -> AgentSpec {
15452        AgentSpec {
15453            id: "conductor".to_owned(),
15454            kind: crate::config::AgentKind::Command,
15455            model: None,
15456            command: vec!["true".to_owned()],
15457            extra_args: Vec::new(),
15458            env: BTreeMap::new(),
15459            prompt_delivery: None,
15460            max_turn_secs: None,
15461        }
15462    }
15463
15464    fn spec(id: &str) -> AgentSpec {
15465        AgentSpec {
15466            id: id.to_owned(),
15467            kind: crate::config::AgentKind::Command,
15468            model: None,
15469            command: vec!["true".to_owned()],
15470            extra_args: Vec::new(),
15471            env: BTreeMap::new(),
15472            prompt_delivery: None,
15473            max_turn_secs: None,
15474        }
15475    }
15476
15477    fn ids(xs: &[&str]) -> BTreeSet<String> {
15478        xs.iter().map(|s| (*s).to_owned()).collect()
15479    }
15480
15481    #[test]
15482    fn pick_successor_skips_an_agent_another_seat_holds() {
15483        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
15484        let roster = [spec("a"), spec("b"), spec("c")];
15485        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15486        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15487    }
15488
15489    #[test]
15490    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
15491        // The other seat started on c but was handed to d; c is free again.
15492        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
15493        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15494        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15495        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
15496        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
15497    }
15498
15499    #[test]
15500    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
15501        let roster = [spec("a"), spec("b")];
15502        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15503        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15504        let carried = ids(&["b"]);
15505        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
15506        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15507    }
15508
15509    #[test]
15510    fn pick_successor_returns_none_without_any_untried_successor() {
15511        let roster = [spec("a"), spec("b")];
15512        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
15513        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
15514        let carried = ids(&["a"]);
15515        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
15516    }
15517
15518    #[test]
15519    fn pick_successor_rescue_avoids_another_seats_occupant() {
15520        // b is a carried failure and free; a is held by the other seat.
15521        let roster = [spec("a"), spec("b"), spec("c")];
15522        let carried = ids(&["b", "c"]);
15523        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
15524        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15525    }
15526
15527    #[test]
15528    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
15529        let roster = [spec("a"), spec("b"), spec("c")];
15530        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
15531        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15532    }
15533
15534    #[test]
15535    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
15536        let roster = [spec("a"), spec("b"), spec("c")];
15537        let failed = ids(&["a", "b", "c"]);
15538        // Rescue looks at the whole roster, once per id, then runs out.
15539        let mut tried = ids(&["b"]);
15540        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15541        assert_eq!(first.id, "a");
15542        tried.insert(first.id.clone());
15543        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15544        assert_eq!(second.id, "c");
15545        tried.insert(second.id.clone());
15546        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
15547    }
15548
15549    #[test]
15550    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
15551        let roster = [spec("a"), spec("b")];
15552        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
15553        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15554    }
15555
15556    #[test]
15557    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15558        let roster = [spec("a"), spec("b"), spec("c")];
15559        let h = SeatHistory {
15560            failed: ids(&["a"]),
15561            last_ok: Some("b".to_owned()),
15562            last_fail: None,
15563        };
15564        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15565        // A last answerer that left the roster, or later failed, is ignored.
15566        let gone = SeatHistory {
15567            last_ok: Some("zzz".to_owned()),
15568            ..h.clone()
15569        };
15570        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15571        let failed = SeatHistory {
15572            failed: ids(&["a", "b"]),
15573            last_ok: Some("b".to_owned()),
15574            last_fail: None,
15575        };
15576        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15577    }
15578
15579    #[test]
15580    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15581        let first = SeatState::new("review-1", "alpha", 7);
15582        let next = handover_seat("review-1", "gamma", 7);
15583        assert_ne!(first.claude_session, next.claude_session);
15584    }
15585
15586    #[test]
15587    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15588        let mut state = state_with_summary("x", "y");
15589        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15590        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15591        assert_ne!(a.claude_session, b.claude_session);
15592    }
15593
15594    #[test]
15595    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15596        let roster = [spec("a"), spec("b")];
15597        let h = SeatHistory {
15598            failed: ids(&["a", "b"]),
15599            ..SeatHistory::default()
15600        };
15601        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15602        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15603        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15604    }
15605
15606    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15607    // fallback loop depends on to terminate: it must walk forward from the
15608    // seat's own position, never restart at the front of the roster, and it
15609    // must never hand back an id already tried, however many times that id
15610    // happens to appear.
15611
15612    #[test]
15613    fn failure_signature_ignores_numbers_and_paths() {
15614        assert_eq!(
15615            failure_signature("exited with Some(2) and no usable output"),
15616            failure_signature("exited with Some(137) and no usable output")
15617        );
15618        assert_eq!(
15619            failure_signature("process exited with no usable output (exit code 2)"),
15620            failure_signature("process exited with no usable output (exit code 137)")
15621        );
15622        for (old, new) in [
15623            (
15624                "exited with Some(2) and no usable output",
15625                "process exited with no usable output (exit code 2)",
15626            ),
15627            (
15628                "exited with None and no usable output",
15629                "process exited with no usable output (exit code unavailable)",
15630            ),
15631        ] {
15632            let previous = FailClass::Other(failure_signature(old));
15633            let current = FailClass::Other(failure_signature(new));
15634            assert_eq!(previous, current, "resumption retains the failure class");
15635            assert!(!should_hand_over(Some(&previous), &current));
15636        }
15637        assert_eq!(
15638            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15639            failure_signature("cannot open /var/x.txt: denied")
15640        );
15641        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15642    }
15643
15644    #[test]
15645    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15646        let other = FailClass::Other("x".into());
15647        assert!(should_hand_over(None, &FailClass::Quota));
15648        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15649        assert!(should_hand_over(
15650            Some(&FailClass::Timeout),
15651            &FailClass::Timeout
15652        ));
15653        assert!(should_hand_over(None, &other));
15654        assert!(!should_hand_over(Some(&other), &other));
15655        assert!(should_hand_over(
15656            Some(&other),
15657            &FailClass::Other("y".into())
15658        ));
15659        // A quota or timeout in between ends the run of identical failures.
15660        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15661        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15662    }
15663
15664    #[test]
15665    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15666        let a = SeatState::new("judge-1", "alpha", 7);
15667        let b = handover_seat("judge-1", "beta", 7);
15668        assert_ne!(a.claude_session, b.claude_session);
15669        assert_eq!(b.turns, 0);
15670    }
15671
15672    #[test]
15673    fn a_timeout_is_classified_apart_from_other_failures() {
15674        assert_eq!(
15675            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15676            Some(FailClass::Timeout)
15677        );
15678        assert!(matches!(
15679            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15680            Some(FailClass::Other(_))
15681        ));
15682    }
15683
15684    #[test]
15685    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15686        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15687        let tried = BTreeSet::from(["beta".to_owned()]);
15688        // beta sits at index 1; the next candidate is gamma, never alpha —
15689        // which is very likely a different candidate slot's own agent.
15690        let next = next_untried_in_roster(&roster, 1, &tried);
15691        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15692    }
15693
15694    #[test]
15695    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15696        let roster = vec![spec("alpha"), spec("beta")];
15697        let tried = BTreeSet::from(["beta".to_owned()]);
15698        // beta is the roster's last entry: nothing follows it, and alpha —
15699        // earlier in the roster, almost certainly a different candidate
15700        // slot's own agent — must not be reached by wrapping back to it.
15701        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15702    }
15703
15704    #[test]
15705    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15706        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15707        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15708        // beta (index 1) and gamma (index 2, the only entry after it) have
15709        // both been tried; alpha (index 0) never has, but it comes before
15710        // beta's own position, so there is nothing further for this seat.
15711        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15712    }
15713
15714    #[test]
15715    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15716        let roster = vec![spec("a"), spec("a"), spec("b")];
15717        let tried = BTreeSet::from(["a".to_owned()]);
15718        let next = next_untried_in_roster(&roster, 0, &tried);
15719        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15720    }
15721
15722    #[test]
15723    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15724        let roster = vec![spec("a"), spec("b")];
15725        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15726        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15727    }
15728
15729    #[test]
15730    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15731        let dir = tempfile::tempdir().unwrap();
15732        let bay = dir.path().join("ffff");
15733
15734        // Not there yet: nothing to do, nothing to panic on.
15735        remove_if_empty(&bay);
15736        assert!(!bay.exists());
15737
15738        // Something still inside - the winner's worktree, or a stray file -
15739        // keeps the directory standing.
15740        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15741        remove_if_empty(&bay);
15742        assert!(bay.exists(), "non-empty directory must survive");
15743
15744        // Once the last entry is gone, so is the directory itself.
15745        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15746        remove_if_empty(&bay);
15747        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15748    }
15749
15750    // `round_is_clean` is the exact decision this task fixed: a round with a
15751    // seat that never answered must not read the same as a round every seat
15752    // actually reviewed. These are deterministic and process-free by design —
15753    // the equivalent end-to-end check (a real reviewer timing out under a
15754    // live graph run) is a genuine race against wall-clock contention, and a
15755    // spawn slow enough to blow even a generous budget under a loaded test
15756    // run must not turn this specific regression check flaky.
15757
15758    #[test]
15759    fn a_full_panel_that_found_nothing_is_clean() {
15760        assert!(round_is_clean(
15761            0,
15762            true,
15763            2,
15764            2,
15765            0,
15766            IncompleteReviewPolicy::Block
15767        ));
15768    }
15769
15770    #[test]
15771    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15772        assert!(!round_is_clean(
15773            0,
15774            true,
15775            1,
15776            2,
15777            0,
15778            IncompleteReviewPolicy::Block
15779        ));
15780    }
15781
15782    #[test]
15783    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15784        assert!(!round_is_clean(
15785            1,
15786            true,
15787            1,
15788            2,
15789            0,
15790            IncompleteReviewPolicy::Warn
15791        ));
15792    }
15793
15794    #[test]
15795    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15796        assert!(round_is_clean(
15797            0,
15798            true,
15799            1,
15800            2,
15801            0,
15802            IncompleteReviewPolicy::Warn
15803        ));
15804    }
15805
15806    #[test]
15807    fn a_full_panel_with_an_open_finding_is_not_clean() {
15808        assert!(!round_is_clean(
15809            1,
15810            true,
15811            2,
15812            2,
15813            0,
15814            IncompleteReviewPolicy::Block
15815        ));
15816    }
15817
15818    #[test]
15819    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15820        assert!(!round_is_clean(
15821            0,
15822            false,
15823            2,
15824            2,
15825            0,
15826            IncompleteReviewPolicy::Block
15827        ));
15828    }
15829
15830    // The stall this task closes: under the default `block` policy, a seat
15831    // missing only because it was rate limited must not force a wait for a
15832    // session limit that will not lift by the next round. `round_is_clean`
15833    // is where that quorum carve-out lives; the review loop around it never
15834    // changes what a reviewer's vote or a finding's severity means.
15835
15836    #[test]
15837    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15838        // 1 of 2 answered, and the one missing was quota'd — the exact
15839        // "review-2 rate limited (quota)" shape from the field report.
15840        assert!(round_is_clean(
15841            0,
15842            true,
15843            1,
15844            2,
15845            1,
15846            IncompleteReviewPolicy::Block
15847        ));
15848    }
15849
15850    #[test]
15851    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15852        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15853        // not a quota loss (`quota_missing` stays 0) — worth another try.
15854        assert!(!round_is_clean(
15855            0,
15856            true,
15857            1,
15858            2,
15859            0,
15860            IncompleteReviewPolicy::Block
15861        ));
15862    }
15863
15864    #[test]
15865    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15866        assert!(!round_is_clean(
15867            1,
15868            true,
15869            1,
15870            2,
15871            1,
15872            IncompleteReviewPolicy::Block
15873        ));
15874        assert!(!round_is_clean(
15875            0,
15876            false,
15877            1,
15878            2,
15879            1,
15880            IncompleteReviewPolicy::Block
15881        ));
15882    }
15883
15884    #[test]
15885    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15886        // Every seat quota'd, nobody answered: there is no panel to decide
15887        // on, so this must fall through to the existing block-and-retry
15888        // fallback rather than call an unreviewed patch clean.
15889        assert!(!round_is_clean(
15890            0,
15891            true,
15892            0,
15893            2,
15894            2,
15895            IncompleteReviewPolicy::Block
15896        ));
15897    }
15898
15899    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15900        CommandOutcome {
15901            command: "test".to_owned(),
15902            code,
15903            output_tail: String::new(),
15904            duration_ms: 0,
15905            resource_blocked,
15906            ..Default::default()
15907        }
15908    }
15909
15910    #[cfg(unix)]
15911    #[tokio::test]
15912    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15913        ask_test_home();
15914        let temp = tempfile::tempdir().unwrap();
15915        let mut runner = runner_at(RunStatus::Gating);
15916        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15917        let commands = vec![
15918            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15919            "touch must-not-run".to_owned(),
15920        ];
15921        let (outcomes, retried, pids) = run_e2e_with_retry(
15922            &mut runner.state,
15923            &shell,
15924            &commands,
15925            temp.path(),
15926            Duration::from_secs(5),
15927            "fixture",
15928            None,
15929        )
15930        .await;
15931        assert_eq!(outcomes.len(), 1);
15932        assert!(outcomes[0].resource_blocked);
15933        assert!(!outcomes[0].build_failed());
15934        assert!(!retried);
15935        assert!(pids.is_empty());
15936        assert!(!temp.path().join("must-not-run").exists());
15937        assert_eq!(
15938            runner.state.resource_block.as_ref().unwrap().kind,
15939            "incremental cache admission"
15940        );
15941    }
15942
15943    #[test]
15944    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15945        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15946        assert!(
15947            !verify_inconclusive(&[outcome(Some(1), false)]),
15948            "an ordinary failure is still evidence about the patch"
15949        );
15950        assert!(verify_inconclusive(&[outcome(None, true)]));
15951        assert!(
15952            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15953            "one inconclusive outcome taints the whole batch"
15954        );
15955        assert!(!verify_inconclusive(&[]));
15956    }
15957
15958    #[tokio::test]
15959    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15960        // Alive for the first two checks, then dead - confirms the loop
15961        // actually re-polls rather than deciding once and sleeping out the
15962        // ceiling regardless.
15963        let calls = std::sync::atomic::AtomicUsize::new(0);
15964        let started = Instant::now();
15965        wait_for_pids_with(
15966            &[123],
15967            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15968            Duration::from_millis(5),
15969            Duration::from_secs(5),
15970        )
15971        .await;
15972        assert!(
15973            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15974            "must keep checking rather than deciding on the first answer"
15975        );
15976        assert!(
15977            started.elapsed() < Duration::from_secs(1),
15978            "must return the moment it is confirmed dead, not wait out the ceiling"
15979        );
15980    }
15981
15982    #[tokio::test]
15983    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15984        let started = Instant::now();
15985        wait_for_pids_with(
15986            &[123],
15987            |_| true, // never reports dead
15988            Duration::from_millis(5),
15989            Duration::from_millis(30),
15990        )
15991        .await;
15992        let elapsed = started.elapsed();
15993        assert!(
15994            elapsed >= Duration::from_millis(30),
15995            "must not give up before its own ceiling: {elapsed:?}"
15996        );
15997        assert!(
15998            elapsed < Duration::from_secs(1),
15999            "must not wait past its own ceiling either: {elapsed:?}"
16000        );
16001    }
16002
16003    #[tokio::test]
16004    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
16005        let started = Instant::now();
16006        wait_for_pids_with(
16007            &[],
16008            |_| true,
16009            Duration::from_secs(5),
16010            Duration::from_secs(5),
16011        )
16012        .await;
16013        assert!(
16014            started.elapsed() < Duration::from_millis(200),
16015            "an empty pid list has nothing to confirm"
16016        );
16017    }
16018
16019    // `review_conclusion` is the exact decision the review hand-off task
16020    // fixed: a round budget spent (or a tree that stopped moving) must not
16021    // collapse into `Blocked` regardless of what verification actually
16022    // said. Deterministic and process-free for the same reason the
16023    // `round_is_clean` family above is.
16024    fn review_round(
16025        clean: bool,
16026        blocking: usize,
16027        answered: usize,
16028        expected: usize,
16029        progressed: bool,
16030        e2e_ok: bool,
16031    ) -> ReviewRound {
16032        ReviewRound {
16033            round: 1,
16034            head: "h".to_owned(),
16035            verified_head: None,
16036            verified_at: None,
16037            reviews: Vec::new(),
16038            e2e: vec![CommandOutcome {
16039                command: "test".to_owned(),
16040                code: Some(if e2e_ok { 0 } else { 1 }),
16041                output_tail: String::new(),
16042                duration_ms: 0,
16043                resource_blocked: false,
16044                ..Default::default()
16045            }],
16046            verify_retried: false,
16047            e2e_deferred: false,
16048            e2e_defer_reason: None,
16049            fix: None,
16050            blocking,
16051            answered,
16052            expected,
16053            clean,
16054            progressed,
16055            vote_split: false,
16056            reconsideration: Vec::new(),
16057            verdict: None,
16058        }
16059    }
16060
16061    #[test]
16062    fn review_conclusion_is_none_when_nothing_has_run() {
16063        assert_eq!(review_conclusion(&[], 3), None);
16064    }
16065
16066    #[test]
16067    fn review_conclusion_is_none_while_rounds_remain() {
16068        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
16069        assert_eq!(review_conclusion(&rounds, 3), None);
16070    }
16071
16072    #[test]
16073    fn review_conclusion_is_gating_once_a_round_is_clean() {
16074        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
16075        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
16076    }
16077
16078    #[test]
16079    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
16080        let rounds = vec![
16081            review_round(false, 1, 2, 2, true, true),
16082            review_round(false, 1, 2, 2, true, true),
16083        ];
16084        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
16085    }
16086
16087    #[test]
16088    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
16089        let rounds = vec![
16090            review_round(false, 1, 2, 2, true, true),
16091            review_round(false, 1, 2, 2, true, false),
16092        ];
16093        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
16094    }
16095
16096    #[test]
16097    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
16098        // Magi never got a command to run against this round's own head — a
16099        // resource-blocked attempt, not a red one — so this must never
16100        // settle on `Blocked` the way a genuine e2e failure would. `None`
16101        // here is what tells `Runner::review_loop` to retry the check
16102        // itself rather than trust this cheap recomputation with a verdict
16103        // it cannot actually produce.
16104        let mut blocked = review_round(false, 1, 2, 2, true, false);
16105        blocked.e2e[0].resource_blocked = true;
16106        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
16107        assert_eq!(review_conclusion(&rounds, 2), None);
16108    }
16109
16110    #[test]
16111    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
16112        // Missing input, not a verified tree — never a hand-off candidate.
16113        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
16114        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
16115    }
16116
16117    #[test]
16118    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
16119        let rounds = vec![
16120            review_round(false, 1, 2, 2, false, true),
16121            review_round(false, 1, 2, 2, false, true),
16122        ];
16123        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
16124    }
16125
16126    fn secs(n: u64) -> Duration {
16127        Duration::from_secs(n)
16128    }
16129
16130    /// A throwaway repo with one commit on `main`, for tests that need `merge`
16131    /// to make real (and, if it runs at all, real*ly fail*) git calls.
16132    #[tokio::test]
16133    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
16134        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
16135        if std::env::var_os(CHILD).is_none() {
16136            // Other tests reconcile every run in the process-global home,
16137            // briefly taking owner locks. This ancestry test expects an idle
16138            // predecessor, so give it its own process and pinned test home.
16139            let output = std::process::Command::new(std::env::current_exe().unwrap())
16140                .args([
16141                    "--exact",
16142                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
16143                    "--nocapture",
16144                ])
16145                .env(CHILD, "1")
16146                .env_remove("MAGI_WORKER_HOME")
16147                .env_remove("MAGI_WORKER_ID")
16148                .output()
16149                .unwrap();
16150            assert!(
16151                output.status.success()
16152                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
16153                "{}\n{}",
16154                String::from_utf8_lossy(&output.stdout),
16155                String::from_utf8_lossy(&output.stderr)
16156            );
16157            return;
16158        }
16159        ask_test_home();
16160        let tmp = tempfile::tempdir().unwrap();
16161        let repo = tmp.path().join("repo");
16162        std::fs::create_dir_all(&repo).unwrap();
16163        init_repo(&repo);
16164        let g = |args: &[&str]| {
16165            let out = std::process::Command::new("git")
16166                .args(args)
16167                .current_dir(&repo)
16168                .quiet()
16169                .output()
16170                .unwrap();
16171            assert!(
16172                out.status.success(),
16173                "{}",
16174                String::from_utf8_lossy(&out.stderr)
16175            );
16176        };
16177        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16178        g(&["checkout", "-b", "historical"]);
16179        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
16180        g(&["add", "."]);
16181        g(&["commit", "-m", "old alternative"]);
16182        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
16183        g(&["checkout", "-b", "magi/task-selected", &base]);
16184        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
16185        g(&["add", "."]);
16186        g(&["commit", "-m", "measurement infrastructure"]);
16187        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
16188        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
16189        g(&["add", "."]);
16190        g(&["commit", "-m", "dependent implementation"]);
16191        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
16192        g(&["checkout", "main"]);
16193        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
16194        g(&["add", "."]);
16195        g(&["commit", "-m", "unrelated base change"]);
16196        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
16197        let origin = tmp.path().join("origin.git");
16198        g(&[
16199            "clone",
16200            "--bare",
16201            repo.to_str().unwrap(),
16202            origin.to_str().unwrap(),
16203        ]);
16204        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
16205        g(&["fetch", "origin"]);
16206        let selection = crate::pr_recovery::Selection {
16207            url: "https://example.test/project/pull/1".into(),
16208            branch: "magi/task-selected".into(),
16209            head: head.clone(),
16210            source_head: None,
16211            source_run: None,
16212            source_proof: None,
16213            disposition: Some(crate::pr_recovery::Disposition::Review),
16214            instruction: "preserve measured behavior".into(),
16215            approved_at: jiff::Timestamp::now(),
16216        };
16217        let mut template = runner_at(RunStatus::Reviewing);
16218        template.state.repo = repo.clone();
16219        template.state.base_commit = current.clone();
16220        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16221        template.state.origin = Some(crate::run::Origin::queue("selected"));
16222        template.state.pr_head = Some(selection.branch.clone());
16223        template.state.pr_recovery = Some(selection.clone());
16224        let mut runner =
16225            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
16226                .await
16227                .unwrap();
16228        let wt = runner.state.winner().unwrap().worktree.clone();
16229        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
16230        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
16231        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
16232        assert!(runner.state.seeds.is_empty());
16233        assert_eq!(runner.state.instruction, "preserve measured behavior");
16234        runner.sync_to_base().await.unwrap();
16235        assert_eq!(
16236            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
16237            "prerequisite"
16238        );
16239        assert_eq!(
16240            std::fs::read_to_string(wt.join("implementation")).unwrap(),
16241            "measured implementation"
16242        );
16243        assert_eq!(
16244            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
16245            "current main change"
16246        );
16247        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16248        assert_eq!(
16249            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16250            head
16251        );
16252
16253        // A failed selected-source setup stays inspectable, never resumable as a new competition.
16254        let mut partial = runner_at(RunStatus::Reviewing);
16255        partial.state.repo = repo.clone();
16256        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
16257        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
16258            run: Some("exit 1".into()),
16259            ..Default::default()
16260        }];
16261        let selection = runner.state.pr_recovery.clone().unwrap();
16262        partial.state.pr_recovery = Some(selection.clone());
16263        partial.state.pr_head = Some(selection.branch.clone());
16264        partial.state.origin = Some(crate::run::Origin::queue("selected"));
16265        let id = partial.state.id.clone();
16266        let error = match Runner::open_selected(
16267            &repo,
16268            partial.state,
16269            partial.roles,
16270            1,
16271            runner.state.base_commit.clone(),
16272            selection,
16273        )
16274        .await
16275        {
16276            Ok(_) => panic!("setup must fail"),
16277            Err(e) => e,
16278        };
16279        assert_eq!(
16280            error
16281                .downcast_ref::<crate::run::StartupFailure>()
16282                .unwrap()
16283                .run,
16284            id
16285        );
16286        let failed = RunState::load(&id).unwrap();
16287        assert_eq!(failed.status, RunStatus::Failed);
16288        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
16289        assert!(Runner::resume(&id).is_err());
16290        runner.state.status = RunStatus::Ready;
16291        runner.state.driver_exited = true;
16292        runner.state.save().unwrap();
16293        let mut retry = runner_at(RunStatus::Reviewing);
16294        retry.state.repo = repo.clone();
16295        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
16296        let mut reselected = runner.state.pr_recovery.clone().unwrap();
16297        reselected.approved_at = jiff::Timestamp::now();
16298        retry.state.origin = Some(crate::run::Origin::queue("selected"));
16299        retry.state.pr_head = Some(reselected.branch.clone());
16300        retry.state.pr_recovery = Some(reselected.clone());
16301        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
16302            .await
16303            .unwrap();
16304        let restarted = Runner::open_selected(
16305            &repo,
16306            retry.state,
16307            retry.roles,
16308            1,
16309            runner.state.base_commit.clone(),
16310            reselected,
16311        )
16312        .await
16313        .unwrap();
16314        assert_eq!(
16315            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
16316                .await
16317                .unwrap(),
16318            head
16319        );
16320        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16321        assert_eq!(
16322            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16323            head
16324        );
16325    }
16326
16327    #[tokio::test]
16328    #[cfg(unix)]
16329    async fn fallback_and_interrupted_restoration_require_coordination() {
16330        use std::os::fd::AsRawFd as _;
16331        ask_test_home();
16332        let tmp = tempfile::tempdir().unwrap();
16333        let mut runner = registered_runner(tmp.path()).await;
16334        runner.state.config.graph.timeout_resource_wait = 1;
16335        let winner = runner.state.candidates[0].clone();
16336        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16337        let leftover = winner.worktree.join("leftover");
16338        std::fs::write(&leftover, "untrusted edits").unwrap();
16339        let next = tmp.path().join("next-fixer");
16340        let mut failed = spec("first");
16341        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
16342        let mut successor = spec("second");
16343        successor.command = vec![
16344            "sh".into(),
16345            "-c".into(),
16346            format!("touch '{}'; echo done", next.display()),
16347        ];
16348        let attempts = vec![
16349            (failed.clone(), "first".into()),
16350            (successor.clone(), "second".into()),
16351        ];
16352        let lock_path = runner.state.repo.join(".git/updater.lock");
16353        let external = std::fs::File::create(&lock_path).unwrap();
16354        assert_eq!(
16355            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16356            0
16357        );
16358        let artifacts = tmp.path().join("artifacts");
16359        let build = |spec, seat| SeatJob {
16360            spec,
16361            seat,
16362            cwd: winner.worktree.clone(),
16363            prompt: "fixture".into(),
16364            timeout: Duration::from_secs(10),
16365            allow_write: true,
16366            sessions: false,
16367            artifacts: artifacts.clone(),
16368            stem: "fix".into(),
16369            handover: None,
16370        };
16371        let (_, _, out) = runner
16372            .ask_fixer_among(
16373                attempts.clone(),
16374                "graft",
16375                None,
16376                Some((&winner.worktree, &head)),
16377                build,
16378            )
16379            .await;
16380        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
16381        assert!(leftover.exists(), "contention must prevent clean");
16382        assert!(!next.exists());
16383        assert!(runner.state.handovers.is_empty());
16384        // Early interrupted-repair rollback uses the same protected route.
16385        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16386            from_run: "earlier".into(),
16387            generation: 1,
16388            mode: crate::recovery::Mode::VerifyRepair,
16389            reasons: Vec::new(),
16390            reviewed_head: None,
16391            rounds: Vec::new(),
16392            open_findings: Vec::new(),
16393            evidence: None,
16394            criteria_inherited: true,
16395            repair: crate::recovery::Repair::Started {
16396                before: head.clone(),
16397            },
16398        });
16399        assert!(
16400            runner
16401                .recovery_repair(&winner)
16402                .await
16403                .unwrap_err()
16404                .is::<crate::repo_lock::ResourceBlocked>()
16405        );
16406        assert!(matches!(
16407            runner.state.recovery.as_ref().unwrap().repair,
16408            crate::recovery::Repair::Started { .. }
16409        ));
16410        assert!(leftover.exists());
16411        drop(external);
16412        runner.recovery_repair(&winner).await.unwrap();
16413        assert!(!leftover.exists());
16414        assert!(matches!(
16415            runner.state.recovery.as_ref().unwrap().repair,
16416            crate::recovery::Repair::Done { .. }
16417        ));
16418        // A hard lock-open failure also leaves HEAD and untracked work intact.
16419        std::fs::remove_file(&lock_path).unwrap();
16420        std::fs::create_dir(&lock_path).unwrap();
16421        std::fs::write(&leftover, "untrusted edits").unwrap();
16422        let (_, _, out) = runner
16423            .ask_fixer_among(
16424                attempts,
16425                "graft",
16426                None,
16427                Some((&winner.worktree, &head)),
16428                build,
16429            )
16430            .await;
16431        assert!(matches!(out, AgentOutcome::Failed(_)));
16432        assert!(leftover.exists());
16433        assert!(!next.exists());
16434        assert_eq!(
16435            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16436            head
16437        );
16438    }
16439
16440    #[cfg(unix)]
16441    async fn registered_runner(root: &Path) -> Runner {
16442        repository_runner(root, crate::config::test_coordination()).await
16443    }
16444
16445    async fn repository_runner(
16446        root: &Path,
16447        coordination: Option<crate::config::Coordination>,
16448    ) -> Runner {
16449        ask_test_home();
16450        let repo = root.join("repo");
16451        std::fs::create_dir_all(&repo).unwrap();
16452        init_repo(&repo);
16453        if coordination.is_some() {
16454            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16455        }
16456        let mut runner = runner_at(RunStatus::Prep);
16457        runner.state.repo = repo.clone();
16458        runner.state.config.coordination = coordination;
16459        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16460        runner.state.config.graph.worktree_root = Some(root.join("wt"));
16461        runner.state.config.graph.advise = false;
16462        runner.roles.implementers = vec![spec("implement")];
16463        runner.roles.judges = vec![spec("judge")];
16464        runner.prep().await.unwrap();
16465        runner
16466    }
16467
16468    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
16469
16470    #[tokio::test]
16471    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
16472        let tmp = tempfile::tempdir().unwrap();
16473        let mut runner = repository_runner(tmp.path(), None).await;
16474        let prompts = runner.state.config.prompts.clone();
16475        let run = runner.state.id.clone();
16476        let ctx = WaveCtx {
16477            carry_seats: false,
16478            pauses: None,
16479            run: &run,
16480            node: "advise",
16481            prompts: &prompts,
16482            cache: None,
16483            round: None,
16484        };
16485        let jobs: Vec<_> = ["alpha", "beta"]
16486            .into_iter()
16487            .map(|id| SeatJob {
16488                spec: scripted(id, AUTH_OUTAGE),
16489                seat: SeatState::new(id, id, 7),
16490                prompt: "propose".into(),
16491                cwd: runner.state.candidates[0].worktree.clone(),
16492                timeout: Duration::from_secs(10),
16493                allow_write: false,
16494                sessions: false,
16495                artifacts: agent::artifacts_dir(&runner.state.dir()),
16496                stem: id.into(),
16497                handover: None,
16498            })
16499            .collect();
16500        let mut losses = Vec::new();
16501        let results = ask_wave_with(
16502            jobs.clone(),
16503            runner.sem.clone(),
16504            2,
16505            &[],
16506            &ctx,
16507            &mut losses,
16508            &mut runner.state,
16509            &|_: &str| Ok(()),
16510        )
16511        .await;
16512        assert!(
16513            results
16514                .iter()
16515                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
16516        );
16517        assert_eq!(runner.state.quota.len(), 2);
16518        assert!(
16519            runner
16520                .state
16521                .quota
16522                .iter()
16523                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
16524        );
16525        assert!(!runner.state.advise_attempted);
16526        runner.stop_for_resource().unwrap();
16527        assert_eq!(runner.state.status, RunStatus::Blocked);
16528        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
16529        assert_eq!(
16530            runner.state.resource_block.as_ref().unwrap().kind,
16531            "agent authentication"
16532        );
16533        // A machine loss followed by an ordinary failure is not evidence
16534        // that the whole node was unavailable, and must not earn a refund.
16535        runner.state.resource_block = None;
16536        runner.state.quota.clear();
16537        let mut mixed = jobs;
16538        mixed[1].spec.command = vec!["false".into()];
16539        let results = ask_wave_with(
16540            mixed,
16541            runner.sem.clone(),
16542            0,
16543            &[],
16544            &ctx,
16545            &mut losses,
16546            &mut runner.state,
16547            &|_: &str| Ok(()),
16548        )
16549        .await;
16550        assert!(results.iter().all(|(_, res, _)| res.is_err()));
16551        assert!(runner.state.resource_block.is_none());
16552        assert_eq!(losses.len(), 1);
16553    }
16554
16555    #[tokio::test]
16556    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16557        let tmp = tempfile::tempdir().unwrap();
16558        let mut runner = repository_runner(tmp.path(), None).await;
16559        let implementer = scripted("implement", AUTH_OUTAGE);
16560        runner.roles.implementers = vec![implementer.clone()];
16561        runner.state.config.agents = vec![implementer];
16562        runner.implement().await.unwrap();
16563        assert_eq!(runner.state.status, RunStatus::Blocked);
16564        assert_eq!(runner.state.quota.len(), 1);
16565        assert_eq!(
16566            runner.state.quota[0].cause,
16567            agent::QuotaCause::Authentication
16568        );
16569        let candidate = &runner.state.candidates[0];
16570        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16571        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16572    }
16573
16574    #[tokio::test]
16575    #[cfg(unix)]
16576    async fn parked_implementer_persists_completed_work() {
16577        for registered in [false, true] {
16578            let tmp = tempfile::tempdir().unwrap();
16579            let mut runner = registered_runner(tmp.path()).await;
16580            if !registered {
16581                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16582            }
16583            let marker = tmp.path().join("started");
16584            let release = tmp.path().join("release");
16585            let mut implementer = spec("implement");
16586            implementer.command = vec![
16587                "sh".into(),
16588                "-c".into(),
16589                format!(
16590                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16591                    marker.display(),
16592                    release.display()
16593                ),
16594            ];
16595            runner.roles.implementers = vec![implementer.clone()];
16596            runner.state.config.agents = vec![implementer];
16597            let pause = runner.pause.clone();
16598            let (result, ()) = tokio::join!(runner.implement(), async {
16599                tokio::time::timeout(Duration::from_secs(10), async {
16600                    while !marker.exists() {
16601                        tokio::time::sleep(Duration::from_millis(10)).await;
16602                    }
16603                })
16604                .await
16605                .unwrap();
16606                pause.park();
16607                std::fs::write(&release, "go").unwrap();
16608            });
16609            result.unwrap();
16610            let candidate = &runner.state.candidates[0];
16611            assert!(candidate.commits > 0, "{candidate:?}");
16612            assert!(candidate.summary.contains("saved-result"));
16613            assert_eq!(candidate.files, 1);
16614            let before = candidate.commits;
16615            runner.implement().await.unwrap();
16616            assert_eq!(runner.state.candidates[0].commits, before);
16617        }
16618    }
16619
16620    #[tokio::test]
16621    #[cfg(unix)]
16622    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16623        let tmp = tempfile::tempdir().unwrap();
16624        let mut runner = registered_runner(tmp.path()).await;
16625        let winner = runner.state.candidates[0].clone();
16626        let cache = tmp.path().join("cache");
16627        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16628        runner.state.config.graph.timeout_resource_wait = 0;
16629        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16630        let crate::cache::AcquireOutcome::Acquired(held) =
16631            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16632        else {
16633            panic!("cache must be free")
16634        };
16635        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16636            from_run: "earlier".into(),
16637            generation: 1,
16638            mode: crate::recovery::Mode::VerifyRepair,
16639            reasons: Vec::new(),
16640            reviewed_head: None,
16641            rounds: Vec::new(),
16642            open_findings: Vec::new(),
16643            evidence: None,
16644            criteria_inherited: true,
16645            repair: crate::recovery::Repair::NotStarted,
16646        });
16647        runner.recovery_repair(&winner).await.unwrap();
16648        assert!(matches!(
16649            runner.state.recovery.as_ref().unwrap().repair,
16650            crate::recovery::Repair::WaitingForRestore { .. }
16651        ));
16652        drop(held);
16653        runner.state.resource_block = None;
16654        runner.state.config.graph.timeout_resource_wait = 1;
16655        runner.recovery_repair(&winner).await.unwrap();
16656        assert!(matches!(
16657            runner.state.recovery.as_ref().unwrap().repair,
16658            crate::recovery::Repair::Done { .. }
16659        ));
16660        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16661    }
16662
16663    #[tokio::test]
16664    #[cfg(unix)]
16665    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16666        use std::os::fd::AsRawFd as _;
16667        for graft in [false, true] {
16668            let tmp = tempfile::tempdir().unwrap();
16669            let mut runner = registered_runner(tmp.path()).await;
16670            runner.state.config.graph.timeout_resource_wait = 1;
16671            let winner = runner.state.candidates[0].clone();
16672            let marker = tmp.path().join("fixer-started");
16673            let mut fixer = spec("fixer");
16674            fixer.command = vec![
16675                "sh".into(),
16676                "-c".into(),
16677                format!("echo started >> '{}'; echo done", marker.display()),
16678            ];
16679            runner.roles.fixer = Some(vec![fixer]);
16680            if graft {
16681                let mut loser = winner.clone();
16682                loser.label = 'B';
16683                loser.index = 1;
16684                runner.state.candidates.push(loser);
16685                runner.state.config.graph.graft_runner_up = true;
16686                runner.state.tally = Some(Tally {
16687                    first_choice: BTreeMap::new(),
16688                    borda: BTreeMap::new(),
16689                    winner: winner.label,
16690                    rankings: 1,
16691                    unanimous_initial: true,
16692                    deliberated: false,
16693                    changed_votes: 0,
16694                    unanimous_final: true,
16695                    tie_break: None,
16696                    judges: 1,
16697                    present: 1,
16698                    quorum: 1,
16699                    met_quorum: true,
16700                    uncontested: None,
16701                });
16702                runner.state.judgements.push(crate::run::Judgement {
16703                    judge: 1,
16704                    seat: "judge-1".into(),
16705                    agent: "judge".into(),
16706                    ranking: vec![winner.label, 'B'],
16707                    reasons: BTreeMap::new(),
16708                    confidence: None,
16709                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16710                    order: vec![0, 1],
16711                    failed: None,
16712                    duration_ms: 0,
16713                });
16714            } else {
16715                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16716                    from_run: "earlier".into(),
16717                    generation: 1,
16718                    mode: crate::recovery::Mode::VerifyRepair,
16719                    reasons: Vec::new(),
16720                    reviewed_head: None,
16721                    rounds: Vec::new(),
16722                    open_findings: Vec::new(),
16723                    evidence: None,
16724                    criteria_inherited: true,
16725                    repair: crate::recovery::Repair::NotStarted,
16726                });
16727            }
16728            let reader = crate::repo_lock::SeatLease::for_checkout(
16729                &winner.worktree,
16730                false,
16731                crate::config::test_coordination().as_ref(),
16732            )
16733            .await
16734            .unwrap();
16735            let pause = runner.pause.clone();
16736            let (result, ()) = tokio::join!(
16737                async {
16738                    if graft {
16739                        runner.graft().await
16740                    } else {
16741                        runner.recovery_repair(&winner).await
16742                    }
16743                },
16744                async {
16745                    tokio::time::sleep(Duration::from_millis(100)).await;
16746                    pause.park();
16747                }
16748            );
16749            result.unwrap();
16750            assert!(!marker.exists(), "a blocked seat must not spawn");
16751            // Exercise the persisted state, as a binary replacement/resume does.
16752            runner.state = RunState::load(&runner.state.id).unwrap();
16753            if graft {
16754                assert_eq!(
16755                    runner.state.graft.as_ref().unwrap().outcome,
16756                    GraftOutcome::WaitingForRestore
16757                );
16758            } else {
16759                assert!(matches!(
16760                    runner.state.recovery.as_ref().unwrap().repair,
16761                    crate::recovery::Repair::WaitingForRestore { .. }
16762                ));
16763            }
16764            drop(reader);
16765            runner.pause = Pause::new();
16766            runner.state.resource_block = None;
16767            // Deferred restoration must still respect an external lock owner.
16768            let external =
16769                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16770            assert_eq!(
16771                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16772                0
16773            );
16774            let leftover = winner.worktree.join("leftover");
16775            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16776            let result = if graft {
16777                runner.graft().await
16778            } else {
16779                runner.recovery_repair(&winner).await
16780            };
16781            assert!(
16782                result
16783                    .unwrap_err()
16784                    .is::<crate::repo_lock::ResourceBlocked>()
16785            );
16786            assert!(leftover.exists());
16787            assert!(!marker.exists());
16788            drop(external);
16789            runner.state.resource_block = None;
16790            let result = if graft {
16791                runner.graft().await
16792            } else {
16793                runner.recovery_repair(&winner).await
16794            };
16795            result.unwrap();
16796            assert!(!leftover.exists(), "restore must precede retry");
16797            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16798            if graft {
16799                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16800            } else {
16801                assert!(matches!(
16802                    runner.state.recovery.as_ref().unwrap().repair,
16803                    crate::recovery::Repair::Done { .. }
16804                ));
16805            }
16806        }
16807    }
16808
16809    #[tokio::test]
16810    #[cfg(unix)]
16811    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16812        use std::os::fd::AsRawFd as _;
16813        let tmp = tempfile::tempdir().unwrap();
16814        let mut runner = registered_runner(tmp.path()).await;
16815        runner.state.config.graph.timeout_resource_wait = 1;
16816        let winner = runner.state.candidates[0].clone();
16817        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16818        runner.state.tally = Some(Tally {
16819            first_choice: BTreeMap::new(),
16820            borda: BTreeMap::new(),
16821            winner: winner.label,
16822            rankings: 0,
16823            unanimous_initial: false,
16824            deliberated: false,
16825            changed_votes: 0,
16826            unanimous_final: false,
16827            tie_break: None,
16828            judges: 0,
16829            present: 0,
16830            quorum: 0,
16831            met_quorum: true,
16832            uncontested: Some("fixture".into()),
16833        });
16834        runner.state.graft = Some(GraftRecord {
16835            pre: pre.clone(),
16836            post: None,
16837            lines: None,
16838            limit: None,
16839            agent: None,
16840            outcome: GraftOutcome::Running,
16841            requested: Vec::new(),
16842            adoption: None,
16843            adoption_error: None,
16844        });
16845        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16846        git::commit_all(&winner.worktree, "unfinished graft")
16847            .await
16848            .unwrap();
16849        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16850        let leftover = winner.worktree.join("leftover");
16851        std::fs::write(&leftover, "untrusted edits").unwrap();
16852        let path = runner.state.repo.join(".git/updater.lock");
16853        let external = std::fs::File::create(&path).unwrap();
16854        assert_eq!(
16855            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16856            0
16857        );
16858        assert!(
16859            runner
16860                .graft()
16861                .await
16862                .unwrap_err()
16863                .is::<crate::repo_lock::ResourceBlocked>()
16864        );
16865        assert!(matches!(
16866            runner.state.graft.as_ref().unwrap().outcome,
16867            GraftOutcome::Running
16868        ));
16869        assert_eq!(
16870            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16871            unfinished
16872        );
16873        assert!(leftover.exists());
16874        drop(external);
16875        std::fs::remove_file(&path).unwrap();
16876        std::fs::create_dir(&path).unwrap();
16877        assert!(runner.graft().await.is_err());
16878        assert!(matches!(
16879            runner.state.graft.as_ref().unwrap().outcome,
16880            GraftOutcome::Running
16881        ));
16882        assert_eq!(
16883            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16884            unfinished
16885        );
16886        assert!(leftover.exists());
16887        std::fs::remove_dir(&path).unwrap();
16888        runner.graft().await.unwrap();
16889        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16890        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16891        assert!(!leftover.exists());
16892    }
16893
16894    #[tokio::test]
16895    #[cfg(unix)]
16896    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16897        use std::os::fd::AsRawFd as _;
16898        let tmp = tempfile::tempdir().unwrap();
16899        let mut runner = registered_runner(tmp.path()).await;
16900        runner.state.prep_complete = Some(false);
16901        runner.state.config.graph.timeout_resource_wait = 1;
16902        runner.state.save().unwrap();
16903        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16904        assert_eq!(
16905            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16906            0
16907        );
16908        runner.execute().await.unwrap();
16909        let disk = RunState::load(&runner.state.id).unwrap();
16910        assert!(disk.driver_exited);
16911        assert_eq!(disk.driver_pid, None);
16912        assert_eq!(runner.state.status, RunStatus::Blocked);
16913        assert_eq!(
16914            runner.state.resource_block.as_ref().unwrap().kind,
16915            "repository coordination"
16916        );
16917        assert!(runner.state.prep_failure.is_none());
16918        assert!(runner.state.seats.is_empty());
16919        runner.pause.park();
16920        // Include headroom for Git subprocesses under parallel test load;
16921        // the repository contention deadline itself remains one second.
16922        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16923            .await
16924            .unwrap()
16925            .unwrap();
16926        assert!(runner.state.parked);
16927        assert!(runner.state.prep_failure.is_none());
16928        let disk = RunState::load(&runner.state.id).unwrap();
16929        assert!(disk.driver_exited);
16930        assert_eq!(disk.driver_pid, None);
16931    }
16932
16933    #[tokio::test]
16934    #[cfg(unix)]
16935    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16936        use std::os::fd::AsRawFd as _;
16937        let tmp = tempfile::tempdir().unwrap();
16938        let mut runner = registered_runner(tmp.path()).await;
16939        runner.state.prep_complete = Some(false);
16940        runner.state.config.graph.timeout_resource_wait = 30;
16941        runner.state.save().unwrap();
16942        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16943        assert_eq!(
16944            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16945            0
16946        );
16947        assert!(
16948            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16949                .await
16950                .is_err()
16951        );
16952        let disk = RunState::load(&runner.state.id).unwrap();
16953        assert!(disk.driver_exited);
16954        assert_eq!(disk.driver_pid, None);
16955        assert!(disk.status.resumable());
16956        assert!(runner.state.driver_exited);
16957        assert_eq!(runner.state.driver_pid, None);
16958        runner.state.save().unwrap();
16959        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16960    }
16961
16962    #[tokio::test]
16963    #[cfg(unix)]
16964    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16965        let tmp = tempfile::tempdir().unwrap();
16966        let mut runner = registered_runner(tmp.path()).await;
16967        let winner = runner.state.candidates[0].clone();
16968        let cache = tmp.path().join("cache");
16969        let started = tmp.path().join("pre-gate-started");
16970        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16971        runner.state.config.verify.gate =
16972            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16973        let home = crate::run::home();
16974        let owner =
16975            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16976        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16977            crate::cache::AcquireOutcome::Acquired(g) => g,
16978            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16979        };
16980        let mut gate = Box::pin(runner.run_gate(&winner));
16981        assert!(
16982            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16983                .await
16984                .is_err()
16985        );
16986        assert!(!started.exists(), "pre-gate must wait for the cache too");
16987        // Simulate the wave that already owns the cache entering invoke.
16988        // It must obtain the editor reservation and finish without waiting
16989        // for the gate that is queued behind its cache.
16990        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16991        let editor = crate::repo_lock::SeatLease::checkout_with(
16992            &winner.worktree,
16993            true,
16994            crate::config::test_coordination().as_ref(),
16995            &wait,
16996        )
16997        .await
16998        .unwrap();
16999        drop(editor);
17000        guard.release();
17001        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17002            .await
17003            .unwrap()
17004            .unwrap();
17005        drop(gate);
17006        assert!(outcomes.iter().all(CommandOutcome::ok));
17007        assert!(started.exists());
17008    }
17009
17010    #[tokio::test]
17011    #[cfg(unix)]
17012    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
17013        use std::os::fd::AsRawFd as _;
17014
17015        ask_test_home();
17016        let tmp = tempfile::tempdir().unwrap();
17017        let repo = tmp.path().join("repo");
17018        std::fs::create_dir_all(&repo).unwrap();
17019        init_repo(&repo);
17020        let common = repo.join(".git");
17021        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17022        let mut runner = runner_at(RunStatus::Prep);
17023        runner.state.repo = repo.clone();
17024        runner.state.config.coordination = crate::config::test_coordination();
17025        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17026        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17027        runner.state.config.graph.advise = false;
17028        runner.roles.implementers = vec![spec("implement")];
17029        runner.roles.judges = vec![spec("judge")];
17030        runner.prep().await.unwrap();
17031        let winner = runner.state.candidates[0].clone();
17032        // Emulate edits already left by a completed seat. The fixture CLI
17033        // only reports completion; it performs no repository operations.
17034        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
17035        let completed = tmp.path().join("seat-completed");
17036        runner.roles.implementers[0].command = vec![
17037            "sh".into(),
17038            "-c".into(),
17039            format!("touch '{}'; echo completed", completed.display()),
17040        ];
17041        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
17042        assert_eq!(
17043            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17044            0
17045        );
17046        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17047        let mut implement = Box::pin(runner.implement());
17048        tokio::select! {
17049            result = &mut implement => panic!("rescue must wait: {result:?}"),
17050            result = tokio::time::timeout(Duration::from_secs(10), async {
17051                while !completed.exists() {
17052                    tokio::time::sleep(Duration::from_millis(20)).await;
17053                }
17054            }) => result.unwrap(),
17055        }
17056        assert!(
17057            tokio::time::timeout(Duration::from_millis(200), &mut implement)
17058                .await
17059                .is_err()
17060        );
17061        assert_eq!(
17062            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17063            before
17064        );
17065        assert_eq!(
17066            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17067            0
17068        );
17069        tokio::time::timeout(Duration::from_secs(10), &mut implement)
17070            .await
17071            .unwrap()
17072            .unwrap();
17073        drop(implement);
17074        assert_ne!(
17075            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17076            before
17077        );
17078        assert!(git::is_clean(&winner.worktree).await.unwrap());
17079
17080        let started = tmp.path().join("pre-gate-started");
17081        let proceed = tmp.path().join("pre-gate-proceed");
17082        let checked = tmp.path().join("gate-ran");
17083        runner.state.config.verify.pre_gate = vec![format!(
17084            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17085            started.display(),
17086            proceed.display()
17087        )];
17088        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
17089        assert_eq!(
17090            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17091            0
17092        );
17093        let mut gate = Box::pin(runner.run_gate(&winner));
17094        assert!(
17095            tokio::time::timeout(Duration::from_millis(200), &mut gate)
17096                .await
17097                .is_err()
17098        );
17099        assert!(!started.exists());
17100        assert!(!checked.exists());
17101        assert!(git::is_clean(&winner.worktree).await.unwrap());
17102        assert_eq!(
17103            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17104            0
17105        );
17106        tokio::select! {
17107            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
17108            result = tokio::time::timeout(Duration::from_secs(10), async {
17109                while !started.exists() {
17110                    tokio::time::sleep(Duration::from_millis(20)).await;
17111                }
17112            }) => result.unwrap(),
17113        }
17114        assert_eq!(
17115            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17116            -1,
17117            "mechanical edits must hold the real lock"
17118        );
17119        std::fs::write(proceed, "ready").unwrap();
17120        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17121            .await
17122            .unwrap()
17123            .unwrap();
17124        drop(gate);
17125        assert!(outcomes.iter().all(CommandOutcome::ok));
17126        assert!(checked.exists());
17127        assert!(runner.state.pre_gate_commit.is_some());
17128        assert!(git::is_clean(&winner.worktree).await.unwrap());
17129        assert_eq!(
17130            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17131            0,
17132            "gate completion must release coordination"
17133        );
17134        drop(outsider);
17135        std::fs::remove_file(common.join("updater.lock")).unwrap();
17136        std::fs::create_dir(common.join("updater.lock")).unwrap();
17137        std::fs::remove_file(&started).unwrap();
17138        std::fs::remove_file(&checked).unwrap();
17139        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17140        let error = runner.run_gate(&winner).await.unwrap_err();
17141        assert!(
17142            error
17143                .to_string()
17144                .contains("acquire mandatory repository lock")
17145        );
17146        assert!(
17147            !started.exists(),
17148            "failed acquisition must prevent pre-gate"
17149        );
17150        assert!(!checked.exists(), "failed acquisition must prevent gate");
17151        assert!(git::is_clean(&winner.worktree).await.unwrap());
17152        assert_eq!(
17153            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17154            head
17155        );
17156    }
17157
17158    #[tokio::test]
17159    #[cfg(unix)]
17160    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
17161        use std::os::fd::AsRawFd as _;
17162        use std::time::Duration;
17163
17164        ask_test_home();
17165        let tmp = tempfile::tempdir().unwrap();
17166        let repo = tmp.path().join("repo");
17167        std::fs::create_dir_all(&repo).unwrap();
17168        init_repo(&repo);
17169        let common = repo.join(".git");
17170        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17171        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
17172        assert_eq!(
17173            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17174            0
17175        );
17176        let mut runner = runner_at(RunStatus::Prep);
17177        runner.state.repo = repo.clone();
17178        runner.state.config.coordination = crate::config::test_coordination();
17179        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17180        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17181        runner.state.config.graph.advise = true;
17182        runner.state.config.graph.advisors = 1;
17183        runner.roles.implementers = vec![spec("implement")];
17184        runner.roles.judges = vec![spec("judge")];
17185        let root = runner.state.worktree_root();
17186        let started = tmp.path().join("setup-started");
17187        let proceed = tmp.path().join("setup-proceed");
17188        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17189            run: Some(format!(
17190                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17191                started.display(),
17192                proceed.display()
17193            )),
17194            ..Default::default()
17195        }];
17196        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
17197        let config = git::git(&repo, &["config", "--local", "--list"])
17198            .await
17199            .unwrap();
17200        let mut prep = Box::pin(runner.prep());
17201        assert!(
17202            tokio::time::timeout(Duration::from_millis(200), &mut prep)
17203                .await
17204                .is_err()
17205        );
17206        assert!(
17207            !root.exists(),
17208            "contention must prevent even checkout creation"
17209        );
17210        assert!(!started.exists(), "contention must prevent setup");
17211        assert_eq!(
17212            git::git(&repo, &["branch", "--list"]).await.unwrap(),
17213            branches
17214        );
17215        assert_eq!(
17216            git::git(&repo, &["config", "--local", "--list"])
17217                .await
17218                .unwrap(),
17219            config
17220        );
17221        drop(lock);
17222        tokio::select! {
17223            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
17224            result = tokio::time::timeout(Duration::from_secs(10), async {
17225                while !started.exists() {
17226                    tokio::time::sleep(Duration::from_millis(20)).await;
17227                }
17228            }) => result.unwrap(),
17229        }
17230        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
17231        assert_eq!(
17232            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17233            -1
17234        );
17235        assert!(
17236            tokio::time::timeout(
17237                Duration::from_millis(100),
17238                crate::repo_lock::SeatLease::for_checkout(
17239                    &repo,
17240                    true,
17241                    crate::config::test_coordination().as_ref()
17242                )
17243            )
17244            .await
17245            .is_err(),
17246            "preparation must also exclude local editors"
17247        );
17248        std::fs::write(proceed, "ready").unwrap();
17249        tokio::time::timeout(Duration::from_secs(10), &mut prep)
17250            .await
17251            .unwrap()
17252            .unwrap();
17253        drop(prep);
17254        assert_eq!(runner.state.prep_complete, Some(true));
17255        assert!(root.join("judge-1").exists());
17256        assert!(root.join("advisor-1").exists());
17257        assert_eq!(
17258            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17259            0
17260        );
17261    }
17262
17263    #[tokio::test]
17264    #[cfg(unix)]
17265    async fn preparation_lock_failure_prevents_repository_changes() {
17266        ask_test_home();
17267        let tmp = tempfile::tempdir().unwrap();
17268        let repo = tmp.path().join("repo");
17269        std::fs::create_dir_all(&repo).unwrap();
17270        init_repo(&repo);
17271        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
17272        // A directory at the required lock path makes opening the real lock
17273        // fail, rather than merely exercising an invalid registration.
17274        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
17275        let mut runner = runner_at(RunStatus::Prep);
17276        runner.state.repo = repo.clone();
17277        runner.state.config.coordination = crate::config::test_coordination();
17278        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17279        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17280        runner.roles.implementers = vec![spec("implement")];
17281        let error = runner.prep().await.unwrap_err();
17282        assert!(
17283            error
17284                .to_string()
17285                .contains("acquire mandatory repository lock")
17286        );
17287        assert!(!runner.state.worktree_root().exists());
17288        assert!(runner.state.candidates.is_empty());
17289        assert!(!repo.join(".git/config.worktree").exists());
17290        assert_eq!(
17291            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
17292            "* main"
17293        );
17294    }
17295
17296    #[tokio::test]
17297    async fn preparation_records_creation_intent_before_git_can_fail() {
17298        ask_test_home();
17299        let tmp = tempfile::tempdir().unwrap();
17300        let repo = tmp.path().join("repo");
17301        std::fs::create_dir_all(&repo).unwrap();
17302        init_repo(&repo);
17303        let mut runner = runner_at(RunStatus::Prep);
17304        runner.state.repo = repo.clone();
17305        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17306        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17307        runner.state.config.blind.commit_msg_hook = false;
17308        runner.roles.implementers = vec![spec("one")];
17309        let label = blind::assign_labels(1, runner.state.seed)[0];
17310        let branch = runner.state.branch_for(label);
17311        // A conflicting branch makes Git refuse creation before a candidate
17312        // can be registered. The durable intent must still identify it.
17313        git::git(&repo, &["branch", &branch]).await.unwrap();
17314        assert!(runner.prep().await.is_err());
17315        let saved = RunState::load(&runner.state.id).unwrap();
17316        assert!(saved.candidates.is_empty());
17317        let event = saved
17318            .events
17319            .iter()
17320            .find(|e| e.node == "prep-intent")
17321            .unwrap();
17322        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
17323        assert_eq!(intent["branch"], branch);
17324        assert_eq!(intent["start"], runner.state.base_commit);
17325        assert_eq!(
17326            intent["worktree"],
17327            runner
17328                .state
17329                .worktree_root()
17330                .join(format!("cand-{label}"))
17331                .to_string_lossy()
17332                .as_ref()
17333        );
17334        assert_eq!(intent["picks"], serde_json::json!([]));
17335    }
17336
17337    #[tokio::test]
17338    async fn invalid_pinned_sources_create_no_partial_worktrees() {
17339        ask_test_home();
17340        let tmp = tempfile::tempdir().unwrap();
17341        let repo = tmp.path().join("repo");
17342        std::fs::create_dir_all(&repo).unwrap();
17343        init_repo(&repo);
17344        let mut runner = runner_at(RunStatus::Prep);
17345        runner.state.repo = repo.clone();
17346        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17347        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17348        runner.state.sources.pick_commits.push(refs::Input {
17349            token: "missing".into(),
17350            sha: "0".repeat(40),
17351            provenance: refs::Provenance::ExplicitCli,
17352        });
17353        assert!(runner.prep().await.is_err());
17354        assert!(runner.state.candidates.is_empty());
17355        assert!(!runner.state.worktree_root().exists());
17356    }
17357
17358    #[tokio::test]
17359    async fn prose_and_legacy_inference_never_import_into_candidates() {
17360        ask_test_home();
17361        let tmp = tempfile::tempdir().unwrap();
17362        let repo = tmp.path().join("repo");
17363        std::fs::create_dir_all(&repo).unwrap();
17364        init_repo(&repo);
17365        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17366        git::git(&repo, &["checkout", "-b", "magi/history/A"])
17367            .await
17368            .unwrap();
17369        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
17370        git::git(&repo, &["add", "."]).await.unwrap();
17371        git::git(&repo, &["commit", "-m", "historical implementation"])
17372            .await
17373            .unwrap();
17374        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
17375        git::git(&repo, &["checkout", "main"]).await.unwrap();
17376        for instruction in [
17377            format!("Example: magi/history/A at {source}"),
17378            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
17379            format!("Never import magi/history/A or {source}"),
17380            format!("Conversation answer: I mentioned {source} only as background"),
17381        ] {
17382            let mut runner = runner_at(RunStatus::Prep);
17383            runner.state.repo = repo.clone();
17384            runner.state.base_commit = base.clone();
17385            runner.state.instruction = instruction.clone();
17386            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
17387            runner.state.config.blind.commit_msg_hook = false;
17388            runner.state.seeds = vec![refs::Seed {
17389                token: "magi/history/A".into(),
17390                sha: source.clone(),
17391                kind: refs::SeedKind::Unmerged,
17392                branch: true,
17393                detail: String::new(),
17394            }];
17395            runner.roles.implementers = vec![spec("one")];
17396            assert_eq!(seeded_instruction(&runner.state), instruction);
17397            // Model an old record with inferred seeds but no structured input field.
17398            let mut legacy = serde_json::to_value(&runner.state).unwrap();
17399            legacy.as_object_mut().unwrap().remove("sources");
17400            runner.state = serde_json::from_value(legacy).unwrap();
17401            assert_eq!(runner.state.sources, refs::Sources::default());
17402            runner.state.save().unwrap();
17403            runner.state = RunState::load(&runner.state.id).unwrap();
17404            runner.prep().await.unwrap();
17405            for candidate in &runner.state.candidates {
17406                assert_eq!(
17407                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
17408                    base
17409                );
17410                assert!(!candidate.worktree.join("unwanted").exists());
17411            }
17412        }
17413    }
17414
17415    #[tokio::test]
17416    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
17417        ask_test_home();
17418        let tmp = tempfile::tempdir().unwrap();
17419        let repo = tmp.path().join("repo");
17420        std::fs::create_dir_all(&repo).unwrap();
17421        init_repo(&repo);
17422        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17423        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
17424        std::fs::write(repo.join("referenced"), "required commit").unwrap();
17425        git::git(&repo, &["add", "."]).await.unwrap();
17426        git::git(&repo, &["commit", "-m", "required seed"])
17427            .await
17428            .unwrap();
17429        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
17430        git::git(&repo, &["checkout", "main"]).await.unwrap();
17431        let mut runner = runner_at(RunStatus::Prep);
17432        runner.state.repo = repo.clone();
17433        runner.state.base_commit = base.clone();
17434        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17435        runner.state.config.graph.advise = false;
17436        runner.state.config.blind.commit_msg_hook = false;
17437        runner.state.sources =
17438            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
17439                .await
17440                .unwrap();
17441        runner.roles.implementers = vec![spec("one"), spec("two")];
17442        runner.roles.judges = vec![spec("judge")];
17443        let label = blind::assign_labels(2, runner.state.seed)[0];
17444        let branch = runner.state.branch_for(label);
17445        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17446        git::worktree_add_branch(&repo, &worktree, &branch, &base)
17447            .await
17448            .unwrap();
17449        runner.state.candidates.push(Candidate {
17450            index: 0,
17451            label,
17452            agent: "one".into(),
17453            branch,
17454            worktree,
17455            summary: String::new(),
17456            stat: String::new(),
17457            files: 0,
17458            commits: 0,
17459            empty: false,
17460            failed: None,
17461            verified_noop: None,
17462            duration_ms: 0,
17463            folded: false,
17464        });
17465        runner.state.save().unwrap();
17466        // Reload the checkpoint immediately before its first cherry-pick.
17467        runner.state = RunState::load(&runner.state.id).unwrap();
17468        assert_eq!(runner.state.prep_complete, Some(false));
17469        runner.prep().await.unwrap();
17470        assert_eq!(runner.state.prep_complete, Some(true));
17471        assert_eq!(runner.state.candidates.len(), 2);
17472        for candidate in &runner.state.candidates {
17473            assert_eq!(
17474                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17475                git::tree_of(&repo, &seed).await.unwrap()
17476            );
17477            assert_eq!(
17478                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
17479                "required commit"
17480            );
17481        }
17482        assert!(runner.state.worktree_root().join("judge-1").exists());
17483        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
17484        runner.prep().await.unwrap();
17485        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
17486
17487        runner.state.prep_complete = Some(false);
17488        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17489            run: Some(format!(
17490                "test -f '{}'",
17491                tmp.path().join("dependency-ready").display()
17492            )),
17493            ..Default::default()
17494        }];
17495        assert!(runner.prep().await.is_err());
17496        assert!(runner.state.prep_failure.is_some());
17497        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
17498        runner.state = RunState::load(&runner.state.id).unwrap();
17499        assert!(
17500            runner.prep().await.is_err(),
17501            "correcting the cause alone must not auto-retry"
17502        );
17503        let failed_at = runner.state.events.last().unwrap().at;
17504        assert!(
17505            runner.retry_preparation(failed_at).is_err(),
17506            "old approvals cannot unlock the hold"
17507        );
17508        let mut task = crate::queue::Task::new(
17509            "retry".into(),
17510            "retry setup".into(),
17511            repo.clone(),
17512            crate::queue::Source::Human,
17513        );
17514        task.start(runner.state.id.clone());
17515        task.hold_machine(Some("setup failed".into()));
17516        task.release_operator("cli", None);
17517        runner
17518            .retry_preparation(task.resumption.as_ref().unwrap().at)
17519            .unwrap();
17520        runner.prep().await.unwrap();
17521        assert!(runner.state.prep_failure.is_none());
17522        assert_eq!(runner.state.prep_complete, Some(true));
17523        assert_eq!(runner.state.candidates.len(), 2);
17524        assert!(runner.state.worktree_root().join("judge-1").exists());
17525        for candidate in &runner.state.candidates {
17526            assert_eq!(
17527                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17528                git::tree_of(&repo, &seed).await.unwrap()
17529            );
17530        }
17531    }
17532
17533    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
17534        let mut heads = Vec::new();
17535        for candidate in candidates {
17536            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
17537        }
17538        heads
17539    }
17540
17541    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
17542        ask_test_home();
17543        let tmp = tempfile::tempdir().unwrap();
17544        let repo = tmp.path().join("repo");
17545        std::fs::create_dir(&repo).unwrap();
17546        init_repo(&repo);
17547        let mut runner = runner_at(RunStatus::Reviewing);
17548        runner.state.repo = repo.clone();
17549        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17550        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17551        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17552            let branch = format!("candidate-{label}");
17553            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17554            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17555                .await
17556                .unwrap();
17557            if label == 'B' {
17558                std::fs::write(worktree.join("change"), "winner").unwrap();
17559                git::rescue_commit(&worktree, "candidate change")
17560                    .await
17561                    .unwrap();
17562            }
17563            runner.state.candidates.push(Candidate {
17564                index,
17565                label,
17566                agent: "alpha".into(),
17567                branch,
17568                worktree,
17569                summary: "completed reply".into(),
17570                stat: String::new(),
17571                files: usize::from(label == 'B'),
17572                commits: usize::from(label == 'B'),
17573                empty: label == 'A',
17574                failed: None,
17575                verified_noop: None,
17576                duration_ms: 1,
17577                folded: false,
17578            });
17579        }
17580        runner.state.judge_skipped = true;
17581        runner.state.tally = Some(Tally {
17582            first_choice: BTreeMap::new(),
17583            borda: BTreeMap::new(),
17584            winner: 'B',
17585            rankings: 0,
17586            unanimous_initial: false,
17587            deliberated: false,
17588            changed_votes: 0,
17589            unanimous_final: false,
17590            tie_break: None,
17591            judges: 0,
17592            present: 0,
17593            quorum: 0,
17594            met_quorum: true,
17595            uncontested: Some("only B produced a change".into()),
17596        });
17597        runner.state.save().unwrap();
17598        (tmp, runner)
17599    }
17600
17601    #[tokio::test]
17602    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17603        let (_tmp, mut runner) = preservation_resume_fixture().await;
17604        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17605        runner.state.config.disk.cache_limit_bytes = 0;
17606        runner.state.config.graph.advise = true;
17607        runner.state.config.graph.advisors = 1;
17608        let advisor = runner.state.worktree_root().join("advisor-1");
17609        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17610            .await
17611            .unwrap();
17612        let home = crate::run::home();
17613        let loser =
17614            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17615        let winner =
17616            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17617        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17618        for target in [&loser, &winner, &advisor] {
17619            std::fs::write(target.join("build-output"), "compiled").unwrap();
17620        }
17621
17622        runner.fold_losers().await.unwrap();
17623
17624        assert!(!loser.join("build-output").exists());
17625        assert!(!advisor.join("build-output").exists());
17626        assert!(winner.join("build-output").is_file());
17627    }
17628
17629    #[tokio::test]
17630    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17631        let (_tmp, mut runner) = preservation_resume_fixture().await;
17632        runner.state.candidates[0].folded = true;
17633        runner.state.config.graph.advise = true;
17634        runner.state.config.graph.advisors = 2;
17635        let repo = runner.state.repo.clone();
17636        let root = runner.state.worktree_root();
17637        let discarded = root.join("advisor-1");
17638        git::worktree_add_detached(&repo, &discarded, "main")
17639            .await
17640            .unwrap();
17641        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17642        let protected = root.join("advisor-2");
17643        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17644            .await
17645            .unwrap();
17646        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17647        runner.state.save().unwrap();
17648
17649        assert!(runner.fold_losers().await.is_err());
17650        assert!(!discarded.exists());
17651        assert!(protected.join("keep").exists());
17652        let saved = RunState::load(&runner.state.id).unwrap();
17653        assert!(saved.events.iter().any(|event| {
17654            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17655        }));
17656    }
17657
17658    #[tokio::test]
17659    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17660        let (tmp, mut runner) = preservation_resume_fixture().await;
17661        let repo = runner.state.repo.clone();
17662        let root = runner.state.worktree_root();
17663        for name in ["advisor-3", "judge-1", "review-2"] {
17664            let path = root.join(name);
17665            git::worktree_add_detached(&repo, &path, "main")
17666                .await
17667                .unwrap();
17668            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17669            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17670            remove_read_seat_worktree(&mut runner.state, &path)
17671                .await
17672                .unwrap();
17673            assert!(!path.exists());
17674        }
17675        let outside = tmp.path().join("advisor-1");
17676        let unknown = root.join("unknown");
17677        let attached = root.join("advisor-4");
17678        git::worktree_add_detached(&repo, &outside, "main")
17679            .await
17680            .unwrap();
17681        git::worktree_add_detached(&repo, &unknown, "main")
17682            .await
17683            .unwrap();
17684        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17685            .await
17686            .unwrap();
17687        let foreign = tmp.path().join("foreign");
17688        std::fs::create_dir(&foreign).unwrap();
17689        init_repo(&foreign);
17690        let wrong_repo = root.join("judge-2");
17691        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17692            .await
17693            .unwrap();
17694        let candidate = runner.state.candidates[0].worktree.clone();
17695        for path in [outside, unknown, attached, wrong_repo, candidate] {
17696            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17697            assert!(
17698                remove_read_seat_worktree(&mut runner.state, &path)
17699                    .await
17700                    .is_err()
17701            );
17702            assert_eq!(
17703                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17704                "keep"
17705            );
17706        }
17707    }
17708
17709    #[tokio::test]
17710    #[cfg(unix)]
17711    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17712        for (solo, failed_checkpoint) in
17713            [(true, false), (false, false), (true, true), (false, true)]
17714        {
17715            let (_tmp, mut runner) = preservation_resume_fixture().await;
17716            if solo {
17717                runner.state.candidates.retain(|c| c.label == 'A');
17718            }
17719            runner.state.candidates[0].empty = false;
17720            runner.state.candidates[0].summary.clear();
17721            runner.state.tally = None;
17722            runner.state.judge_skipped = false;
17723            runner.state.status = RunStatus::Implementing;
17724            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17725            let mut implementer = spec("alpha");
17726            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17727            runner.roles.implementers = vec![implementer];
17728            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17729            if failed_checkpoint {
17730                std::fs::create_dir_all(&patch).unwrap();
17731            }
17732            runner.state.save().unwrap();
17733            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17734            drop(pressure);
17735            runner.state = RunState::load(&runner.state.id).unwrap();
17736            assert_eq!(runner.state.status, RunStatus::Blocked);
17737            assert!(runner.state.interrupted_implementations.contains(&'A'));
17738            assert_eq!(runner.state.candidates[0].commits, 0);
17739            assert!(!runner.state.candidates[0].empty);
17740            assert!(runner.state.candidates[0].failed.is_none());
17741            if failed_checkpoint {
17742                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17743                std::fs::remove_dir(patch).unwrap();
17744            }
17745            runner.state.resource_block = None;
17746            runner.state.config.disk.min_free_bytes = 0;
17747            runner.roles.implementers[0].command = vec![
17748                "sh".into(),
17749                "-c".into(),
17750                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17751            ];
17752            runner.implement().await.unwrap();
17753            assert!(runner.state.interrupted_implementations.is_empty());
17754            assert!(runner.state.candidate_preservation.is_empty());
17755            assert_eq!(runner.state.candidates[0].commits, 1);
17756            assert!(!runner.state.candidates[0].empty);
17757            assert!(
17758                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17759                    .unwrap()
17760                    .contains("retried empty interrupted seat")
17761            );
17762            if !solo {
17763                assert_eq!(runner.state.candidates[1].commits, 1);
17764            }
17765        }
17766    }
17767
17768    #[tokio::test]
17769    #[cfg(unix)]
17770    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17771        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17772            let (_tmp, mut runner) = preservation_resume_fixture().await;
17773            runner.state.candidates.retain(|c| c.label == 'A');
17774            runner.state.candidates[0].empty = false;
17775            runner.state.candidates[0].summary.clear();
17776            runner.state.tally = None;
17777            runner.state.judge_skipped = false;
17778            runner.state.status = RunStatus::Implementing;
17779            // Force only the real post-spawn watchdog, without failing the
17780            // separate admission check. Existing edits predate its measurement.
17781            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17782            let wt = runner.state.candidates[0].worktree.clone();
17783            std::fs::write(
17784                wt.join("interrupted-source"),
17785                "retain implementation work\n",
17786            )
17787            .unwrap();
17788            if committed {
17789                git::rescue_commit(&wt, "implementation checkpoint")
17790                    .await
17791                    .unwrap();
17792            }
17793            let lock = git::git(
17794                &wt,
17795                &[
17796                    "rev-parse",
17797                    "--path-format=absolute",
17798                    "--git-path",
17799                    "index.lock",
17800                ],
17801            )
17802            .await
17803            .unwrap();
17804            if block_rescue {
17805                std::fs::write(&lock, "fixture-owned lock").unwrap();
17806            }
17807            let mut implementer = spec("alpha");
17808            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17809            runner.roles.implementers = vec![implementer];
17810            runner.state.save().unwrap();
17811            let result = runner.implement().await;
17812            drop(pressure);
17813            assert_eq!(result.is_err(), block_rescue);
17814            assert_eq!(
17815                runner.state.resource_block.as_ref().unwrap().kind,
17816                "disk pressure"
17817            );
17818            assert!(
17819                runner
17820                    .state
17821                    .events
17822                    .iter()
17823                    .any(|e| e.message.contains("agent execution interrupted"))
17824            );
17825            assert!(
17826                runner
17827                    .state
17828                    .dir()
17829                    .join("artifacts/candidate-A-recovery/staged.patch")
17830                    .exists()
17831            );
17832            if block_rescue {
17833                let saved = RunState::load(&runner.state.id).unwrap();
17834                assert!(saved.candidate_preservation.contains_key(&'A'));
17835                assert!(!saved.candidates[0].empty);
17836                assert_eq!(
17837                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17838                    "retain implementation work\n"
17839                );
17840                std::fs::remove_file(lock).unwrap();
17841                runner.state = saved;
17842            } else {
17843                assert_eq!(runner.state.status, RunStatus::Blocked);
17844                assert_eq!(runner.state.candidates[0].commits, 1);
17845            }
17846            // Recovery must save the candidate before deciding whether another
17847            // implementation is needed. No implementer is available on retry.
17848            runner.roles.implementers.clear();
17849            runner.state.config.disk.min_free_bytes = 0;
17850            runner.state.resource_block = None;
17851            runner.implement().await.unwrap();
17852            assert!(runner.state.candidate_preservation.is_empty());
17853            assert_eq!(runner.state.candidates[0].commits, 1);
17854            assert!(!runner.state.candidates[0].empty);
17855            assert!(git::is_clean(&wt).await.unwrap());
17856            assert!(
17857                crate::run::read_artifact(&runner.state, "cand-A.patch")
17858                    .unwrap()
17859                    .contains("retain implementation work")
17860            );
17861        }
17862    }
17863
17864    #[tokio::test]
17865    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17866        let (_tmp, mut runner) = preservation_resume_fixture().await;
17867        // Schema 15 already confirmed the unfolded no-change result.
17868        runner.implement().await.unwrap();
17869        assert!(runner.state.candidate_preservation.is_empty());
17870        assert!(
17871            !runner
17872                .state
17873                .dir()
17874                .join("artifacts/candidate-A-recovery")
17875                .exists()
17876        );
17877        runner.fold_losers().await.unwrap();
17878        assert!(!runner.state.candidates[0].worktree.exists());
17879        for schema in [14, crate::run::SCHEMA] {
17880            runner.state.schema = schema;
17881            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17882            runner.state.save().unwrap();
17883            runner.state = RunState::load(&runner.state.id).unwrap();
17884            runner.implement().await.unwrap();
17885            assert!(runner.state.candidate_preservation.is_empty());
17886            assert!(runner.state.candidates[0].folded);
17887            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17888        }
17889    }
17890
17891    #[tokio::test]
17892    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17893        let (_tmp, mut runner) = preservation_resume_fixture().await;
17894        runner.state.candidates.retain(|c| c.label == 'A');
17895        runner.state.tally = None;
17896        runner.state.judge_skipped = false;
17897        let candidate = &mut runner.state.candidates[0];
17898        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17899        candidate.failed = Some("deployment validation unavailable".into());
17900        std::fs::write(
17901            candidate.worktree.join("repair"),
17902            "future launcher policy\n",
17903        )
17904        .unwrap();
17905        runner
17906            .state
17907            .candidate_preservation
17908            .insert('A', "awaiting persistence".into());
17909        runner.persist_candidates().await.unwrap();
17910        let candidate = &runner.state.candidates[0];
17911        assert!(!candidate.empty);
17912        assert_eq!(candidate.commits, 1);
17913        assert_eq!(candidate.files, 1);
17914        assert!(candidate.failed.is_none());
17915        assert!(candidate.summary.contains("EPERM"));
17916        assert!(
17917            crate::run::read_artifact(&runner.state, "cand-A.patch")
17918                .unwrap()
17919                .contains("future launcher policy")
17920        );
17921        assert!(runner.state.candidate_preservation.is_empty());
17922    }
17923
17924    #[tokio::test]
17925    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17926        let (_tmp, mut runner) = preservation_resume_fixture().await;
17927        let wt = runner.state.candidates[0].worktree.clone();
17928        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17929        runner.state.schema = 14;
17930        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17931        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17932        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17933        for _ in 0..2 {
17934            assert!(runner.implement().await.is_err());
17935            assert_eq!(runner.state.status, RunStatus::Blocked);
17936            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17937            assert!(
17938                runner.state.candidates[0].empty,
17939                "old verdict must remain unusable"
17940            );
17941            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17942            assert!(runner.state.judge_skipped);
17943            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17944            assert!(
17945                crate::run::read_artifact(&runner.state, "cand-A.patch")
17946                    .unwrap()
17947                    .contains("owned edits")
17948            );
17949            assert!(wt.exists());
17950            assert_eq!(
17951                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17952                    .await
17953                    .unwrap(),
17954                1
17955            );
17956            runner.state = RunState::load(&runner.state.id).unwrap();
17957        }
17958    }
17959
17960    #[tokio::test]
17961    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17962        let (_tmp, mut runner) = preservation_resume_fixture().await;
17963        let wt = runner.state.candidates[0].worktree.clone();
17964        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17965        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17966        let index_lock = PathBuf::from(
17967            git::git(
17968                &wt,
17969                &[
17970                    "rev-parse",
17971                    "--path-format=absolute",
17972                    "--git-path",
17973                    "index.lock",
17974                ],
17975            )
17976            .await
17977            .unwrap(),
17978        );
17979        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17980        runner.state.schema = 14;
17981        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17982        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17983        assert!(runner.implement().await.is_err());
17984        assert!(runner.after_implement().is_err());
17985        assert!(runner.fold_losers().await.is_err());
17986        assert_eq!(
17987            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17988            "failed seat edits"
17989        );
17990        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17991        runner.state = RunState::load(&runner.state.id).unwrap();
17992        std::fs::remove_file(index_lock).unwrap();
17993        // Recovery finds changes that the old uncontested result never judged.
17994        assert!(runner.implement().await.is_err());
17995        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17996        assert!(runner.state.candidates[0].empty);
17997        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17998        assert!(
17999            crate::run::read_artifact(&runner.state, "cand-A.patch")
18000                .unwrap()
18001                .contains("failed seat edits")
18002        );
18003        assert!(wt.exists());
18004    }
18005
18006    #[tokio::test]
18007    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
18008        let (_tmp, mut runner) = preservation_resume_fixture().await;
18009        let repo = runner.state.repo.clone();
18010        let common = git::git(
18011            &repo,
18012            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
18013        )
18014        .await
18015        .unwrap();
18016        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
18017        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
18018        assert!(runner.fold_losers().await.is_err());
18019        assert!(!runner.state.candidates[0].worktree.exists());
18020        assert!(!runner.state.candidates[0].folded);
18021        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
18022        runner.state = RunState::load(&runner.state.id).unwrap();
18023        std::fs::remove_file(branch_lock).unwrap();
18024        let judge = runner.state.worktree_root().join("judge-1");
18025        git::worktree_add_detached(&repo, &judge, "main")
18026            .await
18027            .unwrap();
18028        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
18029        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
18030            .await
18031            .unwrap();
18032        runner.roles.judges = vec![spec("judge")];
18033        assert!(runner.fold_losers().await.is_err());
18034        runner.state = RunState::load(&runner.state.id).unwrap();
18035        assert!(
18036            runner.state.candidates[0].folded,
18037            "candidate progress saved before judge failure"
18038        );
18039        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
18040        assert!(judge.join("uncommitted").exists());
18041        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
18042            .await
18043            .unwrap();
18044        runner.fold_losers().await.unwrap();
18045        assert!(!judge.exists());
18046        runner.fold_losers().await.unwrap();
18047    }
18048
18049    #[tokio::test]
18050    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
18051        let (_tmp, mut runner) = preservation_resume_fixture().await;
18052        runner.state.candidates.retain(|c| c.label == 'B');
18053        runner.state.tally = None;
18054        runner.state.judge_skipped = false;
18055        runner.state.prep_complete = Some(true);
18056        runner.state.config.graph.advise = false;
18057        runner.state.config.graph.selected_implementer = Some("alpha".into());
18058        let wt = runner.state.candidates[0].worktree.clone();
18059        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
18060        runner
18061            .state
18062            .candidate_preservation
18063            .insert('B', "awaiting persistence".into());
18064        let index_lock = git::git(
18065            &wt,
18066            &[
18067                "rev-parse",
18068                "--path-format=absolute",
18069                "--git-path",
18070                "index.lock",
18071            ],
18072        )
18073        .await
18074        .unwrap();
18075        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18076        runner.state.save().unwrap();
18077        assert!(runner.execute_graph().await.is_err());
18078        assert_eq!(runner.state.status, RunStatus::Blocked);
18079        assert!(runner.state.candidate_preservation.contains_key(&'B'));
18080        std::fs::remove_file(index_lock).unwrap();
18081        // Park at the next graph boundary: this tests the real selected-seat
18082        // hold guard without dispatching reviewers or publishing anything.
18083        for _ in 0..2 {
18084            runner.state = RunState::load(&runner.state.id).unwrap();
18085            runner.pause.park();
18086            runner.execute_graph().await.unwrap();
18087            assert_eq!(runner.state.status, RunStatus::Implementing);
18088            assert!(runner.state.candidate_preservation.is_empty());
18089            assert_eq!(runner.state.candidates[0].commits, 2);
18090            assert!(runner.state.tally.is_none());
18091        }
18092        runner.implement().await.unwrap();
18093        assert_eq!(runner.state.status, RunStatus::Judging);
18094        // A genuine selected-implementer hold must still require release.
18095        runner.state.status = RunStatus::Blocked;
18096        runner.state.candidates[0].failed = Some("implementation failed".into());
18097        runner.state.save().unwrap();
18098        let error = runner.execute_graph().await.unwrap_err();
18099        assert!(
18100            error
18101                .to_string()
18102                .contains("selected implementation is held")
18103        );
18104    }
18105
18106    #[tokio::test]
18107    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
18108        let (_tmp, mut runner) = preservation_resume_fixture().await;
18109        let repo = runner.state.repo.clone();
18110        let candidate = runner.state.candidates[0].clone();
18111        // Remove only the disposable fixture directory, leaving Git's linked
18112        // worktree registration and branch intact, as in a vanished checkout.
18113        let registered = git::worktree_holding(&repo, &candidate.branch)
18114            .await
18115            .unwrap()
18116            .unwrap();
18117        assert_eq!(
18118            registered.canonicalize().unwrap(),
18119            candidate.worktree.canonicalize().unwrap()
18120        );
18121        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18122        assert_eq!(
18123            git::worktree_holding(&repo, &candidate.branch)
18124                .await
18125                .unwrap(),
18126            Some(registered)
18127        );
18128        assert!(
18129            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
18130            "the stale registration initially keeps the branch checked out"
18131        );
18132        runner.fold_losers().await.unwrap();
18133        assert!(runner.state.candidates[0].folded);
18134        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18135        assert_eq!(
18136            git::worktree_holding(&repo, &candidate.branch)
18137                .await
18138                .unwrap(),
18139            None
18140        );
18141        runner.state = RunState::load(&runner.state.id).unwrap();
18142        runner.fold_losers().await.unwrap();
18143    }
18144
18145    #[tokio::test]
18146    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
18147        let (_tmp, mut runner) = preservation_resume_fixture().await;
18148        let repo = runner.state.repo.clone();
18149        let candidate = runner.state.candidates[0].clone();
18150        let winner = runner.state.candidates[1].clone();
18151        let registered = git::worktree_holding(&repo, &candidate.branch)
18152            .await
18153            .unwrap()
18154            .unwrap();
18155        assert_eq!(
18156            registered.canonicalize().unwrap(),
18157            candidate.worktree.canonicalize().unwrap()
18158        );
18159        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18160        assert_eq!(
18161            git::worktree_holding(&repo, &candidate.branch)
18162                .await
18163                .unwrap(),
18164            Some(registered)
18165        );
18166        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
18167
18168        for _ in 0..2 {
18169            fold_run(&mut runner.state, false, &crate::run::home())
18170                .await
18171                .unwrap();
18172            runner.state = RunState::load(&runner.state.id).unwrap();
18173            assert!(runner.state.candidates[0].folded);
18174            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18175            assert_eq!(
18176                git::worktree_holding(&repo, &candidate.branch)
18177                    .await
18178                    .unwrap(),
18179                None
18180            );
18181            assert!(!runner.state.candidates[1].folded);
18182            assert!(winner.worktree.exists());
18183            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
18184        }
18185    }
18186
18187    /// The recovery-retention override, refused for the rule under test. The
18188    /// arrangement is saved in `home` before each call, so `record gone` or
18189    /// `unreadable` would be the fixture's mistake and fails here.
18190    async fn override_refusal(state: &mut RunState, home: &Path) -> anyhow::Error {
18191        let error = fold_run_overriding_recovery_retention(state, true, home)
18192            .await
18193            .expect_err("the override is refused");
18194        assert!(
18195            !matches!(
18196                error.downcast_ref::<FoldRefusal>(),
18197                Some(FoldRefusal::RecordGone | FoldRefusal::Unreadable(_))
18198            ),
18199            "refused for the wrong reason: {error:#}"
18200        );
18201        error
18202    }
18203
18204    #[tokio::test]
18205    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
18206        for sidecar in [false, true] {
18207            let tmp = tempfile::tempdir().unwrap();
18208            let home = tmp.path().join("home");
18209            let repo = tmp.path().join("repo");
18210            std::fs::create_dir(&repo).unwrap();
18211            init_repo(&repo);
18212            let mut state = runner_at(RunStatus::Superseded).state;
18213            state.repo = repo.clone();
18214            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18215            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18216            state.driver_exited = true;
18217            state.reserve_under(&home).unwrap();
18218            git::git(
18219                &repo,
18220                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
18221            )
18222            .await
18223            .unwrap();
18224            let wt = state.worktree_root().join("cand-A");
18225            git::worktree_add_branch(&repo, &wt, "candidate", "main")
18226                .await
18227                .unwrap();
18228            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
18229            git::commit_all(&wt, "fixture: independent source")
18230                .await
18231                .unwrap();
18232            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
18233            state.candidates.push(Candidate {
18234                index: 0,
18235                label: 'A',
18236                agent: "fixture".into(),
18237                branch: "candidate".into(),
18238                worktree: wt.clone(),
18239                summary: String::new(),
18240                stat: String::new(),
18241                files: 0,
18242                commits: 0,
18243                empty: false,
18244                failed: None,
18245                verified_noop: None,
18246                duration_ms: 0,
18247                folded: false,
18248            });
18249            let mut task = crate::queue::Task::new(
18250                "task".into(),
18251                "task".into(),
18252                repo.clone(),
18253                crate::queue::Source::Human,
18254            );
18255            task.runs.push(state.id.clone());
18256            crate::queue::Queue::at(home.join("queue"))
18257                .put(&mut task)
18258                .unwrap();
18259            if sidecar {
18260                crate::pr_recovery::retain_sources(&task, &home).unwrap();
18261            }
18262            state.save_under(&home).unwrap();
18263            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
18264            let refusal = fold_run(&mut state, true, &home).await.unwrap_err();
18265            assert!(
18266                matches!(
18267                    refusal.downcast_ref::<FoldRefusal>(),
18268                    Some(FoldRefusal::Retained(retained)) if retained == &reason
18269                ),
18270                "{refusal:#}"
18271            );
18272            let mut disk = state.config.disk.clone();
18273            disk.fold_grace_secs = 0;
18274            assert_eq!(
18275                crate::clean::fold_due(
18276                    &home.join("runs"),
18277                    &home,
18278                    &state.worktree_root(),
18279                    &disk,
18280                    Timestamp::now() + std::time::Duration::from_secs(10),
18281                )
18282                .await
18283                .unwrap(),
18284                (0, 0)
18285            );
18286            assert!(wt.exists());
18287            state.status = RunStatus::Blocked;
18288            state.save_under(&home).unwrap();
18289            let error = override_refusal(&mut state, &home).await;
18290            assert!(
18291                error
18292                    .to_string()
18293                    .contains("requires a finished, non-resumable run"),
18294                "{error:#}"
18295            );
18296            state.status = RunStatus::Superseded;
18297            state.driver_exited = false;
18298            state.driver_claimed = None;
18299            state.save_under(&home).unwrap();
18300            let error = override_refusal(&mut state, &home).await;
18301            assert!(
18302                error
18303                    .to_string()
18304                    .contains("run is live or its ownership is unknown"),
18305                "{error:#}"
18306            );
18307            state.driver_pid = Some(std::process::id());
18308            state.driver_started_at = crate::proc::process_started_at(std::process::id());
18309            state.save_under(&home).unwrap();
18310            let error = override_refusal(&mut state, &home).await;
18311            assert!(
18312                error
18313                    .to_string()
18314                    .contains("run is live or its ownership is unknown"),
18315                "{error:#}"
18316            );
18317            state.driver_exited = true;
18318            state.driver_pid = None;
18319            state.driver_started_at = None;
18320            state.save_under(&home).unwrap();
18321            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
18322            let error = override_refusal(&mut state, &home).await;
18323            assert!(
18324                matches!(
18325                    error.downcast_ref::<FoldRefusal>(),
18326                    Some(FoldRefusal::Live(_))
18327                ),
18328                "{error:#}"
18329            );
18330            drop(lease);
18331            #[cfg(unix)]
18332            {
18333                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
18334                let error = override_refusal(&mut state, &home).await;
18335                assert!(
18336                    matches!(
18337                        error.downcast_ref::<FoldRefusal>(),
18338                        Some(FoldRefusal::Live(_))
18339                    ),
18340                    "{error:#}"
18341                );
18342                drop(output);
18343            }
18344            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
18345            let error = override_refusal(&mut state, &home).await;
18346            assert!(
18347                matches!(
18348                    error.downcast_ref::<FoldRefusal>(),
18349                    Some(FoldRefusal::Live(_))
18350                ),
18351                "{error:#}"
18352            );
18353            drop(owner);
18354            let checkpoint = git::git(
18355                &wt,
18356                &[
18357                    "rev-parse",
18358                    "--path-format=absolute",
18359                    "--git-path",
18360                    "CHERRY_PICK_HEAD",
18361                ],
18362            )
18363            .await
18364            .unwrap();
18365            std::fs::write(&checkpoint, &head).unwrap();
18366            let error = override_refusal(&mut state, &home).await;
18367            assert!(
18368                matches!(
18369                    error.downcast_ref::<FoldRefusal>(),
18370                    Some(FoldRefusal::ProofIncomplete(detail))
18371                        if detail.contains("Git recovery checkpoint retained")
18372                ),
18373                "{error:#}"
18374            );
18375            std::fs::remove_file(checkpoint).unwrap();
18376            std::fs::write(wt.join("dirty"), "keep").unwrap();
18377            let error = override_refusal(&mut state, &home).await;
18378            assert!(
18379                matches!(
18380                    error.downcast_ref::<FoldRefusal>(),
18381                    Some(FoldRefusal::ProofIncomplete(_))
18382                ),
18383                "{error:#}"
18384            );
18385            assert!(wt.join("dirty").exists());
18386            std::fs::remove_file(wt.join("dirty")).unwrap();
18387            let evidence = home
18388                .join("runs")
18389                .join(&state.id)
18390                .join("artifacts/fold-evidence");
18391            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
18392            std::fs::write(&evidence, "blocked archive").unwrap();
18393            let error = override_refusal(&mut state, &home).await;
18394            assert!(
18395                matches!(
18396                    error.downcast_ref::<FoldRefusal>(),
18397                    Some(FoldRefusal::ProofIncomplete(_))
18398                ),
18399                "{error:#}"
18400            );
18401            assert!(wt.exists());
18402            assert!(
18403                !RunState::load_under(&state.id, &home)
18404                    .unwrap()
18405                    .events
18406                    .iter()
18407                    .any(|event| event.message.contains("--override-recovery-retention"))
18408            );
18409            std::fs::remove_file(&evidence).unwrap();
18410            fold_run_overriding_recovery_retention(&mut state, true, &home)
18411                .await
18412                .unwrap();
18413            assert!(!wt.exists());
18414            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
18415            assert!(
18416                git::worktree_holding(&repo, "candidate")
18417                    .await
18418                    .unwrap()
18419                    .is_none()
18420            );
18421            assert!(
18422                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
18423                    .unwrap()
18424                    .contains("retained implementation")
18425            );
18426            assert!(evidence.join(format!("{head}.index")).is_file());
18427            let saved = RunState::load_under(&state.id, &home).unwrap();
18428            assert_eq!(saved.status, RunStatus::Superseded);
18429            assert!(saved.candidates[0].folded);
18430            assert!(saved.events.iter().any(|event| {
18431                event.message.contains("--override-recovery-retention")
18432                    && event.message.contains(&state.id)
18433                    && event.message.contains(&reason)
18434            }));
18435            assert_eq!(
18436                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
18437                sidecar
18438            );
18439        }
18440    }
18441
18442    #[tokio::test]
18443    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
18444        ask_test_home();
18445        let tmp = tempfile::tempdir().unwrap();
18446        let repo = tmp.path().join("repo");
18447        std::fs::create_dir(&repo).unwrap();
18448        init_repo(&repo);
18449        let mut runner = runner_at(RunStatus::Implementing);
18450        runner.state.repo = repo.clone();
18451        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18452        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18453        for (index, label) in ['A', 'B'].into_iter().enumerate() {
18454            let branch = format!("candidate-{label}");
18455            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
18456            git::worktree_add_branch(&repo, &wt, &branch, "main")
18457                .await
18458                .unwrap();
18459            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
18460            git::git(&wt, &["add", "README.md"]).await.unwrap();
18461            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
18462            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
18463            runner.state.candidates.push(Candidate {
18464                index,
18465                label,
18466                agent: "alpha".to_owned(),
18467                branch,
18468                worktree: wt,
18469                summary: "completed implementation".to_owned(),
18470                stat: String::new(),
18471                files: 0,
18472                commits: 0,
18473                empty: false,
18474                failed: None,
18475                verified_noop: None,
18476                duration_ms: 42,
18477                folded: false,
18478            });
18479            runner
18480                .state
18481                .candidate_preservation
18482                .insert(label, "awaiting persistence".to_owned());
18483        }
18484        let wt = runner.state.candidates[0].worktree.clone();
18485        let index_lock = git::git(
18486            &wt,
18487            &[
18488                "rev-parse",
18489                "--path-format=absolute",
18490                "--git-path",
18491                "index.lock",
18492            ],
18493        )
18494        .await
18495        .unwrap();
18496        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18497        runner.state.save().unwrap();
18498        assert!(runner.persist_candidates().await.is_err());
18499        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18500        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
18501        assert_eq!(
18502            runner.state.candidates[1].commits, 1,
18503            "other results are still collected"
18504        );
18505        assert!(
18506            !runner.state.candidates[0].empty,
18507            "failed rescue is not no change"
18508        );
18509        assert_eq!(
18510            runner.state.candidates[0].summary,
18511            "completed implementation"
18512        );
18513        assert!(runner.after_implement().is_err());
18514        // The record the fold locks is the one on disk, so the arrangement is
18515        // saved first; the refusal asserted is the preservation rule's own,
18516        // never `record gone`.
18517        runner.state.save().unwrap();
18518        let refusal = fold_run(&mut runner.state, true, &crate::run::home())
18519            .await
18520            .unwrap_err();
18521        assert!(
18522            matches!(
18523                refusal.downcast_ref::<FoldRefusal>(),
18524                Some(FoldRefusal::ProofIncomplete(detail))
18525                    if detail.contains("candidate preservation incomplete")
18526            ),
18527            "{refusal:#}"
18528        );
18529        assert!(wt.join("new-file").exists());
18530        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
18531        assert!(recovery.join("staged.patch").exists());
18532        assert!(recovery.join("unstaged.patch").exists());
18533        assert_eq!(
18534            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
18535            "untracked edits\n"
18536        );
18537        runner.state.begin_pass();
18538        runner.state.end_pass_parked(ParkCause::Upgrade {
18539            from: "1.0".into(),
18540            to: Some("1.1".into()),
18541        });
18542        runner.state.save().unwrap();
18543        runner.state = RunState::load(&runner.state.id).unwrap();
18544        assert!(matches!(
18545            runner.state.passes.last().unwrap().end,
18546            Some(crate::run::PassEnd::Parked {
18547                cause: ParkCause::Upgrade { .. }
18548            })
18549        ));
18550        std::fs::remove_file(index_lock).unwrap();
18551        // No implementer is configured: a persistence retry cannot dispatch a seat.
18552        runner.implement().await.unwrap();
18553        assert!(runner.state.candidate_preservation.is_empty());
18554        assert!(
18555            runner
18556                .state
18557                .candidates
18558                .iter()
18559                .all(|c| c.commits == 1 && !c.empty)
18560        );
18561        assert!(git::is_clean(&wt).await.unwrap());
18562        assert!(
18563            crate::run::read_artifact(&runner.state, "cand-A.patch")
18564                .unwrap()
18565                .contains("later tracked edits")
18566        );
18567    }
18568
18569    #[tokio::test]
18570    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
18571        ask_test_home();
18572        let tmp = tempfile::tempdir().unwrap();
18573        let repo = tmp.path().join("repo");
18574        std::fs::create_dir(&repo).unwrap();
18575        init_repo(&repo);
18576        let wt = tmp.path().join("candidate");
18577        git::worktree_add_branch(&repo, &wt, "candidate", "main")
18578            .await
18579            .unwrap();
18580        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18581        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
18582        assert!(wt.join("uncommitted").exists());
18583        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18584        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18585        let mut runner = runner_at(RunStatus::Implementing);
18586        runner.state.repo = repo.clone();
18587        runner.state.base_commit = "missing-base".to_owned();
18588        runner.state.candidates.push(Candidate {
18589            index: 0,
18590            label: 'A',
18591            agent: "alpha".into(),
18592            branch: "candidate".into(),
18593            worktree: wt.clone(),
18594            summary: "completed".into(),
18595            stat: String::new(),
18596            files: 0,
18597            commits: 0,
18598            empty: false,
18599            failed: None,
18600            verified_noop: None,
18601            duration_ms: 1,
18602            folded: false,
18603        });
18604        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18605        // Saved in the home the fold uses: without a record the fold would
18606        // refuse as `record gone` and say nothing about the dirty tree.
18607        let home = tmp.path().join("home");
18608        runner.state.save_under(&home).unwrap();
18609        let refusal = fold_run(&mut runner.state, true, &home).await.unwrap_err();
18610        assert!(
18611            refusal
18612                .to_string()
18613                .contains("worktree has uncommitted work; refusing removal"),
18614            "{refusal:#}"
18615        );
18616        assert!(refusal.downcast_ref::<FoldRefusal>().is_none());
18617        assert!(!runner.state.candidates[0].folded);
18618        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18619        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18620        runner
18621            .state
18622            .candidate_preservation
18623            .insert('A', "pending".into());
18624        assert!(runner.persist_candidates().await.is_err());
18625        assert!(!runner.state.candidates[0].empty);
18626        assert!(!runner.state.candidates[0].folded);
18627        assert!(wt.exists());
18628        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18629        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18630        std::fs::create_dir_all(&patch_path).unwrap();
18631        assert!(
18632            runner.persist_candidates().await.is_err(),
18633            "artifact failure stays pending"
18634        );
18635        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18636        assert!(!runner.state.candidates[0].empty);
18637        std::fs::remove_dir(patch_path).unwrap();
18638        runner.persist_candidates().await.unwrap();
18639        assert!(
18640            runner.state.candidates[0].empty,
18641            "only successful inspection confirms no change"
18642        );
18643    }
18644
18645    fn init_repo(dir: &Path) {
18646        let run = |args: &[&str]| {
18647            let out = std::process::Command::new("git")
18648                .args(args)
18649                .current_dir(dir)
18650                .quiet()
18651                .output()
18652                .expect("spawn git");
18653            assert!(
18654                out.status.success(),
18655                "git {args:?} failed: {}",
18656                String::from_utf8_lossy(&out.stderr)
18657            );
18658        };
18659        run(&["init", "-b", "main"]);
18660        run(&["config", "user.name", "magi test"]);
18661        run(&["config", "user.email", "magi@example.com"]);
18662        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18663        run(&["add", "-A"]);
18664        run(&["commit", "-m", "init"]);
18665    }
18666
18667    // `settle_questions` is what closes the ghost the phone showed: a run's
18668    // seat asked something, the run then ended, and nothing was left to
18669    // abandon the question it left `open`. `HOME` is a process-wide
18670    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18671    // first time it runs in the binary — every test below still reaches the
18672    // same directory whichever call won, and each gets its own run id from
18673    // `RunState::new`, so they never collide there.
18674    fn ask_test_home() {
18675        crate::run::pin_test_home();
18676    }
18677
18678    #[test]
18679    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18680        ask_test_home();
18681        let mut runner = runner_at(RunStatus::Prep);
18682        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18683        // A blocked temporary output path makes the terminal save fail while
18684        // preserving the already published reservation.
18685        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18686        let error = guard
18687            .finish(
18688                &mut runner.state,
18689                Err(
18690                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18691                        .into(),
18692                ),
18693            )
18694            .unwrap_err();
18695        assert_eq!(
18696            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18697            std::io::ErrorKind::PermissionDenied
18698        );
18699        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18700        let message = format!("{error:#}");
18701        assert!(message.contains("original refusal"));
18702        assert!(!message.contains("could not save terminal"));
18703        assert_eq!(
18704            error.chain().count(),
18705            2,
18706            "only startup attribution wraps the original error"
18707        );
18708        let saved = RunState::load(&runner.state.id).unwrap();
18709        assert_eq!(saved.status, RunStatus::Blocked);
18710        assert!(!saved.startup.unwrap().complete);
18711    }
18712
18713    #[test]
18714    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18715        ask_test_home();
18716        let mut runner = runner_at(RunStatus::Prep);
18717        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18718        let id = runner.state.id.clone();
18719        drop(guard);
18720        let saved = RunState::load(&id).unwrap();
18721        assert_eq!(saved.status, RunStatus::Blocked);
18722        assert!(!saved.startup.as_ref().unwrap().complete);
18723        assert!(
18724            saved
18725                .startup
18726                .unwrap()
18727                .failure
18728                .unwrap()
18729                .contains("interrupted")
18730        );
18731        assert!(Runner::resume(&id).is_err());
18732    }
18733
18734    #[test]
18735    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18736        ask_test_home();
18737        let mut runner = runner_at(RunStatus::Prep);
18738        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18739        let error = guard
18740            .finish(
18741                &mut runner.state,
18742                Err(
18743                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18744                        .into(),
18745                ),
18746            )
18747            .unwrap_err();
18748        assert_eq!(
18749            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18750            std::io::ErrorKind::PermissionDenied
18751        );
18752        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18753        let mut task = crate::queue::Task::new(
18754            "review".into(),
18755            "criteria".into(),
18756            runner.state.repo.clone(),
18757            crate::queue::Source::Human,
18758        );
18759        task.record_startup_failure(failure.clone());
18760        task.record_startup_failure(failure.clone());
18761        assert_eq!(task.startup_failures.len(), 1);
18762        assert!(task.runs.is_empty());
18763        assert_eq!(task.attempts, 0);
18764    }
18765
18766    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18767        ask_test_home();
18768        let tmp = tempfile::tempdir().unwrap();
18769        let repo = tmp.path().join("repo");
18770        std::fs::create_dir(&repo).unwrap();
18771        init_repo(&repo);
18772        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18773        let origin = tmp.path().join("origin.git");
18774        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18775            .await
18776            .unwrap();
18777        git::git(
18778            &repo,
18779            &["remote", "add", "origin", origin.to_str().unwrap()],
18780        )
18781        .await
18782        .unwrap();
18783        git::git(&repo, &["checkout", "-b", "fix/retained"])
18784            .await
18785            .unwrap();
18786        std::fs::write(repo.join("retained"), "retained change").unwrap();
18787        git::git(&repo, &["add", "."]).await.unwrap();
18788        git::git(&repo, &["commit", "-m", "retained implementation"])
18789            .await
18790            .unwrap();
18791        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18792        git::git(&repo, &["checkout", "main"]).await.unwrap();
18793        std::fs::write(repo.join("base-change"), "new base").unwrap();
18794        git::git(&repo, &["add", "."]).await.unwrap();
18795        git::git(&repo, &["commit", "-m", "base moved"])
18796            .await
18797            .unwrap();
18798        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18799        git::git(&repo, &["checkout", "fix/retained"])
18800            .await
18801            .unwrap();
18802        let mut runner = runner_at(RunStatus::Voting);
18803        runner.state.repo = repo.clone();
18804        runner.state.base_commit = base;
18805        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18806        runner.state.config.disk.min_free_bytes = 0;
18807        runner.state.config.graph.review_rounds = 1;
18808        runner.state.config.verify.e2e = vec!["true".into()];
18809        runner.state.config.verify.gate = vec!["true".into()];
18810        runner.state.candidates = vec![Candidate {
18811            index: 0,
18812            label: 'A',
18813            agent: "fixture".into(),
18814            branch: "fix/retained".into(),
18815            worktree: repo.clone(),
18816            summary: String::new(),
18817            stat: String::new(),
18818            files: 1,
18819            commits: 1,
18820            empty: false,
18821            failed: None,
18822            verified_noop: None,
18823            duration_ms: 0,
18824            folded: false,
18825        }];
18826        runner.state.tally = Some(Tally {
18827            first_choice: BTreeMap::new(),
18828            borda: BTreeMap::new(),
18829            winner: 'A',
18830            rankings: 0,
18831            unanimous_initial: true,
18832            deliberated: false,
18833            changed_votes: 0,
18834            unanimous_final: true,
18835            tie_break: None,
18836            judges: 0,
18837            present: 0,
18838            quorum: 0,
18839            met_quorum: true,
18840            uncontested: Some("review-only".into()),
18841        });
18842        let mut task = crate::queue::Task::new(
18843            "fixture".into(),
18844            "fixture".into(),
18845            repo,
18846            crate::queue::Source::Human,
18847        );
18848        task.link_run(&runner.state.id);
18849        crate::queue::Queue::open().put(&mut task).unwrap();
18850        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18851        runner.state.base_sync = Some(BaseSync {
18852            tip: String::new(),
18853            behind: 1,
18854            attempts: BASE_SYNC_ROUNDS,
18855            conflict: None,
18856            already_in: None,
18857        });
18858        runner.sync_to_base().await.unwrap();
18859        assert_eq!(runner.state.status, RunStatus::Blocked);
18860        (tmp, runner, head, task.id)
18861    }
18862
18863    #[tokio::test]
18864    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18865        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18866        runner.state.status = RunStatus::Voting;
18867        runner.state.base_sync = None;
18868        runner.state.base_sync_recovery = Default::default();
18869        let scratch = runner.state.dir().join("base-sync");
18870        std::fs::create_dir_all(&scratch).unwrap();
18871        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18872        runner.sync_to_base().await.unwrap();
18873        assert!(runner.state.resource_block.is_some());
18874        assert!(!runner.state.base_sync_blocked());
18875        assert!(runner.state.base_sync.is_none());
18876        assert_eq!(
18877            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18878            "keep"
18879        );
18880        assert_eq!(runner.state.base_episode_used(), 0);
18881        assert!(runner.state.base_sync_recovery.operations.is_empty());
18882        assert!(runner.state.rebase_fixes.is_empty());
18883        assert_eq!(
18884            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18885            head
18886        );
18887        std::fs::remove_dir_all(&scratch).unwrap();
18888        runner.state.resource_block = None;
18889        runner.sync_to_base().await.unwrap();
18890        assert!(!runner.state.base_sync_blocked());
18891        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18892        assert_eq!(runner.state.base_episode_used(), 1);
18893        assert!(runner.state.base_sync_recovery.operations[0].finished);
18894        assert!(runner.state.rebase_fixes.is_empty());
18895        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18896        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18897    }
18898
18899    #[tokio::test]
18900    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18901        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18902        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18903        runner.state.base_sync_recovery = Default::default();
18904        runner.state.task_instruction = Some("fixture".into());
18905        runner.state.config.agents = vec![spec("fixture")];
18906        runner.state.config.graph.review_rounds = 0;
18907        runner.state.config.merge.mode = MergeMode::None;
18908        runner.state.driver_exited = true;
18909        let sync = runner.state.base_sync.as_mut().unwrap();
18910        sync.conflict = None;
18911        sync.attempts = 0;
18912        runner.state.reserve_base_operation(&head, &tip);
18913        runner.state.finish_base_operation(None);
18914        let detail = format!(
18915            "fix/retained conflicts with origin/main and did not rebase: \
18916             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18917             remaining conflicted path(s): none recorded; git said: \
18918             warning: execution failed: {}",
18919            git::REBASE_EXEC
18920        );
18921        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18922        runner.state.record_base_sync_stop(&head);
18923        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18924            unstarted: false,
18925            agent: "fixture".into(),
18926            paths: Vec::new(),
18927            from: Some(head.clone()),
18928            finished: true,
18929            error: None,
18930            stop: None,
18931            onto: None,
18932            index_outside: None,
18933            launcher: None,
18934            infra: None,
18935            outage: None,
18936        });
18937        runner.state.save().unwrap();
18938        assert_eq!(
18939            crate::resume::validate(&crate::run::home(), &runner.state.id)
18940                .unwrap()
18941                .id,
18942            runner.state.id
18943        );
18944
18945        let dirty = runner.state.repo.join("owner-work");
18946        std::fs::write(&dirty, "keep").unwrap();
18947        runner.sync_to_base().await.unwrap();
18948        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18949        assert!(runner.state.base_sync_recovery.operations[0].finished);
18950        assert!(runner.state.base_sync_blocked());
18951        std::fs::remove_file(dirty).unwrap();
18952
18953        let queue = crate::queue::Queue::open();
18954        let id = runner.state.id.clone();
18955        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18956        let _claim = queue.claim(&owner).unwrap();
18957        let mut task = queue.get(&owner).unwrap();
18958        let config = tmp.path().join("test-config.toml");
18959        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18960        let opts = crate::daemon::Opts {
18961            repo: task.repo.clone(),
18962            config: Some(config),
18963            ..Default::default()
18964        };
18965        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18966        let task = queue.get(&owner).unwrap();
18967        assert_eq!(
18968            task.runs.as_slice(),
18969            std::slice::from_ref(&id),
18970            "{:?}",
18971            task.hold_reason
18972        );
18973        runner.state = RunState::load(&id).unwrap();
18974        assert!(!runner.state.base_sync_blocked());
18975        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18976        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18977        assert!(runner.state.base_sync_recovery.operations[0].finished);
18978        assert_eq!(
18979            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18980            detail
18981        );
18982        assert_eq!(runner.state.rebase_fixes.len(), 1);
18983        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18984    }
18985
18986    #[cfg(unix)]
18987    #[tokio::test]
18988    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18989        for routed in [false, true] {
18990            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18991            let home = crate::run::home();
18992            let queue = crate::queue::Queue::open();
18993            let task = queue.get(&owner).unwrap();
18994            runner.state.task_instruction = Some(task.instruction.clone());
18995            runner.state.driver_exited = true;
18996            runner.state.save().unwrap();
18997            let questions = crate::ask::Questions::at(home.join("questions"));
18998            let mut q = crate::ask::Question::new(
18999                runner.state.id.clone(),
19000                "base-recovery".into(),
19001                "owner".into(),
19002                "Recover bounded base movement?".into(),
19003                String::new(),
19004                vec!["recover".into()],
19005            );
19006            q.actions.insert(
19007                "recover".into(),
19008                crate::ask::ChoiceAction::RecoverBase {
19009                    run: runner.state.id.clone(),
19010                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
19011                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
19012                },
19013            );
19014            q.routed_task = Some(owner.clone());
19015            q.answer(crate::ask::Answer::Choice("recover".into()))
19016                .unwrap();
19017            questions.put(&mut q).unwrap();
19018            crate::base_recovery_control::recover(
19019                &queue,
19020                &home,
19021                crate::base_recovery_control::Request {
19022                    run: runner.state.id.clone(),
19023                    head: head.clone(),
19024                    actor: "decisions".into(),
19025                    request: q.id.clone(),
19026                    decision: Some((owner.clone(), q.answered_at.unwrap())),
19027                    expected_stop: Some((
19028                        runner.state.base_sync_recovery.stop.clone().unwrap(),
19029                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
19030                    )),
19031                    evidence_digest: None,
19032                },
19033            )
19034            .await
19035            .unwrap();
19036            if routed {
19037                questions
19038                    .update(&q.id, |q| {
19039                        q.routed_task = Some("another-owner".into());
19040                        Ok(())
19041                    })
19042                    .unwrap();
19043            } else {
19044                let mut task = queue.get(&owner).unwrap();
19045                task.hold_manual(Some("new owner decision".into()));
19046                // Keep the generation to exercise the separate owner-decision binding.
19047                task.status = crate::queue::TaskStatus::Queued;
19048                queue.put(&mut task).unwrap();
19049            }
19050            runner.state = RunState::load(&runner.state.id).unwrap();
19051            runner.sync_to_base().await.unwrap();
19052            let approval = runner
19053                .state
19054                .base_sync_recovery
19055                .authorizations
19056                .last()
19057                .unwrap();
19058            assert!(approval.consumed);
19059            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
19060                "routing"
19061            } else {
19062                "owner decision"
19063            }));
19064            assert_eq!(
19065                runner.state.base_sync.as_ref().unwrap().attempts,
19066                BASE_SYNC_ROUNDS
19067            );
19068            assert_eq!(
19069                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19070                head
19071            );
19072        }
19073    }
19074
19075    #[cfg(unix)]
19076    #[tokio::test]
19077    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
19078        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
19079        if std::env::var_os(CHILD).is_none() {
19080            let home = tempfile::tempdir().unwrap();
19081            let output = std::process::Command::new(std::env::current_exe().unwrap())
19082                .args([
19083                    "--exact",
19084                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
19085                    "--nocapture",
19086                ])
19087                .env(CHILD, "1")
19088                .env("MAGI_HOME", home.path())
19089                .env("MAGI_WORKER_HOME", home.path())
19090                .env("MAGI_WORKER_ID", "abcdef")
19091                .output()
19092                .unwrap();
19093            assert!(
19094                output.status.success()
19095                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19096                "{}\n{}",
19097                String::from_utf8_lossy(&output.stdout),
19098                String::from_utf8_lossy(&output.stderr)
19099            );
19100            return;
19101        }
19102        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
19103        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19104        let home = crate::run::home();
19105        let queue = crate::queue::Queue::open();
19106        let mut owner = queue.get(&task).unwrap();
19107        owner.release_operator("test-release", None);
19108        owner.start(runner.state.id.clone());
19109        queue.put(&mut owner).unwrap();
19110        runner.state.driver_exited = true;
19111        runner.state.task_instruction = Some(owner.instruction.clone());
19112        runner.state.save().unwrap();
19113        let _claim = queue.claim(&task).unwrap();
19114        let reserve = |id: &str| {
19115            let directory = home.join("workers/jobs").join(id);
19116            std::fs::create_dir_all(&directory).unwrap();
19117            let job = crate::worker::Job {
19118                id: id.into(),
19119                sequence: 1,
19120                kind: "task".into(),
19121                key: format!("task:{task}"),
19122                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
19123                generation: "fixture-generation".into(),
19124                version: None,
19125                status: crate::worker::Status::Running,
19126                result: None,
19127                pid: Some(std::process::id()),
19128                created_at: 0,
19129                finished_at: None,
19130            };
19131            std::fs::write(
19132                directory.join("job.json"),
19133                serde_json::to_vec(&job).unwrap(),
19134            )
19135            .unwrap();
19136            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
19137        };
19138        let _own = reserve("abcdef");
19139        let other = reserve("fedcba");
19140        assert!(
19141            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19142                .await
19143                .is_err()
19144        );
19145        assert!(
19146            RunState::load(&runner.state.id)
19147                .unwrap()
19148                .base_sync_recovery
19149                .authorizations
19150                .is_empty()
19151        );
19152        drop(other);
19153        assert!(crate::daemon::is_working_on(
19154            &home,
19155            &runner.state.id,
19156            Timestamp::now()
19157        ));
19158        assert!(
19159            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
19160        );
19161        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19162            .await
19163            .unwrap();
19164        assert!(
19165            RunState::load(&runner.state.id)
19166                .unwrap()
19167                .base_recovery_pending()
19168        );
19169    }
19170
19171    #[cfg(unix)]
19172    #[tokio::test]
19173    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
19174        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19175        let home = crate::run::home();
19176        runner.state.driver_pid = Some(std::process::id());
19177        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
19178        runner.state.driver_exited = false;
19179        runner.state.begin_pass();
19180        runner.state.save().unwrap();
19181        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
19182        driver.record(&runner.state).unwrap();
19183        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
19184        // Preserve the durable claim as if the process died before Drop saved.
19185        drop(driver);
19186        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
19187        assert_eq!(
19188            runner.state.liveness_under(&home, false),
19189            crate::run::Liveness::Dead
19190        );
19191        let queue = crate::queue::Queue::open();
19192        let _claim = queue.claim(&task).unwrap();
19193        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19194            .await
19195            .unwrap();
19196        let disk = RunState::load(&runner.state.id).unwrap();
19197        assert!(!disk.driver_exited);
19198        assert!(disk.base_recovery_pending());
19199    }
19200
19201    #[cfg(unix)]
19202    #[tokio::test]
19203    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
19204        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
19205        if std::env::var_os(CHILD).is_none() {
19206            use std::os::unix::fs::PermissionsExt;
19207            let tmp = tempfile::tempdir().unwrap();
19208            let gh = tmp.path().join("gh");
19209            std::fs::write(&gh, r#"#!/bin/sh
19210case "$1 $2" in
19211  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
19212  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
19213  *) exit 2 ;;
19214esac
19215"#).unwrap();
19216            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
19217            let mut paths = vec![tmp.path().to_path_buf()];
19218            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
19219            let output = std::process::Command::new(std::env::current_exe().unwrap())
19220                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
19221                .env(CHILD, "1")
19222                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
19223                .env("PATH", std::env::join_paths(paths).unwrap())
19224                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
19225                .output().unwrap();
19226            assert!(
19227                output.status.success()
19228                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19229                "{}\n{}",
19230                String::from_utf8_lossy(&output.stdout),
19231                String::from_utf8_lossy(&output.stderr)
19232            );
19233            return;
19234        }
19235        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19236        let repo = runner.state.repo.clone();
19237        git::git(&repo, &["checkout", "main"]).await.unwrap();
19238        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
19239        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19240        git::git(&repo, &["checkout", "fix/retained"])
19241            .await
19242            .unwrap();
19243        runner.state.pr = Some(crate::run::PrRecord {
19244            url: "https://example.test/project/pull/1".into(),
19245            number: 1,
19246            state: "open".into(),
19247            checks: "unknown".into(),
19248            round: 0,
19249            rounds: 1,
19250            red_at_merge: Vec::new(),
19251        });
19252        runner.sync_to_base().await.unwrap();
19253        assert_eq!(runner.state.status, RunStatus::Blocked);
19254        assert_eq!(
19255            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19256            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
19257        );
19258        assert!(runner.state.base_sync_closure_pending());
19259        assert!(crate::handover::can_resume(&runner.state));
19260        let queue = crate::queue::Queue::open();
19261        assert!(!crate::base_sync_recovery::held_task(
19262            &queue,
19263            &queue.get(&task).unwrap()
19264        ));
19265        assert!(runner.state.authorize_base_sync(&task).is_err());
19266        // Legacy closure stops have no typed stop but must retain the checkpoint.
19267        runner.state.base_sync_recovery.stop = None;
19268        runner.state.status = RunStatus::Voting;
19269        runner.state.gate_ran = true;
19270        runner.state.config.graph.review_rounds = 0;
19271        runner.state.save().unwrap();
19272        assert!(crate::handover::can_resume(&runner.state));
19273        runner.state = RunState::load(&runner.state.id).unwrap();
19274        runner.execute_graph().await.unwrap();
19275        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
19276        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
19277        assert_eq!(
19278            runner.state.base_sync.as_ref().unwrap().attempts,
19279            BASE_SYNC_ROUNDS
19280        );
19281        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
19282        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
19283        assert!(runner.state.reviews.is_empty());
19284        assert!(runner.state.gate.is_empty());
19285    }
19286
19287    #[cfg(unix)]
19288    #[tokio::test]
19289    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
19290        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19291        runner.state.driver_exited = true;
19292        runner.state.save().unwrap();
19293        let home = crate::run::home();
19294        let queue = crate::queue::Queue::open();
19295        let _claim = queue.claim(&task).unwrap();
19296        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
19297        assert!(
19298            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19299                .await
19300                .is_err()
19301        );
19302        drop(lease);
19303        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
19304        assert!(
19305            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19306                .await
19307                .is_err()
19308        );
19309        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
19310        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19311            .await
19312            .unwrap();
19313        let disk = RunState::load(&runner.state.id).unwrap();
19314        assert!(disk.base_recovery_pending());
19315        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
19316        assert!(
19317            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19318                .await
19319                .is_err()
19320        );
19321        assert_eq!(
19322            RunState::load(&runner.state.id)
19323                .unwrap()
19324                .base_sync_recovery
19325                .authorizations
19326                .len(),
19327            1
19328        );
19329        let mut owner = queue.get(&task).unwrap();
19330        owner.runs.push("20260101-000000-ffff".into());
19331        queue.put(&mut owner).unwrap();
19332        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19333            .await
19334            .unwrap_err();
19335        assert!(error.to_string().contains("run task ownership changed"));
19336    }
19337
19338    #[cfg(unix)]
19339    #[tokio::test]
19340    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
19341        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19342        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19343        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
19344        legacy["status"] = serde_json::json!("voting");
19345        runner.state = serde_json::from_value(legacy).unwrap();
19346        runner.state.save().unwrap();
19347        for _ in 0..3 {
19348            runner.execute_graph().await.unwrap();
19349            assert_eq!(runner.state.status, RunStatus::Blocked);
19350            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19351            assert!(!crate::handover::can_resume(&runner.state));
19352            assert_eq!(
19353                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19354                head
19355            );
19356            assert!(runner.state.reviews.is_empty());
19357            assert!(!runner.state.gate_ran);
19358        }
19359        let notice = crate::notices::run_ended(&runner.state).unwrap();
19360        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
19361        runner.state.begin_pass();
19362        runner.state.status = RunStatus::Voting;
19363        runner.deliberate().await.unwrap();
19364        runner.vote().await.unwrap();
19365        runner.finish_after_tally().await.unwrap();
19366        assert_eq!(runner.state.status, RunStatus::Blocked);
19367        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
19368        assert_eq!(
19369            crate::notices::run_ended(&runner.state).unwrap().since,
19370            notice.since
19371        );
19372    }
19373
19374    #[cfg(unix)]
19375    #[tokio::test]
19376    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
19377        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19378        for detail in [
19379            "fix/retained conflicts with origin/main and did not rebase: conflict",
19380            "rebased fix/retained locally but origin refused the push",
19381            "unknown failure",
19382        ] {
19383            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
19384            runner.state.record_base_sync_stop(&head);
19385            assert!(runner.state.authorize_base_sync(&task).is_err());
19386            runner.state.status = RunStatus::Voting;
19387            runner.execute_graph().await.unwrap();
19388            assert_eq!(runner.state.status, RunStatus::Blocked);
19389            assert!(!crate::handover::can_resume(&runner.state));
19390            assert_eq!(
19391                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19392                head
19393            );
19394        }
19395    }
19396
19397    #[tokio::test]
19398    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
19399        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19400        let state = &mut runner.state;
19401        let tip = state.base_sync.as_ref().unwrap().tip.clone();
19402        let branch = state.winner().unwrap().branch.clone();
19403        state.base_sync_recovery = Default::default();
19404        state.base_sync.as_mut().unwrap().attempts = 0;
19405        state.reserve_base_operation(&head, &tip);
19406        state.finish_base_operation(None);
19407        let detail = format!(
19408            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
19409        );
19410        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
19411        state.event("land", detail);
19412        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
19413        assert!(state.unknown_preparation_stop(&head));
19414        let digest = state.preparation_digest(&head).unwrap();
19415        state
19416            .base_sync_recovery
19417            .operations
19418            .last_mut()
19419            .unwrap()
19420            .validated_head = Some(head.clone());
19421        assert!(!state.unknown_preparation_stop(&head));
19422        state
19423            .base_sync_recovery
19424            .operations
19425            .last_mut()
19426            .unwrap()
19427            .validated_head = None;
19428        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
19429        state.driver_exited = true;
19430        state.save().unwrap();
19431        let home = crate::run::home();
19432        let queue = crate::queue::Queue::open();
19433        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
19434            .await
19435            .unwrap();
19436        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
19437        assert_eq!(inspection["evidence_digest"], digest);
19438        let request = crate::base_recovery_control::Request {
19439            run: state.id.clone(),
19440            head: head.clone(),
19441            actor: "test".into(),
19442            request: "preparation".into(),
19443            decision: None,
19444            expected_stop: None,
19445            evidence_digest: Some(digest),
19446        };
19447        let mut stale = request.clone();
19448        stale.evidence_digest = Some("stale".into());
19449        assert!(
19450            crate::base_recovery_control::recover(&queue, &home, stale)
19451                .await
19452                .is_err()
19453        );
19454        let scratch = state.dir().join("base-sync");
19455        std::fs::create_dir(&scratch).unwrap();
19456        assert!(
19457            crate::base_recovery_control::recover(&queue, &home, request.clone())
19458                .await
19459                .is_err()
19460        );
19461        std::fs::remove_dir(&scratch).unwrap();
19462        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
19463        git::git(
19464            &state.repo,
19465            &[
19466                "commit",
19467                "--allow-empty",
19468                "-m",
19469                "base advanced after inspection",
19470            ],
19471        )
19472        .await
19473        .unwrap();
19474        git::git(&state.repo, &["push", "origin", "main"])
19475            .await
19476            .unwrap();
19477        git::git(&state.repo, &["checkout", "fix/retained"])
19478            .await
19479            .unwrap();
19480        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
19481            .await
19482            .unwrap();
19483        assert!(!outcome.repeated);
19484        assert!(
19485            crate::base_recovery_control::recover(&queue, &home, request)
19486                .await
19487                .unwrap()
19488                .repeated
19489        );
19490        runner.state = RunState::load(&runner.state.id).unwrap();
19491        assert!(runner.state.base_recovery_pending());
19492        runner.sync_to_base().await.unwrap();
19493        assert!(!runner.state.base_sync_blocked());
19494        assert!(!runner.state.consume_base_recovery(&head));
19495        assert_eq!(runner.state.base_episode_used(), 2);
19496        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19497        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19498        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
19499    }
19500
19501    #[cfg(unix)]
19502    #[tokio::test]
19503    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
19504        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19505        runner.state.authorize_base_sync(&task).unwrap();
19506        assert!(runner.state.consume_base_recovery(&head));
19507        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19508        runner.state.reserve_base_operation(&head, &tip);
19509        runner.state.save().unwrap();
19510        runner.state = RunState::load(&runner.state.id).unwrap();
19511        assert!(!runner.state.consume_base_recovery(&head));
19512        runner.sync_to_base().await.unwrap();
19513        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19514        assert_eq!(runner.state.base_episode_used(), 1);
19515        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19516        assert!(
19517            runner
19518                .state
19519                .base_sync_recovery
19520                .operations
19521                .last()
19522                .unwrap()
19523                .finished
19524        );
19525        assert!(!runner.state.base_sync_blocked());
19526        runner.sync_to_base().await.unwrap();
19527        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19528    }
19529
19530    #[cfg(unix)]
19531    #[tokio::test]
19532    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
19533        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19534        // Both historical diagnostic spellings retain an exhaustion identity.
19535        let original = runner
19536            .state
19537            .base_sync
19538            .as_ref()
19539            .unwrap()
19540            .conflict
19541            .clone()
19542            .unwrap();
19543        runner.state.base_sync.as_mut().unwrap().conflict = Some(
19544            original
19545                .replace("synchronization(s)", "rebase(s)")
19546                .replace("synchronizing", "rebasing"),
19547        );
19548        runner.state.base_sync_recovery = Default::default();
19549        runner.state.record_base_sync_stop(&head);
19550        assert_eq!(
19551            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19552            crate::base_sync_recovery::StopKind::Exhausted
19553        );
19554        runner.state.authorize_base_sync(&task).unwrap();
19555        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19556        let auth = legacy["base_sync_recovery"]["authorizations"][0]
19557            .as_object_mut()
19558            .unwrap();
19559        auth.remove("interval");
19560        auth.remove("scope");
19561        runner.state = serde_json::from_value(legacy).unwrap();
19562        assert!(runner.state.consume_base_recovery(&head));
19563        assert_eq!(runner.state.base_episode_used(), 3);
19564        runner.sync_to_base().await.unwrap();
19565        assert_eq!(runner.state.base_episode_used(), 4);
19566        runner.state.resource_block = Some(crate::run::ResourceBlock {
19567            node: "gate".into(),
19568            kind: "cache".into(),
19569            detail: "legacy wait".into(),
19570            at: Timestamp::now(),
19571            cause: crate::run::ResourceBlockCause::Unrecorded,
19572        });
19573        runner.state.save().unwrap();
19574        assert!(
19575            runner
19576                .state
19577                .base_sync_recovery
19578                .episodes
19579                .last()
19580                .unwrap()
19581                .boundary
19582                .is_none()
19583        );
19584        runner.state.resource_block = None;
19585        advance_base_fixture(&runner).await;
19586        runner.sync_to_base().await.unwrap();
19587        assert!(runner.state.base_sync_blocked());
19588        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19589    }
19590
19591    #[cfg(unix)]
19592    async fn advance_base_fixture(runner: &Runner) {
19593        let repo = &runner.state.repo;
19594        for args in [
19595            vec!["checkout", "main"],
19596            vec!["commit", "--allow-empty", "-m", "base advanced"],
19597            vec!["push", "origin", "main"],
19598            vec!["checkout", "fix/retained"],
19599        ] {
19600            git::git(repo, &args).await.unwrap();
19601        }
19602    }
19603
19604    #[cfg(unix)]
19605    fn fresh_base_interval_fixture(runner: &mut Runner) {
19606        runner.state.base_sync.as_mut().unwrap().attempts = 0;
19607        runner.state.base_sync.as_mut().unwrap().conflict = None;
19608        runner.state.base_sync_recovery = Default::default();
19609        runner.state.status = RunStatus::Voting;
19610    }
19611
19612    #[cfg(unix)]
19613    #[tokio::test]
19614    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
19615        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19616        fresh_base_interval_fixture(&mut runner);
19617        runner.state.begin_pass();
19618        runner.sync_to_base().await.unwrap();
19619        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19620        runner.state.resource_block = Some(crate::run::ResourceBlock {
19621            node: "gate".into(),
19622            kind: "build cache".into(),
19623            detail: "busy".into(),
19624            at: Timestamp::now(),
19625            cause: crate::run::ResourceBlockCause::Timeout {
19626                waited_secs: 1,
19627                limit_secs: 1,
19628            },
19629        });
19630        runner.state.save().unwrap();
19631        let queue = crate::queue::Queue::open();
19632        let mut owner = queue.get(&task).unwrap();
19633        runner.state.task_instruction = Some(owner.instruction.clone());
19634        owner.release_operator("fixture-owner", None);
19635        queue.put(&mut owner).unwrap();
19636        let approval = owner.resumption.clone().unwrap();
19637        runner.state.resource_block = None;
19638        runner.state.save().unwrap();
19639        runner.state = RunState::load(&runner.state.id).unwrap();
19640        advance_base_fixture(&runner).await;
19641        runner.sync_to_base().await.unwrap();
19642        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19643        assert_eq!(runner.state.base_episode_used(), 1);
19644        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19645        assert!(
19646            runner.state.base_sync_recovery.episodes[0]
19647                .boundary
19648                .as_ref()
19649                .unwrap()
19650                .consumed
19651        );
19652        assert!(
19653            !runner
19654                .state
19655                .renew_base_episode(&task, &approval, &head, "base")
19656        );
19657        for _ in 0..3 {
19658            owner.release_operator("fixture-owner", None);
19659            queue.put(&mut owner).unwrap();
19660            runner.state = RunState::load(&runner.state.id).unwrap();
19661            runner.state.begin_pass();
19662            runner.sync_to_base().await.unwrap();
19663            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19664            assert_eq!(runner.state.base_episode_used(), 1);
19665        }
19666        runner.state.resource_block = Some(crate::run::ResourceBlock {
19667            node: "gate".into(),
19668            kind: "disk pressure".into(),
19669            detail: "free space required".into(),
19670            at: Timestamp::now(),
19671            cause: crate::run::ResourceBlockCause::Other,
19672        });
19673        runner.state.end_pass_parked(ParkCause::Interrupt {
19674            reason: "disk pressure".into(),
19675        });
19676        runner.state.save().unwrap();
19677        owner.release_operator("fixture-owner-after-disk", None);
19678        queue.put(&mut owner).unwrap();
19679        runner.state.resource_block = None;
19680        advance_base_fixture(&runner).await;
19681        runner.sync_to_base().await.unwrap();
19682        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19683        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19684        assert_eq!(runner.state.base_episode_used(), 1);
19685        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19686    }
19687
19688    #[cfg(unix)]
19689    #[tokio::test]
19690    async fn base_recovery_continuous_advancement_stops_at_four() {
19691        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19692        fresh_base_interval_fixture(&mut runner);
19693        for spent in 1..=BASE_SYNC_ROUNDS {
19694            runner.sync_to_base().await.unwrap();
19695            assert!(!runner.state.base_sync_blocked());
19696            assert_eq!(runner.state.base_episode_used(), spent);
19697            advance_base_fixture(&runner).await;
19698        }
19699        runner.sync_to_base().await.unwrap();
19700        assert_eq!(
19701            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19702            crate::base_sync_recovery::StopKind::Exhausted
19703        );
19704        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19705        assert!(stop.unverified_sync);
19706        let action = runner.state.base_sync_next_action();
19707        assert!(action.contains("never reached its gate"));
19708        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19709        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19710        runner.state = RunState::load(&runner.state.id).unwrap();
19711        runner.sync_to_base().await.unwrap();
19712        assert_eq!(runner.state.base_episode_used(), 4);
19713        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19714    }
19715
19716    #[cfg(unix)]
19717    #[tokio::test]
19718    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19719        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19720        runner.state.ensure_base_episode();
19721        // Verification progress alone is not evidence of a successful sync.
19722        runner.state.record_base_progress(&head);
19723        runner.state.base_sync_recovery.stop = None;
19724        runner.state.record_base_sync_stop(&head);
19725        assert!(
19726            !runner
19727                .state
19728                .base_sync_recovery
19729                .stop
19730                .as_ref()
19731                .unwrap()
19732                .unverified_sync
19733        );
19734
19735        runner.state.finish_base_operation(Some(&head));
19736        // A gate for another head cannot verify this synchronization.
19737        runner.state.gate_ran = true;
19738        runner.state.gate_head = Some("older-head".into());
19739        runner.state.base_sync_recovery.stop = None;
19740        runner.state.record_base_sync_stop(&head);
19741        runner.state.save().unwrap();
19742        runner.state = RunState::load(&runner.state.id).unwrap();
19743        assert!(
19744            runner
19745                .state
19746                .base_sync_recovery
19747                .stop
19748                .as_ref()
19749                .unwrap()
19750                .unverified_sync
19751        );
19752
19753        runner.state.gate_head = Some(head.clone());
19754        runner.state.base_sync_recovery.stop = None;
19755        runner.state.record_base_sync_stop(&head);
19756        assert!(
19757            !runner
19758                .state
19759                .base_sync_recovery
19760                .stop
19761                .as_ref()
19762                .unwrap()
19763                .unverified_sync
19764        );
19765        assert!(
19766            !runner
19767                .state
19768                .base_sync_next_action()
19769                .contains("never reached its gate")
19770        );
19771
19772        // Historical records cannot establish the missing synchronization evidence.
19773        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19774        legacy["base_sync_recovery"]["stop"]
19775            .as_object_mut()
19776            .unwrap()
19777            .remove("unverified_sync");
19778        legacy["base_sync_recovery"]["episodes"][0]
19779            .as_object_mut()
19780            .unwrap()
19781            .remove("last_sync_head");
19782        runner.state = serde_json::from_value(legacy).unwrap();
19783        assert!(
19784            !runner
19785                .state
19786                .base_sync_recovery
19787                .stop
19788                .as_ref()
19789                .unwrap()
19790                .unverified_sync
19791        );
19792        assert!(
19793            runner.state.base_sync_recovery.episodes[0]
19794                .last_sync_head
19795                .is_none()
19796        );
19797    }
19798
19799    #[cfg(unix)]
19800    #[tokio::test]
19801    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19802        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19803        runner.state.authorize_base_sync(&task).unwrap();
19804        assert!(
19805            runner
19806                .state
19807                .base_sync_next_action()
19808                .contains("Approval recorded")
19809        );
19810        assert!(
19811            runner
19812                .state
19813                .base_sync_next_action()
19814                .contains("4/4 in episode 0, 4 lifetime")
19815        );
19816        assert!(runner.state.consume_base_recovery(&head));
19817        assert!(
19818            runner
19819                .state
19820                .base_sync_next_action()
19821                .contains("0/4 in episode 1, 4 lifetime")
19822        );
19823    }
19824
19825    #[cfg(unix)]
19826    #[tokio::test]
19827    async fn base_recovery_changed_head_invalidates_without_spending() {
19828        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19829        runner.state.authorize_base_sync(&task).unwrap();
19830        git::git(
19831            &runner.state.repo,
19832            &["commit", "--allow-empty", "-m", "external head change"],
19833        )
19834        .await
19835        .unwrap();
19836        runner.sync_to_base().await.unwrap();
19837        let a = runner
19838            .state
19839            .base_sync_recovery
19840            .authorizations
19841            .last()
19842            .unwrap();
19843        assert!(a.consumed);
19844        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19845        runner.state = RunState::load(&runner.state.id).unwrap();
19846        assert!(
19847            runner
19848                .state
19849                .base_sync_next_action()
19850                .contains("Approval invalidated")
19851        );
19852        assert!(!runner.state.base_recovery_pending());
19853        assert!(runner.state.base_sync_blocked());
19854        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19855    }
19856
19857    #[cfg(unix)]
19858    #[tokio::test]
19859    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19860        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19861        runner.state.driver_exited = true;
19862        runner.state.save().unwrap();
19863        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19864            .await
19865            .unwrap();
19866        runner.state = RunState::load(&runner.state.id).unwrap();
19867        advance_base_fixture(&runner).await;
19868        runner.sync_to_base().await.unwrap();
19869        let a = runner
19870            .state
19871            .base_sync_recovery
19872            .authorizations
19873            .last()
19874            .unwrap();
19875        assert!(
19876            a.consumed
19877                && a.invalidated
19878                    .as_deref()
19879                    .unwrap()
19880                    .contains("fetched base changed")
19881        );
19882        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19883        assert_eq!(
19884            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19885            head
19886        );
19887        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19888            .await
19889            .unwrap();
19890        runner.state = RunState::load(&runner.state.id).unwrap();
19891        runner.sync_to_base().await.unwrap();
19892        assert!(!runner.state.base_sync_blocked());
19893        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19894    }
19895
19896    #[cfg(unix)]
19897    #[tokio::test]
19898    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19899        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19900        runner.state.authorize_base_sync(&task).unwrap();
19901        assert!(runner.state.consume_base_recovery(&head));
19902        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19903        runner.state.reserve_base_operation(&head, &tip);
19904        runner.state.save().unwrap();
19905        let scratch = runner.state.dir().join("base-sync");
19906        assert_eq!(
19907            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19908                .await
19909                .unwrap(),
19910            crate::rebase::Rebased::Applied
19911        );
19912        runner.state = RunState::load(&runner.state.id).unwrap();
19913        runner.sync_to_base().await.unwrap();
19914        assert!(
19915            runner
19916                .state
19917                .base_sync_recovery
19918                .operations
19919                .last()
19920                .unwrap()
19921                .finished
19922        );
19923        assert_eq!(runner.state.base_episode_used(), 1);
19924        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19925        assert!(!runner.state.base_sync_blocked());
19926    }
19927
19928    #[cfg(unix)]
19929    #[tokio::test]
19930    async fn base_recovery_crash_preserves_untracked_files() {
19931        for ignored in [false, true] {
19932            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19933            runner.state.authorize_base_sync(&task).unwrap();
19934            assert!(runner.state.consume_base_recovery(&head));
19935            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19936            runner.state.reserve_base_operation(&head, &tip);
19937            runner.state.save().unwrap();
19938            let scratch = runner.state.dir().join("base-sync");
19939            assert_eq!(
19940                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19941                    .await
19942                    .unwrap(),
19943                crate::rebase::Rebased::Applied
19944            );
19945            let repo = &runner.state.repo;
19946            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19947            assert_ne!(result, head);
19948            if ignored {
19949                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19950                    .await
19951                    .unwrap();
19952                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19953            }
19954            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19955            assert!(
19956                git::git_raw(repo, &["diff", "--quiet", &head])
19957                    .await
19958                    .unwrap()
19959                    .ok()
19960            );
19961            // Resume after the branch moved, before its checkout was reset.
19962            runner.state = RunState::load(&runner.state.id).unwrap();
19963            runner.sync_to_base().await.unwrap();
19964            assert!(runner.state.base_sync_blocked());
19965            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19966            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19967            assert_eq!(
19968                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19969                result
19970            );
19971            assert_eq!(
19972                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19973                "retained work\n"
19974            );
19975            assert!(
19976                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19977                    .await
19978                    .unwrap()
19979                    .ok()
19980            );
19981        }
19982    }
19983
19984    #[cfg(unix)]
19985    #[tokio::test]
19986    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19987        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19988        runner.state.authorize_base_sync(&task).unwrap();
19989        assert!(runner.state.consume_base_recovery(&head));
19990        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19991        runner.state.reserve_base_operation(&head, &tip);
19992        runner.state.save().unwrap();
19993        let scratch = runner.state.dir().join("base-sync");
19994        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19995            .await
19996            .unwrap();
19997        git::sync_to_head(&runner.state.repo).await.unwrap();
19998        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19999        git::git(&runner.state.repo, &["add", "foreign"])
20000            .await
20001            .unwrap();
20002        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
20003            .await
20004            .unwrap();
20005        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20006        runner.state = RunState::load(&runner.state.id).unwrap();
20007        runner.sync_to_base().await.unwrap();
20008        assert!(runner.state.base_sync_blocked());
20009        assert!(
20010            !runner
20011                .state
20012                .base_sync_recovery
20013                .operations
20014                .last()
20015                .unwrap()
20016                .finished
20017        );
20018        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20019        assert_eq!(
20020            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20021            foreign_head
20022        );
20023    }
20024
20025    #[cfg(unix)]
20026    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
20027    {
20028        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20029        fresh_base_interval_fixture(&mut runner);
20030        let repo = &runner.state.repo;
20031        git::git(repo, &["checkout", "main"]).await.unwrap();
20032        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
20033        git::git(repo, &["add", "retained"]).await.unwrap();
20034        git::git(repo, &["commit", "-m", "upstream retained change"])
20035            .await
20036            .unwrap();
20037        git::git(repo, &["push", "origin", "main"]).await.unwrap();
20038        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
20039        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
20040        let scratch = runner.state.dir().join("base-sync");
20041        assert!(matches!(
20042            git::rebase_start(repo, &scratch, "fix/retained", &tip)
20043                .await
20044                .unwrap(),
20045            git::RebaseStart::Conflicted(_)
20046        ));
20047        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
20048            unstarted: false,
20049            agent: "fixture".into(),
20050            paths: vec!["retained".into()],
20051            from: Some(head.clone()),
20052            onto: None,
20053            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
20054            index_outside: None,
20055            finished: false,
20056            error: None,
20057            launcher: None,
20058            infra: None,
20059            outage: None,
20060        });
20061        (tmp, runner, head, tip, scratch)
20062    }
20063
20064    #[cfg(unix)]
20065    #[tokio::test]
20066    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
20067        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20068        // A resource stop from before reservations existed, with resolved
20069        // contents left for the launcher's ordinary staging continuation.
20070        std::fs::write(
20071            scratch.join("retained"),
20072            "upstream and retained resolution\n",
20073        )
20074        .unwrap();
20075        runner.state.resource_block = Some(crate::run::ResourceBlock {
20076            node: "rebase".into(),
20077            kind: "repository coordination".into(),
20078            detail: "busy".into(),
20079            at: Timestamp::now(),
20080            cause: crate::run::ResourceBlockCause::Other,
20081        });
20082        runner.state.save().unwrap();
20083        // Advance the remote without moving either checkout participating
20084        // in the standing rebase.
20085        let newer = git::git(
20086            &runner.state.repo,
20087            &[
20088                "commit-tree",
20089                "main^{tree}",
20090                "-p",
20091                "main",
20092                "-m",
20093                "base advanced during wait",
20094            ],
20095        )
20096        .await
20097        .unwrap();
20098        git::git(
20099            &runner.state.repo,
20100            &[
20101                "push",
20102                "origin",
20103                &format!("{}:refs/heads/main", newer.trim()),
20104            ],
20105        )
20106        .await
20107        .unwrap();
20108        runner.state = RunState::load(&runner.state.id).unwrap();
20109        runner.state.resource_block = None;
20110        runner.sync_to_base().await.unwrap();
20111        assert!(!runner.state.base_sync_blocked());
20112        let op = &runner.state.base_sync_recovery.operations[0];
20113        assert_eq!(op.head, head);
20114        assert_eq!(op.tip, tip);
20115        assert!(op.finished);
20116        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20117        assert_eq!(runner.state.rebase_fixes.len(), 1);
20118        let latest = git::rev_parse(&runner.state.repo, "origin/main")
20119            .await
20120            .unwrap();
20121        assert_ne!(latest, tip);
20122        runner.state = RunState::load(&runner.state.id).unwrap();
20123        runner.sync_to_base().await.unwrap();
20124        assert!(!runner.state.base_sync_blocked());
20125        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
20126        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
20127        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
20128    }
20129
20130    #[cfg(unix)]
20131    #[tokio::test]
20132    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
20133        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20134        runner.state.reserve_base_operation(&head, &tip);
20135        runner.state.save().unwrap();
20136        std::fs::write(
20137            scratch.join("retained"),
20138            "upstream and retained resolution\n",
20139        )
20140        .unwrap();
20141        git::git(&scratch, &["add", "retained"]).await.unwrap();
20142        git::git(
20143            &scratch,
20144            &["-c", "core.editor=true", "rebase", "--continue"],
20145        )
20146        .await
20147        .unwrap();
20148        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20149        assert!(
20150            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20151                .await
20152                .unwrap()
20153                .is_empty()
20154        );
20155        assert_eq!(
20156            crate::rebase::finish(
20157                &mut runner.state,
20158                &scratch,
20159                "fix/retained",
20160                &head,
20161                &tip,
20162                &["retained".into()],
20163                ""
20164            )
20165            .await
20166            .unwrap(),
20167            crate::rebase::Rebased::Applied
20168        );
20169        assert!(!scratch.exists());
20170        // Simulate losing the caller before finish_base_operation/save.
20171        runner.state = RunState::load(&runner.state.id).unwrap();
20172        let op = &runner.state.base_sync_recovery.operations[0];
20173        assert!(!op.finished);
20174        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
20175        runner.sync_to_base().await.unwrap();
20176        assert!(!runner.state.base_sync_blocked());
20177        assert!(runner.state.base_sync_recovery.operations[0].finished);
20178        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20179        assert_eq!(runner.state.rebase_fixes.len(), 1);
20180        let winner = runner.state.winner().unwrap().clone();
20181        let wait = runner.repository_wait();
20182        assert!(
20183            verify_current_head(&mut runner.state, &winner, &wait)
20184                .await
20185                .unwrap()
20186        );
20187        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20188    }
20189
20190    #[cfg(unix)]
20191    #[tokio::test]
20192    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
20193        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
20194            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20195            runner.state.reserve_base_operation(&head, &tip);
20196            runner.state.save().unwrap();
20197            std::fs::write(
20198                scratch.join("retained"),
20199                "upstream and retained resolution\n",
20200            )
20201            .unwrap();
20202            git::git(&scratch, &["add", "retained"]).await.unwrap();
20203            git::git(
20204                &scratch,
20205                &["-c", "core.editor=true", "rebase", "--continue"],
20206            )
20207            .await
20208            .unwrap();
20209            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20210            assert!(!git::rebase_in_progress(&scratch).await);
20211            assert!(
20212                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20213                    .await
20214                    .unwrap()
20215                    .is_empty()
20216            );
20217            match damage {
20218                Some("record") => {
20219                    let path =
20220                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
20221                            .await
20222                            .unwrap();
20223                    std::fs::write(scratch.join(path), "").unwrap();
20224                }
20225                Some("foreign") => {
20226                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
20227                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
20228                    git::git(&scratch, &["commit", "-m", "foreign work"])
20229                        .await
20230                        .unwrap();
20231                }
20232                Some("dirty") => {
20233                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
20234                }
20235                _ => {}
20236            }
20237            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20238            // Crash immediately after Git continuation, before finish runs.
20239            runner.state = RunState::load(&runner.state.id).unwrap();
20240            assert!(
20241                runner.state.base_sync_recovery.operations[0]
20242                    .validated_head
20243                    .is_none()
20244            );
20245            runner.sync_to_base().await.unwrap();
20246            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20247            assert_eq!(runner.state.base_episode_used(), 1);
20248            assert_eq!(runner.state.rebase_fixes.len(), 1);
20249            assert_eq!(
20250                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20251                retained_head
20252            );
20253            if damage.is_some() {
20254                assert!(runner.state.base_sync_blocked());
20255                assert!(scratch.exists());
20256                assert!(!runner.state.base_sync_recovery.operations[0].finished);
20257                assert!(
20258                    runner.state.base_sync_recovery.operations[0]
20259                        .validated_head
20260                        .is_none()
20261                );
20262            } else {
20263                assert!(!runner.state.base_sync_blocked());
20264                assert!(!scratch.exists());
20265                assert!(runner.state.base_sync_recovery.operations[0].finished);
20266                assert_eq!(
20267                    runner.state.base_sync_recovery.operations[0]
20268                        .validated_head
20269                        .as_deref(),
20270                    Some(result.as_str())
20271                );
20272                let winner = runner.state.winner().unwrap().clone();
20273                let wait = runner.repository_wait();
20274                assert!(
20275                    verify_current_head(&mut runner.state, &winner, &wait)
20276                        .await
20277                        .unwrap()
20278                );
20279                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20280                runner.state = RunState::load(&runner.state.id).unwrap();
20281                runner.sync_to_base().await.unwrap();
20282                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20283            }
20284        }
20285    }
20286
20287    #[cfg(unix)]
20288    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
20289        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20290        // This is an ordinary gate stop, not an authorized base-budget recovery.
20291        runner.state.prep_complete = Some(true);
20292        runner.state.base_sync = None;
20293        runner.state.base_sync_recovery = Default::default();
20294        runner.state.config.graph.gate_fix_rounds = 1;
20295        let mut review = review_round(true, 0, 1, 1, false, true);
20296        review.head = head.clone();
20297        review.verified_head = Some(head.clone());
20298        runner.state.reviews = vec![review];
20299        runner.state.gate = vec![CommandOutcome {
20300            command: "old gate".into(),
20301            code: Some(1),
20302            output_tail: "old failure".into(),
20303            duration_ms: 0,
20304            resource_blocked: false,
20305            ..Default::default()
20306        }];
20307        runner.state.gate_head = Some(head.clone());
20308        runner.state.gate_ran = true;
20309        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
20310            agent: "fixture".into(),
20311            failed: runner.state.gate.clone(),
20312            notes: "spent".into(),
20313            committed: false,
20314            error: None,
20315        }];
20316        runner.state.land_approval = Some(crate::run::LandApproval {
20317            question: "old approval".into(),
20318            head: head.clone(),
20319        });
20320        runner.state.status = RunStatus::Blocked;
20321        (tmp, runner, head)
20322    }
20323
20324    #[cfg(unix)]
20325    #[tokio::test]
20326    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
20327        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
20328        runner.sync_to_base().await.unwrap();
20329        let winner = runner.state.winner().unwrap().clone();
20330        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
20331        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
20332        assert_ne!(head, base);
20333        runner.state.config.verify.e2e = vec![format!(
20334            "git update-ref refs/remotes/origin/main {head} && false"
20335        )];
20336        let wait = repository_wait(&runner.state, None);
20337        assert!(
20338            !verify_current_head(&mut runner.state, &winner, &wait)
20339                .await
20340                .unwrap()
20341        );
20342        assert_eq!(
20343            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
20344                .await
20345                .unwrap(),
20346            head
20347        );
20348        assert_eq!(
20349            runner
20350                .state
20351                .head_e2e
20352                .as_ref()
20353                .unwrap()
20354                .base_commit
20355                .as_deref(),
20356            Some(base.as_str())
20357        );
20358    }
20359
20360    #[cfg(unix)]
20361    #[tokio::test]
20362    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
20363        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
20364            let (tmp, mut runner, old) = resumed_gate_fixture().await;
20365            let phases = tmp.path().join("phases");
20366            runner.state.config.verify.e2e = vec![format!(
20367                "echo e2e >> '{}'; {}",
20368                phases.display(),
20369                if e2e_ok {
20370                    "true"
20371                } else {
20372                    "echo new-e2e-failure; false"
20373                }
20374            )];
20375            runner.state.config.verify.gate = vec![format!(
20376                "echo gate >> '{}'; {}",
20377                phases.display(),
20378                if gate_ok {
20379                    "true"
20380                } else {
20381                    "echo new-gate-failure; false"
20382                }
20383            )];
20384            runner.state.save().unwrap();
20385            runner.state = RunState::load(&runner.state.id).unwrap();
20386            runner.sync_to_base().await.unwrap();
20387            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20388            assert_ne!(head, old);
20389            // Reentry after Git updated but before verification was invalidated.
20390            runner.state = RunState::load(&runner.state.id).unwrap();
20391            runner.execute_graph().await.unwrap();
20392            assert_eq!(runner.state.gate_fixes.len(), 1);
20393            assert_eq!(runner.state.reviews.len(), 1);
20394            assert_eq!(runner.state.reviews[0].head, old);
20395            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
20396            assert_eq!(runner.state.verification_history.len(), 1);
20397            let history = &runner.state.verification_history[0];
20398            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
20399            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20400            assert!(history.archived_at.is_some());
20401            assert_eq!(history.fixes_spent, Some(1));
20402            assert_eq!(history.gate[0].output_tail, "old failure");
20403            let archive_events: Vec<_> = runner
20404                .state
20405                .events
20406                .iter()
20407                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
20408                .collect();
20409            assert_eq!(archive_events.len(), 1);
20410            assert!(archive_events[0].message.contains(&short(&old)));
20411            assert!(archive_events[0].message.contains(&short(&head)));
20412            assert!(
20413                archive_events[0]
20414                    .message
20415                    .contains("1 gate-fix round(s) already spent stay spent")
20416            );
20417            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
20418            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
20419            if e2e_ok {
20420                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20421                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
20422            } else {
20423                assert!(!runner.state.gate_ran);
20424            }
20425            assert_eq!(
20426                runner.state.status,
20427                if e2e_ok && gate_ok {
20428                    RunStatus::Ready
20429                } else {
20430                    RunStatus::Blocked
20431                }
20432            );
20433            if !e2e_ok || !gate_ok {
20434                let cause = runner.state.verification_blocking_cause().unwrap();
20435                assert!(cause.contains(&head));
20436                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
20437                // A later successful progress event must not become the cause.
20438                runner.state.event("land", "rebased successfully");
20439                let notice = crate::notices::run_ended(&runner.state).unwrap();
20440                assert!(!format!("{notice:?}").contains("rebased successfully"));
20441                assert!(runner.state.merge.is_none());
20442            }
20443            let before = std::fs::read_to_string(&phases).unwrap();
20444            runner.state.save().unwrap();
20445            runner.state = RunState::load(&runner.state.id).unwrap();
20446            runner.review_loop().await.unwrap();
20447            runner.gate().await.unwrap();
20448            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
20449            assert_eq!(runner.state.verification_history.len(), 1);
20450            let history = &runner.state.verification_history[0];
20451            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20452            assert!(history.archived_at.is_some());
20453            assert_eq!(history.fixes_spent, Some(1));
20454        }
20455    }
20456
20457    #[cfg(unix)]
20458    #[tokio::test]
20459    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
20460        let (tmp, mut runner, head) = resumed_gate_fixture().await;
20461        let marker = tmp.path().join("gate-ran");
20462        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
20463        runner.review_loop().await.unwrap();
20464        runner.gate().await.unwrap();
20465        assert_eq!(runner.state.status, RunStatus::Blocked);
20466        assert!(!marker.exists());
20467        assert!(runner.state.verification_history.is_empty());
20468        runner.state.gate_head = None;
20469        runner.gate().await.unwrap();
20470        assert!(marker.exists());
20471        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20472        assert_eq!(runner.state.verification_history.len(), 1);
20473        assert_eq!(runner.state.gate_fixes.len(), 1);
20474    }
20475
20476    #[cfg(unix)]
20477    #[tokio::test]
20478    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
20479        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20480        runner.sync_to_base().await.unwrap();
20481        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20482        runner.state.reconcile_verification_head(&head);
20483        // Both crash-before-command and resource wait are unresolved evidence.
20484        for outcomes in [
20485            Vec::new(),
20486            vec![CommandOutcome {
20487                command: "true".into(),
20488                code: None,
20489                output_tail: "cache unavailable".into(),
20490                duration_ms: 0,
20491                resource_blocked: true,
20492                ..Default::default()
20493            }],
20494        ] {
20495            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20496                head.clone(),
20497                false,
20498                outcomes,
20499            ));
20500            runner.state.gate_ran = false;
20501            runner.state.gate.clear();
20502            runner.state.save().unwrap();
20503            runner.state = RunState::load(&runner.state.id).unwrap();
20504            runner.merge().await.unwrap();
20505            assert!(runner.state.merge.is_none());
20506            runner.review_loop().await.unwrap();
20507            runner.gate().await.unwrap();
20508            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20509            assert!(runner.state.gate_allows_progress());
20510            assert_eq!(runner.state.gate_fixes.len(), 1);
20511            assert!(runner.state.merge.is_none());
20512        }
20513        // Moving the winner after a successful gate cannot publish an unchecked SHA.
20514        git::git(
20515            &runner.state.repo,
20516            &["commit", "--allow-empty", "-m", "external update"],
20517        )
20518        .await
20519        .unwrap();
20520        runner.merge().await.unwrap();
20521        assert!(runner.state.merge.is_none());
20522        assert_eq!(runner.state.status, RunStatus::Blocked);
20523    }
20524
20525    #[cfg(unix)]
20526    #[tokio::test]
20527    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
20528        for waiting_on_gate in [false, true] {
20529            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
20530            runner.sync_to_base().await.unwrap();
20531            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20532            runner.state.reconcile_verification_head(&head);
20533            if waiting_on_gate {
20534                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20535                    head.clone(),
20536                    true,
20537                    Vec::new(),
20538                ));
20539            }
20540            let cache = tmp.path().join("cache");
20541            runner.state.config.verify.e2e =
20542                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
20543            runner.state.config.verify.gate = vec!["true".into()];
20544            runner.state.config.graph.timeout_resource_wait = 1;
20545            let owner =
20546                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
20547            let guard =
20548                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
20549                    crate::cache::AcquireOutcome::Acquired(g) => g,
20550                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
20551                };
20552            runner.review_loop().await.unwrap();
20553            runner.gate().await.unwrap();
20554            assert!(!runner.state.gate_ran);
20555            assert_eq!(runner.state.gate_fixes.len(), 1);
20556            assert!(runner.state.resource_block.is_some());
20557            runner.merge().await.unwrap();
20558            assert!(runner.state.merge.is_none());
20559            drop(guard);
20560            runner.state = RunState::load(&runner.state.id).unwrap();
20561            // The driver clears the previous pass's resource stop on resume.
20562            runner.state.resource_block = None;
20563            runner.review_loop().await.unwrap();
20564            runner.gate().await.unwrap();
20565            assert!(runner.state.gate_allows_progress());
20566            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20567            assert_eq!(runner.state.gate_fixes.len(), 1);
20568        }
20569    }
20570
20571    #[cfg(unix)]
20572    #[tokio::test]
20573    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
20574        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20575        runner.sync_to_base().await.unwrap();
20576        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20577        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
20578        // Verification passes before pre_gate and fails on the mechanically changed head.
20579        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
20580        runner.review_loop().await.unwrap();
20581        runner.gate().await.unwrap();
20582        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20583        assert_ne!(before, after);
20584        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
20585        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
20586        assert!(!runner.state.gate_allows_progress());
20587        runner.merge().await.unwrap();
20588        assert!(runner.state.merge.is_none());
20589        assert!(
20590            runner
20591                .state
20592                .verification_history
20593                .iter()
20594                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
20595        );
20596
20597        // An incomplete review is still an independent hold on a changed head.
20598        runner.state.reviews[0].clean = false;
20599        runner.state.reviews[0].answered = 0;
20600        runner.state.config.verify.e2e = vec!["true".into()];
20601        runner.review_loop().await.unwrap();
20602        runner.gate().await.unwrap();
20603        runner.merge().await.unwrap();
20604        assert_eq!(runner.state.status, RunStatus::Blocked);
20605        assert!(runner.state.merge.is_none());
20606        assert!(
20607            runner
20608                .state
20609                .verification_blocking_cause()
20610                .unwrap()
20611                .contains("review blocked")
20612        );
20613    }
20614
20615    #[cfg(unix)]
20616    #[tokio::test]
20617    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
20618        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20619        runner.state.gate_head = None;
20620        runner.state.config.verify.gate =
20621            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20622        runner.review_loop().await.unwrap();
20623        runner.gate().await.unwrap();
20624        assert_ne!(
20625            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20626            old
20627        );
20628        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20629        assert!(!runner.state.gate_allows_progress());
20630        assert_eq!(runner.state.status, RunStatus::Blocked);
20631        runner.merge().await.unwrap();
20632        assert!(runner.state.merge.is_none());
20633    }
20634
20635    #[cfg(unix)]
20636    #[tokio::test]
20637    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20638        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20639        let mut old_review = review_round(true, 0, 1, 1, false, true);
20640        old_review.head = head.clone();
20641        old_review.verified_head = Some(head.clone());
20642        runner.state.reviews = vec![old_review];
20643        runner.state.gate = vec![CommandOutcome {
20644            command: "old gate".into(),
20645            code: None,
20646            output_tail: "timed out after 2400s".into(),
20647            duration_ms: 2_400_000,
20648            resource_blocked: false,
20649            ..Default::default()
20650        }];
20651        runner.state.gate_ran = true;
20652        runner.state.gate_head = Some(head.clone());
20653        runner.state.land_approval = Some(crate::run::LandApproval {
20654            question: "old-head-approval".into(),
20655            head: head.clone(),
20656        });
20657        runner.state.authorize_base_sync(&task).unwrap();
20658        runner.sync_to_base().await.unwrap();
20659        assert!(!runner.state.base_sync_blocked());
20660        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20661        assert_ne!(head, fresh);
20662        assert_eq!(runner.state.reviews.len(), 1);
20663        assert!(!runner.state.gate_ran);
20664        let saved = &runner.state.base_sync_recovery.authorizations[0];
20665        assert_eq!(saved.reviews[0].head, head);
20666        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20667        assert!(saved.gate_ran);
20668        assert!(!saved.gate[0].ok());
20669        runner.review_loop().await.unwrap();
20670        runner.gate().await.unwrap();
20671        assert_eq!(runner.state.reviews[0].head, head);
20672        assert_eq!(
20673            runner.state.reviews[0].verified_head.as_deref(),
20674            Some(head.as_str())
20675        );
20676        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20677        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20678        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20679        assert!(runner.state.gate_ran);
20680        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20681        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20682        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20683        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20684        assert_eq!(
20685            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20686            "retained change"
20687        );
20688    }
20689
20690    #[cfg(unix)]
20691    #[tokio::test]
20692    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20693        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20694        let queue = crate::queue::Queue::open();
20695        let mut owner = queue.get(&task).unwrap();
20696        owner.release_operator("test-resume", None);
20697        queue.put(&mut owner).unwrap();
20698        let generation = owner.resumption.as_ref().unwrap().generation;
20699        runner.state.task_instruction = Some(owner.instruction.clone());
20700        runner.state.driver_exited = true;
20701        runner.state.save().unwrap();
20702        let home = crate::run::home();
20703        let _claim = queue.claim(&task).unwrap();
20704        owner.resumption.as_mut().unwrap().at =
20705            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20706        queue.put(&mut owner).unwrap();
20707        assert!(
20708            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20709                .await
20710                .is_err(),
20711            "an approval from before the stop grants nothing"
20712        );
20713        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20714        queue.put(&mut owner).unwrap();
20715        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20716            .await
20717            .unwrap();
20718        assert!(
20719            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20720                .await
20721                .is_err()
20722        );
20723        runner.state = RunState::load(&runner.state.id).unwrap();
20724        assert_eq!(
20725            runner.state.base_sync_recovery.authorizations[0].generation,
20726            Some(generation)
20727        );
20728        runner.sync_to_base().await.unwrap();
20729        let repo = runner.state.repo.clone();
20730        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20731        git::git(&repo, &["checkout", "main"]).await.unwrap();
20732        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20733        git::git(&repo, &["add", "."]).await.unwrap();
20734        git::git(&repo, &["commit", "-m", "move base again"])
20735            .await
20736            .unwrap();
20737        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20738        git::git(&repo, &["checkout", "fix/retained"])
20739            .await
20740            .unwrap();
20741        runner.sync_to_base().await.unwrap();
20742        assert!(!runner.state.base_sync_blocked());
20743        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20744        assert_eq!(runner.state.base_episode_used(), 2);
20745        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20746        assert_ne!(fresh, head);
20747        assert!(!runner.state.base_recovery_pending());
20748        // Even replaying the generation with a later timestamp grants nothing.
20749        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20750        queue.put(&mut owner).unwrap();
20751        assert!(
20752            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20753                .await
20754                .is_err()
20755        );
20756        runner.state = RunState::load(&runner.state.id).unwrap();
20757        runner.sync_to_base().await.unwrap();
20758        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20759        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20760        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20761    }
20762
20763    #[cfg(unix)]
20764    #[tokio::test]
20765    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20766        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20767        runner.state.base_sync = None;
20768        runner.state.status = RunStatus::Blocked;
20769        let mut second = runner.state.candidates[0].clone();
20770        second.label = 'B';
20771        runner.state.candidates.push(second);
20772        assert!(runner.state.votes.is_empty());
20773        assert!(runner.state.deliberation.is_empty());
20774        runner.deliberate().await.unwrap();
20775        runner.vote().await.unwrap();
20776        assert_eq!(runner.state.status, RunStatus::Blocked);
20777        assert!(runner.state.votes.is_empty());
20778        assert!(runner.state.deliberation.is_empty());
20779    }
20780
20781    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20782    /// reads nothing else off it.
20783    fn runner_at(status: RunStatus) -> Runner {
20784        let mut state = RunState::new(
20785            PathBuf::from("/nonexistent/repo"),
20786            "main".to_owned(),
20787            "deadbeef".to_owned(),
20788            "task".to_owned(),
20789            Config::default(),
20790        );
20791        // These fixtures test execution flow, independent of host disk capacity.
20792        state.config.disk.min_free_bytes = 0;
20793        // These fixtures share one home and save concurrently. Short clock
20794        // IDs can collide, making an ownership test read another test's run.
20795        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20796        state.id = format!(
20797            "20000101-000000-{:04x}",
20798            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20799        );
20800        state.status = status;
20801        Runner {
20802            state,
20803            roles: ResolvedRoles {
20804                implementers: Vec::new(),
20805                judges: Vec::new(),
20806                reviewers: Vec::new(),
20807                fixer: None,
20808                conductor: conductor(),
20809                implementer_roster: Vec::new(),
20810                judge_roster: Vec::new(),
20811                reviewer_roster: Vec::new(),
20812            },
20813            sem: Arc::new(Semaphore::new(1)),
20814            pause: Pause::new(),
20815            interrupt: Pause::new(),
20816        }
20817    }
20818
20819    #[tokio::test]
20820    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20821        crate::run::pin_test_home();
20822        let home = crate::run::home();
20823        let mut runner = runner_at(RunStatus::Ready);
20824        runner.state.driver_exited = true;
20825        runner.state.save().unwrap();
20826        let id = runner.state.id.clone();
20827        let path = runner.state.dir().join("run.json");
20828        let ids = ["R1-1-1".into()];
20829        let lease = crate::driver::maintenance(&home, &id).unwrap();
20830        for (guard, expected) in [
20831            (Some(lease), "currently being worked on"),
20832            (None, "ownership is being updated"),
20833        ] {
20834            let owner = if guard.is_none() {
20835                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20836            } else {
20837                None
20838            };
20839            let before = std::fs::read(&path).unwrap();
20840            let err = runner
20841                .fix_selected(&ids, "ownership conflict", false)
20842                .await
20843                .unwrap_err();
20844            assert!(format!("{err:#}").contains(expected), "{err:#}");
20845            assert_eq!(std::fs::read(&path).unwrap(), before);
20846            assert!(!runner.state.dir().join("fix.lock").exists());
20847            drop(owner);
20848            drop(guard);
20849        }
20850        let mut disk = RunState::load(&id).unwrap();
20851        disk.driver_exited = false;
20852        disk.driver_pid = Some(std::process::id());
20853        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20854        disk.save().unwrap();
20855        assert_eq!(
20856            disk.liveness_under(&home, false),
20857            crate::run::Liveness::Live
20858        );
20859        let before = std::fs::read(&path).unwrap();
20860        let err = runner
20861            .fix_selected(&ids, "live driver", false)
20862            .await
20863            .unwrap_err();
20864        assert!(
20865            err.to_string().contains("currently being worked on"),
20866            "{err:#}"
20867        );
20868        assert_eq!(std::fs::read(&path).unwrap(), before);
20869        assert!(!runner.state.dir().join("fix.lock").exists());
20870        disk.driver_exited = true;
20871        disk.driver_pid = None;
20872        disk.driver_started_at = None;
20873        disk.status = RunStatus::Reviewing;
20874        disk.save().unwrap();
20875        let before = std::fs::read(&path).unwrap();
20876        let err = runner
20877            .fix_selected(&ids, "stale state", false)
20878            .await
20879            .unwrap_err();
20880        assert!(
20881            err.to_string().contains("run changed since it was loaded"),
20882            "{err:#}"
20883        );
20884        assert_eq!(std::fs::read(&path).unwrap(), before);
20885        assert!(!runner.state.dir().join("fix.lock").exists());
20886        assert!(runner.state.operator_fixes.is_empty());
20887    }
20888
20889    #[tokio::test]
20890    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20891        use std::future::Future;
20892        use std::task::Poll;
20893
20894        crate::run::pin_test_home();
20895        let home = crate::run::home();
20896        let repo = tempfile::tempdir().unwrap();
20897        let mut runner = runner_at(RunStatus::Ready);
20898        runner.state.repo = repo.path().to_path_buf();
20899        runner.state.driver_exited = true;
20900        runner.state.candidates.push(Candidate {
20901            index: 0,
20902            label: 'A',
20903            agent: "mock".into(),
20904            branch: "magi/test/A".into(),
20905            worktree: repo.path().join("wt"),
20906            summary: String::new(),
20907            stat: String::new(),
20908            files: 0,
20909            commits: 0,
20910            empty: false,
20911            failed: None,
20912            verified_noop: None,
20913            duration_ms: 0,
20914            folded: false,
20915        });
20916        runner.state.tally = Some(Tally {
20917            first_choice: BTreeMap::from([('A', 1)]),
20918            borda: BTreeMap::new(),
20919            winner: 'A',
20920            rankings: 1,
20921            unanimous_initial: true,
20922            deliberated: false,
20923            changed_votes: 0,
20924            unanimous_final: true,
20925            tie_break: None,
20926            judges: 1,
20927            present: 1,
20928            quorum: 1,
20929            met_quorum: true,
20930            uncontested: None,
20931        });
20932        runner.state.save().unwrap();
20933        let id = runner.state.id.clone();
20934        let dir = runner.state.dir();
20935        let before = std::fs::read(dir.join("run.json")).unwrap();
20936        let ids = ["R1-1-1".into()];
20937        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20938        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20939            Poll::Pending => Poll::Ready(()),
20940            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20941        })
20942        .await;
20943        assert!(FixClaim::acquire(&dir).is_err());
20944        assert!(crate::driver::maintenance(&home, &id).is_err());
20945        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20946        drop(fix);
20947        assert!(FixClaim::acquire(&dir).is_ok());
20948        assert!(crate::driver::maintenance(&home, &id).is_ok());
20949        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20950    }
20951
20952    #[tokio::test]
20953    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20954        crate::run::pin_test_home();
20955        let temp = tempfile::tempdir().unwrap();
20956        let root = temp.path().canonicalize().unwrap();
20957        let repo = root.join("repo");
20958        std::fs::create_dir(&repo).unwrap();
20959        init_repo(&repo);
20960        git::git(&repo, &["config", "core.autocrlf", "false"])
20961            .await
20962            .unwrap();
20963        let mut runner = runner_at(RunStatus::Blocked);
20964        runner.state.repo = repo.clone();
20965        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20966        runner.state.config.agents = vec![conductor()];
20967        runner.state.config.graph.selected_implementer = Some("conductor".into());
20968        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20969        let (shell, command, setup_output) = if cfg!(windows) {
20970            (
20971                vec!["cmd".into(), "/C".into()],
20972                "echo ready>seat-ready",
20973                "ready\r\n",
20974            )
20975        } else {
20976            (
20977                vec!["sh".into(), "-c".into()],
20978                "printf ready > seat-ready",
20979                "ready",
20980            )
20981        };
20982        runner.state.config.verify.shell = Some(shell);
20983        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20984            run: Some(command.into()),
20985            ..Default::default()
20986        }];
20987        runner.state.save().unwrap();
20988        let path = runner.state.worktree_root().join("judge-1");
20989        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20990            .await
20991            .unwrap();
20992        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20993        git::git(&path, &["add", "."]).await.unwrap();
20994        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20995        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20996            .await
20997            .unwrap();
20998        git::git(&path, &["checkout", "--detach", &head])
20999            .await
21000            .unwrap();
21001        let evidence = crate::fold_evidence::snapshot(
21002            &runner.state,
21003            &crate::run::home().canonicalize().unwrap(),
21004            &head,
21005            64 * 1024 * 1024,
21006        )
21007        .await
21008        .unwrap();
21009        let mut contents = BTreeMap::new();
21010        contents.insert(
21011            repo.join("logs/HEAD"),
21012            format!("{head} {head} fixture\n").into_bytes(),
21013        );
21014        let record = serde_json::json!({
21015            "version":1, "run":runner.state.id, "source":path, "head":head,
21016            "evidence":evidence, "admin":{}, "admin_contents":contents,
21017            "history":{head.clone():evidence}, "phase":"evicted"
21018        });
21019        std::fs::write(
21020            runner.state.dir().join("artifacts/eviction-judge-1.json"),
21021            serde_json::to_vec(&record).unwrap(),
21022        )
21023        .unwrap();
21024        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
21025        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
21026            .await
21027            .unwrap();
21028        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
21029        assert!(
21030            !git::git_raw(&repo, &["cat-file", "-e", &head])
21031                .await
21032                .unwrap()
21033                .ok()
21034        );
21035        let mut resumed = Runner::resume(&runner.state.id).unwrap();
21036        let error = resumed.execute().await.unwrap_err();
21037        assert!(
21038            error
21039                .to_string()
21040                .contains("selected implementation is held"),
21041            "{error:#}"
21042        );
21043        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
21044        assert_eq!(
21045            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
21046            setup_output
21047        );
21048        assert_eq!(
21049            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
21050            "unrelated seat"
21051        );
21052        let error = resumed.execute().await.unwrap_err();
21053        assert!(
21054            error
21055                .to_string()
21056                .contains("selected implementation is held"),
21057            "{error:#}"
21058        );
21059        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
21060        git::git(&path, &["add", "."]).await.unwrap();
21061        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
21062        let next = git::git(
21063            &path,
21064            &[
21065                "commit-tree",
21066                &next_tree,
21067                "-p",
21068                &head,
21069                "-m",
21070                "next review checkpoint",
21071            ],
21072        )
21073        .await
21074        .unwrap();
21075        git::git(&path, &["checkout", "--detach", &next])
21076            .await
21077            .unwrap();
21078        resumed.state.reviews.push(
21079            serde_json::from_value(serde_json::json!({
21080                "round":1, "head":next, "reviews":[]
21081            }))
21082            .unwrap(),
21083        );
21084        resumed.state.save().unwrap();
21085        let error = resumed.execute().await.unwrap_err();
21086        assert!(
21087            error
21088                .to_string()
21089                .contains("selected implementation is held"),
21090            "{error:#}"
21091        );
21092        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
21093    }
21094
21095    #[tokio::test]
21096    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
21097        crate::run::pin_test_home();
21098        let mut runner = runner_at(RunStatus::Gating);
21099        runner.state.save().unwrap();
21100        let id = runner.state.id.clone();
21101        let passes = runner.state.passes.len();
21102        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21103        let mut claiming = Box::pin(runner.claim_driver(None));
21104        std::future::poll_fn(|cx| {
21105            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
21106            std::task::Poll::Ready(())
21107        })
21108        .await;
21109        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
21110        drop(owner);
21111        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
21112            .await
21113            .unwrap()
21114            .unwrap();
21115        assert_eq!(execution.runner.state.passes.len(), passes + 1);
21116        assert!(execution.runner.state.resource_block.is_none());
21117        assert_eq!(
21118            execution.runner.state.liveness(false),
21119            crate::run::Liveness::Live
21120        );
21121        drop(execution);
21122        assert!(RunState::load(&id).unwrap().driver_exited);
21123    }
21124
21125    #[tokio::test]
21126    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
21127        crate::run::pin_test_home();
21128        let mut runner = runner_at(RunStatus::Gating);
21129        runner.state.save().unwrap();
21130        // run.json can commit, but the subsequent lease metadata write fails.
21131        // Cleanup must run after releasing the short ownership lock.
21132        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
21133        assert!(runner.claim_driver(None).await.is_err());
21134        assert!(runner.state.driver_exited);
21135        assert_eq!(runner.state.driver_pid, None);
21136        let disk = RunState::load(&runner.state.id).unwrap();
21137        assert!(disk.driver_exited);
21138        assert_eq!(disk.driver_pid, None);
21139        assert_eq!(disk.status, RunStatus::Gating);
21140    }
21141
21142    #[tokio::test]
21143    async fn an_early_graph_error_releases_its_driver() {
21144        crate::run::pin_test_home();
21145        let mut runner = runner_at(RunStatus::Blocked);
21146        runner.state.config.graph.selected_implementer = Some("selected".into());
21147        runner.state.save().unwrap();
21148        assert!(runner.execute().await.is_err());
21149        let disk = RunState::load(&runner.state.id).unwrap();
21150        assert!(disk.driver_exited);
21151        assert_eq!(disk.driver_pid, None);
21152        assert_eq!(disk.status, RunStatus::Blocked);
21153    }
21154
21155    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
21156        crate::run::MergeRepair {
21157            question: "repair-question".into(),
21158            head: "old-head".into(),
21159            pr: "https://github.com/o/r/pull/42".into(),
21160            reviews: vec![review_round(false, 1, 1, 1, false, true)],
21161            gate: vec![outcome(Some(0), false)],
21162            gate_head: Some("old-head".into()),
21163            gate_fixes: Vec::new(),
21164            pre_gate: Vec::new(),
21165            phase,
21166            failure: None,
21167        }
21168    }
21169
21170    #[tokio::test]
21171    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
21172        crate::run::pin_test_home();
21173        let mut runner = runner_at(RunStatus::Landing);
21174        runner.state.merge_repairs.push(merge_repair_request(
21175            crate::run::MergeRepairPhase::Requested,
21176        ));
21177        runner.state.save().unwrap();
21178        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
21179        assert!(
21180            runner
21181                .execute()
21182                .await
21183                .unwrap_err()
21184                .to_string()
21185                .contains("already running")
21186        );
21187        assert_eq!(
21188            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21189            crate::run::MergeRepairPhase::Requested
21190        );
21191        drop(claim);
21192        let mut disk = runner.state.clone();
21193        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
21194        disk.save().unwrap();
21195        assert!(
21196            runner
21197                .execute()
21198                .await
21199                .unwrap_err()
21200                .to_string()
21201                .contains("decision changed")
21202        );
21203        assert_eq!(
21204            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21205            crate::run::MergeRepairPhase::Complete
21206        );
21207    }
21208
21209    #[test]
21210    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
21211        crate::run::pin_test_home();
21212        let mut runner = runner_at(RunStatus::Landing);
21213        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
21214        runner.state.reviews = request.reviews.clone();
21215        runner.state.gate = request.gate.clone();
21216        runner.state.gate_ran = true;
21217        runner.state.land_approval = Some(crate::run::LandApproval {
21218            question: "old".into(),
21219            head: "old-head".into(),
21220        });
21221        runner.state.merge_repairs.push(request);
21222        runner.begin_merge_repair_review(0).unwrap();
21223        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
21224        assert!(!runner.state.gate_status().ok());
21225        assert!(runner.state.land_approval.is_none());
21226        let disk = RunState::load(&runner.state.id).unwrap();
21227        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
21228        assert!(disk.merge_repairs[0].gate[0].ok());
21229        assert_eq!(
21230            disk.merge_repairs[0].phase,
21231            crate::run::MergeRepairPhase::Reviewing
21232        );
21233        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
21234        assert!(disk.reviews.is_empty());
21235    }
21236
21237    #[tokio::test]
21238    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
21239        crate::run::pin_test_home();
21240        for phase in [
21241            crate::run::MergeRepairPhase::Fixing,
21242            crate::run::MergeRepairPhase::Requested,
21243        ] {
21244            let mut runner = runner_at(RunStatus::Landing);
21245            runner.state.config.graph.land_rounds = 0;
21246            runner.state.merge_repairs.push(merge_repair_request(phase));
21247            runner.state.save().unwrap();
21248            assert!(!runner.repair_merge_review().await.unwrap());
21249            assert_eq!(runner.state.status, RunStatus::Blocked);
21250            assert_eq!(
21251                runner.state.merge_repairs[0].phase,
21252                crate::run::MergeRepairPhase::Failed
21253            );
21254            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
21255            assert!(
21256                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
21257                    "interrupted"
21258                } else {
21259                    "budget exhausted"
21260                })
21261            );
21262            assert!(runner.state.merge.is_none());
21263        }
21264    }
21265
21266    #[tokio::test]
21267    async fn failed_instruction_revision_repair_cannot_resume_into_landing() {
21268        crate::run::pin_test_home();
21269        let mut runner = runner_at(RunStatus::Landing);
21270        let old = merge_repair_request(crate::run::MergeRepairPhase::Complete);
21271        runner.state.reviews = old.reviews.clone();
21272        runner.state.gate = old.gate.clone();
21273        runner.state.gate_ran = true;
21274        runner.state.merge = Some(MergeOutcome {
21275            mode: MergeMode::Pr,
21276            ok: true,
21277            detail: old.pr.clone(),
21278            empty: false,
21279        });
21280        runner.state.merge_repairs.push(old.clone());
21281        crate::instruction_revision_control::adopt_into_run(
21282            &mut runner.state,
21283            "cli/revision",
21284            "revision-repair",
21285            "revised task",
21286            1,
21287            &old.head,
21288            &old.pr,
21289        );
21290        runner.hold_merge_repair(1, "fixer failed".into()).unwrap();
21291        runner.execute().await.unwrap();
21292        let saved = RunState::load(&runner.state.id).unwrap();
21293        assert_eq!(saved.status, RunStatus::Blocked);
21294        assert_eq!(
21295            saved.merge_repairs[0].phase,
21296            crate::run::MergeRepairPhase::Complete
21297        );
21298        assert_eq!(
21299            saved.merge_repairs[1].phase,
21300            crate::run::MergeRepairPhase::Failed
21301        );
21302        assert_eq!(
21303            saved.merge_repairs[1].failure.as_deref(),
21304            Some("fixer failed")
21305        );
21306        assert!(saved.land_approval.is_none());
21307        assert!(!saved.gate_ran);
21308        assert_eq!(saved.reviews.len(), 1);
21309        assert!(
21310            saved.events.iter().any(|event| event.node == "repair"
21311                && event.message.contains("normal resume cannot land"))
21312        );
21313        assert!(!saved.events.iter().any(|event| event.node == "land"));
21314    }
21315
21316    /// `park_here` folding in the reason `Pause::park_because` recorded -
21317    /// this is what lets an operator reading a run's events tell an
21318    /// interrupt-driven park from an ordinary shutdown park.
21319    #[test]
21320    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
21321        crate::run::pin_test_home();
21322        let mut runner = runner_at(RunStatus::Implementing);
21323        let interrupt = Pause::new();
21324        runner.watch_interrupt(interrupt.clone());
21325
21326        interrupt.park_because("task a1b2 asked to run first");
21327
21328        assert!(runner.park_here().expect("park_here"));
21329        assert!(runner.state.parked);
21330        let last = runner.state.events.last().expect("a park event");
21331        assert_eq!(last.node, "park");
21332        assert!(
21333            last.message.contains("task a1b2 asked to run first"),
21334            "expected the interrupt reason in {:?}",
21335            last.message
21336        );
21337    }
21338
21339    /// The cause is stored on the pass when it parks, and the first cause a
21340    /// shared pause was given is the one that stays.
21341    #[test]
21342    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
21343        crate::run::pin_test_home();
21344        let mut runner = runner_at(RunStatus::Implementing);
21345        runner.state.begin_pass();
21346        let shutdown = Pause::new();
21347        runner.on_pause(shutdown.clone());
21348        let upgrade = ParkCause::Upgrade {
21349            from: "0.121.0".to_owned(),
21350            to: Some("0.121.1".to_owned()),
21351        };
21352        shutdown.park_for(upgrade.clone());
21353        shutdown.park_for(ParkCause::Operator);
21354
21355        assert!(runner.park_here().expect("park_here"));
21356        assert_eq!(
21357            runner.state.passes[0].end,
21358            Some(crate::run::PassEnd::Parked { cause: upgrade })
21359        );
21360        let last = runner.state.events.last().expect("a park event");
21361        assert!(last.message.contains("0.121.0"), "{}", last.message);
21362    }
21363
21364    #[tokio::test]
21365    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
21366        crate::run::pin_test_home();
21367        let mut runner = runner_at(RunStatus::Reviewing);
21368        runner.state.save().unwrap();
21369        let mut execution = runner.claim_driver(None).await.expect("first execution");
21370        assert_eq!(execution.runner.state.passes.len(), 1);
21371        execution
21372            .driver
21373            .finish(&mut execution.runner.state)
21374            .await
21375            .unwrap();
21376    }
21377
21378    #[tokio::test]
21379    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
21380        crate::run::pin_test_home();
21381        let mut runner = runner_at(RunStatus::Reviewing);
21382        runner.state.config.agents = vec![conductor()];
21383        runner.state.config.graph.timeout_resource_wait = 0;
21384        runner.state.save().unwrap();
21385        let id = runner.state.id.clone();
21386        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21387        assert!(runner.claim_driver(None).await.is_err());
21388        drop(owner);
21389        drop(runner);
21390        let mut resumed = Runner::resume(&id).unwrap();
21391        assert_eq!(resumed.state.driver_claimed, Some(false));
21392        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
21393        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
21394        let mut execution = resumed
21395            .claim_driver(None)
21396            .await
21397            .expect("retry initial claim after reload");
21398        assert_eq!(execution.runner.state.driver_claimed, Some(true));
21399        assert_eq!(execution.runner.state.passes.len(), 1);
21400        execution
21401            .driver
21402            .finish(&mut execution.runner.state)
21403            .await
21404            .unwrap();
21405    }
21406
21407    #[tokio::test]
21408    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
21409        crate::run::pin_test_home();
21410        let mut runner = runner_at(RunStatus::Reviewing);
21411        runner.state.config.agents = vec![conductor()];
21412        runner.state.save().unwrap();
21413        let id = runner.state.id.clone();
21414        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
21415        let mut resumed = Runner::resume(&id).unwrap();
21416        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
21417        assert!(resumed.claim_driver(None).await.is_err());
21418        assert!(RunState::load(&id).unwrap().passes.is_empty());
21419        drop(lease);
21420        let mut execution = resumed.claim_driver(None).await.unwrap();
21421        execution
21422            .driver
21423            .finish(&mut execution.runner.state)
21424            .await
21425            .unwrap();
21426    }
21427
21428    #[tokio::test]
21429    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
21430        crate::run::pin_test_home();
21431        let mut runner = runner_at(RunStatus::Reviewing);
21432        let state = &mut runner.state;
21433        state.config.agents = vec![conductor()];
21434        state.driver_claimed = None;
21435        state.driver_pid = Some(std::process::id());
21436        state.driver_started_at = None;
21437        state.begin_pass();
21438        state.save().unwrap();
21439        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
21440        std::fs::write(
21441            state.dir().join("driver.json"),
21442            serde_json::to_vec(&serde_json::json!({
21443                "pid": state.driver_pid, "started_at": null,
21444                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
21445            }))
21446            .unwrap(),
21447        )
21448        .unwrap();
21449        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
21450        drop(lease);
21451        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
21452        let mut resumed = Runner::resume(&state.id).unwrap();
21453        assert!(!resumed.state.driver_exited);
21454        let mut execution = resumed
21455            .claim_driver(None)
21456            .await
21457            .expect("lease proves previous execution ended");
21458        assert_eq!(execution.runner.state.passes.len(), 2);
21459        execution
21460            .driver
21461            .finish(&mut execution.runner.state)
21462            .await
21463            .unwrap();
21464    }
21465
21466    #[tokio::test]
21467    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
21468        crate::run::pin_test_home();
21469        let mut runner = runner_at(RunStatus::Reviewing);
21470        let mut json = serde_json::to_value(&runner.state).unwrap();
21471        json.as_object_mut().unwrap().remove("driver_claimed");
21472        runner.state = serde_json::from_value(json).unwrap();
21473        assert_eq!(runner.state.driver_claimed, None);
21474        runner.state.save().unwrap();
21475        let mut execution = runner
21476            .claim_driver(None)
21477            .await
21478            .expect("the execution lease, not a missing marker, excludes a second driver");
21479        assert_eq!(execution.runner.state.passes.len(), 1);
21480        execution
21481            .driver
21482            .finish(&mut execution.runner.state)
21483            .await
21484            .unwrap();
21485    }
21486
21487    #[tokio::test]
21488    async fn driver_admission_refuses_a_proven_live_driver() {
21489        crate::run::pin_test_home();
21490        let mut runner = runner_at(RunStatus::Reviewing);
21491        let pid = std::process::id();
21492        runner.state.driver_pid = Some(pid);
21493        runner.state.driver_started_at = crate::proc::process_started_at(pid);
21494        assert!(runner.state.driver_started_at.is_some());
21495        runner.state.save().unwrap();
21496        let error = runner
21497            .claim_driver(None)
21498            .await
21499            .err()
21500            .expect("a live driver must refuse");
21501        let message = error.to_string();
21502        assert!(
21503            message.starts_with("run already has a live driver: "),
21504            "{message}"
21505        );
21506        assert!(message.contains(&format!("pid={pid}")), "{message}");
21507        assert!(
21508            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
21509            "{message}"
21510        );
21511        let saved = RunState::load(&runner.state.id).unwrap();
21512        assert_eq!(saved.driver_pid, Some(pid));
21513        assert_eq!(saved.status, RunStatus::Reviewing);
21514        assert!(saved.passes.is_empty());
21515    }
21516
21517    #[tokio::test]
21518    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
21519        crate::run::pin_test_home();
21520        let home = crate::run::home();
21521        let mut runner = runner_at(RunStatus::Reviewing);
21522        runner.state.driver_exited = true;
21523        runner.state.driver_pid = None;
21524        runner.state.driver_started_at = None;
21525        runner.state.save().unwrap();
21526
21527        let queue = crate::queue::Queue::at(home.join("queue"));
21528        let mut task = crate::queue::Task::new(
21529            "task".into(),
21530            "task".into(),
21531            runner.state.repo.clone(),
21532            crate::queue::Source::Human,
21533        );
21534        task.runs.push(runner.state.id.clone());
21535        queue.put(&mut task).unwrap();
21536        let payload = serde_json::json!({
21537            "queue": home.join("queue"),
21538            "task": task.id,
21539            "opts": crate::daemon::Opts::default(),
21540            "standalone": false,
21541        });
21542        let (job, lease) =
21543            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
21544
21545        let error = runner
21546            .claim_driver(None)
21547            .await
21548            .err()
21549            .expect("another active worker claim must refuse");
21550        let message = error.to_string();
21551        assert!(
21552            message.starts_with("run already has a live driver: worker claim"),
21553            "{message}"
21554        );
21555        assert!(message.contains(&job.id), "{message}");
21556        assert!(message.contains("status=running"), "{message}");
21557        assert!(message.contains("live.lock held"), "{message}");
21558
21559        drop(lease);
21560        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
21561    }
21562
21563    #[test]
21564    fn parking_resource_halt_persists_the_pass_once() {
21565        crate::run::pin_test_home();
21566        let mut runner = runner_at(RunStatus::Reviewing);
21567        runner.state.begin_pass();
21568        runner.state.resource_block = Some(crate::run::ResourceBlock {
21569            node: "fix".into(),
21570            kind: "shared build cache".into(),
21571            detail: "cancelled".into(),
21572            at: Timestamp::now(),
21573            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
21574        });
21575        let cause = ParkCause::Upgrade {
21576            from: "old".into(),
21577            to: Some("new".into()),
21578        };
21579        runner.pause.park_for(cause.clone());
21580        // Both direct fixer exits and graph resource boundaries must complete
21581        // parking, rather than returning a stale Reviewing record.
21582        runner.stop_for_resource().unwrap();
21583        assert!(runner.resource_halt().unwrap());
21584        assert!(runner.park_here().unwrap());
21585        let saved = RunState::load(&runner.state.id).unwrap();
21586        assert!(saved.parked);
21587        assert_eq!(saved.status, RunStatus::Reviewing);
21588        assert!(saved.passes[0].ended_at.is_some());
21589        assert_eq!(
21590            saved.passes[0].end,
21591            Some(crate::run::PassEnd::Parked {
21592                cause: cause.clone()
21593            })
21594        );
21595        assert_eq!(
21596            saved.resource_block.unwrap().cause,
21597            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
21598        );
21599        assert_eq!(
21600            saved
21601                .events
21602                .iter()
21603                .filter(|event| event.node == "park")
21604                .count(),
21605            1
21606        );
21607    }
21608
21609    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
21610    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
21611    /// cleared) must not make a *different* run - one only watching its own,
21612    /// unshared interrupt `Pause` - see itself as parked. If a future change
21613    /// ever collapsed these back into one handle, the interrupt scheduler
21614    /// would park every run for the rest of the daemon's life, not just the
21615    /// one it meant to interrupt.
21616    #[test]
21617    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
21618        crate::run::pin_test_home();
21619        let mut runner = runner_at(RunStatus::Implementing);
21620        let shutdown = Pause::new();
21621        runner.on_pause(shutdown.clone());
21622        let interrupt = Pause::new();
21623        runner.watch_interrupt(interrupt.clone());
21624
21625        // Nobody has asked for anything yet.
21626        assert!(!runner.park_here().expect("park_here"));
21627        assert!(!runner.state.parked);
21628
21629        // Only the interrupt handle fires; the shutdown handle stays clear.
21630        interrupt.park_because("test");
21631        assert!(!shutdown.parked());
21632        assert!(runner.park_here().expect("park_here"));
21633    }
21634
21635    /// The property every prior attempt at this feature failed to pin down:
21636    /// asking a run to park while one of its nodes has a real, in-flight
21637    /// async operation running (an agent call, in production) must not cut
21638    /// that operation short. `park_here` is only ever consulted *between*
21639    /// `execute`'s node calls - see its own doc - so nothing inside a node
21640    /// can observe a park request until the node itself returns. This proves
21641    /// that structurally, with real `tokio` concurrency and a channel
21642    /// handshake (never a sleep, which would only prove "usually", not
21643    /// "cannot"): the "node" below reports that it has genuinely started,
21644    /// and only then is the park requested; the node still has to be told to
21645    /// finish before `park_here` is ever called, exactly mirroring every
21646    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
21647    /// in `execute`.
21648    #[tokio::test]
21649    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
21650        crate::run::pin_test_home();
21651        let mut runner = runner_at(RunStatus::Implementing);
21652        let interrupt = Pause::new();
21653        runner.watch_interrupt(interrupt.clone());
21654
21655        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
21656        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
21657
21658        // Stands in for one node's in-flight agent call: it proves it has
21659        // genuinely started, then blocks - exactly as a spawned CLI process
21660        // does - until told to finish.
21661        let node = async move {
21662            started_tx.send(()).expect("send started");
21663            finish_rx.await.expect("recv finish");
21664            "node finished"
21665        };
21666
21667        let interrupter = async move {
21668            started_rx.await.expect("recv started");
21669            // The call is now genuinely in flight. Ask it to park.
21670            interrupt.park_because("higher-priority task waiting");
21671            // Nothing the node does can observe this yet - there is no
21672            // check inside it, by construction - so let the executor run
21673            // anything pending and then let the node finish on its own.
21674            tokio::task::yield_now().await;
21675            finish_tx.send(()).expect("send finish");
21676        };
21677
21678        let (node_result, ()) = tokio::join!(node, interrupter);
21679        assert_eq!(
21680            node_result, "node finished",
21681            "the in-flight call ran to completion"
21682        );
21683
21684        // Only now, at the boundary the real `execute` would check right
21685        // after this node, does the park take effect.
21686        assert!(runner.park_here().expect("park_here"));
21687        assert!(runner.state.parked);
21688    }
21689
21690    /// A run parked mid-competition carries every field it had accumulated
21691    /// through the exact same disk round-trip an ordinary resume uses -
21692    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21693    /// Nothing about parking for an interrupt is a special case of that path;
21694    /// this is what proves it rather than assuming it.
21695    #[test]
21696    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21697        crate::run::pin_test_home();
21698        let mut runner = runner_at(RunStatus::Judging);
21699        // `Runner::resume` re-resolves roles from the saved config, which
21700        // refuses an empty roster - give it the same minimal one `conductor`
21701        // itself uses.
21702        runner.state.config.agents = vec![conductor()];
21703        runner.state.candidates = vec![Candidate {
21704            index: 0,
21705            label: 'A',
21706            agent: "alpha".to_owned(),
21707            branch: "magi/x/A".to_owned(),
21708            worktree: PathBuf::from("/nonexistent/worktree"),
21709            summary: "did the thing".to_owned(),
21710            stat: "1 file changed".to_owned(),
21711            files: 1,
21712            commits: 1,
21713            empty: false,
21714            failed: None,
21715            verified_noop: None,
21716            duration_ms: 1234,
21717            folded: false,
21718        }];
21719        let run_id = runner.state.id.clone();
21720
21721        let interrupt = Pause::new();
21722        runner.watch_interrupt(interrupt.clone());
21723        interrupt.park_because("task c3d4 asked to run first");
21724        assert!(runner.park_here().expect("park_here"));
21725
21726        let resumed = Runner::resume(&run_id).expect("resume");
21727        assert_eq!(resumed.state.candidates.len(), 1);
21728        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21729        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21730        assert_eq!(resumed.state.status, runner.state.status);
21731        assert!(
21732            resumed.state.parked,
21733            "still parked until `execute` actually walks the graph again"
21734        );
21735        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21736    }
21737
21738    /// A fresh open question on `run`, stored and handed back for assertions.
21739    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21740        let mut q = ask::Question::new(
21741            run.to_owned(),
21742            "implement".to_owned(),
21743            "impl-A".to_owned(),
21744            "Which storage backend should the cache use?".to_owned(),
21745            String::new(),
21746            vec!["SQLite".to_owned(), "Redis".to_owned()],
21747        );
21748        store.put(&mut q).unwrap();
21749        q
21750    }
21751
21752    #[test]
21753    fn a_failed_runs_open_question_is_abandoned() {
21754        ask_test_home();
21755        let store = ask::Questions::open();
21756        let mut runner = runner_at(RunStatus::Failed);
21757        let run = runner.state.id.clone();
21758        let q = ask_open_question(&store, &run);
21759
21760        runner.settle_questions();
21761
21762        let back = store.get(&q.id).unwrap();
21763        assert!(
21764            !back.status.open(),
21765            "the seat that asked died with the run; nobody is left to read an answer"
21766        );
21767        assert!(
21768            back.detail.contains(&run) && back.detail.contains("failed"),
21769            "the reason names what the run became, not just that it is gone: {}",
21770            back.detail
21771        );
21772    }
21773
21774    #[test]
21775    fn a_merged_runs_open_question_is_abandoned_too() {
21776        ask_test_home();
21777        let store = ask::Questions::open();
21778        // A run that finishes cleanly still leaves nobody to read an answer -
21779        // this is not only a failure-path cleanup.
21780        for status in [RunStatus::Merged, RunStatus::Ready] {
21781            let mut runner = runner_at(status);
21782            let run = runner.state.id.clone();
21783            let q = ask_open_question(&store, &run);
21784
21785            runner.settle_questions();
21786
21787            let back = store.get(&q.id).unwrap();
21788            assert!(
21789                !back.status.open(),
21790                "{status:?} run's question must not outlive the run"
21791            );
21792        }
21793    }
21794
21795    #[test]
21796    fn a_still_resumable_runs_open_question_is_left_alone() {
21797        ask_test_home();
21798        let store = ask::Questions::open();
21799        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21800        // review round and the seat sessions are all still on disk — so a
21801        // question asked mid-round may yet get a real answer from a real
21802        // resume. Sweeping it here would be exactly the failure mode this
21803        // whole feature exists to avoid on the other side.
21804        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21805            let mut runner = runner_at(status);
21806            let run = runner.state.id.clone();
21807            let q = ask_open_question(&store, &run);
21808
21809            runner.settle_questions();
21810
21811            let back = store.get(&q.id).unwrap();
21812            assert!(
21813                back.status.open(),
21814                "{status:?} is still alive; the question must still be waiting"
21815            );
21816        }
21817    }
21818
21819    #[test]
21820    fn settle_questions_never_touches_an_already_answered_question() {
21821        ask_test_home();
21822        let store = ask::Questions::open();
21823        let mut runner = runner_at(RunStatus::Failed);
21824        let run = runner.state.id.clone();
21825        let mut q = ask_open_question(&store, &run);
21826        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21827            .unwrap();
21828        store.put(&mut q).unwrap();
21829
21830        // Called twice, the way a crash-recovered daemon reclaim and the
21831        // graph's own cleanup both can for the same run — `abandon_for_run`
21832        // only ever touches what is still open, so this must be inert both
21833        // times, not merely the second.
21834        runner.settle_questions();
21835        runner.settle_questions();
21836
21837        let back = store.get(&q.id).unwrap();
21838        assert_eq!(
21839            back.status,
21840            ask::QuestionStatus::Answered,
21841            "a real answer is a decision on record, never overwritten by a sweep"
21842        );
21843    }
21844
21845    #[tokio::test]
21846    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21847        let tmp = tempfile::tempdir().unwrap();
21848        let home = tmp.path().join("home");
21849        let repo = tmp.path().join("repo");
21850        std::fs::create_dir(&home).unwrap();
21851        std::fs::create_dir(&repo).unwrap();
21852        init_repo(&repo);
21853
21854        let mut config = Config::default();
21855        config.graph.worktree_root = Some(tmp.path().join("wt"));
21856        config.verify.build_cache = crate::config::BuildCache::Isolated;
21857        let mut state = RunState::new(
21858            repo.clone(),
21859            "main".into(),
21860            "base".into(),
21861            "fold fixture".into(),
21862            config,
21863        );
21864        let root = state.worktree_root();
21865        let mut outputs = Vec::new();
21866        for name in ["idle", "busy"] {
21867            let checkout = root.join(name);
21868            git::worktree_add_detached(&repo, &checkout, "main")
21869                .await
21870                .unwrap();
21871            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21872            let output = target.join("generated");
21873            std::fs::write(&output, name).unwrap();
21874            outputs.push((target, output));
21875        }
21876        let unknown = crate::build_target::root(&home)
21877            .join("00000000-0000-0000-0000-000000000000")
21878            .join("target");
21879        std::fs::create_dir_all(&unknown).unwrap();
21880        let unowned = unknown.join("generated");
21881        std::fs::write(&unowned, "keep").unwrap();
21882        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21883        let crate::cache::AcquireOutcome::Acquired(_lease) =
21884            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21885        else {
21886            panic!("fixture target must be free");
21887        };
21888
21889        state.save_under(&home).unwrap();
21890        fold_run(&mut state, true, &home).await.unwrap();
21891        assert!(!root.exists());
21892        assert!(!outputs[0].1.exists());
21893        assert!(outputs[1].1.is_file());
21894        assert!(unowned.is_file());
21895    }
21896
21897    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21898    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21899    /// without merging, whose winner is still the operator's answer to read.
21900    /// Nothing previously called `fold_run` itself with a real `tally`, so
21901    /// this is the first test to pin down the one distinction the whole
21902    /// automatic-fold feature depends on: the winner's worktree and branch
21903    /// must survive, everything else sharing the run's worktree bay - a
21904    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21905    /// second sweep treats every non-winner directory under the bay alike -
21906    /// must not.
21907    #[tokio::test]
21908    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21909        crate::run::pin_test_home();
21910        let tmp = tempfile::tempdir().expect("tempdir");
21911        let repo = tmp.path().join("repo");
21912        std::fs::create_dir_all(&repo).unwrap();
21913        init_repo(&repo);
21914
21915        let mut config = Config::default();
21916        config.graph.worktree_root = Some(tmp.path().join("wt"));
21917
21918        let mut state = RunState::new(
21919            repo.clone(),
21920            "main".to_owned(),
21921            "deadbeef".to_owned(),
21922            "task".to_owned(),
21923            config,
21924        );
21925        let root = state.worktree_root();
21926        let wt_a = root.join("cand-A");
21927        let wt_b = root.join("cand-B");
21928        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21929            .await
21930            .expect("worktree A");
21931        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21932            .await
21933            .expect("worktree B");
21934
21935        state.candidates = vec![
21936            Candidate {
21937                index: 0,
21938                label: 'A',
21939                agent: "alpha".to_owned(),
21940                branch: "magi/x/A".to_owned(),
21941                worktree: wt_a.clone(),
21942                summary: String::new(),
21943                stat: String::new(),
21944                files: 0,
21945                commits: 0,
21946                empty: false,
21947                failed: None,
21948                verified_noop: None,
21949                duration_ms: 0,
21950                folded: false,
21951            },
21952            Candidate {
21953                index: 1,
21954                label: 'B',
21955                agent: "beta".to_owned(),
21956                branch: "magi/x/B".to_owned(),
21957                worktree: wt_b.clone(),
21958                summary: String::new(),
21959                stat: String::new(),
21960                files: 0,
21961                commits: 0,
21962                empty: false,
21963                failed: None,
21964                verified_noop: None,
21965                duration_ms: 0,
21966                folded: false,
21967            },
21968        ];
21969        state.tally = Some(Tally {
21970            first_choice: BTreeMap::from([('A', 1)]),
21971            borda: BTreeMap::new(),
21972            winner: 'A',
21973            rankings: 1,
21974            unanimous_initial: true,
21975            deliberated: false,
21976            changed_votes: 0,
21977            unanimous_final: true,
21978            tie_break: None,
21979            judges: 1,
21980            present: 1,
21981            quorum: 1,
21982            met_quorum: true,
21983            uncontested: None,
21984        });
21985        state.status = RunStatus::Ready;
21986
21987        state.save_under(&crate::run::home()).unwrap();
21988        fold_run(&mut state, false, &crate::run::home())
21989            .await
21990            .expect("fold_run");
21991
21992        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21993        assert!(
21994            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21995            "the unmerged winner's branch survives"
21996        );
21997        assert!(
21998            !state.candidates[0].folded,
21999            "the winner is not marked folded"
22000        );
22001
22002        assert!(!wt_b.exists(), "the loser's worktree is removed");
22003        assert!(
22004            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
22005            "the loser's branch is removed"
22006        );
22007        assert!(state.candidates[1].folded, "the loser is marked folded");
22008    }
22009
22010    #[tokio::test]
22011    #[cfg(unix)]
22012    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
22013        use std::os::fd::AsRawFd as _;
22014        use std::time::Duration;
22015
22016        let tmp = tempfile::tempdir().unwrap();
22017        let repo = tmp.path().join("repo");
22018        std::fs::create_dir_all(&repo).unwrap();
22019        init_repo(&repo);
22020        let common = repo.join(".git");
22021        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22022        let home = tmp.path().join("home");
22023        let mut config = Config::default();
22024        config.coordination = crate::config::test_coordination();
22025        config.graph.worktree_root = Some(tmp.path().join("wt"));
22026        config.graph.timeout_resource_wait = 1;
22027        let mut state = RunState::new(
22028            repo.clone(),
22029            "main".into(),
22030            "deadbeef".into(),
22031            "task".into(),
22032            config,
22033        );
22034        let root = state.worktree_root();
22035        let candidate = root.join("cand-A");
22036        let reviewer = root.join("review-1");
22037        let branch = state.branch_for('A');
22038        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22039            .await
22040            .unwrap();
22041        git::worktree_add_detached(&repo, &reviewer, "main")
22042            .await
22043            .unwrap();
22044        git::acquire_worktree_config(&repo).await.unwrap();
22045        state.enabled_worktree_config = true;
22046        state.status = RunStatus::Ready;
22047        state.candidates.push(Candidate {
22048            index: 0,
22049            label: 'A',
22050            agent: "implement".into(),
22051            branch: branch.clone(),
22052            worktree: candidate.clone(),
22053            summary: String::new(),
22054            stat: String::new(),
22055            files: 0,
22056            commits: 0,
22057            empty: false,
22058            failed: None,
22059            verified_noop: None,
22060            duration_ms: 0,
22061            folded: false,
22062        });
22063        state.save_under(&home).unwrap();
22064        let config_before = std::fs::read(common.join("config")).unwrap();
22065        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
22066            .await
22067            .unwrap();
22068        // A separate OS handle bypasses the launcher's local gate, exactly as
22069        // an external updater does, and must still prevent all folding work.
22070        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22071        assert_eq!(
22072            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22073            0
22074        );
22075        let mut fold = Box::pin(fold_run(&mut state, true, &home));
22076        assert!(
22077            tokio::time::timeout(Duration::from_millis(200), &mut fold)
22078                .await
22079                .is_err()
22080        );
22081        assert!(candidate.exists());
22082        assert!(reviewer.exists());
22083        assert!(git::branch_exists(&repo, &branch).await.unwrap());
22084        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
22085        assert_eq!(
22086            git::git(&repo, &["worktree", "list", "--porcelain"])
22087                .await
22088                .unwrap(),
22089            worktrees_before
22090        );
22091        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
22092            .await
22093            .unwrap()
22094            .unwrap_err();
22095        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
22096        drop(fold);
22097        assert!(candidate.exists() && reviewer.exists());
22098        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
22099        assert_eq!(
22100            state.resource_block.as_ref().unwrap().kind,
22101            "repository coordination"
22102        );
22103        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
22104        drop(external);
22105        let mut fold = Box::pin(fold_run(&mut state, true, &home));
22106        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
22107            .await
22108            .unwrap()
22109            .unwrap();
22110        drop(fold);
22111        assert!(removed.contains(&branch));
22112        assert!(!root.exists());
22113        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
22114        assert!(state.candidates[0].folded);
22115        assert!(!state.enabled_worktree_config);
22116        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
22117        let enabled = git::git_raw(
22118            &repo,
22119            &["config", "--local", "--get", "extensions.worktreeConfig"],
22120        )
22121        .await
22122        .unwrap();
22123        assert!(!enabled.ok(), "the last config reference was released");
22124    }
22125
22126    /// A handover holds repository coordination and then asks for the
22127    /// predecessor's owner lock; an automatic fold already holds that lock. The
22128    /// fold asks for coordination once and gives way, so the handover's short
22129    /// retry succeeds - waiting for it would leave both waiting for each other.
22130    /// Nothing is changed or saved on the way out and the refusal is `live`;
22131    /// the explicit entry points (`magi fold`) still wait, bounded as before.
22132    #[tokio::test]
22133    #[cfg(unix)]
22134    async fn an_automatic_fold_gives_way_to_busy_coordination_instead_of_waiting() {
22135        use std::os::fd::AsRawFd as _;
22136        use std::time::Duration;
22137
22138        let tmp = tempfile::tempdir().unwrap();
22139        let repo = tmp.path().join("repo");
22140        std::fs::create_dir_all(&repo).unwrap();
22141        init_repo(&repo);
22142        let common = repo.join(".git");
22143        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22144        let home = tmp.path().join("home");
22145        let mut config = Config::default();
22146        config.coordination = crate::config::test_coordination();
22147        config.graph.worktree_root = Some(tmp.path().join("wt"));
22148        config.graph.timeout_resource_wait = 60;
22149        let mut state = RunState::new(
22150            repo.clone(),
22151            "main".into(),
22152            "deadbeef".into(),
22153            "task".into(),
22154            config,
22155        );
22156        let candidate = state.worktree_root().join("cand-A");
22157        let branch = state.branch_for('A');
22158        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22159            .await
22160            .unwrap();
22161        state.status = RunStatus::Ready;
22162        state.driver_exited = true;
22163        state.candidates.push(Candidate {
22164            index: 0,
22165            label: 'A',
22166            agent: "implement".into(),
22167            branch: branch.clone(),
22168            worktree: candidate.clone(),
22169            summary: String::new(),
22170            stat: String::new(),
22171            files: 0,
22172            commits: 0,
22173            empty: false,
22174            failed: None,
22175            verified_noop: None,
22176            duration_ms: 0,
22177            folded: false,
22178        });
22179        state.save_under(&home).unwrap();
22180        let id = state.id.clone();
22181        let record = std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap();
22182
22183        // A separate OS handle bypasses the launcher's local gate, exactly as
22184        // another process holding coordination does.
22185        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22186        assert_eq!(
22187            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22188            0
22189        );
22190        let error = tokio::time::timeout(
22191            Duration::from_secs(10),
22192            fold_run_when(&mut state, &home, &|_| Ok(true)),
22193        )
22194        .await
22195        .expect("the automatic fold does not wait out the 60 s resource wait")
22196        .unwrap_err();
22197        assert!(
22198            matches!(
22199                error.downcast_ref::<FoldRefusal>(),
22200                Some(FoldRefusal::Live(_))
22201            ),
22202            "{error:#}"
22203        );
22204        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
22205        // It gave way: both locks it held are free, nothing was removed and
22206        // nothing was saved (no resource block recorded on the record either).
22207        drop(crate::pr_head::owner_lock(&home, &id).expect("the owner lock was released"));
22208        drop(crate::driver::maintenance(&home, &id).expect("the execution lease was released"));
22209        assert!(candidate.exists() && git::branch_exists(&repo, &branch).await.unwrap());
22210        assert_eq!(
22211            std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap(),
22212            record
22213        );
22214
22215        // The explicit entry point was asked for by a person and still waits.
22216        assert!(
22217            tokio::time::timeout(
22218                Duration::from_millis(300),
22219                fold_run(&mut state, true, &home)
22220            )
22221            .await
22222            .is_err(),
22223            "an explicit fold keeps waiting for coordination"
22224        );
22225        assert!(candidate.exists());
22226
22227        drop(external);
22228        let removed = fold_run_when(&mut state, &home, &|_| Ok(true))
22229            .await
22230            .unwrap();
22231        assert!(removed.contains(&branch));
22232        assert!(!candidate.exists());
22233    }
22234
22235    /// A branch handed to a later run is that run's (and its pull request's):
22236    /// folding the run that released it must not delete it.
22237    #[tokio::test]
22238    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
22239        let tmp = tempfile::tempdir().expect("tempdir");
22240        let repo = tmp.path().join("repo");
22241        std::fs::create_dir_all(&repo).unwrap();
22242        init_repo(&repo);
22243        let home = tmp.path().join("home");
22244
22245        let mut config = Config::default();
22246        config.graph.worktree_root = Some(tmp.path().join("wt"));
22247        let mut state = RunState::new(
22248            repo.clone(),
22249            "main".to_owned(),
22250            "deadbeef".to_owned(),
22251            "task".to_owned(),
22252            config,
22253        );
22254        // The worktree is already gone (released); the branch survives.
22255        git::git(&repo, &["branch", "magi/x/A", "main"])
22256            .await
22257            .expect("branch");
22258        state.candidates = vec![Candidate {
22259            index: 0,
22260            label: 'A',
22261            agent: "alpha".to_owned(),
22262            branch: "magi/x/A".to_owned(),
22263            worktree: state.worktree_root().join("cand-A"),
22264            summary: String::new(),
22265            stat: String::new(),
22266            files: 0,
22267            commits: 0,
22268            empty: false,
22269            failed: None,
22270            verified_noop: None,
22271            duration_ms: 0,
22272            folded: true,
22273        }];
22274        state.released_to = Some("20260901-000000-new1".to_owned());
22275        state.released_branches = vec!["magi/x/A".to_owned()];
22276
22277        state.save_under(&home).unwrap();
22278        fold_run(&mut state, true, &home).await.expect("fold_run");
22279        state.status = RunStatus::Merged;
22280        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
22281        state.merge = Some(crate::run::MergeOutcome {
22282            mode: MergeMode::Pr,
22283            ok: true,
22284            detail: "confirmed merged".into(),
22285            empty: false,
22286        });
22287        state.save_under(&home).unwrap();
22288        fold_run(&mut state, true, &home)
22289            .await
22290            .expect("merged fold");
22291
22292        assert!(
22293            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
22294            "the handed-over branch survives a fold"
22295        );
22296    }
22297
22298    /// A winner with nothing ahead of the base is caught before `gh` is ever
22299    /// asked for a pull request, and the message carries what the task's
22300    /// references resolved to.
22301    #[tokio::test]
22302    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
22303        let tmp = tempfile::tempdir().expect("tempdir");
22304        let repo = tmp.path().join("repo");
22305        std::fs::create_dir_all(&repo).unwrap();
22306        init_repo(&repo);
22307        let run = |args: &[&str]| {
22308            let out = std::process::Command::new("git")
22309                .quiet()
22310                .args(args)
22311                .current_dir(&repo)
22312                .output()
22313                .expect("spawn git");
22314            assert!(out.status.success(), "git {args:?}");
22315        };
22316        run(&["branch", "magi/x/A"]);
22317        run(&["checkout", "-q", "-b", "magi/x/B"]);
22318        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
22319        run(&["add", "-A"]);
22320        run(&["commit", "-q", "-m", "work"]);
22321        run(&["checkout", "-q", "main"]);
22322
22323        // A pull request is compared against the remote's base, so the
22324        // fixture needs one. Before it exists nothing can be read, and the
22325        // answer must be "not empty".
22326        let probe = RunState::new(
22327            repo.clone(),
22328            "main".to_owned(),
22329            "deadbeef".to_owned(),
22330            "task".to_owned(),
22331            Config::default(),
22332        );
22333        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
22334        let bare = tmp.path().join("origin.git");
22335        let out = std::process::Command::new("git")
22336            .quiet()
22337            .args(["init", "-q", "--bare"])
22338            .arg(&bare)
22339            .output()
22340            .expect("spawn git");
22341        assert!(out.status.success(), "git init --bare");
22342        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
22343        run(&["push", "-q", "origin", "main"]);
22344
22345        let mut state = RunState::new(
22346            repo.clone(),
22347            "main".to_owned(),
22348            "deadbeef".to_owned(),
22349            "task".to_owned(),
22350            Config::default(),
22351        );
22352        state.seeds = vec![refs::Seed {
22353            token: "magi/27b2/A".to_owned(),
22354            kind: refs::SeedKind::Unresolved,
22355            sha: String::new(),
22356            branch: true,
22357            detail: "no branch or commit named magi/27b2/A".to_owned(),
22358        }];
22359
22360        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
22361        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
22362        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
22363        let detail = empty_candidate_detail(&state, "main");
22364        assert!(detail.starts_with("empty candidate"), "{detail}");
22365        assert!(!detail.contains("magi/27b2/A"), "{detail}");
22366        assert!(detail.contains("--start-from"), "{detail}");
22367    }
22368
22369    /// `status == Ready` used to be read as "this is the harmless
22370    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
22371    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
22372    /// run's PR was closed without merging — and reentering `merge` with
22373    /// `mode` still `Pr` does not know the difference, so it pushed and
22374    /// opened a second pull request. `mode == Local` reproduces the same
22375    /// blind spot without a network call: reentry must not attempt another
22376    /// git merge once this node has already recorded an outcome.
22377    #[tokio::test]
22378    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
22379        let tmp = tempfile::tempdir().expect("tempdir");
22380        let repo = tmp.path().join("repo");
22381        std::fs::create_dir_all(&repo).unwrap();
22382        init_repo(&repo);
22383
22384        let mut config = Config::default();
22385        config.merge.mode = MergeMode::Local;
22386
22387        let mut state = RunState::new(
22388            repo.clone(),
22389            "main".to_owned(),
22390            "deadbeef".to_owned(),
22391            "task".to_owned(),
22392            config,
22393        );
22394        state.candidates = vec![Candidate {
22395            index: 0,
22396            label: 'A',
22397            agent: "alpha".to_owned(),
22398            branch: "does-not-exist".to_owned(),
22399            worktree: repo.clone(),
22400            summary: String::new(),
22401            stat: String::new(),
22402            files: 0,
22403            commits: 0,
22404            empty: false,
22405            failed: None,
22406            verified_noop: None,
22407            duration_ms: 0,
22408            folded: false,
22409        }];
22410        state.tally = Some(Tally {
22411            first_choice: BTreeMap::from([('A', 1)]),
22412            borda: BTreeMap::new(),
22413            winner: 'A',
22414            rankings: 1,
22415            unanimous_initial: true,
22416            deliberated: false,
22417            changed_votes: 0,
22418            unanimous_final: true,
22419            tie_break: None,
22420            judges: 0,
22421            present: 0,
22422            quorum: 0,
22423            met_quorum: true,
22424            uncontested: Some("only candidate A produced a change".to_owned()),
22425        });
22426        state.reviews = vec![ReviewRound {
22427            round: 1,
22428            head: "deadbeef".to_owned(),
22429            verified_head: None,
22430            verified_at: None,
22431            reviews: Vec::new(),
22432            e2e: Vec::new(),
22433            fix: None,
22434            blocking: 0,
22435            answered: 0,
22436            expected: 0,
22437            clean: true,
22438            verify_retried: false,
22439            e2e_deferred: false,
22440            e2e_defer_reason: None,
22441            progressed: false,
22442            vote_split: false,
22443            reconsideration: Vec::new(),
22444            verdict: None,
22445        }];
22446        state.gate = vec![CommandOutcome {
22447            command: "test".to_owned(),
22448            code: Some(0),
22449            output_tail: String::new(),
22450            duration_ms: 0,
22451            resource_blocked: false,
22452            ..Default::default()
22453        }];
22454        state.gate_ran = true;
22455        // Reached its conclusion already — e.g. `land` closing the PR without
22456        // merging it, which (like the honest `MergeMode::None` path) leaves
22457        // `status` at `Ready`. The recorded outcome is what actually marks
22458        // this node done.
22459        state.status = RunStatus::Ready;
22460        state.merge = Some(MergeOutcome {
22461            mode: MergeMode::Local,
22462            ok: false,
22463            detail: "already concluded".to_owned(),
22464            empty: false,
22465        });
22466
22467        let mut runner = Runner {
22468            state,
22469            roles: ResolvedRoles {
22470                implementers: Vec::new(),
22471                judges: Vec::new(),
22472                reviewers: Vec::new(),
22473                fixer: None,
22474                conductor: conductor(),
22475                implementer_roster: Vec::new(),
22476                judge_roster: Vec::new(),
22477                reviewer_roster: Vec::new(),
22478            },
22479            sem: Arc::new(Semaphore::new(1)),
22480            pause: Pause::new(),
22481            interrupt: Pause::new(),
22482        };
22483
22484        runner.merge().await.expect("merge");
22485
22486        assert_eq!(
22487            runner.state.status,
22488            RunStatus::Ready,
22489            "a concluded run's status must not change on reentry"
22490        );
22491        assert_eq!(
22492            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22493            Some("already concluded"),
22494            "merge must not run again once the node already recorded an outcome"
22495        );
22496    }
22497
22498    /// `gate` leaves `state.gate_ran` false both before it has ever run and
22499    /// when its last attempt was resource-blocked (the shared build cache
22500    /// could not be acquired or confirmed fresh in time - see
22501    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
22502    /// `Vec` this also leaves behind used to read as "nothing failed" and let
22503    /// a run merge a tree the gate never actually checked - exactly the case
22504    /// a contended cache produces on every retry until it clears. `merge`
22505    /// must refuse until `gate` has actually recorded an attempt.
22506    #[tokio::test]
22507    async fn merge_refuses_a_gate_that_has_not_actually_run() {
22508        let tmp = tempfile::tempdir().expect("tempdir");
22509        let repo = tmp.path().join("repo");
22510        std::fs::create_dir_all(&repo).unwrap();
22511        init_repo(&repo);
22512
22513        let mut config = Config::default();
22514        config.merge.mode = MergeMode::Local;
22515
22516        let mut state = RunState::new(
22517            repo.clone(),
22518            "main".to_owned(),
22519            "deadbeef".to_owned(),
22520            "task".to_owned(),
22521            config,
22522        );
22523        state.candidates = vec![Candidate {
22524            index: 0,
22525            label: 'A',
22526            agent: "alpha".to_owned(),
22527            branch: "does-not-exist".to_owned(),
22528            worktree: repo.clone(),
22529            summary: String::new(),
22530            stat: String::new(),
22531            files: 0,
22532            commits: 0,
22533            empty: false,
22534            failed: None,
22535            verified_noop: None,
22536            duration_ms: 0,
22537            folded: false,
22538        }];
22539        state.tally = Some(Tally {
22540            first_choice: BTreeMap::from([('A', 1)]),
22541            borda: BTreeMap::new(),
22542            winner: 'A',
22543            rankings: 1,
22544            unanimous_initial: true,
22545            deliberated: false,
22546            changed_votes: 0,
22547            unanimous_final: true,
22548            tie_break: None,
22549            judges: 0,
22550            present: 0,
22551            quorum: 0,
22552            met_quorum: true,
22553            uncontested: Some("only candidate A produced a change".to_owned()),
22554        });
22555        state.reviews = vec![ReviewRound {
22556            round: 1,
22557            head: "deadbeef".to_owned(),
22558            verified_head: None,
22559            verified_at: None,
22560            reviews: Vec::new(),
22561            e2e: Vec::new(),
22562            fix: None,
22563            blocking: 0,
22564            answered: 0,
22565            expected: 0,
22566            clean: true,
22567            verify_retried: false,
22568            e2e_deferred: false,
22569            e2e_defer_reason: None,
22570            progressed: false,
22571            vote_split: false,
22572            reconsideration: Vec::new(),
22573            verdict: None,
22574        }];
22575        // The point: `gate` has not recorded anything yet.
22576        state.gate = Vec::new();
22577        state.gate_ran = false;
22578        state.status = RunStatus::Gating;
22579
22580        let mut runner = Runner {
22581            state,
22582            roles: ResolvedRoles {
22583                implementers: Vec::new(),
22584                judges: Vec::new(),
22585                reviewers: Vec::new(),
22586                fixer: None,
22587                conductor: conductor(),
22588                implementer_roster: Vec::new(),
22589                judge_roster: Vec::new(),
22590                reviewer_roster: Vec::new(),
22591            },
22592            sem: Arc::new(Semaphore::new(1)),
22593            pause: Pause::new(),
22594            interrupt: Pause::new(),
22595        };
22596
22597        runner.merge().await.expect("merge");
22598
22599        assert!(
22600            runner.state.merge.is_none(),
22601            "an empty gate must never be read as a passing one: {:?}",
22602            runner.state.merge
22603        );
22604    }
22605
22606    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
22607    /// commands configured and `merge.mode` is `none` (a review-only run).
22608    /// `gate` must still record a real attempt — zero commands, vacuously
22609    /// passed — rather than leaving `state.gate` empty in a way `merge`
22610    /// cannot tell apart from "never ran"; otherwise the run reaches
22611    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
22612    #[tokio::test]
22613    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
22614        let tmp = tempfile::tempdir().expect("tempdir");
22615        let repo = tmp.path().join("repo");
22616        std::fs::create_dir_all(&repo).unwrap();
22617        init_repo(&repo);
22618
22619        // Default config: `verify.gate` empty, `merge.mode` is `none`.
22620        let config = Config::default();
22621
22622        let mut state = RunState::new(
22623            repo.clone(),
22624            "main".to_owned(),
22625            "deadbeef".to_owned(),
22626            "task".to_owned(),
22627            config,
22628        );
22629        state.candidates = vec![Candidate {
22630            index: 0,
22631            label: 'A',
22632            agent: "alpha".to_owned(),
22633            branch: "does-not-exist".to_owned(),
22634            worktree: repo.clone(),
22635            summary: String::new(),
22636            stat: String::new(),
22637            files: 0,
22638            commits: 0,
22639            empty: false,
22640            failed: None,
22641            verified_noop: None,
22642            duration_ms: 0,
22643            folded: false,
22644        }];
22645        state.tally = Some(Tally {
22646            first_choice: BTreeMap::from([('A', 1)]),
22647            borda: BTreeMap::new(),
22648            winner: 'A',
22649            rankings: 1,
22650            unanimous_initial: true,
22651            deliberated: false,
22652            changed_votes: 0,
22653            unanimous_final: true,
22654            tie_break: None,
22655            judges: 0,
22656            present: 0,
22657            quorum: 0,
22658            met_quorum: true,
22659            uncontested: Some("only candidate A produced a change".to_owned()),
22660        });
22661        state.reviews = vec![ReviewRound {
22662            round: 1,
22663            head: "deadbeef".to_owned(),
22664            verified_head: None,
22665            verified_at: None,
22666            reviews: Vec::new(),
22667            e2e: Vec::new(),
22668            fix: None,
22669            blocking: 0,
22670            answered: 0,
22671            expected: 0,
22672            clean: true,
22673            verify_retried: false,
22674            e2e_deferred: false,
22675            e2e_defer_reason: None,
22676            progressed: false,
22677            vote_split: false,
22678            reconsideration: Vec::new(),
22679            verdict: None,
22680        }];
22681
22682        let mut runner = Runner {
22683            state,
22684            roles: ResolvedRoles {
22685                implementers: Vec::new(),
22686                judges: Vec::new(),
22687                reviewers: Vec::new(),
22688                fixer: None,
22689                conductor: conductor(),
22690                implementer_roster: Vec::new(),
22691                judge_roster: Vec::new(),
22692                reviewer_roster: Vec::new(),
22693            },
22694            sem: Arc::new(Semaphore::new(1)),
22695            pause: Pause::new(),
22696            interrupt: Pause::new(),
22697        };
22698
22699        runner.gate().await.expect("gate");
22700        assert!(
22701            runner.state.gate_ran,
22702            "zero configured commands is still a real attempt, not an unrun gate"
22703        );
22704        assert!(runner.state.gate.is_empty());
22705        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
22706        assert_ne!(
22707            runner.state.status,
22708            RunStatus::Blocked,
22709            "a gate with nothing to check must not read as failed"
22710        );
22711
22712        runner.merge().await.expect("merge");
22713        assert_eq!(
22714            runner.state.status,
22715            RunStatus::Ready,
22716            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
22717        );
22718    }
22719
22720    /// `Config::cache_dir` is derived from `verify.e2e` as well as
22721    /// `verify.gate` (so the e2e leg and the final gate never build against
22722    /// different directories). With zero `verify.gate` commands but a
22723    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
22724    /// that lease before discovering it had nothing to run - so a repo with
22725    /// no gate commands could come back `resource_blocked` (and therefore
22726    /// still `gate_ran == false`) on nothing but an unrelated run holding the
22727    /// cache, exactly the contention this run's own zero commands could
22728    /// never have touched. `gate` must recognise there is nothing to check
22729    /// before it ever asks for the lease.
22730    #[tokio::test]
22731    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
22732        crate::run::pin_test_home();
22733        let home = crate::run::home();
22734
22735        let tmp = tempfile::tempdir().expect("tempdir");
22736        let repo = tmp.path().join("repo");
22737        std::fs::create_dir_all(&repo).unwrap();
22738        init_repo(&repo);
22739        // Unique to this test, so holding its lease cannot collide with
22740        // another test sharing the same process-wide `home`.
22741        let cache_dir = tmp.path().join("target");
22742
22743        let mut config = Config::default();
22744        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
22745        // `verify.gate` stays empty (the default). Any accidental cache
22746        // acquisition must report contention immediately, regardless of how
22747        // long unrelated Git subprocesses take under parallel test load.
22748        config.graph.timeout_verify = Some(2);
22749        config.graph.timeout_resource_wait = 0;
22750
22751        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22752        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22753            .expect("no io error acquiring directly")
22754        {
22755            crate::cache::AcquireOutcome::Acquired(g) => g,
22756            crate::cache::AcquireOutcome::Busy(b) => {
22757                panic!("expected the direct acquire to win the lease first: {b:?}")
22758            }
22759        };
22760
22761        let mut state = RunState::new(
22762            repo.clone(),
22763            "main".to_owned(),
22764            "deadbeef".to_owned(),
22765            "task".to_owned(),
22766            config,
22767        );
22768        state.candidates = vec![Candidate {
22769            index: 0,
22770            label: 'A',
22771            agent: "alpha".to_owned(),
22772            branch: "does-not-exist".to_owned(),
22773            worktree: repo.clone(),
22774            summary: String::new(),
22775            stat: String::new(),
22776            files: 0,
22777            commits: 0,
22778            empty: false,
22779            failed: None,
22780            verified_noop: None,
22781            duration_ms: 0,
22782            folded: false,
22783        }];
22784        state.tally = Some(Tally {
22785            first_choice: BTreeMap::from([('A', 1)]),
22786            borda: BTreeMap::new(),
22787            winner: 'A',
22788            rankings: 1,
22789            unanimous_initial: true,
22790            deliberated: false,
22791            changed_votes: 0,
22792            unanimous_final: true,
22793            tie_break: None,
22794            judges: 0,
22795            present: 0,
22796            quorum: 0,
22797            met_quorum: true,
22798            uncontested: Some("only candidate A produced a change".to_owned()),
22799        });
22800        state.reviews = vec![ReviewRound {
22801            round: 1,
22802            head: "deadbeef".to_owned(),
22803            verified_head: None,
22804            verified_at: None,
22805            reviews: Vec::new(),
22806            e2e: Vec::new(),
22807            fix: None,
22808            blocking: 0,
22809            answered: 0,
22810            expected: 0,
22811            clean: true,
22812            verify_retried: false,
22813            e2e_deferred: false,
22814            e2e_defer_reason: None,
22815            progressed: false,
22816            vote_split: false,
22817            reconsideration: Vec::new(),
22818            verdict: None,
22819        }];
22820
22821        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22822        state.reviews[0].e2e = vec![CommandOutcome {
22823            command: state.config.verify.e2e[0].clone(),
22824            code: Some(0),
22825            output_tail: String::new(),
22826            duration_ms: 0,
22827            resource_blocked: false,
22828            ..Default::default()
22829        }];
22830        let mut runner = Runner {
22831            state,
22832            roles: ResolvedRoles {
22833                implementers: Vec::new(),
22834                judges: Vec::new(),
22835                reviewers: Vec::new(),
22836                fixer: None,
22837                conductor: conductor(),
22838                implementer_roster: Vec::new(),
22839                judge_roster: Vec::new(),
22840                reviewer_roster: Vec::new(),
22841            },
22842            sem: Arc::new(Semaphore::new(1)),
22843            pause: Pause::new(),
22844            interrupt: Pause::new(),
22845        };
22846
22847        runner.gate().await.expect("gate");
22848        assert!(runner.state.resource_block.is_none());
22849        assert!(
22850            !runner
22851                .state
22852                .events
22853                .iter()
22854                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22855            "a gate with nothing to run must never request the held cache lease"
22856        );
22857        assert!(
22858            runner.state.gate_ran,
22859            "zero commands is still a real, immediate attempt"
22860        );
22861        assert!(runner.state.gate.is_empty());
22862        assert_ne!(
22863            runner.state.status,
22864            RunStatus::Blocked,
22865            "must not read as resource-blocked on a lease it never asked for"
22866        );
22867    }
22868
22869    /// A separate process carries a live worker's environment throughout all
22870    /// verification entry points; the parallel harness never changes its env.
22871    #[cfg(unix)]
22872    #[tokio::test]
22873    async fn verification_is_standalone_inside_a_live_worker() {
22874        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22875        if std::env::var_os(CHILD).is_none() {
22876            let home = tempfile::tempdir().unwrap();
22877            let generation = crate::worker::pin_current(home.path()).unwrap();
22878            let output = std::process::Command::new(std::env::current_exe().unwrap())
22879                .args([
22880                    "--exact",
22881                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22882                    "--nocapture",
22883                ])
22884                .env(CHILD, "1")
22885                .env("MAGI_HOME", home.path())
22886                .env("MAGI_WORKER_HOME", home.path())
22887                .env("MAGI_WORKER_ID", "abcdef")
22888                .env("MAGI_WORKER_GENERATION", &generation.id)
22889                .env("MAGI_WORKER_EXE", &generation.executable)
22890                .env("MAGI_RUN", "verification-parent")
22891                .env("MAGI_NODE", "gate")
22892                .env("MAGI_SEAT", "worker-fixture")
22893                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22894                .env("MAGI_NO_AUTOUPDATE", "0")
22895                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22896                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22897                .env(
22898                    "VERIFY_EXPECT_TOOLCHAIN",
22899                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22900                )
22901                .env(
22902                    "VERIFY_EXPECT_CACHE",
22903                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22904                )
22905                .output()
22906                .unwrap();
22907            assert!(
22908                output.status.success()
22909                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22910                "{}\n{}",
22911                String::from_utf8_lossy(&output.stdout),
22912                String::from_utf8_lossy(&output.stderr)
22913            );
22914            return;
22915        }
22916        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22917        let home = crate::run::home();
22918        let directory = home.join("workers/jobs/abcdef");
22919        std::fs::create_dir_all(&directory).unwrap();
22920        let job = crate::worker::Job {
22921            id: "abcdef".into(),
22922            sequence: 1,
22923            kind: "task".into(),
22924            key: "task:verification".into(),
22925            payload: serde_json::json!({}),
22926            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22927            version: Some(env!("CARGO_PKG_VERSION").into()),
22928            status: crate::worker::Status::Running,
22929            result: None,
22930            pid: Some(std::process::id()),
22931            created_at: 0,
22932            finished_at: None,
22933        };
22934        std::fs::write(
22935            directory.join("job.json"),
22936            serde_json::to_vec(&job).unwrap(),
22937        )
22938        .unwrap();
22939        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22940        let assert_worker = || {
22941            assert_eq!(
22942                crate::worker::current_job(&home).unwrap().unwrap().id,
22943                job.id
22944            );
22945            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22946            assert_eq!(
22947                crate::worker::helper_executable(&home).unwrap(),
22948                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22949            );
22950            assert!(
22951                crate::updater::Checker::new(&crate::config::Update {
22952                    mode: crate::config::UpdateMode::Notify,
22953                    interval: None,
22954                    auto_restart: false,
22955                })
22956                .is_none(),
22957                "the driver remains pinned, even while tests are standalone"
22958            );
22959        };
22960        assert_worker();
22961        let repo = home.join("repo");
22962        std::fs::create_dir_all(&repo).unwrap();
22963        init_repo(&repo);
22964        // Keep storage, seat/control context, containment and tool lookup.
22965        // No inherited values (or credentials) are printed on success.
22966        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22967            test -z "${MAGI_WORKER_GENERATION+x}" &&
22968            test -z "${MAGI_WORKER_HOME+x}" &&
22969            test -z "${MAGI_WORKER_EXE+x}" &&
22970            test "$MAGI_HOME/repo" -ef . &&
22971            test "$MAGI_RUN" = verification-parent &&
22972            test "$MAGI_NODE" = gate &&
22973            test "$MAGI_SEAT" = worker-fixture &&
22974            test -n "$MAGI_PROCESS_OWNER" &&
22975            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22976            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22977            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22978            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22979        // Negative control: an ordinary child inherits the contamination.
22980        assert!(
22981            !std::process::Command::new("sh")
22982                .args(["-c", probe])
22983                .current_dir(&repo)
22984                .status()
22985                .unwrap()
22986                .success()
22987        );
22988        let unrelated_home = tempfile::tempdir().unwrap();
22989        assert!(
22990            crate::worker::current_job(unrelated_home.path()).is_err(),
22991            "an inherited worker id cannot be resolved in a unit fixture's home"
22992        );
22993        let mut runner = runner_at(RunStatus::Gating);
22994        runner.state.repo = repo.clone();
22995        runner.state.config.disk.min_free_bytes = 0;
22996        runner.state.config.coordination = crate::config::test_coordination();
22997        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
22998        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
22999        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
23000        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
23001        let winner = Candidate {
23002            index: 0,
23003            label: 'A',
23004            agent: "fixture".into(),
23005            branch: "main".into(),
23006            worktree: repo.clone(),
23007            summary: String::new(),
23008            stat: String::new(),
23009            files: 0,
23010            commits: 0,
23011            empty: false,
23012            failed: None,
23013            verified_noop: None,
23014            duration_ms: 0,
23015            folded: false,
23016        };
23017        let (e2e, retried, pids) = run_e2e_with_retry(
23018            &mut runner.state,
23019            &["sh".into(), "-c".into()],
23020            &[format!("{probe} && printf initial")],
23021            &repo,
23022            Duration::from_secs(10),
23023            "initial",
23024            None,
23025        )
23026        .await;
23027        assert!(!retried && pids.is_empty());
23028        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
23029        assert_eq!(e2e[0].output_tail, "initial");
23030        let gate = runner.run_gate(&winner).await.unwrap();
23031        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
23032        // An interrupted repair must recheck e2e from saved state. Landing
23033        // reuses that state and must run both pre-gate and gate again.
23034        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
23035            git::rev_parse(&repo, "HEAD").await.unwrap(),
23036            false,
23037            Vec::new(),
23038        ));
23039        runner.state.save().unwrap();
23040        let mut resumed = RunState::load(&runner.state.id).unwrap();
23041        let wait = crate::repo_lock::WaitPolicy::default();
23042        assert!(matches!(
23043            check_gate_repair_e2e(&mut resumed, &winner, &wait)
23044                .await
23045                .unwrap(),
23046            GateFix::Retry
23047        ));
23048        let saved = RunState::load(&resumed.id).unwrap();
23049        let repair = saved.gate_repair_e2e.unwrap();
23050        assert!(repair.passed);
23051        assert_eq!(repair.outcomes.len(), 1);
23052        assert!(repair.outcomes[0].ok());
23053        let landing = run_landing_gate(&mut resumed, &winner, &wait)
23054            .await
23055            .unwrap();
23056        assert_eq!(landing.len(), 1);
23057        assert!(landing[0].ok(), "{landing:?}");
23058        assert_eq!(
23059            std::fs::read_to_string(repo.join("phases")).unwrap(),
23060            "pre\ngate\ne2e\npre\ngate\n"
23061        );
23062        assert_worker();
23063    }
23064
23065    #[cfg(unix)]
23066    #[tokio::test]
23067    async fn verification_keeps_the_panic_and_the_full_output() {
23068        crate::run::pin_test_home();
23069        let tmp = tempfile::tempdir().unwrap();
23070        let mut config = Config::default();
23071        config.disk.min_free_bytes = 0;
23072        let mut state = RunState::new(
23073            tmp.path().to_owned(),
23074            "main".into(),
23075            "base".into(),
23076            "verification evidence".into(),
23077            config,
23078        );
23079        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
23080                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
23081                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
23082        let mut names = Vec::new();
23083        for _ in 0..2 {
23084            let (outcomes, _) = run_commands(
23085                &mut state,
23086                "gate",
23087                "gate",
23088                0,
23089                &["sh".into(), "-c".into()],
23090                &[script.into()],
23091                tmp.path(),
23092                Duration::from_secs(60),
23093            )
23094            .await;
23095            let tail = &outcomes[0].output_tail;
23096            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
23097            assert!(tail.contains("boom assertion"));
23098            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
23099            let line = tail.lines().next().unwrap();
23100            names.push(line.to_owned());
23101        }
23102        assert_ne!(names[0], names[1], "the second run must not overwrite");
23103        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
23104        assert!(full.len() > 500_000 && full.contains("boom assertion"));
23105        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
23106
23107        // Storage failures are evidence too; preserve the command's verdict.
23108        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
23109        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
23110        let (outcomes, _) = run_commands(
23111            &mut state,
23112            "gate",
23113            "gate",
23114            0,
23115            &["sh".into(), "-c".into()],
23116            &["echo failure-output; exit 7".into()],
23117            tmp.path(),
23118            Duration::from_secs(10),
23119        )
23120        .await;
23121        assert_eq!(outcomes[0].code, Some(7));
23122        assert!(state.events.iter().any(|e| {
23123            e.node == "gate" && e.message.contains("could not save the full gate output:")
23124        }));
23125    }
23126
23127    #[cfg(unix)]
23128    #[tokio::test]
23129    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
23130        crate::run::pin_test_home();
23131        let tmp = tempfile::tempdir().unwrap();
23132        let mut config = Config::default();
23133        config.disk.min_free_bytes = 0;
23134        let mut state = RunState::new(
23135            tmp.path().to_owned(),
23136            "main".into(),
23137            "base".into(),
23138            "verification evidence".into(),
23139            config,
23140        );
23141        let (outcomes, pids) = run_commands(
23142            &mut state,
23143            "gate",
23144            "gate",
23145            1,
23146            &["sh".into(), "-c".into()],
23147            &[
23148                "printf before-timeout; exec sleep 30".into(),
23149                "kill -TERM $$".into(),
23150                "exit 7".into(),
23151                "printf success".into(),
23152            ],
23153            tmp.path(),
23154            Duration::from_secs(1),
23155        )
23156        .await;
23157        wait_for_timed_out_children_to_die(&pids).await;
23158        assert_eq!(
23159            pids.len(),
23160            1,
23161            "unleased timeout retains its death-check PID"
23162        );
23163        assert_eq!(outcomes.len(), 4);
23164        assert_eq!(outcomes[0].code, None);
23165        assert!(outcomes[0].output_tail.contains("before-timeout"));
23166        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
23167        assert_eq!(outcomes[1].code, None);
23168        assert!(outcomes[1].output_tail.contains("command terminated:"));
23169        assert!(!outcomes[1].output_tail.contains("timed out"));
23170        assert_eq!(outcomes[2].code, Some(7));
23171        assert!(!outcomes[2].output_tail.contains("timed out"));
23172        assert_eq!(outcomes[3].code, Some(0));
23173        assert_eq!(outcomes[3].output_tail, "success");
23174        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
23175    }
23176
23177    /// The addendum's second gap: a `verify.gate` command running for real
23178    /// wall-clock time had nothing at all to show for it in `active` before
23179    /// `run_commands` learned to record it — a run could sit in `Gating` for
23180    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
23181    /// what was actually happening. Proven with a genuinely still-running
23182    /// command, not just a before/after check on the final state: a poller
23183    /// task reads the same `run.json` `gate()` is writing, the same way the
23184    /// phone or `magi show` would, while the shell command is still blocked
23185    /// on its own release marker.
23186    #[tokio::test]
23187    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
23188        crate::run::pin_test_home();
23189
23190        let tmp = tempfile::tempdir().expect("tempdir");
23191        let repo = tmp.path().join("repo");
23192        std::fs::create_dir_all(&repo).unwrap();
23193        init_repo(&repo);
23194
23195        let mut config = Config::default();
23196        config.disk.min_free_bytes = 0;
23197        config.verify.gate = vec![
23198            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
23199             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
23200                .to_owned(),
23201        ];
23202
23203        let mut state = RunState::new(
23204            repo.clone(),
23205            "main".to_owned(),
23206            "deadbeef".to_owned(),
23207            "task".to_owned(),
23208            config,
23209        );
23210        let run_id = state.id.clone();
23211        state.candidates = vec![Candidate {
23212            index: 0,
23213            label: 'A',
23214            agent: "alpha".to_owned(),
23215            branch: "does-not-exist".to_owned(),
23216            worktree: repo.clone(),
23217            summary: String::new(),
23218            stat: String::new(),
23219            files: 0,
23220            commits: 0,
23221            empty: false,
23222            failed: None,
23223            verified_noop: None,
23224            duration_ms: 0,
23225            folded: false,
23226        }];
23227        state.tally = Some(Tally {
23228            first_choice: BTreeMap::from([('A', 1)]),
23229            borda: BTreeMap::new(),
23230            winner: 'A',
23231            rankings: 1,
23232            unanimous_initial: true,
23233            deliberated: false,
23234            changed_votes: 0,
23235            unanimous_final: true,
23236            tie_break: None,
23237            judges: 0,
23238            present: 0,
23239            quorum: 0,
23240            met_quorum: true,
23241            uncontested: Some("only candidate A produced a change".to_owned()),
23242        });
23243        state.reviews = vec![ReviewRound {
23244            round: 1,
23245            head: "deadbeef".to_owned(),
23246            verified_head: None,
23247            verified_at: None,
23248            reviews: Vec::new(),
23249            e2e: Vec::new(),
23250            fix: None,
23251            blocking: 0,
23252            answered: 0,
23253            expected: 0,
23254            clean: true,
23255            verify_retried: false,
23256            e2e_deferred: false,
23257            e2e_defer_reason: None,
23258            progressed: false,
23259            vote_split: false,
23260            reconsideration: Vec::new(),
23261            verdict: None,
23262        }];
23263
23264        let mut runner = Runner {
23265            state,
23266            roles: ResolvedRoles {
23267                implementers: Vec::new(),
23268                judges: Vec::new(),
23269                reviewers: Vec::new(),
23270                fixer: None,
23271                conductor: conductor(),
23272                implementer_roster: Vec::new(),
23273                judge_roster: Vec::new(),
23274                reviewer_roster: Vec::new(),
23275            },
23276            sem: Arc::new(Semaphore::new(1)),
23277            pause: Pause::new(),
23278            interrupt: Pause::new(),
23279        };
23280
23281        let started_marker = repo.join("started.marker");
23282        let release_marker = repo.join("release.marker");
23283        let observe = async {
23284            loop {
23285                if started_marker.exists()
23286                    && let Ok(s) = crate::run::RunState::load(&run_id)
23287                    && let Some(a) = s.active.get("gate")
23288                {
23289                    std::fs::write(&release_marker, b"go").expect("release marker");
23290                    break a.clone();
23291                }
23292                tokio::time::sleep(Duration::from_millis(50)).await;
23293            }
23294        };
23295        let captured = {
23296            let gate = runner.gate();
23297            tokio::pin!(gate);
23298            let captured = tokio::select! {
23299                observed = observe => observed,
23300                result = &mut gate => panic!(
23301                    "gate exited before its in-flight entry was observed: {result:?}"
23302                ),
23303            };
23304            gate.await.expect("gate");
23305            captured
23306        };
23307
23308        assert_eq!(captured.task.as_deref(), Some("gate"));
23309        assert_eq!(captured.node, "gate");
23310        assert_eq!(captured.index, Some(1));
23311        assert_eq!(captured.total, Some(1));
23312        assert!(
23313            captured
23314                .command
23315                .as_deref()
23316                .is_some_and(|c| c.contains("started.marker")),
23317            "{captured:?}"
23318        );
23319
23320        assert!(
23321            runner.state.active.is_empty(),
23322            "the entry must be cleared once the command actually finished: {:?}",
23323            runner.state.active
23324        );
23325        assert!(runner.state.gate_ran);
23326        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
23327    }
23328
23329    /// The hand-off over a blocking finding a reviewer rejected on leaves a
23330    /// record for `land`; one with only a Minor, or no reject, leaves none.
23331    #[tokio::test]
23332    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
23333        use crate::verdict::{Finding, ReviewVote, Severity};
23334        crate::run::pin_test_home();
23335        let tmp = tempfile::tempdir().expect("tempdir");
23336        let repo = tmp.path().join("repo");
23337        std::fs::create_dir_all(&repo).unwrap();
23338        init_repo(&repo);
23339
23340        for (severity, vote, expect) in [
23341            (Severity::Major, ReviewVote::Reject, true),
23342            (Severity::Minor, ReviewVote::Reject, false),
23343            (Severity::Major, ReviewVote::Approve, false),
23344        ] {
23345            let mut round = review_round(false, 1, 1, 1, false, true);
23346            round.reviews = vec![ReviewRecord {
23347                reviewer: 1,
23348                agent: "alpha".to_owned(),
23349                summary: String::new(),
23350                findings: vec![Finding {
23351                    id: "R1-1-1".to_owned(),
23352                    severity,
23353                    file: None,
23354                    line: None,
23355                    title: "t".to_owned(),
23356                    detail: String::new(),
23357                }],
23358                vote: Some(vote),
23359                failed: None,
23360                duration_ms: 0,
23361                attempts: 0,
23362            }];
23363            let mut state = RunState::new(
23364                repo.clone(),
23365                "main".to_owned(),
23366                "deadbeef".to_owned(),
23367                "task".to_owned(),
23368                Config::default(),
23369            );
23370            state.reviews = vec![round];
23371            let mut runner = Runner {
23372                state,
23373                roles: ResolvedRoles {
23374                    implementers: Vec::new(),
23375                    judges: Vec::new(),
23376                    reviewers: Vec::new(),
23377                    fixer: None,
23378                    conductor: conductor(),
23379                    implementer_roster: Vec::new(),
23380                    judge_roster: Vec::new(),
23381                    reviewer_roster: Vec::new(),
23382                },
23383                sem: Arc::new(Semaphore::new(1)),
23384                pause: Pause::new(),
23385                interrupt: Pause::new(),
23386            };
23387            let shell = runner.state.config.shell();
23388            runner
23389                .stop_reviewing("round budget spent", &shell, &repo)
23390                .await
23391                .expect("stop_reviewing");
23392            assert_eq!(runner.state.status, RunStatus::Gating);
23393            assert_eq!(
23394                runner.state.contested_handoff.is_some(),
23395                expect,
23396                "{severity:?} + {vote:?}"
23397            );
23398        }
23399    }
23400
23401    /// The shape the incident this whole fix responds to actually had: the
23402    /// round budget spent, the last round's own e2e blocked on the shared
23403    /// build cache (held here by a live pid — this test process — exactly
23404    /// `cache`'s own unit tests' pattern for "another owner, still alive"
23405    /// without forking a process). `stop_reviewing` must retry it — not
23406    /// silently leave the round looking untouched (the catch-up-only half of
23407    /// the bug), and not read the contention as a red `e2e` and block the
23408    /// run on it (the other half). Called directly, the same way
23409    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
23410    /// above exercises `gate`, so this never needs a real cargo build to
23411    /// reach: the lease is never released, so `with_cache_lease` never gets
23412    /// past acquiring it into anything that would need a real workspace.
23413    #[tokio::test]
23414    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
23415        crate::run::pin_test_home();
23416        let home = crate::run::home();
23417
23418        let tmp = tempfile::tempdir().expect("tempdir");
23419        let repo = tmp.path().join("repo");
23420        std::fs::create_dir_all(&repo).unwrap();
23421        init_repo(&repo);
23422        let head = crate::git::rev_parse(&repo, "HEAD")
23423            .await
23424            .expect("rev-parse");
23425        // Unique to this test, so holding its lease cannot collide with
23426        // another test sharing the same process-wide `home`.
23427        let cache_dir = tmp.path().join("target");
23428
23429        let mut config = Config::default();
23430        config.verify.e2e = vec![format!(
23431            "CARGO_TARGET_DIR='{}' test -f README.md",
23432            cache_dir.display()
23433        )];
23434        config.graph.review_rounds = 1;
23435        // Bounded so a regression that does start waiting fails the test in
23436        // seconds, not hangs it.
23437        config.graph.timeout_verify = Some(2);
23438        config.graph.timeout_resource_wait = 2;
23439
23440        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23441        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23442            .expect("no io error acquiring directly")
23443        {
23444            crate::cache::AcquireOutcome::Acquired(g) => g,
23445            crate::cache::AcquireOutcome::Busy(b) => {
23446                panic!("expected the direct acquire to win the lease first: {b:?}")
23447            }
23448        };
23449
23450        let mut state = RunState::new(
23451            repo.clone(),
23452            "main".to_owned(),
23453            head.clone(),
23454            "task".to_owned(),
23455            config,
23456        );
23457        state.candidates = vec![Candidate {
23458            index: 0,
23459            label: 'A',
23460            agent: "alpha".to_owned(),
23461            branch: "does-not-exist".to_owned(),
23462            worktree: repo.clone(),
23463            summary: String::new(),
23464            stat: String::new(),
23465            files: 0,
23466            commits: 0,
23467            empty: false,
23468            failed: None,
23469            verified_noop: None,
23470            duration_ms: 0,
23471            folded: false,
23472        }];
23473        state.tally = Some(Tally {
23474            first_choice: BTreeMap::from([('A', 1)]),
23475            borda: BTreeMap::new(),
23476            winner: 'A',
23477            rankings: 1,
23478            unanimous_initial: true,
23479            deliberated: false,
23480            changed_votes: 0,
23481            unanimous_final: true,
23482            tie_break: None,
23483            judges: 0,
23484            present: 0,
23485            quorum: 0,
23486            met_quorum: true,
23487            uncontested: Some("only candidate A produced a change".to_owned()),
23488        });
23489        // The round budget's last round, deferred: `needs_catchup_run`'s
23490        // other trigger. `stop_reviewing`'s retry machinery must treat this
23491        // exactly like a resource-blocked attempt once it actually runs.
23492        state.reviews = vec![ReviewRound {
23493            round: 1,
23494            head: head.clone(),
23495            verified_head: None,
23496            verified_at: None,
23497            reviews: Vec::new(),
23498            e2e: Vec::new(),
23499            fix: None,
23500            blocking: 1,
23501            answered: 1,
23502            expected: 1,
23503            clean: false,
23504            verify_retried: false,
23505            e2e_deferred: true,
23506            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
23507            progressed: false,
23508            vote_split: false,
23509            reconsideration: Vec::new(),
23510            verdict: None,
23511        }];
23512
23513        let mut runner = Runner {
23514            state,
23515            roles: ResolvedRoles {
23516                implementers: Vec::new(),
23517                judges: Vec::new(),
23518                reviewers: Vec::new(),
23519                fixer: None,
23520                conductor: conductor(),
23521                implementer_roster: Vec::new(),
23522                judge_roster: Vec::new(),
23523                reviewer_roster: Vec::new(),
23524            },
23525            sem: Arc::new(Semaphore::new(1)),
23526            pause: Pause::new(),
23527            interrupt: Pause::new(),
23528        };
23529
23530        let shell = runner.state.config.shell();
23531        runner
23532            .stop_reviewing("round budget spent", &shell, &repo)
23533            .await
23534            .expect("stop_reviewing");
23535
23536        let last = runner.state.reviews.last().expect("round record");
23537        assert_eq!(
23538            last.e2e_status(),
23539            E2eStatus::ResourceBlocked,
23540            "the shared cache is still held; the attempt must read as blocked, not deferred or \
23541             failed: {last:?}"
23542        );
23543        assert_eq!(
23544            last.verified_head.as_deref(),
23545            Some(head.as_str()),
23546            "which commit this attempt targeted is known even though nothing finished checking \
23547             it"
23548        );
23549        let first_attempt_at = last
23550            .verified_at
23551            .expect("when this attempt ran is known too");
23552        assert_ne!(
23553            runner.state.status,
23554            RunStatus::Blocked,
23555            "contention is evidence about the machine, not the patch — it must not settle the \
23556             run as blocked: {:?}",
23557            runner.state.status
23558        );
23559        assert!(
23560            !runner
23561                .state
23562                .events
23563                .iter()
23564                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
23565            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
23566            runner.state.events
23567        );
23568
23569        // The cache is still held: a later reentry must retry the same
23570        // round's verification again — not leave it looking exactly as
23571        // untouched as the first blocked attempt, which is indistinguishable
23572        // from never having tried again at all.
23573        runner
23574            .stop_reviewing("round budget spent", &shell, &repo)
23575            .await
23576            .expect("stop_reviewing retry");
23577        assert_eq!(
23578            runner.state.reviews.len(),
23579            1,
23580            "no new round was started: {:?}",
23581            runner.state.reviews
23582        );
23583        let last = runner.state.reviews.last().expect("round record");
23584        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
23585        assert!(
23586            last.verified_at.expect("still known") > first_attempt_at,
23587            "a second reentry must be a fresh attempt, not a stale copy of the first"
23588        );
23589        assert_ne!(runner.state.status, RunStatus::Blocked);
23590
23591        held.release();
23592    }
23593
23594    #[cfg(unix)]
23595    #[tokio::test]
23596    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
23597        ask_test_home();
23598        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
23599            let tmp = tempfile::tempdir().unwrap();
23600            let repo = tmp.path().join("repo");
23601            std::fs::create_dir(&repo).unwrap();
23602            init_repo(&repo);
23603            let run_git = |args: &[&str]| {
23604                let out = std::process::Command::new("git")
23605                    .args(args)
23606                    .current_dir(&repo)
23607                    .output()
23608                    .unwrap();
23609                assert!(
23610                    out.status.success(),
23611                    "{args:?}: {}",
23612                    String::from_utf8_lossy(&out.stderr)
23613                );
23614            };
23615            let origin = tmp.path().join("origin.git");
23616            run_git(&["init", "--bare", origin.to_str().unwrap()]);
23617            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
23618            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
23619            run_git(&["add", "spec.rs"]);
23620            run_git(&["commit", "-m", "initial spec"]);
23621            run_git(&["push", "origin", "main"]);
23622            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
23623            run_git(&["checkout", "-b", "fix/review"]);
23624            std::fs::write(
23625                repo.join("check.rs"),
23626                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
23627            )
23628            .unwrap();
23629            run_git(&["add", "check.rs"]);
23630            run_git(&["commit", "-m", "use spec"]);
23631            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
23632            run_git(&["checkout", "main"]);
23633            std::fs::write(
23634                repo.join("spec.rs"),
23635                "struct AgentSpec { max_turn_secs: u64 }\n",
23636            )
23637            .unwrap();
23638            run_git(&["add", "spec.rs"]);
23639            run_git(&["commit", "-m", "extend spec"]);
23640            run_git(&["push", "origin", "main"]);
23641            run_git(&["checkout", "fix/review"]);
23642
23643            let mut runner = runner_at(RunStatus::Reviewing);
23644            runner.state.repo = repo.clone();
23645            runner.state.base_commit = base;
23646            runner.state.pr_head = Some("fix/review".into());
23647            runner.state.config.graph.review_rounds = max_rounds;
23648            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
23649            runner.state.config.graph.sessions = false;
23650            runner.state.config.disk.min_free_bytes = 0;
23651            runner.state.config.verify.e2e =
23652                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
23653            runner.state.candidates = vec![Candidate {
23654                index: 0,
23655                label: 'A',
23656                agent: "fixture".into(),
23657                branch: "fix/review".into(),
23658                worktree: repo.clone(),
23659                summary: String::new(),
23660                stat: String::new(),
23661                files: 1,
23662                commits: 1,
23663                empty: false,
23664                failed: None,
23665                verified_noop: None,
23666                duration_ms: 0,
23667                folded: false,
23668            }];
23669            runner.state.tally = Some(Tally {
23670                first_choice: BTreeMap::new(),
23671                borda: BTreeMap::new(),
23672                winner: 'A',
23673                rankings: 0,
23674                unanimous_initial: true,
23675                deliberated: false,
23676                changed_votes: 0,
23677                unanimous_final: true,
23678                tie_break: None,
23679                judges: 0,
23680                present: 0,
23681                quorum: 0,
23682                met_quorum: true,
23683                uncontested: Some("review-only".into()),
23684            });
23685            let mut last = review_round(false, 0, 1, 1, false, false);
23686            last.head = reviewed.clone();
23687            last.e2e_deferred = true;
23688            last.e2e[0].resource_blocked = true;
23689            last.e2e[0].output_tail = "waiting for the shared build cache".into();
23690            if max_rounds == 1 {
23691                last.e2e.clear();
23692            }
23693            runner.state.reviews = vec![last];
23694            let calls = tmp.path().join("fix-calls");
23695            let mut fixer = spec("repair");
23696            fixer
23697                .env
23698                .insert("FIX_CALLS".into(), calls.display().to_string());
23699            fixer.command = vec!["sh".into(), "-c".into(), r#"
23700                echo fix >> "$FIX_CALLS"
23701                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
23702                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
23703                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
23704                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
23705            "#.into()];
23706            let mut reviewer = spec("reviewer");
23707            reviewer.command = vec![
23708                "sh".into(),
23709                "-c".into(),
23710                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
23711                    .into(),
23712            ];
23713            runner.roles.fixer = Some(vec![fixer]);
23714            runner.roles.reviewers = vec![reviewer];
23715
23716            runner.sync_to_base().await.unwrap();
23717            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
23718            assert_ne!(rebased, reviewed);
23719            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
23720            if reentry {
23721                // Simulate a crash after catch-up evidence was saved but before
23722                // dispatching the fixer. No dedicated pending-repair field exists.
23723                let shell = runner.state.config.shell();
23724                runner
23725                    .stop_unresolved_review("deferred verification", &shell, &repo)
23726                    .await
23727                    .unwrap();
23728                assert!(runner.catchup_repairable());
23729                assert!(!calls.exists());
23730                runner.state = RunState::load(&runner.state.id).unwrap();
23731                assert!(runner.catchup_repairable());
23732            }
23733            runner.review_loop().await.unwrap();
23734            let first = &runner.state.reviews[0];
23735            assert_eq!(first.head, reviewed);
23736            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
23737            assert!(
23738                first.verify_retried,
23739                "a reproduced build failure gets exactly one retry: {:?}",
23740                first.e2e
23741            );
23742            assert!(first.e2e[0].output_tail.contains("E0063"));
23743            assert!(!runner.catchup_repairable());
23744            if max_rounds == 2 {
23745                assert_eq!(
23746                    runner.state.status,
23747                    RunStatus::Gating,
23748                    "{}",
23749                    crate::report::run(&runner.state)
23750                );
23751                assert_eq!(runner.state.reviews.len(), 2);
23752                assert!(first.fix.as_ref().unwrap().committed);
23753                assert!(runner.state.reviews[1].clean);
23754                assert_eq!(
23755                    runner
23756                        .state
23757                        .reviews
23758                        .iter()
23759                        .filter(|r| r.fix.is_some())
23760                        .count(),
23761                    1
23762                );
23763                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
23764                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
23765            } else {
23766                assert_eq!(runner.state.status, RunStatus::Blocked);
23767                assert!(first.fix.is_none());
23768                assert!(!calls.exists());
23769                let recovery = crate::recovery::assess(
23770                    "prior",
23771                    Some(&runner.state),
23772                    &runner.landing_base(),
23773                    crate::recovery::Relation::Diverged,
23774                );
23775                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
23776                let reasons = recovery.reasons.join("\n");
23777                assert!(
23778                    reasons.contains(&reviewed) && reasons.contains(&rebased),
23779                    "{reasons}"
23780                );
23781                assert!(
23782                    reasons.contains("base sync to")
23783                        && reasons.contains("additional review is required"),
23784                    "{reasons}"
23785                );
23786            }
23787        }
23788    }
23789
23790    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23791    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23792    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23793    /// own top-of-function fast path (`review_conclusion`) correctly reads
23794    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23795    /// own `for` range is empty once the round budget is spent, so
23796    /// `review_loop` must retry the check itself rather than silently doing
23797    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23798    /// above exercises directly, but through `review_loop`'s own entry point
23799    /// this time, proving the wiring between the two rather than just the
23800    /// retry logic in isolation.
23801    #[tokio::test]
23802    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23803        crate::run::pin_test_home();
23804        let home = crate::run::home();
23805
23806        let tmp = tempfile::tempdir().expect("tempdir");
23807        let repo = tmp.path().join("repo");
23808        std::fs::create_dir_all(&repo).unwrap();
23809        init_repo(&repo);
23810        let head = crate::git::rev_parse(&repo, "HEAD")
23811            .await
23812            .expect("rev-parse");
23813        let cache_dir = tmp.path().join("target");
23814
23815        let mut config = Config::default();
23816        config.verify.e2e = vec![format!(
23817            "CARGO_TARGET_DIR='{}' test -f README.md",
23818            cache_dir.display()
23819        )];
23820        config.graph.review_rounds = 1;
23821        config.graph.timeout_verify = Some(2);
23822        config.graph.timeout_resource_wait = 2;
23823
23824        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23825        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23826            .expect("no io error acquiring directly")
23827        {
23828            crate::cache::AcquireOutcome::Acquired(g) => g,
23829            crate::cache::AcquireOutcome::Busy(b) => {
23830                panic!("expected the direct acquire to win the lease first: {b:?}")
23831            }
23832        };
23833
23834        let mut state = RunState::new(
23835            repo.clone(),
23836            "main".to_owned(),
23837            head.clone(),
23838            "task".to_owned(),
23839            config,
23840        );
23841        state.candidates = vec![Candidate {
23842            index: 0,
23843            label: 'A',
23844            agent: "alpha".to_owned(),
23845            branch: "does-not-exist".to_owned(),
23846            worktree: repo.clone(),
23847            summary: String::new(),
23848            stat: String::new(),
23849            files: 0,
23850            commits: 0,
23851            empty: false,
23852            failed: None,
23853            verified_noop: None,
23854            duration_ms: 0,
23855            folded: false,
23856        }];
23857        state.tally = Some(Tally {
23858            first_choice: BTreeMap::from([('A', 1)]),
23859            borda: BTreeMap::new(),
23860            winner: 'A',
23861            rankings: 1,
23862            unanimous_initial: true,
23863            deliberated: false,
23864            changed_votes: 0,
23865            unanimous_final: true,
23866            tie_break: None,
23867            judges: 0,
23868            present: 0,
23869            quorum: 0,
23870            met_quorum: true,
23871            uncontested: Some("only candidate A produced a change".to_owned()),
23872        });
23873        // The exact shape a prior process's `stop_reviewing` would have left
23874        // on disk: the round budget's last round, a real attempt already
23875        // made and already resource-blocked.
23876        state.reviews = vec![ReviewRound {
23877            round: 1,
23878            head: head.clone(),
23879            verified_head: Some(head.clone()),
23880            verified_at: Some(jiff::Timestamp::now()),
23881            reviews: Vec::new(),
23882            e2e: vec![CommandOutcome {
23883                command: format!(
23884                    "CARGO_TARGET_DIR='{}' test -f README.md",
23885                    cache_dir.display()
23886                ),
23887                code: None,
23888                output_tail: "waiting for the shared build cache".to_owned(),
23889                duration_ms: 0,
23890                resource_blocked: true,
23891                ..Default::default()
23892            }],
23893            fix: None,
23894            blocking: 1,
23895            answered: 1,
23896            expected: 1,
23897            clean: false,
23898            verify_retried: false,
23899            e2e_deferred: false,
23900            e2e_defer_reason: None,
23901            progressed: false,
23902            vote_split: false,
23903            reconsideration: Vec::new(),
23904            verdict: None,
23905        }];
23906
23907        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23908        let mut runner = Runner {
23909            state,
23910            roles: ResolvedRoles {
23911                implementers: Vec::new(),
23912                judges: Vec::new(),
23913                reviewers: Vec::new(),
23914                fixer: None,
23915                conductor: conductor(),
23916                implementer_roster: Vec::new(),
23917                judge_roster: Vec::new(),
23918                reviewer_roster: Vec::new(),
23919            },
23920            sem: Arc::new(Semaphore::new(1)),
23921            pause: Pause::new(),
23922            interrupt: Pause::new(),
23923        };
23924
23925        // The lease is still held throughout, so this reentry's own retry is
23926        // also contended — proving `review_loop` actually tried again (not
23927        // that it happened to succeed) is what the timestamp comparison
23928        // below is for.
23929        runner.review_loop().await.expect("review_loop");
23930
23931        assert_eq!(
23932            runner.state.reviews.len(),
23933            1,
23934            "no new round was started on top of the unresolved one: {:?}",
23935            runner.state.reviews
23936        );
23937        let last = &runner.state.reviews[0];
23938        assert_eq!(
23939            last.e2e_status(),
23940            E2eStatus::ResourceBlocked,
23941            "still contended: {last:?}"
23942        );
23943        assert!(
23944            last.verified_at.expect("still known") > first_attempt_at,
23945            "review_loop must have actually retried the check, not left it exactly as found"
23946        );
23947        assert_ne!(
23948            runner.state.status,
23949            RunStatus::Blocked,
23950            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
23951            runner.state.status
23952        );
23953
23954        held.release();
23955    }
23956
23957    #[tokio::test]
23958    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
23959        crate::run::pin_test_home();
23960        for status in [RunStatus::Blocked, RunStatus::Gating] {
23961            let mut runner = runner_at(status);
23962            runner.state.config.graph.land = true;
23963            runner.state.gate_ran = true;
23964            runner.state.merge = Some(MergeOutcome {
23965                mode: MergeMode::Pr,
23966                ok: false,
23967                detail: "the fixer produced no commit".into(),
23968                empty: false,
23969            });
23970            let url = "https://example.invalid/o/r/pull/1";
23971            runner.state.pr = Some(crate::run::PrRecord {
23972                url: url.into(),
23973                number: 1,
23974                state: "open".into(),
23975                checks: "red".into(),
23976                round: 1,
23977                rounds: 1,
23978                red_at_merge: Vec::new(),
23979            });
23980            runner.state.save().unwrap();
23981            // The nonexistent repository makes observation fail before a forge
23982            // command can run. We still must reach land, rather than silently
23983            // return from the graph with its old gate and merge records.
23984            runner.execute_graph().await.unwrap();
23985            assert_eq!(runner.state.status, RunStatus::Blocked);
23986            assert!(runner.state.land_sync_pending);
23987            assert!(runner.state.events.iter().any(|event|
23988                event.node == "land" && event.message == format!("watching {url}")));
23989            assert_eq!(
23990                runner.state.merge.as_ref().unwrap().detail,
23991                "the fixer produced no commit"
23992            );
23993        }
23994    }
23995
23996    #[tokio::test]
23997    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
23998        crate::run::pin_test_home();
23999        let tmp = tempfile::tempdir().expect("tempdir");
24000        let repo = tmp.path().join("repo");
24001        std::fs::create_dir_all(&repo).unwrap();
24002        init_repo(&repo);
24003
24004        let mut config = Config::default();
24005        config.merge.mode = MergeMode::Pr;
24006        config.graph.land = true;
24007        config.graph.land_approval = false;
24008
24009        let mut state = RunState::new(
24010            repo.clone(),
24011            "main".to_owned(),
24012            "deadbeef".to_owned(),
24013            "task".to_owned(),
24014            config,
24015        );
24016        state.candidates = vec![Candidate {
24017            index: 0,
24018            label: 'A',
24019            agent: "alpha".to_owned(),
24020            branch: "does-not-exist".to_owned(),
24021            worktree: repo.clone(),
24022            summary: String::new(),
24023            stat: String::new(),
24024            files: 0,
24025            commits: 0,
24026            empty: false,
24027            failed: None,
24028            verified_noop: None,
24029            duration_ms: 0,
24030            folded: false,
24031        }];
24032        state.tally = Some(Tally {
24033            first_choice: BTreeMap::from([('A', 1)]),
24034            borda: BTreeMap::new(),
24035            winner: 'A',
24036            rankings: 1,
24037            unanimous_initial: true,
24038            deliberated: false,
24039            changed_votes: 0,
24040            unanimous_final: true,
24041            tie_break: None,
24042            judges: 0,
24043            present: 0,
24044            quorum: 0,
24045            met_quorum: true,
24046            uncontested: Some("only candidate A produced a change".to_owned()),
24047        });
24048        state.reviews = vec![ReviewRound {
24049            round: 1,
24050            head: "deadbeef".to_owned(),
24051            verified_head: None,
24052            verified_at: None,
24053            reviews: Vec::new(),
24054            e2e: Vec::new(),
24055            fix: None,
24056            blocking: 0,
24057            answered: 0,
24058            expected: 0,
24059            clean: true,
24060            verify_retried: false,
24061            e2e_deferred: false,
24062            e2e_defer_reason: None,
24063            progressed: false,
24064            vote_split: false,
24065            reconsideration: Vec::new(),
24066            verdict: None,
24067        }];
24068        state.gate = vec![CommandOutcome {
24069            command: "test".to_owned(),
24070            code: Some(0),
24071            output_tail: String::new(),
24072            duration_ms: 0,
24073            resource_blocked: false,
24074            ..Default::default()
24075        }];
24076        state.gate_ran = true;
24077        // A first pass through `merge` already pushed and opened this pull
24078        // request; `status` is `Landing` because a previous call into `land`
24079        // parked or was interrupted before it reached a terminal outcome.
24080        state.status = RunStatus::Landing;
24081        state.merge = Some(MergeOutcome {
24082            mode: MergeMode::Pr,
24083            ok: true,
24084            detail: "https://example.invalid/x/y/pull/1".to_owned(),
24085            empty: false,
24086        });
24087
24088        // The Landing-resume shortcut calls `run_land` directly rather than
24089        // through `merge`, which is exactly the call site that used to skip
24090        // `settle_questions` - see the fixture below.
24091        ask_test_home();
24092        // A real resume loads a persisted run; driver ownership is checked
24093        // against that record before the Landing shortcut is entered.
24094        state.save().expect("save landing run");
24095        let store = ask::Questions::open();
24096        let q = ask_open_question(&store, &state.id);
24097
24098        let mut runner = Runner {
24099            state,
24100            roles: ResolvedRoles {
24101                implementers: Vec::new(),
24102                judges: Vec::new(),
24103                reviewers: Vec::new(),
24104                fixer: None,
24105                conductor: conductor(),
24106                implementer_roster: Vec::new(),
24107                judge_roster: Vec::new(),
24108                reviewer_roster: Vec::new(),
24109            },
24110            sem: Arc::new(Semaphore::new(1)),
24111            pause: Pause::new(),
24112            interrupt: Pause::new(),
24113        };
24114
24115        // `execute`, not `merge` directly: the Landing-resume shortcut lives
24116        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
24117        // exactly because `review_loop` would otherwise clobber the marker
24118        // first.
24119        runner.execute().await.expect("execute");
24120
24121        assert_eq!(
24122            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
24123            Some("https://example.invalid/x/y/pull/1"),
24124            "reentry must not push again or open a second pull request over the \
24125             one `land` is already watching"
24126        );
24127        assert_ne!(
24128            runner.state.status,
24129            RunStatus::Landing,
24130            "land could not actually reach the fake pull request, so it must \
24131             have given up rather than left the run silently parked forever"
24132        );
24133        // `land` could not reach the fake pull request, so it gave up into
24134        // `Blocked` - still resumable, so the question must not have been
24135        // swept just because this branch now also calls `settle_questions`.
24136        assert_eq!(runner.state.status, RunStatus::Blocked);
24137        assert!(
24138            store.get(&q.id).unwrap().status.open(),
24139            "Blocked is still alive; settle_questions must have been a no-op here"
24140        );
24141    }
24142
24143    fn state_with_round(round: ReviewRound) -> RunState {
24144        let mut s = RunState::new(
24145            PathBuf::from("/repo"),
24146            "main".to_owned(),
24147            "abc1234".to_owned(),
24148            "add retries".to_owned(),
24149            Config::default(),
24150        );
24151        s.reviews = vec![round];
24152        s
24153    }
24154
24155    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
24156        crate::verdict::Finding {
24157            id: id.to_owned(),
24158            severity,
24159            file: None,
24160            line: None,
24161            title: title.to_owned(),
24162            detail: String::new(),
24163        }
24164    }
24165
24166    #[test]
24167    fn pr_body_names_open_findings_and_declined_ones() {
24168        let round = ReviewRound {
24169            round: 2,
24170            head: "deadbee".to_owned(),
24171            verified_head: None,
24172            verified_at: None,
24173            reviews: vec![ReviewRecord {
24174                attempts: 0,
24175                reviewer: 1,
24176                agent: "alpha".to_owned(),
24177                summary: String::new(),
24178                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
24179                vote: None,
24180                failed: None,
24181                duration_ms: 0,
24182            }],
24183            e2e: vec![CommandOutcome {
24184                command: "cargo test".to_owned(),
24185                code: Some(0),
24186                output_tail: String::new(),
24187                duration_ms: 0,
24188                resource_blocked: false,
24189                ..Default::default()
24190            }],
24191            verify_retried: false,
24192            e2e_deferred: false,
24193            e2e_defer_reason: None,
24194            fix: Some(FixRecord {
24195                agent: "alpha".to_owned(),
24196                addressed: Vec::new(),
24197                rejected: vec![crate::verdict::Rejection {
24198                    id: "R1-1-1".to_owned(),
24199                    why: "not reachable from any caller".to_owned(),
24200                }],
24201                notes: String::new(),
24202                committed: true,
24203                failed: None,
24204                duration_ms: 0,
24205                continuation: None,
24206            }),
24207            blocking: 0,
24208            answered: 1,
24209            expected: 1,
24210            clean: false,
24211            progressed: true,
24212            vote_split: false,
24213            reconsideration: Vec::new(),
24214            verdict: None,
24215        };
24216        let state = state_with_round(round);
24217        let body = pr_message(&state, 'A').body;
24218
24219        assert!(body.contains("add retries"), "the task must still be there");
24220        assert!(body.contains("R2-1-1"), "{body}");
24221        assert!(!body.contains("unused import"), "{body}");
24222        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
24223        assert!(
24224            !body.contains("not reachable from any caller"),
24225            "the reason it was declined: {body}"
24226        );
24227    }
24228
24229    #[test]
24230    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
24231        let round = ReviewRound {
24232            round: 1,
24233            head: "deadbee".to_owned(),
24234            verified_head: None,
24235            verified_at: None,
24236            reviews: vec![ReviewRecord {
24237                attempts: 0,
24238                reviewer: 1,
24239                agent: "alpha".to_owned(),
24240                summary: String::new(),
24241                findings: Vec::new(),
24242                vote: None,
24243                failed: None,
24244                duration_ms: 0,
24245            }],
24246            e2e: Vec::new(),
24247            verify_retried: false,
24248            e2e_deferred: false,
24249            e2e_defer_reason: None,
24250            fix: None,
24251            blocking: 0,
24252            answered: 1,
24253            expected: 1,
24254            clean: true,
24255            progressed: false,
24256            vote_split: false,
24257            reconsideration: Vec::new(),
24258            verdict: None,
24259        };
24260        let state = state_with_round(round);
24261        let body = pr_message(&state, 'A').body;
24262        assert!(!body.contains("Open review findings"), "{body}");
24263        assert!(!body.contains("Declined"), "{body}");
24264    }
24265
24266    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
24267        let mut state = RunState::new(
24268            PathBuf::from("/repo"),
24269            "main".to_owned(),
24270            "abc1234".to_owned(),
24271            instruction.to_owned(),
24272            Config::default(),
24273        );
24274        // These fixtures test execution flow, independent of host disk capacity.
24275        state.config.disk.min_free_bytes = 0;
24276        state.candidates.push(Candidate {
24277            index: 0,
24278            label: 'A',
24279            agent: "alpha".to_owned(),
24280            branch: "magi/x/A".to_owned(),
24281            worktree: PathBuf::from("/wt"),
24282            summary: summary.to_owned(),
24283            stat: String::new(),
24284            files: 1,
24285            commits: 1,
24286            empty: false,
24287            failed: None,
24288            verified_noop: None,
24289            folded: false,
24290            duration_ms: 0,
24291        });
24292        state
24293    }
24294
24295    fn review_state(subjects: &[&str]) -> RunState {
24296        let mut state = state_with_summary(
24297            "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",
24298            "",
24299        );
24300        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24301        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
24302        state
24303    }
24304
24305    /// A branch rebased onto a main that moved past the recorded
24306    /// `base_commit` is titled from its own first commit, never main's.
24307    #[tokio::test]
24308    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
24309        ask_test_home();
24310        let tmp = tempfile::tempdir().unwrap();
24311        let repo = tmp.path().join("repo");
24312        std::fs::create_dir_all(&repo).unwrap();
24313        init_repo(&repo);
24314        let origin = tmp.path().join("origin.git");
24315        let g = |dir: &Path, args: &[&str]| {
24316            let out = std::process::Command::new("git")
24317                .args(args)
24318                .current_dir(dir)
24319                .quiet()
24320                .output()
24321                .expect("spawn git");
24322            assert!(
24323                out.status.success(),
24324                "git {args:?}: {}",
24325                String::from_utf8_lossy(&out.stderr)
24326            );
24327        };
24328        g(
24329            tmp.path(),
24330            &[
24331                "clone",
24332                "--bare",
24333                "-q",
24334                repo.to_str().unwrap(),
24335                origin.to_str().unwrap(),
24336            ],
24337        );
24338        g(
24339            &repo,
24340            &["remote", "add", "origin", origin.to_str().unwrap()],
24341        );
24342        let c1 = git::rev_parse(&repo, "main").await.unwrap();
24343
24344        // Main moves on; the branch is built on top of the new main.
24345        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
24346        g(&repo, &["add", "-A"]);
24347        g(
24348            &repo,
24349            &["commit", "-q", "-m", "chore(deps): update a crate"],
24350        );
24351        g(&repo, &["push", "-q", "origin", "main"]);
24352        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
24353        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24354        g(&repo, &["add", "-A"]);
24355        g(
24356            &repo,
24357            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
24358        );
24359        g(&repo, &["checkout", "-q", "main"]);
24360
24361        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
24362        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
24363        // Without a readable tracking ref the recorded base's merge base is used.
24364        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
24365        assert_eq!(fallback, c1);
24366
24367        let mut state = review_state(&[
24368            "chore(deps): update a crate",
24369            "fix(daemon): apply a chosen action",
24370        ]);
24371        state.repo = repo.clone();
24372        state.base_branch = "main".to_owned();
24373        state.base_commit = c1;
24374        refresh_reviewed_commits(&mut state, "feat/own").await;
24375        assert_eq!(
24376            state.reviewed_commits,
24377            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
24378        );
24379        assert_eq!(
24380            review_title(&state).as_deref(),
24381            Some("fix(daemon): apply a chosen action")
24382        );
24383        assert_eq!(
24384            leaked_subjects(&state, "feat/own").await,
24385            Some(vec!["chore(deps): update a crate".to_owned()])
24386        );
24387        // A stale tracking ref is still used when the fetch fails, but the
24388        // leak list is withheld.
24389        state.config.merge.remote = "nowhere".to_owned();
24390        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
24391    }
24392
24393    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
24394    /// with `origin/main` one commit behind it, and a summarizing agent that
24395    /// prints whatever `reply` holds.
24396    struct SummaryFixture {
24397        _tmp: tempfile::TempDir,
24398        repo: PathBuf,
24399        reply: PathBuf,
24400        runner: Runner,
24401    }
24402
24403    fn summary_fixture() -> SummaryFixture {
24404        ask_test_home();
24405        let tmp = tempfile::tempdir().unwrap();
24406        let repo = tmp.path().join("repo");
24407        std::fs::create_dir_all(&repo).unwrap();
24408        init_repo(&repo);
24409        let origin = tmp.path().join("origin.git");
24410        let g = |args: &[&str]| {
24411            let out = std::process::Command::new("git")
24412                .args(args)
24413                .current_dir(&repo)
24414                .quiet()
24415                .output()
24416                .expect("spawn git");
24417            assert!(
24418                out.status.success(),
24419                "git {args:?}: {}",
24420                String::from_utf8_lossy(&out.stderr)
24421            );
24422        };
24423        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
24424        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
24425        g(&["push", "-q", "origin", "main"]);
24426        g(&["checkout", "-q", "-b", "feat/own"]);
24427        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24428        g(&["add", "-A"]);
24429        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
24430        let reply = tmp.path().join("reply.txt");
24431        std::fs::write(
24432            &reply,
24433            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
24434        )
24435        .unwrap();
24436        let mut runner = runner_at(RunStatus::Gating);
24437        let mut state = review_state(&["feat(own): add the own file"]);
24438        state.repo = repo.clone();
24439        state.base_branch = "main".to_owned();
24440        state.candidates[0].branch = "feat/own".to_owned();
24441        state.candidates[0].worktree = repo.clone();
24442        let mut author = spec("alpha");
24443        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
24444        author
24445            .env
24446            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
24447        state.config.agents = vec![author];
24448        runner.state = state;
24449        SummaryFixture {
24450            _tmp: tmp,
24451            repo,
24452            reply,
24453            runner,
24454        }
24455    }
24456
24457    async fn posted(f: &mut SummaryFixture) -> PrMessage {
24458        let winner = f.runner.state.candidates[0].clone();
24459        f.runner
24460            .guarded_pr_message(&winner, None, true)
24461            .await
24462            .unwrap()
24463            .expect("an English description never parks")
24464    }
24465
24466    fn clean_round_with_minor_findings() -> ReviewRound {
24467        let mut round = passing_round(2, None);
24468        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
24469        round.reviews = vec![ReviewRecord {
24470            attempts: 0,
24471            reviewer: 1,
24472            agent: "alpha".into(),
24473            summary: "内部レビュー".into(),
24474            findings: vec![
24475                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
24476                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
24477            ],
24478            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
24479            failed: None,
24480            duration_ms: 0,
24481        }];
24482        round
24483    }
24484
24485    #[tokio::test]
24486    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
24487        for review_only in [false, true] {
24488            let mut f = summary_fixture();
24489            if !review_only {
24490                f.runner.state.candidates[0].agent = "alpha".into();
24491            }
24492            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
24493            assert!(f.runner.state.reviews[0].clean);
24494            assert!(f.runner.state.reviews[0].fix.is_none());
24495            assert!(f.runner.state.open_findings().is_empty());
24496            assert_eq!(
24497                crate::pr_outcome::required_finding_ids(&f.runner.state),
24498                ["R2-1-1", "R2-1-2"]
24499            );
24500            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24501            let evidence = crate::pr_outcome::summary_evidence(
24502                &f.runner.state,
24503                crate::pr_outcome::FinalHead::At(&head),
24504            );
24505            assert!(
24506                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
24507            );
24508            // The ordinary reply omits both IDs: no cached description is adopted.
24509            let omitted = posted(&mut f).await;
24510            assert!(omitted.body.contains("No description"));
24511            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
24512            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
24513            assert!(f.runner.state.change_summary.is_none());
24514            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();
24515            let described = posted(&mut f).await;
24516            assert!(described.body.contains("improve documentation for callers"));
24517            assert!(described.body.contains("remaining edge case"));
24518            assert!(described.body.contains("## Open review findings"));
24519            assert!(!described.body.contains("未修正"));
24520        }
24521    }
24522
24523    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
24524        let mut f = summary_fixture();
24525        if !review_only {
24526            f.runner.state.candidates[0].agent = "alpha".into();
24527        }
24528        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24529        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
24530        fixed
24531            .fix
24532            .as_mut()
24533            .unwrap()
24534            .rejected
24535            .push(crate::verdict::Rejection {
24536                id: "R1-1-1".into(),
24537                why: "呼び出されないコードのため辞退".into(),
24538            });
24539        let mut clean = clean_round_with_minor_findings();
24540        clean.verified_head = Some(head.clone());
24541        f.runner.state.reviews = vec![fixed, clean];
24542        ok_gate(&mut f.runner.state, Some(&head));
24543        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
24544        f.runner.state.config.agents.push(scripted("beta", reply));
24545        f.runner.state.config.roles.language_judge =
24546            Some(crate::config::AgentChoice::One("beta".into()));
24547        f
24548    }
24549
24550    #[tokio::test]
24551    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
24552        for review_only in [false, true] {
24553            let mut f = rewrite_fixture_with_findings(review_only,
24554                "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;
24555            let m = posted(&mut f).await;
24556            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24557            let expected =
24558                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
24559            assert!(m.body.contains(&expected));
24560            assert!(m.body.contains("## Review rounds"));
24561            assert!(
24562                m.body
24563                    .contains("Gate (`verify.gate`): passed on the final commit")
24564            );
24565            assert!(
24566                m.body
24567                    .contains("Tests (`verify.e2e`): passed on the final commit")
24568            );
24569            let c = f.runner.state.change_summary.as_ref().unwrap();
24570            assert!(
24571                m.body
24572                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
24573            );
24574            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24575            assert!(crate::pr_outcome::covers_required_findings(
24576                &f.runner.state,
24577                &m.body
24578            ));
24579            assert!(m.body.contains("documentation remains incomplete"));
24580            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
24581            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
24582            assert!(f.runner.state.github_text.is_none());
24583        }
24584    }
24585
24586    #[tokio::test]
24587    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
24588        for review_only in [false, true] {
24589            for reply in [
24590                "TITLE: fix: public description\nA short English description.",
24591                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
24592            ] {
24593                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
24594                let winner = f.runner.state.candidates[0].clone();
24595                let posted = f
24596                    .runner
24597                    .guarded_pr_message(&winner, None, true)
24598                    .await
24599                    .unwrap();
24600                assert!(posted.is_none());
24601                assert!(f.runner.state.parked);
24602                let withheld = f.runner.state.github_text.as_ref().unwrap();
24603                assert!(
24604                    withheld.rewrite.is_none(),
24605                    "an incomplete rewrite must not be selectable"
24606                );
24607                let q = ask::Questions::open()
24608                    .get(withheld.question.as_ref().unwrap())
24609                    .unwrap();
24610                assert!(
24611                    !q.choices
24612                        .contains(&crate::github_text::USE_REWRITE.to_owned())
24613                );
24614                assert!(
24615                    q.detail.contains("R1-1-1")
24616                        && q.detail.contains("R2-1-1")
24617                        && q.detail.contains("R2-1-2")
24618                );
24619            }
24620        }
24621    }
24622
24623    #[tokio::test]
24624    async fn japanese_reports_stay_local_in_both_public_run_modes() {
24625        for review_only in [false, true] {
24626            let mut f = summary_fixture();
24627            if !review_only {
24628                f.runner.state.candidates[0].agent = "alpha".into();
24629            }
24630            f.runner.state.instruction = "内部タスクの説明".into();
24631            f.runner.state.candidates[0].summary = "内部の候補報告".into();
24632            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24633            f.runner.state.reviews = vec![
24634                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
24635                round_with_notes(2, Some("二回目の内部修正報告です。")),
24636                passing_round(3, Some(&head)),
24637            ];
24638            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
24639            ok_gate(&mut f.runner.state, Some(&head));
24640            let captured = f.repo.join("public-prompt.txt");
24641            let author = &mut f.runner.state.config.agents[0];
24642            author.command = vec![
24643                "sh".into(),
24644                "-c".into(),
24645                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24646            ];
24647            author.env.insert(
24648                "PROMPT_FILE".into(),
24649                captured.to_string_lossy().into_owned(),
24650            );
24651            let m = posted(&mut f).await;
24652            assert!(m.body.contains("Adds `own.txt`"));
24653            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
24654            assert!(m.body.contains("R1-1-1"));
24655            assert!(
24656                m.body
24657                    .contains("Gate (`verify.gate`): passed on the final commit")
24658            );
24659            assert!(
24660                m.body
24661                    .contains("Tests (`verify.e2e`): passed on the final commit")
24662            );
24663            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24664            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
24665            let prompt = std::fs::read_to_string(captured).unwrap();
24666            assert!(prompt.contains(&format!(
24667                "git diff {} {head}",
24668                f.runner.state.change_summary.as_ref().unwrap().base
24669            )));
24670            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
24671            assert_eq!(
24672                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
24673                "二回目の内部修正報告です。"
24674            );
24675        }
24676    }
24677
24678    #[tokio::test]
24679    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
24680        for review_only in [false, true] {
24681            let mut f = summary_fixture();
24682            if !review_only {
24683                f.runner.state.candidates[0].agent = "alpha".into();
24684            }
24685            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
24686            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
24687            std::fs::write(&f.reply, "no usable description").unwrap();
24688            let failed = posted(&mut f).await;
24689            assert!(
24690                failed
24691                    .body
24692                    .contains("No description of what this change does could be generated")
24693            );
24694            assert!(failed.body.is_ascii());
24695            assert!(f.runner.state.github_text.is_none());
24696            assert!(f.runner.state.change_summary.is_none());
24697            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24698            let evidence = crate::pr_outcome::summary_evidence(
24699                &f.runner.state,
24700                crate::pr_outcome::FinalHead::At(&head),
24701            );
24702            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
24703            assert!(
24704                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
24705                    .exists()
24706            );
24707            f.runner.state =
24708                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
24709            std::fs::write(
24710                &f.reply,
24711                "TITLE: feat(own): add the own file\nAdds the committed own file.",
24712            )
24713            .unwrap();
24714            let retried = posted(&mut f).await;
24715            assert!(retried.body.contains("Adds the committed own file."));
24716            assert_eq!(
24717                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
24718                "日本語の修正報告"
24719            );
24720        }
24721    }
24722
24723    #[tokio::test]
24724    async fn same_head_verification_and_findings_invalidate_public_prose() {
24725        let mut f = summary_fixture();
24726        posted(&mut f).await;
24727        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24728        let original = f
24729            .runner
24730            .state
24731            .change_summary
24732            .as_ref()
24733            .unwrap()
24734            .evidence
24735            .clone();
24736        ok_gate(&mut f.runner.state, Some(&head));
24737        std::fs::write(
24738            &f.reply,
24739            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
24740        )
24741        .unwrap();
24742        let verified = posted(&mut f).await;
24743        assert!(verified.body.contains("now verified"));
24744        assert_ne!(
24745            f.runner.state.change_summary.as_ref().unwrap().evidence,
24746            original
24747        );
24748        let mut round = round_with_notes(1, Some("内部報告"));
24749        round.reviews.push(ReviewRecord {
24750            attempts: 0,
24751            reviewer: 1,
24752            agent: "alpha".into(),
24753            summary: "内部レビュー".into(),
24754            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
24755            vote: None,
24756            failed: None,
24757            duration_ms: 0,
24758        });
24759        round
24760            .fix
24761            .as_mut()
24762            .unwrap()
24763            .rejected
24764            .push(crate::verdict::Rejection {
24765                id: "R1-1-1".into(),
24766                why: "呼び出し元から到達できない".into(),
24767            });
24768        f.runner.state.reviews = vec![round];
24769        // A description omitting the required ID is unusable, even with a title.
24770        let omitted = posted(&mut f).await;
24771        assert!(omitted.body.contains("No description"));
24772        assert!(omitted.body.contains("R1-1-1"));
24773        assert!(!omitted.body.contains("到達"));
24774        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();
24775        let described = posted(&mut f).await;
24776        assert!(described.body.contains("unreachable from callers"));
24777        assert!(described.body.contains("R1-1-1"));
24778        assert!(!described.body.contains("到達"));
24779        let evidence = f
24780            .runner
24781            .state
24782            .change_summary
24783            .as_ref()
24784            .unwrap()
24785            .evidence
24786            .clone();
24787        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24788        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24789        assert!(posted(&mut f).await.body.contains("rationale updated"));
24790        assert_ne!(
24791            f.runner.state.change_summary.as_ref().unwrap().evidence,
24792            evidence
24793        );
24794        // Old serialized summaries have no evidence fingerprint and must regenerate.
24795        f.runner
24796            .state
24797            .change_summary
24798            .as_mut()
24799            .unwrap()
24800            .evidence
24801            .clear();
24802        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24803        assert!(posted(&mut f).await.body.contains("current specification"));
24804    }
24805
24806    #[tokio::test]
24807    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24808        let mut f = summary_fixture();
24809        let m = posted(&mut f).await;
24810        assert_eq!(m.title, "feat(own): add the own file");
24811        assert!(
24812            m.body
24813                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24814            "{}",
24815            m.body
24816        );
24817        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24818        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24819        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24820        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24821        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24822        let kept = f.runner.state.change_summary.as_ref().unwrap();
24823        assert_eq!(
24824            (kept.head.as_str(), kept.base.as_str()),
24825            (head.as_str(), base.as_str())
24826        );
24827        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24828    }
24829
24830    #[tokio::test]
24831    async fn review_only_summary_receives_the_configured_github_language() {
24832        let mut f = summary_fixture();
24833        f.runner.state.config.graph.github_language = "ja".into();
24834        let captured = f.repo.join("summary-prompt.txt");
24835        let author = &mut f.runner.state.config.agents[0];
24836        author.command = vec![
24837            "sh".into(),
24838            "-c".into(),
24839            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24840        ];
24841        author.env.insert(
24842            "PROMPT_FILE".into(),
24843            captured.to_string_lossy().into_owned(),
24844        );
24845        std::fs::write(
24846            &f.reply,
24847            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24848        )
24849        .unwrap();
24850        let m = posted(&mut f).await;
24851        let prompt = std::fs::read_to_string(captured).unwrap();
24852        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24853        assert!(!prompt.contains("in English"));
24854        assert_eq!(m.title, "feat(own): ファイルを追加");
24855        assert!(m.body.contains("own.txt を追加します。"));
24856    }
24857
24858    #[tokio::test]
24859    async fn review_fixes_come_after_the_whole_change_summary() {
24860        let mut f = summary_fixture();
24861        f.runner.state.reviews = vec![
24862            round_with_notes(1, Some("handled the PATH case")),
24863            round_with_notes(2, None),
24864        ];
24865        let m = posted(&mut f).await;
24866        let summary = m.body.find("## Summary").expect("summary");
24867        let fixes = m.body.find("## Review rounds").expect("review rounds");
24868        assert!(summary < fixes, "{}", m.body);
24869        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24870        assert!(m.body.contains("## Final verification"), "{}", m.body);
24871    }
24872
24873    #[tokio::test]
24874    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24875        let mut f = summary_fixture();
24876        let first = posted(&mut f).await;
24877        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24878        // The same head reuses the record: a different reply is not read.
24879        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24880        let again = posted(&mut f).await;
24881        assert_eq!((again.title, again.body), (first.title, first.body));
24882
24883        let g = |args: &[&str]| {
24884            let out = std::process::Command::new("git")
24885                .args(args)
24886                .current_dir(&f.repo)
24887                .quiet()
24888                .output()
24889                .expect("spawn git");
24890            assert!(out.status.success(), "git {args:?}");
24891        };
24892        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24893        g(&["add", "-A"]);
24894        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24895        let second = posted(&mut f).await;
24896        let kept = f.runner.state.change_summary.clone().unwrap();
24897        assert_ne!(kept.head, first_head);
24898        assert!(second.body.contains("Not read yet."), "{}", second.body);
24899        assert!(!second.body.contains("so the first summary is read"));
24900        assert_eq!(second.title, "feat(own): other");
24901    }
24902
24903    #[tokio::test]
24904    async fn an_unavailable_summary_is_stated_and_never_invented() {
24905        let mut f = summary_fixture();
24906        std::fs::write(&f.reply, "no title line here").unwrap();
24907        let m = posted(&mut f).await;
24908        assert!(
24909            m.body
24910                .contains("No description of what this change does could be generated"),
24911            "{}",
24912            m.body
24913        );
24914        assert!(m.body.contains("internal reports remain in local records"));
24915        assert!(f.runner.state.change_summary.is_none());
24916        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24917        // A preview asks nobody and claims nothing.
24918        let winner = f.runner.state.candidates[0].clone();
24919        let preview = f
24920            .runner
24921            .guarded_pr_message(&winner, None, false)
24922            .await
24923            .unwrap()
24924            .unwrap();
24925        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24926    }
24927
24928    #[test]
24929    fn pr_message_review_single_commit_uses_its_subject() {
24930        let state = review_state(&["feat(nats): per-role user"]);
24931        let m = pr_message(&state, 'A');
24932        assert_eq!(m.title, "feat(nats): per-role user");
24933        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24934        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24935    }
24936
24937    #[test]
24938    fn pr_message_review_multi_commit_takes_the_oldest() {
24939        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24940        let m = pr_message(&state, 'A');
24941        assert_eq!(m.title, "feat: the change");
24942        for s in ["feat: the change", "fix: typo", "fix: again"] {
24943            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24944        }
24945    }
24946
24947    #[test]
24948    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
24949        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
24950            let mut state = review_state(&[first, "fix: later fixup"]);
24951            state.candidates[0].branch = "機能/ログイン".to_owned();
24952            let m = pr_message(&state, 'A');
24953            assert!(
24954                m.title.starts_with("chore: land candidate A of run"),
24955                "{}",
24956                m.title
24957            );
24958        }
24959    }
24960
24961    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
24962        BranchFacts {
24963            commits: commits
24964                .iter()
24965                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
24966                .collect(),
24967            stat: stat.to_owned(),
24968        }
24969    }
24970
24971    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
24972        let mut r = review_round(true, 0, 1, 1, true, true);
24973        r.round = round;
24974        r.fix = notes.map(|n| FixRecord {
24975            agent: "fixer".to_owned(),
24976            addressed: Vec::new(),
24977            rejected: Vec::new(),
24978            notes: n.to_owned(),
24979            committed: true,
24980            failed: None,
24981            duration_ms: 0,
24982            continuation: None,
24983        });
24984        r
24985    }
24986
24987    #[test]
24988    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
24989        let state = review_state(&["ignored"]);
24990        let f = facts(
24991            &[
24992                (
24993                    "fix(login): resolve PATH on macOS",
24994                    "Login shells skip rc files.",
24995                ),
24996                ("fix: address review", ""),
24997            ],
24998            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
24999        );
25000        let m = pr_message_with(&state, 'A', Some(&f));
25001        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
25002        assert!(
25003            m.body
25004                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
25005            "{}",
25006            m.body
25007        );
25008        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
25009        assert!(m.body.contains("## Diff stat"), "{}", m.body);
25010        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
25011        for banned in [
25012            "Review the work already",
25013            "no task statement",
25014            "Original task",
25015        ] {
25016            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
25017        }
25018        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
25019    }
25020
25021    #[test]
25022    fn pr_message_review_truncates_a_huge_first_commit_body() {
25023        let state = review_state(&["ignored"]);
25024        let f = facts(
25025            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
25026            "s",
25027        );
25028        let m = pr_message_with(&state, 'A', Some(&f));
25029        assert!(m.body.len() < 30_000, "{}", m.body.len());
25030        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
25031        assert!(
25032            m.body.contains("- ... 1 more commit(s)"),
25033            "{}",
25034            m.body.len()
25035        );
25036        assert!(m.body.ends_with("magi:candidate-a\n"));
25037    }
25038
25039    #[test]
25040    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
25041        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
25042        assert_eq!(m.title, "feat: x");
25043        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
25044        assert!(!m.body.contains("Diff stat"), "{}", m.body);
25045        assert!(!m.body.contains("no task statement"), "{}", m.body);
25046    }
25047
25048    #[test]
25049    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
25050        let mut state = review_state(&["日本語の件名"]);
25051        state.candidates[0].branch = "fix/macos-login-path".to_owned();
25052        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
25053        state.candidates[0].branch = "機能/ログイン".to_owned();
25054        assert!(
25055            pr_message(&state, 'A')
25056                .title
25057                .starts_with("chore: land candidate A")
25058        );
25059    }
25060
25061    #[test]
25062    fn pr_message_review_fixes_survive_a_clean_final_round() {
25063        let mut state = review_state(&["feat: x"]);
25064        state.reviews = vec![
25065            round_with_notes(1, Some("handled the PATH case")),
25066            round_with_notes(2, None),
25067        ];
25068        let body = pr_message(&state, 'A').body;
25069        assert!(
25070            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
25071            "{body}"
25072        );
25073        assert!(body.contains("### Round 1"), "{body}");
25074
25075        state.reviews = vec![
25076            round_with_notes(1, Some("first fix")),
25077            round_with_notes(2, Some("")),
25078            round_with_notes(3, Some("second fix")),
25079            round_with_notes(4, None),
25080        ];
25081        let body = pr_message(&state, 'A').body;
25082        assert!(
25083            body.contains("### Round 1") && !body.contains("first fix"),
25084            "{body}"
25085        );
25086        assert!(
25087            body.contains("### Round 3") && !body.contains("second fix"),
25088            "{body}"
25089        );
25090        assert!(body.contains("### Round 2"), "{body}");
25091    }
25092
25093    const FINAL: &str = "abcdef1234567890";
25094
25095    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
25096        let mut r = round_with_notes(round, None);
25097        r.verified_head = verified.map(str::to_owned);
25098        r
25099    }
25100
25101    fn ok_gate(state: &mut RunState, head: Option<&str>) {
25102        state.gate = vec![CommandOutcome {
25103            command: "gate".to_owned(),
25104            code: Some(0),
25105            output_tail: String::new(),
25106            duration_ms: 0,
25107            resource_blocked: false,
25108            ..Default::default()
25109        }];
25110        state.gate_ran = true;
25111        state.gate_head = head.map(str::to_owned);
25112    }
25113
25114    fn body_at(state: &RunState) -> String {
25115        pr_message_raw(
25116            state,
25117            'A',
25118            None,
25119            crate::pr_outcome::FinalHead::At(FINAL),
25120            ChangeNote::NotAsked,
25121        )
25122        .body
25123    }
25124
25125    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
25126
25127    #[test]
25128    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
25129        let mut state = review_state(&["feat: x"]);
25130        state.reviews = vec![
25131            round_with_notes(1, Some(SANDBOXED)),
25132            passing_round(2, Some(FINAL)),
25133        ];
25134        ok_gate(&mut state, Some(FINAL));
25135        let body = body_at(&state);
25136        assert!(!body.contains("Handled the PATH case."), "{body}");
25137        assert!(!body.contains("could not commit"), "{body}");
25138        assert!(!body.contains("could not run"), "{body}");
25139        assert!(
25140            body.contains("The fix is committed on the branch"),
25141            "{body}"
25142        );
25143        assert!(!body.contains("sandbox"), "{body}");
25144        assert!(
25145            body.contains("Tests (`verify.e2e`): passed on the final commit"),
25146            "{body}"
25147        );
25148        assert!(
25149            body.contains("Gate (`verify.gate`): passed on the final commit"),
25150            "{body}"
25151        );
25152        // The raw report is untouched in the record.
25153        assert!(
25154            state.reviews[0]
25155                .fix
25156                .as_ref()
25157                .unwrap()
25158                .notes
25159                .contains("could not commit")
25160        );
25161    }
25162
25163    #[test]
25164    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
25165        let mut state = review_state(&["feat: x"]);
25166        let mut r1 = round_with_notes(1, Some(SANDBOXED));
25167        r1.fix.as_mut().unwrap().committed = false;
25168        let mut r2 = passing_round(2, Some(FINAL));
25169        r2.e2e[0].code = Some(1);
25170        state.reviews = vec![r1, r2];
25171        let body = body_at(&state);
25172        assert!(!body.contains("could not commit"), "{body}");
25173        assert!(!body.contains("could not run"), "{body}");
25174        assert!(body.contains("This round produced no commit"), "{body}");
25175        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
25176        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
25177        assert!(!body.contains("passed"), "{body}");
25178    }
25179
25180    #[test]
25181    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
25182        let mut state = review_state(&["feat: x"]);
25183        state.reviews = vec![
25184            round_with_notes(1, Some(SANDBOXED)),
25185            passing_round(2, Some("0123456789abcdef")),
25186        ];
25187        ok_gate(&mut state, Some("0123456789abcdef"));
25188        let body = body_at(&state);
25189        assert!(!body.contains("HTTP tests could not run"), "{body}");
25190        // The commit claim is still settled by the structured record.
25191        assert!(!body.contains("could not commit"), "{body}");
25192        assert!(
25193            body.contains("passed on an earlier commit (`0123456`)"),
25194            "{body}"
25195        );
25196        assert!(!body.contains("passed on the final commit"), "{body}");
25197
25198        // A gate recorded before `gate_head` existed is "not recorded".
25199        ok_gate(&mut state, None);
25200        let body = body_at(&state);
25201        assert!(
25202            body.contains("passed on a commit that was not recorded"),
25203            "{body}"
25204        );
25205    }
25206
25207    #[test]
25208    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
25209        let state = state_with_summary(
25210            "add retries to the client",
25211            "TITLE: feat: retries\n\nDid it.",
25212        );
25213        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
25214        assert_eq!(m.title, "feat: retries");
25215        assert!(
25216            m.body.contains("<summary>Original task</summary>"),
25217            "{}",
25218            m.body
25219        );
25220        assert!(!m.body.contains("Commits under review"), "{}", m.body);
25221        assert!(
25222            m.body
25223                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
25224            "{}",
25225            m.body
25226        );
25227    }
25228
25229    #[test]
25230    fn pr_message_review_bounds_a_long_english_subject() {
25231        let long = format!("feat: {}", "word ".repeat(100));
25232        let m = pr_message(&review_state(&[&long]), 'A');
25233        assert!(m.title.starts_with("feat: word"), "{}", m.title);
25234        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25235    }
25236
25237    #[test]
25238    fn pr_message_implementation_run_is_unchanged_by_review_support() {
25239        let state = state_with_summary("add retries\n\ndetails", "- did some things");
25240        let m = pr_message(&state, 'A');
25241        assert_eq!(m.title, "add retries");
25242        assert!(m.body.contains("<summary>Original task</summary>"));
25243        assert!(!m.body.contains("Commits under review"));
25244        assert_eq!(landing_subject_source(&state), state.instruction);
25245    }
25246
25247    #[test]
25248    fn review_run_squash_subject_is_the_change_not_the_prompt() {
25249        let state = review_state(&["feat: the change", "fix: typo"]);
25250        let source = landing_subject_source(&state);
25251        assert_eq!(land::merge_subject("", &source), "feat: the change");
25252        assert_eq!(
25253            land::merge_subject("magi: candidate A (uncommitted work)", &source),
25254            "feat: the change"
25255        );
25256        // An operator's rename still wins.
25257        assert_eq!(
25258            land::merge_subject("feat: renamed by hand", &source),
25259            "feat: renamed by hand"
25260        );
25261        let blank = review_state(&["日本語"]);
25262        assert!(
25263            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
25264        );
25265    }
25266
25267    #[test]
25268    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
25269        let state = review_state(&["feat: the change"]);
25270        let source = landing_subject_source(&state);
25271        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
25272        assert_eq!(
25273            land::merge_subject(landing_title(&state, old), &source),
25274            "feat: the change"
25275        );
25276        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
25277        let task = state_with_summary("add retries", "");
25278        assert_eq!(landing_title(&task, old), old);
25279    }
25280
25281    #[test]
25282    fn pr_message_describes_the_change_not_the_task() {
25283        let state = state_with_summary(
25284            "今回やってほしいこと: results projector を直す",
25285            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
25286        );
25287        let m = pr_message(&state, 'A');
25288        assert_eq!(m.title, "fix(web): batch the runs list reads");
25289        assert!(
25290            m.body.starts_with("## Summary\n\n- reads run.json once"),
25291            "{}",
25292            m.body
25293        );
25294        assert!(!m.body.contains("TITLE:"), "{}", m.body);
25295        let task_at = m.body.find("今回やってほしいこと").unwrap();
25296        let details_at = m.body.find("<details>").unwrap();
25297        assert!(
25298            details_at < task_at,
25299            "the task lives inside <details>: {}",
25300            m.body
25301        );
25302        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
25303        assert!(m.body.contains("magi:candidate-a"));
25304    }
25305
25306    #[test]
25307    fn pr_message_falls_back_to_the_task_without_a_title_line() {
25308        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
25309        let m = pr_message(&state, 'A');
25310        assert_eq!(m.title, "add retries");
25311        assert!(
25312            m.body.contains("## Summary\n\n- did some things"),
25313            "{}",
25314            m.body
25315        );
25316
25317        let none = RunState::new(
25318            PathBuf::from("/repo"),
25319            "main".to_owned(),
25320            "abc1234".to_owned(),
25321            "add retries".to_owned(),
25322            Config::default(),
25323        );
25324        let m = pr_message(&none, 'A');
25325        assert_eq!(m.title, "add retries");
25326        assert!(!m.body.contains("## Summary"), "{}", m.body);
25327    }
25328
25329    #[test]
25330    fn pr_message_refuses_the_candidate_commit_subject() {
25331        for bad in [
25332            "TITLE: magi: candidate A (uncommitted work)",
25333            "TITLE: chore: stuff (uncommitted work)",
25334            "TITLE:   ",
25335        ] {
25336            let state = state_with_summary("add retries", bad);
25337            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
25338        }
25339    }
25340
25341    #[test]
25342    fn pr_message_bounds_a_very_long_task_and_title() {
25343        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
25344        let state = state_with_summary(&long, "- nothing");
25345        let m = pr_message(&state, 'A');
25346        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25347        assert!(!m.title.contains('\n'));
25348
25349        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
25350        let m = pr_message(&state, 'A');
25351        assert!(m.title.starts_with("feat: "));
25352        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25353        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
25354    }
25355
25356    fn long_title_of(instruction: &str) -> String {
25357        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
25358    }
25359
25360    #[test]
25361    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
25362        let first = "Make the landing path keep a readable title for long tasks";
25363        let line = format!(
25364            "{first}. {}",
25365            "And then keep going with more words ".repeat(20)
25366        );
25367        let t = long_title_of(&line);
25368        assert_eq!(t, first);
25369        assert!(!t.starts_with("chore: land"));
25370    }
25371
25372    #[test]
25373    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
25374        let line = "word ".repeat(200);
25375        let t = long_title_of(&line);
25376        assert!(t.ends_with("word..."), "{t}");
25377        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
25378    }
25379
25380    #[test]
25381    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
25382        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
25383            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
25384        }
25385    }
25386
25387    #[test]
25388    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
25389        let mut state = state_with_summary("再試行を追加する", "- nothing");
25390        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
25391        state.config.graph.github_language = "ja".into();
25392        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
25393    }
25394
25395    #[test]
25396    fn pr_message_title_limit_is_exact() {
25397        let at = "a".repeat(PR_TITLE_MAX);
25398        assert_eq!(long_title_of(&at), at);
25399        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
25400        assert!(over.ends_with("..."), "{over}");
25401        assert_eq!(over.chars().count(), PR_TITLE_MAX);
25402    }
25403
25404    #[test]
25405    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
25406        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
25407        let t = long_title_of(&line);
25408        assert!(t.ends_with("..."), "{t}");
25409        assert!(t.is_ascii(), "{t}");
25410    }
25411
25412    #[test]
25413    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
25414        let line = format!(
25415            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
25416            "plus more filler words ".repeat(20)
25417        );
25418        let t = long_title_of(&line);
25419        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
25420    }
25421
25422    #[test]
25423    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
25424        let line = format!("\n\n# {}", "title words ".repeat(40));
25425        let state = state_with_summary(&line, "- nothing");
25426        let m = pr_message(&state, 'A');
25427        assert!(m.title.starts_with("title words"), "{}", m.title);
25428        assert_eq!(
25429            land::merge_subject(&m.title, &landing_subject_source(&state)),
25430            m.title
25431        );
25432        // An operator's rename wins untouched.
25433        assert_eq!(
25434            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
25435            "feat: renamed by hand"
25436        );
25437    }
25438
25439    #[tokio::test]
25440    async fn github_text_rewrite_is_bounded_and_falls_back() {
25441        crate::run::pin_test_home();
25442        for (reply, accepted) in [
25443            (
25444                "TITLE: fix: retries\nAdd retries for failed requests.",
25445                true,
25446            ),
25447            (
25448                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
25449                false,
25450            ),
25451            (
25452                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
25453                true,
25454            ),
25455            (
25456                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
25457                true,
25458            ),
25459            (
25460                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
25461                true,
25462            ),
25463            (
25464                "TITLE: fix: retries\n日本語の説明です。 token=secret",
25465                false,
25466            ),
25467            ("TITLE: fix: retries\n", false),
25468        ] {
25469            let dir = tempfile::tempdir().unwrap();
25470            let mut runner = runner_at(RunStatus::Gating);
25471            runner.state = state_with_summary(
25472                "add retries",
25473                "TITLE: fix: retries\n日本語の説明を書きます。",
25474            );
25475            runner.state.repo = dir.path().to_owned();
25476            runner.state.candidates[0].worktree = dir.path().to_owned();
25477            let mut author = spec("alpha");
25478            author.command = vec![
25479                "sh".into(),
25480                "-c".into(),
25481                "printf '%s' \"$REWRITE_REPLY\"".into(),
25482            ];
25483            author.env.insert("REWRITE_REPLY".into(), reply.into());
25484            runner.state.config.agents = vec![author];
25485            seed_public_summary(&mut runner);
25486            let winner = runner.state.candidates[0].clone();
25487            let first = runner
25488                .guarded_pr_message(&winner, None, true)
25489                .await
25490                .unwrap();
25491            let message = if accepted {
25492                first.expect("a passing rewrite never asks")
25493            } else {
25494                // Withheld: the run parks on a question and posts nothing yet.
25495                assert!(first.is_none());
25496                assert!(runner.state.parked);
25497                let store = ask::Questions::open();
25498                let asked: Vec<_> = store
25499                    .list()
25500                    .into_iter()
25501                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25502                    .collect();
25503                assert_eq!(asked.len(), 1);
25504                assert!(!asked[0].detail.contains("secret"));
25505                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
25506                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
25507                assert_eq!(
25508                    asked[0]
25509                        .choices
25510                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
25511                    rewrite.is_some()
25512                );
25513                // Silence: the question lapses and the neutral text is used,
25514                // without a second rewrite call or a second question.
25515                store
25516                    .update(&asked[0].id, |q| {
25517                        q.abandon("test");
25518                        Ok(())
25519                    })
25520                    .unwrap();
25521                let again = runner
25522                    .guarded_pr_message(&winner, None, true)
25523                    .await
25524                    .unwrap()
25525                    .expect("an abandoned question falls back");
25526                let n = store
25527                    .list()
25528                    .into_iter()
25529                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25530                    .count();
25531                assert_eq!(n, 1, "asked once per rejected text");
25532                again
25533            };
25534            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
25535            assert!(!message.body.contains("secret"));
25536            assert!(!message.body.contains("prefix"));
25537            assert!(!message.title.contains("secret"));
25538            assert_eq!(
25539                message.body.contains("Add retries for failed requests."),
25540                accepted
25541            );
25542            assert_eq!(
25543                runner.state.seats["github-text-rewrite"].turns, 1,
25544                "only one rewrite invocation"
25545            );
25546            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
25547            if accepted {
25548                assert!(runner.state.github_text.is_none());
25549                assert!(!runner.state.parked);
25550                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
25551                assert!(message.body.contains("## Final verification"));
25552                assert!(message.body.contains("Evidence: final diff"));
25553                assert!(
25554                    message
25555                        .body
25556                        .contains(&format!("magi:run/{}", runner.state.id))
25557                );
25558            }
25559            if !accepted {
25560                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25561                assert!(
25562                    message
25563                        .body
25564                        .contains(&format!("magi:run/{}", runner.state.id))
25565                );
25566            }
25567        }
25568    }
25569
25570    fn scripted(id: &str, reply: &str) -> AgentSpec {
25571        let mut a = spec(id);
25572        a.command = vec![
25573            "sh".into(),
25574            "-c".into(),
25575            "printf '%s' \"$REWRITE_REPLY\"".into(),
25576        ];
25577        a.env.insert("REWRITE_REPLY".into(), reply.into());
25578        a
25579    }
25580
25581    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
25582    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
25583
25584    /// Gate tests inject generated public output, not internal reports.
25585    fn seed_public_summary(runner: &mut Runner) {
25586        let repo = &runner.state.repo;
25587        let g = |args: &[&str]| {
25588            let out = std::process::Command::new("git")
25589                .args(args)
25590                .current_dir(repo)
25591                .quiet()
25592                .output()
25593                .unwrap();
25594            assert!(out.status.success(), "git {args:?}");
25595            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25596        };
25597        g(&["init", "-q", "-b", "main"]);
25598        g(&[
25599            "-c",
25600            "user.name=Test",
25601            "-c",
25602            "user.email=test@example.invalid",
25603            "commit",
25604            "-q",
25605            "--allow-empty",
25606            "-m",
25607            "feat: fixture",
25608        ]);
25609        let head = g(&["rev-parse", "HEAD"]);
25610        g(&["update-ref", "refs/remotes/origin/main", &head]);
25611        let evidence = crate::pr_outcome::summary_evidence(
25612            &runner.state,
25613            crate::pr_outcome::FinalHead::At(&head),
25614        );
25615        let generated = &runner.state.candidates[0].summary;
25616        runner.state.change_summary = Some(crate::run::ChangeSummary {
25617            base: head.clone(),
25618            head,
25619            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
25620            title: summary_title(generated).unwrap(),
25621            body: summary_without_title(generated),
25622        });
25623    }
25624
25625    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
25626        let mut runner = runner_at(RunStatus::Gating);
25627        runner.state = state_with_summary("add retries", JA_SUMMARY);
25628        if review_only {
25629            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
25630        }
25631        runner.state.repo = dir.to_owned();
25632        runner.state.candidates[0].worktree = dir.to_owned();
25633        runner.state.config.agents = agents;
25634        seed_public_summary(&mut runner);
25635        runner
25636    }
25637
25638    fn gate_questions(runner: &Runner) -> usize {
25639        ask::Questions::open()
25640            .list()
25641            .into_iter()
25642            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25643            .count()
25644    }
25645
25646    #[tokio::test]
25647    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
25648        crate::run::pin_test_home();
25649        let dir = tempfile::tempdir().unwrap();
25650        let mut runner = rewrite_runner(
25651            dir.path(),
25652            true,
25653            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25654        );
25655        runner.state.config.roles.language_judge =
25656            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
25657        let winner = runner.state.candidates[0].clone();
25658        let msg = runner
25659            .guarded_pr_message(&winner, None, true)
25660            .await
25661            .unwrap()
25662            .expect("an English rewrite posts without asking");
25663        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
25664        assert!(msg.body.contains("<details>kept</details>"));
25665        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
25666        assert_eq!(gate_questions(&runner), 0);
25667        assert!(runner.state.github_text.is_none());
25668        assert!(!runner.state.seats.contains_key("impl-A"));
25669        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25670    }
25671
25672    #[tokio::test]
25673    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
25674        crate::run::pin_test_home();
25675        let dir = tempfile::tempdir().unwrap();
25676        let mut runner = rewrite_runner(
25677            dir.path(),
25678            false,
25679            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25680        );
25681        runner.state.config.roles.language_judge =
25682            Some(crate::config::AgentChoice::One("beta".into()));
25683        runner.state.seats.insert(
25684            "impl-A".into(),
25685            SeatState::new("impl-A", "alpha", runner.state.seed),
25686        );
25687        let winner = runner.state.candidates[0].clone();
25688        let msg = runner
25689            .guarded_pr_message(&winner, None, true)
25690            .await
25691            .unwrap()
25692            .expect("rewritten");
25693        assert!(msg.body.contains("<details>kept</details>"));
25694        assert_eq!(runner.state.seats["impl-A"].turns, 0);
25695        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25696        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25697    }
25698
25699    #[tokio::test]
25700    async fn rewrite_reuses_a_resumable_implementer_session() {
25701        crate::run::pin_test_home();
25702        let dir = tempfile::tempdir().unwrap();
25703        let mut runner = rewrite_runner(
25704            dir.path(),
25705            false,
25706            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
25707        );
25708        runner.state.config.roles.language_judge =
25709            Some(crate::config::AgentChoice::One("beta".into()));
25710        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25711        seat.turns = 1;
25712        runner.state.seats.insert("impl-A".into(), seat);
25713        let winner = runner.state.candidates[0].clone();
25714        runner
25715            .guarded_pr_message(&winner, None, true)
25716            .await
25717            .unwrap()
25718            .expect("rewritten");
25719        assert_eq!(runner.state.seats["impl-A"].turns, 2);
25720        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
25721    }
25722
25723    #[tokio::test]
25724    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
25725        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
25726        // session, was out of quota, and nothing else was asked.
25727        crate::run::pin_test_home();
25728        let dir = tempfile::tempdir().unwrap();
25729        let mut exhausted = spec("alpha");
25730        exhausted.command = vec!["false".into()];
25731        let mut runner = rewrite_runner(
25732            dir.path(),
25733            false,
25734            vec![exhausted, scripted("beta", EN_REWRITE)],
25735        );
25736        // The implementer's own agent is in the role too: it is not asked twice.
25737        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25738            "alpha".into(),
25739            "beta".into(),
25740        ]));
25741        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25742        seat.turns = 1;
25743        runner.state.seats.insert("impl-A".into(), seat);
25744        let winner = runner.state.candidates[0].clone();
25745        let msg = runner
25746            .guarded_pr_message(&winner, None, true)
25747            .await
25748            .unwrap()
25749            .expect("the role rewrites after the implementer fails");
25750        assert!(msg.body.contains("`src/net.rs`"));
25751        assert_eq!(
25752            runner.state.seats["impl-A"].turns, 2,
25753            "the implementer was tried once"
25754        );
25755        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25756        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25757    }
25758
25759    #[tokio::test]
25760    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
25761        crate::run::pin_test_home();
25762        let dir = tempfile::tempdir().unwrap();
25763        let mut broken = spec("bad");
25764        broken.command = vec!["false".into()];
25765        let mut runner = rewrite_runner(
25766            dir.path(),
25767            true,
25768            vec![
25769                broken,
25770                scripted("noformat", "Add retries."),
25771                scripted("good", EN_REWRITE),
25772            ],
25773        );
25774        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25775            "bad".into(),
25776            "noformat".into(),
25777            "good".into(),
25778        ]));
25779        let winner = runner.state.candidates[0].clone();
25780        let msg = runner
25781            .guarded_pr_message(&winner, None, true)
25782            .await
25783            .unwrap()
25784            .expect("the third agent rewrites");
25785        assert!(msg.body.contains("`src/net.rs`"));
25786        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25787        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25788    }
25789
25790    #[tokio::test]
25791    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25792        crate::run::pin_test_home();
25793        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25794        for (agents, role, saved) in [
25795            (
25796                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25797                Some("beta"),
25798                true,
25799            ),
25800            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25801            (Vec::new(), None, false),
25802        ] {
25803            let dir = tempfile::tempdir().unwrap();
25804            let mut runner = rewrite_runner(dir.path(), true, agents);
25805            runner.state.config.roles.language_judge =
25806                role.map(|r| crate::config::AgentChoice::One(r.into()));
25807            let winner = runner.state.candidates[0].clone();
25808            let first = runner
25809                .guarded_pr_message(&winner, None, true)
25810                .await
25811                .unwrap();
25812            assert!(first.is_none(), "withheld text parks the run");
25813            assert!(runner.state.parked);
25814            assert_eq!(gate_questions(&runner), 1);
25815            let g = runner.state.github_text.as_ref().unwrap();
25816            assert_eq!(g.rewrite.is_some(), saved);
25817            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25818        }
25819    }
25820
25821    #[tokio::test]
25822    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25823        crate::run::pin_test_home();
25824        let dir = tempfile::tempdir().unwrap();
25825        let mut runner = runner_at(RunStatus::Gating);
25826        runner.state =
25827            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25828        runner.state.repo = dir.path().to_owned();
25829        runner.state.candidates[0].worktree = dir.path().to_owned();
25830        let mut author = spec("alpha");
25831        author.command = vec![
25832            "sh".into(),
25833            "-c".into(),
25834            "printf '%s' \"$REWRITE_REPLY\"".into(),
25835        ];
25836        author.env.insert(
25837            "REWRITE_REPLY".into(),
25838            format!(
25839                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25840                "English sentence. ".repeat(600)
25841            ),
25842        );
25843        runner.state.config.agents = vec![author];
25844        seed_public_summary(&mut runner);
25845        let winner = runner.state.candidates[0].clone();
25846        assert!(
25847            runner
25848                .guarded_pr_message(&winner, None, true)
25849                .await
25850                .unwrap()
25851                .is_none()
25852        );
25853        let record = runner.state.github_text.clone().unwrap();
25854        let rewrite = record.rewrite.clone().unwrap();
25855        assert_eq!(rewrite.failed, ["body-language"]);
25856        assert!(
25857            rewrite
25858                .body
25859                .ends_with(&format!("magi:run/{}", runner.state.id))
25860        );
25861        let store = ask::Questions::open();
25862        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25863        assert!(
25864            q.choices
25865                .contains(&crate::github_text::USE_REWRITE.to_owned())
25866        );
25867        for label in [
25868            "ORIGINAL",
25869            "FALLBACK",
25870            "REWRITE",
25871            "Rules still failed: body-language",
25872            "truncated",
25873        ] {
25874            assert!(q.detail.contains(label), "{label}");
25875        }
25876        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25877            &runner.state,
25878            &crate::github_text::artifact_name(&record.fingerprint),
25879        ))
25880        .unwrap();
25881        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25882        // Restart from serialized state, then retry after a bad owner title.
25883        runner.state =
25884            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25885        store
25886            .update(&q.id, |q| {
25887                q.say("まだ日本語")?;
25888                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25889            })
25890            .unwrap();
25891        assert!(
25892            runner
25893                .guarded_pr_message(&winner, None, true)
25894                .await
25895                .unwrap()
25896                .is_none()
25897        );
25898        let retry = runner.state.github_text.as_ref().unwrap();
25899        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25900        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25901        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25902        assert!(
25903            q.posting_comparison
25904                .as_ref()
25905                .unwrap()
25906                .matches_detail(&q.detail)
25907        );
25908        store
25909            .update(&q.id, |q| {
25910                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25911            })
25912            .unwrap();
25913        let message = runner
25914            .guarded_pr_message(&winner, None, true)
25915            .await
25916            .unwrap()
25917            .unwrap();
25918        assert_eq!(message.title, rewrite.title);
25919        assert_eq!(message.body, rewrite.body);
25920        assert_eq!(
25921            runner.state.github_text.as_ref().unwrap().choice,
25922            Some(GithubTextChoice::Rewrite)
25923        );
25924        let again = runner
25925            .guarded_pr_message(&winner, None, true)
25926            .await
25927            .unwrap()
25928            .unwrap();
25929        assert_eq!(again.title, message.title);
25930        assert_eq!(again.body, message.body);
25931        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25932        assert!(
25933            !runner
25934                .state
25935                .events
25936                .iter()
25937                .any(|e| e.message.contains(&rewrite.title)
25938                    || e.message.contains("English sentence."))
25939        );
25940    }
25941
25942    #[tokio::test]
25943    async fn historical_posting_reply_never_expires_into_fallback() {
25944        crate::run::pin_test_home();
25945        let dir = tempfile::tempdir().unwrap();
25946        let mut runner = runner_at(RunStatus::Gating);
25947        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25948        runner.state.repo = dir.path().to_owned();
25949        runner.state.candidates[0].worktree = dir.path().to_owned();
25950        seed_public_summary(&mut runner);
25951        let winner = runner.state.candidates[0].clone();
25952        assert!(
25953            runner
25954                .guarded_pr_message(&winner, None, true)
25955                .await
25956                .unwrap()
25957                .is_none()
25958        );
25959        let id = runner
25960            .state
25961            .github_text
25962            .as_ref()
25963            .unwrap()
25964            .question
25965            .clone()
25966            .unwrap();
25967        let store = ask::Questions::open();
25968        let mut q = store.get(&id).unwrap();
25969        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
25970        q.answer(ask::Answer::Choice(
25971            crate::github_text::POST_ORIGINAL.into(),
25972        ))
25973        .unwrap();
25974        q.answer_delivered = true;
25975        store.put(&mut q).unwrap();
25976        let source = std::fs::read(store.path_of(&id)).unwrap();
25977        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
25978        std::fs::create_dir_all(&migration).unwrap();
25979        std::fs::write(
25980            migration.join("state.json"),
25981            serde_json::to_vec(&serde_json::json!({
25982                "schema": 1, "sources": [id], "pending": [id]
25983            }))
25984            .unwrap(),
25985        )
25986        .unwrap();
25987        for _ in 0..2 {
25988            assert!(
25989                runner
25990                    .guarded_pr_message(&winner, None, true)
25991                    .await
25992                    .unwrap()
25993                    .is_none()
25994            );
25995            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25996            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25997        }
25998        let home = crate::run::home();
25999        crate::task_chat::sweep(
26000            &crate::queue::Queue::at(home.join("queue")),
26001            &crate::talk::Talks::at(home.join("talks")),
26002            &store,
26003            &home,
26004        );
26005        let outbox = crate::task_inquiry::Outbox::at(&home);
26006        outbox
26007            .update_decision(&id, |d| {
26008                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
26009                d.source_answer_at = q.answered_at;
26010                Ok(true)
26011            })
26012            .unwrap();
26013        outbox
26014            .settle(
26015                &id,
26016                "owner-chat",
26017                "Owner confirms no publication remains necessary",
26018                None,
26019            )
26020            .unwrap();
26021        assert!(
26022            runner
26023                .guarded_pr_message(&winner, None, true)
26024                .await
26025                .unwrap()
26026                .is_none()
26027        );
26028        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
26029        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
26030    }
26031
26032    #[tokio::test]
26033    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
26034        crate::run::pin_test_home();
26035        let dir = tempfile::tempdir().unwrap();
26036        let mut runner = runner_at(RunStatus::Gating);
26037        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
26038        runner.state.repo = dir.path().to_owned();
26039        runner.state.candidates[0].worktree = dir.path().to_owned();
26040        seed_public_summary(&mut runner);
26041        let winner = runner.state.candidates[0].clone();
26042        assert!(
26043            runner
26044                .guarded_pr_message(&winner, None, true)
26045                .await
26046                .unwrap()
26047                .is_none()
26048        );
26049        let record = runner.state.github_text.as_ref().unwrap();
26050        assert!(record.rewrite.is_none());
26051        // Records written before the additive field deserialize with no rewrite.
26052        let mut old = serde_json::to_value(record).unwrap();
26053        old.as_object_mut().unwrap().remove("rewrite");
26054        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
26055        assert!(old.rewrite.is_none());
26056        let id = record.question.clone().unwrap();
26057        ask::Questions::open()
26058            .update(&id, |q| {
26059                q.choices.push(crate::github_text::USE_REWRITE.into());
26060                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
26061            })
26062            .unwrap();
26063        let message = runner
26064            .guarded_pr_message(&winner, None, true)
26065            .await
26066            .unwrap()
26067            .unwrap();
26068        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
26069        assert_eq!(
26070            runner.state.github_text.as_ref().unwrap().choice,
26071            Some(GithubTextChoice::Fallback)
26072        );
26073    }
26074
26075    #[tokio::test]
26076    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
26077        crate::run::pin_test_home();
26078        let dir = tempfile::tempdir().unwrap();
26079        let mut runner = runner_at(RunStatus::Gating);
26080        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
26081        runner.state.repo = dir.path().to_owned();
26082        runner.state.candidates[0].worktree = dir.path().to_owned();
26083        seed_public_summary(&mut runner);
26084        let winner = runner.state.candidates[0].clone();
26085        assert!(
26086            runner
26087                .guarded_pr_message(&winner, None, true)
26088                .await
26089                .unwrap()
26090                .is_none()
26091        );
26092        let store = ask::Questions::open();
26093        let find = |run: &str| {
26094            store
26095                .list()
26096                .into_iter()
26097                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
26098                .unwrap()
26099        };
26100        let run = runner.state.id.clone();
26101        let q = find(&run);
26102        let fp = runner
26103            .state
26104            .github_text
26105            .as_ref()
26106            .unwrap()
26107            .fingerprint
26108            .clone();
26109        let name = crate::github_text::artifact_name(&fp);
26110        let path = crate::run::artifact_path(&runner.state, &name);
26111        assert!(q.detail.contains(&path.display().to_string()));
26112        assert!(q.detail.contains("title-language: title"));
26113        let saved = std::fs::read_to_string(&path).expect("artifact written");
26114        assert!(saved.contains("日本語のタイトル"));
26115        assert!(q.cwd.is_none());
26116        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
26117        // A bad replacement is refused and asked about once more.
26118        let say = |id: &str, text: &str, choice: &str| {
26119            store
26120                .update(id, |q| {
26121                    q.thread.push(ask::Turn {
26122                        who: ask::Who::Operator,
26123                        body: text.to_owned(),
26124                        at: jiff::Timestamp::now(),
26125                        note: None,
26126                    });
26127                    q.answer(ask::Answer::Choice(choice.to_owned()))
26128                })
26129                .unwrap();
26130        };
26131        say(&q.id, "まだ日本語", "use my text");
26132        assert!(
26133            runner
26134                .guarded_pr_message(&winner, None, true)
26135                .await
26136                .unwrap()
26137                .is_none()
26138        );
26139        let second = find(&run);
26140        assert_ne!(second.id, q.id);
26141        assert!(second.detail.contains("did not pass"));
26142        // The retry still compares the original text; the rejected
26143        // replacement is named by category only.
26144        assert!(second.detail.contains("日本語のタイトル"));
26145        assert!(!second.detail.contains("まだ日本語"));
26146        assert!(second.detail.contains(&path.display().to_string()));
26147        say(&second.id, "fix: retry failed requests", "use my text");
26148        let message = runner
26149            .guarded_pr_message(&winner, None, true)
26150            .await
26151            .unwrap()
26152            .expect("a vetted replacement is posted");
26153        assert_eq!(message.title, "fix: retry failed requests");
26154        assert_eq!(
26155            runner
26156                .state
26157                .github_text
26158                .as_ref()
26159                .unwrap()
26160                .chosen_title
26161                .as_deref(),
26162            Some("fix: retry failed requests")
26163        );
26164        assert!(runner.state.github_text.as_ref().unwrap().resolved);
26165        // Resumed again: the saved decision is applied, nothing is re-asked.
26166        let again = runner
26167            .guarded_pr_message(&winner, None, true)
26168            .await
26169            .unwrap()
26170            .unwrap();
26171        assert_eq!(again.title, message.title);
26172        assert_eq!(
26173            store
26174                .list()
26175                .into_iter()
26176                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
26177                .count(),
26178            2
26179        );
26180    }
26181
26182    #[test]
26183    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
26184        // What magi itself writes stays English under any configured language,
26185        // so a future localisation of these headings fails here. (The agents'
26186        // own text is also checked by the posting gate.)
26187        let mut state = state_with_summary(
26188            "add retries",
26189            "TITLE: fix(web): batch reads\n- reads run.json once",
26190        );
26191        state.config.graph.language = "ja".to_owned();
26192        let m = pr_message(&state, 'A');
26193        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
26194        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
26195
26196        // The task is the operator's own text: it goes in untouched, and the
26197        // fallback title (no summary) may be in its language too.
26198        let task = "今回やってほしいこと: results projector を直す";
26199        let mut state = state_with_summary(task, "- no title line");
26200        state.config.graph.language = "ja".to_owned();
26201        let m = pr_message(&state, 'A');
26202        assert_eq!(
26203            m.title,
26204            format!("chore: land candidate A of run {}", state.id)
26205        );
26206        assert!(
26207            m.body.contains(&format!(
26208                "<summary>Original task</summary>\n\n{task}\n\n</details>"
26209            )),
26210            "{}",
26211            m.body
26212        );
26213    }
26214
26215    #[test]
26216    fn pr_message_scrubs_home_paths_and_addresses() {
26217        let state = state_with_summary(
26218            "fix it in /Users/someone/src/x",
26219            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
26220        );
26221        let m = pr_message(&state, 'A');
26222        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
26223            assert!(!m.body.contains(leak), "{}", m.body);
26224        }
26225        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
26226    }
26227
26228    #[test]
26229    fn pr_message_survives_a_task_that_closes_details() {
26230        let state = state_with_summary("a </details> b", "TITLE: fix: x");
26231        let m = pr_message(&state, 'A');
26232        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
26233    }
26234
26235    #[test]
26236    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
26237        let cmd = manual_merge_command(
26238            MergeStyle::Squash,
26239            Path::new("/repo"),
26240            "b",
26241            "fix: \"quoted\" $(x) `y`\n\nbody",
26242        );
26243        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
26244    }
26245
26246    #[test]
26247    fn manual_merge_command_matches_the_configured_style() {
26248        let repo = Path::new("/repo");
26249        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
26250
26251        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
26252        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
26253
26254        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
26255        assert_eq!(
26256            squash,
26257            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
26258             \"Merge magi run 0832 (candidate A)\""
26259        );
26260
26261        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
26262        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
26263    }
26264
26265    #[test]
26266    fn a_nudge_gets_a_quarter_of_the_budget() {
26267        // The judge and implement budgets magi ships with.
26268        assert_eq!(retry_budget(secs(1200), true), secs(300));
26269        assert_eq!(retry_budget(secs(3600), true), secs(900));
26270    }
26271
26272    #[test]
26273    fn a_resent_prompt_keeps_the_whole_budget() {
26274        // The seat kept no context, so the retry is the original job again and
26275        // shortening it would only guarantee a second failure.
26276        assert_eq!(retry_budget(secs(1200), false), secs(1200));
26277        assert_eq!(retry_budget(secs(60), false), secs(60));
26278    }
26279
26280    #[test]
26281    fn the_floor_never_exceeds_the_original_budget() {
26282        // A short configured timeout must not be *raised* by the floor: the
26283        // operator asked for a bound, and a retry may not outlast the attempt
26284        // it is retrying.
26285        assert_eq!(retry_budget(secs(60), true), secs(60));
26286        assert_eq!(retry_budget(secs(480), true), secs(120));
26287        assert_eq!(retry_budget(secs(0), true), secs(0));
26288    }
26289
26290    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
26291        agent::CommandEvidence {
26292            id: "item1".to_owned(),
26293            description: "cargo test".to_owned(),
26294            exit_code,
26295            result_summary: String::new(),
26296            source: "codex".to_owned(),
26297        }
26298    }
26299
26300    #[test]
26301    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
26302        // No evidence is not the same fact as unconfirmed evidence: a
26303        // backend with no adapter, or a reply that ran no commands at all,
26304        // must not be misread as carrying a dangling job.
26305        assert!(!has_unconfirmed_command(&[]));
26306    }
26307
26308    fn reply(tool_calls: Option<u64>) -> AgentOutput {
26309        AgentOutput {
26310            text: "## SUMMARY\nImplementation incomplete.".to_owned(),
26311            exit_code: Some(0),
26312            timed_out: false,
26313            duration_ms: 7_000,
26314            artifacts: Vec::new(),
26315            quota: None,
26316            dropped: None,
26317            commands: Vec::new(),
26318            context_tokens: None,
26319            tool_calls,
26320        }
26321    }
26322
26323    #[test]
26324    fn a_clean_reply_with_no_tool_call_on_an_untouched_tree_is_unstarted() {
26325        assert!(ended_unstarted(
26326            &reply(Some(0)),
26327            Some("abc"),
26328            Some("abc"),
26329            Some(true)
26330        ));
26331    }
26332
26333    #[test]
26334    fn unknown_or_real_tool_activity_is_never_unstarted() {
26335        // A backend that reports no tool calls says nothing about them.
26336        assert!(!ended_unstarted(
26337            &reply(None),
26338            Some("abc"),
26339            Some("abc"),
26340            Some(true)
26341        ));
26342        // A seat that looked and then wrote nothing did start.
26343        assert!(!ended_unstarted(
26344            &reply(Some(3)),
26345            Some("abc"),
26346            Some("abc"),
26347            Some(true)
26348        ));
26349        let mut ran = reply(Some(0));
26350        ran.commands.push(evidence(Some(0)));
26351        assert!(!ended_unstarted(&ran, Some("abc"), Some("abc"), Some(true)));
26352    }
26353
26354    #[test]
26355    fn work_in_the_tree_or_an_unreadable_one_is_never_unstarted() {
26356        let out = reply(Some(0));
26357        // A commit, uncommitted edits, and each unknown: none may be replayed.
26358        assert!(!ended_unstarted(&out, Some("abc"), Some("def"), Some(true)));
26359        assert!(!ended_unstarted(
26360            &out,
26361            Some("abc"),
26362            Some("abc"),
26363            Some(false)
26364        ));
26365        assert!(!ended_unstarted(&out, None, Some("abc"), Some(true)));
26366        assert!(!ended_unstarted(&out, Some("abc"), None, Some(true)));
26367        assert!(!ended_unstarted(&out, Some("abc"), Some("abc"), None));
26368        assert!(!ended_unstarted(&out, None, None, Some(true)));
26369    }
26370
26371    #[test]
26372    fn a_failed_or_empty_turn_is_not_an_unstarted_reply() {
26373        let mut failed = reply(Some(0));
26374        failed.exit_code = Some(1);
26375        assert!(!ended_unstarted(
26376            &failed,
26377            Some("abc"),
26378            Some("abc"),
26379            Some(true)
26380        ));
26381        let mut silent = reply(Some(0));
26382        silent.text = String::new();
26383        assert!(!ended_unstarted(
26384            &silent,
26385            Some("abc"),
26386            Some("abc"),
26387            Some(true)
26388        ));
26389    }
26390
26391    #[test]
26392    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
26393        // Deliberately not a check on the exit code's *value*: a fixer
26394        // legitimately runs something that fails mid-iteration before it
26395        // succeeds, and that must never by itself reopen a valid report.
26396        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
26397        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
26398        assert!(!has_unconfirmed_command(&[
26399            evidence(Some(0)),
26400            evidence(Some(101))
26401        ]));
26402    }
26403
26404    #[test]
26405    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
26406        assert!(has_unconfirmed_command(&[
26407            evidence(Some(0)),
26408            evidence(None)
26409        ]));
26410    }
26411
26412    fn evidence_with(
26413        description: &str,
26414        exit_code: Option<i32>,
26415        result_summary: &str,
26416    ) -> agent::CommandEvidence {
26417        agent::CommandEvidence {
26418            id: "item1".to_owned(),
26419            description: description.to_owned(),
26420            exit_code,
26421            result_summary: result_summary.to_owned(),
26422            source: "codex".to_owned(),
26423        }
26424    }
26425
26426    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
26427        format!(
26428            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":[]}}"#
26429        )
26430    }
26431
26432    #[test]
26433    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
26434        let text = valid_noop_summary("b32cfc4", "retry_test");
26435        let claim = verified_noop_claim(true, &[], &text)
26436            .expect("valid structured report with no CommandEvidence must be accepted");
26437        assert!(claim.contains("b32cfc4"), "{claim}");
26438        assert!(claim.contains("retry_test"), "{claim}");
26439    }
26440
26441    #[test]
26442    fn operational_regression_and_legacy_noop_claims_are_rejected() {
26443        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
26444        assert!(verified_noop_claim(true, &[], regression).is_none());
26445        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
26446        assert!(err.contains("single JSON object"), "{err}");
26447
26448        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
26449        assert!(verified_noop_claim(true, &[], legacy).is_none());
26450    }
26451
26452    #[test]
26453    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
26454        // A timeout or a bad exit code reads as the ordinary loss it is,
26455        // whatever the reply's own structured JSON claims.
26456        let text = valid_noop_summary("b32cfc4", "retry_test");
26457        assert!(verified_noop_claim(false, &[], &text).is_none());
26458    }
26459
26460    #[test]
26461    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
26462        let text = valid_noop_summary("b32cfc4", "retry_test");
26463        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
26464        // A matching confirmed command alongside the marker is fine.
26465        assert!(
26466            verified_noop_claim(
26467                true,
26468                &[evidence_with(
26469                    "cargo test --lib retry_test",
26470                    Some(0),
26471                    "1 passed"
26472                )],
26473                &text
26474            )
26475            .is_some()
26476        );
26477    }
26478
26479    #[test]
26480    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
26481     {
26482        let text = valid_noop_summary("b32cfc4", "retry_test");
26483
26484        // Unrelated passing command cannot substantiate a claimed test run.
26485        let err = evaluate_noop_claim(
26486            true,
26487            &[evidence_with("git status", Some(0), "nothing to commit")],
26488            &text,
26489        )
26490        .unwrap_err();
26491        assert!(err.contains("no matching command was recorded"), "{err}");
26492
26493        // Final matching command exited non-zero -> rejected even if an
26494        // unrelated command succeeded afterward.
26495        let err = evaluate_noop_claim(
26496            true,
26497            &[
26498                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
26499                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26500                evidence_with("rg retry_test src", Some(0), "retry_test"),
26501            ],
26502            &text,
26503        )
26504        .unwrap_err();
26505        assert!(err.contains("exited with"), "{err}");
26506
26507        // A different invocation containing the entire method is not a rerun.
26508        let err = evaluate_noop_claim(
26509            true,
26510            &[evidence_with(
26511                "echo 'cargo test --lib retry_test'",
26512                Some(0),
26513                "retry_test",
26514            )],
26515            &text,
26516        )
26517        .unwrap_err();
26518        assert!(err.contains("no matching command was recorded"), "{err}");
26519
26520        // Mid-investigation failure followed by a passing re-run -> accepted!
26521        assert!(
26522            verified_noop_claim(
26523                true,
26524                &[
26525                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26526                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
26527                ],
26528                &text
26529            )
26530            .is_some()
26531        );
26532    }
26533
26534    #[test]
26535    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
26536        let text = valid_noop_summary("b32cfc4", "retry_test");
26537        let method = "cargo test --lib retry_test";
26538        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
26539        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
26540        let failed =
26541            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
26542        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
26543        for output in [empty, ignored, failed] {
26544            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
26545                .unwrap_err();
26546            assert!(err.contains("failure or no passing tests"), "{err}");
26547        }
26548        // Multiple harnesses can legitimately include a filtered-out suite.
26549        let mixed = format!("{passed}\n{empty}");
26550        assert!(
26551            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
26552        );
26553        // A later real rerun of the same command can establish success.
26554        assert!(
26555            verified_noop_claim(
26556                true,
26557                &[
26558                    evidence_with(method, Some(0), empty),
26559                    evidence_with(method, Some(0), passed),
26560                ],
26561                &text,
26562            )
26563            .is_some()
26564        );
26565    }
26566
26567    #[test]
26568    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
26569        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":[]}"#;
26570        let failed = evidence_with("rg expected README.md", Some(1), "");
26571        let unrelated = evidence_with("cat README.md", Some(0), "README");
26572        let err =
26573            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
26574        assert!(err.contains("exited with"), "{err}");
26575        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
26576        assert!(
26577            evaluate_noop_claim(
26578                true,
26579                &[
26580                    failed,
26581                    evidence_with("rg expected README.md", Some(0), "expected header"),
26582                ],
26583                text,
26584            )
26585            .unwrap()
26586            .is_some()
26587        );
26588    }
26589
26590    #[test]
26591    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
26592        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
26593        assert!(matches!(
26594            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
26595            Ok(None)
26596        ));
26597    }
26598
26599    #[tokio::test]
26600    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
26601        let tmp = tempfile::tempdir().unwrap();
26602        let repo = tmp.path().join("repo");
26603        std::fs::create_dir_all(&repo).unwrap();
26604        let run_git = |args: &[&str]| {
26605            let out = std::process::Command::new("git")
26606                .args(args)
26607                .current_dir(&repo)
26608                .output()
26609                .unwrap();
26610            assert!(out.status.success(), "git {args:?} failed");
26611            String::from_utf8_lossy(&out.stdout).trim().to_owned()
26612        };
26613        run_git(&["init", "-b", "main"]);
26614        run_git(&["config", "user.name", "test"]);
26615        run_git(&["config", "user.email", "test@example.com"]);
26616        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
26617        run_git(&["add", "-A"]);
26618        run_git(&["commit", "-m", "base commit"]);
26619        let base = run_git(&["rev-parse", "HEAD"]);
26620
26621        // Create a commit on a side branch not on `base`.
26622        run_git(&["checkout", "-b", "side"]);
26623        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
26624        run_git(&["add", "-A"]);
26625        run_git(&["commit", "-m", "side commit"]);
26626        let side = run_git(&["rev-parse", "HEAD"]);
26627        run_git(&["checkout", "main"]);
26628
26629        // Valid commit on base + existing path -> Accepted.
26630        let valid = format!(
26631            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":[]}}"#
26632        );
26633        assert!(matches!(
26634            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
26635            NoopClaimVerdict::Accepted
26636        ));
26637
26638        // Non-existent commit SHA -> Rejected.
26639        let missing_sha = valid.replace(&base, "deadbeef");
26640        assert!(matches!(
26641            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
26642            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
26643        ));
26644
26645        // Commit on unmerged side branch -> Rejected.
26646        let side_sha = valid.replace(&base, &side);
26647        assert!(matches!(
26648            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
26649            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
26650        ));
26651
26652        // Missing file path -> Rejected.
26653        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
26654        assert!(matches!(
26655            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
26656            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
26657        ));
26658    }
26659
26660    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
26661    /// pair, in order, labelled A, B, C, ...
26662    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
26663        runner.state.candidates = shape
26664            .iter()
26665            .enumerate()
26666            .map(|(i, &(empty, verified))| {
26667                let (summary, verified_noop) = match verified {
26668                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
26669                    None => (String::new(), None),
26670                };
26671                Candidate {
26672                    index: i,
26673                    label: (b'A' + i as u8) as char,
26674                    agent: "sonnet".to_owned(),
26675                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
26676                    worktree: PathBuf::from(format!("/wt/{i}")),
26677                    summary,
26678                    stat: String::new(),
26679                    files: 0,
26680                    commits: 0,
26681                    empty,
26682                    failed: None,
26683                    verified_noop,
26684                    duration_ms: 0,
26685                    folded: false,
26686                }
26687            })
26688            .collect();
26689    }
26690
26691    #[test]
26692    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
26693        ask_test_home();
26694        let mut runner = runner_at(RunStatus::Implementing);
26695        let a = valid_noop_summary("b32cfc4", "test_a");
26696        let b = valid_noop_summary("b32cfc4", "test_b");
26697        set_candidates(
26698            &mut runner,
26699            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
26700        );
26701
26702        runner
26703            .after_implement()
26704            .expect("a verified no-op is not an error");
26705
26706        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
26707    }
26708
26709    #[test]
26710    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
26711        ask_test_home();
26712        let mut runner = runner_at(RunStatus::Implementing);
26713        let a = valid_noop_summary("b32cfc4", "test_a");
26714        // Candidate A declares a verified no-op; candidate B simply wrote
26715        // nothing and said nothing about why. One candidate's claim is not
26716        // the whole run's agreement.
26717        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
26718
26719        let err = runner
26720            .after_implement()
26721            .expect_err("an unverified empty candidate must still fail the run");
26722
26723        assert!(
26724            err.to_string().contains("no candidate produced a change"),
26725            "{err}"
26726        );
26727        assert_eq!(runner.state.status, RunStatus::Failed);
26728    }
26729
26730    #[test]
26731    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
26732        ask_test_home();
26733        let mut runner = runner_at(RunStatus::Implementing);
26734        // Simulate a saved incomplete run that stored a legacy/incomplete
26735        // `verified_noop` string before this build's strict contract.
26736        set_candidates(
26737            &mut runner,
26738            &[(
26739                true,
26740                Some(
26741                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
26742                ),
26743            )],
26744        );
26745
26746        let err = runner
26747            .after_implement()
26748            .expect_err("invalid saved noop claim must fail the run");
26749        assert!(
26750            err.to_string().contains("no candidate produced a change"),
26751            "{err}"
26752        );
26753        assert_eq!(runner.state.status, RunStatus::Failed);
26754        assert!(runner.state.candidates[0].verified_noop.is_none());
26755        assert!(runner.state.candidates[0].failed.is_some());
26756        assert!(runner.state.events.iter().any(|e| {
26757            e.message
26758                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
26759        }));
26760    }
26761
26762    #[test]
26763    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
26764        ask_test_home();
26765        let mut runner = runner_at(RunStatus::Implementing);
26766        let a = valid_noop_summary("b32cfc4", "test_a");
26767        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
26768        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
26769
26770        let err = runner
26771            .after_implement()
26772            .expect_err("a failed candidate must never settle as verified no-op");
26773        assert!(err.to_string().contains("no candidate produced a change"));
26774        assert_eq!(runner.state.status, RunStatus::Failed);
26775        assert!(runner.state.candidates[0].verified_noop.is_none());
26776    }
26777
26778    #[test]
26779    fn after_implement_still_fails_an_ordinary_all_empty_run() {
26780        ask_test_home();
26781        let mut runner = runner_at(RunStatus::Implementing);
26782        set_candidates(&mut runner, &[(true, None), (true, None)]);
26783
26784        let err = runner
26785            .after_implement()
26786            .expect_err("no candidate declared anything; this is an ordinary failure");
26787
26788        assert!(
26789            err.to_string().contains("no candidate produced a change"),
26790            "{err}"
26791        );
26792        assert_eq!(runner.state.status, RunStatus::Failed);
26793    }
26794}
26795
26796/// A graft rollback whose restore could not be confirmed (see
26797/// [`Runner::graft`]).
26798#[derive(Debug)]
26799struct GraftRestoreFailed(String);
26800
26801impl std::fmt::Display for GraftRestoreFailed {
26802    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26803        write!(
26804            f,
26805            "could not restore the winner to its pre-graft commit: {}",
26806            self.0
26807        )
26808    }
26809}
26810
26811impl std::error::Error for GraftRestoreFailed {}
26812
26813/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
26814/// not the agent: they never draw on an agent's own timeout, and running out of
26815/// them never reads as an agent failure.
26816#[cfg(test)]
26817mod resource_wait_tests {
26818    use super::*;
26819    use std::collections::BTreeMap;
26820
26821    fn sh(id: &str, script: &str) -> AgentSpec {
26822        AgentSpec {
26823            id: id.to_owned(),
26824            kind: crate::config::AgentKind::Command,
26825            model: None,
26826            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
26827            extra_args: Vec::new(),
26828            env: BTreeMap::new(),
26829            prompt_delivery: None,
26830            max_turn_secs: None,
26831        }
26832    }
26833
26834    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
26835        SeatJob {
26836            seat: SeatState::new("impl-A", &spec.id, 1),
26837            spec,
26838            cwd: dir.to_path_buf(),
26839            prompt: "do it".to_owned(),
26840            timeout,
26841            allow_write: true,
26842            sessions: false,
26843            artifacts: dir.join("art"),
26844            stem: "impl-A".to_owned(),
26845            handover: None,
26846        }
26847    }
26848
26849    fn state(resource_wait_secs: u64) -> RunState {
26850        let mut config = Config::default();
26851        config.graph.timeout_resource_wait = resource_wait_secs;
26852        RunState::new(
26853            PathBuf::from("/repo"),
26854            "main".to_owned(),
26855            "abc1234".to_owned(),
26856            "task".to_owned(),
26857            config,
26858        )
26859    }
26860
26861    fn hold(cache: &Path) -> crate::cache::Guard {
26862        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
26863        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
26864            crate::cache::AcquireOutcome::Acquired(g) => g,
26865            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26866        }
26867    }
26868
26869    async fn run(
26870        jobs: Vec<SeatJob>,
26871        sem: Arc<Semaphore>,
26872        cache: Option<&Path>,
26873        st: &mut RunState,
26874    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26875        let prompts = Prompts::default();
26876        let ctx = WaveCtx {
26877            run: "r",
26878            node: "implement",
26879            prompts: &prompts,
26880            cache,
26881            round: None,
26882            carry_seats: false,
26883            pauses: None,
26884        };
26885        wave(jobs, sem, &ctx, st, 0).await
26886    }
26887
26888    #[tokio::test]
26889    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26890        crate::run::pin_test_home();
26891        let home = crate::run::home();
26892        let tmp = tempfile::tempdir().unwrap();
26893        let repo = tmp.path().join("repo");
26894        let checkout = tmp.path().join("checkout");
26895        std::fs::create_dir(&repo).unwrap();
26896        git::git(&repo, &["init"]).await.unwrap();
26897        git::git(
26898            &repo,
26899            &[
26900                "-c",
26901                "user.name=Fixture",
26902                "-c",
26903                "user.email=fixture@example.invalid",
26904                "commit",
26905                "--allow-empty",
26906                "-m",
26907                "initial",
26908            ],
26909        )
26910        .await
26911        .unwrap();
26912        git::worktree_add_detached(&repo, &checkout, "HEAD")
26913            .await
26914            .unwrap();
26915        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26916        let target_lease = hold(&target);
26917        let shared = tmp.path().join("unrelated");
26918        let _shared_lease = hold(&shared);
26919        let mut st = state(0);
26920        st.repo = repo.clone();
26921        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26922        st.config.verify.e2e = vec![format!(
26923            "CARGO_TARGET_DIR='{}' cargo test",
26924            git::path_arg(&shared)
26925        )];
26926        let config = tmp.path().join("config.toml");
26927        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26928        let prompts = Prompts::default();
26929        let run_id = st.id.clone();
26930        let ctx = WaveCtx {
26931            run: &run_id,
26932            node: "implement",
26933            prompts: &prompts,
26934            cache: None,
26935            round: None,
26936            carry_seats: false,
26937            pauses: None,
26938        };
26939        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26940        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26941        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26942        assert_eq!(results[0].1.turns, 0);
26943        let saved = RunState::load_under(&run_id, &home).unwrap();
26944        let block = saved.resource_block.unwrap();
26945        assert!(matches!(
26946            block.cause,
26947            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
26948                if actual == &target
26949        ));
26950        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
26951        let mut task = crate::queue::Task::new(
26952            "build".into(),
26953            "build".into(),
26954            repo,
26955            crate::queue::Source::Human,
26956        );
26957        task.runs.push(run_id);
26958        task.hold_machine(Some(format!(
26959            "{}{}",
26960            crate::cache::RESOURCE_HOLD,
26961            block.description()
26962        )));
26963        queue.put(&mut task).unwrap();
26964        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
26965        let triage =
26966            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
26967        let pending = triage();
26968        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
26969        assert_eq!(
26970            queue.get(&task.id).unwrap().status,
26971            crate::queue::TaskStatus::Held
26972        );
26973        drop(target_lease);
26974        assert_eq!(triage().resumed, vec![task.id.clone()]);
26975        assert_eq!(
26976            queue.get(&task.id).unwrap().status,
26977            crate::queue::TaskStatus::Queued
26978        );
26979        assert!(crate::cache::in_use(&home, &shared));
26980    }
26981
26982    #[tokio::test]
26983    async fn verification_cache_wait_preserves_the_command_budget() {
26984        crate::run::pin_test_home();
26985        let tmp = tempfile::tempdir().unwrap();
26986        let cache = tmp.path().join("target");
26987        let guard = hold(&cache);
26988        let release = tokio::spawn(async move {
26989            tokio::time::sleep(Duration::from_millis(100)).await;
26990            guard.release();
26991        });
26992        let mut st = state(10);
26993        let budget = Duration::from_millis(50);
26994        let wait = repository_wait(&st, None);
26995        let (outcomes, _) = with_cache_lease(
26996            &mut st,
26997            Some(&cache),
26998            "gate",
26999            "gate",
27000            tmp.path(),
27001            "abc1234",
27002            budget,
27003            "test gate",
27004            &wait,
27005            |_, available| async move {
27006                assert_eq!(
27007                    available, budget,
27008                    "contention must not shorten verification"
27009                );
27010                (Vec::new(), false, Vec::new())
27011            },
27012        )
27013        .await
27014        .unwrap();
27015        release.await.unwrap();
27016        assert!(outcomes.is_empty(), "{outcomes:?}");
27017        assert!(
27018            st.events
27019                .iter()
27020                .any(|event| event.message.contains("waiting for"))
27021        );
27022        assert!(st.resource_wait.is_none());
27023        // The verification body no longer owns the lease after returning.
27024        hold(&cache).release();
27025    }
27026
27027    #[tokio::test]
27028    async fn verification_cache_wait_expires_without_starting_commands() {
27029        crate::run::pin_test_home();
27030        let tmp = tempfile::tempdir().unwrap();
27031        let cache = tmp.path().join("target");
27032        let _held = hold(&cache);
27033        let mut st = state(0);
27034        let wait = repository_wait(&st, None);
27035        let (outcomes, _) = with_cache_lease(
27036            &mut st,
27037            Some(&cache),
27038            "gate",
27039            "gate",
27040            tmp.path(),
27041            "abc1234",
27042            Duration::from_secs(60),
27043            "test gate",
27044            &wait,
27045            |_, _| async { panic!("commands must not start without the cache lease") },
27046        )
27047        .await
27048        .unwrap();
27049        assert_eq!(outcomes.len(), 1);
27050        assert!(outcomes[0].resource_blocked);
27051        assert!(st.resource_wait.is_none());
27052        assert!(matches!(
27053            st.resource_block.unwrap().cause,
27054            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
27055        ));
27056    }
27057
27058    #[tokio::test]
27059    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
27060        crate::run::pin_test_home();
27061        let tmp = tempfile::tempdir().unwrap();
27062        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
27063        let cache = tmp.path().join("cache");
27064        let mut state = state(21600);
27065        let wait = repository_wait(&state, None);
27066        let (outcomes, _) = with_cache_lease(
27067            &mut state,
27068            Some(&cache),
27069            "gate",
27070            "gate",
27071            tmp.path(),
27072            "head",
27073            Duration::from_secs(60),
27074            "gate",
27075            &wait,
27076            |_, _| async { panic!("freshness failure must not start verification") },
27077        )
27078        .await
27079        .unwrap();
27080        assert_eq!(outcomes.len(), 1);
27081        assert!(outcomes[0].resource_blocked);
27082        let block = state.resource_block.unwrap();
27083        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
27084        assert!(!block.description().contains("timed out"));
27085    }
27086
27087    #[tokio::test]
27088    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
27089        crate::run::pin_test_home();
27090        let tmp = tempfile::tempdir().unwrap();
27091        let cache = tmp.path().join("cache");
27092        let _held = hold(&cache);
27093        let mut state = state(21600);
27094        let pause = Pause::new();
27095        let interrupt = Pause::new();
27096        let cause = ParkCause::Operator;
27097        pause.park_for(cause.clone());
27098        let prompts = Prompts::default();
27099        let ctx = WaveCtx {
27100            run: "test",
27101            node: "fix",
27102            prompts: &prompts,
27103            cache: Some(&cache),
27104            round: None,
27105            carry_seats: false,
27106            pauses: Some((&pause, &interrupt)),
27107        };
27108        let result = wave(
27109            vec![job(
27110                sh("writer", "exit 99"),
27111                tmp.path(),
27112                Duration::from_secs(1),
27113            )],
27114            Arc::new(Semaphore::new(1)),
27115            &ctx,
27116            &mut state,
27117            0,
27118        )
27119        .await;
27120        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
27121        assert_eq!(result[0].1.turns, 0);
27122        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27123        assert_eq!(
27124            state.resource_block.unwrap().cause,
27125            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
27126        );
27127        assert!(state.active.is_empty());
27128    }
27129
27130    #[tokio::test]
27131    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
27132        crate::run::pin_test_home();
27133        let tmp = tempfile::tempdir().unwrap();
27134        let cache = tmp.path().join("target-a");
27135        let guard = hold(&cache);
27136        // Held for longer than the agent's whole 1s budget.
27137        tokio::spawn(async move {
27138            tokio::time::sleep(Duration::from_millis(1500)).await;
27139            guard.release();
27140        });
27141        let mut st = state(60);
27142        let results = run(
27143            vec![job(
27144                sh("alpha", "echo ok"),
27145                tmp.path(),
27146                Duration::from_secs(1),
27147            )],
27148            Arc::new(Semaphore::new(1)),
27149            Some(&cache),
27150            &mut st,
27151        )
27152        .await;
27153        assert!(
27154            matches!(results[0].2, AgentOutcome::Ok(_)),
27155            "the wait must not be charged to the agent"
27156        );
27157        assert!(st.resource_block.is_none());
27158        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27159        assert!(st.resource_wait.is_none() && st.active.is_empty());
27160    }
27161
27162    #[tokio::test]
27163    #[cfg(unix)]
27164    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
27165        use std::os::fd::AsRawFd as _;
27166        crate::run::pin_test_home();
27167        let tmp = tempfile::tempdir().unwrap();
27168        crate::git::git(tmp.path(), &["init"]).await.unwrap();
27169        let common = tmp.path().join(".git");
27170        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
27171        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
27172        assert_eq!(
27173            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
27174            0
27175        );
27176        let mut st = state(1);
27177        st.config.coordination = crate::config::test_coordination();
27178        let mut reader = job(
27179            sh("reader", "echo must-not-run"),
27180            tmp.path(),
27181            Duration::from_secs(30),
27182        );
27183        reader.allow_write = false;
27184        let results = run(
27185            vec![reader.clone()],
27186            Arc::new(Semaphore::new(1)),
27187            None,
27188            &mut st,
27189        )
27190        .await;
27191        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27192        assert_eq!(results[0].1.turns, 0);
27193        assert!(FailClass::of(&results[0].2).is_none());
27194        assert_eq!(
27195            st.resource_block.as_ref().unwrap().kind,
27196            "repository coordination"
27197        );
27198        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27199        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27200        drop(external);
27201        let editor = crate::repo_lock::SeatLease::for_checkout(
27202            tmp.path(),
27203            true,
27204            crate::config::test_coordination().as_ref(),
27205        )
27206        .await
27207        .unwrap();
27208        let pause = Pause::new();
27209        let interrupt = Pause::new();
27210        let prompts = Prompts::default();
27211        let ctx = WaveCtx {
27212            run: "r",
27213            node: "review",
27214            prompts: &prompts,
27215            cache: None,
27216            round: None,
27217            carry_seats: false,
27218            pauses: Some((&pause, &interrupt)),
27219        };
27220        let (results, ()) = tokio::join!(
27221            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
27222            async {
27223                tokio::time::sleep(Duration::from_millis(50)).await;
27224                pause.park();
27225            }
27226        );
27227        assert!(
27228            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
27229        );
27230        assert_eq!(results[0].1.turns, 0);
27231        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27232        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27233        drop(editor);
27234    }
27235
27236    #[tokio::test]
27237    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
27238        crate::run::pin_test_home();
27239        let tmp = tempfile::tempdir().unwrap();
27240        let cache = tmp.path().join("target-b");
27241        let _held = hold(&cache);
27242        let mut st = state(1);
27243        let results = run(
27244            vec![job(
27245                sh("alpha", "echo ok"),
27246                tmp.path(),
27247                Duration::from_secs(1),
27248            )],
27249            Arc::new(Semaphore::new(1)),
27250            Some(&cache),
27251            &mut st,
27252        )
27253        .await;
27254        let (_, seat, out) = &results[0];
27255        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
27256        assert!(wave_blocked(&results));
27257        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
27258        assert_eq!(seat.turns, 0, "nothing was asked");
27259        assert!(
27260            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
27261            "no agent was spawned"
27262        );
27263        assert!(FailClass::of(out).is_none(), "not a failure class");
27264        let block = st.resource_block.as_ref().expect("recorded for the resume");
27265        assert_eq!(block.kind, "shared build cache");
27266        assert!(matches!(
27267            block.cause,
27268            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
27269        ));
27270        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27271        assert!(st.active.is_empty());
27272    }
27273
27274    #[tokio::test]
27275    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
27276        crate::run::pin_test_home();
27277        let tmp = tempfile::tempdir().unwrap();
27278        let mut st = state(1);
27279        let results = run(
27280            vec![job(
27281                sh("alpha", "echo ok"),
27282                tmp.path(),
27283                Duration::from_secs(1),
27284            )],
27285            Arc::new(Semaphore::new(0)),
27286            None,
27287            &mut st,
27288        )
27289        .await;
27290        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27291        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
27292        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
27293    }
27294
27295    #[tokio::test]
27296    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
27297        crate::run::pin_test_home();
27298        let tmp = tempfile::tempdir().unwrap();
27299        let mut st = state(60);
27300        let results = run(
27301            vec![job(
27302                sh("alpha", "sleep 30"),
27303                tmp.path(),
27304                Duration::from_secs(1),
27305            )],
27306            Arc::new(Semaphore::new(1)),
27307            None,
27308            &mut st,
27309        )
27310        .await;
27311        let out = &results[0].2;
27312        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
27313        let class = FailClass::of(out).expect("a failure");
27314        assert_eq!(class, FailClass::Timeout);
27315        assert!(should_hand_over(None, &class), "existing handover policy");
27316        assert!(st.resource_block.is_none());
27317    }
27318}
27319
27320/// A fold acts on the record it locked, and on nothing else.
27321#[cfg(test)]
27322mod fold_record_tests {
27323    use super::*;
27324
27325    fn refusal(error: &anyhow::Error) -> Option<&FoldRefusal> {
27326        error.downcast_ref::<FoldRefusal>()
27327    }
27328
27329    /// A deletion that lands after the fold's look at the record and before its
27330    /// locks must neither be undone (the fold's lock files bring the directory
27331    /// back, its stale copy the record) nor be acted on.
27332    #[tokio::test]
27333    async fn a_run_deleted_between_the_look_and_the_locks_is_refused_and_not_recreated() {
27334        let dir = tempfile::tempdir().unwrap();
27335        let home = dir.path();
27336        let repo = home.join("repo");
27337        std::fs::create_dir_all(&repo).unwrap();
27338        crate::clean::tests::init_repo(&repo);
27339        let (id, worktree) = crate::clean::tests::due_run_with_winner_worktree(
27340            &home.join("runs"),
27341            &home.join("wt"),
27342            &repo,
27343            "20260801-000000-y001",
27344            RunStatus::Superseded,
27345        )
27346        .await;
27347        let mut state = RunState::load_under(&id, home).unwrap();
27348        BEFORE_LOCKS.with(|hook| {
27349            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
27350                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
27351            }));
27352        });
27353
27354        let error = fold_run(&mut state, true, home).await.unwrap_err();
27355        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27356        assert!(
27357            !home.join("runs").join(&id).exists(),
27358            "the fold's own lock files must not bring a deleted run back"
27359        );
27360        assert!(worktree.exists(), "nothing of a deleted run is removed");
27361    }
27362
27363    /// The caller's `state` is only a first look: a record that was never
27364    /// saved is not a record the fold may write.
27365    #[tokio::test]
27366    async fn a_record_that_was_never_saved_is_not_folded_or_written() {
27367        let dir = tempfile::tempdir().unwrap();
27368        let home = dir.path();
27369        let mut state = RunState::new(
27370            home.join("repo"),
27371            "main".to_owned(),
27372            "abc".to_owned(),
27373            "fixture".to_owned(),
27374            crate::config::Config::default(),
27375        );
27376        state.status = RunStatus::Superseded;
27377        let error = fold_run(&mut state, true, home).await.unwrap_err();
27378        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27379        assert!(
27380            !home.join("runs").exists(),
27381            "nothing was created: {error:#}"
27382        );
27383    }
27384
27385    /// A refusal changes nothing. A directory whose record is another run's is
27386    /// not the run that was locked: every entry point answers `record gone`,
27387    /// the other run's worktree is left alone, the record stays as it was, and
27388    /// the lock files are not unlinked (an unlinked lock file lets the next
27389    /// caller lock a different inode - `pr_head::owner_lock`).
27390    #[tokio::test]
27391    async fn a_record_naming_another_run_is_refused_by_every_entry_point_and_nothing_is_touched() {
27392        let dir = tempfile::tempdir().unwrap();
27393        let home = dir.path();
27394        let repo = home.join("repo");
27395        std::fs::create_dir_all(&repo).unwrap();
27396        crate::clean::tests::init_repo(&repo);
27397        let runs = home.join("runs");
27398        let (id, own) = crate::clean::tests::due_run_with_winner_worktree(
27399            &runs,
27400            &home.join("wt"),
27401            &repo,
27402            "20260801-000000-y101",
27403            RunStatus::Superseded,
27404        )
27405        .await;
27406        let (other, theirs) = crate::clean::tests::due_run_with_winner_worktree(
27407            &runs,
27408            &home.join("wt"),
27409            &repo,
27410            "20260801-000000-y102",
27411            RunStatus::Superseded,
27412        )
27413        .await;
27414        let first_look = RunState::load_under(&id, home).unwrap();
27415        let record = runs.join(&id).join("run.json");
27416        std::fs::copy(runs.join(&other).join("run.json"), &record).unwrap();
27417        let before = std::fs::read(&record).unwrap();
27418        for entry in ["fold_run", "fold_run_when", "override"] {
27419            let mut state = first_look.clone();
27420            let result = match entry {
27421                "fold_run" => fold_run(&mut state, true, home).await,
27422                "fold_run_when" => fold_run_when(&mut state, home, &|_| Ok(true)).await,
27423                _ => fold_run_overriding_recovery_retention(&mut state, true, home).await,
27424            };
27425            let error = result.unwrap_err();
27426            assert_eq!(
27427                refusal(&error),
27428                Some(&FoldRefusal::RecordGone),
27429                "{entry}: {error:#}"
27430            );
27431            assert!(own.exists() && theirs.exists(), "{entry}");
27432            assert_eq!(std::fs::read(&record).unwrap(), before, "{entry}");
27433            for lock in ["pr-owner.lock", "driver.lock"] {
27434                assert!(
27435                    runs.join(&id).join(lock).exists(),
27436                    "{entry}: {lock} stays in place"
27437                );
27438            }
27439            assert!(
27440                !RunState::load_under(&other, home).unwrap().candidates[0].folded,
27441                "{entry}: the other run was not folded"
27442            );
27443        }
27444    }
27445
27446    /// The refusal is added to the error underneath, never substituted for it:
27447    /// callers match `ResourceBlocked` for a coordination wait.
27448    #[test]
27449    fn a_live_refusal_keeps_the_error_callers_match() {
27450        let blocked = anyhow::Error::new(crate::repo_lock::ResourceBlocked(
27451            "repository coordination".into(),
27452        ));
27453        let error = live_or(blocked);
27454        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
27455        assert!(matches!(refusal(&error), Some(FoldRefusal::Live(_))));
27456        // Anything that is not a held lock is passed through untouched.
27457        let other = live_or(anyhow::anyhow!("git exploded"));
27458        assert!(refusal(&other).is_none());
27459    }
27460
27461    /// Contention is `live`, a lock call that failed for another reason is a
27462    /// failure of its own (`failed`), missing evidence is an incomplete proof.
27463    #[test]
27464    fn source_verification_failures_are_told_apart() {
27465        let contended = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::WouldBlock))
27466            .context("Cargo build is active");
27467        let error = source_proof_failure(contended);
27468        assert!(
27469            matches!(refusal(&error), Some(FoldRefusal::Live(_))),
27470            "{error:#}"
27471        );
27472
27473        let failed = anyhow::Error::new(crate::retention::LockCallFailed::new(
27474            "Cargo lock target/debug/.cargo-lock".into(),
27475            std::io::Error::from(std::io::ErrorKind::Interrupted),
27476        ));
27477        let error = source_proof_failure(failed);
27478        assert!(refusal(&error).is_none(), "{error:#}");
27479        assert!(
27480            error
27481                .chain()
27482                .any(|cause| cause.is::<crate::retention::LockCallFailed>())
27483        );
27484
27485        let error = source_proof_failure(anyhow::anyhow!("Cargo residue changed"));
27486        assert!(matches!(
27487            refusal(&error),
27488            Some(FoldRefusal::ProofIncomplete(_))
27489        ));
27490    }
27491
27492    /// A run directory that is not there is `record gone` at the lock, not
27493    /// something to create for the lock's sake.
27494    #[test]
27495    fn a_missing_run_directory_at_the_lock_is_record_gone() {
27496        let dir = tempfile::tempdir().unwrap();
27497        let error = crate::pr_head::owner_lock(dir.path(), "20260801-000000-y103")
27498            .map(drop)
27499            .map_err(lock_refusal)
27500            .unwrap_err();
27501        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27502        assert!(!dir.path().join("runs").exists());
27503    }
27504}