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                    }
10482                    // A retry or resume of a run whose branch already has an
10483                    // open pull request adopts it rather than failing on a
10484                    // duplicate. Only this winner branch into this base:
10485                    // `branch_for` derives the name from the run id, so a
10486                    // different run's pull request never matches.
10487                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10488                    let out = match pr_merge_plan(found) {
10489                        PrPlan::Create => {
10490                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10491                                .await
10492                        }
10493                        PrPlan::Adopt { url, title } => {
10494                            self.state
10495                                .event("merge", format!("Pr: adopted open pull request {url}"));
10496                            if self.state.explicit_github_text_selection() {
10497                                // An explicit publication selection applies the prepared
10498                                // payload; acceptance alone is not publication proof.
10499                                land::set_pr_text_verbatim(
10500                                    &winner.worktree,
10501                                    &url,
10502                                    &pr.title,
10503                                    &pr.body,
10504                                )
10505                                .await
10506                                .map(|()| url)
10507                            } else {
10508                                if title != pr.title
10509                                    && (!is_review_run(&self.state)
10510                                        || leaked
10511                                            .as_deref()
10512                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10513                                    && let Err(e) =
10514                                        if self.state.github_text.as_ref().is_some_and(|g| {
10515                                            g.resolved
10516                                                && g.title
10517                                                && g.choice == Some(GithubTextChoice::Original)
10518                                        }) {
10519                                            // The owner chose to post this title unmodified.
10520                                            land::set_pr_title_verbatim(
10521                                                &winner.worktree,
10522                                                &url,
10523                                                &pr.title,
10524                                            )
10525                                            .await
10526                                        } else {
10527                                            land::set_pr_title(
10528                                                &mut self.state,
10529                                                &winner.worktree,
10530                                                &url,
10531                                                &pr.title,
10532                                            )
10533                                            .await
10534                                        }
10535                                {
10536                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10537                                    self.state
10538                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10539                                }
10540                                Ok(url)
10541                            }
10542                        }
10543                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10544                    };
10545                    match out {
10546                        Ok(url) => MergeOutcome {
10547                            mode,
10548                            ok: true,
10549                            detail: url,
10550                            empty: false,
10551                        },
10552                        Err(e) => MergeOutcome {
10553                            mode,
10554                            ok: false,
10555                            detail: e.to_string(),
10556                            empty: false,
10557                        },
10558                    }
10559                }
10560            }
10561        };
10562
10563        self.state.status = match (mode, outcome.ok) {
10564            (MergeMode::None, _) => RunStatus::Ready,
10565            (_, true) if outcome.empty => RunStatus::Ready,
10566            (MergeMode::Pr, true) => RunStatus::Ready,
10567            (_, true) => RunStatus::Merged,
10568            (_, false) => RunStatus::Blocked,
10569        };
10570        self.state.event(
10571            "merge",
10572            format!(
10573                "{:?}: {}",
10574                mode,
10575                outcome.detail.lines().next().unwrap_or("")
10576            ),
10577        );
10578        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10579            self.state.record_github_text_publication(&outcome.detail);
10580        }
10581        self.state.merge = Some(outcome);
10582        self.state.save()?;
10583
10584        // The PR is open and the run would historically stop here, leaving the
10585        // operator to watch checks, feed review comments back to a fixer, and
10586        // merge. That was done by hand six times in one session before this
10587        // existed. Opt-in, because merging is the one irreversible thing magi
10588        // can do to a repository.
10589        if self.state.config.graph.land
10590            && mode == MergeMode::Pr
10591            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10592        {
10593            self.run_land().await?;
10594        }
10595        // `run_land` may have left `status` at `Landing` - still waiting on
10596        // CI or the owner's approval, not actually settled - so this has to
10597        // read whatever `status` ended up as here, not the `Merged` this
10598        // function set a few lines up.
10599        self.settle_questions();
10600        Ok(())
10601    }
10602
10603    /// Enter `land`.
10604    ///
10605    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10606    /// a resumed run's re-entry. `land::land` itself is what serialises the
10607    /// two git-mutating moments inside the loop — the rebase push and
10608    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10609    /// to hold a lock across the whole call, and doing so would serialise
10610    /// this run's CI wait against a *different* run's land-approval resume
10611    /// in the same repository, which is exactly the "must not wait on
10612    /// another task" property the daemon's slot-freeing exists to give.
10613    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10614        Box::pin(self.run_land_inner())
10615    }
10616
10617    async fn run_land_inner(&mut self) -> Result<()> {
10618        crate::pr_head::ensure_owner(&self.state)?;
10619        let url = self
10620            .state
10621            .pr
10622            .as_ref()
10623            .map(|pr| pr.url.clone())
10624            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10625            .unwrap_or_default();
10626        let url = url.lines().next().unwrap_or("").trim().to_owned();
10627        if !url.starts_with("http") {
10628            return Ok(());
10629        }
10630        // A land failure is not a lost run: the work is on a branch and the
10631        // pull request is open, which is exactly where a human takes over.
10632        loop {
10633            match land::land(&mut self.state, &url).await {
10634                Ok(_)
10635                    if self
10636                        .state
10637                        .merge_repairs
10638                        .last()
10639                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10640                {
10641                    if self.repair_merge_review().await? {
10642                        continue;
10643                    }
10644                }
10645                Ok(_) if self.state.resource_block.is_some() => {
10646                    return self.stop_for_resource();
10647                }
10648                Ok(pr) if self.state.parked => {
10649                    // `land` already saved the parked marker; nothing here
10650                    // overrides `status` back to a terminal value while an
10651                    // approval is still outstanding.
10652                    let _ = pr;
10653                }
10654                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10655                    self.state.status = RunStatus::Superseded;
10656                    self.state.save()?;
10657                }
10658                Ok(pr) => {
10659                    self.state.status = match pr.state {
10660                        land::PrLifecycle::Merged => RunStatus::Merged,
10661                        _ => RunStatus::Blocked,
10662                    };
10663                    // Downstream of a confirmed merge only - see
10664                    // `bump::should_release_bump`'s own doc for why this one
10665                    // check covers all three of `land`'s success paths.
10666                    // Best-effort: the run already landed, so a failure here
10667                    // (the decision call, `gh`, `cargo`) is recorded and never
10668                    // turns a landed run into a failed one.
10669                    if bump::should_release_bump(self.state.status)
10670                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10671                    {
10672                        // The event is the run's own record. Not-eligible cases
10673                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10674                        // `Err` is a bump that was tried and failed:
10675                        // `after_merge` itself raises the operator notice for
10676                        // that, whether or not a release PR exists yet.
10677                        self.state
10678                            .event("bump", format!("release bump skipped: {e:#}"));
10679                    }
10680                    // Independent of the bump, and best-effort in the same way:
10681                    // findings the merge left open become follow-up tasks.
10682                    if self.state.status == RunStatus::Merged {
10683                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10684                    }
10685                    self.state.save()?;
10686                }
10687                Err(e) => {
10688                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10689                        return Err(e);
10690                    }
10691                    self.state.status = RunStatus::Blocked;
10692                    self.state.event("land", format!("gave up: {e}"));
10693                    self.state.save()?;
10694                }
10695            }
10696            break;
10697        }
10698        Ok(())
10699    }
10700
10701    /// One repair cycle stays under the existing driver/task claim. An
10702    /// interrupted fixer is rolled back and held rather than run twice.
10703    async fn repair_merge_review(&mut self) -> Result<bool> {
10704        use crate::run::MergeRepairPhase as Phase;
10705        crate::pr_head::ensure_owner(&self.state)?;
10706        let i = self.state.merge_repairs.len() - 1;
10707        let request = self.state.merge_repairs[i].clone();
10708        if request.phase == Phase::Fixing {
10709            let restored = match self.state.winner().cloned() {
10710                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10711                None => Err(anyhow::anyhow!("repair has no winning branch")),
10712            };
10713            let why = match restored {
10714                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10715                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10716                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10717            };
10718            self.hold_merge_repair(i, why)?;
10719            return Ok(false);
10720        }
10721        // A completed repair gate is a publication checkpoint. On reentry,
10722        // reject external changes before the ordinary gate path can replace
10723        // that evidence by verifying a new head. Requested repairs still
10724        // start their own review generation below.
10725        if request.phase == Phase::Reviewing && self.state.gate_ran {
10726            let winner = self
10727                .state
10728                .winner()
10729                .context("repair has no winning branch")?;
10730            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10731            if self.state.gate_head.as_deref() != Some(head.as_str())
10732                || !git::is_clean(&winner.worktree).await?
10733            {
10734                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())?;
10735                return Ok(false);
10736            }
10737        }
10738        let failure = if i >= self.state.config.graph.land_rounds
10739            || self.state.config.graph.review_rounds == 0
10740        {
10741            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10742        } else {
10743            None
10744        };
10745        if let Some(why) = failure {
10746            self.hold_merge_repair(i, why)?;
10747            return Ok(false);
10748        }
10749        if request.phase == Phase::Requested {
10750            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10751                Ok(pr) => pr,
10752                Err(e) => {
10753                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10754                    return Ok(false);
10755                }
10756            };
10757            self.state.merge_repairs[i].phase = Phase::Fixing;
10758            self.state.land_approval = None;
10759            self.state.land_armed_head = None;
10760            self.state.save()?;
10761            let reason = land::merge_repair_reason(&self.state, &request)?;
10762            let budget = self.state.config.graph.land_rounds;
10763            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10764            match result {
10765                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10766                Ok(land::Fixed::Deferred) => {
10767                    // An unavailable fixer did not spend this repair request.
10768                    // Restore partial fallback work before retrying it, as for
10769                    // an interrupted repair, without closing the request.
10770                    let worktree = self
10771                        .state
10772                        .winner()
10773                        .context("repair has no winning branch")?
10774                        .worktree
10775                        .clone();
10776                    self.graft_restore(&worktree, &request.head).await?;
10777                    self.state.merge_repairs[i].phase = Phase::Requested;
10778                    self.stop_for_resource()?;
10779                    return Ok(false);
10780                }
10781                Ok(land::Fixed::Failed(why)) => {
10782                    self.hold_merge_repair(
10783                        i,
10784                        format!(
10785                            "repair failed: {why}; inspect the branch and run an explicit review"
10786                        ),
10787                    )?;
10788                    return Ok(false);
10789                }
10790                Err(e) => {
10791                    self.hold_merge_repair(
10792                        i,
10793                        format!(
10794                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10795                        ),
10796                    )?;
10797                    return Ok(false);
10798                }
10799            }
10800            // Even no change gets a real new reviewer wave. The previous
10801            // evidence remains in the request; a former clean/concluded round
10802            // cannot short-circuit the new review or gate.
10803            self.begin_merge_repair_review(i)?;
10804        }
10805        self.review_loop().await?;
10806        self.gate().await?;
10807        if self.resource_halt()? || self.state.parked {
10808            return Ok(false);
10809        }
10810        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10811            != Some(RunStatus::Gating)
10812            || !self.state.gate_allows_progress()
10813        {
10814            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10815            return Ok(false);
10816        }
10817        // Review and gate may have added commits after the initial repair.
10818        // Publish exactly their final head to the existing PR, with a lease.
10819        let winner = self
10820            .state
10821            .winner()
10822            .cloned()
10823            .context("repair has no winning branch")?;
10824        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10825        if self.state.gate_head.as_deref() != Some(after.as_str())
10826            || !git::is_clean(&winner.worktree).await?
10827        {
10828            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())?;
10829            return Ok(false);
10830        }
10831        let expected = self
10832            .state
10833            .pr_pushed_head
10834            .as_deref()
10835            .unwrap_or(&request.head)
10836            .to_owned();
10837        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10838        // Push the checked commit itself: a local ref moving after the check
10839        // must not change which commit the forge receives.
10840        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10841            return Ok(false);
10842        }
10843        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10844        let refspec = format!("{after}:refs/heads/{public}");
10845        // Saved before the push: lease, verified commit and branch. A forge
10846        // that still shows the leased head afterwards is then recognisably
10847        // this run's own lagging view, not someone else's push.
10848        let publication = crate::run::PrPublication {
10849            previous: expected.clone(),
10850            head: after.clone(),
10851            branch: public.clone(),
10852        };
10853        let already_published =
10854            land::repair_publication_observed(&self.state, &publication).await?;
10855        self.state.pr_publication = Some(publication);
10856        self.state.save()?;
10857        if !already_published {
10858            let push = git::git_raw(
10859                &winner.worktree,
10860                &["push", &lease, &self.state.config.merge.remote, &refspec],
10861            )
10862            .await;
10863            match push {
10864                Ok(out) if out.ok() => {}
10865                Ok(out) => {
10866                    self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10867                    return Ok(false);
10868                }
10869                Err(e) => {
10870                    self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10871                    return Ok(false);
10872                }
10873            }
10874        }
10875        self.state.pr_pushed_head = Some(after);
10876        self.state.merge_repairs[i].phase = Phase::Complete;
10877        self.state.status = RunStatus::Landing;
10878        self.state.event(
10879            "repair",
10880            "new review and gate completed; fresh owner merge decision required",
10881        );
10882        self.state.save()?;
10883        Ok(true)
10884    }
10885
10886    fn merge_repair_artifacts(&self) -> PathBuf {
10887        let artifacts = agent::artifacts_dir(&self.state.dir());
10888        match self
10889            .state
10890            .merge_repairs
10891            .last()
10892            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10893        {
10894            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10895            None => artifacts,
10896        }
10897    }
10898
10899    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10900        if let Some(e2e) = self.state.head_e2e.take() {
10901            self.state
10902                .verification_history
10903                .push(crate::run::VerificationEvidence {
10904                    superseded_by: None,
10905                    archived_at: Some(Timestamp::now()),
10906                    fixes_spent: Some(self.state.gate_fixes.len()),
10907                    gate_head: None,
10908                    gate_ran: false,
10909                    gate: Vec::new(),
10910                    e2e: Some(e2e),
10911                });
10912        }
10913        self.state.reviews.clear();
10914        self.state.gate.clear();
10915        self.state.gate_ran = false;
10916        self.state.gate_head = None;
10917        self.state.gate_fixes.clear();
10918        self.state.gate_repair_e2e = None;
10919        self.state.pre_gate.clear();
10920        self.state.pre_gate_commit = None;
10921        self.state.contested_handoff = None;
10922        self.state.land_reruns = None;
10923        self.state.land_approval = None;
10924        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10925        self.state.status = RunStatus::Reviewing;
10926        self.state.save()
10927    }
10928
10929    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10930        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10931        self.state.merge_repairs[index].failure = Some(why.clone());
10932        self.state.status = RunStatus::Blocked;
10933        self.state.event("repair", why);
10934        self.state.save()
10935    }
10936
10937    // -------------------------------------------------------------- helpers
10938
10939    /// Fetch or create a seat, keeping its conversation across nodes.
10940    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10941        if let Some(existing) = self.state.seats.get(key)
10942            && existing.agent == agent
10943        {
10944            return existing.clone();
10945        }
10946        // A seat that changes agent mints its session id from the agent too,
10947        // like a handover: the old agent's uuid is already taken by the CLI.
10948        let fresh = if self.state.seats.contains_key(key) {
10949            handover_seat(key, agent, self.state.next_seat_seed())
10950        } else {
10951            SeatState::new(key, agent, self.state.seed)
10952        };
10953        self.state.seats.insert(key.to_owned(), fresh.clone());
10954        fresh
10955    }
10956
10957    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10958    /// seat to another roster agent, in which case that agent. Nodes that
10959    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10960    /// reconsideration) must keep talking to whoever answered it, not slip
10961    /// back to the agent that failed it.
10962    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10963        match self.state.seats.get(key) {
10964            Some(s) if s.agent != spec.id => {
10965                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10966            }
10967            _ => spec,
10968        }
10969    }
10970
10971    /// A candidate rendered for judging, with the leak policy applied.
10972    fn view(&self, c: &Candidate) -> CandidateView {
10973        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10974            .unwrap_or_default();
10975        let (patch, _) = blind::sanitize_patch(
10976            &format!("candidate {} patch", c.label),
10977            &raw,
10978            &self.state.config.blind,
10979        );
10980        CandidateView {
10981            label: c.label,
10982            branch: c.branch.clone(),
10983            summary: c.summary.clone(),
10984            stat: c.stat.clone(),
10985            patch,
10986        }
10987    }
10988
10989    /// The full candidate set as prompt text, for seats with no live session.
10990    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10991        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10992        prompt::judge(
10993            "(see above)",
10994            &views,
10995            self.roles.judges.len(),
10996            base_short,
10997            "en",
10998        )
10999    }
11000
11001    /// The final-vote prompt with everything a seat that has no session of its
11002    /// own needs: the candidates, the seat's own ranking and reasons, and the
11003    /// anonymised deliberation it took part in (only when there was one, so a
11004    /// handed-over seat never sees more than the seat it replaces did). The
11005    /// `Final vote` heading stays first.
11006    fn vote_prompt_full(
11007        &self,
11008        j: usize,
11009        labels: &[char],
11010        language: &str,
11011        candidates: &[Candidate],
11012        base_short: &str,
11013    ) -> String {
11014        let mut text = format!(
11015            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
11016            prompt::final_vote(labels, language),
11017            self.state.instruction,
11018            self.candidate_block(candidates, base_short)
11019        );
11020        if let Some(own) = self
11021            .state
11022            .judgements
11023            .get(j)
11024            .filter(|r| !r.ranking.is_empty())
11025        {
11026            let reasons = own
11027                .reasons
11028                .iter()
11029                .map(|(k, v)| format!("- {k}: {v}"))
11030                .collect::<Vec<_>>()
11031                .join("\n");
11032            text.push_str(&format!(
11033                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
11034                own.ranking.iter().collect::<String>(),
11035                if reasons.is_empty() {
11036                    ""
11037                } else {
11038                    ", because:\n"
11039                }
11040            ));
11041        }
11042        if !self.state.deliberation.is_empty() {
11043            text.push_str("\n# What was argued before this vote\n");
11044            for t in self.transcript(&[], j) {
11045                text.push_str(&format!(
11046                    "\n## {}{}\n\n{}\n",
11047                    t.who,
11048                    if t.is_self { " (you)" } else { "" },
11049                    t.body.trim()
11050                ));
11051            }
11052        }
11053        text
11054    }
11055
11056    /// Anonymised transcript for judge `self_idx`.
11057    ///
11058    /// The initial rankings are always the opening statements. Seeding them
11059    /// only when no turn had been taken yet meant every judge after the first
11060    /// argued against a single voice instead of against the actual split — the
11061    /// disagreement is the information, so it is always on the table.
11062    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
11063        let mut turns = Vec::new();
11064        for j in &self.state.judgements {
11065            if j.ranking.is_empty() {
11066                continue;
11067            }
11068            let reasons = j
11069                .reasons
11070                .iter()
11071                .map(|(k, v)| format!("- {k}: {v}"))
11072                .collect::<Vec<_>>()
11073                .join("\n");
11074            turns.push(Turn {
11075                who: format!("Judge {} (opening ranking)", j.judge),
11076                is_self: j.judge == self_idx + 1,
11077                body: format!(
11078                    "Ranked {}{}{reasons}",
11079                    j.ranking.iter().collect::<String>(),
11080                    if reasons.is_empty() {
11081                        ""
11082                    } else {
11083                        ", because:\n"
11084                    }
11085                ),
11086            });
11087        }
11088        for t in self
11089            .state
11090            .deliberation
11091            .iter()
11092            .flat_map(|r| r.turns.iter())
11093            .chain(current)
11094        {
11095            turns.push(Turn {
11096                who: format!("Judge {}", t.judge),
11097                is_self: t.judge == self_idx + 1,
11098                body: t.body.clone(),
11099            });
11100        }
11101        turns
11102    }
11103}
11104
11105/// Does this seat still hold the context a follow-up prompt would rely on?
11106fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
11107    agent::has_session(spec.kind, seat, sessions)
11108}
11109
11110/// The next entry in `roster` after `start`, never wrapping back to the
11111/// front, whose id is not in `tried` yet.
11112///
11113/// Starts one past `start` rather than at the front of `roster`: `start` is
11114/// the seat's own original position, and a seat whose candidate slot already
11115/// sits on the roster's second entry must fall through to the third next, not
11116/// restart at the first — which is very likely a different candidate's own
11117/// agent already. Never wraps back past `start`, for the same reason: an
11118/// entry earlier in the roster than the seat's own position is almost
11119/// certainly some *other* candidate slot's own agent, and once the tail of
11120/// the roster is exhausted there are no more untried agents for *this* seat
11121/// to fall through to — the caller's fallback chain ends there, exactly as
11122/// "no further untried agents remain in the list for that seat" asks for.
11123///
11124/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
11125/// the same id twice (an operator's `roles.implementers` typo, or a
11126/// `[[agents]]` list reused across roles) must not let
11127/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
11128/// over `roster` either finds an untried id or runs out, so this always
11129/// terminates regardless of duplicates.
11130fn next_untried_in_roster<'a>(
11131    roster: &'a [AgentSpec],
11132    start: usize,
11133    tried: &BTreeSet<String>,
11134) -> Option<&'a AgentSpec> {
11135    roster
11136        .get(start + 1..)?
11137        .iter()
11138        .find(|s| !tried.contains(&s.id))
11139}
11140
11141/// The successor for a seat, shared by all four seat kinds (implement, judge,
11142/// review, advise). `others` holds the ids that *currently* occupy the other
11143/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
11144/// sees them), so roster entries beyond the seat count act as spares: a failed
11145/// seat goes to an agent no other seat holds whenever the roster permits.
11146///
11147/// `carried` is `Some` only for the review loop's carried failure history.
11148/// Order: (1) forward from `start`, never wrapping, untried, not a carried
11149/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
11150/// whole roster: untried and not another seat's occupant; (3) the plain walk
11151/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
11152/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
11153/// a better outcome than an empty seat, and it keeps the answer to "is there
11154/// a successor at all" exactly what it was before occupants were considered,
11155/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
11156/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
11157/// carried failure is a cheaper bet than doubling an agent on the panel, and
11158/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
11159/// the same round are handled one at a time, so a seat later in the batch
11160/// sees an earlier one's new occupant but not yet its own freed agent.
11161fn pick_successor<'a>(
11162    roster: &'a [AgentSpec],
11163    start: usize,
11164    tried: &BTreeSet<String>,
11165    carried: Option<&BTreeSet<String>>,
11166    others: &BTreeSet<String>,
11167) -> Option<&'a AgentSpec> {
11168    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
11169    roster
11170        .get(start + 1..)
11171        .and_then(|tail| {
11172            tail.iter()
11173                .filter(free)
11174                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
11175        })
11176        .or_else(|| {
11177            carried
11178                .is_some()
11179                .then(|| roster.iter().find(free))
11180                .flatten()
11181        })
11182        .or_else(|| match carried {
11183            Some(c) => next_for_seat(roster, start, tried, c),
11184            None => next_untried_in_roster(roster, start, tried),
11185        })
11186}
11187
11188/// The next agent for a seat that carries its failure history across rounds
11189/// (the review loop). `round_tried` is this round's own bound and starts
11190/// empty every round; `carried_failed` only decides priority.
11191///
11192/// First: an id walking forward from `start`, never wrapping, that is neither
11193/// tried this round nor failed in an earlier one. Only when that is exhausted
11194/// does it rescue: the first roster id (in roster order, so this one *does*
11195/// look before `start`) not yet tried this round, which is by then a carried
11196/// failure. Each id is rescued at most once per round, so it cannot loop.
11197fn next_for_seat<'a>(
11198    roster: &'a [AgentSpec],
11199    start: usize,
11200    round_tried: &BTreeSet<String>,
11201    carried_failed: &BTreeSet<String>,
11202) -> Option<&'a AgentSpec> {
11203    roster
11204        .get(start + 1..)?
11205        .iter()
11206        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
11207        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
11208}
11209
11210/// Where a reviewer seat starts a round: the agent that last answered it when
11211/// it is still on the roster and not marked failed, else the spec's own agent
11212/// unless it failed, else the next roster agent that has not failed, else the
11213/// spec's own agent again (the whole roster failed). Ids no longer on the
11214/// roster are ignored. An empty roster has no handover, so the spec stands.
11215fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
11216    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
11217        return spec;
11218    };
11219    let ok = |id: &str| !h.failed.contains(id);
11220    if let Some(last) = h.last_ok.as_deref()
11221        && ok(last)
11222        && let Some(s) = roster.iter().find(|s| s.id == last)
11223    {
11224        return s.clone();
11225    }
11226    if ok(&spec.id) {
11227        return spec;
11228    }
11229    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
11230    roster
11231        .get(from + 1..)
11232        .into_iter()
11233        .flatten()
11234        .chain(roster.iter())
11235        .find(|s| ok(&s.id))
11236        .cloned()
11237        .unwrap_or(spec)
11238}
11239
11240/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
11241/// seed so a CLI that mints its session id up front (`--session-id`) never
11242/// reuses the uuid the previous agent already opened under the same seat key.
11243pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
11244    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
11245}
11246
11247/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
11248/// so the classifier below and the code that builds the message cannot drift.
11249const TIMED_OUT: &str = "timed out";
11250
11251impl FailClass {
11252    /// `None` for an answer; otherwise how the turn failed.
11253    fn of(out: &AgentOutcome) -> Option<Self> {
11254        match out {
11255            AgentOutcome::Ok(_) => None,
11256            AgentOutcome::Quota(_) => Some(Self::Quota),
11257            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
11258            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
11259            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
11260            // Not a failure of the agent. Callers check for it first; `None`
11261            // here means "no class to hand over on".
11262            AgentOutcome::ResourceBlocked(_) => None,
11263        }
11264    }
11265
11266    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11267    fn stem_word(&self) -> &'static str {
11268        match self {
11269            Self::Quota => "quota",
11270            _ => "handover",
11271        }
11272    }
11273}
11274
11275/// The message's first line with its variable parts removed — digit runs and
11276/// path-like tokens — so "exit code 2" and "exit code 7" read
11277/// as one kind of failure.
11278fn failure_signature(msg: &str) -> String {
11279    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11280    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11281    // the historical machine key while the process diagnosis uses readable prose.
11282    if let Some(code) = line
11283        .strip_prefix("process exited with no usable output (exit code ")
11284        .and_then(|s| s.strip_suffix(')'))
11285        .and_then(|s| s.parse::<i32>().ok())
11286    {
11287        line = format!("exited with some({code}) and no usable output");
11288    } else if matches!(
11289        line.as_str(),
11290        "process exited with no usable output (no exit code reported)"
11291            | "process exited with no usable output (exit code unavailable)"
11292    ) {
11293        line = "exited with none and no usable output".to_owned();
11294    }
11295    let mut out = Vec::new();
11296    for word in line.split_whitespace() {
11297        if word.contains('/') || word.contains('\\') {
11298            out.push("<path>".to_owned());
11299            continue;
11300        }
11301        let mut w = String::new();
11302        let mut in_digits = false;
11303        for c in word.chars() {
11304            if c.is_ascii_digit() {
11305                if !in_digits {
11306                    w.push('#');
11307                }
11308                in_digits = true;
11309            } else {
11310                in_digits = false;
11311                w.push(c);
11312            }
11313        }
11314        out.push(w);
11315    }
11316    out.join(" ").chars().take(120).collect()
11317}
11318
11319/// Whether a seat that just failed with `cur` may go to the next roster agent.
11320/// A quota or a timeout always may. Any other failure may not when the agent
11321/// before it failed the same way: an error the prompt causes would otherwise
11322/// walk the whole roster. `prev` is the class of the immediately preceding
11323/// agent's failure, so a quota or timeout in between breaks the run of
11324/// identical failures by itself.
11325fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11326    match cur {
11327        FailClass::Quota | FailClass::Timeout => true,
11328        FailClass::Other(_) => prev != Some(cur),
11329    }
11330}
11331
11332/// A short human reason for a failed outcome, for the handover record.
11333fn fail_reason(out: &AgentOutcome) -> String {
11334    match out {
11335        AgentOutcome::Ok(_) => String::new(),
11336        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11337        AgentOutcome::Dropped(o) => format!(
11338            "the CLI dropped the stream ({})",
11339            o.dropped
11340                .as_ref()
11341                .map(|d| d.why.as_str())
11342                .unwrap_or("it ended without delivering its answer")
11343        ),
11344        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11345            e.lines().next().unwrap_or("").chars().take(160).collect()
11346        }
11347    }
11348}
11349
11350/// Note one handover in the run: the structured record and, in the timeline,
11351/// the sentence a person reads. A quota keeps the wording it always had.
11352pub(crate) fn record_handover(
11353    state: &mut RunState,
11354    node: &str,
11355    seat: &str,
11356    from: &str,
11357    to: &str,
11358    class: &FailClass,
11359    reason: &str,
11360) {
11361    let message = if *class == FailClass::Quota {
11362        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11363    } else {
11364        format!("{seat}: handed over {from} -> {to} ({reason})")
11365    };
11366    state.event(node, message);
11367    state.handovers.push(Handover {
11368        at: Timestamp::now(),
11369        node: node.to_owned(),
11370        seat: seat.to_owned(),
11371        from: from.to_owned(),
11372        to: to.to_owned(),
11373        reason: reason.to_owned(),
11374    });
11375}
11376
11377/// Did this reply report running a command whose own CLI never confirmed an
11378/// exit status?
11379///
11380/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11381/// command *finished* (see that type's own doc), so this can only be `true`
11382/// for a command whose completion event carried no readable exit code — not
11383/// for one that simply is not mentioned at all. That is the one signal this
11384/// crate can read, from the same record `state.jobs` renders, about a reply
11385/// standing next to work its own CLI cannot vouch for finishing; it is
11386/// deliberately not a check on the exit code's *value* (a fixer legitimately
11387/// runs a command that fails mid-iteration before it succeeds) and not a
11388/// guess at a command still running in the background (which emits no event
11389/// at all, and so leaves no evidence here to find).
11390fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11391    commands.iter().any(|c| c.exit_code.is_none())
11392}
11393
11394/// The reason recorded for a candidate, and named in a handover, when an
11395/// implement seat ended its turn without starting the work and did so again
11396/// on its one retry. See [`Runner::retry_unstarted`].
11397const UNSTARTED_TWICE: &str = "the agent ended its turn without starting the work (no tool call, \
11398                               worktree unchanged), and again when asked once more";
11399
11400/// Did this turn end cleanly without the seat having started the work?
11401///
11402/// Every part is positive evidence, and a missing one means "no": a usable
11403/// reply; a CLI whose stream reports tool calls and reported none
11404/// (`tool_calls` is `None` for a backend that does not report them, which is
11405/// unknown, never zero); no command evidence; and a checkout whose `HEAD` is
11406/// the one recorded before the turn (`before`) with nothing uncommitted. A
11407/// dirty tree, a moved `HEAD` or an unreadable repository never authorizes a
11408/// retry: partial work is the other recoveries' business.
11409///
11410/// The comparison is with the seat's own starting point, not the run's base,
11411/// so a seat that left an inherited patch untouched is unstarted too.
11412fn ended_unstarted(
11413    out: &AgentOutput,
11414    before: Option<&str>,
11415    after: Option<&str>,
11416    clean: Option<bool>,
11417) -> bool {
11418    out.usable()
11419        && out.tool_calls == Some(0)
11420        && out.commands.is_empty()
11421        && before.is_some()
11422        && before == after
11423        && clean == Some(true)
11424}
11425
11426/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11427/// adoption guard.
11428#[derive(Debug, Clone, PartialEq, Eq)]
11429enum NoopClaimVerdict {
11430    /// Reply did not open with `NO CHANGE NEEDED:`.
11431    Absent,
11432    /// Structured evidence passed schema, CLI command, and repository checks.
11433    Accepted,
11434    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11435    /// concrete reason.
11436    Rejected(String),
11437}
11438
11439fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11440    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11441    cmd.description.trim() == check.method.trim()
11442}
11443
11444/// Checks cited by `requirements` plus the final check, deduplicated in order.
11445fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11446    let mut out = report.cited_checks();
11447    if let Some(last) = report.checks.last()
11448        && !out
11449            .iter()
11450            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11451    {
11452        out.push(last);
11453    }
11454    out
11455}
11456
11457/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11458/// when the backend reported commands. Empty `commands` is allowed because not
11459/// every backend emits structured command events.
11460fn check_command_evidence(
11461    report: &verdict::VerifiedNoopReport,
11462    commands: &[agent::CommandEvidence],
11463) -> std::result::Result<(), String> {
11464    if commands.is_empty() {
11465        return Ok(());
11466    }
11467    for check in checks_to_cross_verify(report) {
11468        let matching: Vec<&agent::CommandEvidence> = commands
11469            .iter()
11470            .filter(|cmd| command_matches_check(cmd, check))
11471            .collect();
11472        match check.kind {
11473            verdict::NoopEvidenceKind::Command
11474            | verdict::NoopEvidenceKind::Test
11475            | verdict::NoopEvidenceKind::Path => {
11476                let Some(last_cmd) = matching.last() else {
11477                    return Err(format!(
11478                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11479                         but no matching command was recorded by the CLI",
11480                        check.id.trim(),
11481                        check.kind,
11482                        check.target.trim()
11483                    ));
11484                };
11485                if last_cmd.exit_code != Some(0) {
11486                    return Err(format!(
11487                        "contradictory command evidence: check `{}` claims `{}` passed, \
11488                         but its last recorded CLI command (`{}`) exited with {}",
11489                        check.id.trim(),
11490                        check.target.trim(),
11491                        last_cmd.description.trim(),
11492                        crate::notices::exit_status(last_cmd.exit_code)
11493                    ));
11494                }
11495                if check.kind == verdict::NoopEvidenceKind::Test
11496                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11497                {
11498                    return Err(format!(
11499                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11500                         but its last recorded CLI output reports failure or no passing tests",
11501                        check.id.trim(),
11502                        check.target.trim()
11503                    ));
11504                }
11505            }
11506            verdict::NoopEvidenceKind::Commit => {
11507                if let Some(last_cmd) = matching.last()
11508                    && last_cmd.exit_code != Some(0)
11509                {
11510                    return Err(format!(
11511                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11512                         but its last recorded CLI command (`{}`) exited with {}",
11513                        check.id.trim(),
11514                        check.target.trim(),
11515                        last_cmd.description.trim(),
11516                        crate::notices::exit_status(last_cmd.exit_code)
11517                    ));
11518                }
11519            }
11520        }
11521    }
11522    Ok(())
11523}
11524
11525/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11526/// exit, confirmed commands, strict structured JSON validation, and
11527/// `CommandEvidence` consistency.
11528fn evaluate_noop_claim(
11529    usable: bool,
11530    commands: &[agent::CommandEvidence],
11531    text: &str,
11532) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11533    if !text
11534        .trim_start()
11535        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11536    {
11537        return Ok(None);
11538    }
11539    if !usable {
11540        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11541    }
11542    if has_unconfirmed_command(commands) {
11543        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11544    }
11545    let Some(parsed) = verdict::parse_verified_noop(text) else {
11546        return Ok(None);
11547    };
11548    let report = parsed?;
11549    check_command_evidence(&report, commands)?;
11550    Ok(Some(report))
11551}
11552
11553/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11554/// structured no-op report against the candidate's real Git history and
11555/// worktree. Existence alone never satisfies a requirement (the report still
11556/// had to carry concrete passing checks), while a missing commit/path or a
11557/// commit not on `base_commit` disqualifies the claim.
11558async fn verify_noop_repo_evidence(
11559    report: &verdict::VerifiedNoopReport,
11560    worktree: &Path,
11561    base_commit: &str,
11562) -> std::result::Result<(), String> {
11563    let wt_canon = std::fs::canonicalize(worktree).ok();
11564    for check in checks_to_cross_verify(report) {
11565        match check.kind {
11566            verdict::NoopEvidenceKind::Commit => {
11567                let target = check.target.trim();
11568                let Some(sha) = git::commit_of(worktree, target).await else {
11569                    return Err(format!(
11570                        "check `{}` cites commit `{target}`, which does not exist in git history",
11571                        check.id.trim()
11572                    ));
11573                };
11574                if !git::is_ancestor(worktree, &sha, base_commit).await {
11575                    return Err(format!(
11576                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11577                        check.id.trim(),
11578                        short(base_commit)
11579                    ));
11580                }
11581            }
11582            verdict::NoopEvidenceKind::Path => {
11583                let target = check.target.trim();
11584                let rel = verdict::strip_path_locator(target);
11585                let full = worktree.join(rel);
11586                if !full.exists() {
11587                    return Err(format!(
11588                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11589                        check.id.trim()
11590                    ));
11591                }
11592                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11593                    && !path_canon.starts_with(wt_canon)
11594                {
11595                    return Err(format!(
11596                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11597                        check.id.trim()
11598                    ));
11599                }
11600            }
11601            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11602        }
11603    }
11604    Ok(())
11605}
11606
11607/// Full adoption guard for an implementer reply, including real Git history and
11608/// worktree path verification.
11609async fn verified_noop_claim_in_worktree(
11610    usable: bool,
11611    commands: &[agent::CommandEvidence],
11612    text: &str,
11613    worktree: &Path,
11614    base_commit: &str,
11615) -> NoopClaimVerdict {
11616    let report = match evaluate_noop_claim(usable, commands, text) {
11617        Ok(Some(r)) => r,
11618        Ok(None) => return NoopClaimVerdict::Absent,
11619        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11620    };
11621    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11622        return NoopClaimVerdict::Rejected(reason);
11623    }
11624    NoopClaimVerdict::Accepted
11625}
11626
11627/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11628/// trusted as a verified no-op — the adoption guard's pure text-and-command
11629/// half (repository history/path verification runs in
11630/// [`verified_noop_claim_in_worktree`]).
11631///
11632/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11633/// timed out): a marker only earns the benefit of the doubt from a turn the
11634/// CLI itself vouches for finishing properly, the same house style
11635/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11636/// *fix* report to for `commands`. A candidate that timed out, exited
11637/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11638/// or failed structured validation returns `None`.
11639#[cfg(test)]
11640fn verified_noop_claim(
11641    usable: bool,
11642    commands: &[agent::CommandEvidence],
11643    text: &str,
11644) -> Option<String> {
11645    evaluate_noop_claim(usable, commands, text)
11646        .ok()
11647        .flatten()
11648        .map(|report| report.summary_text())
11649}
11650
11651fn short(commit: &str) -> String {
11652    commit.chars().take(7).collect()
11653}
11654
11655fn make_executable(path: &Path) -> Result<()> {
11656    #[cfg(unix)]
11657    {
11658        use std::os::unix::fs::PermissionsExt as _;
11659        let mut perms = std::fs::metadata(path)?.permissions();
11660        perms.set_mode(0o755);
11661        std::fs::set_permissions(path, perms)?;
11662    }
11663    #[cfg(not(unix))]
11664    {
11665        let _ = path;
11666    }
11667    Ok(())
11668}
11669
11670/// What every seat in one batch shares: where the answers are attributed, the
11671/// prompt overlay they inherit, and the build cache they are told to use.
11672///
11673/// A struct rather than four more parameters: `wave` also needs the run's
11674/// state (to record who is answering right now) and the attempt number, and
11675/// eight positional arguments is both unreadable and a clippy error.
11676struct WaveCtx<'a> {
11677    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11678    /// paid for it.
11679    run: &'a str,
11680    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11681    node: &'a str,
11682    prompts: &'a Prompts,
11683    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11684    cache: Option<&'a Path>,
11685    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11686    /// `JobRecord::round`. `None` for every other node.
11687    round: Option<usize>,
11688    /// Carry each seat's failed-agent history across waves (the review loop
11689    /// only): start-of-round priority and handover choice read
11690    /// [`RunState::seat_history`], and every answer or failure writes it.
11691    carry_seats: bool,
11692    /// The run's park / interrupt requests, so a wait for a shared resource
11693    /// can be abandoned the moment the operator asks to park.
11694    pauses: Option<(&'a Pause, &'a Pause)>,
11695}
11696
11697/// Shared scheduling policy for operations and spawned seat invocations.
11698fn repository_wait(
11699    state: &RunState,
11700    pauses: Option<(&Pause, &Pause)>,
11701) -> crate::repo_lock::WaitPolicy {
11702    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11703    let inherited = crate::repo_lock::WaitPolicy::current();
11704    crate::repo_lock::WaitPolicy::new(
11705        Duration::from_secs(state.config.graph.timeout_resource_wait),
11706        move || {
11707            inherited.cancelled()
11708                || pauses
11709                    .as_ref()
11710                    .is_some_and(|(a, b)| a.parked() || b.parked())
11711        },
11712    )
11713}
11714
11715fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11716    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11717        state.event("resource", timeout.0.description());
11718        state.resource_block = Some(timeout.0.clone());
11719        return;
11720    }
11721    if error.is::<crate::repo_lock::ResourceBlocked>() {
11722        state.resource_block = Some(crate::run::ResourceBlock {
11723            cause: crate::run::ResourceBlockCause::Other,
11724            node: "repository".into(),
11725            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11726                "disk admission"
11727            } else if error.to_string().contains("disk pressure") {
11728                "disk pressure"
11729            } else if error.to_string().contains("disk admission") {
11730                "disk admission"
11731            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11732                "incremental cache admission"
11733            } else {
11734                "repository coordination"
11735            }
11736            .into(),
11737            detail: format!("{error:#}"),
11738            at: Timestamp::now(),
11739        });
11740        state.event("resource", error.to_string());
11741    }
11742}
11743
11744async fn coordinate_operation(
11745    state: &mut RunState,
11746    cwd: &Path,
11747    wait: &crate::repo_lock::WaitPolicy,
11748) -> Result<Option<crate::repo_lock::SeatLease>> {
11749    let result =
11750        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11751            .await;
11752    if let Err(e) = &result {
11753        record_repository_block(state, e);
11754    }
11755    result
11756}
11757
11758/// Run one job, honouring the parallelism budget.
11759async fn run_one(
11760    job: SeatJob,
11761    sem: Arc<Semaphore>,
11762    ctx: &WaveCtx<'_>,
11763    state: &mut RunState,
11764    attempt: usize,
11765) -> (SeatState, AgentOutcome) {
11766    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11767        .await
11768        .pop()
11769        .expect("one job in, one result out");
11770    (seat, out)
11771}
11772
11773/// Run every job concurrently, capped by the semaphore, preserving order.
11774///
11775/// Every seat in the batch is recorded into [`RunState::active`] before the
11776/// wave starts and cleared as each answer lands, so the run's own record says
11777/// who is still being waited on rather than only who finished.
11778async fn wave(
11779    jobs: Vec<SeatJob>,
11780    sem: Arc<Semaphore>,
11781    ctx: &WaveCtx<'_>,
11782    state: &mut RunState,
11783    attempt: usize,
11784) -> Vec<(usize, SeatState, AgentOutcome)> {
11785    let WaveCtx {
11786        run,
11787        node,
11788        prompts,
11789        cache,
11790        round,
11791        carry_seats: _,
11792        pauses,
11793    } = *ctx;
11794    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11795    for job in &jobs {
11796        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11797    }
11798    if let Err(e) = state.save() {
11799        // A failed persist of "who is answering right now" must not abort the
11800        // wave: the seats are already being asked, and the alternative is
11801        // losing the answers to save a status line nobody may even be
11802        // watching.
11803        tracing::warn!("could not persist in-progress seats: {e:#}");
11804    }
11805    // Shared-mode waves keep their existing single lease. Isolated writers
11806    // acquire their own checkout's target at seat admission.
11807    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11808    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11809    // never borrowed from a job's agent budget (and never charged to it either,
11810    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11811    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11812    let cache_guard = if let Some(cache_dir) = cache {
11813        if jobs_had_a_writer {
11814            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11815            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11816            match acquire_cache_lease(
11817                state,
11818                cache_dir,
11819                &owner,
11820                resource_limit,
11821                node,
11822                node,
11823                &cancel,
11824            )
11825            .await
11826            {
11827                Ok(Some(g)) => Some(g),
11828                // Parking: leave without spawning anything. The run parks at
11829                // the next boundary and the seats are asked afresh on resume.
11830                Ok(None) => {
11831                    if let Some(block) = &mut state.resource_block {
11832                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11833                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11834                        };
11835                    }
11836                    return block_wave(
11837                        jobs,
11838                        state,
11839                        node,
11840                        attempt,
11841                        "parked while waiting for the shared build cache",
11842                    );
11843                }
11844                // An unreadable lease is not contention: keep the old
11845                // fallback (no shared cache for this wave's seats).
11846                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11847                Err(e) => {
11848                    // Writing seats may not build into a cache this run does
11849                    // not hold, and an agent that cannot be given one is not
11850                    // asked at all: the run stops resumably instead.
11851                    let why = format!("{e:#}");
11852                    state.event(
11853                        "resource",
11854                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11855                    );
11856                    return block_wave(jobs, state, node, attempt, &why);
11857                }
11858            }
11859        } else {
11860            None
11861        }
11862    } else {
11863        None
11864    };
11865    let cache_guard = cache_guard.map(Arc::new);
11866    // Every job keeps its whole budget: the wait above was not the agent's.
11867    // Restart the seats' clocks so "started" means "being spawned now".
11868    state.seats_spawning(node, attempt);
11869    if let Err(e) = state.save() {
11870        tracing::warn!("could not persist the start of a wave: {e:#}");
11871    }
11872    // Queueing behind this wave's own seats for a parallelism slot is normal
11873    // (each of them is bounded by its own agent timeout); only a wait beyond
11874    // all of them plus the resource limit means the slots never came back.
11875    let slot_limit = resource_limit
11876        + jobs
11877            .iter()
11878            .map(|j| j.timeout)
11879            .max()
11880            .unwrap_or_default()
11881            .saturating_mul(jobs.len() as u32);
11882    let mut set = tokio::task::JoinSet::new();
11883    // Seats announce themselves here the moment they hold a parallelism
11884    // permit, i.e. just before their CLI is spawned.
11885    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11886    let overlay = prompts.overlay(node);
11887    let repository_wait = repository_wait(state, pauses);
11888    for (i, mut job) in jobs.into_iter().enumerate() {
11889        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11890        if cache.is_some() && (!job.allow_write || cache_guard.is_some()) {
11891            job.prompt.push('\n');
11892            job.prompt
11893                .push_str(&prompt::build_cache_note(node, job.allow_write));
11894        }
11895        let sem = Arc::clone(&sem);
11896        let run = run.to_owned();
11897        let node = node.to_owned();
11898        // Only implementers were told about the task's attachments, so only
11899        // their seats get the directory widened for reading.
11900        let attachments = if node == "implement" {
11901            state.attachments.clone()
11902        } else {
11903            Vec::new()
11904        };
11905        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11906        // `prompt::build_cache_note`'s doc for why setting it anyway is
11907        // exactly how a sandboxed reviewer's write refusal got reported as a
11908        // defect in the patch, not a property of its own seat. And a
11909        // write-allowed one is handed it only when the lease above was
11910        // actually acquired: a wave that could not get it (`cache_guard` is
11911        // `None`, see its own comment) must not send seats to build into a
11912        // directory this run does not hold - that is the exact concurrent,
11913        // unmanaged-write race this module exists to prevent, not something
11914        // "proceeding anyway" is allowed to reintroduce.
11915        let cache = cache
11916            .filter(|_| job.allow_write && cache_guard.is_some())
11917            .map(Path::to_path_buf);
11918        let cache_guard = cache_guard.clone();
11919        let spawned_tx = spawned_tx.clone();
11920        let repository_wait = repository_wait.clone();
11921        let coordination = state.config.coordination.clone();
11922        let fetched_base = state.fetched_base.clone();
11923        set.spawn(async move {
11924            // A wait for a parallelism slot is scheduling, not the agent: it
11925            // is bounded by its own limit and ends as a resource block, never
11926            // as a timeout of the agent that was not started.
11927            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11928                Ok(p) => p,
11929                Err(_) => {
11930                    return (
11931                        i,
11932                        job.seat,
11933                        AgentOutcome::ResourceBlocked(format!(
11934                            "no parallel slot became free within {}s",
11935                            slot_limit.as_secs()
11936                        )),
11937                        None,
11938                        false,
11939                    );
11940                }
11941            };
11942            spawned_tx.send(job.seat.key.clone()).ok();
11943            let mut seat = job.seat;
11944            let out = repository_wait
11945                .scope(agent::invoke_in_wave(
11946                    &job.spec,
11947                    &mut seat,
11948                    &Invocation {
11949                        coordination: coordination.as_ref(),
11950                        fetched_base: fetched_base.as_ref(),
11951                        cwd: &job.cwd,
11952                        prompt: &job.prompt,
11953                        timeout: job.timeout,
11954                        allow_write: job.allow_write,
11955                        sessions: job.sessions,
11956                        artifacts: &job.artifacts,
11957                        stem: &job.stem,
11958                        run: &run,
11959                        node: &node,
11960                        cache_dir: cache.as_deref(),
11961                        attachments: &attachments,
11962                        writable: &[],
11963                    },
11964                    cache_guard.as_deref(),
11965                ))
11966                .await;
11967            let cache_block = out
11968                .as_ref()
11969                .err()
11970                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11971                .map(|timeout| timeout.0.clone());
11972            let interrupted = out
11973                .as_ref()
11974                .err()
11975                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11976            let out = match out {
11977                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11978                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11979                // Billed work the CLI failed to hand over is not an ordinary
11980                // failure, but its text is the CLI's raw error JSON, not an
11981                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11982                // read it as one by forgetting to check. `usable()` is always
11983                // false here (dropped implies an empty response), so this has
11984                // to be checked before the catch-all `Failed` below or the
11985                // one shape this exists for is lost with the rest.
11986                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11987                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11988                Ok(o) => AgentOutcome::Failed(format!(
11989                    "process exited with no usable output ({})",
11990                    crate::notices::exit_status(o.exit_code)
11991                )),
11992                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11993                    AgentOutcome::ResourceBlocked(e.to_string())
11994                }
11995                Err(e) => AgentOutcome::Failed(e.to_string()),
11996            };
11997            (i, seat, out, cache_block, interrupted)
11998        });
11999    }
12000    drop(spawned_tx);
12001    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
12002    loop {
12003        let joined = tokio::select! {
12004            Some(key) = spawned_rx.recv() => {
12005                // The clock of this seat starts now, not when it queued.
12006                state.seat_spawned(&key);
12007                if let Err(e) = state.save() {
12008                    tracing::warn!("could not persist a seat's start: {e:#}");
12009                }
12010                continue;
12011            }
12012            joined = set.join_next() => joined,
12013        };
12014        let Some(joined) = joined else {
12015            break;
12016        };
12017        let (i, seat, out, cache_block, interrupted) = match joined {
12018            Ok(v) => v,
12019            // No seat to clear: a panicked task never reported which one it
12020            // was. The defensive sweep below this loop is what stops that
12021            // seat's `active` entry from surviving forever.
12022            Err(e) => {
12023                tracing::error!("agent task panicked: {e}");
12024                continue;
12025            }
12026        };
12027        state.seat_finished(&seat.key);
12028        if interrupted
12029            && node == "implement"
12030            && let Some(label) = state
12031                .candidates
12032                .iter()
12033                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
12034                .map(|candidate| candidate.label)
12035        {
12036            state.candidate_preservation.insert(
12037                label,
12038                "interrupted implementation awaiting persistence".into(),
12039            );
12040            state.interrupted_implementations.insert(label);
12041        }
12042        if let Some(block) = cache_block
12043            && state.resource_block.is_none()
12044        {
12045            state.event("resource", block.description());
12046            state.resource_block = Some(block);
12047        }
12048        if let AgentOutcome::ResourceBlocked(why) = &out
12049            && state.resource_block.is_none()
12050        {
12051            state.resource_block = Some(crate::run::ResourceBlock {
12052                cause: crate::run::ResourceBlockCause::Other,
12053                node: node.to_owned(),
12054                kind: if why.contains("disk pressure") {
12055                    "disk pressure"
12056                } else if why.contains("disk admission") {
12057                    "disk admission"
12058                } else if why.contains(crate::incremental::BLOCKED) {
12059                    "incremental cache admission"
12060                } else if why.contains(crate::build_target::KIND) {
12061                    crate::build_target::KIND
12062                } else if why.contains("repository coordination") {
12063                    "repository coordination"
12064                } else {
12065                    "parallel slot"
12066                }
12067                .to_owned(),
12068                detail: why.clone(),
12069                at: Timestamp::now(),
12070            });
12071            let activity = if interrupted {
12072                "agent execution interrupted"
12073            } else {
12074                "no agent was started"
12075            };
12076            state.event("resource", format!("{node}: {activity} - {why}"));
12077        }
12078        record_jobs(state, node, round, &seat.key, &out);
12079        if let Err(e) = state.save() {
12080            tracing::warn!("could not persist a seat's completion: {e:#}");
12081        }
12082        if collected.len() <= i {
12083            collected.resize_with(i + 1, || None);
12084        }
12085        collected[i] = Some((i, seat, out));
12086    }
12087    // Belt-and-braces for the panic branch above: every seat this exact batch
12088    // started shares this `(node, attempt)` pair, and every seat that finished
12089    // normally already cleared itself, so anything left tagged with it here
12090    // can only be a panicked task's leftover. Cleared unconditionally rather
12091    // than left to read as still answering forever.
12092    if state
12093        .active
12094        .values()
12095        .any(|a| a.node == node && a.attempt == attempt)
12096    {
12097        state
12098            .active
12099            .retain(|_, a| !(a.node == node && a.attempt == attempt));
12100        if let Err(e) = state.save() {
12101            tracing::warn!("could not persist the end of a wave: {e:#}");
12102        }
12103    }
12104    drop(cache_guard);
12105    collected.into_iter().flatten().collect()
12106}
12107
12108/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
12109/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
12110/// this is data collection, not the fix-specific completion contract in
12111/// [`Runner::continue_fix_report`], and applies regardless of which node
12112/// asked.
12113///
12114/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
12115/// evidence from; `Failed` does not, and correctly contributes nothing — a
12116/// timeout or crash is not itself evidence about a command the seat may have
12117/// started.
12118fn record_jobs(
12119    state: &mut RunState,
12120    node: &str,
12121    round: Option<usize>,
12122    seat: &str,
12123    out: &AgentOutcome,
12124) {
12125    let commands: &[agent::CommandEvidence] = match out {
12126        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
12127        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
12128    };
12129    let checked_at = Timestamp::now();
12130    for c in commands {
12131        state.jobs.push(JobRecord {
12132            node: node.to_owned(),
12133            round,
12134            seat: seat.to_owned(),
12135            id: c.id.clone(),
12136            description: c.description.clone(),
12137            checked_at,
12138            status: match c.exit_code {
12139                Some(0) => JobStatus::Completed,
12140                Some(_) => JobStatus::Failed,
12141                None => JobStatus::Unknown,
12142            },
12143            exit_code: c.exit_code,
12144            result_summary: c.result_summary.clone(),
12145            source: c.source.clone(),
12146        });
12147    }
12148}
12149
12150/// Is a review round clean, given how many reviewer seats answered against
12151/// how many the round expected?
12152///
12153/// A seat that never answered (timeout, crash, unparsable output) is not a
12154/// seat that read the patch and found nothing — treating it as such is
12155/// exactly the bug this function exists to close. Under the default `block`
12156/// policy a missing seat can never be clean; `warn` still requires the seats
12157/// that *did* answer to have found nothing blocking and verification to be
12158/// green.
12159///
12160/// `quota_missing` narrows that `block` default for exactly one cause of
12161/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
12162/// a session limit lifts by the very next round buys nothing — the seat is
12163/// asked again with the same quota — so once every missing seat is accounted
12164/// for by a quota loss (and at least one seat *did* answer, so a decision has
12165/// something to rest on) the round is decided on the panel that could answer,
12166/// same as `warn` would. A panel that lost every seat to quota is not
12167/// decided here: `answered == 0` falls through to the existing `block`
12168/// fallback so a fully collapsed panel still waits rather than landing on no
12169/// review at all.
12170fn round_is_clean(
12171    blocking: usize,
12172    e2e_ok: bool,
12173    answered: usize,
12174    expected: usize,
12175    quota_missing: usize,
12176    policy: IncompleteReviewPolicy,
12177) -> bool {
12178    if blocking != 0 || !e2e_ok {
12179        return false;
12180    }
12181    if answered == expected || policy == IncompleteReviewPolicy::Warn {
12182        return true;
12183    }
12184    answered > 0 && expected - answered <= quota_missing
12185}
12186
12187/// The review loop's own conclusion, derived entirely from its persisted
12188/// round records and the round budget that produced them — never from
12189/// `status`, so a reentry (or `gate`/`merge` reading it independently)
12190/// recomputes the identical answer regardless of what an earlier node in the
12191/// same walk, or a previous walk, did to `status`.
12192///
12193/// `None` while more rounds remain to try, including when review never ran
12194/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
12195/// gone clean, or the budget is spent, or the tree has stopped moving (see
12196/// [`STAGNANT_LIMIT`]), the answer is one of two things:
12197///
12198/// - An incomplete panel that raised nothing is missing input, not a
12199///   verified tree — never a hand-off candidate, whatever verification said
12200///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
12201/// - Otherwise, green e2e on the last round hands off (see
12202///   [`Runner::stop_reviewing`]); red e2e blocks.
12203///
12204/// A last round whose own verification is still `ResourceBlocked` — magi
12205/// itself never got a command to run, not evidence the patch is broken —
12206/// is neither: this returns `None` for it too, the same as "more rounds
12207/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
12208/// handling of that shape) instead of this cheap recomputation guessing a
12209/// verdict a real attempt never produced.
12210pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
12211    if max_rounds == 0
12212        || reviews.last().is_some_and(|r| {
12213            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
12214        })
12215    {
12216        return Some(RunStatus::Gating);
12217    }
12218    let last = reviews.last()?;
12219    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
12220    if reviews.len() < max_rounds && !stagnant {
12221        return None;
12222    }
12223    if last.incomplete() && last.blocking == 0 {
12224        return Some(RunStatus::Blocked);
12225    }
12226    if last.e2e_status() == E2eStatus::ResourceBlocked
12227        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
12228    {
12229        return None;
12230    }
12231    Some(if last.e2e.iter().all(CommandOutcome::ok) {
12232        RunStatus::Gating
12233    } else {
12234        RunStatus::Blocked
12235    })
12236}
12237
12238/// How long a re-ask may take, given the budget the first attempt had.
12239///
12240/// A `nudged` retry is a request to restate an answer the seat has already
12241/// worked out: it carries no new work, so it does not deserve the original
12242/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
12243/// 133 seconds while a third sat for over ten minutes on a resumed session
12244/// holding 410 KB of prior output - and because the retry had inherited the
12245/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
12246/// judging round whose other seats were long finished.
12247///
12248/// A quarter of the budget, with a floor so that a deliberately short timeout
12249/// does not collapse to nothing. A retry that re-sends the whole prompt
12250/// (because the seat kept no context) is the original job again, and keeps the
12251/// original budget.
12252pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
12253    if nudged {
12254        (full / 4).max(Duration::from_secs(120)).min(full)
12255    } else {
12256        full
12257    }
12258}
12259
12260/// Run a wave and parse each reply, re-asking the seats whose reply was
12261/// unusable.
12262///
12263/// The re-ask is a nudge rather than the whole prompt again when the seat still
12264/// holds its conversation, which is the difference between a cheap retry and
12265/// paying for the entire candidate set twice.
12266///
12267/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
12268/// successor in `roster` is handed to it instead of being re-asked: the
12269/// handover is the retry. A seat with no successor left (a single-agent
12270/// roster, the roster's tail) is nudged as before, up to `retries` times. So
12271/// the asks to one seat in one node number at most
12272/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
12273/// is asked once (a dropped stream is nudged first), and only the last agent
12274/// of the chain gets the `retries` same-agent nudges. Each roster agent is
12275/// tried at most once per seat, walking forward from the seat's own position and never wrapping
12276/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
12277/// other failure stops the chain when the previous agent failed the same way
12278/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
12279/// [`has_context`] is false and the job's own full prompt and full budget are
12280/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
12281/// intermediate ones are not losses) and is returned as a failure like any
12282/// other absent seat — the caller decides whether the panel still has a
12283/// quorum. An empty `roster` disables handover: failures are nudged as they
12284/// always were, and a quota is simply lost. A reply that fails to parse or
12285/// validate is the prompt's doing and is only ever nudged, never handed over.
12286///
12287/// The returned [`SeatState`] names the agent that answered (or tried last).
12288#[allow(clippy::too_many_arguments)]
12289async fn ask_json_wave<T>(
12290    jobs: Vec<SeatJob>,
12291    sem: Arc<Semaphore>,
12292    retries: usize,
12293    roster: &[AgentSpec],
12294    ctx: &WaveCtx<'_>,
12295    losses: &mut Vec<QuotaLoss>,
12296    state: &mut RunState,
12297    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12298) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12299where
12300    T: serde::de::DeserializeOwned + Send + 'static,
12301{
12302    ask_wave_with(
12303        jobs,
12304        sem,
12305        retries,
12306        roster,
12307        ctx,
12308        losses,
12309        state,
12310        &|text: &str| {
12311            let v = verdict::extract_json::<T>(text)?;
12312            validate(&v)?;
12313            Ok(v)
12314        },
12315    )
12316    .await
12317}
12318
12319/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12320/// a node whose answer is prose (deliberation) shares the same handover,
12321/// failure classification, quota bookkeeping and bounds instead of a copy.
12322///
12323/// A seat handed to another roster agent is sent the job's `handover` prompt
12324/// (when it has one) rather than `prompt`: the new agent has no session, so a
12325/// resume-style prompt would be incomplete. That holds for the handover ask
12326/// and for every nudge to that agent whose `has_context` is false.
12327#[allow(clippy::too_many_arguments)]
12328async fn ask_wave_with<T>(
12329    jobs: Vec<SeatJob>,
12330    sem: Arc<Semaphore>,
12331    retries: usize,
12332    roster: &[AgentSpec],
12333    ctx: &WaveCtx<'_>,
12334    losses: &mut Vec<QuotaLoss>,
12335    state: &mut RunState,
12336    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12337) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12338where
12339    T: Send + 'static,
12340{
12341    let n = jobs.len();
12342    let originals: Vec<SeatJob> = jobs;
12343    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12344    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12345    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12346    // answer, N once it has gone through N nudges. Read back once this
12347    // returns, so a caller building a history record (`ReviewRecord`) can
12348    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12349    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12350    // field's own doc.
12351    let mut nudges: Vec<usize> = vec![0; n];
12352    // The agent now occupying each seat, the ids it has already been through,
12353    // where in the roster the walk began, the class of the last failure, and
12354    // the stem word of a handover not yet asked (full prompt, full budget).
12355    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12356    let mut tried: Vec<BTreeSet<String>> = specs
12357        .iter()
12358        .map(|s| BTreeSet::from([s.id.clone()]))
12359        .collect();
12360    let starts: Vec<usize> = specs
12361        .iter()
12362        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12363        .collect();
12364    let carry = ctx.carry_seats && !roster.is_empty();
12365    // Carried across rounds: ids that failed the seat earlier, and how the
12366    // last failure went (so a repeat of it is not handed over again).
12367    let carried: Vec<BTreeSet<String>> = originals
12368        .iter()
12369        .map(|j| {
12370            state
12371                .seat_history
12372                .get(&j.seat.key)
12373                .filter(|_| carry)
12374                .map(|h| h.failed.clone())
12375                .unwrap_or_default()
12376        })
12377        .collect();
12378    let mut prev: Vec<Option<FailClass>> = originals
12379        .iter()
12380        .map(|j| {
12381            state
12382                .seat_history
12383                .get(&j.seat.key)
12384                .filter(|_| carry)
12385                .and_then(|h| h.last_fail.clone())
12386        })
12387        .collect();
12388    let next_agent =
12389        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12390            let others: BTreeSet<String> = specs
12391                .iter()
12392                .enumerate()
12393                .filter(|(j, _)| *j != i)
12394                .map(|(_, s)| s.id.clone())
12395                .collect();
12396            pick_successor(
12397                roster,
12398                starts[i],
12399                tried,
12400                carry.then(|| &carried[i]),
12401                &others,
12402            )
12403            .cloned()
12404        };
12405    let mut fresh: Vec<Option<String>> = vec![None; n];
12406    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12407    let mut pending: Vec<usize> = (0..n).collect();
12408
12409    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12410    // asks: an agent with a successor is asked once and handed over, and only
12411    // a seat with no successor spends `retries` nudges on the same agent. This
12412    // only guarantees the loop's own termination whatever those say.
12413    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12414    for round in 0..max_rounds {
12415        if pending.is_empty() {
12416            break;
12417        }
12418        let mut batch = Vec::with_capacity(pending.len());
12419        let mut renudged: Vec<&str> = Vec::new();
12420        for &i in &pending {
12421            let src = &originals[i];
12422            // A seat now held by another agent than the job named has no
12423            // session of its own: it gets the full-context prompt whenever
12424            // it is asked in full (the handover ask, a nudge it cannot
12425            // resume).
12426            let full: &str = match &src.handover {
12427                Some(h) if specs[i].id != src.spec.id => h,
12428                _ => &src.prompt,
12429            };
12430            // The prompt and the budget are one decision: a nudge restates
12431            // finished work, a re-sent prompt redoes it.
12432            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12433                (
12434                    full.to_owned(),
12435                    src.timeout,
12436                    format!("{}-{word}-{}", src.stem, specs[i].id),
12437                )
12438            } else if nudges[i] == 0 {
12439                (full.to_owned(), src.timeout, src.stem.clone())
12440            } else {
12441                renudged.push(src.seat.key.as_str());
12442                let why = done[i]
12443                    .as_ref()
12444                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12445                    .unwrap_or_else(|| "no parsable answer".to_owned());
12446                let nudge = prompt::nudge(&why);
12447                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12448                let prompt = if nudged {
12449                    nudge
12450                } else {
12451                    format!("{full}\n\n---\n\n{nudge}")
12452                };
12453                (
12454                    prompt,
12455                    retry_budget(src.timeout, nudged),
12456                    format!("{}-retry{}", src.stem, nudges[i]),
12457                )
12458            };
12459            batch.push(SeatJob {
12460                spec: specs[i].clone(),
12461                seat: seats[i].clone(),
12462                cwd: src.cwd.clone(),
12463                prompt,
12464                timeout,
12465                allow_write: src.allow_write,
12466                sessions: src.sessions,
12467                artifacts: src.artifacts.clone(),
12468                stem,
12469                handover: None,
12470            });
12471        }
12472
12473        if !renudged.is_empty() {
12474            state.event(
12475                ctx.node,
12476                format!("retry {round}: re-asking {}", renudged.join(", ")),
12477            );
12478        }
12479        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12480        let mut still = Vec::new();
12481        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12482            seats[i] = seat;
12483            // No agent was asked: nothing to hand over, nudge, remember or
12484            // charge. The caller sees `resource_block` and stops the node.
12485            if let AgentOutcome::ResourceBlocked(why) = &out {
12486                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12487                continue;
12488            }
12489            let class = FailClass::of(&out);
12490            // A dropped stream is nudged first (the conversation is still
12491            // there to pick up); only a seat whose nudges are spent hands over.
12492            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12493                && nudges[i] < retries
12494                && !roster.is_empty();
12495            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12496                let next = should_hand_over(prev[i].as_ref(), &cur)
12497                    .then(|| next_agent(i, &tried[i], &specs))
12498                    .flatten();
12499                if carry {
12500                    let h = state
12501                        .seat_history
12502                        .entry(originals[i].seat.key.clone())
12503                        .or_default();
12504                    h.failed.insert(specs[i].id.clone());
12505                    h.last_fail = Some(cur.clone());
12506                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12507                        h.last_ok = None;
12508                    }
12509                    // Saved before the next agent is asked, so a restart in
12510                    // between does not forget who failed.
12511                    if let Err(e) = state.save() {
12512                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12513                    }
12514                }
12515                if let Some(next) = next {
12516                    record_handover(
12517                        state,
12518                        ctx.node,
12519                        &originals[i].seat.key,
12520                        &specs[i].id,
12521                        &next.id,
12522                        &cur,
12523                        &fail_reason(&out),
12524                    );
12525                    tried[i].insert(next.id.clone());
12526                    prev[i] = Some(cur.clone());
12527                    seats[i] =
12528                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12529                    specs[i] = next;
12530                    fresh[i] = Some(cur.stem_word().to_owned());
12531                    nudges[i] = 0;
12532                    done[i] = Some(Err(anyhow::anyhow!(
12533                        "handed over after: {}",
12534                        fail_reason(&out)
12535                    )));
12536                    still.push(i);
12537                    continue;
12538                }
12539            }
12540            if carry
12541                && !nudge_first
12542                && let Some(cur) = class.clone()
12543            {
12544                // The chain ended here (no successor, or a repeated failure).
12545                let h = state
12546                    .seat_history
12547                    .entry(originals[i].seat.key.clone())
12548                    .or_default();
12549                h.failed.insert(specs[i].id.clone());
12550                h.last_fail = Some(cur);
12551            }
12552            let parsed = match out {
12553                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12554                AgentOutcome::Quota(o) => {
12555                    last_quota[i] = o.quota.clone();
12556                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12557                }
12558                // Not a parseable answer: the nudge loop re-asks it, which is
12559                // exactly what a dropped stream needs. Just don't hand its raw
12560                // error JSON to `extract_json`.
12561                AgentOutcome::Dropped(o) => {
12562                    let why = o
12563                        .dropped
12564                        .as_ref()
12565                        .map(|d| d.why.as_str())
12566                        .unwrap_or("the CLI ended the stream without delivering its answer");
12567                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12568                }
12569                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12570                    Err(anyhow::anyhow!(e))
12571                }
12572            };
12573            let quota = class == Some(FailClass::Quota);
12574            let failed = parsed.is_err();
12575            if !failed && matches!(ctx.node, "judge" | "vote") {
12576                // A validated answer restores this seat's quorum presence,
12577                // including on the normal path after an all-seat block.
12578                state
12579                    .quota
12580                    .retain(|loss| loss.seat != originals[i].seat.key);
12581            }
12582            done[i] = Some(parsed);
12583            if carry && !failed {
12584                let h = state
12585                    .seat_history
12586                    .entry(originals[i].seat.key.clone())
12587                    .or_default();
12588                h.failed.remove(&specs[i].id);
12589                h.last_ok = Some(specs[i].id.clone());
12590                h.last_fail = None;
12591            }
12592            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12593            // fail the same way; and never re-ask a seat that already parsed.
12594            // A failed agent that still has a successor is not re-asked
12595            // either: the handover was its remedy and has just been refused
12596            // (the chain stops on a repeated failure class). A seat with no
12597            // successor left (a single-agent roster, the roster's tail, or an
12598            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12599            let agent_failure = class.is_some()
12600                && !nudge_first
12601                && !roster.is_empty()
12602                && next_agent(i, &tried[i], &specs).is_some();
12603            if failed && !quota && !agent_failure && nudges[i] < retries {
12604                nudges[i] += 1;
12605                still.push(i);
12606            }
12607        }
12608        pending = still;
12609    }
12610
12611    // One loss per seat whose chain ended on a quota: the intermediate ones
12612    // were absorbed by a handover and are not losses.
12613    for (i, q) in last_quota.into_iter().enumerate() {
12614        if let Some(quota) = q {
12615            losses.push(QuotaLoss::from_report(
12616                originals[i].seat.key.clone(),
12617                ctx.node,
12618                Some(&quota),
12619            ));
12620        }
12621    }
12622
12623    // A stalled quorum already has its own recovery checkpoint. Refresh
12624    // its missing seats before deciding whether it can resume.
12625    if state.status != RunStatus::Stalled
12626        && ctx.node != "deliberate"
12627        && n > 0
12628        && losses.len() == n
12629        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12630    {
12631        block_machine_outage(state, ctx.node, losses);
12632        state.quota.append(losses);
12633    }
12634
12635    seats
12636        .into_iter()
12637        .zip(done)
12638        .zip(nudges)
12639        .map(|((seat, res), attempts)| {
12640            (
12641                seat,
12642                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12643                attempts,
12644            )
12645        })
12646        .collect()
12647}
12648
12649/// A node with no available agent has no task verdict. Preserve the node
12650/// checkpoint and record why a subsequent explicit resume is needed.
12651pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12652    let mut auth: Vec<_> = losses
12653        .iter()
12654        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12655        .map(|loss| loss.agent.clone())
12656        .collect();
12657    auth.sort();
12658    auth.dedup();
12659    let (kind, detail) = if auth.is_empty() {
12660        (
12661            "agent usage limit",
12662            "All seats reached their agent usage limits; resume after usage is available"
12663                .to_owned(),
12664        )
12665    } else {
12666        (
12667            "agent authentication",
12668            format!(
12669                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12670                auth.join(", ")
12671            ),
12672        )
12673    };
12674    state.resource_block = Some(crate::run::ResourceBlock {
12675        node: node.to_owned(),
12676        kind: kind.to_owned(),
12677        cause: crate::run::ResourceBlockCause::Other,
12678        detail: detail.clone(),
12679        at: Timestamp::now(),
12680    });
12681    state.event(node, detail);
12682}
12683
12684/// Did the wave end without asking any agent (see [`block_wave`])?
12685fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12686    results
12687        .iter()
12688        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12689}
12690
12691/// Settle a wave that never spawned anything: every job answers
12692/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12693/// else about the seat (session, history, quota) is touched.
12694fn block_wave(
12695    jobs: Vec<SeatJob>,
12696    state: &mut RunState,
12697    node: &str,
12698    attempt: usize,
12699    why: &str,
12700) -> Vec<(usize, SeatState, AgentOutcome)> {
12701    state.resource_wait = None;
12702    state
12703        .active
12704        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12705    if let Err(e) = state.save() {
12706        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12707    }
12708    jobs.into_iter()
12709        .enumerate()
12710        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12711        .collect()
12712}
12713
12714/// Acquire the shared build cache's lease, waiting out contention within
12715/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12716/// unbounded wait is never acceptable).
12717///
12718/// A first, non-blocking check happens before ever waiting; if it finds the
12719/// lease busy, that fact is logged as a `verify` event *and* flushed with
12720/// [`RunState::save`] immediately — not only once the wait finally succeeds
12721/// or gives up — so a `magi show` run by a different process while this one
12722/// is still waiting reads a `run.json` that says so, rather than whatever it
12723/// looked like before the wait started. The same applies to the terminal
12724/// failure: logged and saved before this returns `Err`, so a caller that
12725/// could not get the lease at all still leaves a legible record of why.
12726async fn acquire_cache_lease(
12727    state: &mut RunState,
12728    cache_dir: &Path,
12729    owner: &crate::cache::Owner,
12730    budget: Duration,
12731    node: &str,
12732    context: &str,
12733    cancel: &(dyn Fn() -> bool + Sync),
12734) -> Result<Option<crate::cache::Guard>> {
12735    let home = crate::run::home();
12736    let kind = if crate::build_target::isolated(&state.config) {
12737        crate::build_target::KIND
12738    } else {
12739        "shared build cache"
12740    };
12741    let started = Instant::now();
12742    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12743        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12744        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12745        Err(e) => {
12746            state.event(
12747                "verify",
12748                format!(
12749                    "{context}: could not check the {kind} at {}: {e:#}",
12750                    cache_dir.display()
12751                ),
12752            );
12753            if let Err(e2) = state.save() {
12754                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12755            }
12756            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12757        }
12758    };
12759    state.event(
12760        "verify",
12761        format!(
12762            "{context}: waiting for the {kind} at {} ({})",
12763            cache_dir.display(),
12764            busy.describe()
12765        ),
12766    );
12767    // Seats of this node are waiting, not running: say so, so the countdown a
12768    // reader sees only ever measures an agent that has been spawned.
12769    state.resource_wait = Some(crate::run::ResourceWait {
12770        node: context.to_owned(),
12771        kind: kind.to_owned(),
12772        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12773        since: Timestamp::now(),
12774        limit_secs: budget.as_secs(),
12775    });
12776    if let Err(e) = state.save() {
12777        tracing::warn!("could not persist a cache wait: {e:#}");
12778    }
12779    let remaining = budget.saturating_sub(started.elapsed());
12780    let waited = crate::cache::wait_for_unless(
12781        &home,
12782        cache_dir,
12783        owner,
12784        remaining,
12785        Duration::from_secs(5),
12786        cancel,
12787    )
12788    .await;
12789    state.resource_wait = None;
12790    let cause = match &waited {
12791        Ok(Some(_)) => None,
12792        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12793        Err(error)
12794            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12795        {
12796            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12797                target: cache_dir.to_owned(),
12798                waited_secs: started.elapsed().as_secs(),
12799                limit_secs: budget.as_secs(),
12800            })
12801        }
12802        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12803            Some(crate::run::ResourceBlockCause::Timeout {
12804                waited_secs: started.elapsed().as_secs(),
12805                limit_secs: budget.as_secs(),
12806            })
12807        }
12808        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12809    };
12810    if let Some(cause) = cause {
12811        let detail = match &waited {
12812            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12813            Err(error) => format!("{error:#}"),
12814        };
12815        state.resource_block = Some(crate::run::ResourceBlock {
12816            cause,
12817            node: node.to_owned(),
12818            kind: kind.into(),
12819            detail: format!("{}: {detail}", cache_dir.display()),
12820            at: Timestamp::now(),
12821        });
12822        state.event(
12823            "resource",
12824            state.resource_block.as_ref().unwrap().description(),
12825        );
12826    }
12827    if let Err(error) = state.save() {
12828        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12829    }
12830    waited
12831}
12832
12833/// The lease state could not be read at all (unreadable lease file, a
12834/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12835/// known to be contended, so a wave degrades to running without a shared cache
12836/// instead of stopping on a hold that [`crate::triage`] could never release.
12837#[derive(Debug)]
12838struct CacheCheckError(String);
12839
12840impl std::fmt::Display for CacheCheckError {
12841    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12842        f.write_str(&self.0)
12843    }
12844}
12845
12846impl std::error::Error for CacheCheckError {}
12847
12848/// Keep a specific acquisition outcome when the caller adds command evidence.
12849fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12850    let kind = if crate::build_target::isolated(&state.config) {
12851        crate::build_target::KIND
12852    } else {
12853        "shared build cache"
12854    };
12855    state
12856        .resource_block
12857        .get_or_insert_with(|| crate::run::ResourceBlock {
12858            cause: crate::run::ResourceBlockCause::Other,
12859            node: node.to_owned(),
12860            kind: kind.into(),
12861            detail: format!("{error:#}"),
12862            at: Timestamp::now(),
12863        });
12864    if let Err(error) = state.save() {
12865        tracing::warn!("could not persist cache resource block: {error:#}");
12866    }
12867}
12868
12869tokio::task_local! {
12870    static VERIFY_TARGET: PathBuf;
12871}
12872
12873/// Run `body` — a verify command batch — while holding the shared build
12874/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12875/// never interleave with another borrower's build against the same
12876/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12877/// timeout, or a human's own `magi review`. See the `cache` module doc for
12878/// why this matters more than Cargo's own per-target locking covers — two
12879/// *different* worktrees building the same package name/version into one
12880/// cache directory is a staleness bug, not a lock contention one.
12881///
12882/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12883/// agent waves do. Repository scheduling also has its own bounded,
12884/// cancellable resource-wait policy. Contention must not consume the
12885/// verification budget: `body` receives the full `budget` after both leases
12886/// are acquired and the cache is fresh. Without a shared cache, only
12887/// repository coordination is acquired before handing over the full budget.
12888///
12889/// A lease that cannot be acquired within the resource wait is reported as a single
12890/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12891/// verification — the same shape a spawn failure already takes in
12892/// [`run_commands`], so a caller need not special-case it.
12893#[allow(clippy::too_many_arguments)]
12894async fn with_cache_lease<'s, F, Fut>(
12895    state: &'s mut RunState,
12896    cache_dir: Option<&Path>,
12897    node: &str,
12898    seat: &str,
12899    worktree: &Path,
12900    head: &str,
12901    budget: Duration,
12902    context: &str,
12903    wait: &crate::repo_lock::WaitPolicy,
12904    body: F,
12905) -> Result<(Vec<CommandOutcome>, bool)>
12906where
12907    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12908    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12909{
12910    // Match editing waves: cache first, repository second. In particular,
12911    // pre_gate must never hold the repository while waiting for a wave's cache.
12912    let started = Instant::now();
12913    let home = crate::run::home();
12914    let isolated = crate::build_target::isolated(&state.config);
12915    let planned_target = if isolated {
12916        let plan = (|| -> Result<PathBuf> {
12917            crate::build_target::supports(&state.config)?;
12918            crate::build_target::resolve(&home, worktree)
12919        })();
12920        match plan {
12921            Ok(path) => Some(path),
12922            Err(error) => {
12923                record_cache_error(state, node, &error);
12924                return Ok((
12925                    vec![CommandOutcome {
12926                        command: "(planning isolated build cache)".into(),
12927                        code: None,
12928                        output_tail: format!("{error:#}"),
12929                        duration_ms: 0,
12930                        resource_blocked: true,
12931                        ..Default::default()
12932                    }],
12933                    false,
12934                ));
12935            }
12936        }
12937    } else {
12938        None
12939    };
12940    let cache_dir = planned_target.as_deref().or(cache_dir);
12941    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12942    let guard = if let Some(cache_dir) = cache_dir {
12943        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12944        match acquire_cache_lease(
12945            state,
12946            cache_dir,
12947            &owner,
12948            resource_limit,
12949            node,
12950            context,
12951            &|| wait.cancelled(),
12952        )
12953        .await
12954        .and_then(|g| {
12955            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12956        }) {
12957            Ok(g) => Some(g),
12958            Err(e) => {
12959                record_cache_error(state, node, &e);
12960                return Ok((
12961                    vec![CommandOutcome {
12962                        command: if isolated {
12963                            "(waiting for the isolated build cache)"
12964                        } else {
12965                            "(waiting for the shared build cache)"
12966                        }
12967                        .into(),
12968                        code: None,
12969                        output_tail: e.to_string(),
12970                        duration_ms: started.elapsed().as_millis() as u64,
12971                        resource_blocked: true,
12972                        ..Default::default()
12973                    }],
12974                    false,
12975                ));
12976            }
12977        }
12978    } else {
12979        None
12980    };
12981    let _coordination = coordinate_operation(state, worktree, wait).await?;
12982    if let Some(path) = &planned_target {
12983        state.event(node, format!("isolated build target: {}", path.display()));
12984    }
12985    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12986        let identity = crate::cache::Identity::new(worktree, head);
12987        let fresh = crate::cache::ensure_fresh(
12988            &home,
12989            cache_dir,
12990            &identity,
12991            &state.config.verify.cargo_manifests(),
12992        );
12993        if let Err(e) = fresh {
12994            record_cache_error(state, node, &e);
12995            state.event(
12996                "verify",
12997                format!(
12998                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12999                    worktree.display(),
13000                    short(head)
13001                ),
13002            );
13003            if let Some(guard) = guard {
13004                guard.release();
13005            }
13006            return Ok((
13007                vec![CommandOutcome {
13008                    command: "(confirming the build cache is fresh)".into(),
13009                    code: None,
13010                    output_tail: e.to_string(),
13011                    duration_ms: started.elapsed().as_millis() as u64,
13012                    resource_blocked: true,
13013                    ..Default::default()
13014                }],
13015                false,
13016            ));
13017        }
13018    }
13019    let future = body(state, budget);
13020    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
13021        VERIFY_TARGET.scope(target, future).await
13022    } else {
13023        future.await
13024    };
13025    if !timed_out_pids.is_empty() {
13026        wait_for_timed_out_children_to_die(&timed_out_pids).await;
13027    }
13028    // Drop repository coordination before releasing the cache, reversing the
13029    // acquisition order. A cancelled/error future also drops both guards.
13030    drop(_coordination);
13031    if let Some(guard) = guard {
13032        guard.release();
13033    }
13034    Ok((outcomes, retried))
13035}
13036
13037/// Poll `pids` — commands [`run_commands`] reports as still running when its
13038/// own timeout elapsed — until every one is confirmed gone, or
13039/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
13040///
13041/// Real confirmation where confirmation is possible, not a substitute for
13042/// full process-tree observation: a grandchild the timed-out process spawned
13043/// and that survives independently of it is invisible to a pid check the
13044/// same way it always was, and continuing to observe and collect *that*
13045/// stays a different piece of work with its own owner. This only narrows a
13046/// fixed blind wait into an actual check of the pids this process does know
13047/// about.
13048async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
13049    wait_for_pids_with(
13050        pids,
13051        crate::proc::pid_alive,
13052        LEASE_RELEASE_POLL,
13053        LEASE_RELEASE_MAX_WAIT,
13054    )
13055    .await;
13056}
13057
13058/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
13059/// interval and ceiling supplied by the caller, so the polling *logic* -
13060/// returns as soon as every pid reports dead, gives up at the ceiling
13061/// otherwise - is testable on millisecond durations without asking the real
13062/// OS about a pid at all.
13063async fn wait_for_pids_with<F: Fn(u32) -> bool>(
13064    pids: &[u32],
13065    alive: F,
13066    poll: Duration,
13067    max_wait: Duration,
13068) {
13069    let deadline = Instant::now() + max_wait;
13070    loop {
13071        if pids.iter().all(|&pid| !alive(pid)) {
13072            return;
13073        }
13074        if Instant::now() >= deadline {
13075            return;
13076        }
13077        tokio::time::sleep(poll).await;
13078    }
13079}
13080
13081/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
13082/// admission that it could not even get a verify command to run, as opposed
13083/// to evidence the command actually produced? A caller that would otherwise
13084/// read a resource-blocked outcome as a red command must check this first:
13085/// see [`Runner::gate`], which retries rather than records `Blocked` when
13086/// this is true.
13087fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
13088    outcomes.iter().any(|o| o.resource_blocked)
13089}
13090
13091/// What [`Runner::gate_fix_round`] decided.
13092pub(crate) enum GateFix {
13093    /// The tree changed and `verify.e2e` is still green: run the gate again.
13094    Retry,
13095    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
13096    /// last failure stands and the run ends blocked.
13097    Stop,
13098    /// `verify.e2e` could not run after the fix (magi's own contention):
13099    /// decide nothing now, a later reentry retries.
13100    Defer,
13101}
13102
13103/// Is every red command in `outcomes` an ordinary failure the code could
13104/// explain: it ran, exited non-zero, and said something?
13105///
13106/// A timeout, a spawn failure and a killed process all leave `code` `None`;
13107/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
13108/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
13109/// what the command is stays the gate's business.
13110pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
13111    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13112    red.peek().is_some()
13113        && red.all(|o| {
13114            !o.resource_blocked
13115                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13116                && !o.output_tail.trim().is_empty()
13117        })
13118}
13119
13120/// Describe one verify command's outcome for the event log, distinguishing a
13121/// build/link failure — the toolchain never produced a binary to run — from
13122/// an actual test failure, since only the latter is a verdict on the patch.
13123fn e2e_outcome_label(o: &CommandOutcome) -> String {
13124    if o.ok() {
13125        return "pass".to_owned();
13126    }
13127    let reason = if o.build_failed() {
13128        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
13129    } else {
13130        format!("FAIL ({:?})", o.code)
13131    };
13132    format!(
13133        "{reason}\n{}",
13134        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13135    )
13136}
13137
13138/// Does `outcomes` hold a failure worth one more run on the same commit?
13139///
13140/// Only an ordinary test result qualifies: every red command ran, exited
13141/// non-zero and said which way (not a build/link failure, a timeout or kill,
13142/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
13143/// evidence about the machine or the toolchain, never about a flaky test.
13144fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
13145    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13146    red.peek().is_some()
13147        && !verify_inconclusive(outcomes)
13148        && red.all(|o| {
13149            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13150        })
13151}
13152
13153/// Run `verify.e2e`, retrying once if the first attempt could not build or
13154/// link — a build/link failure is frequently a race against a shared
13155/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
13156/// `verify` event per command, tagged with `context` (normally `"round N"`)
13157/// so the call sites that need this — the ordinary per-round leg in
13158/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
13159/// will ever call a round green, `verify_current_head` and the gate-repair
13160/// check — read identically in the event log.
13161///
13162/// A failure that is a test result (see [`rerunnable_failure`]) is believed
13163/// only after the failed commands have run once more on the same commit, in
13164/// the same worktree and — because the caller holds it around this whole
13165/// function — under the same cache lease, with a full `timeout` of their own
13166/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
13167/// flake: the head is verified, the first failure is recorded and filed
13168/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
13169/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
13170/// preserving bounded evidence and artifact references for both attempts;
13171/// it claims a matching reproduction only when both attempts yield identical
13172/// confirmed terminal test failures. One verification is therefore run at most
13173/// three times: the build/link retry, then this one rerun. `round` is the
13174/// review round the verification belongs to, if any.
13175async fn run_e2e_with_retry(
13176    state: &mut RunState,
13177    shell: &[String],
13178    commands: &[String],
13179    worktree: &Path,
13180    timeout: Duration,
13181    context: &str,
13182    round: Option<usize>,
13183) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
13184    let (mut e2e, mut timed_out_pids) = run_commands(
13185        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
13186    )
13187    .await;
13188    for o in &e2e {
13189        state.event(
13190            "verify",
13191            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
13192        );
13193    }
13194    // A build/link failure is not a verdict on the patch — it is frequently a
13195    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
13196    // one retry before letting a red like that decide the round.
13197    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
13198    if verify_retried {
13199        state.event(
13200            "verify",
13201            format!(
13202                "{context}: verify could not build/link, not a test result — retrying once \
13203                 before concluding"
13204            ),
13205        );
13206        let retried = run_commands(
13207            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
13208        )
13209        .await;
13210        e2e = retried.0;
13211        // Both attempts' timeouts matter, not just the last one: the first
13212        // attempt's descendants may still be alive alongside the retry's.
13213        timed_out_pids.extend(retried.1);
13214        for o in &e2e {
13215            state.event(
13216                "verify",
13217                format!(
13218                    "{context}: retry `{}` -> {}",
13219                    o.command,
13220                    e2e_outcome_label(o)
13221                ),
13222            );
13223        }
13224    }
13225    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
13226        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
13227        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
13228        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
13229        state.event(
13230            "verify",
13231            format!(
13232                "{context}: {} failed with a test result — running it once more on the same \
13233                 commit {} before deciding",
13234                rerun_commands
13235                    .iter()
13236                    .map(|c| format!("`{c}`"))
13237                    .collect::<Vec<_>>()
13238                    .join(", "),
13239                short(&head)
13240            ),
13241        );
13242        let (second, pids) = run_commands(
13243            state,
13244            "verify",
13245            "e2e",
13246            1 + usize::from(verify_retried),
13247            shell,
13248            &rerun_commands,
13249            worktree,
13250            timeout,
13251        )
13252        .await;
13253        timed_out_pids.extend(pids);
13254        for o in &second {
13255            state.event(
13256                "verify",
13257                format!(
13258                    "{context}: rerun `{}` -> {}",
13259                    o.command,
13260                    e2e_outcome_label(o)
13261                ),
13262            );
13263        }
13264        for (slot, &i) in failed.iter().enumerate() {
13265            let Some(again) = second.get(slot) else {
13266                break;
13267            };
13268            let first = std::mem::replace(&mut e2e[i], again.clone());
13269            if again.ok() {
13270                let signature = crate::flake::signature(&first.output_tail, first.code);
13271                let flake = crate::run::VerifyFlake {
13272                    round,
13273                    context: context.to_owned(),
13274                    head: head.clone(),
13275                    command: first.command.clone(),
13276                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
13277                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
13278                    at: Timestamp::now(),
13279                    task: None,
13280                    filed: false,
13281                    filing_error: None,
13282                };
13283                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
13284            } else if !again.resource_blocked {
13285                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
13286                let message = crate::verify_evidence::rerun_event_message(
13287                    context,
13288                    &e2e[i].command,
13289                    &comparison,
13290                );
13291                e2e[i].rerun_comparison = Some(comparison);
13292                state.event("verify", message);
13293            }
13294        }
13295    }
13296    (e2e, verify_retried, timed_out_pids)
13297}
13298
13299/// Run configured shell commands in `cwd`, in order. The second element is
13300/// the pid of every command that hit `timeout` and was still running when
13301/// this stopped waiting on it (best-effort: `None` when the platform did not
13302/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13303/// that releases a shared resource afterward needs to know.
13304///
13305/// Records `task` into [`RunState::active`] at every command boundary
13306/// (`RunState::task_command`) and clears it once the whole list has run
13307/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13308/// for minutes with no seat and no output of its own to show for it (see
13309/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13310/// apart from "not yet run" without this), and this is the only place that
13311/// knows which command is running right now and how many are left. Three
13312/// saves per command — start, not per second — matching the same "only at a
13313/// boundary" rule [`wave`] already follows for seats.
13314#[allow(clippy::too_many_arguments)]
13315async fn run_commands(
13316    state: &mut RunState,
13317    node: &str,
13318    task: &str,
13319    attempt: usize,
13320    shell: &[String],
13321    commands: &[String],
13322    cwd: &Path,
13323    timeout: Duration,
13324) -> (Vec<CommandOutcome>, Vec<u32>) {
13325    let isolated = crate::build_target::isolated(&state.config);
13326    if isolated && let Some(block) = &state.resource_block {
13327        return (
13328            vec![CommandOutcome {
13329                command: "(isolated build admission)".into(),
13330                code: None,
13331                output_tail: block.description(),
13332                duration_ms: 0,
13333                resource_blocked: true,
13334                ..Default::default()
13335            }],
13336            Vec::new(),
13337        );
13338    }
13339    if commands.is_empty() {
13340        // Nothing to mark as running and nothing to clear — an empty list
13341        // means "not configured", and touching `active` (or the disk) over
13342        // that would be a write for every round of a repo with no
13343        // `verify.e2e` / `verify.gate` commands at all.
13344        return (Vec::new(), Vec::new());
13345    }
13346    let mut out = Vec::new();
13347    let mut timed_out_pids = Vec::new();
13348    let total = commands.len();
13349    for (idx, command) in commands.iter().enumerate() {
13350        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13351        if let Err(e) = state.save() {
13352            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13353        }
13354        let started = Instant::now();
13355        let mut cmd = tokio::process::Command::new(&shell[0]);
13356        cmd.quiet();
13357        // Verify the checkout as a standalone caller. Worker ownership and
13358        // pinned executable selection belong to this driver, not to tests or
13359        // tools it runs. Preserve home/seat context and Running's containment.
13360        for key in crate::worker::INVOCATION_ENV {
13361            cmd.env_remove(key);
13362        }
13363        cmd.env_remove(crate::build_id::EXPECT_ENV);
13364        cmd.args(&shell[1..])
13365            .current_dir(cwd)
13366            .stdin(std::process::Stdio::null())
13367            .stdout(std::process::Stdio::piped())
13368            .stderr(std::process::Stdio::piped())
13369            .kill_on_drop(true);
13370        let mut outputs = Vec::new();
13371        let mut cache = None;
13372        let home = crate::run::home();
13373        let head = if isolated {
13374            Some(git::rev_parse(cwd, "HEAD").await)
13375        } else {
13376            None
13377        };
13378        let protected = (|| -> Result<()> {
13379            crate::incremental::configure(&mut cmd, cwd)?;
13380            cache = if isolated {
13381                let target = VERIFY_TARGET
13382                    .try_with(Clone::clone)
13383                    .context("isolated verification has no target lease")?;
13384                cmd.arg(crate::build_target::command::normalize(command)?);
13385                crate::build_target::command::configure(&mut cmd, &target)?;
13386                Some(target)
13387            } else {
13388                crate::build_target::command::clear(&mut cmd)?;
13389                cmd.arg(command);
13390                state.config.cache_dir()
13391            };
13392            let mut paths = vec![cwd.to_owned()];
13393            if let Some(cache) = &cache {
13394                paths.push(cache.clone());
13395            }
13396            let admit = if isolated {
13397                crate::retention::OutputLease::admit_isolated
13398            } else {
13399                crate::retention::OutputLease::admit
13400            };
13401            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13402            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13403                outputs.push(guard);
13404            }
13405            if let Some(cache) = &cache {
13406                outputs.push(crate::retention::OutputLease::cache(
13407                    &crate::run::home(),
13408                    cache,
13409                    false,
13410                )?);
13411                if let Some(head) = head {
13412                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13413                    if task == "pre_gate" {
13414                        crate::cache::invalidate_identity(&home, cache);
13415                    }
13416                }
13417            }
13418            Ok(())
13419        })();
13420        if let Err(e) = protected {
13421            let detail = format!("execution admission unavailable: {e:#}");
13422            state.resource_block = Some(crate::run::ResourceBlock {
13423                cause: crate::run::ResourceBlockCause::Other,
13424                node: node.to_owned(),
13425                kind: if detail.contains("disk admission") {
13426                    "disk admission"
13427                } else {
13428                    "output ownership"
13429                }
13430                .to_owned(),
13431                detail: detail.clone(),
13432                at: Timestamp::now(),
13433            });
13434            out.push(CommandOutcome {
13435                command: command.clone(),
13436                code: None,
13437                output_tail: detail,
13438                duration_ms: 0,
13439                resource_blocked: true,
13440                ..Default::default()
13441            });
13442            break;
13443        }
13444        let spawned = if isolated {
13445            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13446        } else {
13447            crate::seat_process::Running::spawn(cmd, None, outputs)
13448        };
13449        let (code, out_text, err_text, body) = match spawned {
13450            Ok(mut running) => {
13451                let pid = running.child().id();
13452                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13453                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13454                let mut paths = vec![cwd.to_owned()];
13455                if let Some(cache) = cache {
13456                    paths.push(cache);
13457                }
13458                let mut pressure = None;
13459                let status = tokio::select! {
13460                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13461                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13462                        pressure = Some(reason); None
13463                    }
13464                };
13465                let (code, failure) = match status {
13466                    Some(Ok(Ok(status))) => (
13467                        status.code(),
13468                        status
13469                            .code()
13470                            .is_none()
13471                            .then(|| format!("command terminated: {status}")),
13472                    ),
13473                    Some(Ok(Err(error))) => {
13474                        (None, Some(format!("failed waiting for command: {error}")))
13475                    }
13476                    Some(Err(_)) => {
13477                        // Leased cleanup confirms process-tree death itself.
13478                        // Unleased commands still need the caller's PID check
13479                        // after kill-on-drop, before releasing cache ownership.
13480                        if !running.coordinated()
13481                            && let Some(pid) = pid
13482                        {
13483                            timed_out_pids.push(pid);
13484                        }
13485                        (
13486                            None,
13487                            Some(format!("timed out after {}s", timeout.as_secs())),
13488                        )
13489                    }
13490                    None => (None, None),
13491                };
13492                running.finish().await;
13493                if let Some(reason) = pressure {
13494                    state.resource_block = Some(crate::run::ResourceBlock {
13495                        cause: crate::run::ResourceBlockCause::Other,
13496                        node: node.to_owned(),
13497                        kind: "disk pressure".to_owned(),
13498                        detail: reason.clone(),
13499                        at: Timestamp::now(),
13500                    });
13501                    out.push(CommandOutcome {
13502                        command: command.clone(),
13503                        code: None,
13504                        output_tail: reason,
13505                        duration_ms: started.elapsed().as_millis() as u64,
13506                        resource_blocked: true,
13507                        ..Default::default()
13508                    });
13509                    break;
13510                }
13511                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13512                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13513                let mut body = out_text.clone();
13514                body.push_str(&err_text);
13515                if let Some(failure) = failure {
13516                    body.push('\n');
13517                    body.push_str(&failure);
13518                }
13519                (code, out_text, err_text, body)
13520            }
13521            Err(e) if isolated => {
13522                let e = anyhow::Error::new(e)
13523                    .context(format!("could not start managed build `{}`", shell[0]));
13524                record_cache_error(state, node, &e);
13525                out.push(CommandOutcome {
13526                    command: command.clone(),
13527                    code: None,
13528                    output_tail: format!("{e:#}"),
13529                    duration_ms: 0,
13530                    resource_blocked: true,
13531                    ..Default::default()
13532                });
13533                break;
13534            }
13535            Err(e) => (
13536                None,
13537                String::new(),
13538                String::new(),
13539                format!("failed to spawn `{}`: {e}", shell[0]),
13540            ),
13541        };
13542        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13543        let mut artifact = None;
13544        if !body.is_empty() {
13545            // The full text is kept whatever the summary dropped. A fresh
13546            // name per command so a resume or retry never overwrites an
13547            // earlier run's output. A failed write changes no verdict.
13548            match crate::run::write_verification_artifact(state, task, &body) {
13549                Ok(name) => {
13550                    let rel = format!("artifacts/{name}");
13551                    if summary != body {
13552                        summary = format!("[full output: {rel}]\n{summary}");
13553                    }
13554                    artifact = Some(rel);
13555                }
13556                Err(e) => {
13557                    let warning = format!("could not save the full {task} output: {e:#}");
13558                    tracing::warn!("{warning}");
13559                    state.event(node, warning);
13560                    if summary != body {
13561                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13562                    }
13563                }
13564            }
13565        }
13566        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13567        let mut outcome = CommandOutcome {
13568            command: command.clone(),
13569            code,
13570            output_tail: summary,
13571            duration_ms: started.elapsed().as_millis() as u64,
13572            resource_blocked,
13573            artifact,
13574            failure_evidence: None,
13575            rerun_comparison: None,
13576        };
13577        if !outcome.ok() && !outcome.resource_blocked {
13578            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13579                code,
13580                outcome.build_failed(),
13581                &out_text,
13582                &err_text,
13583            ));
13584        }
13585        out.push(outcome);
13586        if resource_blocked {
13587            state.resource_block = Some(crate::run::ResourceBlock {
13588                cause: crate::run::ResourceBlockCause::Other,
13589                node: node.to_owned(),
13590                kind: "incremental cache admission".into(),
13591                detail: body,
13592                at: Timestamp::now(),
13593            });
13594            break;
13595        }
13596    }
13597    state.task_finished(task);
13598    if let Err(e) = state.save() {
13599        tracing::warn!("could not persist the end of {task}: {e:#}");
13600    }
13601    (out, timed_out_pids)
13602}
13603
13604/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13605/// section (`report::run`) and in the `merge` event this node records — for
13606/// the operator to run by hand.
13607///
13608/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13609/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13610/// merge commits", or "require linear history") rejects the push a `--no-ff`
13611/// merge would produce, which is exactly the guidance this function replaces.
13612/// `message`'s first line becomes the squash commit's subject, matching the
13613/// note `report::run` prints alongside this command — see that function for
13614/// why an explicit subject is not optional there.
13615fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13616    let repo = repo.display();
13617    match style {
13618        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13619        MergeStyle::Squash => {
13620            // The subject sits inside double quotes, and a title an agent
13621            // wrote may carry the characters that break out of them.
13622            let subject = message
13623                .lines()
13624                .next()
13625                .unwrap_or(branch)
13626                .replace(['\\', '"', '$', '`'], "");
13627            format!(
13628                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13629            )
13630        }
13631        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13632    }
13633}
13634
13635/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13636/// under the hood, rejects a `title` over 256 characters and the whole
13637/// command fails — no PR at all, for a run whose body was otherwise fine
13638/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13639/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13640/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13641/// this bound. It is a margin, not a guarantee — a title packed
13642/// with multi-unit characters could still in principle land close to the
13643/// edge, but a real task title's occasional emoji or accented letter fits
13644/// comfortably inside it.
13645const PR_TITLE_MAX: usize = 240;
13646
13647/// A pull request title from the opening line of `text`, or `None` when that
13648/// line is not English (GitHub text is) or has no letters.
13649///
13650/// A line within `max` is kept as is. A longer one is cut at the end of its
13651/// first sentence when that falls inside `max`, else at a word boundary with a
13652/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13653/// make every merely-truncated title look non-English). The language check
13654/// runs on the kept text before any mark is added, so only what GitHub will
13655/// show is judged: an English opening followed by non-ASCII far past the cut
13656/// still passes.
13657fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13658    let line = queue::first_line(text)?;
13659    let chars: Vec<char> = line.chars().collect();
13660    let (kept, mark) = if chars.len() <= max {
13661        (line.to_owned(), "")
13662    } else if let Some(end) = sentence_end(&chars, max) {
13663        (chars[..end].iter().collect::<String>(), "")
13664    } else {
13665        let room = max.saturating_sub(3);
13666        // Cut at the last space inside the room; when the char just past the
13667        // room is a space the room already ends on a word.
13668        let cut = if chars[room].is_whitespace() {
13669            room
13670        } else {
13671            chars[..room]
13672                .iter()
13673                .rposition(|c| c.is_whitespace())
13674                .unwrap_or(room)
13675        };
13676        let head: String = chars[..cut].iter().collect();
13677        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13678        (head.to_owned(), "...")
13679    };
13680    if kept.is_empty() {
13681        return None;
13682    }
13683    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13684        return None;
13685    }
13686    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13687        return None;
13688    }
13689    Some(format!("{kept}{mark}"))
13690}
13691
13692/// The char length of the first sentence of `chars` when it ends within `max`
13693/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13694/// abbreviations so `e.g. foo` does not end a title early.
13695fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13696    const MIN: usize = 20;
13697    for i in MIN..max.min(chars.len()) {
13698        if !matches!(chars[i], '.' | '!' | '?') {
13699            continue;
13700        }
13701        let Some(&next) = chars.get(i + 1) else {
13702            continue;
13703        };
13704        if !next.is_whitespace() {
13705            continue;
13706        }
13707        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13708        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13709            continue;
13710        }
13711        let word: String = chars[..i]
13712            .iter()
13713            .rev()
13714            .take_while(|c| !c.is_whitespace())
13715            .collect::<Vec<_>>()
13716            .into_iter()
13717            .rev()
13718            .collect();
13719        let word = word.to_ascii_lowercase();
13720        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13721            continue;
13722        }
13723        let end = chars[..i]
13724            .iter()
13725            .rposition(|c| !c.is_whitespace())
13726            .map_or(i, |p| p + 1);
13727        return Some(end);
13728    }
13729    None
13730}
13731
13732/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13733/// change: a title and a body describing what was *implemented*, not the task
13734/// that asked for it. A task reads as a request; a reader of the merged
13735/// history wants the change.
13736struct PrMessage {
13737    title: String,
13738    body: String,
13739}
13740
13741impl PrMessage {
13742    /// Title, blank line, body. The first line is the squash/merge commit
13743    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13744    /// has to stay one sensible line.
13745    fn commit_message(&self) -> String {
13746        format!("{}\n\n{}", self.title, self.body)
13747    }
13748}
13749
13750/// The text after a leading `TITLE:` (any case) on `line`.
13751fn title_marker(line: &str) -> Option<&str> {
13752    let line = line.trim();
13753    let head = line.get(..6)?;
13754    head.eq_ignore_ascii_case("title:")
13755        .then(|| line[6..].trim())
13756}
13757
13758/// The implementer's own one-line title: the `TITLE:` line the implement
13759/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13760/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13761/// source, and a title that says as much is refused here too.
13762fn summary_title(summary: &str) -> Option<String> {
13763    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13764    let raw = title_marker(first)?;
13765    if raw.is_empty() {
13766        return None;
13767    }
13768    let title = queue::title_from(raw, PR_TITLE_MAX);
13769    let lower = title.to_ascii_lowercase();
13770    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13771        return None;
13772    }
13773    Some(title)
13774}
13775
13776/// How `open_review`'s instruction begins; see [`landing_title`].
13777const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13778
13779/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13780pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13781
13782/// Does this run review work that already existed, rather than implement a
13783/// task? Runs recorded before `reviewed_commits` existed carry only the
13784/// candidate marker.
13785pub(crate) fn is_review_run(state: &RunState) -> bool {
13786    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13787}
13788
13789/// The title of a review-only run: the subject of the oldest commit under
13790/// review. Later commits are usually fixups, and `instruction` is the review
13791/// prompt, which says nothing about the change. GitHub text is English, so a
13792/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13793fn review_title(state: &RunState) -> Option<String> {
13794    english_subject(
13795        state.reviewed_commits.as_ref()?.first()?,
13796        state.config.graph.github_english(),
13797    )
13798}
13799
13800/// `raw` as a pull request title, or `None` when it is blank, not English
13801/// (GitHub text is), or one of magi's own candidate commit subjects.
13802fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13803    let raw = raw.trim();
13804    if raw.is_empty() {
13805        return None;
13806    }
13807    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13808        return None;
13809    }
13810    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13811        return None;
13812    }
13813    let title = queue::title_from(raw, PR_TITLE_MAX);
13814    let lower = title.to_ascii_lowercase();
13815    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13816        return None;
13817    }
13818    Some(title)
13819}
13820
13821/// What a review-only run's branch says about itself, read at the moment the
13822/// pull request is opened.
13823#[derive(Debug, Clone, PartialEq, Eq)]
13824struct BranchFacts {
13825    /// `(subject, body)` of each commit, oldest first.
13826    commits: Vec<(String, String)>,
13827    /// Trimmed `git diff --stat`.
13828    stat: String,
13829}
13830
13831/// Longest diff stat shown: this many file lines plus the summary line.
13832const STAT_FILE_LINES: usize = 25;
13833/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13834const COMMITS_MAX_CHARS: usize = 20_000;
13835
13836/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13837/// say or finds nothing, so the caller falls back to what the run recorded.
13838async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13839    let commits = git::commit_log(repo, base, branch).await.ok()?;
13840    if commits.is_empty() {
13841        return None;
13842    }
13843    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13844    let lines: Vec<&str> = stat.lines().collect();
13845    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13846        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13847        let more = format!(" ... {omitted} more file(s)");
13848        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13849        kept.push(&more);
13850        kept.push(lines[lines.len() - 1]);
13851        kept.join("\n")
13852    } else {
13853        lines.join("\n")
13854    };
13855    Some(BranchFacts { commits, stat })
13856}
13857
13858/// Defang what would break the surrounding markdown: a closing `</details>`
13859/// and a code fence.
13860fn markdown_safe(text: &str) -> String {
13861    text.replace("</details>", "&lt;/details&gt;")
13862        .replace("\x60\x60\x60", "~~~")
13863}
13864
13865fn neutral_title(state: &RunState, winner: char) -> String {
13866    format!(
13867        "chore: land candidate {} of run {}",
13868        winner.to_ascii_uppercase(),
13869        state.id
13870    )
13871}
13872
13873/// Reuse the graph's bounded fixer without starting another graph or driver.
13874/// Copy the working state back even on errors so spent rounds remain visible.
13875pub(crate) async fn repair_landing_gate(
13876    state: &mut RunState,
13877    winner: &Candidate,
13878    outcomes: &[CommandOutcome],
13879) -> Result<GateFix> {
13880    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13881        return Ok(GateFix::Stop);
13882    }
13883    let mut runner = Runner {
13884        roles: state.config.resolve_roles()?,
13885        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13886        state: state.clone(),
13887        pause: Pause::new(),
13888        interrupt: Pause::new(),
13889    };
13890    let result = runner.gate_fix_round(winner, outcomes).await;
13891    *state = runner.state;
13892    result
13893}
13894
13895/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13896/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13897pub(crate) async fn verify_current_head(
13898    state: &mut RunState,
13899    winner: &Candidate,
13900    wait: &crate::repo_lock::WaitPolicy,
13901) -> Result<bool> {
13902    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13903    // Preserve the previous record before replacing it, including on crash recovery.
13904    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13905        state
13906            .verification_history
13907            .push(crate::run::VerificationEvidence {
13908                superseded_by: Some(head.clone()),
13909                archived_at: Some(Timestamp::now()),
13910                fixes_spent: Some(state.gate_fixes.len()),
13911                gate_head: None,
13912                gate_ran: false,
13913                gate: Vec::new(),
13914                e2e: state.head_e2e.take(),
13915            });
13916    }
13917    if let Some(e) = &state.head_e2e
13918        && e.head == head
13919    {
13920        if e.passed {
13921            return Ok(true);
13922        }
13923        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13924            state.status = RunStatus::Blocked;
13925            state.save()?;
13926            return Ok(false);
13927        }
13928    } else if state.reviews.last().is_some_and(|r| {
13929        r.verified_head.as_deref() == Some(head.as_str())
13930            && (r.e2e_status() == E2eStatus::Passed
13931                || (r.e2e_status() == E2eStatus::NotConfigured
13932                    && state.config.verify.e2e.is_empty()))
13933    }) || state
13934        .gate_repair_e2e
13935        .as_ref()
13936        .is_some_and(|e| e.head == head && e.passed)
13937    {
13938        return Ok(true);
13939    }
13940    if let Some(e) = &state.gate_repair_e2e
13941        && e.head == head
13942        && !e.passed
13943        && !e.outcomes.is_empty()
13944        && !verify_inconclusive(&e.outcomes)
13945    {
13946        state.status = RunStatus::Blocked;
13947        state.save()?;
13948        return Ok(false);
13949    }
13950    // Bind the result to the base used by the candidate, not a tracking ref
13951    // that the background fetch can advance independently of verification.
13952    let base_commit = state
13953        .base_sync
13954        .as_ref()
13955        .map(|s| s.tip.clone())
13956        .filter(|tip| !tip.is_empty())
13957        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13958    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13959        head.clone(),
13960        false,
13961        Vec::new(),
13962    ));
13963    state.save()?;
13964    let commands = state.config.verify.e2e.clone();
13965    let shell = state.config.shell();
13966    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13967    let cache_dir = state.config.cache_dir();
13968    let outcomes = if commands.is_empty() {
13969        Vec::new()
13970    } else {
13971        let (outcomes, _) = with_cache_lease(
13972            state,
13973            cache_dir.as_deref(),
13974            "e2e",
13975            "e2e",
13976            &winner.worktree,
13977            &head,
13978            timeout,
13979            "current head e2e",
13980            wait,
13981            |state, budget| async move {
13982                run_e2e_with_retry(
13983                    state,
13984                    &shell,
13985                    &commands,
13986                    &winner.worktree,
13987                    budget,
13988                    "current head e2e",
13989                    None,
13990                )
13991                .await
13992            },
13993        )
13994        .await?;
13995        outcomes
13996    };
13997    let unresolved = verify_inconclusive(&outcomes);
13998    let passed = !unresolved
13999        && outcomes.iter().all(CommandOutcome::ok)
14000        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14001    if !outcomes.is_empty() && !unresolved {
14002        state.record_base_progress(&head);
14003    }
14004    let generation = Some(state.verification_history.len());
14005    let pass = state.passes.last().map(|p| p.index);
14006    let recorded_at = Some(Timestamp::now());
14007    let resumption_generation = state.entry_resumption_generation;
14008    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
14009    record.base_commit = base_commit;
14010    record.generation = generation;
14011    record.pass = pass;
14012    record.recorded_at = recorded_at;
14013    record.resumption_generation = resumption_generation;
14014    if !passed && !unresolved {
14015        let detail = state
14016            .head_e2e
14017            .as_ref()
14018            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14019            .map(|d| format!(" ({d})"))
14020            .unwrap_or_default();
14021        state.status = RunStatus::Blocked;
14022        state.event(
14023            "e2e",
14024            format!("verify.e2e failed on head {head}{detail}; nothing published"),
14025        );
14026        record.recorded_events = Some(state.events.len());
14027    }
14028    state.head_e2e = Some(record);
14029    state.save()?;
14030    Ok(passed)
14031}
14032
14033/// Recheck a repair's e2e requirement across failures, resource deferrals and
14034/// process interruptions. A successful result only applies to its exact SHA.
14035pub(crate) async fn check_gate_repair_e2e(
14036    state: &mut RunState,
14037    winner: &Candidate,
14038    wait: &crate::repo_lock::WaitPolicy,
14039) -> Result<GateFix> {
14040    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
14041        return Ok(GateFix::Retry);
14042    }
14043    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14044    if let Some(record) = &state.gate_repair_e2e
14045        && record.head == head
14046    {
14047        if record.passed {
14048            return Ok(GateFix::Retry);
14049        }
14050        if !record.outcomes.is_empty()
14051            && record.outcomes.iter().all(|o| {
14052                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
14053            })
14054        {
14055            return Ok(GateFix::Stop);
14056        }
14057    }
14058    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
14059        head.clone(),
14060        false,
14061        Vec::new(),
14062    ));
14063    state.save()?;
14064    let commands = state.config.verify.e2e.clone();
14065    let outcomes = if commands.is_empty() {
14066        Vec::new()
14067    } else {
14068        let shell = state.config.shell();
14069        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14070        let cache_dir = state.config.cache_dir();
14071        let (outcomes, _) = with_cache_lease(
14072            state,
14073            cache_dir.as_deref(),
14074            "e2e",
14075            "e2e",
14076            &winner.worktree,
14077            &head,
14078            timeout,
14079            "gate repair e2e",
14080            wait,
14081            |state, budget| async move {
14082                run_e2e_with_retry(
14083                    state,
14084                    &shell,
14085                    &commands,
14086                    &winner.worktree,
14087                    budget,
14088                    "gate repair e2e",
14089                    None,
14090                )
14091                .await
14092            },
14093        )
14094        .await?;
14095        outcomes
14096    };
14097    let deferred = verify_inconclusive(&outcomes);
14098    let passed = outcomes.iter().all(CommandOutcome::ok)
14099        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14100    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
14101    state.save()?;
14102    if deferred {
14103        Ok(GateFix::Defer)
14104    } else if !passed {
14105        let detail = state
14106            .gate_repair_e2e
14107            .as_ref()
14108            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14109            .map(|d| format!(" ({d})"))
14110            .unwrap_or_default();
14111        state.event(
14112            "gate",
14113            format!("verify.e2e failed after gate repair{detail}; nothing published"),
14114        );
14115        Ok(GateFix::Stop)
14116    } else {
14117        Ok(GateFix::Retry)
14118    }
14119}
14120
14121/// Run the same configured gate for a landing head and a fresh graph.
14122pub(crate) async fn run_landing_gate(
14123    state: &mut RunState,
14124    winner: &Candidate,
14125    wait: &crate::repo_lock::WaitPolicy,
14126) -> Result<Vec<CommandOutcome>> {
14127    let shell = state.config.shell();
14128    let gate_commands = state.config.verify.gate.clone();
14129    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
14130    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
14131        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
14132        Vec::new()
14133    } else {
14134        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14135        let cache_dir = state.config.cache_dir();
14136        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14137        let (outcomes, _) = with_cache_lease(
14138            state,
14139            cache_dir.as_deref(),
14140            "gate",
14141            "gate",
14142            &winner.worktree,
14143            &head,
14144            timeout,
14145            "final gate",
14146            wait,
14147            |state, budget| {
14148                let shell = shell.clone();
14149                let gate_commands = gate_commands.clone();
14150                let winner = winner.clone();
14151                async move {
14152                    Runner::run_pre_gate(state, &winner).await;
14153                    // Bind command evidence after mechanical fixes, before commands start.
14154                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
14155                    let (outcomes, timed_out_pids) = run_commands(
14156                        state,
14157                        "gate",
14158                        "gate",
14159                        0,
14160                        &shell,
14161                        &gate_commands,
14162                        &winner.worktree,
14163                        budget,
14164                    )
14165                    .await;
14166                    (outcomes, false, timed_out_pids)
14167                }
14168            },
14169        )
14170        .await?;
14171        outcomes
14172    };
14173    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
14174    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
14175        let mut outcomes = outcomes;
14176        outcomes.push(CommandOutcome {
14177            command: "gate head stability".into(), code: None,
14178            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
14179            duration_ms: 0, resource_blocked: false,
14180            ..Default::default()
14181        });
14182        return Ok(outcomes);
14183    }
14184    if outcomes.is_empty() {
14185        // Nothing configured to check — distinct from every other
14186        // silence in this run's event log, since an empty `gate` alone
14187        // no longer says whether the gate ran at all (see
14188        // `RunState::gate_ran`'s own doc).
14189        state.event("gate", "no gate commands configured; not tested");
14190    }
14191    for o in &outcomes {
14192        state.event(
14193            "gate",
14194            format!(
14195                "`{}` -> {}",
14196                o.command,
14197                if o.ok() {
14198                    "pass".to_owned()
14199                } else {
14200                    format!(
14201                        "FAIL ({:?})\n{}",
14202                        o.code,
14203                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
14204                    )
14205                }
14206            ),
14207        );
14208    }
14209    Ok(outcomes)
14210}
14211
14212/// The pull request title to hand to `land::merge_subject`. A review-only run
14213/// opened by an earlier build titled its pull request with the review prompt;
14214/// that title is dropped (empty, so the fallback applies) rather than landed.
14215/// Any other title, including an operator's rename, passes through untouched,
14216/// and so does every title of a run that implements a task.
14217pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
14218    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
14219        ""
14220    } else {
14221        pr_title
14222    }
14223}
14224
14225/// What the squash subject falls back to when the pull request title is empty
14226/// or candidate-shaped: for a review-only run the derived title, never the
14227/// review prompt held in `instruction`.
14228pub fn landing_subject_source(state: &RunState) -> String {
14229    if is_review_run(state) {
14230        let winner = state.candidates.first().map_or('A', |c| c.label);
14231        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
14232    }
14233    state.instruction.clone()
14234}
14235
14236/// `summary` without its `TITLE:` line, which the pull request title already
14237/// carries.
14238fn summary_without_title(summary: &str) -> String {
14239    let mut lines = summary.trim().lines().peekable();
14240    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
14241        lines.next();
14242    }
14243    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
14244}
14245
14246/// The pull request title and body for the winning candidate.
14247///
14248/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
14249/// the task's own opening line via [`queue::title_from`] when there is none.
14250/// `state.instruction` can open with blank lines (`task_text` only rejects a
14251/// body that is blank *entirely*), which `title_from` skips.
14252///
14253/// Publishing uses an independent description generated from the final diff
14254/// and structured evidence. Internal summaries and reports remain local.
14255/// Non-publishing previews may display the original task and candidate summary.
14256/// The footer retains the run and candidate provenance.
14257#[cfg(test)]
14258fn pr_message(state: &RunState, winner: char) -> PrMessage {
14259    pr_message_with(state, winner, None)
14260}
14261
14262/// [`pr_message`] with what the branch of a review-only run says about itself.
14263/// `facts` is ignored for a run that implements a task.
14264#[cfg(test)]
14265fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
14266    let raw = pr_message_raw(
14267        state,
14268        winner,
14269        facts,
14270        crate::pr_outcome::FinalHead::Unreported,
14271        ChangeNote::NotAsked,
14272    );
14273    let id = crate::scrub::Identity::current();
14274    PrMessage {
14275        title: crate::scrub::scrub(&raw.title, &id),
14276        body: crate::scrub::scrub(&raw.body, &id),
14277    }
14278}
14279
14280/// What the public description may say about the change itself.
14281#[derive(Debug, Clone, Copy)]
14282enum ChangeNote<'a> {
14283    /// A local preview or non-publishing merge mode: no public generation needed.
14284    NotAsked,
14285    /// A summary written from the final diff.
14286    Summary(&'a crate::run::ChangeSummary),
14287    /// A summary was asked for and could not be produced; the text says why.
14288    Unavailable(&'a str),
14289}
14290
14291fn pr_message_raw(
14292    state: &RunState,
14293    winner: char,
14294    facts: Option<&BranchFacts>,
14295    head: crate::pr_outcome::FinalHead<'_>,
14296    change: ChangeNote<'_>,
14297) -> PrMessage {
14298    if !matches!(change, ChangeNote::NotAsked) {
14299        let (title, mut body) = match change {
14300            ChangeNote::Summary(c) => (
14301                c.title.clone(),
14302                format!("## Summary\n\n{}\n\n", c.body.trim()),
14303            ),
14304            ChangeNote::Unavailable(why) => (
14305                neutral_title(state, winner),
14306                format!(
14307                    "## 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"
14308                ),
14309            ),
14310            ChangeNote::NotAsked => unreachable!(),
14311        };
14312        body.push_str(&public_pr_evidence(state, head));
14313        body.push_str(&format!(
14314            "\n---\nmagi:run/{} magi:candidate-{}\n",
14315            state.id,
14316            winner.to_ascii_lowercase()
14317        ));
14318        return PrMessage { title, body };
14319    }
14320    pr_preview(state, winner, facts, head)
14321}
14322
14323/// Append public facts from the run records after every prose generation,
14324/// including posting-gate rewrites. The agent cannot drop this provenance.
14325fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14326    let mut body = crate::pr_outcome::review_rounds(state);
14327    body.push_str(&crate::pr_outcome::final_verification(state, head));
14328    let open = state.last_round_findings();
14329    if !open.is_empty() {
14330        body.push_str("## Open review findings\n\n");
14331        for f in open {
14332            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14333        }
14334        body.push('\n');
14335    }
14336    if let Some(c) = state.change_summary.as_ref()
14337        && head == crate::pr_outcome::FinalHead::At(&c.head)
14338    {
14339        body.push_str(&format!(
14340            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14341            c.base, c.head
14342        ));
14343    }
14344    body
14345}
14346
14347/// Local-only preview of the operator's task and candidate summary.
14348fn pr_preview(
14349    state: &RunState,
14350    winner: char,
14351    facts: Option<&BranchFacts>,
14352    head: crate::pr_outcome::FinalHead<'_>,
14353) -> PrMessage {
14354    let summary = state
14355        .candidates
14356        .iter()
14357        .find(|c| c.label == winner)
14358        .map(|c| c.summary.as_str())
14359        .unwrap_or_default();
14360    // The fallback is the operator's own words and may not be English; GitHub
14361    // text always is, so a non-English task gets a neutral title instead.
14362    let review = is_review_run(state);
14363    let title = if review {
14364        facts
14365            .and_then(|f| {
14366                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14367            })
14368            .or_else(|| review_title(state))
14369            .or_else(|| {
14370                state
14371                    .candidates
14372                    .iter()
14373                    .find(|c| c.label == winner)
14374                    .filter(|c| !c.branch.starts_with("magi/"))
14375                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14376            })
14377            .unwrap_or_else(|| neutral_title(state, winner))
14378    } else {
14379        summary_title(summary).unwrap_or_else(|| {
14380            english_title(
14381                &state.instruction,
14382                PR_TITLE_MAX,
14383                state.config.graph.github_english(),
14384            )
14385            .unwrap_or_else(|| neutral_title(state, winner))
14386        })
14387    };
14388
14389    let mut body = String::new();
14390    let what = summary_without_title(summary);
14391    if !what.is_empty() {
14392        body.push_str("## Summary\n\n");
14393        body.push_str(&what);
14394        body.push_str("\n\n");
14395    }
14396
14397    // Review history uses structured facts across all rounds, never reports.
14398    body.push_str(&crate::pr_outcome::review_rounds(state));
14399    body.push_str(&crate::pr_outcome::final_verification(state, head));
14400    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14401
14402    let open = state.open_findings();
14403    if !open.is_empty() {
14404        body.push_str("## Open review findings\n\n");
14405        for f in &open {
14406            body.push_str(&format!(
14407                "- `{}` [{:?}] {}\n",
14408                f.id, f.severity, "Context retained in local review records."
14409            ));
14410        }
14411        body.push('\n');
14412    }
14413
14414    if let Some(fix) = fix
14415        && !fix.rejected.is_empty()
14416    {
14417        body.push_str("## Declined by the fixer\n\n");
14418        for r in &fix.rejected {
14419            body.push_str(&format!(
14420                "- `{}`: {}\n",
14421                r.id, "Reason retained in local review records."
14422            ));
14423        }
14424        body.push('\n');
14425    }
14426
14427    if review {
14428        // The review prompt is not the task; list what the branch carries.
14429        body.push_str("## Commits under review\n\n");
14430        if let Some(facts) = facts {
14431            let mut left = COMMITS_MAX_CHARS;
14432            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14433                let mut entry = format!("- {}\n", markdown_safe(subject));
14434                for l in markdown_safe(text).lines() {
14435                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14436                }
14437                if left == 0 {
14438                    body.push_str(&format!(
14439                        "- ... {} more commit(s)\n",
14440                        facts.commits.len() - i
14441                    ));
14442                    break;
14443                }
14444                if entry.len() > left {
14445                    // Even the first commit is cut: one huge body must not
14446                    // push the whole description past GitHub's limit.
14447                    let mut end = left;
14448                    while !entry.is_char_boundary(end) {
14449                        end -= 1;
14450                    }
14451                    entry.truncate(end);
14452                    entry.push_str("\n  ... (truncated)\n");
14453                    left = 0;
14454                } else {
14455                    left -= entry.len();
14456                }
14457                body.push_str(&entry);
14458            }
14459            if !facts.stat.trim().is_empty() {
14460                body.push_str(&format!(
14461                    "\n## Diff stat\n\n```\n{}\n```\n",
14462                    markdown_safe(facts.stat.trim())
14463                ));
14464            }
14465        } else {
14466            match &state.reviewed_commits {
14467                Some(subjects) => {
14468                    for s in subjects {
14469                        body.push_str(&format!("- {}\n", s.trim()));
14470                    }
14471                }
14472                None => {
14473                    // An older run kept only the prompt, with the commit list
14474                    // after its first paragraph.
14475                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14476                    body.push_str(rest.trim());
14477                    body.push('\n');
14478                }
14479            }
14480        }
14481    } else {
14482        let task = state.instruction.trim();
14483        let task = if task.is_empty() {
14484            "(empty task)"
14485        } else {
14486            task
14487        };
14488        body.push_str(&format!(
14489            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14490            task.replace("</details>", "&lt;/details&gt;")
14491        ));
14492    }
14493
14494    body.push_str(&format!(
14495        "\n---\nmagi:run/{} magi:candidate-{}\n",
14496        state.id,
14497        winner.to_ascii_lowercase()
14498    ));
14499
14500    PrMessage { title, body }
14501}
14502
14503/// Source imports have already been prepared from structured inputs. Legacy
14504/// inferred references must never instruct a seat to reconstruct those imports.
14505fn seeded_instruction(state: &RunState) -> String {
14506    let mut inputs = Vec::new();
14507    if let Some(start) = &state.sources.start_from {
14508        inputs.push(format!(
14509            "Start from `{}` at `{}` (including ancestry).",
14510            start.token, start.sha
14511        ));
14512    }
14513    for pick in &state.sources.pick_commits {
14514        inputs.push(format!(
14515            "Pick `{}` at `{}` (single commit).",
14516            pick.token, pick.sha
14517        ));
14518    }
14519    if inputs.is_empty() {
14520        state.instruction.clone()
14521    } else {
14522        format!(
14523            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14524            state.instruction,
14525            inputs.join("\n")
14526        )
14527    }
14528}
14529
14530/// Does the winner have no commits ahead of the base it would land on?
14531/// Any failure to find out reads as "not empty": the merge then behaves as it
14532/// always did rather than refusing on a guess.
14533async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14534    let base = &state.base_branch;
14535    let mut against = base.clone();
14536    if mode == MergeMode::Pr {
14537        // A pull request lands on the remote's base, never the local branch
14538        // of the same name: if that cannot be read, "not empty" is the safe
14539        // answer.
14540        let remote = &state.config.merge.remote;
14541        let tracking = format!("{remote}/{base}");
14542        let fetched = git::fetch(repo, remote, base).await;
14543        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14544            against = tracking;
14545        } else {
14546            return false;
14547        }
14548    }
14549    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14550}
14551
14552/// Why nothing was opened for an empty winner, with what the task's own
14553/// references resolved to.
14554fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14555    let mut detail = format!(
14556        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14557         nothing to open a pull request for"
14558    );
14559    detail.push_str(
14560        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14561    );
14562    detail
14563}
14564
14565/// What the `Pr` merge does once it knows whether the branch already has an
14566/// open pull request.
14567#[derive(Debug, PartialEq, Eq)]
14568enum PrPlan {
14569    Create,
14570    Adopt { url: String, title: String },
14571    Stop(String),
14572}
14573
14574/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14575/// a failed lookup -> stop with the real reason. Never guesses.
14576fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14577    match found {
14578        Ok(land::OpenPr::None) => PrPlan::Create,
14579        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14580        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14581            "several open pull requests exist for this branch, not picking one: {}",
14582            urls.join(" ")
14583        )),
14584        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14585    }
14586}
14587
14588/// `gh pr create`, returning the PR url.
14589pub(crate) async fn gh_pr_create(
14590    cwd: &Path,
14591    base: &str,
14592    head: &str,
14593    title: &str,
14594    body: &str,
14595) -> Result<String> {
14596    let out = tokio::process::Command::new("gh")
14597        .args([
14598            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14599        ])
14600        .current_dir(cwd)
14601        .quiet()
14602        .stdin(std::process::Stdio::null())
14603        .output()
14604        .await
14605        .context("spawn gh")?;
14606    if out.status.success() {
14607        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14608    } else {
14609        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14610    }
14611}
14612
14613/// Never force deletion of uncommitted work, including unknown legacy trees.
14614async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14615    match std::fs::symlink_metadata(path) {
14616        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14617            // A previous cleanup may have removed the tree before a branch
14618            // deletion or state save failed. Unregister it if still present.
14619            git::worktree_remove_clean(repo, path).await?;
14620            return Ok(());
14621        }
14622        Err(e) => return Err(e.into()),
14623        Ok(_) => {}
14624    }
14625    if !git::is_clean(path).await? {
14626        bail!(
14627            "worktree has uncommitted work; refusing removal: {}",
14628            path.display()
14629        );
14630    }
14631    if !git::worktree_remove_clean(repo, path).await? {
14632        bail!("worktree removal refused: {}", path.display());
14633    }
14634    Ok(())
14635}
14636
14637/// Read seats return replies, not working-tree changes. Only registered,
14638/// detached seats directly inside this run's root may discard those changes.
14639async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14640    if !crate::retention::read_seat(path) || !path.exists() {
14641        return remove_preserved_worktree(&state.repo, path).await;
14642    }
14643    let owned = std::fs::symlink_metadata(path)?.is_dir()
14644        && path.parent().map(Path::canonicalize).transpose()?
14645            == Some(state.worktree_root().canonicalize()?)
14646        && crate::retention::worktrees(state)
14647            .await?
14648            .contains(&path.canonicalize()?);
14649    let common = crate::repo_lock::common_dir(&state.repo).await?;
14650    if !owned
14651        || common.is_none()
14652        || crate::repo_lock::common_dir(path).await? != common
14653        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14654            .await?
14655            .ok()
14656        || state.candidates.iter().any(|c| c.worktree == path)
14657    {
14658        return remove_preserved_worktree(&state.repo, path).await;
14659    }
14660    let changes = git::status_porcelain(path).await?;
14661    if !git::worktree_remove(&state.repo, path).await? {
14662        bail!(
14663            "read-only seat worktree removal refused: {}",
14664            path.display()
14665        );
14666    }
14667    if !changes.is_empty() {
14668        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14669        let paths: String = paths.chars().take(1024).collect();
14670        state.event(
14671            "fold",
14672            format!(
14673                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14674                path.file_name().unwrap_or_default().to_string_lossy(),
14675                changes.lines().count()
14676            ),
14677        );
14678    }
14679    Ok(())
14680}
14681
14682fn fold_target(
14683    home: &Path,
14684    root: &Path,
14685    path: &Path,
14686    isolated: bool,
14687) -> Option<crate::build_target::FoldTarget> {
14688    if !isolated {
14689        return None;
14690    }
14691    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14692        Ok(target) => target,
14693        Err(error) => {
14694            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14695            None
14696        }
14697    }
14698}
14699
14700fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14701    if let Some(target) = target
14702        && let Err(error) = target.reclaim_orphaned_target(home)
14703    {
14704        tracing::warn!(%error, "isolated target retained after fold");
14705    }
14706}
14707
14708/// Why a fold left a run alone. A typed refusal lets the automatic callers
14709/// (`clean::fold_one`, and through it the idle janitor and the busy-time fold
14710/// turn) say *why* in their receipts; it never changes what is deleted.
14711#[derive(Debug, Clone, PartialEq, Eq)]
14712pub enum FoldRefusal {
14713    /// A lease or lock a live owner holds - the run's execution lease or
14714    /// ownership lock, a source's output lease, a Cargo build, the repository's
14715    /// coordination lease - or a live daemon claim on the run.
14716    Live(String),
14717    /// A resumable status: someone may still continue this run.
14718    Resumable,
14719    /// Finished less than the fold grace period ago.
14720    WithinGrace,
14721    /// An explicitly retained recovery source (`pr_recovery`).
14722    Retained(String),
14723    /// The proof that nothing is lost is not complete: startup or candidate
14724    /// preservation unfinished, or the confirmed-merge source proof (Cargo
14725    /// residue, Git checkpoints, the fetched base) could not be established.
14726    ProofIncomplete(String),
14727    /// The run's record is gone, or is not the record that was locked: it was
14728    /// deleted while the fold waited for its locks. Nothing is touched and
14729    /// nothing is recreated.
14730    RecordGone,
14731    /// The record was readable when the caller first looked and cannot be read
14732    /// once the run's locks are held.
14733    Unreadable(String),
14734}
14735
14736impl std::fmt::Display for FoldRefusal {
14737    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14738        match self {
14739            Self::Live(detail) | Self::ProofIncomplete(detail) => f.write_str(detail),
14740            Self::Resumable => f.write_str("refusing fold: the run is resumable"),
14741            Self::WithinGrace => f.write_str("refusing fold: the run finished within its grace"),
14742            Self::Retained(reason) => write!(f, "refusing fold: {reason}"),
14743            Self::RecordGone => f.write_str("refusing fold: record gone"),
14744            Self::Unreadable(detail) => {
14745                write!(
14746                    f,
14747                    "refusing fold: the run record became unreadable: {detail}"
14748                )
14749            }
14750        }
14751    }
14752}
14753
14754impl std::error::Error for FoldRefusal {}
14755
14756/// Is `error` somebody else holding a lock or lease right now? Only
14757/// contention is: any other failure of a lock call is a real failure.
14758pub(crate) fn held_by_live_owner(error: &anyhow::Error) -> bool {
14759    error.chain().any(|cause| {
14760        cause.is::<crate::retention::OutputsInUse>()
14761            || cause.is::<crate::repo_lock::ResourceBlocked>()
14762            || cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
14763                io.kind() == std::io::ErrorKind::WouldBlock
14764                    || cfg!(windows) && io.raw_os_error() == Some(33)
14765            })
14766    })
14767}
14768
14769/// `error`, marked as [`FoldRefusal::Live`] when it is a held lock.
14770///
14771/// The refusal is *added to* the error as context, never substituted for it:
14772/// callers match the error underneath (`repo_lock::ResourceBlocked` for a
14773/// coordination wait, which several of them treat as a resource stop), and the
14774/// receipt's classification reads the refusal. Both downcasts succeed.
14775fn live_or(error: anyhow::Error) -> anyhow::Error {
14776    if held_by_live_owner(&error) {
14777        error.context(FoldRefusal::Live(
14778            "a lock or lease is held by another owner".into(),
14779        ))
14780    } else {
14781        error
14782    }
14783}
14784
14785/// A failure to take a run's owner lock or execution lease. A run directory
14786/// that is not there (deleted, or never was) is `record gone` and is *not*
14787/// created for the lock's sake; contention is `live`; anything else stays a
14788/// failure with its own text.
14789fn lock_refusal(error: anyhow::Error) -> anyhow::Error {
14790    if is_missing(&error) {
14791        FoldRefusal::RecordGone.into()
14792    } else {
14793        live_or(error)
14794    }
14795}
14796
14797fn is_missing(error: &anyhow::Error) -> bool {
14798    error.chain().any(|cause| {
14799        cause
14800            .downcast_ref::<std::io::Error>()
14801            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
14802    })
14803}
14804
14805fn preservation_refusal() -> anyhow::Error {
14806    FoldRefusal::ProofIncomplete("candidate preservation incomplete; refusing cleanup".into())
14807        .into()
14808}
14809
14810/// The record's own preconditions for the explicit recovery-retention override.
14811fn ensure_overridable(state: &RunState) -> Result<()> {
14812    anyhow::ensure!(
14813        state.status.done() && !state.status.resumable(),
14814        "recovery retention override requires a finished, non-resumable run"
14815    );
14816    Ok(())
14817}
14818
14819/// How a failure of the confirmed-merge source verification reaches the fold's
14820/// caller: somebody else holding a lock is `live`; a lock call that failed for
14821/// another reason is a failure of its own (`failed` in the receipt), not
14822/// evidence that the sources are unproven; anything else - missing or changed
14823/// evidence - is an incomplete proof.
14824fn source_proof_failure(error: anyhow::Error) -> anyhow::Error {
14825    if held_by_live_owner(&error) {
14826        live_or(error)
14827    } else if error
14828        .chain()
14829        .any(|cause| cause.is::<crate::retention::LockCallFailed>())
14830    {
14831        error
14832    } else {
14833        FoldRefusal::ProofIncomplete(format!("{error:#}")).into()
14834    }
14835}
14836
14837/// Which loader a fold uses on the record it reads again under its locks.
14838#[derive(Clone, Copy, PartialEq, Eq)]
14839enum Reload {
14840    /// Housekeeping: the record as saved, whatever schema wrote it
14841    /// ([`RunState::load_tolerant_under`]), exactly as `clean::fold_due` has
14842    /// always read it.
14843    Tolerant,
14844    /// An explicit fold (`magi fold`, the phone's route): the migrating loader
14845    /// the caller itself used ([`RunState::load_under`]), whose derived fields
14846    /// the preservation checks and the saved record then rest on.
14847    Strict,
14848}
14849
14850/// Why a record read under the locks is no longer the one that was locked.
14851fn reload_refusal(error: &anyhow::Error) -> FoldRefusal {
14852    if is_missing(error) {
14853        FoldRefusal::RecordGone
14854    } else {
14855        FoldRefusal::Unreadable(format!("{error:#}"))
14856    }
14857}
14858
14859/// What a test does after a fold's first look at the record and before it
14860/// takes the run's locks: where a deletion or a handover falls.
14861#[cfg(test)]
14862type BeforeLocks = Box<dyn FnOnce(&Path, &str)>;
14863
14864#[cfg(test)]
14865thread_local! {
14866    static BEFORE_LOCKS: std::cell::RefCell<Option<BeforeLocks>> =
14867        const { std::cell::RefCell::new(None) };
14868}
14869
14870/// Tear a run's worktrees and branches down.
14871///
14872/// `home` is where the updated `run.json` is saved (via
14873/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14874/// a housekeeping pass already has its own honest `home` handed to it, and
14875/// falling through to the global here would write back through whichever
14876/// directory some other process or test pinned into that `OnceLock` first,
14877/// not the one the caller actually resolved its `runs` and `state` from.
14878///
14879/// Every deletion decision is made on the record as it is on disk once the
14880/// owner lock and execution lease are held, not on the `state` the caller read
14881/// earlier: see [`fold_run_when`].
14882pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14883    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, false).await
14884}
14885
14886/// [`fold_run`] for the automatic callers, which decide whether the run may be
14887/// folded at all, and whether its winner goes too, from the run record.
14888///
14889/// `decide` is called on the caller's earlier read by the caller itself, and
14890/// again here on the record reloaded after taking the run's owner lock and
14891/// execution lease. A handover (`handover::release`) records `released_to` /
14892/// `released_branches` under that owner lock and removes the old worktree while
14893/// keeping the branch; a fold that acted on a record read before the handover
14894/// would delete the branch already given to the successor and save the stale
14895/// record over the handover. A run no longer eligible under the fresh record
14896/// is left alone and the refusal says why. The reload is tolerant of older
14897/// schemas, as `clean::fold_due` always was; the explicit entry points
14898/// ([`fold_run`], [`fold_run_overriding_recovery_retention`]) use the
14899/// migrating loader.
14900pub async fn fold_run_when(
14901    state: &mut RunState,
14902    home: &Path,
14903    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14904) -> Result<Vec<String>> {
14905    fold_run_with_policy(state, home, decide, Reload::Tolerant, false).await
14906}
14907
14908/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14909pub async fn fold_run_overriding_recovery_retention(
14910    state: &mut RunState,
14911    drop_winner: bool,
14912    home: &Path,
14913) -> Result<Vec<String>> {
14914    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, true).await
14915}
14916
14917async fn fold_run_with_policy(
14918    state: &mut RunState,
14919    home: &Path,
14920    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14921    reload: Reload,
14922    override_recovery_retention: bool,
14923) -> Result<Vec<String>> {
14924    // Cheap refusals on the caller's snapshot, before any lock is taken.
14925    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14926        && !override_recovery_retention
14927    {
14928        return Err(FoldRefusal::Retained(reason).into());
14929    }
14930    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14931        return Err(preservation_refusal());
14932    }
14933    // A fold needs the saved record of the run it locks. Nothing below may
14934    // bring a deleted run's directory back, and a fold is never entitled to
14935    // write a record of its own making: the caller's `state` is only a first
14936    // look, and every decision is made on what is read under the locks.
14937    let id = state.id.clone();
14938    let record = home.join("runs").join(&id).join("run.json");
14939    if !record.try_exists()? {
14940        return Err(FoldRefusal::RecordGone.into());
14941    }
14942    #[cfg(test)]
14943    if let Some(hook) = BEFORE_LOCKS.with(|hook| hook.borrow_mut().take()) {
14944        hook(home, &id);
14945    }
14946    // Serialize ordinary folding with the same starts/resumes as target-only
14947    // eviction. Otherwise a second janitor could remove the whole worktree
14948    // around a live output borrower even though target eviction was fenced.
14949    // Deleting a run record takes these same two locks (`clean::delete_run`).
14950    // The lock files are opened where they are and never created in a
14951    // directory that is not there: a refusal changes nothing, and the lock
14952    // files are never unlinked (`pr_head::owner_lock`).
14953    let _owner = crate::pr_head::owner_lock(home, &id).map_err(lock_refusal)?;
14954    // An override must use current durable ownership, not a pre-lock snapshot.
14955    // Its liveness assessment has to be made before this fold holds the
14956    // execution lease itself (a held lease reads as a live driver); the record
14957    // it is made on is checked for identity like every other, and the final
14958    // record, read once both locks are held, is checked again below.
14959    if override_recovery_retention {
14960        let current =
14961            RunState::load_under(&id, home).map_err(|e| anyhow::Error::from(reload_refusal(&e)))?;
14962        if current.id != id {
14963            return Err(FoldRefusal::RecordGone.into());
14964        }
14965        ensure_overridable(&current)?;
14966        let claimed = crate::daemon::is_working_on_other(home, &id, Timestamp::now())?;
14967        anyhow::ensure!(
14968            current.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14969            "run is live or its ownership is unknown"
14970        );
14971    }
14972    let _driver = crate::driver::maintenance(home, &id).map_err(lock_refusal)?;
14973    // Both locks are held, so no handover, driver claim, deletion or other
14974    // fold can change the record from here on: act on it, not on the earlier
14975    // read. There is no fallback to that read - a record that cannot be read
14976    // again, or is not this run's, ends the fold and touches nothing.
14977    let loaded = match reload {
14978        Reload::Tolerant => RunState::load_tolerant_under(&id, home),
14979        Reload::Strict => RunState::load_under(&id, home),
14980    };
14981    match loaded {
14982        Ok(fresh) if fresh.id == id => *state = fresh,
14983        Ok(_) => return Err(FoldRefusal::RecordGone.into()),
14984        Err(e) => return Err(reload_refusal(&e).into()),
14985    }
14986    if override_recovery_retention {
14987        ensure_overridable(state)?;
14988    }
14989    let drop_winner = decide(state)?;
14990    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14991        return Err(preservation_refusal());
14992    }
14993    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14994    if let Some(reason) = &retention_reason
14995        && !override_recovery_retention
14996    {
14997        return Err(FoldRefusal::Retained(reason.clone()).into());
14998    }
14999    let mut output_guards = Vec::new();
15000    for entry in std::fs::read_dir(state.worktree_root())
15001        .into_iter()
15002        .flatten()
15003        .flatten()
15004    {
15005        if entry.path().join(".git").is_file() {
15006            output_guards
15007                .push(crate::retention::OutputLease::take(&entry.path(), true).map_err(live_or)?);
15008        }
15009    }
15010    let repo = state.repo.clone();
15011    // CLI, Web and automatic cleanup all enter here, independently of
15012    // Runner::fold_losers. Protect deletion and shared config release too.
15013    //
15014    // Lock order. A handover (`handover::release`, a review taking a branch
15015    // over) holds repository coordination and then asks for this run's owner
15016    // lock; this fold already holds the owner lock. An automatic fold must not
15017    // *wait* for coordination here: the handover would wait for the owner lock
15018    // while the fold waited for coordination, and neither bound (the handover's
15019    // short retry, the fold's `timeout_resource_wait`) resolves that inversion
15020    // - the handover fails its startup, which costs the task an attempt. So it
15021    // asks once; when the lease is busy it gives way: everything it holds is
15022    // released on return, nothing was changed or saved, and the run is `live`
15023    // for this pass and judged again on a later one. The explicit callers
15024    // (`magi fold`, the phone's route) were asked for by a person and still
15025    // wait, bounded as before.
15026    let _coordination = if reload == Reload::Tolerant {
15027        match crate::repo_lock::SeatLease::operation_with(
15028            &repo,
15029            state.config.coordination.as_ref(),
15030            &crate::repo_lock::WaitPolicy::immediate(),
15031        )
15032        .await
15033        {
15034            Ok(lease) => lease,
15035            Err(e) => return Err(live_or(e)),
15036        }
15037    } else {
15038        let wait = repository_wait(state, None);
15039        match coordinate_operation(state, &repo, &wait).await {
15040            Ok(lease) => lease,
15041            Err(e) => {
15042                state.save_under(home)?;
15043                return Err(live_or(e));
15044            }
15045        }
15046    };
15047    // Confirmed merges dispose of their owned sources after durable evidence
15048    // capture. Preflight every source before removing anything. A failure of
15049    // this stage is, by what the stage is for, an incomplete proof - unless
15050    // it is only a lock somebody else holds.
15051    let _source_outputs = if retention_reason.is_some()
15052        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
15053    {
15054        match verify_merged_fold_sources(state, drop_winner, home).await {
15055            Ok(held) => held,
15056            Err(e) => return Err(source_proof_failure(e)),
15057        }
15058    } else {
15059        Vec::new()
15060    };
15061    if let Some(reason) = retention_reason {
15062        state.event(
15063            "fold",
15064            format!(
15065                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
15066                state.id
15067            ),
15068        );
15069        state.save_under(home)?;
15070    }
15071    let root = state.worktree_root();
15072    let winner = state.tally.as_ref().map(|t| t.winner);
15073    let mut removed = Vec::new();
15074    let isolated = crate::build_target::isolated(&state.config);
15075
15076    for i in 0..state.candidates.len() {
15077        let c = state.candidates[i].clone();
15078        let is_winner = Some(c.label) == winner;
15079        if is_winner && !drop_winner {
15080            continue;
15081        }
15082        let existed = c.worktree.exists();
15083        let target = fold_target(home, &root, &c.worktree, isolated);
15084        // A vanished directory can still have a Git registration that keeps
15085        // its branch checked out. Remove that registration before the branch.
15086        remove_preserved_worktree(&repo, &c.worktree).await?;
15087        reclaim_fold_target(home, target);
15088        if existed {
15089            removed.push(c.worktree.to_string_lossy().into_owned());
15090        }
15091        // A branch handed to a later run (and its pull request) is not this
15092        // run's to delete.
15093        let handed_over = state.released_branches.contains(&c.branch);
15094        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
15095            if !git::branch_delete(&repo, &c.branch).await? {
15096                bail!("candidate branch removal refused");
15097            }
15098            removed.push(c.branch.clone());
15099        }
15100        state.candidates[i].folded = true;
15101    }
15102
15103    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
15104        let path = name.path();
15105        let keep = !drop_winner
15106            && winner.is_some_and(|w| {
15107                path.file_name()
15108                    .is_some_and(|n| n == format!("cand-{w}").as_str())
15109            });
15110        if keep {
15111            continue;
15112        }
15113        let target = fold_target(home, &root, &path, isolated);
15114        remove_read_seat_worktree(state, &path).await?;
15115        reclaim_fold_target(home, target);
15116        removed.push(path.to_string_lossy().into_owned());
15117    }
15118
15119    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
15120    // judge worktrees, so once the loop above has cleared all of them out,
15121    // the parent is a bare directory nobody else was ever going to remove -
15122    // git only ever managed what was inside it. Left alone, one of these
15123    // accumulates per fully-folded run; the operator's own machine had 74.
15124    // `remove_if_empty` re-checks rather than assuming: a run whose winner
15125    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
15126    // so does anything a run never claimed that happens to share the bay.
15127    remove_if_empty(&root);
15128
15129    if state.enabled_worktree_config && drop_winner {
15130        // A release, not a raw disable: some sibling run in this repository
15131        // may still hold its own reference (see `git::acquire_worktree_config`),
15132        // and only the last release actually turns the setting back off.
15133        git::release_worktree_config(&repo).await.ok();
15134        state.enabled_worktree_config = false;
15135    }
15136    // What this fold itself found, written in the same locked save: nothing
15137    // left to remove and no bay on disk (a failed or erroring check is not
15138    // "gone"). The busy-time fold turn skips such a run only while the bay is
15139    // still confirmed absent; any fold that found work clears the mark.
15140    state.fold_settled_at =
15141        (removed.is_empty() && matches!(root.try_exists(), Ok(false))).then(Timestamp::now);
15142    state.save_under(home)?;
15143    Ok(removed)
15144}
15145
15146async fn verify_merged_fold_sources(
15147    state: &RunState,
15148    drop_winner: bool,
15149    home: &Path,
15150) -> Result<Vec<std::fs::File>> {
15151    let winner = state.tally.as_ref().map(|t| t.winner);
15152    let mut heads = BTreeSet::new();
15153    for candidate in &state.candidates {
15154        if Some(candidate.label) == winner && !drop_winner {
15155            continue;
15156        }
15157        anyhow::ensure!(
15158            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
15159            "candidate recovery source is outside the inventoried run root: {}",
15160            candidate.worktree.display()
15161        );
15162        match std::fs::symlink_metadata(&candidate.worktree) {
15163            Ok(_) => {}
15164            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15165            Err(error) => return Err(error.into()),
15166        }
15167        if !state.released_branches.contains(&candidate.branch)
15168            && git::branch_exists(&state.repo, &candidate.branch).await?
15169        {
15170            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
15171        }
15172    }
15173    let mut cargo_guards = Vec::new();
15174    let entries = match std::fs::read_dir(state.worktree_root()) {
15175        Ok(entries) => Some(entries),
15176        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
15177        Err(error) => return Err(error.into()),
15178    };
15179    for entry in entries.into_iter().flatten() {
15180        let path = entry?.path();
15181        let metadata = std::fs::symlink_metadata(&path)?;
15182        anyhow::ensure!(
15183            metadata.is_dir() && !metadata.file_type().is_symlink(),
15184            "non-directory or symlink recovery source retained: {}",
15185            path.display()
15186        );
15187        if !drop_winner
15188            && winner.is_some_and(|w| {
15189                path.file_name()
15190                    .is_some_and(|name| name == format!("cand-{w}").as_str())
15191            })
15192        {
15193            continue;
15194        }
15195        anyhow::ensure!(
15196            path.join(".git").is_file(),
15197            "unregistered recovery source retained: {}",
15198            path.display()
15199        );
15200        anyhow::ensure!(
15201            git::git(
15202                &path,
15203                &[
15204                    "status",
15205                    "--porcelain",
15206                    "--untracked-files=all",
15207                    "--ignored",
15208                    "--",
15209                    ".",
15210                    ":(exclude)target"
15211                ]
15212            )
15213            .await?
15214            .is_empty(),
15215            "source changes or ignored recovery files retained: {}",
15216            path.display()
15217        );
15218        match std::fs::symlink_metadata(path.join("target")) {
15219            Ok(_) => {
15220                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
15221            }
15222            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15223            Err(error) => return Err(error.into()),
15224        }
15225        for checkpoint in [
15226            "rebase-merge",
15227            "rebase-apply",
15228            "sequencer",
15229            "CHERRY_PICK_HEAD",
15230            "MERGE_HEAD",
15231            "REBASE_HEAD",
15232            "REVERT_HEAD",
15233            "BISECT_LOG",
15234            "AUTO_MERGE",
15235            "MERGE_MSG",
15236        ] {
15237            let location = git::git(
15238                &path,
15239                &[
15240                    "rev-parse",
15241                    "--path-format=absolute",
15242                    "--git-path",
15243                    checkpoint,
15244                ],
15245            )
15246            .await?;
15247            anyhow::ensure!(
15248                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
15249                if e.kind() == std::io::ErrorKind::NotFound),
15250                "Git recovery checkpoint retained: {checkpoint}"
15251            );
15252        }
15253        heads.insert(git::rev_parse(&path, "HEAD").await?);
15254    }
15255    crate::fold_evidence::preserve(state, home, &heads).await?;
15256
15257    Ok(cargo_guards)
15258}
15259
15260/// Remove `dir` if it exists and has nothing in it.
15261///
15262/// Best-effort and silent by design: a directory that is not empty (a run
15263/// whose winner is still parked there, a stray file some other process left)
15264/// is exactly the case this must refuse, and a directory that is already gone
15265/// is not a failure worth reporting either. `std::fs::remove_dir` itself
15266/// already refuses a non-empty directory, so the emptiness check below is
15267/// belt, not suspenders - it is what keeps this from ever attempting the
15268/// removal in the case that matters, rather than trusting `remove_dir`'s
15269/// error path to have no side effects if it ever changed.
15270fn remove_if_empty(dir: &Path) {
15271    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
15272        std::fs::remove_dir(dir).ok();
15273    }
15274}
15275
15276/// Severity of the worst open finding in the last review round, for reporting.
15277pub fn worst_open(state: &RunState) -> Option<Severity> {
15278    state
15279        .reviews
15280        .last()?
15281        .reviews
15282        .iter()
15283        .flat_map(|r| r.findings.iter())
15284        .map(|f| f.severity)
15285        .max()
15286}
15287
15288/// `[worktree] setup` hides its products per worktree, which needs
15289/// `extensions.worktreeConfig`. Taken once per run and released with the run's
15290/// worktrees, like the hook's; every place that runs setup calls this first.
15291async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
15292    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
15293        git::acquire_worktree_config(repo).await?;
15294        state.enabled_worktree_config = true;
15295    }
15296    Ok(())
15297}
15298
15299#[cfg(test)]
15300mod tests {
15301    #[tokio::test]
15302    async fn launcher_base_fetch_requires_remote_success() {
15303        let tmp = tempfile::tempdir().unwrap();
15304        let repo = tmp.path().join("repo");
15305        let remote = tmp.path().join("remote");
15306        std::fs::create_dir(&repo).unwrap();
15307        std::fs::create_dir(&remote).unwrap();
15308        git::git(&remote, &["init", "--bare", "-b", "main"])
15309            .await
15310            .unwrap();
15311        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
15312        git::git(
15313            &repo,
15314            &[
15315                "-c",
15316                "user.name=Fixture",
15317                "-c",
15318                "user.email=fixture@example.invalid",
15319                "commit",
15320                "--allow-empty",
15321                "-m",
15322                "fixture",
15323            ],
15324        )
15325        .await
15326        .unwrap();
15327        git::git(
15328            &repo,
15329            &["remote", "add", "origin", remote.to_str().unwrap()],
15330        )
15331        .await
15332        .unwrap();
15333        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
15334        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15335        assert_eq!(
15336            resolve_base(&repo, "main", "origin", None)
15337                .await
15338                .unwrap()
15339                .commit,
15340            head
15341        );
15342        #[cfg(unix)]
15343        {
15344            let policy: crate::config::Coordination = toml::from_str(
15345                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
15346            ).unwrap();
15347            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
15348            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
15349            let held = crate::repo_lock::SeatLease::operation_with(
15350                &repo,
15351                Some(&policy),
15352                &crate::repo_lock::WaitPolicy::default(),
15353            )
15354            .await
15355            .unwrap();
15356            assert!(held.is_some());
15357            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
15358            tokio::pin!(fetch);
15359            assert!(
15360                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
15361                    .await
15362                    .is_err()
15363            );
15364            assert!(
15365                !repo.join(".git/FETCH_HEAD").exists(),
15366                "no fetch before admission"
15367            );
15368            drop(held);
15369            let fetched = fetch.await.unwrap();
15370            assert_eq!(fetched.commit, head);
15371            assert_eq!(fetched.remote, "origin");
15372            assert_eq!(fetched.branch, "main");
15373        }
15374        // A surviving tracking ref is not successful fetch evidence.
15375        git::git(
15376            &repo,
15377            &[
15378                "remote",
15379                "set-url",
15380                "origin",
15381                tmp.path().join("missing").to_str().unwrap(),
15382            ],
15383        )
15384        .await
15385        .unwrap();
15386        let error = resolve_base(&repo, "main", "origin", None)
15387            .await
15388            .unwrap_err()
15389            .to_string();
15390        assert!(error.contains("cannot read origin/main"));
15391        assert!(error.contains("refusing to branch off"));
15392    }
15393
15394    #[test]
15395    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
15396        let leaked = vec!["chore(deps): update a crate".to_owned()];
15397        let own = "fix(daemon): apply a chosen action";
15398        assert!(should_retitle("", own, &leaked));
15399        assert!(should_retitle(
15400            &format!("{REVIEW_PROMPT_OPENING} `x`"),
15401            own,
15402            &leaked
15403        ));
15404        assert!(should_retitle(
15405            "chore: land candidate A of run 1",
15406            own,
15407            &leaked
15408        ));
15409        assert!(should_retitle(
15410            "magi: candidate A (uncommitted work)",
15411            own,
15412            &leaked
15413        ));
15414        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
15415        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
15416        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
15417    }
15418
15419    #[test]
15420    fn pr_merge_plan_creates_adopts_or_stops() {
15421        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
15422        assert_eq!(
15423            pr_merge_plan(Ok(land::OpenPr::One {
15424                url: "u".into(),
15425                title: "t".into()
15426            })),
15427            PrPlan::Adopt {
15428                url: "u".into(),
15429                title: "t".into()
15430            }
15431        );
15432        let PrPlan::Stop(many) =
15433            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
15434        else {
15435            panic!("many must stop");
15436        };
15437        assert!(many.contains('a') && many.contains('b'));
15438        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
15439            panic!("a failed lookup must stop");
15440        };
15441        assert!(err.contains("bad token"));
15442    }
15443
15444    use super::*;
15445    use crate::run::GateStatus;
15446    use std::collections::BTreeMap;
15447    use std::time::Duration;
15448
15449    fn conductor() -> AgentSpec {
15450        AgentSpec {
15451            id: "conductor".to_owned(),
15452            kind: crate::config::AgentKind::Command,
15453            model: None,
15454            command: vec!["true".to_owned()],
15455            extra_args: Vec::new(),
15456            env: BTreeMap::new(),
15457            prompt_delivery: None,
15458            max_turn_secs: None,
15459        }
15460    }
15461
15462    fn spec(id: &str) -> AgentSpec {
15463        AgentSpec {
15464            id: id.to_owned(),
15465            kind: crate::config::AgentKind::Command,
15466            model: None,
15467            command: vec!["true".to_owned()],
15468            extra_args: Vec::new(),
15469            env: BTreeMap::new(),
15470            prompt_delivery: None,
15471            max_turn_secs: None,
15472        }
15473    }
15474
15475    fn ids(xs: &[&str]) -> BTreeSet<String> {
15476        xs.iter().map(|s| (*s).to_owned()).collect()
15477    }
15478
15479    #[test]
15480    fn pick_successor_skips_an_agent_another_seat_holds() {
15481        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
15482        let roster = [spec("a"), spec("b"), spec("c")];
15483        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15484        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15485    }
15486
15487    #[test]
15488    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
15489        // The other seat started on c but was handed to d; c is free again.
15490        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
15491        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15492        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15493        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
15494        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
15495    }
15496
15497    #[test]
15498    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
15499        let roster = [spec("a"), spec("b")];
15500        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15501        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15502        let carried = ids(&["b"]);
15503        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
15504        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15505    }
15506
15507    #[test]
15508    fn pick_successor_returns_none_without_any_untried_successor() {
15509        let roster = [spec("a"), spec("b")];
15510        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
15511        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
15512        let carried = ids(&["a"]);
15513        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
15514    }
15515
15516    #[test]
15517    fn pick_successor_rescue_avoids_another_seats_occupant() {
15518        // b is a carried failure and free; a is held by the other seat.
15519        let roster = [spec("a"), spec("b"), spec("c")];
15520        let carried = ids(&["b", "c"]);
15521        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
15522        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15523    }
15524
15525    #[test]
15526    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
15527        let roster = [spec("a"), spec("b"), spec("c")];
15528        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
15529        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15530    }
15531
15532    #[test]
15533    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
15534        let roster = [spec("a"), spec("b"), spec("c")];
15535        let failed = ids(&["a", "b", "c"]);
15536        // Rescue looks at the whole roster, once per id, then runs out.
15537        let mut tried = ids(&["b"]);
15538        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15539        assert_eq!(first.id, "a");
15540        tried.insert(first.id.clone());
15541        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15542        assert_eq!(second.id, "c");
15543        tried.insert(second.id.clone());
15544        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
15545    }
15546
15547    #[test]
15548    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
15549        let roster = [spec("a"), spec("b")];
15550        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
15551        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15552    }
15553
15554    #[test]
15555    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15556        let roster = [spec("a"), spec("b"), spec("c")];
15557        let h = SeatHistory {
15558            failed: ids(&["a"]),
15559            last_ok: Some("b".to_owned()),
15560            last_fail: None,
15561        };
15562        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15563        // A last answerer that left the roster, or later failed, is ignored.
15564        let gone = SeatHistory {
15565            last_ok: Some("zzz".to_owned()),
15566            ..h.clone()
15567        };
15568        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15569        let failed = SeatHistory {
15570            failed: ids(&["a", "b"]),
15571            last_ok: Some("b".to_owned()),
15572            last_fail: None,
15573        };
15574        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15575    }
15576
15577    #[test]
15578    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15579        let first = SeatState::new("review-1", "alpha", 7);
15580        let next = handover_seat("review-1", "gamma", 7);
15581        assert_ne!(first.claude_session, next.claude_session);
15582    }
15583
15584    #[test]
15585    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15586        let mut state = state_with_summary("x", "y");
15587        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15588        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15589        assert_ne!(a.claude_session, b.claude_session);
15590    }
15591
15592    #[test]
15593    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15594        let roster = [spec("a"), spec("b")];
15595        let h = SeatHistory {
15596            failed: ids(&["a", "b"]),
15597            ..SeatHistory::default()
15598        };
15599        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15600        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15601        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15602    }
15603
15604    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15605    // fallback loop depends on to terminate: it must walk forward from the
15606    // seat's own position, never restart at the front of the roster, and it
15607    // must never hand back an id already tried, however many times that id
15608    // happens to appear.
15609
15610    #[test]
15611    fn failure_signature_ignores_numbers_and_paths() {
15612        assert_eq!(
15613            failure_signature("exited with Some(2) and no usable output"),
15614            failure_signature("exited with Some(137) and no usable output")
15615        );
15616        assert_eq!(
15617            failure_signature("process exited with no usable output (exit code 2)"),
15618            failure_signature("process exited with no usable output (exit code 137)")
15619        );
15620        for (old, new) in [
15621            (
15622                "exited with Some(2) and no usable output",
15623                "process exited with no usable output (exit code 2)",
15624            ),
15625            (
15626                "exited with None and no usable output",
15627                "process exited with no usable output (exit code unavailable)",
15628            ),
15629        ] {
15630            let previous = FailClass::Other(failure_signature(old));
15631            let current = FailClass::Other(failure_signature(new));
15632            assert_eq!(previous, current, "resumption retains the failure class");
15633            assert!(!should_hand_over(Some(&previous), &current));
15634        }
15635        assert_eq!(
15636            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15637            failure_signature("cannot open /var/x.txt: denied")
15638        );
15639        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15640    }
15641
15642    #[test]
15643    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15644        let other = FailClass::Other("x".into());
15645        assert!(should_hand_over(None, &FailClass::Quota));
15646        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15647        assert!(should_hand_over(
15648            Some(&FailClass::Timeout),
15649            &FailClass::Timeout
15650        ));
15651        assert!(should_hand_over(None, &other));
15652        assert!(!should_hand_over(Some(&other), &other));
15653        assert!(should_hand_over(
15654            Some(&other),
15655            &FailClass::Other("y".into())
15656        ));
15657        // A quota or timeout in between ends the run of identical failures.
15658        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15659        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15660    }
15661
15662    #[test]
15663    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15664        let a = SeatState::new("judge-1", "alpha", 7);
15665        let b = handover_seat("judge-1", "beta", 7);
15666        assert_ne!(a.claude_session, b.claude_session);
15667        assert_eq!(b.turns, 0);
15668    }
15669
15670    #[test]
15671    fn a_timeout_is_classified_apart_from_other_failures() {
15672        assert_eq!(
15673            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15674            Some(FailClass::Timeout)
15675        );
15676        assert!(matches!(
15677            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15678            Some(FailClass::Other(_))
15679        ));
15680    }
15681
15682    #[test]
15683    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15684        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15685        let tried = BTreeSet::from(["beta".to_owned()]);
15686        // beta sits at index 1; the next candidate is gamma, never alpha —
15687        // which is very likely a different candidate slot's own agent.
15688        let next = next_untried_in_roster(&roster, 1, &tried);
15689        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15690    }
15691
15692    #[test]
15693    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15694        let roster = vec![spec("alpha"), spec("beta")];
15695        let tried = BTreeSet::from(["beta".to_owned()]);
15696        // beta is the roster's last entry: nothing follows it, and alpha —
15697        // earlier in the roster, almost certainly a different candidate
15698        // slot's own agent — must not be reached by wrapping back to it.
15699        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15700    }
15701
15702    #[test]
15703    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15704        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15705        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15706        // beta (index 1) and gamma (index 2, the only entry after it) have
15707        // both been tried; alpha (index 0) never has, but it comes before
15708        // beta's own position, so there is nothing further for this seat.
15709        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15710    }
15711
15712    #[test]
15713    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15714        let roster = vec![spec("a"), spec("a"), spec("b")];
15715        let tried = BTreeSet::from(["a".to_owned()]);
15716        let next = next_untried_in_roster(&roster, 0, &tried);
15717        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15718    }
15719
15720    #[test]
15721    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15722        let roster = vec![spec("a"), spec("b")];
15723        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15724        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15725    }
15726
15727    #[test]
15728    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15729        let dir = tempfile::tempdir().unwrap();
15730        let bay = dir.path().join("ffff");
15731
15732        // Not there yet: nothing to do, nothing to panic on.
15733        remove_if_empty(&bay);
15734        assert!(!bay.exists());
15735
15736        // Something still inside - the winner's worktree, or a stray file -
15737        // keeps the directory standing.
15738        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15739        remove_if_empty(&bay);
15740        assert!(bay.exists(), "non-empty directory must survive");
15741
15742        // Once the last entry is gone, so is the directory itself.
15743        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15744        remove_if_empty(&bay);
15745        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15746    }
15747
15748    // `round_is_clean` is the exact decision this task fixed: a round with a
15749    // seat that never answered must not read the same as a round every seat
15750    // actually reviewed. These are deterministic and process-free by design —
15751    // the equivalent end-to-end check (a real reviewer timing out under a
15752    // live graph run) is a genuine race against wall-clock contention, and a
15753    // spawn slow enough to blow even a generous budget under a loaded test
15754    // run must not turn this specific regression check flaky.
15755
15756    #[test]
15757    fn a_full_panel_that_found_nothing_is_clean() {
15758        assert!(round_is_clean(
15759            0,
15760            true,
15761            2,
15762            2,
15763            0,
15764            IncompleteReviewPolicy::Block
15765        ));
15766    }
15767
15768    #[test]
15769    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15770        assert!(!round_is_clean(
15771            0,
15772            true,
15773            1,
15774            2,
15775            0,
15776            IncompleteReviewPolicy::Block
15777        ));
15778    }
15779
15780    #[test]
15781    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15782        assert!(!round_is_clean(
15783            1,
15784            true,
15785            1,
15786            2,
15787            0,
15788            IncompleteReviewPolicy::Warn
15789        ));
15790    }
15791
15792    #[test]
15793    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15794        assert!(round_is_clean(
15795            0,
15796            true,
15797            1,
15798            2,
15799            0,
15800            IncompleteReviewPolicy::Warn
15801        ));
15802    }
15803
15804    #[test]
15805    fn a_full_panel_with_an_open_finding_is_not_clean() {
15806        assert!(!round_is_clean(
15807            1,
15808            true,
15809            2,
15810            2,
15811            0,
15812            IncompleteReviewPolicy::Block
15813        ));
15814    }
15815
15816    #[test]
15817    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15818        assert!(!round_is_clean(
15819            0,
15820            false,
15821            2,
15822            2,
15823            0,
15824            IncompleteReviewPolicy::Block
15825        ));
15826    }
15827
15828    // The stall this task closes: under the default `block` policy, a seat
15829    // missing only because it was rate limited must not force a wait for a
15830    // session limit that will not lift by the next round. `round_is_clean`
15831    // is where that quorum carve-out lives; the review loop around it never
15832    // changes what a reviewer's vote or a finding's severity means.
15833
15834    #[test]
15835    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15836        // 1 of 2 answered, and the one missing was quota'd — the exact
15837        // "review-2 rate limited (quota)" shape from the field report.
15838        assert!(round_is_clean(
15839            0,
15840            true,
15841            1,
15842            2,
15843            1,
15844            IncompleteReviewPolicy::Block
15845        ));
15846    }
15847
15848    #[test]
15849    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15850        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15851        // not a quota loss (`quota_missing` stays 0) — worth another try.
15852        assert!(!round_is_clean(
15853            0,
15854            true,
15855            1,
15856            2,
15857            0,
15858            IncompleteReviewPolicy::Block
15859        ));
15860    }
15861
15862    #[test]
15863    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15864        assert!(!round_is_clean(
15865            1,
15866            true,
15867            1,
15868            2,
15869            1,
15870            IncompleteReviewPolicy::Block
15871        ));
15872        assert!(!round_is_clean(
15873            0,
15874            false,
15875            1,
15876            2,
15877            1,
15878            IncompleteReviewPolicy::Block
15879        ));
15880    }
15881
15882    #[test]
15883    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15884        // Every seat quota'd, nobody answered: there is no panel to decide
15885        // on, so this must fall through to the existing block-and-retry
15886        // fallback rather than call an unreviewed patch clean.
15887        assert!(!round_is_clean(
15888            0,
15889            true,
15890            0,
15891            2,
15892            2,
15893            IncompleteReviewPolicy::Block
15894        ));
15895    }
15896
15897    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15898        CommandOutcome {
15899            command: "test".to_owned(),
15900            code,
15901            output_tail: String::new(),
15902            duration_ms: 0,
15903            resource_blocked,
15904            ..Default::default()
15905        }
15906    }
15907
15908    #[cfg(unix)]
15909    #[tokio::test]
15910    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15911        ask_test_home();
15912        let temp = tempfile::tempdir().unwrap();
15913        let mut runner = runner_at(RunStatus::Gating);
15914        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15915        let commands = vec![
15916            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15917            "touch must-not-run".to_owned(),
15918        ];
15919        let (outcomes, retried, pids) = run_e2e_with_retry(
15920            &mut runner.state,
15921            &shell,
15922            &commands,
15923            temp.path(),
15924            Duration::from_secs(5),
15925            "fixture",
15926            None,
15927        )
15928        .await;
15929        assert_eq!(outcomes.len(), 1);
15930        assert!(outcomes[0].resource_blocked);
15931        assert!(!outcomes[0].build_failed());
15932        assert!(!retried);
15933        assert!(pids.is_empty());
15934        assert!(!temp.path().join("must-not-run").exists());
15935        assert_eq!(
15936            runner.state.resource_block.as_ref().unwrap().kind,
15937            "incremental cache admission"
15938        );
15939    }
15940
15941    #[test]
15942    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15943        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15944        assert!(
15945            !verify_inconclusive(&[outcome(Some(1), false)]),
15946            "an ordinary failure is still evidence about the patch"
15947        );
15948        assert!(verify_inconclusive(&[outcome(None, true)]));
15949        assert!(
15950            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15951            "one inconclusive outcome taints the whole batch"
15952        );
15953        assert!(!verify_inconclusive(&[]));
15954    }
15955
15956    #[tokio::test]
15957    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15958        // Alive for the first two checks, then dead - confirms the loop
15959        // actually re-polls rather than deciding once and sleeping out the
15960        // ceiling regardless.
15961        let calls = std::sync::atomic::AtomicUsize::new(0);
15962        let started = Instant::now();
15963        wait_for_pids_with(
15964            &[123],
15965            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15966            Duration::from_millis(5),
15967            Duration::from_secs(5),
15968        )
15969        .await;
15970        assert!(
15971            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15972            "must keep checking rather than deciding on the first answer"
15973        );
15974        assert!(
15975            started.elapsed() < Duration::from_secs(1),
15976            "must return the moment it is confirmed dead, not wait out the ceiling"
15977        );
15978    }
15979
15980    #[tokio::test]
15981    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15982        let started = Instant::now();
15983        wait_for_pids_with(
15984            &[123],
15985            |_| true, // never reports dead
15986            Duration::from_millis(5),
15987            Duration::from_millis(30),
15988        )
15989        .await;
15990        let elapsed = started.elapsed();
15991        assert!(
15992            elapsed >= Duration::from_millis(30),
15993            "must not give up before its own ceiling: {elapsed:?}"
15994        );
15995        assert!(
15996            elapsed < Duration::from_secs(1),
15997            "must not wait past its own ceiling either: {elapsed:?}"
15998        );
15999    }
16000
16001    #[tokio::test]
16002    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
16003        let started = Instant::now();
16004        wait_for_pids_with(
16005            &[],
16006            |_| true,
16007            Duration::from_secs(5),
16008            Duration::from_secs(5),
16009        )
16010        .await;
16011        assert!(
16012            started.elapsed() < Duration::from_millis(200),
16013            "an empty pid list has nothing to confirm"
16014        );
16015    }
16016
16017    // `review_conclusion` is the exact decision the review hand-off task
16018    // fixed: a round budget spent (or a tree that stopped moving) must not
16019    // collapse into `Blocked` regardless of what verification actually
16020    // said. Deterministic and process-free for the same reason the
16021    // `round_is_clean` family above is.
16022    fn review_round(
16023        clean: bool,
16024        blocking: usize,
16025        answered: usize,
16026        expected: usize,
16027        progressed: bool,
16028        e2e_ok: bool,
16029    ) -> ReviewRound {
16030        ReviewRound {
16031            round: 1,
16032            head: "h".to_owned(),
16033            verified_head: None,
16034            verified_at: None,
16035            reviews: Vec::new(),
16036            e2e: vec![CommandOutcome {
16037                command: "test".to_owned(),
16038                code: Some(if e2e_ok { 0 } else { 1 }),
16039                output_tail: String::new(),
16040                duration_ms: 0,
16041                resource_blocked: false,
16042                ..Default::default()
16043            }],
16044            verify_retried: false,
16045            e2e_deferred: false,
16046            e2e_defer_reason: None,
16047            fix: None,
16048            blocking,
16049            answered,
16050            expected,
16051            clean,
16052            progressed,
16053            vote_split: false,
16054            reconsideration: Vec::new(),
16055            verdict: None,
16056        }
16057    }
16058
16059    #[test]
16060    fn review_conclusion_is_none_when_nothing_has_run() {
16061        assert_eq!(review_conclusion(&[], 3), None);
16062    }
16063
16064    #[test]
16065    fn review_conclusion_is_none_while_rounds_remain() {
16066        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
16067        assert_eq!(review_conclusion(&rounds, 3), None);
16068    }
16069
16070    #[test]
16071    fn review_conclusion_is_gating_once_a_round_is_clean() {
16072        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
16073        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
16074    }
16075
16076    #[test]
16077    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
16078        let rounds = vec![
16079            review_round(false, 1, 2, 2, true, true),
16080            review_round(false, 1, 2, 2, true, true),
16081        ];
16082        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
16083    }
16084
16085    #[test]
16086    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
16087        let rounds = vec![
16088            review_round(false, 1, 2, 2, true, true),
16089            review_round(false, 1, 2, 2, true, false),
16090        ];
16091        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
16092    }
16093
16094    #[test]
16095    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
16096        // Magi never got a command to run against this round's own head — a
16097        // resource-blocked attempt, not a red one — so this must never
16098        // settle on `Blocked` the way a genuine e2e failure would. `None`
16099        // here is what tells `Runner::review_loop` to retry the check
16100        // itself rather than trust this cheap recomputation with a verdict
16101        // it cannot actually produce.
16102        let mut blocked = review_round(false, 1, 2, 2, true, false);
16103        blocked.e2e[0].resource_blocked = true;
16104        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
16105        assert_eq!(review_conclusion(&rounds, 2), None);
16106    }
16107
16108    #[test]
16109    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
16110        // Missing input, not a verified tree — never a hand-off candidate.
16111        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
16112        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
16113    }
16114
16115    #[test]
16116    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
16117        let rounds = vec![
16118            review_round(false, 1, 2, 2, false, true),
16119            review_round(false, 1, 2, 2, false, true),
16120        ];
16121        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
16122    }
16123
16124    fn secs(n: u64) -> Duration {
16125        Duration::from_secs(n)
16126    }
16127
16128    /// A throwaway repo with one commit on `main`, for tests that need `merge`
16129    /// to make real (and, if it runs at all, real*ly fail*) git calls.
16130    #[tokio::test]
16131    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
16132        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
16133        if std::env::var_os(CHILD).is_none() {
16134            // Other tests reconcile every run in the process-global home,
16135            // briefly taking owner locks. This ancestry test expects an idle
16136            // predecessor, so give it its own process and pinned test home.
16137            let output = std::process::Command::new(std::env::current_exe().unwrap())
16138                .args([
16139                    "--exact",
16140                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
16141                    "--nocapture",
16142                ])
16143                .env(CHILD, "1")
16144                .env_remove("MAGI_WORKER_HOME")
16145                .env_remove("MAGI_WORKER_ID")
16146                .output()
16147                .unwrap();
16148            assert!(
16149                output.status.success()
16150                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
16151                "{}\n{}",
16152                String::from_utf8_lossy(&output.stdout),
16153                String::from_utf8_lossy(&output.stderr)
16154            );
16155            return;
16156        }
16157        ask_test_home();
16158        let tmp = tempfile::tempdir().unwrap();
16159        let repo = tmp.path().join("repo");
16160        std::fs::create_dir_all(&repo).unwrap();
16161        init_repo(&repo);
16162        let g = |args: &[&str]| {
16163            let out = std::process::Command::new("git")
16164                .args(args)
16165                .current_dir(&repo)
16166                .quiet()
16167                .output()
16168                .unwrap();
16169            assert!(
16170                out.status.success(),
16171                "{}",
16172                String::from_utf8_lossy(&out.stderr)
16173            );
16174        };
16175        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16176        g(&["checkout", "-b", "historical"]);
16177        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
16178        g(&["add", "."]);
16179        g(&["commit", "-m", "old alternative"]);
16180        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
16181        g(&["checkout", "-b", "magi/task-selected", &base]);
16182        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
16183        g(&["add", "."]);
16184        g(&["commit", "-m", "measurement infrastructure"]);
16185        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
16186        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
16187        g(&["add", "."]);
16188        g(&["commit", "-m", "dependent implementation"]);
16189        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
16190        g(&["checkout", "main"]);
16191        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
16192        g(&["add", "."]);
16193        g(&["commit", "-m", "unrelated base change"]);
16194        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
16195        let origin = tmp.path().join("origin.git");
16196        g(&[
16197            "clone",
16198            "--bare",
16199            repo.to_str().unwrap(),
16200            origin.to_str().unwrap(),
16201        ]);
16202        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
16203        g(&["fetch", "origin"]);
16204        let selection = crate::pr_recovery::Selection {
16205            url: "https://example.test/project/pull/1".into(),
16206            branch: "magi/task-selected".into(),
16207            head: head.clone(),
16208            source_head: None,
16209            source_run: None,
16210            source_proof: None,
16211            disposition: Some(crate::pr_recovery::Disposition::Review),
16212            instruction: "preserve measured behavior".into(),
16213            approved_at: jiff::Timestamp::now(),
16214        };
16215        let mut template = runner_at(RunStatus::Reviewing);
16216        template.state.repo = repo.clone();
16217        template.state.base_commit = current.clone();
16218        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16219        template.state.origin = Some(crate::run::Origin::queue("selected"));
16220        template.state.pr_head = Some(selection.branch.clone());
16221        template.state.pr_recovery = Some(selection.clone());
16222        let mut runner =
16223            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
16224                .await
16225                .unwrap();
16226        let wt = runner.state.winner().unwrap().worktree.clone();
16227        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
16228        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
16229        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
16230        assert!(runner.state.seeds.is_empty());
16231        assert_eq!(runner.state.instruction, "preserve measured behavior");
16232        runner.sync_to_base().await.unwrap();
16233        assert_eq!(
16234            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
16235            "prerequisite"
16236        );
16237        assert_eq!(
16238            std::fs::read_to_string(wt.join("implementation")).unwrap(),
16239            "measured implementation"
16240        );
16241        assert_eq!(
16242            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
16243            "current main change"
16244        );
16245        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16246        assert_eq!(
16247            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16248            head
16249        );
16250
16251        // A failed selected-source setup stays inspectable, never resumable as a new competition.
16252        let mut partial = runner_at(RunStatus::Reviewing);
16253        partial.state.repo = repo.clone();
16254        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
16255        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
16256            run: Some("exit 1".into()),
16257            ..Default::default()
16258        }];
16259        let selection = runner.state.pr_recovery.clone().unwrap();
16260        partial.state.pr_recovery = Some(selection.clone());
16261        partial.state.pr_head = Some(selection.branch.clone());
16262        partial.state.origin = Some(crate::run::Origin::queue("selected"));
16263        let id = partial.state.id.clone();
16264        let error = match Runner::open_selected(
16265            &repo,
16266            partial.state,
16267            partial.roles,
16268            1,
16269            runner.state.base_commit.clone(),
16270            selection,
16271        )
16272        .await
16273        {
16274            Ok(_) => panic!("setup must fail"),
16275            Err(e) => e,
16276        };
16277        assert_eq!(
16278            error
16279                .downcast_ref::<crate::run::StartupFailure>()
16280                .unwrap()
16281                .run,
16282            id
16283        );
16284        let failed = RunState::load(&id).unwrap();
16285        assert_eq!(failed.status, RunStatus::Failed);
16286        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
16287        assert!(Runner::resume(&id).is_err());
16288        runner.state.status = RunStatus::Ready;
16289        runner.state.driver_exited = true;
16290        runner.state.save().unwrap();
16291        let mut retry = runner_at(RunStatus::Reviewing);
16292        retry.state.repo = repo.clone();
16293        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
16294        let mut reselected = runner.state.pr_recovery.clone().unwrap();
16295        reselected.approved_at = jiff::Timestamp::now();
16296        retry.state.origin = Some(crate::run::Origin::queue("selected"));
16297        retry.state.pr_head = Some(reselected.branch.clone());
16298        retry.state.pr_recovery = Some(reselected.clone());
16299        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
16300            .await
16301            .unwrap();
16302        let restarted = Runner::open_selected(
16303            &repo,
16304            retry.state,
16305            retry.roles,
16306            1,
16307            runner.state.base_commit.clone(),
16308            reselected,
16309        )
16310        .await
16311        .unwrap();
16312        assert_eq!(
16313            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
16314                .await
16315                .unwrap(),
16316            head
16317        );
16318        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16319        assert_eq!(
16320            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16321            head
16322        );
16323    }
16324
16325    #[tokio::test]
16326    #[cfg(unix)]
16327    async fn fallback_and_interrupted_restoration_require_coordination() {
16328        use std::os::fd::AsRawFd as _;
16329        ask_test_home();
16330        let tmp = tempfile::tempdir().unwrap();
16331        let mut runner = registered_runner(tmp.path()).await;
16332        runner.state.config.graph.timeout_resource_wait = 1;
16333        let winner = runner.state.candidates[0].clone();
16334        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16335        let leftover = winner.worktree.join("leftover");
16336        std::fs::write(&leftover, "untrusted edits").unwrap();
16337        let next = tmp.path().join("next-fixer");
16338        let mut failed = spec("first");
16339        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
16340        let mut successor = spec("second");
16341        successor.command = vec![
16342            "sh".into(),
16343            "-c".into(),
16344            format!("touch '{}'; echo done", next.display()),
16345        ];
16346        let attempts = vec![
16347            (failed.clone(), "first".into()),
16348            (successor.clone(), "second".into()),
16349        ];
16350        let lock_path = runner.state.repo.join(".git/updater.lock");
16351        let external = std::fs::File::create(&lock_path).unwrap();
16352        assert_eq!(
16353            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16354            0
16355        );
16356        let artifacts = tmp.path().join("artifacts");
16357        let build = |spec, seat| SeatJob {
16358            spec,
16359            seat,
16360            cwd: winner.worktree.clone(),
16361            prompt: "fixture".into(),
16362            timeout: Duration::from_secs(10),
16363            allow_write: true,
16364            sessions: false,
16365            artifacts: artifacts.clone(),
16366            stem: "fix".into(),
16367            handover: None,
16368        };
16369        let (_, _, out) = runner
16370            .ask_fixer_among(
16371                attempts.clone(),
16372                "graft",
16373                None,
16374                Some((&winner.worktree, &head)),
16375                build,
16376            )
16377            .await;
16378        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
16379        assert!(leftover.exists(), "contention must prevent clean");
16380        assert!(!next.exists());
16381        assert!(runner.state.handovers.is_empty());
16382        // Early interrupted-repair rollback uses the same protected route.
16383        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16384            from_run: "earlier".into(),
16385            generation: 1,
16386            mode: crate::recovery::Mode::VerifyRepair,
16387            reasons: Vec::new(),
16388            reviewed_head: None,
16389            rounds: Vec::new(),
16390            open_findings: Vec::new(),
16391            evidence: None,
16392            criteria_inherited: true,
16393            repair: crate::recovery::Repair::Started {
16394                before: head.clone(),
16395            },
16396        });
16397        assert!(
16398            runner
16399                .recovery_repair(&winner)
16400                .await
16401                .unwrap_err()
16402                .is::<crate::repo_lock::ResourceBlocked>()
16403        );
16404        assert!(matches!(
16405            runner.state.recovery.as_ref().unwrap().repair,
16406            crate::recovery::Repair::Started { .. }
16407        ));
16408        assert!(leftover.exists());
16409        drop(external);
16410        runner.recovery_repair(&winner).await.unwrap();
16411        assert!(!leftover.exists());
16412        assert!(matches!(
16413            runner.state.recovery.as_ref().unwrap().repair,
16414            crate::recovery::Repair::Done { .. }
16415        ));
16416        // A hard lock-open failure also leaves HEAD and untracked work intact.
16417        std::fs::remove_file(&lock_path).unwrap();
16418        std::fs::create_dir(&lock_path).unwrap();
16419        std::fs::write(&leftover, "untrusted edits").unwrap();
16420        let (_, _, out) = runner
16421            .ask_fixer_among(
16422                attempts,
16423                "graft",
16424                None,
16425                Some((&winner.worktree, &head)),
16426                build,
16427            )
16428            .await;
16429        assert!(matches!(out, AgentOutcome::Failed(_)));
16430        assert!(leftover.exists());
16431        assert!(!next.exists());
16432        assert_eq!(
16433            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16434            head
16435        );
16436    }
16437
16438    #[cfg(unix)]
16439    async fn registered_runner(root: &Path) -> Runner {
16440        repository_runner(root, crate::config::test_coordination()).await
16441    }
16442
16443    async fn repository_runner(
16444        root: &Path,
16445        coordination: Option<crate::config::Coordination>,
16446    ) -> Runner {
16447        ask_test_home();
16448        let repo = root.join("repo");
16449        std::fs::create_dir_all(&repo).unwrap();
16450        init_repo(&repo);
16451        if coordination.is_some() {
16452            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16453        }
16454        let mut runner = runner_at(RunStatus::Prep);
16455        runner.state.repo = repo.clone();
16456        runner.state.config.coordination = coordination;
16457        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16458        runner.state.config.graph.worktree_root = Some(root.join("wt"));
16459        runner.state.config.graph.advise = false;
16460        runner.roles.implementers = vec![spec("implement")];
16461        runner.roles.judges = vec![spec("judge")];
16462        runner.prep().await.unwrap();
16463        runner
16464    }
16465
16466    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
16467
16468    #[tokio::test]
16469    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
16470        let tmp = tempfile::tempdir().unwrap();
16471        let mut runner = repository_runner(tmp.path(), None).await;
16472        let prompts = runner.state.config.prompts.clone();
16473        let run = runner.state.id.clone();
16474        let ctx = WaveCtx {
16475            carry_seats: false,
16476            pauses: None,
16477            run: &run,
16478            node: "advise",
16479            prompts: &prompts,
16480            cache: None,
16481            round: None,
16482        };
16483        let jobs: Vec<_> = ["alpha", "beta"]
16484            .into_iter()
16485            .map(|id| SeatJob {
16486                spec: scripted(id, AUTH_OUTAGE),
16487                seat: SeatState::new(id, id, 7),
16488                prompt: "propose".into(),
16489                cwd: runner.state.candidates[0].worktree.clone(),
16490                timeout: Duration::from_secs(10),
16491                allow_write: false,
16492                sessions: false,
16493                artifacts: agent::artifacts_dir(&runner.state.dir()),
16494                stem: id.into(),
16495                handover: None,
16496            })
16497            .collect();
16498        let mut losses = Vec::new();
16499        let results = ask_wave_with(
16500            jobs.clone(),
16501            runner.sem.clone(),
16502            2,
16503            &[],
16504            &ctx,
16505            &mut losses,
16506            &mut runner.state,
16507            &|_: &str| Ok(()),
16508        )
16509        .await;
16510        assert!(
16511            results
16512                .iter()
16513                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
16514        );
16515        assert_eq!(runner.state.quota.len(), 2);
16516        assert!(
16517            runner
16518                .state
16519                .quota
16520                .iter()
16521                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
16522        );
16523        assert!(!runner.state.advise_attempted);
16524        runner.stop_for_resource().unwrap();
16525        assert_eq!(runner.state.status, RunStatus::Blocked);
16526        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
16527        assert_eq!(
16528            runner.state.resource_block.as_ref().unwrap().kind,
16529            "agent authentication"
16530        );
16531        // A machine loss followed by an ordinary failure is not evidence
16532        // that the whole node was unavailable, and must not earn a refund.
16533        runner.state.resource_block = None;
16534        runner.state.quota.clear();
16535        let mut mixed = jobs;
16536        mixed[1].spec.command = vec!["false".into()];
16537        let results = ask_wave_with(
16538            mixed,
16539            runner.sem.clone(),
16540            0,
16541            &[],
16542            &ctx,
16543            &mut losses,
16544            &mut runner.state,
16545            &|_: &str| Ok(()),
16546        )
16547        .await;
16548        assert!(results.iter().all(|(_, res, _)| res.is_err()));
16549        assert!(runner.state.resource_block.is_none());
16550        assert_eq!(losses.len(), 1);
16551    }
16552
16553    #[tokio::test]
16554    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16555        let tmp = tempfile::tempdir().unwrap();
16556        let mut runner = repository_runner(tmp.path(), None).await;
16557        let implementer = scripted("implement", AUTH_OUTAGE);
16558        runner.roles.implementers = vec![implementer.clone()];
16559        runner.state.config.agents = vec![implementer];
16560        runner.implement().await.unwrap();
16561        assert_eq!(runner.state.status, RunStatus::Blocked);
16562        assert_eq!(runner.state.quota.len(), 1);
16563        assert_eq!(
16564            runner.state.quota[0].cause,
16565            agent::QuotaCause::Authentication
16566        );
16567        let candidate = &runner.state.candidates[0];
16568        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16569        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16570    }
16571
16572    #[tokio::test]
16573    #[cfg(unix)]
16574    async fn parked_implementer_persists_completed_work() {
16575        for registered in [false, true] {
16576            let tmp = tempfile::tempdir().unwrap();
16577            let mut runner = registered_runner(tmp.path()).await;
16578            if !registered {
16579                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16580            }
16581            let marker = tmp.path().join("started");
16582            let release = tmp.path().join("release");
16583            let mut implementer = spec("implement");
16584            implementer.command = vec![
16585                "sh".into(),
16586                "-c".into(),
16587                format!(
16588                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16589                    marker.display(),
16590                    release.display()
16591                ),
16592            ];
16593            runner.roles.implementers = vec![implementer.clone()];
16594            runner.state.config.agents = vec![implementer];
16595            let pause = runner.pause.clone();
16596            let (result, ()) = tokio::join!(runner.implement(), async {
16597                tokio::time::timeout(Duration::from_secs(10), async {
16598                    while !marker.exists() {
16599                        tokio::time::sleep(Duration::from_millis(10)).await;
16600                    }
16601                })
16602                .await
16603                .unwrap();
16604                pause.park();
16605                std::fs::write(&release, "go").unwrap();
16606            });
16607            result.unwrap();
16608            let candidate = &runner.state.candidates[0];
16609            assert!(candidate.commits > 0, "{candidate:?}");
16610            assert!(candidate.summary.contains("saved-result"));
16611            assert_eq!(candidate.files, 1);
16612            let before = candidate.commits;
16613            runner.implement().await.unwrap();
16614            assert_eq!(runner.state.candidates[0].commits, before);
16615        }
16616    }
16617
16618    #[tokio::test]
16619    #[cfg(unix)]
16620    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16621        let tmp = tempfile::tempdir().unwrap();
16622        let mut runner = registered_runner(tmp.path()).await;
16623        let winner = runner.state.candidates[0].clone();
16624        let cache = tmp.path().join("cache");
16625        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16626        runner.state.config.graph.timeout_resource_wait = 0;
16627        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16628        let crate::cache::AcquireOutcome::Acquired(held) =
16629            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16630        else {
16631            panic!("cache must be free")
16632        };
16633        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16634            from_run: "earlier".into(),
16635            generation: 1,
16636            mode: crate::recovery::Mode::VerifyRepair,
16637            reasons: Vec::new(),
16638            reviewed_head: None,
16639            rounds: Vec::new(),
16640            open_findings: Vec::new(),
16641            evidence: None,
16642            criteria_inherited: true,
16643            repair: crate::recovery::Repair::NotStarted,
16644        });
16645        runner.recovery_repair(&winner).await.unwrap();
16646        assert!(matches!(
16647            runner.state.recovery.as_ref().unwrap().repair,
16648            crate::recovery::Repair::WaitingForRestore { .. }
16649        ));
16650        drop(held);
16651        runner.state.resource_block = None;
16652        runner.state.config.graph.timeout_resource_wait = 1;
16653        runner.recovery_repair(&winner).await.unwrap();
16654        assert!(matches!(
16655            runner.state.recovery.as_ref().unwrap().repair,
16656            crate::recovery::Repair::Done { .. }
16657        ));
16658        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16659    }
16660
16661    #[tokio::test]
16662    #[cfg(unix)]
16663    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16664        use std::os::fd::AsRawFd as _;
16665        for graft in [false, true] {
16666            let tmp = tempfile::tempdir().unwrap();
16667            let mut runner = registered_runner(tmp.path()).await;
16668            runner.state.config.graph.timeout_resource_wait = 1;
16669            let winner = runner.state.candidates[0].clone();
16670            let marker = tmp.path().join("fixer-started");
16671            let mut fixer = spec("fixer");
16672            fixer.command = vec![
16673                "sh".into(),
16674                "-c".into(),
16675                format!("echo started >> '{}'; echo done", marker.display()),
16676            ];
16677            runner.roles.fixer = Some(vec![fixer]);
16678            if graft {
16679                let mut loser = winner.clone();
16680                loser.label = 'B';
16681                loser.index = 1;
16682                runner.state.candidates.push(loser);
16683                runner.state.config.graph.graft_runner_up = true;
16684                runner.state.tally = Some(Tally {
16685                    first_choice: BTreeMap::new(),
16686                    borda: BTreeMap::new(),
16687                    winner: winner.label,
16688                    rankings: 1,
16689                    unanimous_initial: true,
16690                    deliberated: false,
16691                    changed_votes: 0,
16692                    unanimous_final: true,
16693                    tie_break: None,
16694                    judges: 1,
16695                    present: 1,
16696                    quorum: 1,
16697                    met_quorum: true,
16698                    uncontested: None,
16699                });
16700                runner.state.judgements.push(crate::run::Judgement {
16701                    judge: 1,
16702                    seat: "judge-1".into(),
16703                    agent: "judge".into(),
16704                    ranking: vec![winner.label, 'B'],
16705                    reasons: BTreeMap::new(),
16706                    confidence: None,
16707                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16708                    order: vec![0, 1],
16709                    failed: None,
16710                    duration_ms: 0,
16711                });
16712            } else {
16713                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16714                    from_run: "earlier".into(),
16715                    generation: 1,
16716                    mode: crate::recovery::Mode::VerifyRepair,
16717                    reasons: Vec::new(),
16718                    reviewed_head: None,
16719                    rounds: Vec::new(),
16720                    open_findings: Vec::new(),
16721                    evidence: None,
16722                    criteria_inherited: true,
16723                    repair: crate::recovery::Repair::NotStarted,
16724                });
16725            }
16726            let reader = crate::repo_lock::SeatLease::for_checkout(
16727                &winner.worktree,
16728                false,
16729                crate::config::test_coordination().as_ref(),
16730            )
16731            .await
16732            .unwrap();
16733            let pause = runner.pause.clone();
16734            let (result, ()) = tokio::join!(
16735                async {
16736                    if graft {
16737                        runner.graft().await
16738                    } else {
16739                        runner.recovery_repair(&winner).await
16740                    }
16741                },
16742                async {
16743                    tokio::time::sleep(Duration::from_millis(100)).await;
16744                    pause.park();
16745                }
16746            );
16747            result.unwrap();
16748            assert!(!marker.exists(), "a blocked seat must not spawn");
16749            // Exercise the persisted state, as a binary replacement/resume does.
16750            runner.state = RunState::load(&runner.state.id).unwrap();
16751            if graft {
16752                assert_eq!(
16753                    runner.state.graft.as_ref().unwrap().outcome,
16754                    GraftOutcome::WaitingForRestore
16755                );
16756            } else {
16757                assert!(matches!(
16758                    runner.state.recovery.as_ref().unwrap().repair,
16759                    crate::recovery::Repair::WaitingForRestore { .. }
16760                ));
16761            }
16762            drop(reader);
16763            runner.pause = Pause::new();
16764            runner.state.resource_block = None;
16765            // Deferred restoration must still respect an external lock owner.
16766            let external =
16767                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16768            assert_eq!(
16769                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16770                0
16771            );
16772            let leftover = winner.worktree.join("leftover");
16773            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16774            let result = if graft {
16775                runner.graft().await
16776            } else {
16777                runner.recovery_repair(&winner).await
16778            };
16779            assert!(
16780                result
16781                    .unwrap_err()
16782                    .is::<crate::repo_lock::ResourceBlocked>()
16783            );
16784            assert!(leftover.exists());
16785            assert!(!marker.exists());
16786            drop(external);
16787            runner.state.resource_block = None;
16788            let result = if graft {
16789                runner.graft().await
16790            } else {
16791                runner.recovery_repair(&winner).await
16792            };
16793            result.unwrap();
16794            assert!(!leftover.exists(), "restore must precede retry");
16795            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16796            if graft {
16797                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16798            } else {
16799                assert!(matches!(
16800                    runner.state.recovery.as_ref().unwrap().repair,
16801                    crate::recovery::Repair::Done { .. }
16802                ));
16803            }
16804        }
16805    }
16806
16807    #[tokio::test]
16808    #[cfg(unix)]
16809    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16810        use std::os::fd::AsRawFd as _;
16811        let tmp = tempfile::tempdir().unwrap();
16812        let mut runner = registered_runner(tmp.path()).await;
16813        runner.state.config.graph.timeout_resource_wait = 1;
16814        let winner = runner.state.candidates[0].clone();
16815        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16816        runner.state.tally = Some(Tally {
16817            first_choice: BTreeMap::new(),
16818            borda: BTreeMap::new(),
16819            winner: winner.label,
16820            rankings: 0,
16821            unanimous_initial: false,
16822            deliberated: false,
16823            changed_votes: 0,
16824            unanimous_final: false,
16825            tie_break: None,
16826            judges: 0,
16827            present: 0,
16828            quorum: 0,
16829            met_quorum: true,
16830            uncontested: Some("fixture".into()),
16831        });
16832        runner.state.graft = Some(GraftRecord {
16833            pre: pre.clone(),
16834            post: None,
16835            lines: None,
16836            limit: None,
16837            agent: None,
16838            outcome: GraftOutcome::Running,
16839            requested: Vec::new(),
16840            adoption: None,
16841            adoption_error: None,
16842        });
16843        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16844        git::commit_all(&winner.worktree, "unfinished graft")
16845            .await
16846            .unwrap();
16847        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16848        let leftover = winner.worktree.join("leftover");
16849        std::fs::write(&leftover, "untrusted edits").unwrap();
16850        let path = runner.state.repo.join(".git/updater.lock");
16851        let external = std::fs::File::create(&path).unwrap();
16852        assert_eq!(
16853            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16854            0
16855        );
16856        assert!(
16857            runner
16858                .graft()
16859                .await
16860                .unwrap_err()
16861                .is::<crate::repo_lock::ResourceBlocked>()
16862        );
16863        assert!(matches!(
16864            runner.state.graft.as_ref().unwrap().outcome,
16865            GraftOutcome::Running
16866        ));
16867        assert_eq!(
16868            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16869            unfinished
16870        );
16871        assert!(leftover.exists());
16872        drop(external);
16873        std::fs::remove_file(&path).unwrap();
16874        std::fs::create_dir(&path).unwrap();
16875        assert!(runner.graft().await.is_err());
16876        assert!(matches!(
16877            runner.state.graft.as_ref().unwrap().outcome,
16878            GraftOutcome::Running
16879        ));
16880        assert_eq!(
16881            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16882            unfinished
16883        );
16884        assert!(leftover.exists());
16885        std::fs::remove_dir(&path).unwrap();
16886        runner.graft().await.unwrap();
16887        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16888        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16889        assert!(!leftover.exists());
16890    }
16891
16892    #[tokio::test]
16893    #[cfg(unix)]
16894    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16895        use std::os::fd::AsRawFd as _;
16896        let tmp = tempfile::tempdir().unwrap();
16897        let mut runner = registered_runner(tmp.path()).await;
16898        runner.state.prep_complete = Some(false);
16899        runner.state.config.graph.timeout_resource_wait = 1;
16900        runner.state.save().unwrap();
16901        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16902        assert_eq!(
16903            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16904            0
16905        );
16906        runner.execute().await.unwrap();
16907        let disk = RunState::load(&runner.state.id).unwrap();
16908        assert!(disk.driver_exited);
16909        assert_eq!(disk.driver_pid, None);
16910        assert_eq!(runner.state.status, RunStatus::Blocked);
16911        assert_eq!(
16912            runner.state.resource_block.as_ref().unwrap().kind,
16913            "repository coordination"
16914        );
16915        assert!(runner.state.prep_failure.is_none());
16916        assert!(runner.state.seats.is_empty());
16917        runner.pause.park();
16918        // Include headroom for Git subprocesses under parallel test load;
16919        // the repository contention deadline itself remains one second.
16920        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16921            .await
16922            .unwrap()
16923            .unwrap();
16924        assert!(runner.state.parked);
16925        assert!(runner.state.prep_failure.is_none());
16926        let disk = RunState::load(&runner.state.id).unwrap();
16927        assert!(disk.driver_exited);
16928        assert_eq!(disk.driver_pid, None);
16929    }
16930
16931    #[tokio::test]
16932    #[cfg(unix)]
16933    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16934        use std::os::fd::AsRawFd as _;
16935        let tmp = tempfile::tempdir().unwrap();
16936        let mut runner = registered_runner(tmp.path()).await;
16937        runner.state.prep_complete = Some(false);
16938        runner.state.config.graph.timeout_resource_wait = 30;
16939        runner.state.save().unwrap();
16940        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16941        assert_eq!(
16942            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16943            0
16944        );
16945        assert!(
16946            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16947                .await
16948                .is_err()
16949        );
16950        let disk = RunState::load(&runner.state.id).unwrap();
16951        assert!(disk.driver_exited);
16952        assert_eq!(disk.driver_pid, None);
16953        assert!(disk.status.resumable());
16954        assert!(runner.state.driver_exited);
16955        assert_eq!(runner.state.driver_pid, None);
16956        runner.state.save().unwrap();
16957        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16958    }
16959
16960    #[tokio::test]
16961    #[cfg(unix)]
16962    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16963        let tmp = tempfile::tempdir().unwrap();
16964        let mut runner = registered_runner(tmp.path()).await;
16965        let winner = runner.state.candidates[0].clone();
16966        let cache = tmp.path().join("cache");
16967        let started = tmp.path().join("pre-gate-started");
16968        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16969        runner.state.config.verify.gate =
16970            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16971        let home = crate::run::home();
16972        let owner =
16973            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16974        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16975            crate::cache::AcquireOutcome::Acquired(g) => g,
16976            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16977        };
16978        let mut gate = Box::pin(runner.run_gate(&winner));
16979        assert!(
16980            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16981                .await
16982                .is_err()
16983        );
16984        assert!(!started.exists(), "pre-gate must wait for the cache too");
16985        // Simulate the wave that already owns the cache entering invoke.
16986        // It must obtain the editor reservation and finish without waiting
16987        // for the gate that is queued behind its cache.
16988        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16989        let editor = crate::repo_lock::SeatLease::checkout_with(
16990            &winner.worktree,
16991            true,
16992            crate::config::test_coordination().as_ref(),
16993            &wait,
16994        )
16995        .await
16996        .unwrap();
16997        drop(editor);
16998        guard.release();
16999        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17000            .await
17001            .unwrap()
17002            .unwrap();
17003        drop(gate);
17004        assert!(outcomes.iter().all(CommandOutcome::ok));
17005        assert!(started.exists());
17006    }
17007
17008    #[tokio::test]
17009    #[cfg(unix)]
17010    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
17011        use std::os::fd::AsRawFd as _;
17012
17013        ask_test_home();
17014        let tmp = tempfile::tempdir().unwrap();
17015        let repo = tmp.path().join("repo");
17016        std::fs::create_dir_all(&repo).unwrap();
17017        init_repo(&repo);
17018        let common = repo.join(".git");
17019        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17020        let mut runner = runner_at(RunStatus::Prep);
17021        runner.state.repo = repo.clone();
17022        runner.state.config.coordination = crate::config::test_coordination();
17023        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17024        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17025        runner.state.config.graph.advise = false;
17026        runner.roles.implementers = vec![spec("implement")];
17027        runner.roles.judges = vec![spec("judge")];
17028        runner.prep().await.unwrap();
17029        let winner = runner.state.candidates[0].clone();
17030        // Emulate edits already left by a completed seat. The fixture CLI
17031        // only reports completion; it performs no repository operations.
17032        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
17033        let completed = tmp.path().join("seat-completed");
17034        runner.roles.implementers[0].command = vec![
17035            "sh".into(),
17036            "-c".into(),
17037            format!("touch '{}'; echo completed", completed.display()),
17038        ];
17039        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
17040        assert_eq!(
17041            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17042            0
17043        );
17044        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17045        let mut implement = Box::pin(runner.implement());
17046        tokio::select! {
17047            result = &mut implement => panic!("rescue must wait: {result:?}"),
17048            result = tokio::time::timeout(Duration::from_secs(10), async {
17049                while !completed.exists() {
17050                    tokio::time::sleep(Duration::from_millis(20)).await;
17051                }
17052            }) => result.unwrap(),
17053        }
17054        assert!(
17055            tokio::time::timeout(Duration::from_millis(200), &mut implement)
17056                .await
17057                .is_err()
17058        );
17059        assert_eq!(
17060            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17061            before
17062        );
17063        assert_eq!(
17064            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17065            0
17066        );
17067        tokio::time::timeout(Duration::from_secs(10), &mut implement)
17068            .await
17069            .unwrap()
17070            .unwrap();
17071        drop(implement);
17072        assert_ne!(
17073            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17074            before
17075        );
17076        assert!(git::is_clean(&winner.worktree).await.unwrap());
17077
17078        let started = tmp.path().join("pre-gate-started");
17079        let proceed = tmp.path().join("pre-gate-proceed");
17080        let checked = tmp.path().join("gate-ran");
17081        runner.state.config.verify.pre_gate = vec![format!(
17082            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17083            started.display(),
17084            proceed.display()
17085        )];
17086        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
17087        assert_eq!(
17088            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17089            0
17090        );
17091        let mut gate = Box::pin(runner.run_gate(&winner));
17092        assert!(
17093            tokio::time::timeout(Duration::from_millis(200), &mut gate)
17094                .await
17095                .is_err()
17096        );
17097        assert!(!started.exists());
17098        assert!(!checked.exists());
17099        assert!(git::is_clean(&winner.worktree).await.unwrap());
17100        assert_eq!(
17101            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17102            0
17103        );
17104        tokio::select! {
17105            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
17106            result = tokio::time::timeout(Duration::from_secs(10), async {
17107                while !started.exists() {
17108                    tokio::time::sleep(Duration::from_millis(20)).await;
17109                }
17110            }) => result.unwrap(),
17111        }
17112        assert_eq!(
17113            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17114            -1,
17115            "mechanical edits must hold the real lock"
17116        );
17117        std::fs::write(proceed, "ready").unwrap();
17118        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17119            .await
17120            .unwrap()
17121            .unwrap();
17122        drop(gate);
17123        assert!(outcomes.iter().all(CommandOutcome::ok));
17124        assert!(checked.exists());
17125        assert!(runner.state.pre_gate_commit.is_some());
17126        assert!(git::is_clean(&winner.worktree).await.unwrap());
17127        assert_eq!(
17128            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17129            0,
17130            "gate completion must release coordination"
17131        );
17132        drop(outsider);
17133        std::fs::remove_file(common.join("updater.lock")).unwrap();
17134        std::fs::create_dir(common.join("updater.lock")).unwrap();
17135        std::fs::remove_file(&started).unwrap();
17136        std::fs::remove_file(&checked).unwrap();
17137        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17138        let error = runner.run_gate(&winner).await.unwrap_err();
17139        assert!(
17140            error
17141                .to_string()
17142                .contains("acquire mandatory repository lock")
17143        );
17144        assert!(
17145            !started.exists(),
17146            "failed acquisition must prevent pre-gate"
17147        );
17148        assert!(!checked.exists(), "failed acquisition must prevent gate");
17149        assert!(git::is_clean(&winner.worktree).await.unwrap());
17150        assert_eq!(
17151            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17152            head
17153        );
17154    }
17155
17156    #[tokio::test]
17157    #[cfg(unix)]
17158    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
17159        use std::os::fd::AsRawFd as _;
17160        use std::time::Duration;
17161
17162        ask_test_home();
17163        let tmp = tempfile::tempdir().unwrap();
17164        let repo = tmp.path().join("repo");
17165        std::fs::create_dir_all(&repo).unwrap();
17166        init_repo(&repo);
17167        let common = repo.join(".git");
17168        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17169        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
17170        assert_eq!(
17171            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17172            0
17173        );
17174        let mut runner = runner_at(RunStatus::Prep);
17175        runner.state.repo = repo.clone();
17176        runner.state.config.coordination = crate::config::test_coordination();
17177        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17178        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17179        runner.state.config.graph.advise = true;
17180        runner.state.config.graph.advisors = 1;
17181        runner.roles.implementers = vec![spec("implement")];
17182        runner.roles.judges = vec![spec("judge")];
17183        let root = runner.state.worktree_root();
17184        let started = tmp.path().join("setup-started");
17185        let proceed = tmp.path().join("setup-proceed");
17186        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17187            run: Some(format!(
17188                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17189                started.display(),
17190                proceed.display()
17191            )),
17192            ..Default::default()
17193        }];
17194        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
17195        let config = git::git(&repo, &["config", "--local", "--list"])
17196            .await
17197            .unwrap();
17198        let mut prep = Box::pin(runner.prep());
17199        assert!(
17200            tokio::time::timeout(Duration::from_millis(200), &mut prep)
17201                .await
17202                .is_err()
17203        );
17204        assert!(
17205            !root.exists(),
17206            "contention must prevent even checkout creation"
17207        );
17208        assert!(!started.exists(), "contention must prevent setup");
17209        assert_eq!(
17210            git::git(&repo, &["branch", "--list"]).await.unwrap(),
17211            branches
17212        );
17213        assert_eq!(
17214            git::git(&repo, &["config", "--local", "--list"])
17215                .await
17216                .unwrap(),
17217            config
17218        );
17219        drop(lock);
17220        tokio::select! {
17221            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
17222            result = tokio::time::timeout(Duration::from_secs(10), async {
17223                while !started.exists() {
17224                    tokio::time::sleep(Duration::from_millis(20)).await;
17225                }
17226            }) => result.unwrap(),
17227        }
17228        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
17229        assert_eq!(
17230            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17231            -1
17232        );
17233        assert!(
17234            tokio::time::timeout(
17235                Duration::from_millis(100),
17236                crate::repo_lock::SeatLease::for_checkout(
17237                    &repo,
17238                    true,
17239                    crate::config::test_coordination().as_ref()
17240                )
17241            )
17242            .await
17243            .is_err(),
17244            "preparation must also exclude local editors"
17245        );
17246        std::fs::write(proceed, "ready").unwrap();
17247        tokio::time::timeout(Duration::from_secs(10), &mut prep)
17248            .await
17249            .unwrap()
17250            .unwrap();
17251        drop(prep);
17252        assert_eq!(runner.state.prep_complete, Some(true));
17253        assert!(root.join("judge-1").exists());
17254        assert!(root.join("advisor-1").exists());
17255        assert_eq!(
17256            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17257            0
17258        );
17259    }
17260
17261    #[tokio::test]
17262    #[cfg(unix)]
17263    async fn preparation_lock_failure_prevents_repository_changes() {
17264        ask_test_home();
17265        let tmp = tempfile::tempdir().unwrap();
17266        let repo = tmp.path().join("repo");
17267        std::fs::create_dir_all(&repo).unwrap();
17268        init_repo(&repo);
17269        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
17270        // A directory at the required lock path makes opening the real lock
17271        // fail, rather than merely exercising an invalid registration.
17272        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
17273        let mut runner = runner_at(RunStatus::Prep);
17274        runner.state.repo = repo.clone();
17275        runner.state.config.coordination = crate::config::test_coordination();
17276        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17277        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17278        runner.roles.implementers = vec![spec("implement")];
17279        let error = runner.prep().await.unwrap_err();
17280        assert!(
17281            error
17282                .to_string()
17283                .contains("acquire mandatory repository lock")
17284        );
17285        assert!(!runner.state.worktree_root().exists());
17286        assert!(runner.state.candidates.is_empty());
17287        assert!(!repo.join(".git/config.worktree").exists());
17288        assert_eq!(
17289            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
17290            "* main"
17291        );
17292    }
17293
17294    #[tokio::test]
17295    async fn preparation_records_creation_intent_before_git_can_fail() {
17296        ask_test_home();
17297        let tmp = tempfile::tempdir().unwrap();
17298        let repo = tmp.path().join("repo");
17299        std::fs::create_dir_all(&repo).unwrap();
17300        init_repo(&repo);
17301        let mut runner = runner_at(RunStatus::Prep);
17302        runner.state.repo = repo.clone();
17303        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17304        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17305        runner.state.config.blind.commit_msg_hook = false;
17306        runner.roles.implementers = vec![spec("one")];
17307        let label = blind::assign_labels(1, runner.state.seed)[0];
17308        let branch = runner.state.branch_for(label);
17309        // A conflicting branch makes Git refuse creation before a candidate
17310        // can be registered. The durable intent must still identify it.
17311        git::git(&repo, &["branch", &branch]).await.unwrap();
17312        assert!(runner.prep().await.is_err());
17313        let saved = RunState::load(&runner.state.id).unwrap();
17314        assert!(saved.candidates.is_empty());
17315        let event = saved
17316            .events
17317            .iter()
17318            .find(|e| e.node == "prep-intent")
17319            .unwrap();
17320        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
17321        assert_eq!(intent["branch"], branch);
17322        assert_eq!(intent["start"], runner.state.base_commit);
17323        assert_eq!(
17324            intent["worktree"],
17325            runner
17326                .state
17327                .worktree_root()
17328                .join(format!("cand-{label}"))
17329                .to_string_lossy()
17330                .as_ref()
17331        );
17332        assert_eq!(intent["picks"], serde_json::json!([]));
17333    }
17334
17335    #[tokio::test]
17336    async fn invalid_pinned_sources_create_no_partial_worktrees() {
17337        ask_test_home();
17338        let tmp = tempfile::tempdir().unwrap();
17339        let repo = tmp.path().join("repo");
17340        std::fs::create_dir_all(&repo).unwrap();
17341        init_repo(&repo);
17342        let mut runner = runner_at(RunStatus::Prep);
17343        runner.state.repo = repo.clone();
17344        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17345        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17346        runner.state.sources.pick_commits.push(refs::Input {
17347            token: "missing".into(),
17348            sha: "0".repeat(40),
17349            provenance: refs::Provenance::ExplicitCli,
17350        });
17351        assert!(runner.prep().await.is_err());
17352        assert!(runner.state.candidates.is_empty());
17353        assert!(!runner.state.worktree_root().exists());
17354    }
17355
17356    #[tokio::test]
17357    async fn prose_and_legacy_inference_never_import_into_candidates() {
17358        ask_test_home();
17359        let tmp = tempfile::tempdir().unwrap();
17360        let repo = tmp.path().join("repo");
17361        std::fs::create_dir_all(&repo).unwrap();
17362        init_repo(&repo);
17363        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17364        git::git(&repo, &["checkout", "-b", "magi/history/A"])
17365            .await
17366            .unwrap();
17367        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
17368        git::git(&repo, &["add", "."]).await.unwrap();
17369        git::git(&repo, &["commit", "-m", "historical implementation"])
17370            .await
17371            .unwrap();
17372        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
17373        git::git(&repo, &["checkout", "main"]).await.unwrap();
17374        for instruction in [
17375            format!("Example: magi/history/A at {source}"),
17376            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
17377            format!("Never import magi/history/A or {source}"),
17378            format!("Conversation answer: I mentioned {source} only as background"),
17379        ] {
17380            let mut runner = runner_at(RunStatus::Prep);
17381            runner.state.repo = repo.clone();
17382            runner.state.base_commit = base.clone();
17383            runner.state.instruction = instruction.clone();
17384            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
17385            runner.state.config.blind.commit_msg_hook = false;
17386            runner.state.seeds = vec![refs::Seed {
17387                token: "magi/history/A".into(),
17388                sha: source.clone(),
17389                kind: refs::SeedKind::Unmerged,
17390                branch: true,
17391                detail: String::new(),
17392            }];
17393            runner.roles.implementers = vec![spec("one")];
17394            assert_eq!(seeded_instruction(&runner.state), instruction);
17395            // Model an old record with inferred seeds but no structured input field.
17396            let mut legacy = serde_json::to_value(&runner.state).unwrap();
17397            legacy.as_object_mut().unwrap().remove("sources");
17398            runner.state = serde_json::from_value(legacy).unwrap();
17399            assert_eq!(runner.state.sources, refs::Sources::default());
17400            runner.state.save().unwrap();
17401            runner.state = RunState::load(&runner.state.id).unwrap();
17402            runner.prep().await.unwrap();
17403            for candidate in &runner.state.candidates {
17404                assert_eq!(
17405                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
17406                    base
17407                );
17408                assert!(!candidate.worktree.join("unwanted").exists());
17409            }
17410        }
17411    }
17412
17413    #[tokio::test]
17414    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
17415        ask_test_home();
17416        let tmp = tempfile::tempdir().unwrap();
17417        let repo = tmp.path().join("repo");
17418        std::fs::create_dir_all(&repo).unwrap();
17419        init_repo(&repo);
17420        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17421        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
17422        std::fs::write(repo.join("referenced"), "required commit").unwrap();
17423        git::git(&repo, &["add", "."]).await.unwrap();
17424        git::git(&repo, &["commit", "-m", "required seed"])
17425            .await
17426            .unwrap();
17427        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
17428        git::git(&repo, &["checkout", "main"]).await.unwrap();
17429        let mut runner = runner_at(RunStatus::Prep);
17430        runner.state.repo = repo.clone();
17431        runner.state.base_commit = base.clone();
17432        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17433        runner.state.config.graph.advise = false;
17434        runner.state.config.blind.commit_msg_hook = false;
17435        runner.state.sources =
17436            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
17437                .await
17438                .unwrap();
17439        runner.roles.implementers = vec![spec("one"), spec("two")];
17440        runner.roles.judges = vec![spec("judge")];
17441        let label = blind::assign_labels(2, runner.state.seed)[0];
17442        let branch = runner.state.branch_for(label);
17443        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17444        git::worktree_add_branch(&repo, &worktree, &branch, &base)
17445            .await
17446            .unwrap();
17447        runner.state.candidates.push(Candidate {
17448            index: 0,
17449            label,
17450            agent: "one".into(),
17451            branch,
17452            worktree,
17453            summary: String::new(),
17454            stat: String::new(),
17455            files: 0,
17456            commits: 0,
17457            empty: false,
17458            failed: None,
17459            verified_noop: None,
17460            duration_ms: 0,
17461            folded: false,
17462        });
17463        runner.state.save().unwrap();
17464        // Reload the checkpoint immediately before its first cherry-pick.
17465        runner.state = RunState::load(&runner.state.id).unwrap();
17466        assert_eq!(runner.state.prep_complete, Some(false));
17467        runner.prep().await.unwrap();
17468        assert_eq!(runner.state.prep_complete, Some(true));
17469        assert_eq!(runner.state.candidates.len(), 2);
17470        for candidate in &runner.state.candidates {
17471            assert_eq!(
17472                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17473                git::tree_of(&repo, &seed).await.unwrap()
17474            );
17475            assert_eq!(
17476                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
17477                "required commit"
17478            );
17479        }
17480        assert!(runner.state.worktree_root().join("judge-1").exists());
17481        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
17482        runner.prep().await.unwrap();
17483        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
17484
17485        runner.state.prep_complete = Some(false);
17486        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17487            run: Some(format!(
17488                "test -f '{}'",
17489                tmp.path().join("dependency-ready").display()
17490            )),
17491            ..Default::default()
17492        }];
17493        assert!(runner.prep().await.is_err());
17494        assert!(runner.state.prep_failure.is_some());
17495        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
17496        runner.state = RunState::load(&runner.state.id).unwrap();
17497        assert!(
17498            runner.prep().await.is_err(),
17499            "correcting the cause alone must not auto-retry"
17500        );
17501        let failed_at = runner.state.events.last().unwrap().at;
17502        assert!(
17503            runner.retry_preparation(failed_at).is_err(),
17504            "old approvals cannot unlock the hold"
17505        );
17506        let mut task = crate::queue::Task::new(
17507            "retry".into(),
17508            "retry setup".into(),
17509            repo.clone(),
17510            crate::queue::Source::Human,
17511        );
17512        task.start(runner.state.id.clone());
17513        task.hold_machine(Some("setup failed".into()));
17514        task.release_operator("cli", None);
17515        runner
17516            .retry_preparation(task.resumption.as_ref().unwrap().at)
17517            .unwrap();
17518        runner.prep().await.unwrap();
17519        assert!(runner.state.prep_failure.is_none());
17520        assert_eq!(runner.state.prep_complete, Some(true));
17521        assert_eq!(runner.state.candidates.len(), 2);
17522        assert!(runner.state.worktree_root().join("judge-1").exists());
17523        for candidate in &runner.state.candidates {
17524            assert_eq!(
17525                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17526                git::tree_of(&repo, &seed).await.unwrap()
17527            );
17528        }
17529    }
17530
17531    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
17532        let mut heads = Vec::new();
17533        for candidate in candidates {
17534            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
17535        }
17536        heads
17537    }
17538
17539    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
17540        ask_test_home();
17541        let tmp = tempfile::tempdir().unwrap();
17542        let repo = tmp.path().join("repo");
17543        std::fs::create_dir(&repo).unwrap();
17544        init_repo(&repo);
17545        let mut runner = runner_at(RunStatus::Reviewing);
17546        runner.state.repo = repo.clone();
17547        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17548        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17549        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17550            let branch = format!("candidate-{label}");
17551            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17552            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17553                .await
17554                .unwrap();
17555            if label == 'B' {
17556                std::fs::write(worktree.join("change"), "winner").unwrap();
17557                git::rescue_commit(&worktree, "candidate change")
17558                    .await
17559                    .unwrap();
17560            }
17561            runner.state.candidates.push(Candidate {
17562                index,
17563                label,
17564                agent: "alpha".into(),
17565                branch,
17566                worktree,
17567                summary: "completed reply".into(),
17568                stat: String::new(),
17569                files: usize::from(label == 'B'),
17570                commits: usize::from(label == 'B'),
17571                empty: label == 'A',
17572                failed: None,
17573                verified_noop: None,
17574                duration_ms: 1,
17575                folded: false,
17576            });
17577        }
17578        runner.state.judge_skipped = true;
17579        runner.state.tally = Some(Tally {
17580            first_choice: BTreeMap::new(),
17581            borda: BTreeMap::new(),
17582            winner: 'B',
17583            rankings: 0,
17584            unanimous_initial: false,
17585            deliberated: false,
17586            changed_votes: 0,
17587            unanimous_final: false,
17588            tie_break: None,
17589            judges: 0,
17590            present: 0,
17591            quorum: 0,
17592            met_quorum: true,
17593            uncontested: Some("only B produced a change".into()),
17594        });
17595        runner.state.save().unwrap();
17596        (tmp, runner)
17597    }
17598
17599    #[tokio::test]
17600    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17601        let (_tmp, mut runner) = preservation_resume_fixture().await;
17602        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17603        runner.state.config.disk.cache_limit_bytes = 0;
17604        runner.state.config.graph.advise = true;
17605        runner.state.config.graph.advisors = 1;
17606        let advisor = runner.state.worktree_root().join("advisor-1");
17607        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17608            .await
17609            .unwrap();
17610        let home = crate::run::home();
17611        let loser =
17612            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17613        let winner =
17614            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17615        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17616        for target in [&loser, &winner, &advisor] {
17617            std::fs::write(target.join("build-output"), "compiled").unwrap();
17618        }
17619
17620        runner.fold_losers().await.unwrap();
17621
17622        assert!(!loser.join("build-output").exists());
17623        assert!(!advisor.join("build-output").exists());
17624        assert!(winner.join("build-output").is_file());
17625    }
17626
17627    #[tokio::test]
17628    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17629        let (_tmp, mut runner) = preservation_resume_fixture().await;
17630        runner.state.candidates[0].folded = true;
17631        runner.state.config.graph.advise = true;
17632        runner.state.config.graph.advisors = 2;
17633        let repo = runner.state.repo.clone();
17634        let root = runner.state.worktree_root();
17635        let discarded = root.join("advisor-1");
17636        git::worktree_add_detached(&repo, &discarded, "main")
17637            .await
17638            .unwrap();
17639        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17640        let protected = root.join("advisor-2");
17641        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17642            .await
17643            .unwrap();
17644        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17645        runner.state.save().unwrap();
17646
17647        assert!(runner.fold_losers().await.is_err());
17648        assert!(!discarded.exists());
17649        assert!(protected.join("keep").exists());
17650        let saved = RunState::load(&runner.state.id).unwrap();
17651        assert!(saved.events.iter().any(|event| {
17652            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17653        }));
17654    }
17655
17656    #[tokio::test]
17657    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17658        let (tmp, mut runner) = preservation_resume_fixture().await;
17659        let repo = runner.state.repo.clone();
17660        let root = runner.state.worktree_root();
17661        for name in ["advisor-3", "judge-1", "review-2"] {
17662            let path = root.join(name);
17663            git::worktree_add_detached(&repo, &path, "main")
17664                .await
17665                .unwrap();
17666            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17667            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17668            remove_read_seat_worktree(&mut runner.state, &path)
17669                .await
17670                .unwrap();
17671            assert!(!path.exists());
17672        }
17673        let outside = tmp.path().join("advisor-1");
17674        let unknown = root.join("unknown");
17675        let attached = root.join("advisor-4");
17676        git::worktree_add_detached(&repo, &outside, "main")
17677            .await
17678            .unwrap();
17679        git::worktree_add_detached(&repo, &unknown, "main")
17680            .await
17681            .unwrap();
17682        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17683            .await
17684            .unwrap();
17685        let foreign = tmp.path().join("foreign");
17686        std::fs::create_dir(&foreign).unwrap();
17687        init_repo(&foreign);
17688        let wrong_repo = root.join("judge-2");
17689        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17690            .await
17691            .unwrap();
17692        let candidate = runner.state.candidates[0].worktree.clone();
17693        for path in [outside, unknown, attached, wrong_repo, candidate] {
17694            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17695            assert!(
17696                remove_read_seat_worktree(&mut runner.state, &path)
17697                    .await
17698                    .is_err()
17699            );
17700            assert_eq!(
17701                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17702                "keep"
17703            );
17704        }
17705    }
17706
17707    #[tokio::test]
17708    #[cfg(unix)]
17709    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17710        for (solo, failed_checkpoint) in
17711            [(true, false), (false, false), (true, true), (false, true)]
17712        {
17713            let (_tmp, mut runner) = preservation_resume_fixture().await;
17714            if solo {
17715                runner.state.candidates.retain(|c| c.label == 'A');
17716            }
17717            runner.state.candidates[0].empty = false;
17718            runner.state.candidates[0].summary.clear();
17719            runner.state.tally = None;
17720            runner.state.judge_skipped = false;
17721            runner.state.status = RunStatus::Implementing;
17722            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17723            let mut implementer = spec("alpha");
17724            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17725            runner.roles.implementers = vec![implementer];
17726            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17727            if failed_checkpoint {
17728                std::fs::create_dir_all(&patch).unwrap();
17729            }
17730            runner.state.save().unwrap();
17731            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17732            drop(pressure);
17733            runner.state = RunState::load(&runner.state.id).unwrap();
17734            assert_eq!(runner.state.status, RunStatus::Blocked);
17735            assert!(runner.state.interrupted_implementations.contains(&'A'));
17736            assert_eq!(runner.state.candidates[0].commits, 0);
17737            assert!(!runner.state.candidates[0].empty);
17738            assert!(runner.state.candidates[0].failed.is_none());
17739            if failed_checkpoint {
17740                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17741                std::fs::remove_dir(patch).unwrap();
17742            }
17743            runner.state.resource_block = None;
17744            runner.state.config.disk.min_free_bytes = 0;
17745            runner.roles.implementers[0].command = vec![
17746                "sh".into(),
17747                "-c".into(),
17748                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17749            ];
17750            runner.implement().await.unwrap();
17751            assert!(runner.state.interrupted_implementations.is_empty());
17752            assert!(runner.state.candidate_preservation.is_empty());
17753            assert_eq!(runner.state.candidates[0].commits, 1);
17754            assert!(!runner.state.candidates[0].empty);
17755            assert!(
17756                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17757                    .unwrap()
17758                    .contains("retried empty interrupted seat")
17759            );
17760            if !solo {
17761                assert_eq!(runner.state.candidates[1].commits, 1);
17762            }
17763        }
17764    }
17765
17766    #[tokio::test]
17767    #[cfg(unix)]
17768    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17769        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17770            let (_tmp, mut runner) = preservation_resume_fixture().await;
17771            runner.state.candidates.retain(|c| c.label == 'A');
17772            runner.state.candidates[0].empty = false;
17773            runner.state.candidates[0].summary.clear();
17774            runner.state.tally = None;
17775            runner.state.judge_skipped = false;
17776            runner.state.status = RunStatus::Implementing;
17777            // Force only the real post-spawn watchdog, without failing the
17778            // separate admission check. Existing edits predate its measurement.
17779            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17780            let wt = runner.state.candidates[0].worktree.clone();
17781            std::fs::write(
17782                wt.join("interrupted-source"),
17783                "retain implementation work\n",
17784            )
17785            .unwrap();
17786            if committed {
17787                git::rescue_commit(&wt, "implementation checkpoint")
17788                    .await
17789                    .unwrap();
17790            }
17791            let lock = git::git(
17792                &wt,
17793                &[
17794                    "rev-parse",
17795                    "--path-format=absolute",
17796                    "--git-path",
17797                    "index.lock",
17798                ],
17799            )
17800            .await
17801            .unwrap();
17802            if block_rescue {
17803                std::fs::write(&lock, "fixture-owned lock").unwrap();
17804            }
17805            let mut implementer = spec("alpha");
17806            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17807            runner.roles.implementers = vec![implementer];
17808            runner.state.save().unwrap();
17809            let result = runner.implement().await;
17810            drop(pressure);
17811            assert_eq!(result.is_err(), block_rescue);
17812            assert_eq!(
17813                runner.state.resource_block.as_ref().unwrap().kind,
17814                "disk pressure"
17815            );
17816            assert!(
17817                runner
17818                    .state
17819                    .events
17820                    .iter()
17821                    .any(|e| e.message.contains("agent execution interrupted"))
17822            );
17823            assert!(
17824                runner
17825                    .state
17826                    .dir()
17827                    .join("artifacts/candidate-A-recovery/staged.patch")
17828                    .exists()
17829            );
17830            if block_rescue {
17831                let saved = RunState::load(&runner.state.id).unwrap();
17832                assert!(saved.candidate_preservation.contains_key(&'A'));
17833                assert!(!saved.candidates[0].empty);
17834                assert_eq!(
17835                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17836                    "retain implementation work\n"
17837                );
17838                std::fs::remove_file(lock).unwrap();
17839                runner.state = saved;
17840            } else {
17841                assert_eq!(runner.state.status, RunStatus::Blocked);
17842                assert_eq!(runner.state.candidates[0].commits, 1);
17843            }
17844            // Recovery must save the candidate before deciding whether another
17845            // implementation is needed. No implementer is available on retry.
17846            runner.roles.implementers.clear();
17847            runner.state.config.disk.min_free_bytes = 0;
17848            runner.state.resource_block = None;
17849            runner.implement().await.unwrap();
17850            assert!(runner.state.candidate_preservation.is_empty());
17851            assert_eq!(runner.state.candidates[0].commits, 1);
17852            assert!(!runner.state.candidates[0].empty);
17853            assert!(git::is_clean(&wt).await.unwrap());
17854            assert!(
17855                crate::run::read_artifact(&runner.state, "cand-A.patch")
17856                    .unwrap()
17857                    .contains("retain implementation work")
17858            );
17859        }
17860    }
17861
17862    #[tokio::test]
17863    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17864        let (_tmp, mut runner) = preservation_resume_fixture().await;
17865        // Schema 15 already confirmed the unfolded no-change result.
17866        runner.implement().await.unwrap();
17867        assert!(runner.state.candidate_preservation.is_empty());
17868        assert!(
17869            !runner
17870                .state
17871                .dir()
17872                .join("artifacts/candidate-A-recovery")
17873                .exists()
17874        );
17875        runner.fold_losers().await.unwrap();
17876        assert!(!runner.state.candidates[0].worktree.exists());
17877        for schema in [14, crate::run::SCHEMA] {
17878            runner.state.schema = schema;
17879            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17880            runner.state.save().unwrap();
17881            runner.state = RunState::load(&runner.state.id).unwrap();
17882            runner.implement().await.unwrap();
17883            assert!(runner.state.candidate_preservation.is_empty());
17884            assert!(runner.state.candidates[0].folded);
17885            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17886        }
17887    }
17888
17889    #[tokio::test]
17890    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17891        let (_tmp, mut runner) = preservation_resume_fixture().await;
17892        runner.state.candidates.retain(|c| c.label == 'A');
17893        runner.state.tally = None;
17894        runner.state.judge_skipped = false;
17895        let candidate = &mut runner.state.candidates[0];
17896        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17897        candidate.failed = Some("deployment validation unavailable".into());
17898        std::fs::write(
17899            candidate.worktree.join("repair"),
17900            "future launcher policy\n",
17901        )
17902        .unwrap();
17903        runner
17904            .state
17905            .candidate_preservation
17906            .insert('A', "awaiting persistence".into());
17907        runner.persist_candidates().await.unwrap();
17908        let candidate = &runner.state.candidates[0];
17909        assert!(!candidate.empty);
17910        assert_eq!(candidate.commits, 1);
17911        assert_eq!(candidate.files, 1);
17912        assert!(candidate.failed.is_none());
17913        assert!(candidate.summary.contains("EPERM"));
17914        assert!(
17915            crate::run::read_artifact(&runner.state, "cand-A.patch")
17916                .unwrap()
17917                .contains("future launcher policy")
17918        );
17919        assert!(runner.state.candidate_preservation.is_empty());
17920    }
17921
17922    #[tokio::test]
17923    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17924        let (_tmp, mut runner) = preservation_resume_fixture().await;
17925        let wt = runner.state.candidates[0].worktree.clone();
17926        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17927        runner.state.schema = 14;
17928        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17929        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17930        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17931        for _ in 0..2 {
17932            assert!(runner.implement().await.is_err());
17933            assert_eq!(runner.state.status, RunStatus::Blocked);
17934            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17935            assert!(
17936                runner.state.candidates[0].empty,
17937                "old verdict must remain unusable"
17938            );
17939            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17940            assert!(runner.state.judge_skipped);
17941            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17942            assert!(
17943                crate::run::read_artifact(&runner.state, "cand-A.patch")
17944                    .unwrap()
17945                    .contains("owned edits")
17946            );
17947            assert!(wt.exists());
17948            assert_eq!(
17949                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17950                    .await
17951                    .unwrap(),
17952                1
17953            );
17954            runner.state = RunState::load(&runner.state.id).unwrap();
17955        }
17956    }
17957
17958    #[tokio::test]
17959    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17960        let (_tmp, mut runner) = preservation_resume_fixture().await;
17961        let wt = runner.state.candidates[0].worktree.clone();
17962        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17963        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17964        let index_lock = PathBuf::from(
17965            git::git(
17966                &wt,
17967                &[
17968                    "rev-parse",
17969                    "--path-format=absolute",
17970                    "--git-path",
17971                    "index.lock",
17972                ],
17973            )
17974            .await
17975            .unwrap(),
17976        );
17977        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17978        runner.state.schema = 14;
17979        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17980        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17981        assert!(runner.implement().await.is_err());
17982        assert!(runner.after_implement().is_err());
17983        assert!(runner.fold_losers().await.is_err());
17984        assert_eq!(
17985            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17986            "failed seat edits"
17987        );
17988        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17989        runner.state = RunState::load(&runner.state.id).unwrap();
17990        std::fs::remove_file(index_lock).unwrap();
17991        // Recovery finds changes that the old uncontested result never judged.
17992        assert!(runner.implement().await.is_err());
17993        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17994        assert!(runner.state.candidates[0].empty);
17995        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17996        assert!(
17997            crate::run::read_artifact(&runner.state, "cand-A.patch")
17998                .unwrap()
17999                .contains("failed seat edits")
18000        );
18001        assert!(wt.exists());
18002    }
18003
18004    #[tokio::test]
18005    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
18006        let (_tmp, mut runner) = preservation_resume_fixture().await;
18007        let repo = runner.state.repo.clone();
18008        let common = git::git(
18009            &repo,
18010            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
18011        )
18012        .await
18013        .unwrap();
18014        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
18015        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
18016        assert!(runner.fold_losers().await.is_err());
18017        assert!(!runner.state.candidates[0].worktree.exists());
18018        assert!(!runner.state.candidates[0].folded);
18019        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
18020        runner.state = RunState::load(&runner.state.id).unwrap();
18021        std::fs::remove_file(branch_lock).unwrap();
18022        let judge = runner.state.worktree_root().join("judge-1");
18023        git::worktree_add_detached(&repo, &judge, "main")
18024            .await
18025            .unwrap();
18026        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
18027        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
18028            .await
18029            .unwrap();
18030        runner.roles.judges = vec![spec("judge")];
18031        assert!(runner.fold_losers().await.is_err());
18032        runner.state = RunState::load(&runner.state.id).unwrap();
18033        assert!(
18034            runner.state.candidates[0].folded,
18035            "candidate progress saved before judge failure"
18036        );
18037        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
18038        assert!(judge.join("uncommitted").exists());
18039        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
18040            .await
18041            .unwrap();
18042        runner.fold_losers().await.unwrap();
18043        assert!(!judge.exists());
18044        runner.fold_losers().await.unwrap();
18045    }
18046
18047    #[tokio::test]
18048    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
18049        let (_tmp, mut runner) = preservation_resume_fixture().await;
18050        runner.state.candidates.retain(|c| c.label == 'B');
18051        runner.state.tally = None;
18052        runner.state.judge_skipped = false;
18053        runner.state.prep_complete = Some(true);
18054        runner.state.config.graph.advise = false;
18055        runner.state.config.graph.selected_implementer = Some("alpha".into());
18056        let wt = runner.state.candidates[0].worktree.clone();
18057        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
18058        runner
18059            .state
18060            .candidate_preservation
18061            .insert('B', "awaiting persistence".into());
18062        let index_lock = git::git(
18063            &wt,
18064            &[
18065                "rev-parse",
18066                "--path-format=absolute",
18067                "--git-path",
18068                "index.lock",
18069            ],
18070        )
18071        .await
18072        .unwrap();
18073        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18074        runner.state.save().unwrap();
18075        assert!(runner.execute_graph().await.is_err());
18076        assert_eq!(runner.state.status, RunStatus::Blocked);
18077        assert!(runner.state.candidate_preservation.contains_key(&'B'));
18078        std::fs::remove_file(index_lock).unwrap();
18079        // Park at the next graph boundary: this tests the real selected-seat
18080        // hold guard without dispatching reviewers or publishing anything.
18081        for _ in 0..2 {
18082            runner.state = RunState::load(&runner.state.id).unwrap();
18083            runner.pause.park();
18084            runner.execute_graph().await.unwrap();
18085            assert_eq!(runner.state.status, RunStatus::Implementing);
18086            assert!(runner.state.candidate_preservation.is_empty());
18087            assert_eq!(runner.state.candidates[0].commits, 2);
18088            assert!(runner.state.tally.is_none());
18089        }
18090        runner.implement().await.unwrap();
18091        assert_eq!(runner.state.status, RunStatus::Judging);
18092        // A genuine selected-implementer hold must still require release.
18093        runner.state.status = RunStatus::Blocked;
18094        runner.state.candidates[0].failed = Some("implementation failed".into());
18095        runner.state.save().unwrap();
18096        let error = runner.execute_graph().await.unwrap_err();
18097        assert!(
18098            error
18099                .to_string()
18100                .contains("selected implementation is held")
18101        );
18102    }
18103
18104    #[tokio::test]
18105    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
18106        let (_tmp, mut runner) = preservation_resume_fixture().await;
18107        let repo = runner.state.repo.clone();
18108        let candidate = runner.state.candidates[0].clone();
18109        // Remove only the disposable fixture directory, leaving Git's linked
18110        // worktree registration and branch intact, as in a vanished checkout.
18111        let registered = git::worktree_holding(&repo, &candidate.branch)
18112            .await
18113            .unwrap()
18114            .unwrap();
18115        assert_eq!(
18116            registered.canonicalize().unwrap(),
18117            candidate.worktree.canonicalize().unwrap()
18118        );
18119        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18120        assert_eq!(
18121            git::worktree_holding(&repo, &candidate.branch)
18122                .await
18123                .unwrap(),
18124            Some(registered)
18125        );
18126        assert!(
18127            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
18128            "the stale registration initially keeps the branch checked out"
18129        );
18130        runner.fold_losers().await.unwrap();
18131        assert!(runner.state.candidates[0].folded);
18132        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18133        assert_eq!(
18134            git::worktree_holding(&repo, &candidate.branch)
18135                .await
18136                .unwrap(),
18137            None
18138        );
18139        runner.state = RunState::load(&runner.state.id).unwrap();
18140        runner.fold_losers().await.unwrap();
18141    }
18142
18143    #[tokio::test]
18144    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
18145        let (_tmp, mut runner) = preservation_resume_fixture().await;
18146        let repo = runner.state.repo.clone();
18147        let candidate = runner.state.candidates[0].clone();
18148        let winner = runner.state.candidates[1].clone();
18149        let registered = git::worktree_holding(&repo, &candidate.branch)
18150            .await
18151            .unwrap()
18152            .unwrap();
18153        assert_eq!(
18154            registered.canonicalize().unwrap(),
18155            candidate.worktree.canonicalize().unwrap()
18156        );
18157        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18158        assert_eq!(
18159            git::worktree_holding(&repo, &candidate.branch)
18160                .await
18161                .unwrap(),
18162            Some(registered)
18163        );
18164        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
18165
18166        for _ in 0..2 {
18167            fold_run(&mut runner.state, false, &crate::run::home())
18168                .await
18169                .unwrap();
18170            runner.state = RunState::load(&runner.state.id).unwrap();
18171            assert!(runner.state.candidates[0].folded);
18172            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18173            assert_eq!(
18174                git::worktree_holding(&repo, &candidate.branch)
18175                    .await
18176                    .unwrap(),
18177                None
18178            );
18179            assert!(!runner.state.candidates[1].folded);
18180            assert!(winner.worktree.exists());
18181            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
18182        }
18183    }
18184
18185    /// The recovery-retention override, refused for the rule under test. The
18186    /// arrangement is saved in `home` before each call, so `record gone` or
18187    /// `unreadable` would be the fixture's mistake and fails here.
18188    async fn override_refusal(state: &mut RunState, home: &Path) -> anyhow::Error {
18189        let error = fold_run_overriding_recovery_retention(state, true, home)
18190            .await
18191            .expect_err("the override is refused");
18192        assert!(
18193            !matches!(
18194                error.downcast_ref::<FoldRefusal>(),
18195                Some(FoldRefusal::RecordGone | FoldRefusal::Unreadable(_))
18196            ),
18197            "refused for the wrong reason: {error:#}"
18198        );
18199        error
18200    }
18201
18202    #[tokio::test]
18203    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
18204        for sidecar in [false, true] {
18205            let tmp = tempfile::tempdir().unwrap();
18206            let home = tmp.path().join("home");
18207            let repo = tmp.path().join("repo");
18208            std::fs::create_dir(&repo).unwrap();
18209            init_repo(&repo);
18210            let mut state = runner_at(RunStatus::Superseded).state;
18211            state.repo = repo.clone();
18212            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18213            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18214            state.driver_exited = true;
18215            state.reserve_under(&home).unwrap();
18216            git::git(
18217                &repo,
18218                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
18219            )
18220            .await
18221            .unwrap();
18222            let wt = state.worktree_root().join("cand-A");
18223            git::worktree_add_branch(&repo, &wt, "candidate", "main")
18224                .await
18225                .unwrap();
18226            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
18227            git::commit_all(&wt, "fixture: independent source")
18228                .await
18229                .unwrap();
18230            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
18231            state.candidates.push(Candidate {
18232                index: 0,
18233                label: 'A',
18234                agent: "fixture".into(),
18235                branch: "candidate".into(),
18236                worktree: wt.clone(),
18237                summary: String::new(),
18238                stat: String::new(),
18239                files: 0,
18240                commits: 0,
18241                empty: false,
18242                failed: None,
18243                verified_noop: None,
18244                duration_ms: 0,
18245                folded: false,
18246            });
18247            let mut task = crate::queue::Task::new(
18248                "task".into(),
18249                "task".into(),
18250                repo.clone(),
18251                crate::queue::Source::Human,
18252            );
18253            task.runs.push(state.id.clone());
18254            crate::queue::Queue::at(home.join("queue"))
18255                .put(&mut task)
18256                .unwrap();
18257            if sidecar {
18258                crate::pr_recovery::retain_sources(&task, &home).unwrap();
18259            }
18260            state.save_under(&home).unwrap();
18261            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
18262            let refusal = fold_run(&mut state, true, &home).await.unwrap_err();
18263            assert!(
18264                matches!(
18265                    refusal.downcast_ref::<FoldRefusal>(),
18266                    Some(FoldRefusal::Retained(retained)) if retained == &reason
18267                ),
18268                "{refusal:#}"
18269            );
18270            let mut disk = state.config.disk.clone();
18271            disk.fold_grace_secs = 0;
18272            assert_eq!(
18273                crate::clean::fold_due(
18274                    &home.join("runs"),
18275                    &home,
18276                    &state.worktree_root(),
18277                    &disk,
18278                    Timestamp::now() + std::time::Duration::from_secs(10),
18279                )
18280                .await
18281                .unwrap(),
18282                (0, 0)
18283            );
18284            assert!(wt.exists());
18285            state.status = RunStatus::Blocked;
18286            state.save_under(&home).unwrap();
18287            let error = override_refusal(&mut state, &home).await;
18288            assert!(
18289                error
18290                    .to_string()
18291                    .contains("requires a finished, non-resumable run"),
18292                "{error:#}"
18293            );
18294            state.status = RunStatus::Superseded;
18295            state.driver_exited = false;
18296            state.driver_claimed = None;
18297            state.save_under(&home).unwrap();
18298            let error = override_refusal(&mut state, &home).await;
18299            assert!(
18300                error
18301                    .to_string()
18302                    .contains("run is live or its ownership is unknown"),
18303                "{error:#}"
18304            );
18305            state.driver_pid = Some(std::process::id());
18306            state.driver_started_at = crate::proc::process_started_at(std::process::id());
18307            state.save_under(&home).unwrap();
18308            let error = override_refusal(&mut state, &home).await;
18309            assert!(
18310                error
18311                    .to_string()
18312                    .contains("run is live or its ownership is unknown"),
18313                "{error:#}"
18314            );
18315            state.driver_exited = true;
18316            state.driver_pid = None;
18317            state.driver_started_at = None;
18318            state.save_under(&home).unwrap();
18319            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
18320            let error = override_refusal(&mut state, &home).await;
18321            assert!(
18322                matches!(
18323                    error.downcast_ref::<FoldRefusal>(),
18324                    Some(FoldRefusal::Live(_))
18325                ),
18326                "{error:#}"
18327            );
18328            drop(lease);
18329            #[cfg(unix)]
18330            {
18331                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
18332                let error = override_refusal(&mut state, &home).await;
18333                assert!(
18334                    matches!(
18335                        error.downcast_ref::<FoldRefusal>(),
18336                        Some(FoldRefusal::Live(_))
18337                    ),
18338                    "{error:#}"
18339                );
18340                drop(output);
18341            }
18342            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
18343            let error = override_refusal(&mut state, &home).await;
18344            assert!(
18345                matches!(
18346                    error.downcast_ref::<FoldRefusal>(),
18347                    Some(FoldRefusal::Live(_))
18348                ),
18349                "{error:#}"
18350            );
18351            drop(owner);
18352            let checkpoint = git::git(
18353                &wt,
18354                &[
18355                    "rev-parse",
18356                    "--path-format=absolute",
18357                    "--git-path",
18358                    "CHERRY_PICK_HEAD",
18359                ],
18360            )
18361            .await
18362            .unwrap();
18363            std::fs::write(&checkpoint, &head).unwrap();
18364            let error = override_refusal(&mut state, &home).await;
18365            assert!(
18366                matches!(
18367                    error.downcast_ref::<FoldRefusal>(),
18368                    Some(FoldRefusal::ProofIncomplete(detail))
18369                        if detail.contains("Git recovery checkpoint retained")
18370                ),
18371                "{error:#}"
18372            );
18373            std::fs::remove_file(checkpoint).unwrap();
18374            std::fs::write(wt.join("dirty"), "keep").unwrap();
18375            let error = override_refusal(&mut state, &home).await;
18376            assert!(
18377                matches!(
18378                    error.downcast_ref::<FoldRefusal>(),
18379                    Some(FoldRefusal::ProofIncomplete(_))
18380                ),
18381                "{error:#}"
18382            );
18383            assert!(wt.join("dirty").exists());
18384            std::fs::remove_file(wt.join("dirty")).unwrap();
18385            let evidence = home
18386                .join("runs")
18387                .join(&state.id)
18388                .join("artifacts/fold-evidence");
18389            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
18390            std::fs::write(&evidence, "blocked archive").unwrap();
18391            let error = override_refusal(&mut state, &home).await;
18392            assert!(
18393                matches!(
18394                    error.downcast_ref::<FoldRefusal>(),
18395                    Some(FoldRefusal::ProofIncomplete(_))
18396                ),
18397                "{error:#}"
18398            );
18399            assert!(wt.exists());
18400            assert!(
18401                !RunState::load_under(&state.id, &home)
18402                    .unwrap()
18403                    .events
18404                    .iter()
18405                    .any(|event| event.message.contains("--override-recovery-retention"))
18406            );
18407            std::fs::remove_file(&evidence).unwrap();
18408            fold_run_overriding_recovery_retention(&mut state, true, &home)
18409                .await
18410                .unwrap();
18411            assert!(!wt.exists());
18412            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
18413            assert!(
18414                git::worktree_holding(&repo, "candidate")
18415                    .await
18416                    .unwrap()
18417                    .is_none()
18418            );
18419            assert!(
18420                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
18421                    .unwrap()
18422                    .contains("retained implementation")
18423            );
18424            assert!(evidence.join(format!("{head}.index")).is_file());
18425            let saved = RunState::load_under(&state.id, &home).unwrap();
18426            assert_eq!(saved.status, RunStatus::Superseded);
18427            assert!(saved.candidates[0].folded);
18428            assert!(saved.events.iter().any(|event| {
18429                event.message.contains("--override-recovery-retention")
18430                    && event.message.contains(&state.id)
18431                    && event.message.contains(&reason)
18432            }));
18433            assert_eq!(
18434                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
18435                sidecar
18436            );
18437        }
18438    }
18439
18440    #[tokio::test]
18441    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
18442        ask_test_home();
18443        let tmp = tempfile::tempdir().unwrap();
18444        let repo = tmp.path().join("repo");
18445        std::fs::create_dir(&repo).unwrap();
18446        init_repo(&repo);
18447        let mut runner = runner_at(RunStatus::Implementing);
18448        runner.state.repo = repo.clone();
18449        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18450        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18451        for (index, label) in ['A', 'B'].into_iter().enumerate() {
18452            let branch = format!("candidate-{label}");
18453            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
18454            git::worktree_add_branch(&repo, &wt, &branch, "main")
18455                .await
18456                .unwrap();
18457            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
18458            git::git(&wt, &["add", "README.md"]).await.unwrap();
18459            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
18460            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
18461            runner.state.candidates.push(Candidate {
18462                index,
18463                label,
18464                agent: "alpha".to_owned(),
18465                branch,
18466                worktree: wt,
18467                summary: "completed implementation".to_owned(),
18468                stat: String::new(),
18469                files: 0,
18470                commits: 0,
18471                empty: false,
18472                failed: None,
18473                verified_noop: None,
18474                duration_ms: 42,
18475                folded: false,
18476            });
18477            runner
18478                .state
18479                .candidate_preservation
18480                .insert(label, "awaiting persistence".to_owned());
18481        }
18482        let wt = runner.state.candidates[0].worktree.clone();
18483        let index_lock = git::git(
18484            &wt,
18485            &[
18486                "rev-parse",
18487                "--path-format=absolute",
18488                "--git-path",
18489                "index.lock",
18490            ],
18491        )
18492        .await
18493        .unwrap();
18494        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18495        runner.state.save().unwrap();
18496        assert!(runner.persist_candidates().await.is_err());
18497        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18498        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
18499        assert_eq!(
18500            runner.state.candidates[1].commits, 1,
18501            "other results are still collected"
18502        );
18503        assert!(
18504            !runner.state.candidates[0].empty,
18505            "failed rescue is not no change"
18506        );
18507        assert_eq!(
18508            runner.state.candidates[0].summary,
18509            "completed implementation"
18510        );
18511        assert!(runner.after_implement().is_err());
18512        // The record the fold locks is the one on disk, so the arrangement is
18513        // saved first; the refusal asserted is the preservation rule's own,
18514        // never `record gone`.
18515        runner.state.save().unwrap();
18516        let refusal = fold_run(&mut runner.state, true, &crate::run::home())
18517            .await
18518            .unwrap_err();
18519        assert!(
18520            matches!(
18521                refusal.downcast_ref::<FoldRefusal>(),
18522                Some(FoldRefusal::ProofIncomplete(detail))
18523                    if detail.contains("candidate preservation incomplete")
18524            ),
18525            "{refusal:#}"
18526        );
18527        assert!(wt.join("new-file").exists());
18528        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
18529        assert!(recovery.join("staged.patch").exists());
18530        assert!(recovery.join("unstaged.patch").exists());
18531        assert_eq!(
18532            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
18533            "untracked edits\n"
18534        );
18535        runner.state.begin_pass();
18536        runner.state.end_pass_parked(ParkCause::Upgrade {
18537            from: "1.0".into(),
18538            to: Some("1.1".into()),
18539        });
18540        runner.state.save().unwrap();
18541        runner.state = RunState::load(&runner.state.id).unwrap();
18542        assert!(matches!(
18543            runner.state.passes.last().unwrap().end,
18544            Some(crate::run::PassEnd::Parked {
18545                cause: ParkCause::Upgrade { .. }
18546            })
18547        ));
18548        std::fs::remove_file(index_lock).unwrap();
18549        // No implementer is configured: a persistence retry cannot dispatch a seat.
18550        runner.implement().await.unwrap();
18551        assert!(runner.state.candidate_preservation.is_empty());
18552        assert!(
18553            runner
18554                .state
18555                .candidates
18556                .iter()
18557                .all(|c| c.commits == 1 && !c.empty)
18558        );
18559        assert!(git::is_clean(&wt).await.unwrap());
18560        assert!(
18561            crate::run::read_artifact(&runner.state, "cand-A.patch")
18562                .unwrap()
18563                .contains("later tracked edits")
18564        );
18565    }
18566
18567    #[tokio::test]
18568    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
18569        ask_test_home();
18570        let tmp = tempfile::tempdir().unwrap();
18571        let repo = tmp.path().join("repo");
18572        std::fs::create_dir(&repo).unwrap();
18573        init_repo(&repo);
18574        let wt = tmp.path().join("candidate");
18575        git::worktree_add_branch(&repo, &wt, "candidate", "main")
18576            .await
18577            .unwrap();
18578        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18579        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
18580        assert!(wt.join("uncommitted").exists());
18581        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18582        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18583        let mut runner = runner_at(RunStatus::Implementing);
18584        runner.state.repo = repo.clone();
18585        runner.state.base_commit = "missing-base".to_owned();
18586        runner.state.candidates.push(Candidate {
18587            index: 0,
18588            label: 'A',
18589            agent: "alpha".into(),
18590            branch: "candidate".into(),
18591            worktree: wt.clone(),
18592            summary: "completed".into(),
18593            stat: String::new(),
18594            files: 0,
18595            commits: 0,
18596            empty: false,
18597            failed: None,
18598            verified_noop: None,
18599            duration_ms: 1,
18600            folded: false,
18601        });
18602        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18603        // Saved in the home the fold uses: without a record the fold would
18604        // refuse as `record gone` and say nothing about the dirty tree.
18605        let home = tmp.path().join("home");
18606        runner.state.save_under(&home).unwrap();
18607        let refusal = fold_run(&mut runner.state, true, &home).await.unwrap_err();
18608        assert!(
18609            refusal
18610                .to_string()
18611                .contains("worktree has uncommitted work; refusing removal"),
18612            "{refusal:#}"
18613        );
18614        assert!(refusal.downcast_ref::<FoldRefusal>().is_none());
18615        assert!(!runner.state.candidates[0].folded);
18616        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18617        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18618        runner
18619            .state
18620            .candidate_preservation
18621            .insert('A', "pending".into());
18622        assert!(runner.persist_candidates().await.is_err());
18623        assert!(!runner.state.candidates[0].empty);
18624        assert!(!runner.state.candidates[0].folded);
18625        assert!(wt.exists());
18626        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18627        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18628        std::fs::create_dir_all(&patch_path).unwrap();
18629        assert!(
18630            runner.persist_candidates().await.is_err(),
18631            "artifact failure stays pending"
18632        );
18633        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18634        assert!(!runner.state.candidates[0].empty);
18635        std::fs::remove_dir(patch_path).unwrap();
18636        runner.persist_candidates().await.unwrap();
18637        assert!(
18638            runner.state.candidates[0].empty,
18639            "only successful inspection confirms no change"
18640        );
18641    }
18642
18643    fn init_repo(dir: &Path) {
18644        let run = |args: &[&str]| {
18645            let out = std::process::Command::new("git")
18646                .args(args)
18647                .current_dir(dir)
18648                .quiet()
18649                .output()
18650                .expect("spawn git");
18651            assert!(
18652                out.status.success(),
18653                "git {args:?} failed: {}",
18654                String::from_utf8_lossy(&out.stderr)
18655            );
18656        };
18657        run(&["init", "-b", "main"]);
18658        run(&["config", "user.name", "magi test"]);
18659        run(&["config", "user.email", "magi@example.com"]);
18660        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18661        run(&["add", "-A"]);
18662        run(&["commit", "-m", "init"]);
18663    }
18664
18665    // `settle_questions` is what closes the ghost the phone showed: a run's
18666    // seat asked something, the run then ended, and nothing was left to
18667    // abandon the question it left `open`. `HOME` is a process-wide
18668    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18669    // first time it runs in the binary — every test below still reaches the
18670    // same directory whichever call won, and each gets its own run id from
18671    // `RunState::new`, so they never collide there.
18672    fn ask_test_home() {
18673        crate::run::pin_test_home();
18674    }
18675
18676    #[test]
18677    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18678        ask_test_home();
18679        let mut runner = runner_at(RunStatus::Prep);
18680        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18681        // A blocked temporary output path makes the terminal save fail while
18682        // preserving the already published reservation.
18683        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18684        let error = guard
18685            .finish(
18686                &mut runner.state,
18687                Err(
18688                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18689                        .into(),
18690                ),
18691            )
18692            .unwrap_err();
18693        assert_eq!(
18694            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18695            std::io::ErrorKind::PermissionDenied
18696        );
18697        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18698        let message = format!("{error:#}");
18699        assert!(message.contains("original refusal"));
18700        assert!(!message.contains("could not save terminal"));
18701        assert_eq!(
18702            error.chain().count(),
18703            2,
18704            "only startup attribution wraps the original error"
18705        );
18706        let saved = RunState::load(&runner.state.id).unwrap();
18707        assert_eq!(saved.status, RunStatus::Blocked);
18708        assert!(!saved.startup.unwrap().complete);
18709    }
18710
18711    #[test]
18712    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18713        ask_test_home();
18714        let mut runner = runner_at(RunStatus::Prep);
18715        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18716        let id = runner.state.id.clone();
18717        drop(guard);
18718        let saved = RunState::load(&id).unwrap();
18719        assert_eq!(saved.status, RunStatus::Blocked);
18720        assert!(!saved.startup.as_ref().unwrap().complete);
18721        assert!(
18722            saved
18723                .startup
18724                .unwrap()
18725                .failure
18726                .unwrap()
18727                .contains("interrupted")
18728        );
18729        assert!(Runner::resume(&id).is_err());
18730    }
18731
18732    #[test]
18733    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18734        ask_test_home();
18735        let mut runner = runner_at(RunStatus::Prep);
18736        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18737        let error = guard
18738            .finish(
18739                &mut runner.state,
18740                Err(
18741                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18742                        .into(),
18743                ),
18744            )
18745            .unwrap_err();
18746        assert_eq!(
18747            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18748            std::io::ErrorKind::PermissionDenied
18749        );
18750        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18751        let mut task = crate::queue::Task::new(
18752            "review".into(),
18753            "criteria".into(),
18754            runner.state.repo.clone(),
18755            crate::queue::Source::Human,
18756        );
18757        task.record_startup_failure(failure.clone());
18758        task.record_startup_failure(failure.clone());
18759        assert_eq!(task.startup_failures.len(), 1);
18760        assert!(task.runs.is_empty());
18761        assert_eq!(task.attempts, 0);
18762    }
18763
18764    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18765        ask_test_home();
18766        let tmp = tempfile::tempdir().unwrap();
18767        let repo = tmp.path().join("repo");
18768        std::fs::create_dir(&repo).unwrap();
18769        init_repo(&repo);
18770        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18771        let origin = tmp.path().join("origin.git");
18772        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18773            .await
18774            .unwrap();
18775        git::git(
18776            &repo,
18777            &["remote", "add", "origin", origin.to_str().unwrap()],
18778        )
18779        .await
18780        .unwrap();
18781        git::git(&repo, &["checkout", "-b", "fix/retained"])
18782            .await
18783            .unwrap();
18784        std::fs::write(repo.join("retained"), "retained change").unwrap();
18785        git::git(&repo, &["add", "."]).await.unwrap();
18786        git::git(&repo, &["commit", "-m", "retained implementation"])
18787            .await
18788            .unwrap();
18789        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18790        git::git(&repo, &["checkout", "main"]).await.unwrap();
18791        std::fs::write(repo.join("base-change"), "new base").unwrap();
18792        git::git(&repo, &["add", "."]).await.unwrap();
18793        git::git(&repo, &["commit", "-m", "base moved"])
18794            .await
18795            .unwrap();
18796        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18797        git::git(&repo, &["checkout", "fix/retained"])
18798            .await
18799            .unwrap();
18800        let mut runner = runner_at(RunStatus::Voting);
18801        runner.state.repo = repo.clone();
18802        runner.state.base_commit = base;
18803        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18804        runner.state.config.disk.min_free_bytes = 0;
18805        runner.state.config.graph.review_rounds = 1;
18806        runner.state.config.verify.e2e = vec!["true".into()];
18807        runner.state.config.verify.gate = vec!["true".into()];
18808        runner.state.candidates = vec![Candidate {
18809            index: 0,
18810            label: 'A',
18811            agent: "fixture".into(),
18812            branch: "fix/retained".into(),
18813            worktree: repo.clone(),
18814            summary: String::new(),
18815            stat: String::new(),
18816            files: 1,
18817            commits: 1,
18818            empty: false,
18819            failed: None,
18820            verified_noop: None,
18821            duration_ms: 0,
18822            folded: false,
18823        }];
18824        runner.state.tally = Some(Tally {
18825            first_choice: BTreeMap::new(),
18826            borda: BTreeMap::new(),
18827            winner: 'A',
18828            rankings: 0,
18829            unanimous_initial: true,
18830            deliberated: false,
18831            changed_votes: 0,
18832            unanimous_final: true,
18833            tie_break: None,
18834            judges: 0,
18835            present: 0,
18836            quorum: 0,
18837            met_quorum: true,
18838            uncontested: Some("review-only".into()),
18839        });
18840        let mut task = crate::queue::Task::new(
18841            "fixture".into(),
18842            "fixture".into(),
18843            repo,
18844            crate::queue::Source::Human,
18845        );
18846        task.link_run(&runner.state.id);
18847        crate::queue::Queue::open().put(&mut task).unwrap();
18848        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18849        runner.state.base_sync = Some(BaseSync {
18850            tip: String::new(),
18851            behind: 1,
18852            attempts: BASE_SYNC_ROUNDS,
18853            conflict: None,
18854            already_in: None,
18855        });
18856        runner.sync_to_base().await.unwrap();
18857        assert_eq!(runner.state.status, RunStatus::Blocked);
18858        (tmp, runner, head, task.id)
18859    }
18860
18861    #[tokio::test]
18862    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18863        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18864        runner.state.status = RunStatus::Voting;
18865        runner.state.base_sync = None;
18866        runner.state.base_sync_recovery = Default::default();
18867        let scratch = runner.state.dir().join("base-sync");
18868        std::fs::create_dir_all(&scratch).unwrap();
18869        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18870        runner.sync_to_base().await.unwrap();
18871        assert!(runner.state.resource_block.is_some());
18872        assert!(!runner.state.base_sync_blocked());
18873        assert!(runner.state.base_sync.is_none());
18874        assert_eq!(
18875            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18876            "keep"
18877        );
18878        assert_eq!(runner.state.base_episode_used(), 0);
18879        assert!(runner.state.base_sync_recovery.operations.is_empty());
18880        assert!(runner.state.rebase_fixes.is_empty());
18881        assert_eq!(
18882            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18883            head
18884        );
18885        std::fs::remove_dir_all(&scratch).unwrap();
18886        runner.state.resource_block = None;
18887        runner.sync_to_base().await.unwrap();
18888        assert!(!runner.state.base_sync_blocked());
18889        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18890        assert_eq!(runner.state.base_episode_used(), 1);
18891        assert!(runner.state.base_sync_recovery.operations[0].finished);
18892        assert!(runner.state.rebase_fixes.is_empty());
18893        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18894        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18895    }
18896
18897    #[tokio::test]
18898    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18899        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18900        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18901        runner.state.base_sync_recovery = Default::default();
18902        runner.state.task_instruction = Some("fixture".into());
18903        runner.state.config.agents = vec![spec("fixture")];
18904        runner.state.config.graph.review_rounds = 0;
18905        runner.state.config.merge.mode = MergeMode::None;
18906        runner.state.driver_exited = true;
18907        let sync = runner.state.base_sync.as_mut().unwrap();
18908        sync.conflict = None;
18909        sync.attempts = 0;
18910        runner.state.reserve_base_operation(&head, &tip);
18911        runner.state.finish_base_operation(None);
18912        let detail = format!(
18913            "fix/retained conflicts with origin/main and did not rebase: \
18914             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18915             remaining conflicted path(s): none recorded; git said: \
18916             warning: execution failed: {}",
18917            git::REBASE_EXEC
18918        );
18919        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18920        runner.state.record_base_sync_stop(&head);
18921        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18922            unstarted: false,
18923            agent: "fixture".into(),
18924            paths: Vec::new(),
18925            from: Some(head.clone()),
18926            finished: true,
18927            error: None,
18928            stop: None,
18929            onto: None,
18930            index_outside: None,
18931            launcher: None,
18932            infra: None,
18933            outage: None,
18934        });
18935        runner.state.save().unwrap();
18936        assert_eq!(
18937            crate::resume::validate(&crate::run::home(), &runner.state.id)
18938                .unwrap()
18939                .id,
18940            runner.state.id
18941        );
18942
18943        let dirty = runner.state.repo.join("owner-work");
18944        std::fs::write(&dirty, "keep").unwrap();
18945        runner.sync_to_base().await.unwrap();
18946        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18947        assert!(runner.state.base_sync_recovery.operations[0].finished);
18948        assert!(runner.state.base_sync_blocked());
18949        std::fs::remove_file(dirty).unwrap();
18950
18951        let queue = crate::queue::Queue::open();
18952        let id = runner.state.id.clone();
18953        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18954        let _claim = queue.claim(&owner).unwrap();
18955        let mut task = queue.get(&owner).unwrap();
18956        let config = tmp.path().join("test-config.toml");
18957        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18958        let opts = crate::daemon::Opts {
18959            repo: task.repo.clone(),
18960            config: Some(config),
18961            ..Default::default()
18962        };
18963        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18964        let task = queue.get(&owner).unwrap();
18965        assert_eq!(
18966            task.runs.as_slice(),
18967            std::slice::from_ref(&id),
18968            "{:?}",
18969            task.hold_reason
18970        );
18971        runner.state = RunState::load(&id).unwrap();
18972        assert!(!runner.state.base_sync_blocked());
18973        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18974        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18975        assert!(runner.state.base_sync_recovery.operations[0].finished);
18976        assert_eq!(
18977            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18978            detail
18979        );
18980        assert_eq!(runner.state.rebase_fixes.len(), 1);
18981        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18982    }
18983
18984    #[cfg(unix)]
18985    #[tokio::test]
18986    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18987        for routed in [false, true] {
18988            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18989            let home = crate::run::home();
18990            let queue = crate::queue::Queue::open();
18991            let task = queue.get(&owner).unwrap();
18992            runner.state.task_instruction = Some(task.instruction.clone());
18993            runner.state.driver_exited = true;
18994            runner.state.save().unwrap();
18995            let questions = crate::ask::Questions::at(home.join("questions"));
18996            let mut q = crate::ask::Question::new(
18997                runner.state.id.clone(),
18998                "base-recovery".into(),
18999                "owner".into(),
19000                "Recover bounded base movement?".into(),
19001                String::new(),
19002                vec!["recover".into()],
19003            );
19004            q.actions.insert(
19005                "recover".into(),
19006                crate::ask::ChoiceAction::RecoverBase {
19007                    run: runner.state.id.clone(),
19008                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
19009                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
19010                },
19011            );
19012            q.routed_task = Some(owner.clone());
19013            q.answer(crate::ask::Answer::Choice("recover".into()))
19014                .unwrap();
19015            questions.put(&mut q).unwrap();
19016            crate::base_recovery_control::recover(
19017                &queue,
19018                &home,
19019                crate::base_recovery_control::Request {
19020                    run: runner.state.id.clone(),
19021                    head: head.clone(),
19022                    actor: "decisions".into(),
19023                    request: q.id.clone(),
19024                    decision: Some((owner.clone(), q.answered_at.unwrap())),
19025                    expected_stop: Some((
19026                        runner.state.base_sync_recovery.stop.clone().unwrap(),
19027                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
19028                    )),
19029                    evidence_digest: None,
19030                },
19031            )
19032            .await
19033            .unwrap();
19034            if routed {
19035                questions
19036                    .update(&q.id, |q| {
19037                        q.routed_task = Some("another-owner".into());
19038                        Ok(())
19039                    })
19040                    .unwrap();
19041            } else {
19042                let mut task = queue.get(&owner).unwrap();
19043                task.hold_manual(Some("new owner decision".into()));
19044                // Keep the generation to exercise the separate owner-decision binding.
19045                task.status = crate::queue::TaskStatus::Queued;
19046                queue.put(&mut task).unwrap();
19047            }
19048            runner.state = RunState::load(&runner.state.id).unwrap();
19049            runner.sync_to_base().await.unwrap();
19050            let approval = runner
19051                .state
19052                .base_sync_recovery
19053                .authorizations
19054                .last()
19055                .unwrap();
19056            assert!(approval.consumed);
19057            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
19058                "routing"
19059            } else {
19060                "owner decision"
19061            }));
19062            assert_eq!(
19063                runner.state.base_sync.as_ref().unwrap().attempts,
19064                BASE_SYNC_ROUNDS
19065            );
19066            assert_eq!(
19067                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19068                head
19069            );
19070        }
19071    }
19072
19073    #[cfg(unix)]
19074    #[tokio::test]
19075    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
19076        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
19077        if std::env::var_os(CHILD).is_none() {
19078            let home = tempfile::tempdir().unwrap();
19079            let output = std::process::Command::new(std::env::current_exe().unwrap())
19080                .args([
19081                    "--exact",
19082                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
19083                    "--nocapture",
19084                ])
19085                .env(CHILD, "1")
19086                .env("MAGI_HOME", home.path())
19087                .env("MAGI_WORKER_HOME", home.path())
19088                .env("MAGI_WORKER_ID", "abcdef")
19089                .output()
19090                .unwrap();
19091            assert!(
19092                output.status.success()
19093                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19094                "{}\n{}",
19095                String::from_utf8_lossy(&output.stdout),
19096                String::from_utf8_lossy(&output.stderr)
19097            );
19098            return;
19099        }
19100        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
19101        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19102        let home = crate::run::home();
19103        let queue = crate::queue::Queue::open();
19104        let mut owner = queue.get(&task).unwrap();
19105        owner.release_operator("test-release", None);
19106        owner.start(runner.state.id.clone());
19107        queue.put(&mut owner).unwrap();
19108        runner.state.driver_exited = true;
19109        runner.state.task_instruction = Some(owner.instruction.clone());
19110        runner.state.save().unwrap();
19111        let _claim = queue.claim(&task).unwrap();
19112        let reserve = |id: &str| {
19113            let directory = home.join("workers/jobs").join(id);
19114            std::fs::create_dir_all(&directory).unwrap();
19115            let job = crate::worker::Job {
19116                id: id.into(),
19117                sequence: 1,
19118                kind: "task".into(),
19119                key: format!("task:{task}"),
19120                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
19121                generation: "fixture-generation".into(),
19122                version: None,
19123                status: crate::worker::Status::Running,
19124                result: None,
19125                pid: Some(std::process::id()),
19126                created_at: 0,
19127                finished_at: None,
19128            };
19129            std::fs::write(
19130                directory.join("job.json"),
19131                serde_json::to_vec(&job).unwrap(),
19132            )
19133            .unwrap();
19134            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
19135        };
19136        let _own = reserve("abcdef");
19137        let other = reserve("fedcba");
19138        assert!(
19139            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19140                .await
19141                .is_err()
19142        );
19143        assert!(
19144            RunState::load(&runner.state.id)
19145                .unwrap()
19146                .base_sync_recovery
19147                .authorizations
19148                .is_empty()
19149        );
19150        drop(other);
19151        assert!(crate::daemon::is_working_on(
19152            &home,
19153            &runner.state.id,
19154            Timestamp::now()
19155        ));
19156        assert!(
19157            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
19158        );
19159        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19160            .await
19161            .unwrap();
19162        assert!(
19163            RunState::load(&runner.state.id)
19164                .unwrap()
19165                .base_recovery_pending()
19166        );
19167    }
19168
19169    #[cfg(unix)]
19170    #[tokio::test]
19171    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
19172        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19173        let home = crate::run::home();
19174        runner.state.driver_pid = Some(std::process::id());
19175        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
19176        runner.state.driver_exited = false;
19177        runner.state.begin_pass();
19178        runner.state.save().unwrap();
19179        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
19180        driver.record(&runner.state).unwrap();
19181        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
19182        // Preserve the durable claim as if the process died before Drop saved.
19183        drop(driver);
19184        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
19185        assert_eq!(
19186            runner.state.liveness_under(&home, false),
19187            crate::run::Liveness::Dead
19188        );
19189        let queue = crate::queue::Queue::open();
19190        let _claim = queue.claim(&task).unwrap();
19191        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19192            .await
19193            .unwrap();
19194        let disk = RunState::load(&runner.state.id).unwrap();
19195        assert!(!disk.driver_exited);
19196        assert!(disk.base_recovery_pending());
19197    }
19198
19199    #[cfg(unix)]
19200    #[tokio::test]
19201    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
19202        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
19203        if std::env::var_os(CHILD).is_none() {
19204            use std::os::unix::fs::PermissionsExt;
19205            let tmp = tempfile::tempdir().unwrap();
19206            let gh = tmp.path().join("gh");
19207            std::fs::write(&gh, r#"#!/bin/sh
19208case "$1 $2" in
19209  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
19210  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
19211  *) exit 2 ;;
19212esac
19213"#).unwrap();
19214            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
19215            let mut paths = vec![tmp.path().to_path_buf()];
19216            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
19217            let output = std::process::Command::new(std::env::current_exe().unwrap())
19218                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
19219                .env(CHILD, "1")
19220                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
19221                .env("PATH", std::env::join_paths(paths).unwrap())
19222                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
19223                .output().unwrap();
19224            assert!(
19225                output.status.success()
19226                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19227                "{}\n{}",
19228                String::from_utf8_lossy(&output.stdout),
19229                String::from_utf8_lossy(&output.stderr)
19230            );
19231            return;
19232        }
19233        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19234        let repo = runner.state.repo.clone();
19235        git::git(&repo, &["checkout", "main"]).await.unwrap();
19236        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
19237        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19238        git::git(&repo, &["checkout", "fix/retained"])
19239            .await
19240            .unwrap();
19241        runner.state.pr = Some(crate::run::PrRecord {
19242            url: "https://example.test/project/pull/1".into(),
19243            number: 1,
19244            state: "open".into(),
19245            checks: "unknown".into(),
19246            round: 0,
19247            rounds: 1,
19248            red_at_merge: Vec::new(),
19249        });
19250        runner.sync_to_base().await.unwrap();
19251        assert_eq!(runner.state.status, RunStatus::Blocked);
19252        assert_eq!(
19253            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19254            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
19255        );
19256        assert!(runner.state.base_sync_closure_pending());
19257        assert!(crate::handover::can_resume(&runner.state));
19258        let queue = crate::queue::Queue::open();
19259        assert!(!crate::base_sync_recovery::held_task(
19260            &queue,
19261            &queue.get(&task).unwrap()
19262        ));
19263        assert!(runner.state.authorize_base_sync(&task).is_err());
19264        // Legacy closure stops have no typed stop but must retain the checkpoint.
19265        runner.state.base_sync_recovery.stop = None;
19266        runner.state.status = RunStatus::Voting;
19267        runner.state.gate_ran = true;
19268        runner.state.config.graph.review_rounds = 0;
19269        runner.state.save().unwrap();
19270        assert!(crate::handover::can_resume(&runner.state));
19271        runner.state = RunState::load(&runner.state.id).unwrap();
19272        runner.execute_graph().await.unwrap();
19273        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
19274        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
19275        assert_eq!(
19276            runner.state.base_sync.as_ref().unwrap().attempts,
19277            BASE_SYNC_ROUNDS
19278        );
19279        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
19280        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
19281        assert!(runner.state.reviews.is_empty());
19282        assert!(runner.state.gate.is_empty());
19283    }
19284
19285    #[cfg(unix)]
19286    #[tokio::test]
19287    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
19288        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19289        runner.state.driver_exited = true;
19290        runner.state.save().unwrap();
19291        let home = crate::run::home();
19292        let queue = crate::queue::Queue::open();
19293        let _claim = queue.claim(&task).unwrap();
19294        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
19295        assert!(
19296            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19297                .await
19298                .is_err()
19299        );
19300        drop(lease);
19301        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
19302        assert!(
19303            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19304                .await
19305                .is_err()
19306        );
19307        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
19308        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19309            .await
19310            .unwrap();
19311        let disk = RunState::load(&runner.state.id).unwrap();
19312        assert!(disk.base_recovery_pending());
19313        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
19314        assert!(
19315            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19316                .await
19317                .is_err()
19318        );
19319        assert_eq!(
19320            RunState::load(&runner.state.id)
19321                .unwrap()
19322                .base_sync_recovery
19323                .authorizations
19324                .len(),
19325            1
19326        );
19327        let mut owner = queue.get(&task).unwrap();
19328        owner.runs.push("20260101-000000-ffff".into());
19329        queue.put(&mut owner).unwrap();
19330        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19331            .await
19332            .unwrap_err();
19333        assert!(error.to_string().contains("run task ownership changed"));
19334    }
19335
19336    #[cfg(unix)]
19337    #[tokio::test]
19338    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
19339        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19340        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19341        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
19342        legacy["status"] = serde_json::json!("voting");
19343        runner.state = serde_json::from_value(legacy).unwrap();
19344        runner.state.save().unwrap();
19345        for _ in 0..3 {
19346            runner.execute_graph().await.unwrap();
19347            assert_eq!(runner.state.status, RunStatus::Blocked);
19348            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19349            assert!(!crate::handover::can_resume(&runner.state));
19350            assert_eq!(
19351                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19352                head
19353            );
19354            assert!(runner.state.reviews.is_empty());
19355            assert!(!runner.state.gate_ran);
19356        }
19357        let notice = crate::notices::run_ended(&runner.state).unwrap();
19358        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
19359        runner.state.begin_pass();
19360        runner.state.status = RunStatus::Voting;
19361        runner.deliberate().await.unwrap();
19362        runner.vote().await.unwrap();
19363        runner.finish_after_tally().await.unwrap();
19364        assert_eq!(runner.state.status, RunStatus::Blocked);
19365        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
19366        assert_eq!(
19367            crate::notices::run_ended(&runner.state).unwrap().since,
19368            notice.since
19369        );
19370    }
19371
19372    #[cfg(unix)]
19373    #[tokio::test]
19374    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
19375        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19376        for detail in [
19377            "fix/retained conflicts with origin/main and did not rebase: conflict",
19378            "rebased fix/retained locally but origin refused the push",
19379            "unknown failure",
19380        ] {
19381            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
19382            runner.state.record_base_sync_stop(&head);
19383            assert!(runner.state.authorize_base_sync(&task).is_err());
19384            runner.state.status = RunStatus::Voting;
19385            runner.execute_graph().await.unwrap();
19386            assert_eq!(runner.state.status, RunStatus::Blocked);
19387            assert!(!crate::handover::can_resume(&runner.state));
19388            assert_eq!(
19389                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19390                head
19391            );
19392        }
19393    }
19394
19395    #[tokio::test]
19396    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
19397        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19398        let state = &mut runner.state;
19399        let tip = state.base_sync.as_ref().unwrap().tip.clone();
19400        let branch = state.winner().unwrap().branch.clone();
19401        state.base_sync_recovery = Default::default();
19402        state.base_sync.as_mut().unwrap().attempts = 0;
19403        state.reserve_base_operation(&head, &tip);
19404        state.finish_base_operation(None);
19405        let detail = format!(
19406            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
19407        );
19408        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
19409        state.event("land", detail);
19410        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
19411        assert!(state.unknown_preparation_stop(&head));
19412        let digest = state.preparation_digest(&head).unwrap();
19413        state
19414            .base_sync_recovery
19415            .operations
19416            .last_mut()
19417            .unwrap()
19418            .validated_head = Some(head.clone());
19419        assert!(!state.unknown_preparation_stop(&head));
19420        state
19421            .base_sync_recovery
19422            .operations
19423            .last_mut()
19424            .unwrap()
19425            .validated_head = None;
19426        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
19427        state.driver_exited = true;
19428        state.save().unwrap();
19429        let home = crate::run::home();
19430        let queue = crate::queue::Queue::open();
19431        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
19432            .await
19433            .unwrap();
19434        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
19435        assert_eq!(inspection["evidence_digest"], digest);
19436        let request = crate::base_recovery_control::Request {
19437            run: state.id.clone(),
19438            head: head.clone(),
19439            actor: "test".into(),
19440            request: "preparation".into(),
19441            decision: None,
19442            expected_stop: None,
19443            evidence_digest: Some(digest),
19444        };
19445        let mut stale = request.clone();
19446        stale.evidence_digest = Some("stale".into());
19447        assert!(
19448            crate::base_recovery_control::recover(&queue, &home, stale)
19449                .await
19450                .is_err()
19451        );
19452        let scratch = state.dir().join("base-sync");
19453        std::fs::create_dir(&scratch).unwrap();
19454        assert!(
19455            crate::base_recovery_control::recover(&queue, &home, request.clone())
19456                .await
19457                .is_err()
19458        );
19459        std::fs::remove_dir(&scratch).unwrap();
19460        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
19461        git::git(
19462            &state.repo,
19463            &[
19464                "commit",
19465                "--allow-empty",
19466                "-m",
19467                "base advanced after inspection",
19468            ],
19469        )
19470        .await
19471        .unwrap();
19472        git::git(&state.repo, &["push", "origin", "main"])
19473            .await
19474            .unwrap();
19475        git::git(&state.repo, &["checkout", "fix/retained"])
19476            .await
19477            .unwrap();
19478        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
19479            .await
19480            .unwrap();
19481        assert!(!outcome.repeated);
19482        assert!(
19483            crate::base_recovery_control::recover(&queue, &home, request)
19484                .await
19485                .unwrap()
19486                .repeated
19487        );
19488        runner.state = RunState::load(&runner.state.id).unwrap();
19489        assert!(runner.state.base_recovery_pending());
19490        runner.sync_to_base().await.unwrap();
19491        assert!(!runner.state.base_sync_blocked());
19492        assert!(!runner.state.consume_base_recovery(&head));
19493        assert_eq!(runner.state.base_episode_used(), 2);
19494        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19495        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19496        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
19497    }
19498
19499    #[cfg(unix)]
19500    #[tokio::test]
19501    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
19502        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19503        runner.state.authorize_base_sync(&task).unwrap();
19504        assert!(runner.state.consume_base_recovery(&head));
19505        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19506        runner.state.reserve_base_operation(&head, &tip);
19507        runner.state.save().unwrap();
19508        runner.state = RunState::load(&runner.state.id).unwrap();
19509        assert!(!runner.state.consume_base_recovery(&head));
19510        runner.sync_to_base().await.unwrap();
19511        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19512        assert_eq!(runner.state.base_episode_used(), 1);
19513        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19514        assert!(
19515            runner
19516                .state
19517                .base_sync_recovery
19518                .operations
19519                .last()
19520                .unwrap()
19521                .finished
19522        );
19523        assert!(!runner.state.base_sync_blocked());
19524        runner.sync_to_base().await.unwrap();
19525        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19526    }
19527
19528    #[cfg(unix)]
19529    #[tokio::test]
19530    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
19531        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19532        // Both historical diagnostic spellings retain an exhaustion identity.
19533        let original = runner
19534            .state
19535            .base_sync
19536            .as_ref()
19537            .unwrap()
19538            .conflict
19539            .clone()
19540            .unwrap();
19541        runner.state.base_sync.as_mut().unwrap().conflict = Some(
19542            original
19543                .replace("synchronization(s)", "rebase(s)")
19544                .replace("synchronizing", "rebasing"),
19545        );
19546        runner.state.base_sync_recovery = Default::default();
19547        runner.state.record_base_sync_stop(&head);
19548        assert_eq!(
19549            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19550            crate::base_sync_recovery::StopKind::Exhausted
19551        );
19552        runner.state.authorize_base_sync(&task).unwrap();
19553        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19554        let auth = legacy["base_sync_recovery"]["authorizations"][0]
19555            .as_object_mut()
19556            .unwrap();
19557        auth.remove("interval");
19558        auth.remove("scope");
19559        runner.state = serde_json::from_value(legacy).unwrap();
19560        assert!(runner.state.consume_base_recovery(&head));
19561        assert_eq!(runner.state.base_episode_used(), 3);
19562        runner.sync_to_base().await.unwrap();
19563        assert_eq!(runner.state.base_episode_used(), 4);
19564        runner.state.resource_block = Some(crate::run::ResourceBlock {
19565            node: "gate".into(),
19566            kind: "cache".into(),
19567            detail: "legacy wait".into(),
19568            at: Timestamp::now(),
19569            cause: crate::run::ResourceBlockCause::Unrecorded,
19570        });
19571        runner.state.save().unwrap();
19572        assert!(
19573            runner
19574                .state
19575                .base_sync_recovery
19576                .episodes
19577                .last()
19578                .unwrap()
19579                .boundary
19580                .is_none()
19581        );
19582        runner.state.resource_block = None;
19583        advance_base_fixture(&runner).await;
19584        runner.sync_to_base().await.unwrap();
19585        assert!(runner.state.base_sync_blocked());
19586        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19587    }
19588
19589    #[cfg(unix)]
19590    async fn advance_base_fixture(runner: &Runner) {
19591        let repo = &runner.state.repo;
19592        for args in [
19593            vec!["checkout", "main"],
19594            vec!["commit", "--allow-empty", "-m", "base advanced"],
19595            vec!["push", "origin", "main"],
19596            vec!["checkout", "fix/retained"],
19597        ] {
19598            git::git(repo, &args).await.unwrap();
19599        }
19600    }
19601
19602    #[cfg(unix)]
19603    fn fresh_base_interval_fixture(runner: &mut Runner) {
19604        runner.state.base_sync.as_mut().unwrap().attempts = 0;
19605        runner.state.base_sync.as_mut().unwrap().conflict = None;
19606        runner.state.base_sync_recovery = Default::default();
19607        runner.state.status = RunStatus::Voting;
19608    }
19609
19610    #[cfg(unix)]
19611    #[tokio::test]
19612    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
19613        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19614        fresh_base_interval_fixture(&mut runner);
19615        runner.state.begin_pass();
19616        runner.sync_to_base().await.unwrap();
19617        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19618        runner.state.resource_block = Some(crate::run::ResourceBlock {
19619            node: "gate".into(),
19620            kind: "build cache".into(),
19621            detail: "busy".into(),
19622            at: Timestamp::now(),
19623            cause: crate::run::ResourceBlockCause::Timeout {
19624                waited_secs: 1,
19625                limit_secs: 1,
19626            },
19627        });
19628        runner.state.save().unwrap();
19629        let queue = crate::queue::Queue::open();
19630        let mut owner = queue.get(&task).unwrap();
19631        runner.state.task_instruction = Some(owner.instruction.clone());
19632        owner.release_operator("fixture-owner", None);
19633        queue.put(&mut owner).unwrap();
19634        let approval = owner.resumption.clone().unwrap();
19635        runner.state.resource_block = None;
19636        runner.state.save().unwrap();
19637        runner.state = RunState::load(&runner.state.id).unwrap();
19638        advance_base_fixture(&runner).await;
19639        runner.sync_to_base().await.unwrap();
19640        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19641        assert_eq!(runner.state.base_episode_used(), 1);
19642        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19643        assert!(
19644            runner.state.base_sync_recovery.episodes[0]
19645                .boundary
19646                .as_ref()
19647                .unwrap()
19648                .consumed
19649        );
19650        assert!(
19651            !runner
19652                .state
19653                .renew_base_episode(&task, &approval, &head, "base")
19654        );
19655        for _ in 0..3 {
19656            owner.release_operator("fixture-owner", None);
19657            queue.put(&mut owner).unwrap();
19658            runner.state = RunState::load(&runner.state.id).unwrap();
19659            runner.state.begin_pass();
19660            runner.sync_to_base().await.unwrap();
19661            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19662            assert_eq!(runner.state.base_episode_used(), 1);
19663        }
19664        runner.state.resource_block = Some(crate::run::ResourceBlock {
19665            node: "gate".into(),
19666            kind: "disk pressure".into(),
19667            detail: "free space required".into(),
19668            at: Timestamp::now(),
19669            cause: crate::run::ResourceBlockCause::Other,
19670        });
19671        runner.state.end_pass_parked(ParkCause::Interrupt {
19672            reason: "disk pressure".into(),
19673        });
19674        runner.state.save().unwrap();
19675        owner.release_operator("fixture-owner-after-disk", None);
19676        queue.put(&mut owner).unwrap();
19677        runner.state.resource_block = None;
19678        advance_base_fixture(&runner).await;
19679        runner.sync_to_base().await.unwrap();
19680        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19681        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19682        assert_eq!(runner.state.base_episode_used(), 1);
19683        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19684    }
19685
19686    #[cfg(unix)]
19687    #[tokio::test]
19688    async fn base_recovery_continuous_advancement_stops_at_four() {
19689        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19690        fresh_base_interval_fixture(&mut runner);
19691        for spent in 1..=BASE_SYNC_ROUNDS {
19692            runner.sync_to_base().await.unwrap();
19693            assert!(!runner.state.base_sync_blocked());
19694            assert_eq!(runner.state.base_episode_used(), spent);
19695            advance_base_fixture(&runner).await;
19696        }
19697        runner.sync_to_base().await.unwrap();
19698        assert_eq!(
19699            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19700            crate::base_sync_recovery::StopKind::Exhausted
19701        );
19702        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19703        assert!(stop.unverified_sync);
19704        let action = runner.state.base_sync_next_action();
19705        assert!(action.contains("never reached its gate"));
19706        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19707        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19708        runner.state = RunState::load(&runner.state.id).unwrap();
19709        runner.sync_to_base().await.unwrap();
19710        assert_eq!(runner.state.base_episode_used(), 4);
19711        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19712    }
19713
19714    #[cfg(unix)]
19715    #[tokio::test]
19716    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19717        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19718        runner.state.ensure_base_episode();
19719        // Verification progress alone is not evidence of a successful sync.
19720        runner.state.record_base_progress(&head);
19721        runner.state.base_sync_recovery.stop = None;
19722        runner.state.record_base_sync_stop(&head);
19723        assert!(
19724            !runner
19725                .state
19726                .base_sync_recovery
19727                .stop
19728                .as_ref()
19729                .unwrap()
19730                .unverified_sync
19731        );
19732
19733        runner.state.finish_base_operation(Some(&head));
19734        // A gate for another head cannot verify this synchronization.
19735        runner.state.gate_ran = true;
19736        runner.state.gate_head = Some("older-head".into());
19737        runner.state.base_sync_recovery.stop = None;
19738        runner.state.record_base_sync_stop(&head);
19739        runner.state.save().unwrap();
19740        runner.state = RunState::load(&runner.state.id).unwrap();
19741        assert!(
19742            runner
19743                .state
19744                .base_sync_recovery
19745                .stop
19746                .as_ref()
19747                .unwrap()
19748                .unverified_sync
19749        );
19750
19751        runner.state.gate_head = Some(head.clone());
19752        runner.state.base_sync_recovery.stop = None;
19753        runner.state.record_base_sync_stop(&head);
19754        assert!(
19755            !runner
19756                .state
19757                .base_sync_recovery
19758                .stop
19759                .as_ref()
19760                .unwrap()
19761                .unverified_sync
19762        );
19763        assert!(
19764            !runner
19765                .state
19766                .base_sync_next_action()
19767                .contains("never reached its gate")
19768        );
19769
19770        // Historical records cannot establish the missing synchronization evidence.
19771        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19772        legacy["base_sync_recovery"]["stop"]
19773            .as_object_mut()
19774            .unwrap()
19775            .remove("unverified_sync");
19776        legacy["base_sync_recovery"]["episodes"][0]
19777            .as_object_mut()
19778            .unwrap()
19779            .remove("last_sync_head");
19780        runner.state = serde_json::from_value(legacy).unwrap();
19781        assert!(
19782            !runner
19783                .state
19784                .base_sync_recovery
19785                .stop
19786                .as_ref()
19787                .unwrap()
19788                .unverified_sync
19789        );
19790        assert!(
19791            runner.state.base_sync_recovery.episodes[0]
19792                .last_sync_head
19793                .is_none()
19794        );
19795    }
19796
19797    #[cfg(unix)]
19798    #[tokio::test]
19799    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19800        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19801        runner.state.authorize_base_sync(&task).unwrap();
19802        assert!(
19803            runner
19804                .state
19805                .base_sync_next_action()
19806                .contains("Approval recorded")
19807        );
19808        assert!(
19809            runner
19810                .state
19811                .base_sync_next_action()
19812                .contains("4/4 in episode 0, 4 lifetime")
19813        );
19814        assert!(runner.state.consume_base_recovery(&head));
19815        assert!(
19816            runner
19817                .state
19818                .base_sync_next_action()
19819                .contains("0/4 in episode 1, 4 lifetime")
19820        );
19821    }
19822
19823    #[cfg(unix)]
19824    #[tokio::test]
19825    async fn base_recovery_changed_head_invalidates_without_spending() {
19826        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19827        runner.state.authorize_base_sync(&task).unwrap();
19828        git::git(
19829            &runner.state.repo,
19830            &["commit", "--allow-empty", "-m", "external head change"],
19831        )
19832        .await
19833        .unwrap();
19834        runner.sync_to_base().await.unwrap();
19835        let a = runner
19836            .state
19837            .base_sync_recovery
19838            .authorizations
19839            .last()
19840            .unwrap();
19841        assert!(a.consumed);
19842        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19843        runner.state = RunState::load(&runner.state.id).unwrap();
19844        assert!(
19845            runner
19846                .state
19847                .base_sync_next_action()
19848                .contains("Approval invalidated")
19849        );
19850        assert!(!runner.state.base_recovery_pending());
19851        assert!(runner.state.base_sync_blocked());
19852        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19853    }
19854
19855    #[cfg(unix)]
19856    #[tokio::test]
19857    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19858        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19859        runner.state.driver_exited = true;
19860        runner.state.save().unwrap();
19861        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19862            .await
19863            .unwrap();
19864        runner.state = RunState::load(&runner.state.id).unwrap();
19865        advance_base_fixture(&runner).await;
19866        runner.sync_to_base().await.unwrap();
19867        let a = runner
19868            .state
19869            .base_sync_recovery
19870            .authorizations
19871            .last()
19872            .unwrap();
19873        assert!(
19874            a.consumed
19875                && a.invalidated
19876                    .as_deref()
19877                    .unwrap()
19878                    .contains("fetched base changed")
19879        );
19880        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19881        assert_eq!(
19882            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19883            head
19884        );
19885        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19886            .await
19887            .unwrap();
19888        runner.state = RunState::load(&runner.state.id).unwrap();
19889        runner.sync_to_base().await.unwrap();
19890        assert!(!runner.state.base_sync_blocked());
19891        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19892    }
19893
19894    #[cfg(unix)]
19895    #[tokio::test]
19896    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19897        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19898        runner.state.authorize_base_sync(&task).unwrap();
19899        assert!(runner.state.consume_base_recovery(&head));
19900        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19901        runner.state.reserve_base_operation(&head, &tip);
19902        runner.state.save().unwrap();
19903        let scratch = runner.state.dir().join("base-sync");
19904        assert_eq!(
19905            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19906                .await
19907                .unwrap(),
19908            crate::rebase::Rebased::Applied
19909        );
19910        runner.state = RunState::load(&runner.state.id).unwrap();
19911        runner.sync_to_base().await.unwrap();
19912        assert!(
19913            runner
19914                .state
19915                .base_sync_recovery
19916                .operations
19917                .last()
19918                .unwrap()
19919                .finished
19920        );
19921        assert_eq!(runner.state.base_episode_used(), 1);
19922        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19923        assert!(!runner.state.base_sync_blocked());
19924    }
19925
19926    #[cfg(unix)]
19927    #[tokio::test]
19928    async fn base_recovery_crash_preserves_untracked_files() {
19929        for ignored in [false, true] {
19930            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19931            runner.state.authorize_base_sync(&task).unwrap();
19932            assert!(runner.state.consume_base_recovery(&head));
19933            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19934            runner.state.reserve_base_operation(&head, &tip);
19935            runner.state.save().unwrap();
19936            let scratch = runner.state.dir().join("base-sync");
19937            assert_eq!(
19938                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19939                    .await
19940                    .unwrap(),
19941                crate::rebase::Rebased::Applied
19942            );
19943            let repo = &runner.state.repo;
19944            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19945            assert_ne!(result, head);
19946            if ignored {
19947                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19948                    .await
19949                    .unwrap();
19950                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19951            }
19952            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19953            assert!(
19954                git::git_raw(repo, &["diff", "--quiet", &head])
19955                    .await
19956                    .unwrap()
19957                    .ok()
19958            );
19959            // Resume after the branch moved, before its checkout was reset.
19960            runner.state = RunState::load(&runner.state.id).unwrap();
19961            runner.sync_to_base().await.unwrap();
19962            assert!(runner.state.base_sync_blocked());
19963            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19964            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19965            assert_eq!(
19966                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19967                result
19968            );
19969            assert_eq!(
19970                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19971                "retained work\n"
19972            );
19973            assert!(
19974                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19975                    .await
19976                    .unwrap()
19977                    .ok()
19978            );
19979        }
19980    }
19981
19982    #[cfg(unix)]
19983    #[tokio::test]
19984    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19985        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19986        runner.state.authorize_base_sync(&task).unwrap();
19987        assert!(runner.state.consume_base_recovery(&head));
19988        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19989        runner.state.reserve_base_operation(&head, &tip);
19990        runner.state.save().unwrap();
19991        let scratch = runner.state.dir().join("base-sync");
19992        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19993            .await
19994            .unwrap();
19995        git::sync_to_head(&runner.state.repo).await.unwrap();
19996        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19997        git::git(&runner.state.repo, &["add", "foreign"])
19998            .await
19999            .unwrap();
20000        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
20001            .await
20002            .unwrap();
20003        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20004        runner.state = RunState::load(&runner.state.id).unwrap();
20005        runner.sync_to_base().await.unwrap();
20006        assert!(runner.state.base_sync_blocked());
20007        assert!(
20008            !runner
20009                .state
20010                .base_sync_recovery
20011                .operations
20012                .last()
20013                .unwrap()
20014                .finished
20015        );
20016        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20017        assert_eq!(
20018            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20019            foreign_head
20020        );
20021    }
20022
20023    #[cfg(unix)]
20024    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
20025    {
20026        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20027        fresh_base_interval_fixture(&mut runner);
20028        let repo = &runner.state.repo;
20029        git::git(repo, &["checkout", "main"]).await.unwrap();
20030        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
20031        git::git(repo, &["add", "retained"]).await.unwrap();
20032        git::git(repo, &["commit", "-m", "upstream retained change"])
20033            .await
20034            .unwrap();
20035        git::git(repo, &["push", "origin", "main"]).await.unwrap();
20036        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
20037        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
20038        let scratch = runner.state.dir().join("base-sync");
20039        assert!(matches!(
20040            git::rebase_start(repo, &scratch, "fix/retained", &tip)
20041                .await
20042                .unwrap(),
20043            git::RebaseStart::Conflicted(_)
20044        ));
20045        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
20046            unstarted: false,
20047            agent: "fixture".into(),
20048            paths: vec!["retained".into()],
20049            from: Some(head.clone()),
20050            onto: None,
20051            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
20052            index_outside: None,
20053            finished: false,
20054            error: None,
20055            launcher: None,
20056            infra: None,
20057            outage: None,
20058        });
20059        (tmp, runner, head, tip, scratch)
20060    }
20061
20062    #[cfg(unix)]
20063    #[tokio::test]
20064    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
20065        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20066        // A resource stop from before reservations existed, with resolved
20067        // contents left for the launcher's ordinary staging continuation.
20068        std::fs::write(
20069            scratch.join("retained"),
20070            "upstream and retained resolution\n",
20071        )
20072        .unwrap();
20073        runner.state.resource_block = Some(crate::run::ResourceBlock {
20074            node: "rebase".into(),
20075            kind: "repository coordination".into(),
20076            detail: "busy".into(),
20077            at: Timestamp::now(),
20078            cause: crate::run::ResourceBlockCause::Other,
20079        });
20080        runner.state.save().unwrap();
20081        // Advance the remote without moving either checkout participating
20082        // in the standing rebase.
20083        let newer = git::git(
20084            &runner.state.repo,
20085            &[
20086                "commit-tree",
20087                "main^{tree}",
20088                "-p",
20089                "main",
20090                "-m",
20091                "base advanced during wait",
20092            ],
20093        )
20094        .await
20095        .unwrap();
20096        git::git(
20097            &runner.state.repo,
20098            &[
20099                "push",
20100                "origin",
20101                &format!("{}:refs/heads/main", newer.trim()),
20102            ],
20103        )
20104        .await
20105        .unwrap();
20106        runner.state = RunState::load(&runner.state.id).unwrap();
20107        runner.state.resource_block = None;
20108        runner.sync_to_base().await.unwrap();
20109        assert!(!runner.state.base_sync_blocked());
20110        let op = &runner.state.base_sync_recovery.operations[0];
20111        assert_eq!(op.head, head);
20112        assert_eq!(op.tip, tip);
20113        assert!(op.finished);
20114        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20115        assert_eq!(runner.state.rebase_fixes.len(), 1);
20116        let latest = git::rev_parse(&runner.state.repo, "origin/main")
20117            .await
20118            .unwrap();
20119        assert_ne!(latest, tip);
20120        runner.state = RunState::load(&runner.state.id).unwrap();
20121        runner.sync_to_base().await.unwrap();
20122        assert!(!runner.state.base_sync_blocked());
20123        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
20124        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
20125        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
20126    }
20127
20128    #[cfg(unix)]
20129    #[tokio::test]
20130    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
20131        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20132        runner.state.reserve_base_operation(&head, &tip);
20133        runner.state.save().unwrap();
20134        std::fs::write(
20135            scratch.join("retained"),
20136            "upstream and retained resolution\n",
20137        )
20138        .unwrap();
20139        git::git(&scratch, &["add", "retained"]).await.unwrap();
20140        git::git(
20141            &scratch,
20142            &["-c", "core.editor=true", "rebase", "--continue"],
20143        )
20144        .await
20145        .unwrap();
20146        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20147        assert!(
20148            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20149                .await
20150                .unwrap()
20151                .is_empty()
20152        );
20153        assert_eq!(
20154            crate::rebase::finish(
20155                &mut runner.state,
20156                &scratch,
20157                "fix/retained",
20158                &head,
20159                &tip,
20160                &["retained".into()],
20161                ""
20162            )
20163            .await
20164            .unwrap(),
20165            crate::rebase::Rebased::Applied
20166        );
20167        assert!(!scratch.exists());
20168        // Simulate losing the caller before finish_base_operation/save.
20169        runner.state = RunState::load(&runner.state.id).unwrap();
20170        let op = &runner.state.base_sync_recovery.operations[0];
20171        assert!(!op.finished);
20172        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
20173        runner.sync_to_base().await.unwrap();
20174        assert!(!runner.state.base_sync_blocked());
20175        assert!(runner.state.base_sync_recovery.operations[0].finished);
20176        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20177        assert_eq!(runner.state.rebase_fixes.len(), 1);
20178        let winner = runner.state.winner().unwrap().clone();
20179        let wait = runner.repository_wait();
20180        assert!(
20181            verify_current_head(&mut runner.state, &winner, &wait)
20182                .await
20183                .unwrap()
20184        );
20185        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20186    }
20187
20188    #[cfg(unix)]
20189    #[tokio::test]
20190    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
20191        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
20192            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20193            runner.state.reserve_base_operation(&head, &tip);
20194            runner.state.save().unwrap();
20195            std::fs::write(
20196                scratch.join("retained"),
20197                "upstream and retained resolution\n",
20198            )
20199            .unwrap();
20200            git::git(&scratch, &["add", "retained"]).await.unwrap();
20201            git::git(
20202                &scratch,
20203                &["-c", "core.editor=true", "rebase", "--continue"],
20204            )
20205            .await
20206            .unwrap();
20207            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20208            assert!(!git::rebase_in_progress(&scratch).await);
20209            assert!(
20210                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20211                    .await
20212                    .unwrap()
20213                    .is_empty()
20214            );
20215            match damage {
20216                Some("record") => {
20217                    let path =
20218                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
20219                            .await
20220                            .unwrap();
20221                    std::fs::write(scratch.join(path), "").unwrap();
20222                }
20223                Some("foreign") => {
20224                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
20225                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
20226                    git::git(&scratch, &["commit", "-m", "foreign work"])
20227                        .await
20228                        .unwrap();
20229                }
20230                Some("dirty") => {
20231                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
20232                }
20233                _ => {}
20234            }
20235            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20236            // Crash immediately after Git continuation, before finish runs.
20237            runner.state = RunState::load(&runner.state.id).unwrap();
20238            assert!(
20239                runner.state.base_sync_recovery.operations[0]
20240                    .validated_head
20241                    .is_none()
20242            );
20243            runner.sync_to_base().await.unwrap();
20244            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20245            assert_eq!(runner.state.base_episode_used(), 1);
20246            assert_eq!(runner.state.rebase_fixes.len(), 1);
20247            assert_eq!(
20248                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20249                retained_head
20250            );
20251            if damage.is_some() {
20252                assert!(runner.state.base_sync_blocked());
20253                assert!(scratch.exists());
20254                assert!(!runner.state.base_sync_recovery.operations[0].finished);
20255                assert!(
20256                    runner.state.base_sync_recovery.operations[0]
20257                        .validated_head
20258                        .is_none()
20259                );
20260            } else {
20261                assert!(!runner.state.base_sync_blocked());
20262                assert!(!scratch.exists());
20263                assert!(runner.state.base_sync_recovery.operations[0].finished);
20264                assert_eq!(
20265                    runner.state.base_sync_recovery.operations[0]
20266                        .validated_head
20267                        .as_deref(),
20268                    Some(result.as_str())
20269                );
20270                let winner = runner.state.winner().unwrap().clone();
20271                let wait = runner.repository_wait();
20272                assert!(
20273                    verify_current_head(&mut runner.state, &winner, &wait)
20274                        .await
20275                        .unwrap()
20276                );
20277                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20278                runner.state = RunState::load(&runner.state.id).unwrap();
20279                runner.sync_to_base().await.unwrap();
20280                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20281            }
20282        }
20283    }
20284
20285    #[cfg(unix)]
20286    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
20287        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20288        // This is an ordinary gate stop, not an authorized base-budget recovery.
20289        runner.state.prep_complete = Some(true);
20290        runner.state.base_sync = None;
20291        runner.state.base_sync_recovery = Default::default();
20292        runner.state.config.graph.gate_fix_rounds = 1;
20293        let mut review = review_round(true, 0, 1, 1, false, true);
20294        review.head = head.clone();
20295        review.verified_head = Some(head.clone());
20296        runner.state.reviews = vec![review];
20297        runner.state.gate = vec![CommandOutcome {
20298            command: "old gate".into(),
20299            code: Some(1),
20300            output_tail: "old failure".into(),
20301            duration_ms: 0,
20302            resource_blocked: false,
20303            ..Default::default()
20304        }];
20305        runner.state.gate_head = Some(head.clone());
20306        runner.state.gate_ran = true;
20307        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
20308            agent: "fixture".into(),
20309            failed: runner.state.gate.clone(),
20310            notes: "spent".into(),
20311            committed: false,
20312            error: None,
20313        }];
20314        runner.state.land_approval = Some(crate::run::LandApproval {
20315            question: "old approval".into(),
20316            head: head.clone(),
20317        });
20318        runner.state.status = RunStatus::Blocked;
20319        (tmp, runner, head)
20320    }
20321
20322    #[cfg(unix)]
20323    #[tokio::test]
20324    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
20325        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
20326        runner.sync_to_base().await.unwrap();
20327        let winner = runner.state.winner().unwrap().clone();
20328        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
20329        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
20330        assert_ne!(head, base);
20331        runner.state.config.verify.e2e = vec![format!(
20332            "git update-ref refs/remotes/origin/main {head} && false"
20333        )];
20334        let wait = repository_wait(&runner.state, None);
20335        assert!(
20336            !verify_current_head(&mut runner.state, &winner, &wait)
20337                .await
20338                .unwrap()
20339        );
20340        assert_eq!(
20341            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
20342                .await
20343                .unwrap(),
20344            head
20345        );
20346        assert_eq!(
20347            runner
20348                .state
20349                .head_e2e
20350                .as_ref()
20351                .unwrap()
20352                .base_commit
20353                .as_deref(),
20354            Some(base.as_str())
20355        );
20356    }
20357
20358    #[cfg(unix)]
20359    #[tokio::test]
20360    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
20361        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
20362            let (tmp, mut runner, old) = resumed_gate_fixture().await;
20363            let phases = tmp.path().join("phases");
20364            runner.state.config.verify.e2e = vec![format!(
20365                "echo e2e >> '{}'; {}",
20366                phases.display(),
20367                if e2e_ok {
20368                    "true"
20369                } else {
20370                    "echo new-e2e-failure; false"
20371                }
20372            )];
20373            runner.state.config.verify.gate = vec![format!(
20374                "echo gate >> '{}'; {}",
20375                phases.display(),
20376                if gate_ok {
20377                    "true"
20378                } else {
20379                    "echo new-gate-failure; false"
20380                }
20381            )];
20382            runner.state.save().unwrap();
20383            runner.state = RunState::load(&runner.state.id).unwrap();
20384            runner.sync_to_base().await.unwrap();
20385            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20386            assert_ne!(head, old);
20387            // Reentry after Git updated but before verification was invalidated.
20388            runner.state = RunState::load(&runner.state.id).unwrap();
20389            runner.execute_graph().await.unwrap();
20390            assert_eq!(runner.state.gate_fixes.len(), 1);
20391            assert_eq!(runner.state.reviews.len(), 1);
20392            assert_eq!(runner.state.reviews[0].head, old);
20393            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
20394            assert_eq!(runner.state.verification_history.len(), 1);
20395            let history = &runner.state.verification_history[0];
20396            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
20397            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20398            assert!(history.archived_at.is_some());
20399            assert_eq!(history.fixes_spent, Some(1));
20400            assert_eq!(history.gate[0].output_tail, "old failure");
20401            let archive_events: Vec<_> = runner
20402                .state
20403                .events
20404                .iter()
20405                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
20406                .collect();
20407            assert_eq!(archive_events.len(), 1);
20408            assert!(archive_events[0].message.contains(&short(&old)));
20409            assert!(archive_events[0].message.contains(&short(&head)));
20410            assert!(
20411                archive_events[0]
20412                    .message
20413                    .contains("1 gate-fix round(s) already spent stay spent")
20414            );
20415            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
20416            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
20417            if e2e_ok {
20418                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20419                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
20420            } else {
20421                assert!(!runner.state.gate_ran);
20422            }
20423            assert_eq!(
20424                runner.state.status,
20425                if e2e_ok && gate_ok {
20426                    RunStatus::Ready
20427                } else {
20428                    RunStatus::Blocked
20429                }
20430            );
20431            if !e2e_ok || !gate_ok {
20432                let cause = runner.state.verification_blocking_cause().unwrap();
20433                assert!(cause.contains(&head));
20434                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
20435                // A later successful progress event must not become the cause.
20436                runner.state.event("land", "rebased successfully");
20437                let notice = crate::notices::run_ended(&runner.state).unwrap();
20438                assert!(!format!("{notice:?}").contains("rebased successfully"));
20439                assert!(runner.state.merge.is_none());
20440            }
20441            let before = std::fs::read_to_string(&phases).unwrap();
20442            runner.state.save().unwrap();
20443            runner.state = RunState::load(&runner.state.id).unwrap();
20444            runner.review_loop().await.unwrap();
20445            runner.gate().await.unwrap();
20446            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
20447            assert_eq!(runner.state.verification_history.len(), 1);
20448            let history = &runner.state.verification_history[0];
20449            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20450            assert!(history.archived_at.is_some());
20451            assert_eq!(history.fixes_spent, Some(1));
20452        }
20453    }
20454
20455    #[cfg(unix)]
20456    #[tokio::test]
20457    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
20458        let (tmp, mut runner, head) = resumed_gate_fixture().await;
20459        let marker = tmp.path().join("gate-ran");
20460        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
20461        runner.review_loop().await.unwrap();
20462        runner.gate().await.unwrap();
20463        assert_eq!(runner.state.status, RunStatus::Blocked);
20464        assert!(!marker.exists());
20465        assert!(runner.state.verification_history.is_empty());
20466        runner.state.gate_head = None;
20467        runner.gate().await.unwrap();
20468        assert!(marker.exists());
20469        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20470        assert_eq!(runner.state.verification_history.len(), 1);
20471        assert_eq!(runner.state.gate_fixes.len(), 1);
20472    }
20473
20474    #[cfg(unix)]
20475    #[tokio::test]
20476    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
20477        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20478        runner.sync_to_base().await.unwrap();
20479        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20480        runner.state.reconcile_verification_head(&head);
20481        // Both crash-before-command and resource wait are unresolved evidence.
20482        for outcomes in [
20483            Vec::new(),
20484            vec![CommandOutcome {
20485                command: "true".into(),
20486                code: None,
20487                output_tail: "cache unavailable".into(),
20488                duration_ms: 0,
20489                resource_blocked: true,
20490                ..Default::default()
20491            }],
20492        ] {
20493            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20494                head.clone(),
20495                false,
20496                outcomes,
20497            ));
20498            runner.state.gate_ran = false;
20499            runner.state.gate.clear();
20500            runner.state.save().unwrap();
20501            runner.state = RunState::load(&runner.state.id).unwrap();
20502            runner.merge().await.unwrap();
20503            assert!(runner.state.merge.is_none());
20504            runner.review_loop().await.unwrap();
20505            runner.gate().await.unwrap();
20506            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20507            assert!(runner.state.gate_allows_progress());
20508            assert_eq!(runner.state.gate_fixes.len(), 1);
20509            assert!(runner.state.merge.is_none());
20510        }
20511        // Moving the winner after a successful gate cannot publish an unchecked SHA.
20512        git::git(
20513            &runner.state.repo,
20514            &["commit", "--allow-empty", "-m", "external update"],
20515        )
20516        .await
20517        .unwrap();
20518        runner.merge().await.unwrap();
20519        assert!(runner.state.merge.is_none());
20520        assert_eq!(runner.state.status, RunStatus::Blocked);
20521    }
20522
20523    #[cfg(unix)]
20524    #[tokio::test]
20525    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
20526        for waiting_on_gate in [false, true] {
20527            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
20528            runner.sync_to_base().await.unwrap();
20529            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20530            runner.state.reconcile_verification_head(&head);
20531            if waiting_on_gate {
20532                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20533                    head.clone(),
20534                    true,
20535                    Vec::new(),
20536                ));
20537            }
20538            let cache = tmp.path().join("cache");
20539            runner.state.config.verify.e2e =
20540                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
20541            runner.state.config.verify.gate = vec!["true".into()];
20542            runner.state.config.graph.timeout_resource_wait = 1;
20543            let owner =
20544                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
20545            let guard =
20546                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
20547                    crate::cache::AcquireOutcome::Acquired(g) => g,
20548                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
20549                };
20550            runner.review_loop().await.unwrap();
20551            runner.gate().await.unwrap();
20552            assert!(!runner.state.gate_ran);
20553            assert_eq!(runner.state.gate_fixes.len(), 1);
20554            assert!(runner.state.resource_block.is_some());
20555            runner.merge().await.unwrap();
20556            assert!(runner.state.merge.is_none());
20557            drop(guard);
20558            runner.state = RunState::load(&runner.state.id).unwrap();
20559            // The driver clears the previous pass's resource stop on resume.
20560            runner.state.resource_block = None;
20561            runner.review_loop().await.unwrap();
20562            runner.gate().await.unwrap();
20563            assert!(runner.state.gate_allows_progress());
20564            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20565            assert_eq!(runner.state.gate_fixes.len(), 1);
20566        }
20567    }
20568
20569    #[cfg(unix)]
20570    #[tokio::test]
20571    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
20572        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20573        runner.sync_to_base().await.unwrap();
20574        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20575        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
20576        // Verification passes before pre_gate and fails on the mechanically changed head.
20577        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
20578        runner.review_loop().await.unwrap();
20579        runner.gate().await.unwrap();
20580        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20581        assert_ne!(before, after);
20582        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
20583        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
20584        assert!(!runner.state.gate_allows_progress());
20585        runner.merge().await.unwrap();
20586        assert!(runner.state.merge.is_none());
20587        assert!(
20588            runner
20589                .state
20590                .verification_history
20591                .iter()
20592                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
20593        );
20594
20595        // An incomplete review is still an independent hold on a changed head.
20596        runner.state.reviews[0].clean = false;
20597        runner.state.reviews[0].answered = 0;
20598        runner.state.config.verify.e2e = vec!["true".into()];
20599        runner.review_loop().await.unwrap();
20600        runner.gate().await.unwrap();
20601        runner.merge().await.unwrap();
20602        assert_eq!(runner.state.status, RunStatus::Blocked);
20603        assert!(runner.state.merge.is_none());
20604        assert!(
20605            runner
20606                .state
20607                .verification_blocking_cause()
20608                .unwrap()
20609                .contains("review blocked")
20610        );
20611    }
20612
20613    #[cfg(unix)]
20614    #[tokio::test]
20615    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
20616        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20617        runner.state.gate_head = None;
20618        runner.state.config.verify.gate =
20619            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20620        runner.review_loop().await.unwrap();
20621        runner.gate().await.unwrap();
20622        assert_ne!(
20623            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20624            old
20625        );
20626        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20627        assert!(!runner.state.gate_allows_progress());
20628        assert_eq!(runner.state.status, RunStatus::Blocked);
20629        runner.merge().await.unwrap();
20630        assert!(runner.state.merge.is_none());
20631    }
20632
20633    #[cfg(unix)]
20634    #[tokio::test]
20635    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20636        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20637        let mut old_review = review_round(true, 0, 1, 1, false, true);
20638        old_review.head = head.clone();
20639        old_review.verified_head = Some(head.clone());
20640        runner.state.reviews = vec![old_review];
20641        runner.state.gate = vec![CommandOutcome {
20642            command: "old gate".into(),
20643            code: None,
20644            output_tail: "timed out after 2400s".into(),
20645            duration_ms: 2_400_000,
20646            resource_blocked: false,
20647            ..Default::default()
20648        }];
20649        runner.state.gate_ran = true;
20650        runner.state.gate_head = Some(head.clone());
20651        runner.state.land_approval = Some(crate::run::LandApproval {
20652            question: "old-head-approval".into(),
20653            head: head.clone(),
20654        });
20655        runner.state.authorize_base_sync(&task).unwrap();
20656        runner.sync_to_base().await.unwrap();
20657        assert!(!runner.state.base_sync_blocked());
20658        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20659        assert_ne!(head, fresh);
20660        assert_eq!(runner.state.reviews.len(), 1);
20661        assert!(!runner.state.gate_ran);
20662        let saved = &runner.state.base_sync_recovery.authorizations[0];
20663        assert_eq!(saved.reviews[0].head, head);
20664        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20665        assert!(saved.gate_ran);
20666        assert!(!saved.gate[0].ok());
20667        runner.review_loop().await.unwrap();
20668        runner.gate().await.unwrap();
20669        assert_eq!(runner.state.reviews[0].head, head);
20670        assert_eq!(
20671            runner.state.reviews[0].verified_head.as_deref(),
20672            Some(head.as_str())
20673        );
20674        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20675        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20676        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20677        assert!(runner.state.gate_ran);
20678        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20679        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20680        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20681        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20682        assert_eq!(
20683            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20684            "retained change"
20685        );
20686    }
20687
20688    #[cfg(unix)]
20689    #[tokio::test]
20690    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20691        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20692        let queue = crate::queue::Queue::open();
20693        let mut owner = queue.get(&task).unwrap();
20694        owner.release_operator("test-resume", None);
20695        queue.put(&mut owner).unwrap();
20696        let generation = owner.resumption.as_ref().unwrap().generation;
20697        runner.state.task_instruction = Some(owner.instruction.clone());
20698        runner.state.driver_exited = true;
20699        runner.state.save().unwrap();
20700        let home = crate::run::home();
20701        let _claim = queue.claim(&task).unwrap();
20702        owner.resumption.as_mut().unwrap().at =
20703            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20704        queue.put(&mut owner).unwrap();
20705        assert!(
20706            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20707                .await
20708                .is_err(),
20709            "an approval from before the stop grants nothing"
20710        );
20711        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20712        queue.put(&mut owner).unwrap();
20713        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20714            .await
20715            .unwrap();
20716        assert!(
20717            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20718                .await
20719                .is_err()
20720        );
20721        runner.state = RunState::load(&runner.state.id).unwrap();
20722        assert_eq!(
20723            runner.state.base_sync_recovery.authorizations[0].generation,
20724            Some(generation)
20725        );
20726        runner.sync_to_base().await.unwrap();
20727        let repo = runner.state.repo.clone();
20728        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20729        git::git(&repo, &["checkout", "main"]).await.unwrap();
20730        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20731        git::git(&repo, &["add", "."]).await.unwrap();
20732        git::git(&repo, &["commit", "-m", "move base again"])
20733            .await
20734            .unwrap();
20735        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20736        git::git(&repo, &["checkout", "fix/retained"])
20737            .await
20738            .unwrap();
20739        runner.sync_to_base().await.unwrap();
20740        assert!(!runner.state.base_sync_blocked());
20741        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20742        assert_eq!(runner.state.base_episode_used(), 2);
20743        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20744        assert_ne!(fresh, head);
20745        assert!(!runner.state.base_recovery_pending());
20746        // Even replaying the generation with a later timestamp grants nothing.
20747        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20748        queue.put(&mut owner).unwrap();
20749        assert!(
20750            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20751                .await
20752                .is_err()
20753        );
20754        runner.state = RunState::load(&runner.state.id).unwrap();
20755        runner.sync_to_base().await.unwrap();
20756        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20757        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20758        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20759    }
20760
20761    #[cfg(unix)]
20762    #[tokio::test]
20763    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20764        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20765        runner.state.base_sync = None;
20766        runner.state.status = RunStatus::Blocked;
20767        let mut second = runner.state.candidates[0].clone();
20768        second.label = 'B';
20769        runner.state.candidates.push(second);
20770        assert!(runner.state.votes.is_empty());
20771        assert!(runner.state.deliberation.is_empty());
20772        runner.deliberate().await.unwrap();
20773        runner.vote().await.unwrap();
20774        assert_eq!(runner.state.status, RunStatus::Blocked);
20775        assert!(runner.state.votes.is_empty());
20776        assert!(runner.state.deliberation.is_empty());
20777    }
20778
20779    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20780    /// reads nothing else off it.
20781    fn runner_at(status: RunStatus) -> Runner {
20782        let mut state = RunState::new(
20783            PathBuf::from("/nonexistent/repo"),
20784            "main".to_owned(),
20785            "deadbeef".to_owned(),
20786            "task".to_owned(),
20787            Config::default(),
20788        );
20789        // These fixtures test execution flow, independent of host disk capacity.
20790        state.config.disk.min_free_bytes = 0;
20791        // These fixtures share one home and save concurrently. Short clock
20792        // IDs can collide, making an ownership test read another test's run.
20793        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20794        state.id = format!(
20795            "20000101-000000-{:04x}",
20796            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20797        );
20798        state.status = status;
20799        Runner {
20800            state,
20801            roles: ResolvedRoles {
20802                implementers: Vec::new(),
20803                judges: Vec::new(),
20804                reviewers: Vec::new(),
20805                fixer: None,
20806                conductor: conductor(),
20807                implementer_roster: Vec::new(),
20808                judge_roster: Vec::new(),
20809                reviewer_roster: Vec::new(),
20810            },
20811            sem: Arc::new(Semaphore::new(1)),
20812            pause: Pause::new(),
20813            interrupt: Pause::new(),
20814        }
20815    }
20816
20817    #[tokio::test]
20818    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20819        crate::run::pin_test_home();
20820        let home = crate::run::home();
20821        let mut runner = runner_at(RunStatus::Ready);
20822        runner.state.driver_exited = true;
20823        runner.state.save().unwrap();
20824        let id = runner.state.id.clone();
20825        let path = runner.state.dir().join("run.json");
20826        let ids = ["R1-1-1".into()];
20827        let lease = crate::driver::maintenance(&home, &id).unwrap();
20828        for (guard, expected) in [
20829            (Some(lease), "currently being worked on"),
20830            (None, "ownership is being updated"),
20831        ] {
20832            let owner = if guard.is_none() {
20833                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20834            } else {
20835                None
20836            };
20837            let before = std::fs::read(&path).unwrap();
20838            let err = runner
20839                .fix_selected(&ids, "ownership conflict", false)
20840                .await
20841                .unwrap_err();
20842            assert!(format!("{err:#}").contains(expected), "{err:#}");
20843            assert_eq!(std::fs::read(&path).unwrap(), before);
20844            assert!(!runner.state.dir().join("fix.lock").exists());
20845            drop(owner);
20846            drop(guard);
20847        }
20848        let mut disk = RunState::load(&id).unwrap();
20849        disk.driver_exited = false;
20850        disk.driver_pid = Some(std::process::id());
20851        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20852        disk.save().unwrap();
20853        assert_eq!(
20854            disk.liveness_under(&home, false),
20855            crate::run::Liveness::Live
20856        );
20857        let before = std::fs::read(&path).unwrap();
20858        let err = runner
20859            .fix_selected(&ids, "live driver", false)
20860            .await
20861            .unwrap_err();
20862        assert!(
20863            err.to_string().contains("currently being worked on"),
20864            "{err:#}"
20865        );
20866        assert_eq!(std::fs::read(&path).unwrap(), before);
20867        assert!(!runner.state.dir().join("fix.lock").exists());
20868        disk.driver_exited = true;
20869        disk.driver_pid = None;
20870        disk.driver_started_at = None;
20871        disk.status = RunStatus::Reviewing;
20872        disk.save().unwrap();
20873        let before = std::fs::read(&path).unwrap();
20874        let err = runner
20875            .fix_selected(&ids, "stale state", false)
20876            .await
20877            .unwrap_err();
20878        assert!(
20879            err.to_string().contains("run changed since it was loaded"),
20880            "{err:#}"
20881        );
20882        assert_eq!(std::fs::read(&path).unwrap(), before);
20883        assert!(!runner.state.dir().join("fix.lock").exists());
20884        assert!(runner.state.operator_fixes.is_empty());
20885    }
20886
20887    #[tokio::test]
20888    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20889        use std::future::Future;
20890        use std::task::Poll;
20891
20892        crate::run::pin_test_home();
20893        let home = crate::run::home();
20894        let repo = tempfile::tempdir().unwrap();
20895        let mut runner = runner_at(RunStatus::Ready);
20896        runner.state.repo = repo.path().to_path_buf();
20897        runner.state.driver_exited = true;
20898        runner.state.candidates.push(Candidate {
20899            index: 0,
20900            label: 'A',
20901            agent: "mock".into(),
20902            branch: "magi/test/A".into(),
20903            worktree: repo.path().join("wt"),
20904            summary: String::new(),
20905            stat: String::new(),
20906            files: 0,
20907            commits: 0,
20908            empty: false,
20909            failed: None,
20910            verified_noop: None,
20911            duration_ms: 0,
20912            folded: false,
20913        });
20914        runner.state.tally = Some(Tally {
20915            first_choice: BTreeMap::from([('A', 1)]),
20916            borda: BTreeMap::new(),
20917            winner: 'A',
20918            rankings: 1,
20919            unanimous_initial: true,
20920            deliberated: false,
20921            changed_votes: 0,
20922            unanimous_final: true,
20923            tie_break: None,
20924            judges: 1,
20925            present: 1,
20926            quorum: 1,
20927            met_quorum: true,
20928            uncontested: None,
20929        });
20930        runner.state.save().unwrap();
20931        let id = runner.state.id.clone();
20932        let dir = runner.state.dir();
20933        let before = std::fs::read(dir.join("run.json")).unwrap();
20934        let ids = ["R1-1-1".into()];
20935        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20936        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20937            Poll::Pending => Poll::Ready(()),
20938            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20939        })
20940        .await;
20941        assert!(FixClaim::acquire(&dir).is_err());
20942        assert!(crate::driver::maintenance(&home, &id).is_err());
20943        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20944        drop(fix);
20945        assert!(FixClaim::acquire(&dir).is_ok());
20946        assert!(crate::driver::maintenance(&home, &id).is_ok());
20947        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20948    }
20949
20950    #[tokio::test]
20951    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20952        crate::run::pin_test_home();
20953        let temp = tempfile::tempdir().unwrap();
20954        let root = temp.path().canonicalize().unwrap();
20955        let repo = root.join("repo");
20956        std::fs::create_dir(&repo).unwrap();
20957        init_repo(&repo);
20958        git::git(&repo, &["config", "core.autocrlf", "false"])
20959            .await
20960            .unwrap();
20961        let mut runner = runner_at(RunStatus::Blocked);
20962        runner.state.repo = repo.clone();
20963        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20964        runner.state.config.agents = vec![conductor()];
20965        runner.state.config.graph.selected_implementer = Some("conductor".into());
20966        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20967        let (shell, command, setup_output) = if cfg!(windows) {
20968            (
20969                vec!["cmd".into(), "/C".into()],
20970                "echo ready>seat-ready",
20971                "ready\r\n",
20972            )
20973        } else {
20974            (
20975                vec!["sh".into(), "-c".into()],
20976                "printf ready > seat-ready",
20977                "ready",
20978            )
20979        };
20980        runner.state.config.verify.shell = Some(shell);
20981        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20982            run: Some(command.into()),
20983            ..Default::default()
20984        }];
20985        runner.state.save().unwrap();
20986        let path = runner.state.worktree_root().join("judge-1");
20987        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20988            .await
20989            .unwrap();
20990        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20991        git::git(&path, &["add", "."]).await.unwrap();
20992        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20993        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20994            .await
20995            .unwrap();
20996        git::git(&path, &["checkout", "--detach", &head])
20997            .await
20998            .unwrap();
20999        let evidence = crate::fold_evidence::snapshot(
21000            &runner.state,
21001            &crate::run::home().canonicalize().unwrap(),
21002            &head,
21003            64 * 1024 * 1024,
21004        )
21005        .await
21006        .unwrap();
21007        let mut contents = BTreeMap::new();
21008        contents.insert(
21009            repo.join("logs/HEAD"),
21010            format!("{head} {head} fixture\n").into_bytes(),
21011        );
21012        let record = serde_json::json!({
21013            "version":1, "run":runner.state.id, "source":path, "head":head,
21014            "evidence":evidence, "admin":{}, "admin_contents":contents,
21015            "history":{head.clone():evidence}, "phase":"evicted"
21016        });
21017        std::fs::write(
21018            runner.state.dir().join("artifacts/eviction-judge-1.json"),
21019            serde_json::to_vec(&record).unwrap(),
21020        )
21021        .unwrap();
21022        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
21023        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
21024            .await
21025            .unwrap();
21026        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
21027        assert!(
21028            !git::git_raw(&repo, &["cat-file", "-e", &head])
21029                .await
21030                .unwrap()
21031                .ok()
21032        );
21033        let mut resumed = Runner::resume(&runner.state.id).unwrap();
21034        let error = resumed.execute().await.unwrap_err();
21035        assert!(
21036            error
21037                .to_string()
21038                .contains("selected implementation is held"),
21039            "{error:#}"
21040        );
21041        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
21042        assert_eq!(
21043            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
21044            setup_output
21045        );
21046        assert_eq!(
21047            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
21048            "unrelated seat"
21049        );
21050        let error = resumed.execute().await.unwrap_err();
21051        assert!(
21052            error
21053                .to_string()
21054                .contains("selected implementation is held"),
21055            "{error:#}"
21056        );
21057        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
21058        git::git(&path, &["add", "."]).await.unwrap();
21059        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
21060        let next = git::git(
21061            &path,
21062            &[
21063                "commit-tree",
21064                &next_tree,
21065                "-p",
21066                &head,
21067                "-m",
21068                "next review checkpoint",
21069            ],
21070        )
21071        .await
21072        .unwrap();
21073        git::git(&path, &["checkout", "--detach", &next])
21074            .await
21075            .unwrap();
21076        resumed.state.reviews.push(
21077            serde_json::from_value(serde_json::json!({
21078                "round":1, "head":next, "reviews":[]
21079            }))
21080            .unwrap(),
21081        );
21082        resumed.state.save().unwrap();
21083        let error = resumed.execute().await.unwrap_err();
21084        assert!(
21085            error
21086                .to_string()
21087                .contains("selected implementation is held"),
21088            "{error:#}"
21089        );
21090        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
21091    }
21092
21093    #[tokio::test]
21094    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
21095        crate::run::pin_test_home();
21096        let mut runner = runner_at(RunStatus::Gating);
21097        runner.state.save().unwrap();
21098        let id = runner.state.id.clone();
21099        let passes = runner.state.passes.len();
21100        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21101        let mut claiming = Box::pin(runner.claim_driver(None));
21102        std::future::poll_fn(|cx| {
21103            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
21104            std::task::Poll::Ready(())
21105        })
21106        .await;
21107        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
21108        drop(owner);
21109        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
21110            .await
21111            .unwrap()
21112            .unwrap();
21113        assert_eq!(execution.runner.state.passes.len(), passes + 1);
21114        assert!(execution.runner.state.resource_block.is_none());
21115        assert_eq!(
21116            execution.runner.state.liveness(false),
21117            crate::run::Liveness::Live
21118        );
21119        drop(execution);
21120        assert!(RunState::load(&id).unwrap().driver_exited);
21121    }
21122
21123    #[tokio::test]
21124    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
21125        crate::run::pin_test_home();
21126        let mut runner = runner_at(RunStatus::Gating);
21127        runner.state.save().unwrap();
21128        // run.json can commit, but the subsequent lease metadata write fails.
21129        // Cleanup must run after releasing the short ownership lock.
21130        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
21131        assert!(runner.claim_driver(None).await.is_err());
21132        assert!(runner.state.driver_exited);
21133        assert_eq!(runner.state.driver_pid, None);
21134        let disk = RunState::load(&runner.state.id).unwrap();
21135        assert!(disk.driver_exited);
21136        assert_eq!(disk.driver_pid, None);
21137        assert_eq!(disk.status, RunStatus::Gating);
21138    }
21139
21140    #[tokio::test]
21141    async fn an_early_graph_error_releases_its_driver() {
21142        crate::run::pin_test_home();
21143        let mut runner = runner_at(RunStatus::Blocked);
21144        runner.state.config.graph.selected_implementer = Some("selected".into());
21145        runner.state.save().unwrap();
21146        assert!(runner.execute().await.is_err());
21147        let disk = RunState::load(&runner.state.id).unwrap();
21148        assert!(disk.driver_exited);
21149        assert_eq!(disk.driver_pid, None);
21150        assert_eq!(disk.status, RunStatus::Blocked);
21151    }
21152
21153    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
21154        crate::run::MergeRepair {
21155            question: "repair-question".into(),
21156            head: "old-head".into(),
21157            pr: "https://github.com/o/r/pull/42".into(),
21158            reviews: vec![review_round(false, 1, 1, 1, false, true)],
21159            gate: vec![outcome(Some(0), false)],
21160            gate_head: Some("old-head".into()),
21161            gate_fixes: Vec::new(),
21162            pre_gate: Vec::new(),
21163            phase,
21164            failure: None,
21165        }
21166    }
21167
21168    #[tokio::test]
21169    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
21170        crate::run::pin_test_home();
21171        let mut runner = runner_at(RunStatus::Landing);
21172        runner.state.merge_repairs.push(merge_repair_request(
21173            crate::run::MergeRepairPhase::Requested,
21174        ));
21175        runner.state.save().unwrap();
21176        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
21177        assert!(
21178            runner
21179                .execute()
21180                .await
21181                .unwrap_err()
21182                .to_string()
21183                .contains("already running")
21184        );
21185        assert_eq!(
21186            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21187            crate::run::MergeRepairPhase::Requested
21188        );
21189        drop(claim);
21190        let mut disk = runner.state.clone();
21191        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
21192        disk.save().unwrap();
21193        assert!(
21194            runner
21195                .execute()
21196                .await
21197                .unwrap_err()
21198                .to_string()
21199                .contains("decision changed")
21200        );
21201        assert_eq!(
21202            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21203            crate::run::MergeRepairPhase::Complete
21204        );
21205    }
21206
21207    #[test]
21208    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
21209        crate::run::pin_test_home();
21210        let mut runner = runner_at(RunStatus::Landing);
21211        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
21212        runner.state.reviews = request.reviews.clone();
21213        runner.state.gate = request.gate.clone();
21214        runner.state.gate_ran = true;
21215        runner.state.land_approval = Some(crate::run::LandApproval {
21216            question: "old".into(),
21217            head: "old-head".into(),
21218        });
21219        runner.state.merge_repairs.push(request);
21220        runner.begin_merge_repair_review(0).unwrap();
21221        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
21222        assert!(!runner.state.gate_status().ok());
21223        assert!(runner.state.land_approval.is_none());
21224        let disk = RunState::load(&runner.state.id).unwrap();
21225        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
21226        assert!(disk.merge_repairs[0].gate[0].ok());
21227        assert_eq!(
21228            disk.merge_repairs[0].phase,
21229            crate::run::MergeRepairPhase::Reviewing
21230        );
21231        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
21232        assert!(disk.reviews.is_empty());
21233    }
21234
21235    #[tokio::test]
21236    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
21237        crate::run::pin_test_home();
21238        for phase in [
21239            crate::run::MergeRepairPhase::Fixing,
21240            crate::run::MergeRepairPhase::Requested,
21241        ] {
21242            let mut runner = runner_at(RunStatus::Landing);
21243            runner.state.config.graph.land_rounds = 0;
21244            runner.state.merge_repairs.push(merge_repair_request(phase));
21245            runner.state.save().unwrap();
21246            assert!(!runner.repair_merge_review().await.unwrap());
21247            assert_eq!(runner.state.status, RunStatus::Blocked);
21248            assert_eq!(
21249                runner.state.merge_repairs[0].phase,
21250                crate::run::MergeRepairPhase::Failed
21251            );
21252            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
21253            assert!(
21254                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
21255                    "interrupted"
21256                } else {
21257                    "budget exhausted"
21258                })
21259            );
21260            assert!(runner.state.merge.is_none());
21261        }
21262    }
21263
21264    #[tokio::test]
21265    async fn failed_instruction_revision_repair_cannot_resume_into_landing() {
21266        crate::run::pin_test_home();
21267        let mut runner = runner_at(RunStatus::Landing);
21268        let old = merge_repair_request(crate::run::MergeRepairPhase::Complete);
21269        runner.state.reviews = old.reviews.clone();
21270        runner.state.gate = old.gate.clone();
21271        runner.state.gate_ran = true;
21272        runner.state.merge = Some(MergeOutcome {
21273            mode: MergeMode::Pr,
21274            ok: true,
21275            detail: old.pr.clone(),
21276            empty: false,
21277        });
21278        runner.state.merge_repairs.push(old.clone());
21279        crate::instruction_revision_control::adopt_into_run(
21280            &mut runner.state,
21281            "cli/revision",
21282            "revision-repair",
21283            "revised task",
21284            1,
21285            &old.head,
21286            &old.pr,
21287        );
21288        runner.hold_merge_repair(1, "fixer failed".into()).unwrap();
21289        runner.execute().await.unwrap();
21290        let saved = RunState::load(&runner.state.id).unwrap();
21291        assert_eq!(saved.status, RunStatus::Blocked);
21292        assert_eq!(
21293            saved.merge_repairs[0].phase,
21294            crate::run::MergeRepairPhase::Complete
21295        );
21296        assert_eq!(
21297            saved.merge_repairs[1].phase,
21298            crate::run::MergeRepairPhase::Failed
21299        );
21300        assert_eq!(
21301            saved.merge_repairs[1].failure.as_deref(),
21302            Some("fixer failed")
21303        );
21304        assert!(saved.land_approval.is_none());
21305        assert!(!saved.gate_ran);
21306        assert_eq!(saved.reviews.len(), 1);
21307        assert!(
21308            saved.events.iter().any(|event| event.node == "repair"
21309                && event.message.contains("normal resume cannot land"))
21310        );
21311        assert!(!saved.events.iter().any(|event| event.node == "land"));
21312    }
21313
21314    /// `park_here` folding in the reason `Pause::park_because` recorded -
21315    /// this is what lets an operator reading a run's events tell an
21316    /// interrupt-driven park from an ordinary shutdown park.
21317    #[test]
21318    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
21319        crate::run::pin_test_home();
21320        let mut runner = runner_at(RunStatus::Implementing);
21321        let interrupt = Pause::new();
21322        runner.watch_interrupt(interrupt.clone());
21323
21324        interrupt.park_because("task a1b2 asked to run first");
21325
21326        assert!(runner.park_here().expect("park_here"));
21327        assert!(runner.state.parked);
21328        let last = runner.state.events.last().expect("a park event");
21329        assert_eq!(last.node, "park");
21330        assert!(
21331            last.message.contains("task a1b2 asked to run first"),
21332            "expected the interrupt reason in {:?}",
21333            last.message
21334        );
21335    }
21336
21337    /// The cause is stored on the pass when it parks, and the first cause a
21338    /// shared pause was given is the one that stays.
21339    #[test]
21340    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
21341        crate::run::pin_test_home();
21342        let mut runner = runner_at(RunStatus::Implementing);
21343        runner.state.begin_pass();
21344        let shutdown = Pause::new();
21345        runner.on_pause(shutdown.clone());
21346        let upgrade = ParkCause::Upgrade {
21347            from: "0.121.0".to_owned(),
21348            to: Some("0.121.1".to_owned()),
21349        };
21350        shutdown.park_for(upgrade.clone());
21351        shutdown.park_for(ParkCause::Operator);
21352
21353        assert!(runner.park_here().expect("park_here"));
21354        assert_eq!(
21355            runner.state.passes[0].end,
21356            Some(crate::run::PassEnd::Parked { cause: upgrade })
21357        );
21358        let last = runner.state.events.last().expect("a park event");
21359        assert!(last.message.contains("0.121.0"), "{}", last.message);
21360    }
21361
21362    #[tokio::test]
21363    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
21364        crate::run::pin_test_home();
21365        let mut runner = runner_at(RunStatus::Reviewing);
21366        runner.state.save().unwrap();
21367        let mut execution = runner.claim_driver(None).await.expect("first execution");
21368        assert_eq!(execution.runner.state.passes.len(), 1);
21369        execution
21370            .driver
21371            .finish(&mut execution.runner.state)
21372            .await
21373            .unwrap();
21374    }
21375
21376    #[tokio::test]
21377    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
21378        crate::run::pin_test_home();
21379        let mut runner = runner_at(RunStatus::Reviewing);
21380        runner.state.config.agents = vec![conductor()];
21381        runner.state.config.graph.timeout_resource_wait = 0;
21382        runner.state.save().unwrap();
21383        let id = runner.state.id.clone();
21384        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21385        assert!(runner.claim_driver(None).await.is_err());
21386        drop(owner);
21387        drop(runner);
21388        let mut resumed = Runner::resume(&id).unwrap();
21389        assert_eq!(resumed.state.driver_claimed, Some(false));
21390        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
21391        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
21392        let mut execution = resumed
21393            .claim_driver(None)
21394            .await
21395            .expect("retry initial claim after reload");
21396        assert_eq!(execution.runner.state.driver_claimed, Some(true));
21397        assert_eq!(execution.runner.state.passes.len(), 1);
21398        execution
21399            .driver
21400            .finish(&mut execution.runner.state)
21401            .await
21402            .unwrap();
21403    }
21404
21405    #[tokio::test]
21406    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
21407        crate::run::pin_test_home();
21408        let mut runner = runner_at(RunStatus::Reviewing);
21409        runner.state.config.agents = vec![conductor()];
21410        runner.state.save().unwrap();
21411        let id = runner.state.id.clone();
21412        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
21413        let mut resumed = Runner::resume(&id).unwrap();
21414        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
21415        assert!(resumed.claim_driver(None).await.is_err());
21416        assert!(RunState::load(&id).unwrap().passes.is_empty());
21417        drop(lease);
21418        let mut execution = resumed.claim_driver(None).await.unwrap();
21419        execution
21420            .driver
21421            .finish(&mut execution.runner.state)
21422            .await
21423            .unwrap();
21424    }
21425
21426    #[tokio::test]
21427    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
21428        crate::run::pin_test_home();
21429        let mut runner = runner_at(RunStatus::Reviewing);
21430        let state = &mut runner.state;
21431        state.config.agents = vec![conductor()];
21432        state.driver_claimed = None;
21433        state.driver_pid = Some(std::process::id());
21434        state.driver_started_at = None;
21435        state.begin_pass();
21436        state.save().unwrap();
21437        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
21438        std::fs::write(
21439            state.dir().join("driver.json"),
21440            serde_json::to_vec(&serde_json::json!({
21441                "pid": state.driver_pid, "started_at": null,
21442                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
21443            }))
21444            .unwrap(),
21445        )
21446        .unwrap();
21447        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
21448        drop(lease);
21449        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
21450        let mut resumed = Runner::resume(&state.id).unwrap();
21451        assert!(!resumed.state.driver_exited);
21452        let mut execution = resumed
21453            .claim_driver(None)
21454            .await
21455            .expect("lease proves previous execution ended");
21456        assert_eq!(execution.runner.state.passes.len(), 2);
21457        execution
21458            .driver
21459            .finish(&mut execution.runner.state)
21460            .await
21461            .unwrap();
21462    }
21463
21464    #[tokio::test]
21465    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
21466        crate::run::pin_test_home();
21467        let mut runner = runner_at(RunStatus::Reviewing);
21468        let mut json = serde_json::to_value(&runner.state).unwrap();
21469        json.as_object_mut().unwrap().remove("driver_claimed");
21470        runner.state = serde_json::from_value(json).unwrap();
21471        assert_eq!(runner.state.driver_claimed, None);
21472        runner.state.save().unwrap();
21473        let mut execution = runner
21474            .claim_driver(None)
21475            .await
21476            .expect("the execution lease, not a missing marker, excludes a second driver");
21477        assert_eq!(execution.runner.state.passes.len(), 1);
21478        execution
21479            .driver
21480            .finish(&mut execution.runner.state)
21481            .await
21482            .unwrap();
21483    }
21484
21485    #[tokio::test]
21486    async fn driver_admission_refuses_a_proven_live_driver() {
21487        crate::run::pin_test_home();
21488        let mut runner = runner_at(RunStatus::Reviewing);
21489        let pid = std::process::id();
21490        runner.state.driver_pid = Some(pid);
21491        runner.state.driver_started_at = crate::proc::process_started_at(pid);
21492        assert!(runner.state.driver_started_at.is_some());
21493        runner.state.save().unwrap();
21494        let error = runner
21495            .claim_driver(None)
21496            .await
21497            .err()
21498            .expect("a live driver must refuse");
21499        let message = error.to_string();
21500        assert!(
21501            message.starts_with("run already has a live driver: "),
21502            "{message}"
21503        );
21504        assert!(message.contains(&format!("pid={pid}")), "{message}");
21505        assert!(
21506            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
21507            "{message}"
21508        );
21509        let saved = RunState::load(&runner.state.id).unwrap();
21510        assert_eq!(saved.driver_pid, Some(pid));
21511        assert_eq!(saved.status, RunStatus::Reviewing);
21512        assert!(saved.passes.is_empty());
21513    }
21514
21515    #[tokio::test]
21516    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
21517        crate::run::pin_test_home();
21518        let home = crate::run::home();
21519        let mut runner = runner_at(RunStatus::Reviewing);
21520        runner.state.driver_exited = true;
21521        runner.state.driver_pid = None;
21522        runner.state.driver_started_at = None;
21523        runner.state.save().unwrap();
21524
21525        let queue = crate::queue::Queue::at(home.join("queue"));
21526        let mut task = crate::queue::Task::new(
21527            "task".into(),
21528            "task".into(),
21529            runner.state.repo.clone(),
21530            crate::queue::Source::Human,
21531        );
21532        task.runs.push(runner.state.id.clone());
21533        queue.put(&mut task).unwrap();
21534        let payload = serde_json::json!({
21535            "queue": home.join("queue"),
21536            "task": task.id,
21537            "opts": crate::daemon::Opts::default(),
21538            "standalone": false,
21539        });
21540        let (job, lease) =
21541            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
21542
21543        let error = runner
21544            .claim_driver(None)
21545            .await
21546            .err()
21547            .expect("another active worker claim must refuse");
21548        let message = error.to_string();
21549        assert!(
21550            message.starts_with("run already has a live driver: worker claim"),
21551            "{message}"
21552        );
21553        assert!(message.contains(&job.id), "{message}");
21554        assert!(message.contains("status=running"), "{message}");
21555        assert!(message.contains("live.lock held"), "{message}");
21556
21557        drop(lease);
21558        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
21559    }
21560
21561    #[test]
21562    fn parking_resource_halt_persists_the_pass_once() {
21563        crate::run::pin_test_home();
21564        let mut runner = runner_at(RunStatus::Reviewing);
21565        runner.state.begin_pass();
21566        runner.state.resource_block = Some(crate::run::ResourceBlock {
21567            node: "fix".into(),
21568            kind: "shared build cache".into(),
21569            detail: "cancelled".into(),
21570            at: Timestamp::now(),
21571            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
21572        });
21573        let cause = ParkCause::Upgrade {
21574            from: "old".into(),
21575            to: Some("new".into()),
21576        };
21577        runner.pause.park_for(cause.clone());
21578        // Both direct fixer exits and graph resource boundaries must complete
21579        // parking, rather than returning a stale Reviewing record.
21580        runner.stop_for_resource().unwrap();
21581        assert!(runner.resource_halt().unwrap());
21582        assert!(runner.park_here().unwrap());
21583        let saved = RunState::load(&runner.state.id).unwrap();
21584        assert!(saved.parked);
21585        assert_eq!(saved.status, RunStatus::Reviewing);
21586        assert!(saved.passes[0].ended_at.is_some());
21587        assert_eq!(
21588            saved.passes[0].end,
21589            Some(crate::run::PassEnd::Parked {
21590                cause: cause.clone()
21591            })
21592        );
21593        assert_eq!(
21594            saved.resource_block.unwrap().cause,
21595            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
21596        );
21597        assert_eq!(
21598            saved
21599                .events
21600                .iter()
21601                .filter(|event| event.node == "park")
21602                .count(),
21603            1
21604        );
21605    }
21606
21607    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
21608    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
21609    /// cleared) must not make a *different* run - one only watching its own,
21610    /// unshared interrupt `Pause` - see itself as parked. If a future change
21611    /// ever collapsed these back into one handle, the interrupt scheduler
21612    /// would park every run for the rest of the daemon's life, not just the
21613    /// one it meant to interrupt.
21614    #[test]
21615    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
21616        crate::run::pin_test_home();
21617        let mut runner = runner_at(RunStatus::Implementing);
21618        let shutdown = Pause::new();
21619        runner.on_pause(shutdown.clone());
21620        let interrupt = Pause::new();
21621        runner.watch_interrupt(interrupt.clone());
21622
21623        // Nobody has asked for anything yet.
21624        assert!(!runner.park_here().expect("park_here"));
21625        assert!(!runner.state.parked);
21626
21627        // Only the interrupt handle fires; the shutdown handle stays clear.
21628        interrupt.park_because("test");
21629        assert!(!shutdown.parked());
21630        assert!(runner.park_here().expect("park_here"));
21631    }
21632
21633    /// The property every prior attempt at this feature failed to pin down:
21634    /// asking a run to park while one of its nodes has a real, in-flight
21635    /// async operation running (an agent call, in production) must not cut
21636    /// that operation short. `park_here` is only ever consulted *between*
21637    /// `execute`'s node calls - see its own doc - so nothing inside a node
21638    /// can observe a park request until the node itself returns. This proves
21639    /// that structurally, with real `tokio` concurrency and a channel
21640    /// handshake (never a sleep, which would only prove "usually", not
21641    /// "cannot"): the "node" below reports that it has genuinely started,
21642    /// and only then is the park requested; the node still has to be told to
21643    /// finish before `park_here` is ever called, exactly mirroring every
21644    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
21645    /// in `execute`.
21646    #[tokio::test]
21647    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
21648        crate::run::pin_test_home();
21649        let mut runner = runner_at(RunStatus::Implementing);
21650        let interrupt = Pause::new();
21651        runner.watch_interrupt(interrupt.clone());
21652
21653        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
21654        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
21655
21656        // Stands in for one node's in-flight agent call: it proves it has
21657        // genuinely started, then blocks - exactly as a spawned CLI process
21658        // does - until told to finish.
21659        let node = async move {
21660            started_tx.send(()).expect("send started");
21661            finish_rx.await.expect("recv finish");
21662            "node finished"
21663        };
21664
21665        let interrupter = async move {
21666            started_rx.await.expect("recv started");
21667            // The call is now genuinely in flight. Ask it to park.
21668            interrupt.park_because("higher-priority task waiting");
21669            // Nothing the node does can observe this yet - there is no
21670            // check inside it, by construction - so let the executor run
21671            // anything pending and then let the node finish on its own.
21672            tokio::task::yield_now().await;
21673            finish_tx.send(()).expect("send finish");
21674        };
21675
21676        let (node_result, ()) = tokio::join!(node, interrupter);
21677        assert_eq!(
21678            node_result, "node finished",
21679            "the in-flight call ran to completion"
21680        );
21681
21682        // Only now, at the boundary the real `execute` would check right
21683        // after this node, does the park take effect.
21684        assert!(runner.park_here().expect("park_here"));
21685        assert!(runner.state.parked);
21686    }
21687
21688    /// A run parked mid-competition carries every field it had accumulated
21689    /// through the exact same disk round-trip an ordinary resume uses -
21690    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21691    /// Nothing about parking for an interrupt is a special case of that path;
21692    /// this is what proves it rather than assuming it.
21693    #[test]
21694    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21695        crate::run::pin_test_home();
21696        let mut runner = runner_at(RunStatus::Judging);
21697        // `Runner::resume` re-resolves roles from the saved config, which
21698        // refuses an empty roster - give it the same minimal one `conductor`
21699        // itself uses.
21700        runner.state.config.agents = vec![conductor()];
21701        runner.state.candidates = vec![Candidate {
21702            index: 0,
21703            label: 'A',
21704            agent: "alpha".to_owned(),
21705            branch: "magi/x/A".to_owned(),
21706            worktree: PathBuf::from("/nonexistent/worktree"),
21707            summary: "did the thing".to_owned(),
21708            stat: "1 file changed".to_owned(),
21709            files: 1,
21710            commits: 1,
21711            empty: false,
21712            failed: None,
21713            verified_noop: None,
21714            duration_ms: 1234,
21715            folded: false,
21716        }];
21717        let run_id = runner.state.id.clone();
21718
21719        let interrupt = Pause::new();
21720        runner.watch_interrupt(interrupt.clone());
21721        interrupt.park_because("task c3d4 asked to run first");
21722        assert!(runner.park_here().expect("park_here"));
21723
21724        let resumed = Runner::resume(&run_id).expect("resume");
21725        assert_eq!(resumed.state.candidates.len(), 1);
21726        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21727        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21728        assert_eq!(resumed.state.status, runner.state.status);
21729        assert!(
21730            resumed.state.parked,
21731            "still parked until `execute` actually walks the graph again"
21732        );
21733        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21734    }
21735
21736    /// A fresh open question on `run`, stored and handed back for assertions.
21737    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21738        let mut q = ask::Question::new(
21739            run.to_owned(),
21740            "implement".to_owned(),
21741            "impl-A".to_owned(),
21742            "Which storage backend should the cache use?".to_owned(),
21743            String::new(),
21744            vec!["SQLite".to_owned(), "Redis".to_owned()],
21745        );
21746        store.put(&mut q).unwrap();
21747        q
21748    }
21749
21750    #[test]
21751    fn a_failed_runs_open_question_is_abandoned() {
21752        ask_test_home();
21753        let store = ask::Questions::open();
21754        let mut runner = runner_at(RunStatus::Failed);
21755        let run = runner.state.id.clone();
21756        let q = ask_open_question(&store, &run);
21757
21758        runner.settle_questions();
21759
21760        let back = store.get(&q.id).unwrap();
21761        assert!(
21762            !back.status.open(),
21763            "the seat that asked died with the run; nobody is left to read an answer"
21764        );
21765        assert!(
21766            back.detail.contains(&run) && back.detail.contains("failed"),
21767            "the reason names what the run became, not just that it is gone: {}",
21768            back.detail
21769        );
21770    }
21771
21772    #[test]
21773    fn a_merged_runs_open_question_is_abandoned_too() {
21774        ask_test_home();
21775        let store = ask::Questions::open();
21776        // A run that finishes cleanly still leaves nobody to read an answer -
21777        // this is not only a failure-path cleanup.
21778        for status in [RunStatus::Merged, RunStatus::Ready] {
21779            let mut runner = runner_at(status);
21780            let run = runner.state.id.clone();
21781            let q = ask_open_question(&store, &run);
21782
21783            runner.settle_questions();
21784
21785            let back = store.get(&q.id).unwrap();
21786            assert!(
21787                !back.status.open(),
21788                "{status:?} run's question must not outlive the run"
21789            );
21790        }
21791    }
21792
21793    #[test]
21794    fn a_still_resumable_runs_open_question_is_left_alone() {
21795        ask_test_home();
21796        let store = ask::Questions::open();
21797        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21798        // review round and the seat sessions are all still on disk — so a
21799        // question asked mid-round may yet get a real answer from a real
21800        // resume. Sweeping it here would be exactly the failure mode this
21801        // whole feature exists to avoid on the other side.
21802        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21803            let mut runner = runner_at(status);
21804            let run = runner.state.id.clone();
21805            let q = ask_open_question(&store, &run);
21806
21807            runner.settle_questions();
21808
21809            let back = store.get(&q.id).unwrap();
21810            assert!(
21811                back.status.open(),
21812                "{status:?} is still alive; the question must still be waiting"
21813            );
21814        }
21815    }
21816
21817    #[test]
21818    fn settle_questions_never_touches_an_already_answered_question() {
21819        ask_test_home();
21820        let store = ask::Questions::open();
21821        let mut runner = runner_at(RunStatus::Failed);
21822        let run = runner.state.id.clone();
21823        let mut q = ask_open_question(&store, &run);
21824        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21825            .unwrap();
21826        store.put(&mut q).unwrap();
21827
21828        // Called twice, the way a crash-recovered daemon reclaim and the
21829        // graph's own cleanup both can for the same run — `abandon_for_run`
21830        // only ever touches what is still open, so this must be inert both
21831        // times, not merely the second.
21832        runner.settle_questions();
21833        runner.settle_questions();
21834
21835        let back = store.get(&q.id).unwrap();
21836        assert_eq!(
21837            back.status,
21838            ask::QuestionStatus::Answered,
21839            "a real answer is a decision on record, never overwritten by a sweep"
21840        );
21841    }
21842
21843    #[tokio::test]
21844    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21845        let tmp = tempfile::tempdir().unwrap();
21846        let home = tmp.path().join("home");
21847        let repo = tmp.path().join("repo");
21848        std::fs::create_dir(&home).unwrap();
21849        std::fs::create_dir(&repo).unwrap();
21850        init_repo(&repo);
21851
21852        let mut config = Config::default();
21853        config.graph.worktree_root = Some(tmp.path().join("wt"));
21854        config.verify.build_cache = crate::config::BuildCache::Isolated;
21855        let mut state = RunState::new(
21856            repo.clone(),
21857            "main".into(),
21858            "base".into(),
21859            "fold fixture".into(),
21860            config,
21861        );
21862        let root = state.worktree_root();
21863        let mut outputs = Vec::new();
21864        for name in ["idle", "busy"] {
21865            let checkout = root.join(name);
21866            git::worktree_add_detached(&repo, &checkout, "main")
21867                .await
21868                .unwrap();
21869            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21870            let output = target.join("generated");
21871            std::fs::write(&output, name).unwrap();
21872            outputs.push((target, output));
21873        }
21874        let unknown = crate::build_target::root(&home)
21875            .join("00000000-0000-0000-0000-000000000000")
21876            .join("target");
21877        std::fs::create_dir_all(&unknown).unwrap();
21878        let unowned = unknown.join("generated");
21879        std::fs::write(&unowned, "keep").unwrap();
21880        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21881        let crate::cache::AcquireOutcome::Acquired(_lease) =
21882            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21883        else {
21884            panic!("fixture target must be free");
21885        };
21886
21887        state.save_under(&home).unwrap();
21888        fold_run(&mut state, true, &home).await.unwrap();
21889        assert!(!root.exists());
21890        assert!(!outputs[0].1.exists());
21891        assert!(outputs[1].1.is_file());
21892        assert!(unowned.is_file());
21893    }
21894
21895    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21896    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21897    /// without merging, whose winner is still the operator's answer to read.
21898    /// Nothing previously called `fold_run` itself with a real `tally`, so
21899    /// this is the first test to pin down the one distinction the whole
21900    /// automatic-fold feature depends on: the winner's worktree and branch
21901    /// must survive, everything else sharing the run's worktree bay - a
21902    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21903    /// second sweep treats every non-winner directory under the bay alike -
21904    /// must not.
21905    #[tokio::test]
21906    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21907        crate::run::pin_test_home();
21908        let tmp = tempfile::tempdir().expect("tempdir");
21909        let repo = tmp.path().join("repo");
21910        std::fs::create_dir_all(&repo).unwrap();
21911        init_repo(&repo);
21912
21913        let mut config = Config::default();
21914        config.graph.worktree_root = Some(tmp.path().join("wt"));
21915
21916        let mut state = RunState::new(
21917            repo.clone(),
21918            "main".to_owned(),
21919            "deadbeef".to_owned(),
21920            "task".to_owned(),
21921            config,
21922        );
21923        let root = state.worktree_root();
21924        let wt_a = root.join("cand-A");
21925        let wt_b = root.join("cand-B");
21926        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21927            .await
21928            .expect("worktree A");
21929        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21930            .await
21931            .expect("worktree B");
21932
21933        state.candidates = vec![
21934            Candidate {
21935                index: 0,
21936                label: 'A',
21937                agent: "alpha".to_owned(),
21938                branch: "magi/x/A".to_owned(),
21939                worktree: wt_a.clone(),
21940                summary: String::new(),
21941                stat: String::new(),
21942                files: 0,
21943                commits: 0,
21944                empty: false,
21945                failed: None,
21946                verified_noop: None,
21947                duration_ms: 0,
21948                folded: false,
21949            },
21950            Candidate {
21951                index: 1,
21952                label: 'B',
21953                agent: "beta".to_owned(),
21954                branch: "magi/x/B".to_owned(),
21955                worktree: wt_b.clone(),
21956                summary: String::new(),
21957                stat: String::new(),
21958                files: 0,
21959                commits: 0,
21960                empty: false,
21961                failed: None,
21962                verified_noop: None,
21963                duration_ms: 0,
21964                folded: false,
21965            },
21966        ];
21967        state.tally = Some(Tally {
21968            first_choice: BTreeMap::from([('A', 1)]),
21969            borda: BTreeMap::new(),
21970            winner: 'A',
21971            rankings: 1,
21972            unanimous_initial: true,
21973            deliberated: false,
21974            changed_votes: 0,
21975            unanimous_final: true,
21976            tie_break: None,
21977            judges: 1,
21978            present: 1,
21979            quorum: 1,
21980            met_quorum: true,
21981            uncontested: None,
21982        });
21983        state.status = RunStatus::Ready;
21984
21985        state.save_under(&crate::run::home()).unwrap();
21986        fold_run(&mut state, false, &crate::run::home())
21987            .await
21988            .expect("fold_run");
21989
21990        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21991        assert!(
21992            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21993            "the unmerged winner's branch survives"
21994        );
21995        assert!(
21996            !state.candidates[0].folded,
21997            "the winner is not marked folded"
21998        );
21999
22000        assert!(!wt_b.exists(), "the loser's worktree is removed");
22001        assert!(
22002            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
22003            "the loser's branch is removed"
22004        );
22005        assert!(state.candidates[1].folded, "the loser is marked folded");
22006    }
22007
22008    #[tokio::test]
22009    #[cfg(unix)]
22010    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
22011        use std::os::fd::AsRawFd as _;
22012        use std::time::Duration;
22013
22014        let tmp = tempfile::tempdir().unwrap();
22015        let repo = tmp.path().join("repo");
22016        std::fs::create_dir_all(&repo).unwrap();
22017        init_repo(&repo);
22018        let common = repo.join(".git");
22019        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22020        let home = tmp.path().join("home");
22021        let mut config = Config::default();
22022        config.coordination = crate::config::test_coordination();
22023        config.graph.worktree_root = Some(tmp.path().join("wt"));
22024        config.graph.timeout_resource_wait = 1;
22025        let mut state = RunState::new(
22026            repo.clone(),
22027            "main".into(),
22028            "deadbeef".into(),
22029            "task".into(),
22030            config,
22031        );
22032        let root = state.worktree_root();
22033        let candidate = root.join("cand-A");
22034        let reviewer = root.join("review-1");
22035        let branch = state.branch_for('A');
22036        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22037            .await
22038            .unwrap();
22039        git::worktree_add_detached(&repo, &reviewer, "main")
22040            .await
22041            .unwrap();
22042        git::acquire_worktree_config(&repo).await.unwrap();
22043        state.enabled_worktree_config = true;
22044        state.status = RunStatus::Ready;
22045        state.candidates.push(Candidate {
22046            index: 0,
22047            label: 'A',
22048            agent: "implement".into(),
22049            branch: branch.clone(),
22050            worktree: candidate.clone(),
22051            summary: String::new(),
22052            stat: String::new(),
22053            files: 0,
22054            commits: 0,
22055            empty: false,
22056            failed: None,
22057            verified_noop: None,
22058            duration_ms: 0,
22059            folded: false,
22060        });
22061        state.save_under(&home).unwrap();
22062        let config_before = std::fs::read(common.join("config")).unwrap();
22063        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
22064            .await
22065            .unwrap();
22066        // A separate OS handle bypasses the launcher's local gate, exactly as
22067        // an external updater does, and must still prevent all folding work.
22068        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22069        assert_eq!(
22070            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22071            0
22072        );
22073        let mut fold = Box::pin(fold_run(&mut state, true, &home));
22074        assert!(
22075            tokio::time::timeout(Duration::from_millis(200), &mut fold)
22076                .await
22077                .is_err()
22078        );
22079        assert!(candidate.exists());
22080        assert!(reviewer.exists());
22081        assert!(git::branch_exists(&repo, &branch).await.unwrap());
22082        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
22083        assert_eq!(
22084            git::git(&repo, &["worktree", "list", "--porcelain"])
22085                .await
22086                .unwrap(),
22087            worktrees_before
22088        );
22089        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
22090            .await
22091            .unwrap()
22092            .unwrap_err();
22093        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
22094        drop(fold);
22095        assert!(candidate.exists() && reviewer.exists());
22096        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
22097        assert_eq!(
22098            state.resource_block.as_ref().unwrap().kind,
22099            "repository coordination"
22100        );
22101        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
22102        drop(external);
22103        let mut fold = Box::pin(fold_run(&mut state, true, &home));
22104        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
22105            .await
22106            .unwrap()
22107            .unwrap();
22108        drop(fold);
22109        assert!(removed.contains(&branch));
22110        assert!(!root.exists());
22111        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
22112        assert!(state.candidates[0].folded);
22113        assert!(!state.enabled_worktree_config);
22114        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
22115        let enabled = git::git_raw(
22116            &repo,
22117            &["config", "--local", "--get", "extensions.worktreeConfig"],
22118        )
22119        .await
22120        .unwrap();
22121        assert!(!enabled.ok(), "the last config reference was released");
22122    }
22123
22124    /// A handover holds repository coordination and then asks for the
22125    /// predecessor's owner lock; an automatic fold already holds that lock. The
22126    /// fold asks for coordination once and gives way, so the handover's short
22127    /// retry succeeds - waiting for it would leave both waiting for each other.
22128    /// Nothing is changed or saved on the way out and the refusal is `live`;
22129    /// the explicit entry points (`magi fold`) still wait, bounded as before.
22130    #[tokio::test]
22131    #[cfg(unix)]
22132    async fn an_automatic_fold_gives_way_to_busy_coordination_instead_of_waiting() {
22133        use std::os::fd::AsRawFd as _;
22134        use std::time::Duration;
22135
22136        let tmp = tempfile::tempdir().unwrap();
22137        let repo = tmp.path().join("repo");
22138        std::fs::create_dir_all(&repo).unwrap();
22139        init_repo(&repo);
22140        let common = repo.join(".git");
22141        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22142        let home = tmp.path().join("home");
22143        let mut config = Config::default();
22144        config.coordination = crate::config::test_coordination();
22145        config.graph.worktree_root = Some(tmp.path().join("wt"));
22146        config.graph.timeout_resource_wait = 60;
22147        let mut state = RunState::new(
22148            repo.clone(),
22149            "main".into(),
22150            "deadbeef".into(),
22151            "task".into(),
22152            config,
22153        );
22154        let candidate = state.worktree_root().join("cand-A");
22155        let branch = state.branch_for('A');
22156        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22157            .await
22158            .unwrap();
22159        state.status = RunStatus::Ready;
22160        state.driver_exited = true;
22161        state.candidates.push(Candidate {
22162            index: 0,
22163            label: 'A',
22164            agent: "implement".into(),
22165            branch: branch.clone(),
22166            worktree: candidate.clone(),
22167            summary: String::new(),
22168            stat: String::new(),
22169            files: 0,
22170            commits: 0,
22171            empty: false,
22172            failed: None,
22173            verified_noop: None,
22174            duration_ms: 0,
22175            folded: false,
22176        });
22177        state.save_under(&home).unwrap();
22178        let id = state.id.clone();
22179        let record = std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap();
22180
22181        // A separate OS handle bypasses the launcher's local gate, exactly as
22182        // another process holding coordination does.
22183        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22184        assert_eq!(
22185            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22186            0
22187        );
22188        let error = tokio::time::timeout(
22189            Duration::from_secs(10),
22190            fold_run_when(&mut state, &home, &|_| Ok(true)),
22191        )
22192        .await
22193        .expect("the automatic fold does not wait out the 60 s resource wait")
22194        .unwrap_err();
22195        assert!(
22196            matches!(
22197                error.downcast_ref::<FoldRefusal>(),
22198                Some(FoldRefusal::Live(_))
22199            ),
22200            "{error:#}"
22201        );
22202        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
22203        // It gave way: both locks it held are free, nothing was removed and
22204        // nothing was saved (no resource block recorded on the record either).
22205        drop(crate::pr_head::owner_lock(&home, &id).expect("the owner lock was released"));
22206        drop(crate::driver::maintenance(&home, &id).expect("the execution lease was released"));
22207        assert!(candidate.exists() && git::branch_exists(&repo, &branch).await.unwrap());
22208        assert_eq!(
22209            std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap(),
22210            record
22211        );
22212
22213        // The explicit entry point was asked for by a person and still waits.
22214        assert!(
22215            tokio::time::timeout(
22216                Duration::from_millis(300),
22217                fold_run(&mut state, true, &home)
22218            )
22219            .await
22220            .is_err(),
22221            "an explicit fold keeps waiting for coordination"
22222        );
22223        assert!(candidate.exists());
22224
22225        drop(external);
22226        let removed = fold_run_when(&mut state, &home, &|_| Ok(true))
22227            .await
22228            .unwrap();
22229        assert!(removed.contains(&branch));
22230        assert!(!candidate.exists());
22231    }
22232
22233    /// A branch handed to a later run is that run's (and its pull request's):
22234    /// folding the run that released it must not delete it.
22235    #[tokio::test]
22236    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
22237        let tmp = tempfile::tempdir().expect("tempdir");
22238        let repo = tmp.path().join("repo");
22239        std::fs::create_dir_all(&repo).unwrap();
22240        init_repo(&repo);
22241        let home = tmp.path().join("home");
22242
22243        let mut config = Config::default();
22244        config.graph.worktree_root = Some(tmp.path().join("wt"));
22245        let mut state = RunState::new(
22246            repo.clone(),
22247            "main".to_owned(),
22248            "deadbeef".to_owned(),
22249            "task".to_owned(),
22250            config,
22251        );
22252        // The worktree is already gone (released); the branch survives.
22253        git::git(&repo, &["branch", "magi/x/A", "main"])
22254            .await
22255            .expect("branch");
22256        state.candidates = vec![Candidate {
22257            index: 0,
22258            label: 'A',
22259            agent: "alpha".to_owned(),
22260            branch: "magi/x/A".to_owned(),
22261            worktree: state.worktree_root().join("cand-A"),
22262            summary: String::new(),
22263            stat: String::new(),
22264            files: 0,
22265            commits: 0,
22266            empty: false,
22267            failed: None,
22268            verified_noop: None,
22269            duration_ms: 0,
22270            folded: true,
22271        }];
22272        state.released_to = Some("20260901-000000-new1".to_owned());
22273        state.released_branches = vec!["magi/x/A".to_owned()];
22274
22275        state.save_under(&home).unwrap();
22276        fold_run(&mut state, true, &home).await.expect("fold_run");
22277        state.status = RunStatus::Merged;
22278        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
22279        state.merge = Some(crate::run::MergeOutcome {
22280            mode: MergeMode::Pr,
22281            ok: true,
22282            detail: "confirmed merged".into(),
22283            empty: false,
22284        });
22285        state.save_under(&home).unwrap();
22286        fold_run(&mut state, true, &home)
22287            .await
22288            .expect("merged fold");
22289
22290        assert!(
22291            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
22292            "the handed-over branch survives a fold"
22293        );
22294    }
22295
22296    /// A winner with nothing ahead of the base is caught before `gh` is ever
22297    /// asked for a pull request, and the message carries what the task's
22298    /// references resolved to.
22299    #[tokio::test]
22300    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
22301        let tmp = tempfile::tempdir().expect("tempdir");
22302        let repo = tmp.path().join("repo");
22303        std::fs::create_dir_all(&repo).unwrap();
22304        init_repo(&repo);
22305        let run = |args: &[&str]| {
22306            let out = std::process::Command::new("git")
22307                .quiet()
22308                .args(args)
22309                .current_dir(&repo)
22310                .output()
22311                .expect("spawn git");
22312            assert!(out.status.success(), "git {args:?}");
22313        };
22314        run(&["branch", "magi/x/A"]);
22315        run(&["checkout", "-q", "-b", "magi/x/B"]);
22316        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
22317        run(&["add", "-A"]);
22318        run(&["commit", "-q", "-m", "work"]);
22319        run(&["checkout", "-q", "main"]);
22320
22321        // A pull request is compared against the remote's base, so the
22322        // fixture needs one. Before it exists nothing can be read, and the
22323        // answer must be "not empty".
22324        let probe = RunState::new(
22325            repo.clone(),
22326            "main".to_owned(),
22327            "deadbeef".to_owned(),
22328            "task".to_owned(),
22329            Config::default(),
22330        );
22331        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
22332        let bare = tmp.path().join("origin.git");
22333        let out = std::process::Command::new("git")
22334            .quiet()
22335            .args(["init", "-q", "--bare"])
22336            .arg(&bare)
22337            .output()
22338            .expect("spawn git");
22339        assert!(out.status.success(), "git init --bare");
22340        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
22341        run(&["push", "-q", "origin", "main"]);
22342
22343        let mut state = RunState::new(
22344            repo.clone(),
22345            "main".to_owned(),
22346            "deadbeef".to_owned(),
22347            "task".to_owned(),
22348            Config::default(),
22349        );
22350        state.seeds = vec![refs::Seed {
22351            token: "magi/27b2/A".to_owned(),
22352            kind: refs::SeedKind::Unresolved,
22353            sha: String::new(),
22354            branch: true,
22355            detail: "no branch or commit named magi/27b2/A".to_owned(),
22356        }];
22357
22358        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
22359        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
22360        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
22361        let detail = empty_candidate_detail(&state, "main");
22362        assert!(detail.starts_with("empty candidate"), "{detail}");
22363        assert!(!detail.contains("magi/27b2/A"), "{detail}");
22364        assert!(detail.contains("--start-from"), "{detail}");
22365    }
22366
22367    /// `status == Ready` used to be read as "this is the harmless
22368    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
22369    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
22370    /// run's PR was closed without merging — and reentering `merge` with
22371    /// `mode` still `Pr` does not know the difference, so it pushed and
22372    /// opened a second pull request. `mode == Local` reproduces the same
22373    /// blind spot without a network call: reentry must not attempt another
22374    /// git merge once this node has already recorded an outcome.
22375    #[tokio::test]
22376    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
22377        let tmp = tempfile::tempdir().expect("tempdir");
22378        let repo = tmp.path().join("repo");
22379        std::fs::create_dir_all(&repo).unwrap();
22380        init_repo(&repo);
22381
22382        let mut config = Config::default();
22383        config.merge.mode = MergeMode::Local;
22384
22385        let mut state = RunState::new(
22386            repo.clone(),
22387            "main".to_owned(),
22388            "deadbeef".to_owned(),
22389            "task".to_owned(),
22390            config,
22391        );
22392        state.candidates = vec![Candidate {
22393            index: 0,
22394            label: 'A',
22395            agent: "alpha".to_owned(),
22396            branch: "does-not-exist".to_owned(),
22397            worktree: repo.clone(),
22398            summary: String::new(),
22399            stat: String::new(),
22400            files: 0,
22401            commits: 0,
22402            empty: false,
22403            failed: None,
22404            verified_noop: None,
22405            duration_ms: 0,
22406            folded: false,
22407        }];
22408        state.tally = Some(Tally {
22409            first_choice: BTreeMap::from([('A', 1)]),
22410            borda: BTreeMap::new(),
22411            winner: 'A',
22412            rankings: 1,
22413            unanimous_initial: true,
22414            deliberated: false,
22415            changed_votes: 0,
22416            unanimous_final: true,
22417            tie_break: None,
22418            judges: 0,
22419            present: 0,
22420            quorum: 0,
22421            met_quorum: true,
22422            uncontested: Some("only candidate A produced a change".to_owned()),
22423        });
22424        state.reviews = vec![ReviewRound {
22425            round: 1,
22426            head: "deadbeef".to_owned(),
22427            verified_head: None,
22428            verified_at: None,
22429            reviews: Vec::new(),
22430            e2e: Vec::new(),
22431            fix: None,
22432            blocking: 0,
22433            answered: 0,
22434            expected: 0,
22435            clean: true,
22436            verify_retried: false,
22437            e2e_deferred: false,
22438            e2e_defer_reason: None,
22439            progressed: false,
22440            vote_split: false,
22441            reconsideration: Vec::new(),
22442            verdict: None,
22443        }];
22444        state.gate = vec![CommandOutcome {
22445            command: "test".to_owned(),
22446            code: Some(0),
22447            output_tail: String::new(),
22448            duration_ms: 0,
22449            resource_blocked: false,
22450            ..Default::default()
22451        }];
22452        state.gate_ran = true;
22453        // Reached its conclusion already — e.g. `land` closing the PR without
22454        // merging it, which (like the honest `MergeMode::None` path) leaves
22455        // `status` at `Ready`. The recorded outcome is what actually marks
22456        // this node done.
22457        state.status = RunStatus::Ready;
22458        state.merge = Some(MergeOutcome {
22459            mode: MergeMode::Local,
22460            ok: false,
22461            detail: "already concluded".to_owned(),
22462            empty: false,
22463        });
22464
22465        let mut runner = Runner {
22466            state,
22467            roles: ResolvedRoles {
22468                implementers: Vec::new(),
22469                judges: Vec::new(),
22470                reviewers: Vec::new(),
22471                fixer: None,
22472                conductor: conductor(),
22473                implementer_roster: Vec::new(),
22474                judge_roster: Vec::new(),
22475                reviewer_roster: Vec::new(),
22476            },
22477            sem: Arc::new(Semaphore::new(1)),
22478            pause: Pause::new(),
22479            interrupt: Pause::new(),
22480        };
22481
22482        runner.merge().await.expect("merge");
22483
22484        assert_eq!(
22485            runner.state.status,
22486            RunStatus::Ready,
22487            "a concluded run's status must not change on reentry"
22488        );
22489        assert_eq!(
22490            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22491            Some("already concluded"),
22492            "merge must not run again once the node already recorded an outcome"
22493        );
22494    }
22495
22496    /// `gate` leaves `state.gate_ran` false both before it has ever run and
22497    /// when its last attempt was resource-blocked (the shared build cache
22498    /// could not be acquired or confirmed fresh in time - see
22499    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
22500    /// `Vec` this also leaves behind used to read as "nothing failed" and let
22501    /// a run merge a tree the gate never actually checked - exactly the case
22502    /// a contended cache produces on every retry until it clears. `merge`
22503    /// must refuse until `gate` has actually recorded an attempt.
22504    #[tokio::test]
22505    async fn merge_refuses_a_gate_that_has_not_actually_run() {
22506        let tmp = tempfile::tempdir().expect("tempdir");
22507        let repo = tmp.path().join("repo");
22508        std::fs::create_dir_all(&repo).unwrap();
22509        init_repo(&repo);
22510
22511        let mut config = Config::default();
22512        config.merge.mode = MergeMode::Local;
22513
22514        let mut state = RunState::new(
22515            repo.clone(),
22516            "main".to_owned(),
22517            "deadbeef".to_owned(),
22518            "task".to_owned(),
22519            config,
22520        );
22521        state.candidates = vec![Candidate {
22522            index: 0,
22523            label: 'A',
22524            agent: "alpha".to_owned(),
22525            branch: "does-not-exist".to_owned(),
22526            worktree: repo.clone(),
22527            summary: String::new(),
22528            stat: String::new(),
22529            files: 0,
22530            commits: 0,
22531            empty: false,
22532            failed: None,
22533            verified_noop: None,
22534            duration_ms: 0,
22535            folded: false,
22536        }];
22537        state.tally = Some(Tally {
22538            first_choice: BTreeMap::from([('A', 1)]),
22539            borda: BTreeMap::new(),
22540            winner: 'A',
22541            rankings: 1,
22542            unanimous_initial: true,
22543            deliberated: false,
22544            changed_votes: 0,
22545            unanimous_final: true,
22546            tie_break: None,
22547            judges: 0,
22548            present: 0,
22549            quorum: 0,
22550            met_quorum: true,
22551            uncontested: Some("only candidate A produced a change".to_owned()),
22552        });
22553        state.reviews = vec![ReviewRound {
22554            round: 1,
22555            head: "deadbeef".to_owned(),
22556            verified_head: None,
22557            verified_at: None,
22558            reviews: Vec::new(),
22559            e2e: Vec::new(),
22560            fix: None,
22561            blocking: 0,
22562            answered: 0,
22563            expected: 0,
22564            clean: true,
22565            verify_retried: false,
22566            e2e_deferred: false,
22567            e2e_defer_reason: None,
22568            progressed: false,
22569            vote_split: false,
22570            reconsideration: Vec::new(),
22571            verdict: None,
22572        }];
22573        // The point: `gate` has not recorded anything yet.
22574        state.gate = Vec::new();
22575        state.gate_ran = false;
22576        state.status = RunStatus::Gating;
22577
22578        let mut runner = Runner {
22579            state,
22580            roles: ResolvedRoles {
22581                implementers: Vec::new(),
22582                judges: Vec::new(),
22583                reviewers: Vec::new(),
22584                fixer: None,
22585                conductor: conductor(),
22586                implementer_roster: Vec::new(),
22587                judge_roster: Vec::new(),
22588                reviewer_roster: Vec::new(),
22589            },
22590            sem: Arc::new(Semaphore::new(1)),
22591            pause: Pause::new(),
22592            interrupt: Pause::new(),
22593        };
22594
22595        runner.merge().await.expect("merge");
22596
22597        assert!(
22598            runner.state.merge.is_none(),
22599            "an empty gate must never be read as a passing one: {:?}",
22600            runner.state.merge
22601        );
22602    }
22603
22604    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
22605    /// commands configured and `merge.mode` is `none` (a review-only run).
22606    /// `gate` must still record a real attempt — zero commands, vacuously
22607    /// passed — rather than leaving `state.gate` empty in a way `merge`
22608    /// cannot tell apart from "never ran"; otherwise the run reaches
22609    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
22610    #[tokio::test]
22611    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
22612        let tmp = tempfile::tempdir().expect("tempdir");
22613        let repo = tmp.path().join("repo");
22614        std::fs::create_dir_all(&repo).unwrap();
22615        init_repo(&repo);
22616
22617        // Default config: `verify.gate` empty, `merge.mode` is `none`.
22618        let config = Config::default();
22619
22620        let mut state = RunState::new(
22621            repo.clone(),
22622            "main".to_owned(),
22623            "deadbeef".to_owned(),
22624            "task".to_owned(),
22625            config,
22626        );
22627        state.candidates = vec![Candidate {
22628            index: 0,
22629            label: 'A',
22630            agent: "alpha".to_owned(),
22631            branch: "does-not-exist".to_owned(),
22632            worktree: repo.clone(),
22633            summary: String::new(),
22634            stat: String::new(),
22635            files: 0,
22636            commits: 0,
22637            empty: false,
22638            failed: None,
22639            verified_noop: None,
22640            duration_ms: 0,
22641            folded: false,
22642        }];
22643        state.tally = Some(Tally {
22644            first_choice: BTreeMap::from([('A', 1)]),
22645            borda: BTreeMap::new(),
22646            winner: 'A',
22647            rankings: 1,
22648            unanimous_initial: true,
22649            deliberated: false,
22650            changed_votes: 0,
22651            unanimous_final: true,
22652            tie_break: None,
22653            judges: 0,
22654            present: 0,
22655            quorum: 0,
22656            met_quorum: true,
22657            uncontested: Some("only candidate A produced a change".to_owned()),
22658        });
22659        state.reviews = vec![ReviewRound {
22660            round: 1,
22661            head: "deadbeef".to_owned(),
22662            verified_head: None,
22663            verified_at: None,
22664            reviews: Vec::new(),
22665            e2e: Vec::new(),
22666            fix: None,
22667            blocking: 0,
22668            answered: 0,
22669            expected: 0,
22670            clean: true,
22671            verify_retried: false,
22672            e2e_deferred: false,
22673            e2e_defer_reason: None,
22674            progressed: false,
22675            vote_split: false,
22676            reconsideration: Vec::new(),
22677            verdict: None,
22678        }];
22679
22680        let mut runner = Runner {
22681            state,
22682            roles: ResolvedRoles {
22683                implementers: Vec::new(),
22684                judges: Vec::new(),
22685                reviewers: Vec::new(),
22686                fixer: None,
22687                conductor: conductor(),
22688                implementer_roster: Vec::new(),
22689                judge_roster: Vec::new(),
22690                reviewer_roster: Vec::new(),
22691            },
22692            sem: Arc::new(Semaphore::new(1)),
22693            pause: Pause::new(),
22694            interrupt: Pause::new(),
22695        };
22696
22697        runner.gate().await.expect("gate");
22698        assert!(
22699            runner.state.gate_ran,
22700            "zero configured commands is still a real attempt, not an unrun gate"
22701        );
22702        assert!(runner.state.gate.is_empty());
22703        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
22704        assert_ne!(
22705            runner.state.status,
22706            RunStatus::Blocked,
22707            "a gate with nothing to check must not read as failed"
22708        );
22709
22710        runner.merge().await.expect("merge");
22711        assert_eq!(
22712            runner.state.status,
22713            RunStatus::Ready,
22714            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
22715        );
22716    }
22717
22718    /// `Config::cache_dir` is derived from `verify.e2e` as well as
22719    /// `verify.gate` (so the e2e leg and the final gate never build against
22720    /// different directories). With zero `verify.gate` commands but a
22721    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
22722    /// that lease before discovering it had nothing to run - so a repo with
22723    /// no gate commands could come back `resource_blocked` (and therefore
22724    /// still `gate_ran == false`) on nothing but an unrelated run holding the
22725    /// cache, exactly the contention this run's own zero commands could
22726    /// never have touched. `gate` must recognise there is nothing to check
22727    /// before it ever asks for the lease.
22728    #[tokio::test]
22729    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
22730        crate::run::pin_test_home();
22731        let home = crate::run::home();
22732
22733        let tmp = tempfile::tempdir().expect("tempdir");
22734        let repo = tmp.path().join("repo");
22735        std::fs::create_dir_all(&repo).unwrap();
22736        init_repo(&repo);
22737        // Unique to this test, so holding its lease cannot collide with
22738        // another test sharing the same process-wide `home`.
22739        let cache_dir = tmp.path().join("target");
22740
22741        let mut config = Config::default();
22742        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
22743        // `verify.gate` stays empty (the default). Any accidental cache
22744        // acquisition must report contention immediately, regardless of how
22745        // long unrelated Git subprocesses take under parallel test load.
22746        config.graph.timeout_verify = Some(2);
22747        config.graph.timeout_resource_wait = 0;
22748
22749        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22750        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22751            .expect("no io error acquiring directly")
22752        {
22753            crate::cache::AcquireOutcome::Acquired(g) => g,
22754            crate::cache::AcquireOutcome::Busy(b) => {
22755                panic!("expected the direct acquire to win the lease first: {b:?}")
22756            }
22757        };
22758
22759        let mut state = RunState::new(
22760            repo.clone(),
22761            "main".to_owned(),
22762            "deadbeef".to_owned(),
22763            "task".to_owned(),
22764            config,
22765        );
22766        state.candidates = vec![Candidate {
22767            index: 0,
22768            label: 'A',
22769            agent: "alpha".to_owned(),
22770            branch: "does-not-exist".to_owned(),
22771            worktree: repo.clone(),
22772            summary: String::new(),
22773            stat: String::new(),
22774            files: 0,
22775            commits: 0,
22776            empty: false,
22777            failed: None,
22778            verified_noop: None,
22779            duration_ms: 0,
22780            folded: false,
22781        }];
22782        state.tally = Some(Tally {
22783            first_choice: BTreeMap::from([('A', 1)]),
22784            borda: BTreeMap::new(),
22785            winner: 'A',
22786            rankings: 1,
22787            unanimous_initial: true,
22788            deliberated: false,
22789            changed_votes: 0,
22790            unanimous_final: true,
22791            tie_break: None,
22792            judges: 0,
22793            present: 0,
22794            quorum: 0,
22795            met_quorum: true,
22796            uncontested: Some("only candidate A produced a change".to_owned()),
22797        });
22798        state.reviews = vec![ReviewRound {
22799            round: 1,
22800            head: "deadbeef".to_owned(),
22801            verified_head: None,
22802            verified_at: None,
22803            reviews: Vec::new(),
22804            e2e: Vec::new(),
22805            fix: None,
22806            blocking: 0,
22807            answered: 0,
22808            expected: 0,
22809            clean: true,
22810            verify_retried: false,
22811            e2e_deferred: false,
22812            e2e_defer_reason: None,
22813            progressed: false,
22814            vote_split: false,
22815            reconsideration: Vec::new(),
22816            verdict: None,
22817        }];
22818
22819        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22820        state.reviews[0].e2e = vec![CommandOutcome {
22821            command: state.config.verify.e2e[0].clone(),
22822            code: Some(0),
22823            output_tail: String::new(),
22824            duration_ms: 0,
22825            resource_blocked: false,
22826            ..Default::default()
22827        }];
22828        let mut runner = Runner {
22829            state,
22830            roles: ResolvedRoles {
22831                implementers: Vec::new(),
22832                judges: Vec::new(),
22833                reviewers: Vec::new(),
22834                fixer: None,
22835                conductor: conductor(),
22836                implementer_roster: Vec::new(),
22837                judge_roster: Vec::new(),
22838                reviewer_roster: Vec::new(),
22839            },
22840            sem: Arc::new(Semaphore::new(1)),
22841            pause: Pause::new(),
22842            interrupt: Pause::new(),
22843        };
22844
22845        runner.gate().await.expect("gate");
22846        assert!(runner.state.resource_block.is_none());
22847        assert!(
22848            !runner
22849                .state
22850                .events
22851                .iter()
22852                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22853            "a gate with nothing to run must never request the held cache lease"
22854        );
22855        assert!(
22856            runner.state.gate_ran,
22857            "zero commands is still a real, immediate attempt"
22858        );
22859        assert!(runner.state.gate.is_empty());
22860        assert_ne!(
22861            runner.state.status,
22862            RunStatus::Blocked,
22863            "must not read as resource-blocked on a lease it never asked for"
22864        );
22865    }
22866
22867    /// A separate process carries a live worker's environment throughout all
22868    /// verification entry points; the parallel harness never changes its env.
22869    #[cfg(unix)]
22870    #[tokio::test]
22871    async fn verification_is_standalone_inside_a_live_worker() {
22872        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22873        if std::env::var_os(CHILD).is_none() {
22874            let home = tempfile::tempdir().unwrap();
22875            let generation = crate::worker::pin_current(home.path()).unwrap();
22876            let output = std::process::Command::new(std::env::current_exe().unwrap())
22877                .args([
22878                    "--exact",
22879                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22880                    "--nocapture",
22881                ])
22882                .env(CHILD, "1")
22883                .env("MAGI_HOME", home.path())
22884                .env("MAGI_WORKER_HOME", home.path())
22885                .env("MAGI_WORKER_ID", "abcdef")
22886                .env("MAGI_WORKER_GENERATION", &generation.id)
22887                .env("MAGI_WORKER_EXE", &generation.executable)
22888                .env("MAGI_RUN", "verification-parent")
22889                .env("MAGI_NODE", "gate")
22890                .env("MAGI_SEAT", "worker-fixture")
22891                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22892                .env("MAGI_NO_AUTOUPDATE", "0")
22893                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22894                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22895                .env(
22896                    "VERIFY_EXPECT_TOOLCHAIN",
22897                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22898                )
22899                .env(
22900                    "VERIFY_EXPECT_CACHE",
22901                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22902                )
22903                .output()
22904                .unwrap();
22905            assert!(
22906                output.status.success()
22907                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22908                "{}\n{}",
22909                String::from_utf8_lossy(&output.stdout),
22910                String::from_utf8_lossy(&output.stderr)
22911            );
22912            return;
22913        }
22914        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22915        let home = crate::run::home();
22916        let directory = home.join("workers/jobs/abcdef");
22917        std::fs::create_dir_all(&directory).unwrap();
22918        let job = crate::worker::Job {
22919            id: "abcdef".into(),
22920            sequence: 1,
22921            kind: "task".into(),
22922            key: "task:verification".into(),
22923            payload: serde_json::json!({}),
22924            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22925            version: Some(env!("CARGO_PKG_VERSION").into()),
22926            status: crate::worker::Status::Running,
22927            result: None,
22928            pid: Some(std::process::id()),
22929            created_at: 0,
22930            finished_at: None,
22931        };
22932        std::fs::write(
22933            directory.join("job.json"),
22934            serde_json::to_vec(&job).unwrap(),
22935        )
22936        .unwrap();
22937        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22938        let assert_worker = || {
22939            assert_eq!(
22940                crate::worker::current_job(&home).unwrap().unwrap().id,
22941                job.id
22942            );
22943            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22944            assert_eq!(
22945                crate::worker::helper_executable(&home).unwrap(),
22946                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22947            );
22948            assert!(
22949                crate::updater::Checker::new(&crate::config::Update {
22950                    mode: crate::config::UpdateMode::Notify,
22951                    interval: None,
22952                    auto_restart: false,
22953                })
22954                .is_none(),
22955                "the driver remains pinned, even while tests are standalone"
22956            );
22957        };
22958        assert_worker();
22959        let repo = home.join("repo");
22960        std::fs::create_dir_all(&repo).unwrap();
22961        init_repo(&repo);
22962        // Keep storage, seat/control context, containment and tool lookup.
22963        // No inherited values (or credentials) are printed on success.
22964        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22965            test -z "${MAGI_WORKER_GENERATION+x}" &&
22966            test -z "${MAGI_WORKER_HOME+x}" &&
22967            test -z "${MAGI_WORKER_EXE+x}" &&
22968            test "$MAGI_HOME/repo" -ef . &&
22969            test "$MAGI_RUN" = verification-parent &&
22970            test "$MAGI_NODE" = gate &&
22971            test "$MAGI_SEAT" = worker-fixture &&
22972            test -n "$MAGI_PROCESS_OWNER" &&
22973            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22974            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22975            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22976            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22977        // Negative control: an ordinary child inherits the contamination.
22978        assert!(
22979            !std::process::Command::new("sh")
22980                .args(["-c", probe])
22981                .current_dir(&repo)
22982                .status()
22983                .unwrap()
22984                .success()
22985        );
22986        let unrelated_home = tempfile::tempdir().unwrap();
22987        assert!(
22988            crate::worker::current_job(unrelated_home.path()).is_err(),
22989            "an inherited worker id cannot be resolved in a unit fixture's home"
22990        );
22991        let mut runner = runner_at(RunStatus::Gating);
22992        runner.state.repo = repo.clone();
22993        runner.state.config.disk.min_free_bytes = 0;
22994        runner.state.config.coordination = crate::config::test_coordination();
22995        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
22996        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
22997        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
22998        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
22999        let winner = Candidate {
23000            index: 0,
23001            label: 'A',
23002            agent: "fixture".into(),
23003            branch: "main".into(),
23004            worktree: repo.clone(),
23005            summary: String::new(),
23006            stat: String::new(),
23007            files: 0,
23008            commits: 0,
23009            empty: false,
23010            failed: None,
23011            verified_noop: None,
23012            duration_ms: 0,
23013            folded: false,
23014        };
23015        let (e2e, retried, pids) = run_e2e_with_retry(
23016            &mut runner.state,
23017            &["sh".into(), "-c".into()],
23018            &[format!("{probe} && printf initial")],
23019            &repo,
23020            Duration::from_secs(10),
23021            "initial",
23022            None,
23023        )
23024        .await;
23025        assert!(!retried && pids.is_empty());
23026        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
23027        assert_eq!(e2e[0].output_tail, "initial");
23028        let gate = runner.run_gate(&winner).await.unwrap();
23029        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
23030        // An interrupted repair must recheck e2e from saved state. Landing
23031        // reuses that state and must run both pre-gate and gate again.
23032        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
23033            git::rev_parse(&repo, "HEAD").await.unwrap(),
23034            false,
23035            Vec::new(),
23036        ));
23037        runner.state.save().unwrap();
23038        let mut resumed = RunState::load(&runner.state.id).unwrap();
23039        let wait = crate::repo_lock::WaitPolicy::default();
23040        assert!(matches!(
23041            check_gate_repair_e2e(&mut resumed, &winner, &wait)
23042                .await
23043                .unwrap(),
23044            GateFix::Retry
23045        ));
23046        let saved = RunState::load(&resumed.id).unwrap();
23047        let repair = saved.gate_repair_e2e.unwrap();
23048        assert!(repair.passed);
23049        assert_eq!(repair.outcomes.len(), 1);
23050        assert!(repair.outcomes[0].ok());
23051        let landing = run_landing_gate(&mut resumed, &winner, &wait)
23052            .await
23053            .unwrap();
23054        assert_eq!(landing.len(), 1);
23055        assert!(landing[0].ok(), "{landing:?}");
23056        assert_eq!(
23057            std::fs::read_to_string(repo.join("phases")).unwrap(),
23058            "pre\ngate\ne2e\npre\ngate\n"
23059        );
23060        assert_worker();
23061    }
23062
23063    #[cfg(unix)]
23064    #[tokio::test]
23065    async fn verification_keeps_the_panic_and_the_full_output() {
23066        crate::run::pin_test_home();
23067        let tmp = tempfile::tempdir().unwrap();
23068        let mut config = Config::default();
23069        config.disk.min_free_bytes = 0;
23070        let mut state = RunState::new(
23071            tmp.path().to_owned(),
23072            "main".into(),
23073            "base".into(),
23074            "verification evidence".into(),
23075            config,
23076        );
23077        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
23078                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
23079                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
23080        let mut names = Vec::new();
23081        for _ in 0..2 {
23082            let (outcomes, _) = run_commands(
23083                &mut state,
23084                "gate",
23085                "gate",
23086                0,
23087                &["sh".into(), "-c".into()],
23088                &[script.into()],
23089                tmp.path(),
23090                Duration::from_secs(60),
23091            )
23092            .await;
23093            let tail = &outcomes[0].output_tail;
23094            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
23095            assert!(tail.contains("boom assertion"));
23096            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
23097            let line = tail.lines().next().unwrap();
23098            names.push(line.to_owned());
23099        }
23100        assert_ne!(names[0], names[1], "the second run must not overwrite");
23101        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
23102        assert!(full.len() > 500_000 && full.contains("boom assertion"));
23103        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
23104
23105        // Storage failures are evidence too; preserve the command's verdict.
23106        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
23107        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
23108        let (outcomes, _) = run_commands(
23109            &mut state,
23110            "gate",
23111            "gate",
23112            0,
23113            &["sh".into(), "-c".into()],
23114            &["echo failure-output; exit 7".into()],
23115            tmp.path(),
23116            Duration::from_secs(10),
23117        )
23118        .await;
23119        assert_eq!(outcomes[0].code, Some(7));
23120        assert!(state.events.iter().any(|e| {
23121            e.node == "gate" && e.message.contains("could not save the full gate output:")
23122        }));
23123    }
23124
23125    #[cfg(unix)]
23126    #[tokio::test]
23127    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
23128        crate::run::pin_test_home();
23129        let tmp = tempfile::tempdir().unwrap();
23130        let mut config = Config::default();
23131        config.disk.min_free_bytes = 0;
23132        let mut state = RunState::new(
23133            tmp.path().to_owned(),
23134            "main".into(),
23135            "base".into(),
23136            "verification evidence".into(),
23137            config,
23138        );
23139        let (outcomes, pids) = run_commands(
23140            &mut state,
23141            "gate",
23142            "gate",
23143            1,
23144            &["sh".into(), "-c".into()],
23145            &[
23146                "printf before-timeout; exec sleep 30".into(),
23147                "kill -TERM $$".into(),
23148                "exit 7".into(),
23149                "printf success".into(),
23150            ],
23151            tmp.path(),
23152            Duration::from_secs(1),
23153        )
23154        .await;
23155        wait_for_timed_out_children_to_die(&pids).await;
23156        assert_eq!(
23157            pids.len(),
23158            1,
23159            "unleased timeout retains its death-check PID"
23160        );
23161        assert_eq!(outcomes.len(), 4);
23162        assert_eq!(outcomes[0].code, None);
23163        assert!(outcomes[0].output_tail.contains("before-timeout"));
23164        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
23165        assert_eq!(outcomes[1].code, None);
23166        assert!(outcomes[1].output_tail.contains("command terminated:"));
23167        assert!(!outcomes[1].output_tail.contains("timed out"));
23168        assert_eq!(outcomes[2].code, Some(7));
23169        assert!(!outcomes[2].output_tail.contains("timed out"));
23170        assert_eq!(outcomes[3].code, Some(0));
23171        assert_eq!(outcomes[3].output_tail, "success");
23172        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
23173    }
23174
23175    /// The addendum's second gap: a `verify.gate` command running for real
23176    /// wall-clock time had nothing at all to show for it in `active` before
23177    /// `run_commands` learned to record it — a run could sit in `Gating` for
23178    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
23179    /// what was actually happening. Proven with a genuinely still-running
23180    /// command, not just a before/after check on the final state: a poller
23181    /// task reads the same `run.json` `gate()` is writing, the same way the
23182    /// phone or `magi show` would, while the shell command is still blocked
23183    /// on its own release marker.
23184    #[tokio::test]
23185    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
23186        crate::run::pin_test_home();
23187
23188        let tmp = tempfile::tempdir().expect("tempdir");
23189        let repo = tmp.path().join("repo");
23190        std::fs::create_dir_all(&repo).unwrap();
23191        init_repo(&repo);
23192
23193        let mut config = Config::default();
23194        config.disk.min_free_bytes = 0;
23195        config.verify.gate = vec![
23196            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
23197             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
23198                .to_owned(),
23199        ];
23200
23201        let mut state = RunState::new(
23202            repo.clone(),
23203            "main".to_owned(),
23204            "deadbeef".to_owned(),
23205            "task".to_owned(),
23206            config,
23207        );
23208        let run_id = state.id.clone();
23209        state.candidates = vec![Candidate {
23210            index: 0,
23211            label: 'A',
23212            agent: "alpha".to_owned(),
23213            branch: "does-not-exist".to_owned(),
23214            worktree: repo.clone(),
23215            summary: String::new(),
23216            stat: String::new(),
23217            files: 0,
23218            commits: 0,
23219            empty: false,
23220            failed: None,
23221            verified_noop: None,
23222            duration_ms: 0,
23223            folded: false,
23224        }];
23225        state.tally = Some(Tally {
23226            first_choice: BTreeMap::from([('A', 1)]),
23227            borda: BTreeMap::new(),
23228            winner: 'A',
23229            rankings: 1,
23230            unanimous_initial: true,
23231            deliberated: false,
23232            changed_votes: 0,
23233            unanimous_final: true,
23234            tie_break: None,
23235            judges: 0,
23236            present: 0,
23237            quorum: 0,
23238            met_quorum: true,
23239            uncontested: Some("only candidate A produced a change".to_owned()),
23240        });
23241        state.reviews = vec![ReviewRound {
23242            round: 1,
23243            head: "deadbeef".to_owned(),
23244            verified_head: None,
23245            verified_at: None,
23246            reviews: Vec::new(),
23247            e2e: Vec::new(),
23248            fix: None,
23249            blocking: 0,
23250            answered: 0,
23251            expected: 0,
23252            clean: true,
23253            verify_retried: false,
23254            e2e_deferred: false,
23255            e2e_defer_reason: None,
23256            progressed: false,
23257            vote_split: false,
23258            reconsideration: Vec::new(),
23259            verdict: None,
23260        }];
23261
23262        let mut runner = Runner {
23263            state,
23264            roles: ResolvedRoles {
23265                implementers: Vec::new(),
23266                judges: Vec::new(),
23267                reviewers: Vec::new(),
23268                fixer: None,
23269                conductor: conductor(),
23270                implementer_roster: Vec::new(),
23271                judge_roster: Vec::new(),
23272                reviewer_roster: Vec::new(),
23273            },
23274            sem: Arc::new(Semaphore::new(1)),
23275            pause: Pause::new(),
23276            interrupt: Pause::new(),
23277        };
23278
23279        let started_marker = repo.join("started.marker");
23280        let release_marker = repo.join("release.marker");
23281        let observe = async {
23282            loop {
23283                if started_marker.exists()
23284                    && let Ok(s) = crate::run::RunState::load(&run_id)
23285                    && let Some(a) = s.active.get("gate")
23286                {
23287                    std::fs::write(&release_marker, b"go").expect("release marker");
23288                    break a.clone();
23289                }
23290                tokio::time::sleep(Duration::from_millis(50)).await;
23291            }
23292        };
23293        let captured = {
23294            let gate = runner.gate();
23295            tokio::pin!(gate);
23296            let captured = tokio::select! {
23297                observed = observe => observed,
23298                result = &mut gate => panic!(
23299                    "gate exited before its in-flight entry was observed: {result:?}"
23300                ),
23301            };
23302            gate.await.expect("gate");
23303            captured
23304        };
23305
23306        assert_eq!(captured.task.as_deref(), Some("gate"));
23307        assert_eq!(captured.node, "gate");
23308        assert_eq!(captured.index, Some(1));
23309        assert_eq!(captured.total, Some(1));
23310        assert!(
23311            captured
23312                .command
23313                .as_deref()
23314                .is_some_and(|c| c.contains("started.marker")),
23315            "{captured:?}"
23316        );
23317
23318        assert!(
23319            runner.state.active.is_empty(),
23320            "the entry must be cleared once the command actually finished: {:?}",
23321            runner.state.active
23322        );
23323        assert!(runner.state.gate_ran);
23324        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
23325    }
23326
23327    /// The hand-off over a blocking finding a reviewer rejected on leaves a
23328    /// record for `land`; one with only a Minor, or no reject, leaves none.
23329    #[tokio::test]
23330    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
23331        use crate::verdict::{Finding, ReviewVote, Severity};
23332        crate::run::pin_test_home();
23333        let tmp = tempfile::tempdir().expect("tempdir");
23334        let repo = tmp.path().join("repo");
23335        std::fs::create_dir_all(&repo).unwrap();
23336        init_repo(&repo);
23337
23338        for (severity, vote, expect) in [
23339            (Severity::Major, ReviewVote::Reject, true),
23340            (Severity::Minor, ReviewVote::Reject, false),
23341            (Severity::Major, ReviewVote::Approve, false),
23342        ] {
23343            let mut round = review_round(false, 1, 1, 1, false, true);
23344            round.reviews = vec![ReviewRecord {
23345                reviewer: 1,
23346                agent: "alpha".to_owned(),
23347                summary: String::new(),
23348                findings: vec![Finding {
23349                    id: "R1-1-1".to_owned(),
23350                    severity,
23351                    file: None,
23352                    line: None,
23353                    title: "t".to_owned(),
23354                    detail: String::new(),
23355                }],
23356                vote: Some(vote),
23357                failed: None,
23358                duration_ms: 0,
23359                attempts: 0,
23360            }];
23361            let mut state = RunState::new(
23362                repo.clone(),
23363                "main".to_owned(),
23364                "deadbeef".to_owned(),
23365                "task".to_owned(),
23366                Config::default(),
23367            );
23368            state.reviews = vec![round];
23369            let mut runner = Runner {
23370                state,
23371                roles: ResolvedRoles {
23372                    implementers: Vec::new(),
23373                    judges: Vec::new(),
23374                    reviewers: Vec::new(),
23375                    fixer: None,
23376                    conductor: conductor(),
23377                    implementer_roster: Vec::new(),
23378                    judge_roster: Vec::new(),
23379                    reviewer_roster: Vec::new(),
23380                },
23381                sem: Arc::new(Semaphore::new(1)),
23382                pause: Pause::new(),
23383                interrupt: Pause::new(),
23384            };
23385            let shell = runner.state.config.shell();
23386            runner
23387                .stop_reviewing("round budget spent", &shell, &repo)
23388                .await
23389                .expect("stop_reviewing");
23390            assert_eq!(runner.state.status, RunStatus::Gating);
23391            assert_eq!(
23392                runner.state.contested_handoff.is_some(),
23393                expect,
23394                "{severity:?} + {vote:?}"
23395            );
23396        }
23397    }
23398
23399    /// The shape the incident this whole fix responds to actually had: the
23400    /// round budget spent, the last round's own e2e blocked on the shared
23401    /// build cache (held here by a live pid — this test process — exactly
23402    /// `cache`'s own unit tests' pattern for "another owner, still alive"
23403    /// without forking a process). `stop_reviewing` must retry it — not
23404    /// silently leave the round looking untouched (the catch-up-only half of
23405    /// the bug), and not read the contention as a red `e2e` and block the
23406    /// run on it (the other half). Called directly, the same way
23407    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
23408    /// above exercises `gate`, so this never needs a real cargo build to
23409    /// reach: the lease is never released, so `with_cache_lease` never gets
23410    /// past acquiring it into anything that would need a real workspace.
23411    #[tokio::test]
23412    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
23413        crate::run::pin_test_home();
23414        let home = crate::run::home();
23415
23416        let tmp = tempfile::tempdir().expect("tempdir");
23417        let repo = tmp.path().join("repo");
23418        std::fs::create_dir_all(&repo).unwrap();
23419        init_repo(&repo);
23420        let head = crate::git::rev_parse(&repo, "HEAD")
23421            .await
23422            .expect("rev-parse");
23423        // Unique to this test, so holding its lease cannot collide with
23424        // another test sharing the same process-wide `home`.
23425        let cache_dir = tmp.path().join("target");
23426
23427        let mut config = Config::default();
23428        config.verify.e2e = vec![format!(
23429            "CARGO_TARGET_DIR='{}' test -f README.md",
23430            cache_dir.display()
23431        )];
23432        config.graph.review_rounds = 1;
23433        // Bounded so a regression that does start waiting fails the test in
23434        // seconds, not hangs it.
23435        config.graph.timeout_verify = Some(2);
23436        config.graph.timeout_resource_wait = 2;
23437
23438        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23439        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23440            .expect("no io error acquiring directly")
23441        {
23442            crate::cache::AcquireOutcome::Acquired(g) => g,
23443            crate::cache::AcquireOutcome::Busy(b) => {
23444                panic!("expected the direct acquire to win the lease first: {b:?}")
23445            }
23446        };
23447
23448        let mut state = RunState::new(
23449            repo.clone(),
23450            "main".to_owned(),
23451            head.clone(),
23452            "task".to_owned(),
23453            config,
23454        );
23455        state.candidates = vec![Candidate {
23456            index: 0,
23457            label: 'A',
23458            agent: "alpha".to_owned(),
23459            branch: "does-not-exist".to_owned(),
23460            worktree: repo.clone(),
23461            summary: String::new(),
23462            stat: String::new(),
23463            files: 0,
23464            commits: 0,
23465            empty: false,
23466            failed: None,
23467            verified_noop: None,
23468            duration_ms: 0,
23469            folded: false,
23470        }];
23471        state.tally = Some(Tally {
23472            first_choice: BTreeMap::from([('A', 1)]),
23473            borda: BTreeMap::new(),
23474            winner: 'A',
23475            rankings: 1,
23476            unanimous_initial: true,
23477            deliberated: false,
23478            changed_votes: 0,
23479            unanimous_final: true,
23480            tie_break: None,
23481            judges: 0,
23482            present: 0,
23483            quorum: 0,
23484            met_quorum: true,
23485            uncontested: Some("only candidate A produced a change".to_owned()),
23486        });
23487        // The round budget's last round, deferred: `needs_catchup_run`'s
23488        // other trigger. `stop_reviewing`'s retry machinery must treat this
23489        // exactly like a resource-blocked attempt once it actually runs.
23490        state.reviews = vec![ReviewRound {
23491            round: 1,
23492            head: head.clone(),
23493            verified_head: None,
23494            verified_at: None,
23495            reviews: Vec::new(),
23496            e2e: Vec::new(),
23497            fix: None,
23498            blocking: 1,
23499            answered: 1,
23500            expected: 1,
23501            clean: false,
23502            verify_retried: false,
23503            e2e_deferred: true,
23504            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
23505            progressed: false,
23506            vote_split: false,
23507            reconsideration: Vec::new(),
23508            verdict: None,
23509        }];
23510
23511        let mut runner = Runner {
23512            state,
23513            roles: ResolvedRoles {
23514                implementers: Vec::new(),
23515                judges: Vec::new(),
23516                reviewers: Vec::new(),
23517                fixer: None,
23518                conductor: conductor(),
23519                implementer_roster: Vec::new(),
23520                judge_roster: Vec::new(),
23521                reviewer_roster: Vec::new(),
23522            },
23523            sem: Arc::new(Semaphore::new(1)),
23524            pause: Pause::new(),
23525            interrupt: Pause::new(),
23526        };
23527
23528        let shell = runner.state.config.shell();
23529        runner
23530            .stop_reviewing("round budget spent", &shell, &repo)
23531            .await
23532            .expect("stop_reviewing");
23533
23534        let last = runner.state.reviews.last().expect("round record");
23535        assert_eq!(
23536            last.e2e_status(),
23537            E2eStatus::ResourceBlocked,
23538            "the shared cache is still held; the attempt must read as blocked, not deferred or \
23539             failed: {last:?}"
23540        );
23541        assert_eq!(
23542            last.verified_head.as_deref(),
23543            Some(head.as_str()),
23544            "which commit this attempt targeted is known even though nothing finished checking \
23545             it"
23546        );
23547        let first_attempt_at = last
23548            .verified_at
23549            .expect("when this attempt ran is known too");
23550        assert_ne!(
23551            runner.state.status,
23552            RunStatus::Blocked,
23553            "contention is evidence about the machine, not the patch — it must not settle the \
23554             run as blocked: {:?}",
23555            runner.state.status
23556        );
23557        assert!(
23558            !runner
23559                .state
23560                .events
23561                .iter()
23562                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
23563            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
23564            runner.state.events
23565        );
23566
23567        // The cache is still held: a later reentry must retry the same
23568        // round's verification again — not leave it looking exactly as
23569        // untouched as the first blocked attempt, which is indistinguishable
23570        // from never having tried again at all.
23571        runner
23572            .stop_reviewing("round budget spent", &shell, &repo)
23573            .await
23574            .expect("stop_reviewing retry");
23575        assert_eq!(
23576            runner.state.reviews.len(),
23577            1,
23578            "no new round was started: {:?}",
23579            runner.state.reviews
23580        );
23581        let last = runner.state.reviews.last().expect("round record");
23582        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
23583        assert!(
23584            last.verified_at.expect("still known") > first_attempt_at,
23585            "a second reentry must be a fresh attempt, not a stale copy of the first"
23586        );
23587        assert_ne!(runner.state.status, RunStatus::Blocked);
23588
23589        held.release();
23590    }
23591
23592    #[cfg(unix)]
23593    #[tokio::test]
23594    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
23595        ask_test_home();
23596        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
23597            let tmp = tempfile::tempdir().unwrap();
23598            let repo = tmp.path().join("repo");
23599            std::fs::create_dir(&repo).unwrap();
23600            init_repo(&repo);
23601            let run_git = |args: &[&str]| {
23602                let out = std::process::Command::new("git")
23603                    .args(args)
23604                    .current_dir(&repo)
23605                    .output()
23606                    .unwrap();
23607                assert!(
23608                    out.status.success(),
23609                    "{args:?}: {}",
23610                    String::from_utf8_lossy(&out.stderr)
23611                );
23612            };
23613            let origin = tmp.path().join("origin.git");
23614            run_git(&["init", "--bare", origin.to_str().unwrap()]);
23615            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
23616            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
23617            run_git(&["add", "spec.rs"]);
23618            run_git(&["commit", "-m", "initial spec"]);
23619            run_git(&["push", "origin", "main"]);
23620            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
23621            run_git(&["checkout", "-b", "fix/review"]);
23622            std::fs::write(
23623                repo.join("check.rs"),
23624                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
23625            )
23626            .unwrap();
23627            run_git(&["add", "check.rs"]);
23628            run_git(&["commit", "-m", "use spec"]);
23629            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
23630            run_git(&["checkout", "main"]);
23631            std::fs::write(
23632                repo.join("spec.rs"),
23633                "struct AgentSpec { max_turn_secs: u64 }\n",
23634            )
23635            .unwrap();
23636            run_git(&["add", "spec.rs"]);
23637            run_git(&["commit", "-m", "extend spec"]);
23638            run_git(&["push", "origin", "main"]);
23639            run_git(&["checkout", "fix/review"]);
23640
23641            let mut runner = runner_at(RunStatus::Reviewing);
23642            runner.state.repo = repo.clone();
23643            runner.state.base_commit = base;
23644            runner.state.pr_head = Some("fix/review".into());
23645            runner.state.config.graph.review_rounds = max_rounds;
23646            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
23647            runner.state.config.graph.sessions = false;
23648            runner.state.config.disk.min_free_bytes = 0;
23649            runner.state.config.verify.e2e =
23650                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
23651            runner.state.candidates = vec![Candidate {
23652                index: 0,
23653                label: 'A',
23654                agent: "fixture".into(),
23655                branch: "fix/review".into(),
23656                worktree: repo.clone(),
23657                summary: String::new(),
23658                stat: String::new(),
23659                files: 1,
23660                commits: 1,
23661                empty: false,
23662                failed: None,
23663                verified_noop: None,
23664                duration_ms: 0,
23665                folded: false,
23666            }];
23667            runner.state.tally = Some(Tally {
23668                first_choice: BTreeMap::new(),
23669                borda: BTreeMap::new(),
23670                winner: 'A',
23671                rankings: 0,
23672                unanimous_initial: true,
23673                deliberated: false,
23674                changed_votes: 0,
23675                unanimous_final: true,
23676                tie_break: None,
23677                judges: 0,
23678                present: 0,
23679                quorum: 0,
23680                met_quorum: true,
23681                uncontested: Some("review-only".into()),
23682            });
23683            let mut last = review_round(false, 0, 1, 1, false, false);
23684            last.head = reviewed.clone();
23685            last.e2e_deferred = true;
23686            last.e2e[0].resource_blocked = true;
23687            last.e2e[0].output_tail = "waiting for the shared build cache".into();
23688            if max_rounds == 1 {
23689                last.e2e.clear();
23690            }
23691            runner.state.reviews = vec![last];
23692            let calls = tmp.path().join("fix-calls");
23693            let mut fixer = spec("repair");
23694            fixer
23695                .env
23696                .insert("FIX_CALLS".into(), calls.display().to_string());
23697            fixer.command = vec!["sh".into(), "-c".into(), r#"
23698                echo fix >> "$FIX_CALLS"
23699                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
23700                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
23701                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
23702                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
23703            "#.into()];
23704            let mut reviewer = spec("reviewer");
23705            reviewer.command = vec![
23706                "sh".into(),
23707                "-c".into(),
23708                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
23709                    .into(),
23710            ];
23711            runner.roles.fixer = Some(vec![fixer]);
23712            runner.roles.reviewers = vec![reviewer];
23713
23714            runner.sync_to_base().await.unwrap();
23715            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
23716            assert_ne!(rebased, reviewed);
23717            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
23718            if reentry {
23719                // Simulate a crash after catch-up evidence was saved but before
23720                // dispatching the fixer. No dedicated pending-repair field exists.
23721                let shell = runner.state.config.shell();
23722                runner
23723                    .stop_unresolved_review("deferred verification", &shell, &repo)
23724                    .await
23725                    .unwrap();
23726                assert!(runner.catchup_repairable());
23727                assert!(!calls.exists());
23728                runner.state = RunState::load(&runner.state.id).unwrap();
23729                assert!(runner.catchup_repairable());
23730            }
23731            runner.review_loop().await.unwrap();
23732            let first = &runner.state.reviews[0];
23733            assert_eq!(first.head, reviewed);
23734            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
23735            assert!(
23736                first.verify_retried,
23737                "a reproduced build failure gets exactly one retry: {:?}",
23738                first.e2e
23739            );
23740            assert!(first.e2e[0].output_tail.contains("E0063"));
23741            assert!(!runner.catchup_repairable());
23742            if max_rounds == 2 {
23743                assert_eq!(
23744                    runner.state.status,
23745                    RunStatus::Gating,
23746                    "{}",
23747                    crate::report::run(&runner.state)
23748                );
23749                assert_eq!(runner.state.reviews.len(), 2);
23750                assert!(first.fix.as_ref().unwrap().committed);
23751                assert!(runner.state.reviews[1].clean);
23752                assert_eq!(
23753                    runner
23754                        .state
23755                        .reviews
23756                        .iter()
23757                        .filter(|r| r.fix.is_some())
23758                        .count(),
23759                    1
23760                );
23761                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
23762                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
23763            } else {
23764                assert_eq!(runner.state.status, RunStatus::Blocked);
23765                assert!(first.fix.is_none());
23766                assert!(!calls.exists());
23767                let recovery = crate::recovery::assess(
23768                    "prior",
23769                    Some(&runner.state),
23770                    &runner.landing_base(),
23771                    crate::recovery::Relation::Diverged,
23772                );
23773                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
23774                let reasons = recovery.reasons.join("\n");
23775                assert!(
23776                    reasons.contains(&reviewed) && reasons.contains(&rebased),
23777                    "{reasons}"
23778                );
23779                assert!(
23780                    reasons.contains("base sync to")
23781                        && reasons.contains("additional review is required"),
23782                    "{reasons}"
23783                );
23784            }
23785        }
23786    }
23787
23788    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23789    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23790    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23791    /// own top-of-function fast path (`review_conclusion`) correctly reads
23792    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23793    /// own `for` range is empty once the round budget is spent, so
23794    /// `review_loop` must retry the check itself rather than silently doing
23795    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23796    /// above exercises directly, but through `review_loop`'s own entry point
23797    /// this time, proving the wiring between the two rather than just the
23798    /// retry logic in isolation.
23799    #[tokio::test]
23800    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23801        crate::run::pin_test_home();
23802        let home = crate::run::home();
23803
23804        let tmp = tempfile::tempdir().expect("tempdir");
23805        let repo = tmp.path().join("repo");
23806        std::fs::create_dir_all(&repo).unwrap();
23807        init_repo(&repo);
23808        let head = crate::git::rev_parse(&repo, "HEAD")
23809            .await
23810            .expect("rev-parse");
23811        let cache_dir = tmp.path().join("target");
23812
23813        let mut config = Config::default();
23814        config.verify.e2e = vec![format!(
23815            "CARGO_TARGET_DIR='{}' test -f README.md",
23816            cache_dir.display()
23817        )];
23818        config.graph.review_rounds = 1;
23819        config.graph.timeout_verify = Some(2);
23820        config.graph.timeout_resource_wait = 2;
23821
23822        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23823        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23824            .expect("no io error acquiring directly")
23825        {
23826            crate::cache::AcquireOutcome::Acquired(g) => g,
23827            crate::cache::AcquireOutcome::Busy(b) => {
23828                panic!("expected the direct acquire to win the lease first: {b:?}")
23829            }
23830        };
23831
23832        let mut state = RunState::new(
23833            repo.clone(),
23834            "main".to_owned(),
23835            head.clone(),
23836            "task".to_owned(),
23837            config,
23838        );
23839        state.candidates = vec![Candidate {
23840            index: 0,
23841            label: 'A',
23842            agent: "alpha".to_owned(),
23843            branch: "does-not-exist".to_owned(),
23844            worktree: repo.clone(),
23845            summary: String::new(),
23846            stat: String::new(),
23847            files: 0,
23848            commits: 0,
23849            empty: false,
23850            failed: None,
23851            verified_noop: None,
23852            duration_ms: 0,
23853            folded: false,
23854        }];
23855        state.tally = Some(Tally {
23856            first_choice: BTreeMap::from([('A', 1)]),
23857            borda: BTreeMap::new(),
23858            winner: 'A',
23859            rankings: 1,
23860            unanimous_initial: true,
23861            deliberated: false,
23862            changed_votes: 0,
23863            unanimous_final: true,
23864            tie_break: None,
23865            judges: 0,
23866            present: 0,
23867            quorum: 0,
23868            met_quorum: true,
23869            uncontested: Some("only candidate A produced a change".to_owned()),
23870        });
23871        // The exact shape a prior process's `stop_reviewing` would have left
23872        // on disk: the round budget's last round, a real attempt already
23873        // made and already resource-blocked.
23874        state.reviews = vec![ReviewRound {
23875            round: 1,
23876            head: head.clone(),
23877            verified_head: Some(head.clone()),
23878            verified_at: Some(jiff::Timestamp::now()),
23879            reviews: Vec::new(),
23880            e2e: vec![CommandOutcome {
23881                command: format!(
23882                    "CARGO_TARGET_DIR='{}' test -f README.md",
23883                    cache_dir.display()
23884                ),
23885                code: None,
23886                output_tail: "waiting for the shared build cache".to_owned(),
23887                duration_ms: 0,
23888                resource_blocked: true,
23889                ..Default::default()
23890            }],
23891            fix: None,
23892            blocking: 1,
23893            answered: 1,
23894            expected: 1,
23895            clean: false,
23896            verify_retried: false,
23897            e2e_deferred: false,
23898            e2e_defer_reason: None,
23899            progressed: false,
23900            vote_split: false,
23901            reconsideration: Vec::new(),
23902            verdict: None,
23903        }];
23904
23905        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23906        let mut runner = Runner {
23907            state,
23908            roles: ResolvedRoles {
23909                implementers: Vec::new(),
23910                judges: Vec::new(),
23911                reviewers: Vec::new(),
23912                fixer: None,
23913                conductor: conductor(),
23914                implementer_roster: Vec::new(),
23915                judge_roster: Vec::new(),
23916                reviewer_roster: Vec::new(),
23917            },
23918            sem: Arc::new(Semaphore::new(1)),
23919            pause: Pause::new(),
23920            interrupt: Pause::new(),
23921        };
23922
23923        // The lease is still held throughout, so this reentry's own retry is
23924        // also contended — proving `review_loop` actually tried again (not
23925        // that it happened to succeed) is what the timestamp comparison
23926        // below is for.
23927        runner.review_loop().await.expect("review_loop");
23928
23929        assert_eq!(
23930            runner.state.reviews.len(),
23931            1,
23932            "no new round was started on top of the unresolved one: {:?}",
23933            runner.state.reviews
23934        );
23935        let last = &runner.state.reviews[0];
23936        assert_eq!(
23937            last.e2e_status(),
23938            E2eStatus::ResourceBlocked,
23939            "still contended: {last:?}"
23940        );
23941        assert!(
23942            last.verified_at.expect("still known") > first_attempt_at,
23943            "review_loop must have actually retried the check, not left it exactly as found"
23944        );
23945        assert_ne!(
23946            runner.state.status,
23947            RunStatus::Blocked,
23948            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
23949            runner.state.status
23950        );
23951
23952        held.release();
23953    }
23954
23955    #[tokio::test]
23956    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
23957        crate::run::pin_test_home();
23958        for status in [RunStatus::Blocked, RunStatus::Gating] {
23959            let mut runner = runner_at(status);
23960            runner.state.config.graph.land = true;
23961            runner.state.gate_ran = true;
23962            runner.state.merge = Some(MergeOutcome {
23963                mode: MergeMode::Pr,
23964                ok: false,
23965                detail: "the fixer produced no commit".into(),
23966                empty: false,
23967            });
23968            let url = "https://example.invalid/o/r/pull/1";
23969            runner.state.pr = Some(crate::run::PrRecord {
23970                url: url.into(),
23971                number: 1,
23972                state: "open".into(),
23973                checks: "red".into(),
23974                round: 1,
23975                rounds: 1,
23976                red_at_merge: Vec::new(),
23977            });
23978            runner.state.save().unwrap();
23979            // The nonexistent repository makes observation fail before a forge
23980            // command can run. We still must reach land, rather than silently
23981            // return from the graph with its old gate and merge records.
23982            runner.execute_graph().await.unwrap();
23983            assert_eq!(runner.state.status, RunStatus::Blocked);
23984            assert!(runner.state.land_sync_pending);
23985            assert!(runner.state.events.iter().any(|event|
23986                event.node == "land" && event.message == format!("watching {url}")));
23987            assert_eq!(
23988                runner.state.merge.as_ref().unwrap().detail,
23989                "the fixer produced no commit"
23990            );
23991        }
23992    }
23993
23994    #[tokio::test]
23995    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
23996        crate::run::pin_test_home();
23997        let tmp = tempfile::tempdir().expect("tempdir");
23998        let repo = tmp.path().join("repo");
23999        std::fs::create_dir_all(&repo).unwrap();
24000        init_repo(&repo);
24001
24002        let mut config = Config::default();
24003        config.merge.mode = MergeMode::Pr;
24004        config.graph.land = true;
24005        config.graph.land_approval = false;
24006
24007        let mut state = RunState::new(
24008            repo.clone(),
24009            "main".to_owned(),
24010            "deadbeef".to_owned(),
24011            "task".to_owned(),
24012            config,
24013        );
24014        state.candidates = vec![Candidate {
24015            index: 0,
24016            label: 'A',
24017            agent: "alpha".to_owned(),
24018            branch: "does-not-exist".to_owned(),
24019            worktree: repo.clone(),
24020            summary: String::new(),
24021            stat: String::new(),
24022            files: 0,
24023            commits: 0,
24024            empty: false,
24025            failed: None,
24026            verified_noop: None,
24027            duration_ms: 0,
24028            folded: false,
24029        }];
24030        state.tally = Some(Tally {
24031            first_choice: BTreeMap::from([('A', 1)]),
24032            borda: BTreeMap::new(),
24033            winner: 'A',
24034            rankings: 1,
24035            unanimous_initial: true,
24036            deliberated: false,
24037            changed_votes: 0,
24038            unanimous_final: true,
24039            tie_break: None,
24040            judges: 0,
24041            present: 0,
24042            quorum: 0,
24043            met_quorum: true,
24044            uncontested: Some("only candidate A produced a change".to_owned()),
24045        });
24046        state.reviews = vec![ReviewRound {
24047            round: 1,
24048            head: "deadbeef".to_owned(),
24049            verified_head: None,
24050            verified_at: None,
24051            reviews: Vec::new(),
24052            e2e: Vec::new(),
24053            fix: None,
24054            blocking: 0,
24055            answered: 0,
24056            expected: 0,
24057            clean: true,
24058            verify_retried: false,
24059            e2e_deferred: false,
24060            e2e_defer_reason: None,
24061            progressed: false,
24062            vote_split: false,
24063            reconsideration: Vec::new(),
24064            verdict: None,
24065        }];
24066        state.gate = vec![CommandOutcome {
24067            command: "test".to_owned(),
24068            code: Some(0),
24069            output_tail: String::new(),
24070            duration_ms: 0,
24071            resource_blocked: false,
24072            ..Default::default()
24073        }];
24074        state.gate_ran = true;
24075        // A first pass through `merge` already pushed and opened this pull
24076        // request; `status` is `Landing` because a previous call into `land`
24077        // parked or was interrupted before it reached a terminal outcome.
24078        state.status = RunStatus::Landing;
24079        state.merge = Some(MergeOutcome {
24080            mode: MergeMode::Pr,
24081            ok: true,
24082            detail: "https://example.invalid/x/y/pull/1".to_owned(),
24083            empty: false,
24084        });
24085
24086        // The Landing-resume shortcut calls `run_land` directly rather than
24087        // through `merge`, which is exactly the call site that used to skip
24088        // `settle_questions` - see the fixture below.
24089        ask_test_home();
24090        // A real resume loads a persisted run; driver ownership is checked
24091        // against that record before the Landing shortcut is entered.
24092        state.save().expect("save landing run");
24093        let store = ask::Questions::open();
24094        let q = ask_open_question(&store, &state.id);
24095
24096        let mut runner = Runner {
24097            state,
24098            roles: ResolvedRoles {
24099                implementers: Vec::new(),
24100                judges: Vec::new(),
24101                reviewers: Vec::new(),
24102                fixer: None,
24103                conductor: conductor(),
24104                implementer_roster: Vec::new(),
24105                judge_roster: Vec::new(),
24106                reviewer_roster: Vec::new(),
24107            },
24108            sem: Arc::new(Semaphore::new(1)),
24109            pause: Pause::new(),
24110            interrupt: Pause::new(),
24111        };
24112
24113        // `execute`, not `merge` directly: the Landing-resume shortcut lives
24114        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
24115        // exactly because `review_loop` would otherwise clobber the marker
24116        // first.
24117        runner.execute().await.expect("execute");
24118
24119        assert_eq!(
24120            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
24121            Some("https://example.invalid/x/y/pull/1"),
24122            "reentry must not push again or open a second pull request over the \
24123             one `land` is already watching"
24124        );
24125        assert_ne!(
24126            runner.state.status,
24127            RunStatus::Landing,
24128            "land could not actually reach the fake pull request, so it must \
24129             have given up rather than left the run silently parked forever"
24130        );
24131        // `land` could not reach the fake pull request, so it gave up into
24132        // `Blocked` - still resumable, so the question must not have been
24133        // swept just because this branch now also calls `settle_questions`.
24134        assert_eq!(runner.state.status, RunStatus::Blocked);
24135        assert!(
24136            store.get(&q.id).unwrap().status.open(),
24137            "Blocked is still alive; settle_questions must have been a no-op here"
24138        );
24139    }
24140
24141    fn state_with_round(round: ReviewRound) -> RunState {
24142        let mut s = RunState::new(
24143            PathBuf::from("/repo"),
24144            "main".to_owned(),
24145            "abc1234".to_owned(),
24146            "add retries".to_owned(),
24147            Config::default(),
24148        );
24149        s.reviews = vec![round];
24150        s
24151    }
24152
24153    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
24154        crate::verdict::Finding {
24155            id: id.to_owned(),
24156            severity,
24157            file: None,
24158            line: None,
24159            title: title.to_owned(),
24160            detail: String::new(),
24161        }
24162    }
24163
24164    #[test]
24165    fn pr_body_names_open_findings_and_declined_ones() {
24166        let round = ReviewRound {
24167            round: 2,
24168            head: "deadbee".to_owned(),
24169            verified_head: None,
24170            verified_at: None,
24171            reviews: vec![ReviewRecord {
24172                attempts: 0,
24173                reviewer: 1,
24174                agent: "alpha".to_owned(),
24175                summary: String::new(),
24176                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
24177                vote: None,
24178                failed: None,
24179                duration_ms: 0,
24180            }],
24181            e2e: vec![CommandOutcome {
24182                command: "cargo test".to_owned(),
24183                code: Some(0),
24184                output_tail: String::new(),
24185                duration_ms: 0,
24186                resource_blocked: false,
24187                ..Default::default()
24188            }],
24189            verify_retried: false,
24190            e2e_deferred: false,
24191            e2e_defer_reason: None,
24192            fix: Some(FixRecord {
24193                agent: "alpha".to_owned(),
24194                addressed: Vec::new(),
24195                rejected: vec![crate::verdict::Rejection {
24196                    id: "R1-1-1".to_owned(),
24197                    why: "not reachable from any caller".to_owned(),
24198                }],
24199                notes: String::new(),
24200                committed: true,
24201                failed: None,
24202                duration_ms: 0,
24203                continuation: None,
24204            }),
24205            blocking: 0,
24206            answered: 1,
24207            expected: 1,
24208            clean: false,
24209            progressed: true,
24210            vote_split: false,
24211            reconsideration: Vec::new(),
24212            verdict: None,
24213        };
24214        let state = state_with_round(round);
24215        let body = pr_message(&state, 'A').body;
24216
24217        assert!(body.contains("add retries"), "the task must still be there");
24218        assert!(body.contains("R2-1-1"), "{body}");
24219        assert!(!body.contains("unused import"), "{body}");
24220        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
24221        assert!(
24222            !body.contains("not reachable from any caller"),
24223            "the reason it was declined: {body}"
24224        );
24225    }
24226
24227    #[test]
24228    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
24229        let round = ReviewRound {
24230            round: 1,
24231            head: "deadbee".to_owned(),
24232            verified_head: None,
24233            verified_at: None,
24234            reviews: vec![ReviewRecord {
24235                attempts: 0,
24236                reviewer: 1,
24237                agent: "alpha".to_owned(),
24238                summary: String::new(),
24239                findings: Vec::new(),
24240                vote: None,
24241                failed: None,
24242                duration_ms: 0,
24243            }],
24244            e2e: Vec::new(),
24245            verify_retried: false,
24246            e2e_deferred: false,
24247            e2e_defer_reason: None,
24248            fix: None,
24249            blocking: 0,
24250            answered: 1,
24251            expected: 1,
24252            clean: true,
24253            progressed: false,
24254            vote_split: false,
24255            reconsideration: Vec::new(),
24256            verdict: None,
24257        };
24258        let state = state_with_round(round);
24259        let body = pr_message(&state, 'A').body;
24260        assert!(!body.contains("Open review findings"), "{body}");
24261        assert!(!body.contains("Declined"), "{body}");
24262    }
24263
24264    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
24265        let mut state = RunState::new(
24266            PathBuf::from("/repo"),
24267            "main".to_owned(),
24268            "abc1234".to_owned(),
24269            instruction.to_owned(),
24270            Config::default(),
24271        );
24272        // These fixtures test execution flow, independent of host disk capacity.
24273        state.config.disk.min_free_bytes = 0;
24274        state.candidates.push(Candidate {
24275            index: 0,
24276            label: 'A',
24277            agent: "alpha".to_owned(),
24278            branch: "magi/x/A".to_owned(),
24279            worktree: PathBuf::from("/wt"),
24280            summary: summary.to_owned(),
24281            stat: String::new(),
24282            files: 1,
24283            commits: 1,
24284            empty: false,
24285            failed: None,
24286            verified_noop: None,
24287            folded: false,
24288            duration_ms: 0,
24289        });
24290        state
24291    }
24292
24293    fn review_state(subjects: &[&str]) -> RunState {
24294        let mut state = state_with_summary(
24295            "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",
24296            "",
24297        );
24298        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24299        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
24300        state
24301    }
24302
24303    /// A branch rebased onto a main that moved past the recorded
24304    /// `base_commit` is titled from its own first commit, never main's.
24305    #[tokio::test]
24306    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
24307        ask_test_home();
24308        let tmp = tempfile::tempdir().unwrap();
24309        let repo = tmp.path().join("repo");
24310        std::fs::create_dir_all(&repo).unwrap();
24311        init_repo(&repo);
24312        let origin = tmp.path().join("origin.git");
24313        let g = |dir: &Path, args: &[&str]| {
24314            let out = std::process::Command::new("git")
24315                .args(args)
24316                .current_dir(dir)
24317                .quiet()
24318                .output()
24319                .expect("spawn git");
24320            assert!(
24321                out.status.success(),
24322                "git {args:?}: {}",
24323                String::from_utf8_lossy(&out.stderr)
24324            );
24325        };
24326        g(
24327            tmp.path(),
24328            &[
24329                "clone",
24330                "--bare",
24331                "-q",
24332                repo.to_str().unwrap(),
24333                origin.to_str().unwrap(),
24334            ],
24335        );
24336        g(
24337            &repo,
24338            &["remote", "add", "origin", origin.to_str().unwrap()],
24339        );
24340        let c1 = git::rev_parse(&repo, "main").await.unwrap();
24341
24342        // Main moves on; the branch is built on top of the new main.
24343        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
24344        g(&repo, &["add", "-A"]);
24345        g(
24346            &repo,
24347            &["commit", "-q", "-m", "chore(deps): update a crate"],
24348        );
24349        g(&repo, &["push", "-q", "origin", "main"]);
24350        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
24351        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24352        g(&repo, &["add", "-A"]);
24353        g(
24354            &repo,
24355            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
24356        );
24357        g(&repo, &["checkout", "-q", "main"]);
24358
24359        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
24360        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
24361        // Without a readable tracking ref the recorded base's merge base is used.
24362        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
24363        assert_eq!(fallback, c1);
24364
24365        let mut state = review_state(&[
24366            "chore(deps): update a crate",
24367            "fix(daemon): apply a chosen action",
24368        ]);
24369        state.repo = repo.clone();
24370        state.base_branch = "main".to_owned();
24371        state.base_commit = c1;
24372        refresh_reviewed_commits(&mut state, "feat/own").await;
24373        assert_eq!(
24374            state.reviewed_commits,
24375            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
24376        );
24377        assert_eq!(
24378            review_title(&state).as_deref(),
24379            Some("fix(daemon): apply a chosen action")
24380        );
24381        assert_eq!(
24382            leaked_subjects(&state, "feat/own").await,
24383            Some(vec!["chore(deps): update a crate".to_owned()])
24384        );
24385        // A stale tracking ref is still used when the fetch fails, but the
24386        // leak list is withheld.
24387        state.config.merge.remote = "nowhere".to_owned();
24388        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
24389    }
24390
24391    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
24392    /// with `origin/main` one commit behind it, and a summarizing agent that
24393    /// prints whatever `reply` holds.
24394    struct SummaryFixture {
24395        _tmp: tempfile::TempDir,
24396        repo: PathBuf,
24397        reply: PathBuf,
24398        runner: Runner,
24399    }
24400
24401    fn summary_fixture() -> SummaryFixture {
24402        ask_test_home();
24403        let tmp = tempfile::tempdir().unwrap();
24404        let repo = tmp.path().join("repo");
24405        std::fs::create_dir_all(&repo).unwrap();
24406        init_repo(&repo);
24407        let origin = tmp.path().join("origin.git");
24408        let g = |args: &[&str]| {
24409            let out = std::process::Command::new("git")
24410                .args(args)
24411                .current_dir(&repo)
24412                .quiet()
24413                .output()
24414                .expect("spawn git");
24415            assert!(
24416                out.status.success(),
24417                "git {args:?}: {}",
24418                String::from_utf8_lossy(&out.stderr)
24419            );
24420        };
24421        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
24422        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
24423        g(&["push", "-q", "origin", "main"]);
24424        g(&["checkout", "-q", "-b", "feat/own"]);
24425        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24426        g(&["add", "-A"]);
24427        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
24428        let reply = tmp.path().join("reply.txt");
24429        std::fs::write(
24430            &reply,
24431            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
24432        )
24433        .unwrap();
24434        let mut runner = runner_at(RunStatus::Gating);
24435        let mut state = review_state(&["feat(own): add the own file"]);
24436        state.repo = repo.clone();
24437        state.base_branch = "main".to_owned();
24438        state.candidates[0].branch = "feat/own".to_owned();
24439        state.candidates[0].worktree = repo.clone();
24440        let mut author = spec("alpha");
24441        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
24442        author
24443            .env
24444            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
24445        state.config.agents = vec![author];
24446        runner.state = state;
24447        SummaryFixture {
24448            _tmp: tmp,
24449            repo,
24450            reply,
24451            runner,
24452        }
24453    }
24454
24455    async fn posted(f: &mut SummaryFixture) -> PrMessage {
24456        let winner = f.runner.state.candidates[0].clone();
24457        f.runner
24458            .guarded_pr_message(&winner, None, true)
24459            .await
24460            .unwrap()
24461            .expect("an English description never parks")
24462    }
24463
24464    fn clean_round_with_minor_findings() -> ReviewRound {
24465        let mut round = passing_round(2, None);
24466        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
24467        round.reviews = vec![ReviewRecord {
24468            attempts: 0,
24469            reviewer: 1,
24470            agent: "alpha".into(),
24471            summary: "内部レビュー".into(),
24472            findings: vec![
24473                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
24474                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
24475            ],
24476            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
24477            failed: None,
24478            duration_ms: 0,
24479        }];
24480        round
24481    }
24482
24483    #[tokio::test]
24484    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
24485        for review_only in [false, true] {
24486            let mut f = summary_fixture();
24487            if !review_only {
24488                f.runner.state.candidates[0].agent = "alpha".into();
24489            }
24490            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
24491            assert!(f.runner.state.reviews[0].clean);
24492            assert!(f.runner.state.reviews[0].fix.is_none());
24493            assert!(f.runner.state.open_findings().is_empty());
24494            assert_eq!(
24495                crate::pr_outcome::required_finding_ids(&f.runner.state),
24496                ["R2-1-1", "R2-1-2"]
24497            );
24498            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24499            let evidence = crate::pr_outcome::summary_evidence(
24500                &f.runner.state,
24501                crate::pr_outcome::FinalHead::At(&head),
24502            );
24503            assert!(
24504                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
24505            );
24506            // The ordinary reply omits both IDs: no cached description is adopted.
24507            let omitted = posted(&mut f).await;
24508            assert!(omitted.body.contains("No description"));
24509            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
24510            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
24511            assert!(f.runner.state.change_summary.is_none());
24512            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();
24513            let described = posted(&mut f).await;
24514            assert!(described.body.contains("improve documentation for callers"));
24515            assert!(described.body.contains("remaining edge case"));
24516            assert!(described.body.contains("## Open review findings"));
24517            assert!(!described.body.contains("未修正"));
24518        }
24519    }
24520
24521    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
24522        let mut f = summary_fixture();
24523        if !review_only {
24524            f.runner.state.candidates[0].agent = "alpha".into();
24525        }
24526        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24527        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
24528        fixed
24529            .fix
24530            .as_mut()
24531            .unwrap()
24532            .rejected
24533            .push(crate::verdict::Rejection {
24534                id: "R1-1-1".into(),
24535                why: "呼び出されないコードのため辞退".into(),
24536            });
24537        let mut clean = clean_round_with_minor_findings();
24538        clean.verified_head = Some(head.clone());
24539        f.runner.state.reviews = vec![fixed, clean];
24540        ok_gate(&mut f.runner.state, Some(&head));
24541        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
24542        f.runner.state.config.agents.push(scripted("beta", reply));
24543        f.runner.state.config.roles.language_judge =
24544            Some(crate::config::AgentChoice::One("beta".into()));
24545        f
24546    }
24547
24548    #[tokio::test]
24549    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
24550        for review_only in [false, true] {
24551            let mut f = rewrite_fixture_with_findings(review_only,
24552                "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;
24553            let m = posted(&mut f).await;
24554            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24555            let expected =
24556                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
24557            assert!(m.body.contains(&expected));
24558            assert!(m.body.contains("## Review rounds"));
24559            assert!(
24560                m.body
24561                    .contains("Gate (`verify.gate`): passed on the final commit")
24562            );
24563            assert!(
24564                m.body
24565                    .contains("Tests (`verify.e2e`): passed on the final commit")
24566            );
24567            let c = f.runner.state.change_summary.as_ref().unwrap();
24568            assert!(
24569                m.body
24570                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
24571            );
24572            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24573            assert!(crate::pr_outcome::covers_required_findings(
24574                &f.runner.state,
24575                &m.body
24576            ));
24577            assert!(m.body.contains("documentation remains incomplete"));
24578            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
24579            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
24580            assert!(f.runner.state.github_text.is_none());
24581        }
24582    }
24583
24584    #[tokio::test]
24585    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
24586        for review_only in [false, true] {
24587            for reply in [
24588                "TITLE: fix: public description\nA short English description.",
24589                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
24590            ] {
24591                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
24592                let winner = f.runner.state.candidates[0].clone();
24593                let posted = f
24594                    .runner
24595                    .guarded_pr_message(&winner, None, true)
24596                    .await
24597                    .unwrap();
24598                assert!(posted.is_none());
24599                assert!(f.runner.state.parked);
24600                let withheld = f.runner.state.github_text.as_ref().unwrap();
24601                assert!(
24602                    withheld.rewrite.is_none(),
24603                    "an incomplete rewrite must not be selectable"
24604                );
24605                let q = ask::Questions::open()
24606                    .get(withheld.question.as_ref().unwrap())
24607                    .unwrap();
24608                assert!(
24609                    !q.choices
24610                        .contains(&crate::github_text::USE_REWRITE.to_owned())
24611                );
24612                assert!(
24613                    q.detail.contains("R1-1-1")
24614                        && q.detail.contains("R2-1-1")
24615                        && q.detail.contains("R2-1-2")
24616                );
24617            }
24618        }
24619    }
24620
24621    #[tokio::test]
24622    async fn japanese_reports_stay_local_in_both_public_run_modes() {
24623        for review_only in [false, true] {
24624            let mut f = summary_fixture();
24625            if !review_only {
24626                f.runner.state.candidates[0].agent = "alpha".into();
24627            }
24628            f.runner.state.instruction = "内部タスクの説明".into();
24629            f.runner.state.candidates[0].summary = "内部の候補報告".into();
24630            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24631            f.runner.state.reviews = vec![
24632                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
24633                round_with_notes(2, Some("二回目の内部修正報告です。")),
24634                passing_round(3, Some(&head)),
24635            ];
24636            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
24637            ok_gate(&mut f.runner.state, Some(&head));
24638            let captured = f.repo.join("public-prompt.txt");
24639            let author = &mut f.runner.state.config.agents[0];
24640            author.command = vec![
24641                "sh".into(),
24642                "-c".into(),
24643                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24644            ];
24645            author.env.insert(
24646                "PROMPT_FILE".into(),
24647                captured.to_string_lossy().into_owned(),
24648            );
24649            let m = posted(&mut f).await;
24650            assert!(m.body.contains("Adds `own.txt`"));
24651            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
24652            assert!(m.body.contains("R1-1-1"));
24653            assert!(
24654                m.body
24655                    .contains("Gate (`verify.gate`): passed on the final commit")
24656            );
24657            assert!(
24658                m.body
24659                    .contains("Tests (`verify.e2e`): passed on the final commit")
24660            );
24661            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24662            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
24663            let prompt = std::fs::read_to_string(captured).unwrap();
24664            assert!(prompt.contains(&format!(
24665                "git diff {} {head}",
24666                f.runner.state.change_summary.as_ref().unwrap().base
24667            )));
24668            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
24669            assert_eq!(
24670                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
24671                "二回目の内部修正報告です。"
24672            );
24673        }
24674    }
24675
24676    #[tokio::test]
24677    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
24678        for review_only in [false, true] {
24679            let mut f = summary_fixture();
24680            if !review_only {
24681                f.runner.state.candidates[0].agent = "alpha".into();
24682            }
24683            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
24684            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
24685            std::fs::write(&f.reply, "no usable description").unwrap();
24686            let failed = posted(&mut f).await;
24687            assert!(
24688                failed
24689                    .body
24690                    .contains("No description of what this change does could be generated")
24691            );
24692            assert!(failed.body.is_ascii());
24693            assert!(f.runner.state.github_text.is_none());
24694            assert!(f.runner.state.change_summary.is_none());
24695            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24696            let evidence = crate::pr_outcome::summary_evidence(
24697                &f.runner.state,
24698                crate::pr_outcome::FinalHead::At(&head),
24699            );
24700            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
24701            assert!(
24702                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
24703                    .exists()
24704            );
24705            f.runner.state =
24706                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
24707            std::fs::write(
24708                &f.reply,
24709                "TITLE: feat(own): add the own file\nAdds the committed own file.",
24710            )
24711            .unwrap();
24712            let retried = posted(&mut f).await;
24713            assert!(retried.body.contains("Adds the committed own file."));
24714            assert_eq!(
24715                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
24716                "日本語の修正報告"
24717            );
24718        }
24719    }
24720
24721    #[tokio::test]
24722    async fn same_head_verification_and_findings_invalidate_public_prose() {
24723        let mut f = summary_fixture();
24724        posted(&mut f).await;
24725        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24726        let original = f
24727            .runner
24728            .state
24729            .change_summary
24730            .as_ref()
24731            .unwrap()
24732            .evidence
24733            .clone();
24734        ok_gate(&mut f.runner.state, Some(&head));
24735        std::fs::write(
24736            &f.reply,
24737            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
24738        )
24739        .unwrap();
24740        let verified = posted(&mut f).await;
24741        assert!(verified.body.contains("now verified"));
24742        assert_ne!(
24743            f.runner.state.change_summary.as_ref().unwrap().evidence,
24744            original
24745        );
24746        let mut round = round_with_notes(1, Some("内部報告"));
24747        round.reviews.push(ReviewRecord {
24748            attempts: 0,
24749            reviewer: 1,
24750            agent: "alpha".into(),
24751            summary: "内部レビュー".into(),
24752            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
24753            vote: None,
24754            failed: None,
24755            duration_ms: 0,
24756        });
24757        round
24758            .fix
24759            .as_mut()
24760            .unwrap()
24761            .rejected
24762            .push(crate::verdict::Rejection {
24763                id: "R1-1-1".into(),
24764                why: "呼び出し元から到達できない".into(),
24765            });
24766        f.runner.state.reviews = vec![round];
24767        // A description omitting the required ID is unusable, even with a title.
24768        let omitted = posted(&mut f).await;
24769        assert!(omitted.body.contains("No description"));
24770        assert!(omitted.body.contains("R1-1-1"));
24771        assert!(!omitted.body.contains("到達"));
24772        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();
24773        let described = posted(&mut f).await;
24774        assert!(described.body.contains("unreachable from callers"));
24775        assert!(described.body.contains("R1-1-1"));
24776        assert!(!described.body.contains("到達"));
24777        let evidence = f
24778            .runner
24779            .state
24780            .change_summary
24781            .as_ref()
24782            .unwrap()
24783            .evidence
24784            .clone();
24785        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24786        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24787        assert!(posted(&mut f).await.body.contains("rationale updated"));
24788        assert_ne!(
24789            f.runner.state.change_summary.as_ref().unwrap().evidence,
24790            evidence
24791        );
24792        // Old serialized summaries have no evidence fingerprint and must regenerate.
24793        f.runner
24794            .state
24795            .change_summary
24796            .as_mut()
24797            .unwrap()
24798            .evidence
24799            .clear();
24800        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24801        assert!(posted(&mut f).await.body.contains("current specification"));
24802    }
24803
24804    #[tokio::test]
24805    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24806        let mut f = summary_fixture();
24807        let m = posted(&mut f).await;
24808        assert_eq!(m.title, "feat(own): add the own file");
24809        assert!(
24810            m.body
24811                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24812            "{}",
24813            m.body
24814        );
24815        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24816        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24817        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24818        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24819        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24820        let kept = f.runner.state.change_summary.as_ref().unwrap();
24821        assert_eq!(
24822            (kept.head.as_str(), kept.base.as_str()),
24823            (head.as_str(), base.as_str())
24824        );
24825        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24826    }
24827
24828    #[tokio::test]
24829    async fn review_only_summary_receives_the_configured_github_language() {
24830        let mut f = summary_fixture();
24831        f.runner.state.config.graph.github_language = "ja".into();
24832        let captured = f.repo.join("summary-prompt.txt");
24833        let author = &mut f.runner.state.config.agents[0];
24834        author.command = vec![
24835            "sh".into(),
24836            "-c".into(),
24837            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24838        ];
24839        author.env.insert(
24840            "PROMPT_FILE".into(),
24841            captured.to_string_lossy().into_owned(),
24842        );
24843        std::fs::write(
24844            &f.reply,
24845            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24846        )
24847        .unwrap();
24848        let m = posted(&mut f).await;
24849        let prompt = std::fs::read_to_string(captured).unwrap();
24850        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24851        assert!(!prompt.contains("in English"));
24852        assert_eq!(m.title, "feat(own): ファイルを追加");
24853        assert!(m.body.contains("own.txt を追加します。"));
24854    }
24855
24856    #[tokio::test]
24857    async fn review_fixes_come_after_the_whole_change_summary() {
24858        let mut f = summary_fixture();
24859        f.runner.state.reviews = vec![
24860            round_with_notes(1, Some("handled the PATH case")),
24861            round_with_notes(2, None),
24862        ];
24863        let m = posted(&mut f).await;
24864        let summary = m.body.find("## Summary").expect("summary");
24865        let fixes = m.body.find("## Review rounds").expect("review rounds");
24866        assert!(summary < fixes, "{}", m.body);
24867        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24868        assert!(m.body.contains("## Final verification"), "{}", m.body);
24869    }
24870
24871    #[tokio::test]
24872    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24873        let mut f = summary_fixture();
24874        let first = posted(&mut f).await;
24875        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24876        // The same head reuses the record: a different reply is not read.
24877        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24878        let again = posted(&mut f).await;
24879        assert_eq!((again.title, again.body), (first.title, first.body));
24880
24881        let g = |args: &[&str]| {
24882            let out = std::process::Command::new("git")
24883                .args(args)
24884                .current_dir(&f.repo)
24885                .quiet()
24886                .output()
24887                .expect("spawn git");
24888            assert!(out.status.success(), "git {args:?}");
24889        };
24890        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24891        g(&["add", "-A"]);
24892        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24893        let second = posted(&mut f).await;
24894        let kept = f.runner.state.change_summary.clone().unwrap();
24895        assert_ne!(kept.head, first_head);
24896        assert!(second.body.contains("Not read yet."), "{}", second.body);
24897        assert!(!second.body.contains("so the first summary is read"));
24898        assert_eq!(second.title, "feat(own): other");
24899    }
24900
24901    #[tokio::test]
24902    async fn an_unavailable_summary_is_stated_and_never_invented() {
24903        let mut f = summary_fixture();
24904        std::fs::write(&f.reply, "no title line here").unwrap();
24905        let m = posted(&mut f).await;
24906        assert!(
24907            m.body
24908                .contains("No description of what this change does could be generated"),
24909            "{}",
24910            m.body
24911        );
24912        assert!(m.body.contains("internal reports remain in local records"));
24913        assert!(f.runner.state.change_summary.is_none());
24914        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24915        // A preview asks nobody and claims nothing.
24916        let winner = f.runner.state.candidates[0].clone();
24917        let preview = f
24918            .runner
24919            .guarded_pr_message(&winner, None, false)
24920            .await
24921            .unwrap()
24922            .unwrap();
24923        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24924    }
24925
24926    #[test]
24927    fn pr_message_review_single_commit_uses_its_subject() {
24928        let state = review_state(&["feat(nats): per-role user"]);
24929        let m = pr_message(&state, 'A');
24930        assert_eq!(m.title, "feat(nats): per-role user");
24931        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24932        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24933    }
24934
24935    #[test]
24936    fn pr_message_review_multi_commit_takes_the_oldest() {
24937        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24938        let m = pr_message(&state, 'A');
24939        assert_eq!(m.title, "feat: the change");
24940        for s in ["feat: the change", "fix: typo", "fix: again"] {
24941            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24942        }
24943    }
24944
24945    #[test]
24946    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
24947        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
24948            let mut state = review_state(&[first, "fix: later fixup"]);
24949            state.candidates[0].branch = "機能/ログイン".to_owned();
24950            let m = pr_message(&state, 'A');
24951            assert!(
24952                m.title.starts_with("chore: land candidate A of run"),
24953                "{}",
24954                m.title
24955            );
24956        }
24957    }
24958
24959    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
24960        BranchFacts {
24961            commits: commits
24962                .iter()
24963                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
24964                .collect(),
24965            stat: stat.to_owned(),
24966        }
24967    }
24968
24969    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
24970        let mut r = review_round(true, 0, 1, 1, true, true);
24971        r.round = round;
24972        r.fix = notes.map(|n| FixRecord {
24973            agent: "fixer".to_owned(),
24974            addressed: Vec::new(),
24975            rejected: Vec::new(),
24976            notes: n.to_owned(),
24977            committed: true,
24978            failed: None,
24979            duration_ms: 0,
24980            continuation: None,
24981        });
24982        r
24983    }
24984
24985    #[test]
24986    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
24987        let state = review_state(&["ignored"]);
24988        let f = facts(
24989            &[
24990                (
24991                    "fix(login): resolve PATH on macOS",
24992                    "Login shells skip rc files.",
24993                ),
24994                ("fix: address review", ""),
24995            ],
24996            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
24997        );
24998        let m = pr_message_with(&state, 'A', Some(&f));
24999        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
25000        assert!(
25001            m.body
25002                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
25003            "{}",
25004            m.body
25005        );
25006        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
25007        assert!(m.body.contains("## Diff stat"), "{}", m.body);
25008        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
25009        for banned in [
25010            "Review the work already",
25011            "no task statement",
25012            "Original task",
25013        ] {
25014            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
25015        }
25016        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
25017    }
25018
25019    #[test]
25020    fn pr_message_review_truncates_a_huge_first_commit_body() {
25021        let state = review_state(&["ignored"]);
25022        let f = facts(
25023            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
25024            "s",
25025        );
25026        let m = pr_message_with(&state, 'A', Some(&f));
25027        assert!(m.body.len() < 30_000, "{}", m.body.len());
25028        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
25029        assert!(
25030            m.body.contains("- ... 1 more commit(s)"),
25031            "{}",
25032            m.body.len()
25033        );
25034        assert!(m.body.ends_with("magi:candidate-a\n"));
25035    }
25036
25037    #[test]
25038    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
25039        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
25040        assert_eq!(m.title, "feat: x");
25041        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
25042        assert!(!m.body.contains("Diff stat"), "{}", m.body);
25043        assert!(!m.body.contains("no task statement"), "{}", m.body);
25044    }
25045
25046    #[test]
25047    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
25048        let mut state = review_state(&["日本語の件名"]);
25049        state.candidates[0].branch = "fix/macos-login-path".to_owned();
25050        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
25051        state.candidates[0].branch = "機能/ログイン".to_owned();
25052        assert!(
25053            pr_message(&state, 'A')
25054                .title
25055                .starts_with("chore: land candidate A")
25056        );
25057    }
25058
25059    #[test]
25060    fn pr_message_review_fixes_survive_a_clean_final_round() {
25061        let mut state = review_state(&["feat: x"]);
25062        state.reviews = vec![
25063            round_with_notes(1, Some("handled the PATH case")),
25064            round_with_notes(2, None),
25065        ];
25066        let body = pr_message(&state, 'A').body;
25067        assert!(
25068            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
25069            "{body}"
25070        );
25071        assert!(body.contains("### Round 1"), "{body}");
25072
25073        state.reviews = vec![
25074            round_with_notes(1, Some("first fix")),
25075            round_with_notes(2, Some("")),
25076            round_with_notes(3, Some("second fix")),
25077            round_with_notes(4, None),
25078        ];
25079        let body = pr_message(&state, 'A').body;
25080        assert!(
25081            body.contains("### Round 1") && !body.contains("first fix"),
25082            "{body}"
25083        );
25084        assert!(
25085            body.contains("### Round 3") && !body.contains("second fix"),
25086            "{body}"
25087        );
25088        assert!(body.contains("### Round 2"), "{body}");
25089    }
25090
25091    const FINAL: &str = "abcdef1234567890";
25092
25093    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
25094        let mut r = round_with_notes(round, None);
25095        r.verified_head = verified.map(str::to_owned);
25096        r
25097    }
25098
25099    fn ok_gate(state: &mut RunState, head: Option<&str>) {
25100        state.gate = vec![CommandOutcome {
25101            command: "gate".to_owned(),
25102            code: Some(0),
25103            output_tail: String::new(),
25104            duration_ms: 0,
25105            resource_blocked: false,
25106            ..Default::default()
25107        }];
25108        state.gate_ran = true;
25109        state.gate_head = head.map(str::to_owned);
25110    }
25111
25112    fn body_at(state: &RunState) -> String {
25113        pr_message_raw(
25114            state,
25115            'A',
25116            None,
25117            crate::pr_outcome::FinalHead::At(FINAL),
25118            ChangeNote::NotAsked,
25119        )
25120        .body
25121    }
25122
25123    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
25124
25125    #[test]
25126    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
25127        let mut state = review_state(&["feat: x"]);
25128        state.reviews = vec![
25129            round_with_notes(1, Some(SANDBOXED)),
25130            passing_round(2, Some(FINAL)),
25131        ];
25132        ok_gate(&mut state, Some(FINAL));
25133        let body = body_at(&state);
25134        assert!(!body.contains("Handled the PATH case."), "{body}");
25135        assert!(!body.contains("could not commit"), "{body}");
25136        assert!(!body.contains("could not run"), "{body}");
25137        assert!(
25138            body.contains("The fix is committed on the branch"),
25139            "{body}"
25140        );
25141        assert!(!body.contains("sandbox"), "{body}");
25142        assert!(
25143            body.contains("Tests (`verify.e2e`): passed on the final commit"),
25144            "{body}"
25145        );
25146        assert!(
25147            body.contains("Gate (`verify.gate`): passed on the final commit"),
25148            "{body}"
25149        );
25150        // The raw report is untouched in the record.
25151        assert!(
25152            state.reviews[0]
25153                .fix
25154                .as_ref()
25155                .unwrap()
25156                .notes
25157                .contains("could not commit")
25158        );
25159    }
25160
25161    #[test]
25162    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
25163        let mut state = review_state(&["feat: x"]);
25164        let mut r1 = round_with_notes(1, Some(SANDBOXED));
25165        r1.fix.as_mut().unwrap().committed = false;
25166        let mut r2 = passing_round(2, Some(FINAL));
25167        r2.e2e[0].code = Some(1);
25168        state.reviews = vec![r1, r2];
25169        let body = body_at(&state);
25170        assert!(!body.contains("could not commit"), "{body}");
25171        assert!(!body.contains("could not run"), "{body}");
25172        assert!(body.contains("This round produced no commit"), "{body}");
25173        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
25174        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
25175        assert!(!body.contains("passed"), "{body}");
25176    }
25177
25178    #[test]
25179    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
25180        let mut state = review_state(&["feat: x"]);
25181        state.reviews = vec![
25182            round_with_notes(1, Some(SANDBOXED)),
25183            passing_round(2, Some("0123456789abcdef")),
25184        ];
25185        ok_gate(&mut state, Some("0123456789abcdef"));
25186        let body = body_at(&state);
25187        assert!(!body.contains("HTTP tests could not run"), "{body}");
25188        // The commit claim is still settled by the structured record.
25189        assert!(!body.contains("could not commit"), "{body}");
25190        assert!(
25191            body.contains("passed on an earlier commit (`0123456`)"),
25192            "{body}"
25193        );
25194        assert!(!body.contains("passed on the final commit"), "{body}");
25195
25196        // A gate recorded before `gate_head` existed is "not recorded".
25197        ok_gate(&mut state, None);
25198        let body = body_at(&state);
25199        assert!(
25200            body.contains("passed on a commit that was not recorded"),
25201            "{body}"
25202        );
25203    }
25204
25205    #[test]
25206    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
25207        let state = state_with_summary(
25208            "add retries to the client",
25209            "TITLE: feat: retries\n\nDid it.",
25210        );
25211        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
25212        assert_eq!(m.title, "feat: retries");
25213        assert!(
25214            m.body.contains("<summary>Original task</summary>"),
25215            "{}",
25216            m.body
25217        );
25218        assert!(!m.body.contains("Commits under review"), "{}", m.body);
25219        assert!(
25220            m.body
25221                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
25222            "{}",
25223            m.body
25224        );
25225    }
25226
25227    #[test]
25228    fn pr_message_review_bounds_a_long_english_subject() {
25229        let long = format!("feat: {}", "word ".repeat(100));
25230        let m = pr_message(&review_state(&[&long]), 'A');
25231        assert!(m.title.starts_with("feat: word"), "{}", m.title);
25232        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25233    }
25234
25235    #[test]
25236    fn pr_message_implementation_run_is_unchanged_by_review_support() {
25237        let state = state_with_summary("add retries\n\ndetails", "- did some things");
25238        let m = pr_message(&state, 'A');
25239        assert_eq!(m.title, "add retries");
25240        assert!(m.body.contains("<summary>Original task</summary>"));
25241        assert!(!m.body.contains("Commits under review"));
25242        assert_eq!(landing_subject_source(&state), state.instruction);
25243    }
25244
25245    #[test]
25246    fn review_run_squash_subject_is_the_change_not_the_prompt() {
25247        let state = review_state(&["feat: the change", "fix: typo"]);
25248        let source = landing_subject_source(&state);
25249        assert_eq!(land::merge_subject("", &source), "feat: the change");
25250        assert_eq!(
25251            land::merge_subject("magi: candidate A (uncommitted work)", &source),
25252            "feat: the change"
25253        );
25254        // An operator's rename still wins.
25255        assert_eq!(
25256            land::merge_subject("feat: renamed by hand", &source),
25257            "feat: renamed by hand"
25258        );
25259        let blank = review_state(&["日本語"]);
25260        assert!(
25261            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
25262        );
25263    }
25264
25265    #[test]
25266    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
25267        let state = review_state(&["feat: the change"]);
25268        let source = landing_subject_source(&state);
25269        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
25270        assert_eq!(
25271            land::merge_subject(landing_title(&state, old), &source),
25272            "feat: the change"
25273        );
25274        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
25275        let task = state_with_summary("add retries", "");
25276        assert_eq!(landing_title(&task, old), old);
25277    }
25278
25279    #[test]
25280    fn pr_message_describes_the_change_not_the_task() {
25281        let state = state_with_summary(
25282            "今回やってほしいこと: results projector を直す",
25283            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
25284        );
25285        let m = pr_message(&state, 'A');
25286        assert_eq!(m.title, "fix(web): batch the runs list reads");
25287        assert!(
25288            m.body.starts_with("## Summary\n\n- reads run.json once"),
25289            "{}",
25290            m.body
25291        );
25292        assert!(!m.body.contains("TITLE:"), "{}", m.body);
25293        let task_at = m.body.find("今回やってほしいこと").unwrap();
25294        let details_at = m.body.find("<details>").unwrap();
25295        assert!(
25296            details_at < task_at,
25297            "the task lives inside <details>: {}",
25298            m.body
25299        );
25300        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
25301        assert!(m.body.contains("magi:candidate-a"));
25302    }
25303
25304    #[test]
25305    fn pr_message_falls_back_to_the_task_without_a_title_line() {
25306        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
25307        let m = pr_message(&state, 'A');
25308        assert_eq!(m.title, "add retries");
25309        assert!(
25310            m.body.contains("## Summary\n\n- did some things"),
25311            "{}",
25312            m.body
25313        );
25314
25315        let none = RunState::new(
25316            PathBuf::from("/repo"),
25317            "main".to_owned(),
25318            "abc1234".to_owned(),
25319            "add retries".to_owned(),
25320            Config::default(),
25321        );
25322        let m = pr_message(&none, 'A');
25323        assert_eq!(m.title, "add retries");
25324        assert!(!m.body.contains("## Summary"), "{}", m.body);
25325    }
25326
25327    #[test]
25328    fn pr_message_refuses_the_candidate_commit_subject() {
25329        for bad in [
25330            "TITLE: magi: candidate A (uncommitted work)",
25331            "TITLE: chore: stuff (uncommitted work)",
25332            "TITLE:   ",
25333        ] {
25334            let state = state_with_summary("add retries", bad);
25335            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
25336        }
25337    }
25338
25339    #[test]
25340    fn pr_message_bounds_a_very_long_task_and_title() {
25341        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
25342        let state = state_with_summary(&long, "- nothing");
25343        let m = pr_message(&state, 'A');
25344        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25345        assert!(!m.title.contains('\n'));
25346
25347        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
25348        let m = pr_message(&state, 'A');
25349        assert!(m.title.starts_with("feat: "));
25350        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25351        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
25352    }
25353
25354    fn long_title_of(instruction: &str) -> String {
25355        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
25356    }
25357
25358    #[test]
25359    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
25360        let first = "Make the landing path keep a readable title for long tasks";
25361        let line = format!(
25362            "{first}. {}",
25363            "And then keep going with more words ".repeat(20)
25364        );
25365        let t = long_title_of(&line);
25366        assert_eq!(t, first);
25367        assert!(!t.starts_with("chore: land"));
25368    }
25369
25370    #[test]
25371    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
25372        let line = "word ".repeat(200);
25373        let t = long_title_of(&line);
25374        assert!(t.ends_with("word..."), "{t}");
25375        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
25376    }
25377
25378    #[test]
25379    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
25380        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
25381            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
25382        }
25383    }
25384
25385    #[test]
25386    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
25387        let mut state = state_with_summary("再試行を追加する", "- nothing");
25388        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
25389        state.config.graph.github_language = "ja".into();
25390        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
25391    }
25392
25393    #[test]
25394    fn pr_message_title_limit_is_exact() {
25395        let at = "a".repeat(PR_TITLE_MAX);
25396        assert_eq!(long_title_of(&at), at);
25397        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
25398        assert!(over.ends_with("..."), "{over}");
25399        assert_eq!(over.chars().count(), PR_TITLE_MAX);
25400    }
25401
25402    #[test]
25403    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
25404        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
25405        let t = long_title_of(&line);
25406        assert!(t.ends_with("..."), "{t}");
25407        assert!(t.is_ascii(), "{t}");
25408    }
25409
25410    #[test]
25411    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
25412        let line = format!(
25413            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
25414            "plus more filler words ".repeat(20)
25415        );
25416        let t = long_title_of(&line);
25417        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
25418    }
25419
25420    #[test]
25421    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
25422        let line = format!("\n\n# {}", "title words ".repeat(40));
25423        let state = state_with_summary(&line, "- nothing");
25424        let m = pr_message(&state, 'A');
25425        assert!(m.title.starts_with("title words"), "{}", m.title);
25426        assert_eq!(
25427            land::merge_subject(&m.title, &landing_subject_source(&state)),
25428            m.title
25429        );
25430        // An operator's rename wins untouched.
25431        assert_eq!(
25432            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
25433            "feat: renamed by hand"
25434        );
25435    }
25436
25437    #[tokio::test]
25438    async fn github_text_rewrite_is_bounded_and_falls_back() {
25439        crate::run::pin_test_home();
25440        for (reply, accepted) in [
25441            (
25442                "TITLE: fix: retries\nAdd retries for failed requests.",
25443                true,
25444            ),
25445            (
25446                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
25447                false,
25448            ),
25449            (
25450                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
25451                true,
25452            ),
25453            (
25454                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
25455                true,
25456            ),
25457            (
25458                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
25459                true,
25460            ),
25461            (
25462                "TITLE: fix: retries\n日本語の説明です。 token=secret",
25463                false,
25464            ),
25465            ("TITLE: fix: retries\n", false),
25466        ] {
25467            let dir = tempfile::tempdir().unwrap();
25468            let mut runner = runner_at(RunStatus::Gating);
25469            runner.state = state_with_summary(
25470                "add retries",
25471                "TITLE: fix: retries\n日本語の説明を書きます。",
25472            );
25473            runner.state.repo = dir.path().to_owned();
25474            runner.state.candidates[0].worktree = dir.path().to_owned();
25475            let mut author = spec("alpha");
25476            author.command = vec![
25477                "sh".into(),
25478                "-c".into(),
25479                "printf '%s' \"$REWRITE_REPLY\"".into(),
25480            ];
25481            author.env.insert("REWRITE_REPLY".into(), reply.into());
25482            runner.state.config.agents = vec![author];
25483            seed_public_summary(&mut runner);
25484            let winner = runner.state.candidates[0].clone();
25485            let first = runner
25486                .guarded_pr_message(&winner, None, true)
25487                .await
25488                .unwrap();
25489            let message = if accepted {
25490                first.expect("a passing rewrite never asks")
25491            } else {
25492                // Withheld: the run parks on a question and posts nothing yet.
25493                assert!(first.is_none());
25494                assert!(runner.state.parked);
25495                let store = ask::Questions::open();
25496                let asked: Vec<_> = store
25497                    .list()
25498                    .into_iter()
25499                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25500                    .collect();
25501                assert_eq!(asked.len(), 1);
25502                assert!(!asked[0].detail.contains("secret"));
25503                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
25504                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
25505                assert_eq!(
25506                    asked[0]
25507                        .choices
25508                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
25509                    rewrite.is_some()
25510                );
25511                // Silence: the question lapses and the neutral text is used,
25512                // without a second rewrite call or a second question.
25513                store
25514                    .update(&asked[0].id, |q| {
25515                        q.abandon("test");
25516                        Ok(())
25517                    })
25518                    .unwrap();
25519                let again = runner
25520                    .guarded_pr_message(&winner, None, true)
25521                    .await
25522                    .unwrap()
25523                    .expect("an abandoned question falls back");
25524                let n = store
25525                    .list()
25526                    .into_iter()
25527                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25528                    .count();
25529                assert_eq!(n, 1, "asked once per rejected text");
25530                again
25531            };
25532            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
25533            assert!(!message.body.contains("secret"));
25534            assert!(!message.body.contains("prefix"));
25535            assert!(!message.title.contains("secret"));
25536            assert_eq!(
25537                message.body.contains("Add retries for failed requests."),
25538                accepted
25539            );
25540            assert_eq!(
25541                runner.state.seats["github-text-rewrite"].turns, 1,
25542                "only one rewrite invocation"
25543            );
25544            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
25545            if accepted {
25546                assert!(runner.state.github_text.is_none());
25547                assert!(!runner.state.parked);
25548                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
25549                assert!(message.body.contains("## Final verification"));
25550                assert!(message.body.contains("Evidence: final diff"));
25551                assert!(
25552                    message
25553                        .body
25554                        .contains(&format!("magi:run/{}", runner.state.id))
25555                );
25556            }
25557            if !accepted {
25558                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25559                assert!(
25560                    message
25561                        .body
25562                        .contains(&format!("magi:run/{}", runner.state.id))
25563                );
25564            }
25565        }
25566    }
25567
25568    fn scripted(id: &str, reply: &str) -> AgentSpec {
25569        let mut a = spec(id);
25570        a.command = vec![
25571            "sh".into(),
25572            "-c".into(),
25573            "printf '%s' \"$REWRITE_REPLY\"".into(),
25574        ];
25575        a.env.insert("REWRITE_REPLY".into(), reply.into());
25576        a
25577    }
25578
25579    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
25580    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
25581
25582    /// Gate tests inject generated public output, not internal reports.
25583    fn seed_public_summary(runner: &mut Runner) {
25584        let repo = &runner.state.repo;
25585        let g = |args: &[&str]| {
25586            let out = std::process::Command::new("git")
25587                .args(args)
25588                .current_dir(repo)
25589                .quiet()
25590                .output()
25591                .unwrap();
25592            assert!(out.status.success(), "git {args:?}");
25593            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25594        };
25595        g(&["init", "-q", "-b", "main"]);
25596        g(&[
25597            "-c",
25598            "user.name=Test",
25599            "-c",
25600            "user.email=test@example.invalid",
25601            "commit",
25602            "-q",
25603            "--allow-empty",
25604            "-m",
25605            "feat: fixture",
25606        ]);
25607        let head = g(&["rev-parse", "HEAD"]);
25608        g(&["update-ref", "refs/remotes/origin/main", &head]);
25609        let evidence = crate::pr_outcome::summary_evidence(
25610            &runner.state,
25611            crate::pr_outcome::FinalHead::At(&head),
25612        );
25613        let generated = &runner.state.candidates[0].summary;
25614        runner.state.change_summary = Some(crate::run::ChangeSummary {
25615            base: head.clone(),
25616            head,
25617            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
25618            title: summary_title(generated).unwrap(),
25619            body: summary_without_title(generated),
25620        });
25621    }
25622
25623    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
25624        let mut runner = runner_at(RunStatus::Gating);
25625        runner.state = state_with_summary("add retries", JA_SUMMARY);
25626        if review_only {
25627            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
25628        }
25629        runner.state.repo = dir.to_owned();
25630        runner.state.candidates[0].worktree = dir.to_owned();
25631        runner.state.config.agents = agents;
25632        seed_public_summary(&mut runner);
25633        runner
25634    }
25635
25636    fn gate_questions(runner: &Runner) -> usize {
25637        ask::Questions::open()
25638            .list()
25639            .into_iter()
25640            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25641            .count()
25642    }
25643
25644    #[tokio::test]
25645    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
25646        crate::run::pin_test_home();
25647        let dir = tempfile::tempdir().unwrap();
25648        let mut runner = rewrite_runner(
25649            dir.path(),
25650            true,
25651            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25652        );
25653        runner.state.config.roles.language_judge =
25654            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
25655        let winner = runner.state.candidates[0].clone();
25656        let msg = runner
25657            .guarded_pr_message(&winner, None, true)
25658            .await
25659            .unwrap()
25660            .expect("an English rewrite posts without asking");
25661        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
25662        assert!(msg.body.contains("<details>kept</details>"));
25663        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
25664        assert_eq!(gate_questions(&runner), 0);
25665        assert!(runner.state.github_text.is_none());
25666        assert!(!runner.state.seats.contains_key("impl-A"));
25667        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25668    }
25669
25670    #[tokio::test]
25671    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
25672        crate::run::pin_test_home();
25673        let dir = tempfile::tempdir().unwrap();
25674        let mut runner = rewrite_runner(
25675            dir.path(),
25676            false,
25677            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25678        );
25679        runner.state.config.roles.language_judge =
25680            Some(crate::config::AgentChoice::One("beta".into()));
25681        runner.state.seats.insert(
25682            "impl-A".into(),
25683            SeatState::new("impl-A", "alpha", runner.state.seed),
25684        );
25685        let winner = runner.state.candidates[0].clone();
25686        let msg = runner
25687            .guarded_pr_message(&winner, None, true)
25688            .await
25689            .unwrap()
25690            .expect("rewritten");
25691        assert!(msg.body.contains("<details>kept</details>"));
25692        assert_eq!(runner.state.seats["impl-A"].turns, 0);
25693        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25694        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25695    }
25696
25697    #[tokio::test]
25698    async fn rewrite_reuses_a_resumable_implementer_session() {
25699        crate::run::pin_test_home();
25700        let dir = tempfile::tempdir().unwrap();
25701        let mut runner = rewrite_runner(
25702            dir.path(),
25703            false,
25704            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
25705        );
25706        runner.state.config.roles.language_judge =
25707            Some(crate::config::AgentChoice::One("beta".into()));
25708        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25709        seat.turns = 1;
25710        runner.state.seats.insert("impl-A".into(), seat);
25711        let winner = runner.state.candidates[0].clone();
25712        runner
25713            .guarded_pr_message(&winner, None, true)
25714            .await
25715            .unwrap()
25716            .expect("rewritten");
25717        assert_eq!(runner.state.seats["impl-A"].turns, 2);
25718        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
25719    }
25720
25721    #[tokio::test]
25722    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
25723        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
25724        // session, was out of quota, and nothing else was asked.
25725        crate::run::pin_test_home();
25726        let dir = tempfile::tempdir().unwrap();
25727        let mut exhausted = spec("alpha");
25728        exhausted.command = vec!["false".into()];
25729        let mut runner = rewrite_runner(
25730            dir.path(),
25731            false,
25732            vec![exhausted, scripted("beta", EN_REWRITE)],
25733        );
25734        // The implementer's own agent is in the role too: it is not asked twice.
25735        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25736            "alpha".into(),
25737            "beta".into(),
25738        ]));
25739        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25740        seat.turns = 1;
25741        runner.state.seats.insert("impl-A".into(), seat);
25742        let winner = runner.state.candidates[0].clone();
25743        let msg = runner
25744            .guarded_pr_message(&winner, None, true)
25745            .await
25746            .unwrap()
25747            .expect("the role rewrites after the implementer fails");
25748        assert!(msg.body.contains("`src/net.rs`"));
25749        assert_eq!(
25750            runner.state.seats["impl-A"].turns, 2,
25751            "the implementer was tried once"
25752        );
25753        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25754        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25755    }
25756
25757    #[tokio::test]
25758    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
25759        crate::run::pin_test_home();
25760        let dir = tempfile::tempdir().unwrap();
25761        let mut broken = spec("bad");
25762        broken.command = vec!["false".into()];
25763        let mut runner = rewrite_runner(
25764            dir.path(),
25765            true,
25766            vec![
25767                broken,
25768                scripted("noformat", "Add retries."),
25769                scripted("good", EN_REWRITE),
25770            ],
25771        );
25772        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25773            "bad".into(),
25774            "noformat".into(),
25775            "good".into(),
25776        ]));
25777        let winner = runner.state.candidates[0].clone();
25778        let msg = runner
25779            .guarded_pr_message(&winner, None, true)
25780            .await
25781            .unwrap()
25782            .expect("the third agent rewrites");
25783        assert!(msg.body.contains("`src/net.rs`"));
25784        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25785        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25786    }
25787
25788    #[tokio::test]
25789    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25790        crate::run::pin_test_home();
25791        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25792        for (agents, role, saved) in [
25793            (
25794                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25795                Some("beta"),
25796                true,
25797            ),
25798            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25799            (Vec::new(), None, false),
25800        ] {
25801            let dir = tempfile::tempdir().unwrap();
25802            let mut runner = rewrite_runner(dir.path(), true, agents);
25803            runner.state.config.roles.language_judge =
25804                role.map(|r| crate::config::AgentChoice::One(r.into()));
25805            let winner = runner.state.candidates[0].clone();
25806            let first = runner
25807                .guarded_pr_message(&winner, None, true)
25808                .await
25809                .unwrap();
25810            assert!(first.is_none(), "withheld text parks the run");
25811            assert!(runner.state.parked);
25812            assert_eq!(gate_questions(&runner), 1);
25813            let g = runner.state.github_text.as_ref().unwrap();
25814            assert_eq!(g.rewrite.is_some(), saved);
25815            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25816        }
25817    }
25818
25819    #[tokio::test]
25820    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25821        crate::run::pin_test_home();
25822        let dir = tempfile::tempdir().unwrap();
25823        let mut runner = runner_at(RunStatus::Gating);
25824        runner.state =
25825            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25826        runner.state.repo = dir.path().to_owned();
25827        runner.state.candidates[0].worktree = dir.path().to_owned();
25828        let mut author = spec("alpha");
25829        author.command = vec![
25830            "sh".into(),
25831            "-c".into(),
25832            "printf '%s' \"$REWRITE_REPLY\"".into(),
25833        ];
25834        author.env.insert(
25835            "REWRITE_REPLY".into(),
25836            format!(
25837                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25838                "English sentence. ".repeat(600)
25839            ),
25840        );
25841        runner.state.config.agents = vec![author];
25842        seed_public_summary(&mut runner);
25843        let winner = runner.state.candidates[0].clone();
25844        assert!(
25845            runner
25846                .guarded_pr_message(&winner, None, true)
25847                .await
25848                .unwrap()
25849                .is_none()
25850        );
25851        let record = runner.state.github_text.clone().unwrap();
25852        let rewrite = record.rewrite.clone().unwrap();
25853        assert_eq!(rewrite.failed, ["body-language"]);
25854        assert!(
25855            rewrite
25856                .body
25857                .ends_with(&format!("magi:run/{}", runner.state.id))
25858        );
25859        let store = ask::Questions::open();
25860        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25861        assert!(
25862            q.choices
25863                .contains(&crate::github_text::USE_REWRITE.to_owned())
25864        );
25865        for label in [
25866            "ORIGINAL",
25867            "FALLBACK",
25868            "REWRITE",
25869            "Rules still failed: body-language",
25870            "truncated",
25871        ] {
25872            assert!(q.detail.contains(label), "{label}");
25873        }
25874        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25875            &runner.state,
25876            &crate::github_text::artifact_name(&record.fingerprint),
25877        ))
25878        .unwrap();
25879        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25880        // Restart from serialized state, then retry after a bad owner title.
25881        runner.state =
25882            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25883        store
25884            .update(&q.id, |q| {
25885                q.say("まだ日本語")?;
25886                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25887            })
25888            .unwrap();
25889        assert!(
25890            runner
25891                .guarded_pr_message(&winner, None, true)
25892                .await
25893                .unwrap()
25894                .is_none()
25895        );
25896        let retry = runner.state.github_text.as_ref().unwrap();
25897        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25898        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25899        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25900        assert!(
25901            q.posting_comparison
25902                .as_ref()
25903                .unwrap()
25904                .matches_detail(&q.detail)
25905        );
25906        store
25907            .update(&q.id, |q| {
25908                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25909            })
25910            .unwrap();
25911        let message = runner
25912            .guarded_pr_message(&winner, None, true)
25913            .await
25914            .unwrap()
25915            .unwrap();
25916        assert_eq!(message.title, rewrite.title);
25917        assert_eq!(message.body, rewrite.body);
25918        assert_eq!(
25919            runner.state.github_text.as_ref().unwrap().choice,
25920            Some(GithubTextChoice::Rewrite)
25921        );
25922        let again = runner
25923            .guarded_pr_message(&winner, None, true)
25924            .await
25925            .unwrap()
25926            .unwrap();
25927        assert_eq!(again.title, message.title);
25928        assert_eq!(again.body, message.body);
25929        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25930        assert!(
25931            !runner
25932                .state
25933                .events
25934                .iter()
25935                .any(|e| e.message.contains(&rewrite.title)
25936                    || e.message.contains("English sentence."))
25937        );
25938    }
25939
25940    #[tokio::test]
25941    async fn historical_posting_reply_never_expires_into_fallback() {
25942        crate::run::pin_test_home();
25943        let dir = tempfile::tempdir().unwrap();
25944        let mut runner = runner_at(RunStatus::Gating);
25945        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25946        runner.state.repo = dir.path().to_owned();
25947        runner.state.candidates[0].worktree = dir.path().to_owned();
25948        seed_public_summary(&mut runner);
25949        let winner = runner.state.candidates[0].clone();
25950        assert!(
25951            runner
25952                .guarded_pr_message(&winner, None, true)
25953                .await
25954                .unwrap()
25955                .is_none()
25956        );
25957        let id = runner
25958            .state
25959            .github_text
25960            .as_ref()
25961            .unwrap()
25962            .question
25963            .clone()
25964            .unwrap();
25965        let store = ask::Questions::open();
25966        let mut q = store.get(&id).unwrap();
25967        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
25968        q.answer(ask::Answer::Choice(
25969            crate::github_text::POST_ORIGINAL.into(),
25970        ))
25971        .unwrap();
25972        q.answer_delivered = true;
25973        store.put(&mut q).unwrap();
25974        let source = std::fs::read(store.path_of(&id)).unwrap();
25975        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
25976        std::fs::create_dir_all(&migration).unwrap();
25977        std::fs::write(
25978            migration.join("state.json"),
25979            serde_json::to_vec(&serde_json::json!({
25980                "schema": 1, "sources": [id], "pending": [id]
25981            }))
25982            .unwrap(),
25983        )
25984        .unwrap();
25985        for _ in 0..2 {
25986            assert!(
25987                runner
25988                    .guarded_pr_message(&winner, None, true)
25989                    .await
25990                    .unwrap()
25991                    .is_none()
25992            );
25993            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25994            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25995        }
25996        let home = crate::run::home();
25997        crate::task_chat::sweep(
25998            &crate::queue::Queue::at(home.join("queue")),
25999            &crate::talk::Talks::at(home.join("talks")),
26000            &store,
26001            &home,
26002        );
26003        let outbox = crate::task_inquiry::Outbox::at(&home);
26004        outbox
26005            .update_decision(&id, |d| {
26006                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
26007                d.source_answer_at = q.answered_at;
26008                Ok(true)
26009            })
26010            .unwrap();
26011        outbox
26012            .settle(
26013                &id,
26014                "owner-chat",
26015                "Owner confirms no publication remains necessary",
26016                None,
26017            )
26018            .unwrap();
26019        assert!(
26020            runner
26021                .guarded_pr_message(&winner, None, true)
26022                .await
26023                .unwrap()
26024                .is_none()
26025        );
26026        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
26027        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
26028    }
26029
26030    #[tokio::test]
26031    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
26032        crate::run::pin_test_home();
26033        let dir = tempfile::tempdir().unwrap();
26034        let mut runner = runner_at(RunStatus::Gating);
26035        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
26036        runner.state.repo = dir.path().to_owned();
26037        runner.state.candidates[0].worktree = dir.path().to_owned();
26038        seed_public_summary(&mut runner);
26039        let winner = runner.state.candidates[0].clone();
26040        assert!(
26041            runner
26042                .guarded_pr_message(&winner, None, true)
26043                .await
26044                .unwrap()
26045                .is_none()
26046        );
26047        let record = runner.state.github_text.as_ref().unwrap();
26048        assert!(record.rewrite.is_none());
26049        // Records written before the additive field deserialize with no rewrite.
26050        let mut old = serde_json::to_value(record).unwrap();
26051        old.as_object_mut().unwrap().remove("rewrite");
26052        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
26053        assert!(old.rewrite.is_none());
26054        let id = record.question.clone().unwrap();
26055        ask::Questions::open()
26056            .update(&id, |q| {
26057                q.choices.push(crate::github_text::USE_REWRITE.into());
26058                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
26059            })
26060            .unwrap();
26061        let message = runner
26062            .guarded_pr_message(&winner, None, true)
26063            .await
26064            .unwrap()
26065            .unwrap();
26066        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
26067        assert_eq!(
26068            runner.state.github_text.as_ref().unwrap().choice,
26069            Some(GithubTextChoice::Fallback)
26070        );
26071    }
26072
26073    #[tokio::test]
26074    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
26075        crate::run::pin_test_home();
26076        let dir = tempfile::tempdir().unwrap();
26077        let mut runner = runner_at(RunStatus::Gating);
26078        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
26079        runner.state.repo = dir.path().to_owned();
26080        runner.state.candidates[0].worktree = dir.path().to_owned();
26081        seed_public_summary(&mut runner);
26082        let winner = runner.state.candidates[0].clone();
26083        assert!(
26084            runner
26085                .guarded_pr_message(&winner, None, true)
26086                .await
26087                .unwrap()
26088                .is_none()
26089        );
26090        let store = ask::Questions::open();
26091        let find = |run: &str| {
26092            store
26093                .list()
26094                .into_iter()
26095                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
26096                .unwrap()
26097        };
26098        let run = runner.state.id.clone();
26099        let q = find(&run);
26100        let fp = runner
26101            .state
26102            .github_text
26103            .as_ref()
26104            .unwrap()
26105            .fingerprint
26106            .clone();
26107        let name = crate::github_text::artifact_name(&fp);
26108        let path = crate::run::artifact_path(&runner.state, &name);
26109        assert!(q.detail.contains(&path.display().to_string()));
26110        assert!(q.detail.contains("title-language: title"));
26111        let saved = std::fs::read_to_string(&path).expect("artifact written");
26112        assert!(saved.contains("日本語のタイトル"));
26113        assert!(q.cwd.is_none());
26114        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
26115        // A bad replacement is refused and asked about once more.
26116        let say = |id: &str, text: &str, choice: &str| {
26117            store
26118                .update(id, |q| {
26119                    q.thread.push(ask::Turn {
26120                        who: ask::Who::Operator,
26121                        body: text.to_owned(),
26122                        at: jiff::Timestamp::now(),
26123                        note: None,
26124                    });
26125                    q.answer(ask::Answer::Choice(choice.to_owned()))
26126                })
26127                .unwrap();
26128        };
26129        say(&q.id, "まだ日本語", "use my text");
26130        assert!(
26131            runner
26132                .guarded_pr_message(&winner, None, true)
26133                .await
26134                .unwrap()
26135                .is_none()
26136        );
26137        let second = find(&run);
26138        assert_ne!(second.id, q.id);
26139        assert!(second.detail.contains("did not pass"));
26140        // The retry still compares the original text; the rejected
26141        // replacement is named by category only.
26142        assert!(second.detail.contains("日本語のタイトル"));
26143        assert!(!second.detail.contains("まだ日本語"));
26144        assert!(second.detail.contains(&path.display().to_string()));
26145        say(&second.id, "fix: retry failed requests", "use my text");
26146        let message = runner
26147            .guarded_pr_message(&winner, None, true)
26148            .await
26149            .unwrap()
26150            .expect("a vetted replacement is posted");
26151        assert_eq!(message.title, "fix: retry failed requests");
26152        assert_eq!(
26153            runner
26154                .state
26155                .github_text
26156                .as_ref()
26157                .unwrap()
26158                .chosen_title
26159                .as_deref(),
26160            Some("fix: retry failed requests")
26161        );
26162        assert!(runner.state.github_text.as_ref().unwrap().resolved);
26163        // Resumed again: the saved decision is applied, nothing is re-asked.
26164        let again = runner
26165            .guarded_pr_message(&winner, None, true)
26166            .await
26167            .unwrap()
26168            .unwrap();
26169        assert_eq!(again.title, message.title);
26170        assert_eq!(
26171            store
26172                .list()
26173                .into_iter()
26174                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
26175                .count(),
26176            2
26177        );
26178    }
26179
26180    #[test]
26181    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
26182        // What magi itself writes stays English under any configured language,
26183        // so a future localisation of these headings fails here. (The agents'
26184        // own text is also checked by the posting gate.)
26185        let mut state = state_with_summary(
26186            "add retries",
26187            "TITLE: fix(web): batch reads\n- reads run.json once",
26188        );
26189        state.config.graph.language = "ja".to_owned();
26190        let m = pr_message(&state, 'A');
26191        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
26192        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
26193
26194        // The task is the operator's own text: it goes in untouched, and the
26195        // fallback title (no summary) may be in its language too.
26196        let task = "今回やってほしいこと: results projector を直す";
26197        let mut state = state_with_summary(task, "- no title line");
26198        state.config.graph.language = "ja".to_owned();
26199        let m = pr_message(&state, 'A');
26200        assert_eq!(
26201            m.title,
26202            format!("chore: land candidate A of run {}", state.id)
26203        );
26204        assert!(
26205            m.body.contains(&format!(
26206                "<summary>Original task</summary>\n\n{task}\n\n</details>"
26207            )),
26208            "{}",
26209            m.body
26210        );
26211    }
26212
26213    #[test]
26214    fn pr_message_scrubs_home_paths_and_addresses() {
26215        let state = state_with_summary(
26216            "fix it in /Users/someone/src/x",
26217            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
26218        );
26219        let m = pr_message(&state, 'A');
26220        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
26221            assert!(!m.body.contains(leak), "{}", m.body);
26222        }
26223        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
26224    }
26225
26226    #[test]
26227    fn pr_message_survives_a_task_that_closes_details() {
26228        let state = state_with_summary("a </details> b", "TITLE: fix: x");
26229        let m = pr_message(&state, 'A');
26230        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
26231    }
26232
26233    #[test]
26234    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
26235        let cmd = manual_merge_command(
26236            MergeStyle::Squash,
26237            Path::new("/repo"),
26238            "b",
26239            "fix: \"quoted\" $(x) `y`\n\nbody",
26240        );
26241        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
26242    }
26243
26244    #[test]
26245    fn manual_merge_command_matches_the_configured_style() {
26246        let repo = Path::new("/repo");
26247        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
26248
26249        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
26250        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
26251
26252        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
26253        assert_eq!(
26254            squash,
26255            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
26256             \"Merge magi run 0832 (candidate A)\""
26257        );
26258
26259        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
26260        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
26261    }
26262
26263    #[test]
26264    fn a_nudge_gets_a_quarter_of_the_budget() {
26265        // The judge and implement budgets magi ships with.
26266        assert_eq!(retry_budget(secs(1200), true), secs(300));
26267        assert_eq!(retry_budget(secs(3600), true), secs(900));
26268    }
26269
26270    #[test]
26271    fn a_resent_prompt_keeps_the_whole_budget() {
26272        // The seat kept no context, so the retry is the original job again and
26273        // shortening it would only guarantee a second failure.
26274        assert_eq!(retry_budget(secs(1200), false), secs(1200));
26275        assert_eq!(retry_budget(secs(60), false), secs(60));
26276    }
26277
26278    #[test]
26279    fn the_floor_never_exceeds_the_original_budget() {
26280        // A short configured timeout must not be *raised* by the floor: the
26281        // operator asked for a bound, and a retry may not outlast the attempt
26282        // it is retrying.
26283        assert_eq!(retry_budget(secs(60), true), secs(60));
26284        assert_eq!(retry_budget(secs(480), true), secs(120));
26285        assert_eq!(retry_budget(secs(0), true), secs(0));
26286    }
26287
26288    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
26289        agent::CommandEvidence {
26290            id: "item1".to_owned(),
26291            description: "cargo test".to_owned(),
26292            exit_code,
26293            result_summary: String::new(),
26294            source: "codex".to_owned(),
26295        }
26296    }
26297
26298    #[test]
26299    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
26300        // No evidence is not the same fact as unconfirmed evidence: a
26301        // backend with no adapter, or a reply that ran no commands at all,
26302        // must not be misread as carrying a dangling job.
26303        assert!(!has_unconfirmed_command(&[]));
26304    }
26305
26306    fn reply(tool_calls: Option<u64>) -> AgentOutput {
26307        AgentOutput {
26308            text: "## SUMMARY\nImplementation incomplete.".to_owned(),
26309            exit_code: Some(0),
26310            timed_out: false,
26311            duration_ms: 7_000,
26312            artifacts: Vec::new(),
26313            quota: None,
26314            dropped: None,
26315            commands: Vec::new(),
26316            context_tokens: None,
26317            tool_calls,
26318        }
26319    }
26320
26321    #[test]
26322    fn a_clean_reply_with_no_tool_call_on_an_untouched_tree_is_unstarted() {
26323        assert!(ended_unstarted(
26324            &reply(Some(0)),
26325            Some("abc"),
26326            Some("abc"),
26327            Some(true)
26328        ));
26329    }
26330
26331    #[test]
26332    fn unknown_or_real_tool_activity_is_never_unstarted() {
26333        // A backend that reports no tool calls says nothing about them.
26334        assert!(!ended_unstarted(
26335            &reply(None),
26336            Some("abc"),
26337            Some("abc"),
26338            Some(true)
26339        ));
26340        // A seat that looked and then wrote nothing did start.
26341        assert!(!ended_unstarted(
26342            &reply(Some(3)),
26343            Some("abc"),
26344            Some("abc"),
26345            Some(true)
26346        ));
26347        let mut ran = reply(Some(0));
26348        ran.commands.push(evidence(Some(0)));
26349        assert!(!ended_unstarted(&ran, Some("abc"), Some("abc"), Some(true)));
26350    }
26351
26352    #[test]
26353    fn work_in_the_tree_or_an_unreadable_one_is_never_unstarted() {
26354        let out = reply(Some(0));
26355        // A commit, uncommitted edits, and each unknown: none may be replayed.
26356        assert!(!ended_unstarted(&out, Some("abc"), Some("def"), Some(true)));
26357        assert!(!ended_unstarted(
26358            &out,
26359            Some("abc"),
26360            Some("abc"),
26361            Some(false)
26362        ));
26363        assert!(!ended_unstarted(&out, None, Some("abc"), Some(true)));
26364        assert!(!ended_unstarted(&out, Some("abc"), None, Some(true)));
26365        assert!(!ended_unstarted(&out, Some("abc"), Some("abc"), None));
26366        assert!(!ended_unstarted(&out, None, None, Some(true)));
26367    }
26368
26369    #[test]
26370    fn a_failed_or_empty_turn_is_not_an_unstarted_reply() {
26371        let mut failed = reply(Some(0));
26372        failed.exit_code = Some(1);
26373        assert!(!ended_unstarted(
26374            &failed,
26375            Some("abc"),
26376            Some("abc"),
26377            Some(true)
26378        ));
26379        let mut silent = reply(Some(0));
26380        silent.text = String::new();
26381        assert!(!ended_unstarted(
26382            &silent,
26383            Some("abc"),
26384            Some("abc"),
26385            Some(true)
26386        ));
26387    }
26388
26389    #[test]
26390    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
26391        // Deliberately not a check on the exit code's *value*: a fixer
26392        // legitimately runs something that fails mid-iteration before it
26393        // succeeds, and that must never by itself reopen a valid report.
26394        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
26395        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
26396        assert!(!has_unconfirmed_command(&[
26397            evidence(Some(0)),
26398            evidence(Some(101))
26399        ]));
26400    }
26401
26402    #[test]
26403    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
26404        assert!(has_unconfirmed_command(&[
26405            evidence(Some(0)),
26406            evidence(None)
26407        ]));
26408    }
26409
26410    fn evidence_with(
26411        description: &str,
26412        exit_code: Option<i32>,
26413        result_summary: &str,
26414    ) -> agent::CommandEvidence {
26415        agent::CommandEvidence {
26416            id: "item1".to_owned(),
26417            description: description.to_owned(),
26418            exit_code,
26419            result_summary: result_summary.to_owned(),
26420            source: "codex".to_owned(),
26421        }
26422    }
26423
26424    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
26425        format!(
26426            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":[]}}"#
26427        )
26428    }
26429
26430    #[test]
26431    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
26432        let text = valid_noop_summary("b32cfc4", "retry_test");
26433        let claim = verified_noop_claim(true, &[], &text)
26434            .expect("valid structured report with no CommandEvidence must be accepted");
26435        assert!(claim.contains("b32cfc4"), "{claim}");
26436        assert!(claim.contains("retry_test"), "{claim}");
26437    }
26438
26439    #[test]
26440    fn operational_regression_and_legacy_noop_claims_are_rejected() {
26441        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
26442        assert!(verified_noop_claim(true, &[], regression).is_none());
26443        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
26444        assert!(err.contains("single JSON object"), "{err}");
26445
26446        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
26447        assert!(verified_noop_claim(true, &[], legacy).is_none());
26448    }
26449
26450    #[test]
26451    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
26452        // A timeout or a bad exit code reads as the ordinary loss it is,
26453        // whatever the reply's own structured JSON claims.
26454        let text = valid_noop_summary("b32cfc4", "retry_test");
26455        assert!(verified_noop_claim(false, &[], &text).is_none());
26456    }
26457
26458    #[test]
26459    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
26460        let text = valid_noop_summary("b32cfc4", "retry_test");
26461        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
26462        // A matching confirmed command alongside the marker is fine.
26463        assert!(
26464            verified_noop_claim(
26465                true,
26466                &[evidence_with(
26467                    "cargo test --lib retry_test",
26468                    Some(0),
26469                    "1 passed"
26470                )],
26471                &text
26472            )
26473            .is_some()
26474        );
26475    }
26476
26477    #[test]
26478    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
26479     {
26480        let text = valid_noop_summary("b32cfc4", "retry_test");
26481
26482        // Unrelated passing command cannot substantiate a claimed test run.
26483        let err = evaluate_noop_claim(
26484            true,
26485            &[evidence_with("git status", Some(0), "nothing to commit")],
26486            &text,
26487        )
26488        .unwrap_err();
26489        assert!(err.contains("no matching command was recorded"), "{err}");
26490
26491        // Final matching command exited non-zero -> rejected even if an
26492        // unrelated command succeeded afterward.
26493        let err = evaluate_noop_claim(
26494            true,
26495            &[
26496                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
26497                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26498                evidence_with("rg retry_test src", Some(0), "retry_test"),
26499            ],
26500            &text,
26501        )
26502        .unwrap_err();
26503        assert!(err.contains("exited with"), "{err}");
26504
26505        // A different invocation containing the entire method is not a rerun.
26506        let err = evaluate_noop_claim(
26507            true,
26508            &[evidence_with(
26509                "echo 'cargo test --lib retry_test'",
26510                Some(0),
26511                "retry_test",
26512            )],
26513            &text,
26514        )
26515        .unwrap_err();
26516        assert!(err.contains("no matching command was recorded"), "{err}");
26517
26518        // Mid-investigation failure followed by a passing re-run -> accepted!
26519        assert!(
26520            verified_noop_claim(
26521                true,
26522                &[
26523                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26524                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
26525                ],
26526                &text
26527            )
26528            .is_some()
26529        );
26530    }
26531
26532    #[test]
26533    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
26534        let text = valid_noop_summary("b32cfc4", "retry_test");
26535        let method = "cargo test --lib retry_test";
26536        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
26537        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
26538        let failed =
26539            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
26540        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
26541        for output in [empty, ignored, failed] {
26542            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
26543                .unwrap_err();
26544            assert!(err.contains("failure or no passing tests"), "{err}");
26545        }
26546        // Multiple harnesses can legitimately include a filtered-out suite.
26547        let mixed = format!("{passed}\n{empty}");
26548        assert!(
26549            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
26550        );
26551        // A later real rerun of the same command can establish success.
26552        assert!(
26553            verified_noop_claim(
26554                true,
26555                &[
26556                    evidence_with(method, Some(0), empty),
26557                    evidence_with(method, Some(0), passed),
26558                ],
26559                &text,
26560            )
26561            .is_some()
26562        );
26563    }
26564
26565    #[test]
26566    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
26567        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":[]}"#;
26568        let failed = evidence_with("rg expected README.md", Some(1), "");
26569        let unrelated = evidence_with("cat README.md", Some(0), "README");
26570        let err =
26571            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
26572        assert!(err.contains("exited with"), "{err}");
26573        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
26574        assert!(
26575            evaluate_noop_claim(
26576                true,
26577                &[
26578                    failed,
26579                    evidence_with("rg expected README.md", Some(0), "expected header"),
26580                ],
26581                text,
26582            )
26583            .unwrap()
26584            .is_some()
26585        );
26586    }
26587
26588    #[test]
26589    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
26590        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
26591        assert!(matches!(
26592            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
26593            Ok(None)
26594        ));
26595    }
26596
26597    #[tokio::test]
26598    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
26599        let tmp = tempfile::tempdir().unwrap();
26600        let repo = tmp.path().join("repo");
26601        std::fs::create_dir_all(&repo).unwrap();
26602        let run_git = |args: &[&str]| {
26603            let out = std::process::Command::new("git")
26604                .args(args)
26605                .current_dir(&repo)
26606                .output()
26607                .unwrap();
26608            assert!(out.status.success(), "git {args:?} failed");
26609            String::from_utf8_lossy(&out.stdout).trim().to_owned()
26610        };
26611        run_git(&["init", "-b", "main"]);
26612        run_git(&["config", "user.name", "test"]);
26613        run_git(&["config", "user.email", "test@example.com"]);
26614        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
26615        run_git(&["add", "-A"]);
26616        run_git(&["commit", "-m", "base commit"]);
26617        let base = run_git(&["rev-parse", "HEAD"]);
26618
26619        // Create a commit on a side branch not on `base`.
26620        run_git(&["checkout", "-b", "side"]);
26621        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
26622        run_git(&["add", "-A"]);
26623        run_git(&["commit", "-m", "side commit"]);
26624        let side = run_git(&["rev-parse", "HEAD"]);
26625        run_git(&["checkout", "main"]);
26626
26627        // Valid commit on base + existing path -> Accepted.
26628        let valid = format!(
26629            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":[]}}"#
26630        );
26631        assert!(matches!(
26632            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
26633            NoopClaimVerdict::Accepted
26634        ));
26635
26636        // Non-existent commit SHA -> Rejected.
26637        let missing_sha = valid.replace(&base, "deadbeef");
26638        assert!(matches!(
26639            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
26640            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
26641        ));
26642
26643        // Commit on unmerged side branch -> Rejected.
26644        let side_sha = valid.replace(&base, &side);
26645        assert!(matches!(
26646            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
26647            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
26648        ));
26649
26650        // Missing file path -> Rejected.
26651        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
26652        assert!(matches!(
26653            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
26654            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
26655        ));
26656    }
26657
26658    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
26659    /// pair, in order, labelled A, B, C, ...
26660    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
26661        runner.state.candidates = shape
26662            .iter()
26663            .enumerate()
26664            .map(|(i, &(empty, verified))| {
26665                let (summary, verified_noop) = match verified {
26666                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
26667                    None => (String::new(), None),
26668                };
26669                Candidate {
26670                    index: i,
26671                    label: (b'A' + i as u8) as char,
26672                    agent: "sonnet".to_owned(),
26673                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
26674                    worktree: PathBuf::from(format!("/wt/{i}")),
26675                    summary,
26676                    stat: String::new(),
26677                    files: 0,
26678                    commits: 0,
26679                    empty,
26680                    failed: None,
26681                    verified_noop,
26682                    duration_ms: 0,
26683                    folded: false,
26684                }
26685            })
26686            .collect();
26687    }
26688
26689    #[test]
26690    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
26691        ask_test_home();
26692        let mut runner = runner_at(RunStatus::Implementing);
26693        let a = valid_noop_summary("b32cfc4", "test_a");
26694        let b = valid_noop_summary("b32cfc4", "test_b");
26695        set_candidates(
26696            &mut runner,
26697            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
26698        );
26699
26700        runner
26701            .after_implement()
26702            .expect("a verified no-op is not an error");
26703
26704        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
26705    }
26706
26707    #[test]
26708    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
26709        ask_test_home();
26710        let mut runner = runner_at(RunStatus::Implementing);
26711        let a = valid_noop_summary("b32cfc4", "test_a");
26712        // Candidate A declares a verified no-op; candidate B simply wrote
26713        // nothing and said nothing about why. One candidate's claim is not
26714        // the whole run's agreement.
26715        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
26716
26717        let err = runner
26718            .after_implement()
26719            .expect_err("an unverified empty candidate must still fail the run");
26720
26721        assert!(
26722            err.to_string().contains("no candidate produced a change"),
26723            "{err}"
26724        );
26725        assert_eq!(runner.state.status, RunStatus::Failed);
26726    }
26727
26728    #[test]
26729    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
26730        ask_test_home();
26731        let mut runner = runner_at(RunStatus::Implementing);
26732        // Simulate a saved incomplete run that stored a legacy/incomplete
26733        // `verified_noop` string before this build's strict contract.
26734        set_candidates(
26735            &mut runner,
26736            &[(
26737                true,
26738                Some(
26739                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
26740                ),
26741            )],
26742        );
26743
26744        let err = runner
26745            .after_implement()
26746            .expect_err("invalid saved noop claim must fail the run");
26747        assert!(
26748            err.to_string().contains("no candidate produced a change"),
26749            "{err}"
26750        );
26751        assert_eq!(runner.state.status, RunStatus::Failed);
26752        assert!(runner.state.candidates[0].verified_noop.is_none());
26753        assert!(runner.state.candidates[0].failed.is_some());
26754        assert!(runner.state.events.iter().any(|e| {
26755            e.message
26756                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
26757        }));
26758    }
26759
26760    #[test]
26761    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
26762        ask_test_home();
26763        let mut runner = runner_at(RunStatus::Implementing);
26764        let a = valid_noop_summary("b32cfc4", "test_a");
26765        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
26766        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
26767
26768        let err = runner
26769            .after_implement()
26770            .expect_err("a failed candidate must never settle as verified no-op");
26771        assert!(err.to_string().contains("no candidate produced a change"));
26772        assert_eq!(runner.state.status, RunStatus::Failed);
26773        assert!(runner.state.candidates[0].verified_noop.is_none());
26774    }
26775
26776    #[test]
26777    fn after_implement_still_fails_an_ordinary_all_empty_run() {
26778        ask_test_home();
26779        let mut runner = runner_at(RunStatus::Implementing);
26780        set_candidates(&mut runner, &[(true, None), (true, None)]);
26781
26782        let err = runner
26783            .after_implement()
26784            .expect_err("no candidate declared anything; this is an ordinary failure");
26785
26786        assert!(
26787            err.to_string().contains("no candidate produced a change"),
26788            "{err}"
26789        );
26790        assert_eq!(runner.state.status, RunStatus::Failed);
26791    }
26792}
26793
26794/// A graft rollback whose restore could not be confirmed (see
26795/// [`Runner::graft`]).
26796#[derive(Debug)]
26797struct GraftRestoreFailed(String);
26798
26799impl std::fmt::Display for GraftRestoreFailed {
26800    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26801        write!(
26802            f,
26803            "could not restore the winner to its pre-graft commit: {}",
26804            self.0
26805        )
26806    }
26807}
26808
26809impl std::error::Error for GraftRestoreFailed {}
26810
26811/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
26812/// not the agent: they never draw on an agent's own timeout, and running out of
26813/// them never reads as an agent failure.
26814#[cfg(test)]
26815mod resource_wait_tests {
26816    use super::*;
26817    use std::collections::BTreeMap;
26818
26819    fn sh(id: &str, script: &str) -> AgentSpec {
26820        AgentSpec {
26821            id: id.to_owned(),
26822            kind: crate::config::AgentKind::Command,
26823            model: None,
26824            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
26825            extra_args: Vec::new(),
26826            env: BTreeMap::new(),
26827            prompt_delivery: None,
26828            max_turn_secs: None,
26829        }
26830    }
26831
26832    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
26833        SeatJob {
26834            seat: SeatState::new("impl-A", &spec.id, 1),
26835            spec,
26836            cwd: dir.to_path_buf(),
26837            prompt: "do it".to_owned(),
26838            timeout,
26839            allow_write: true,
26840            sessions: false,
26841            artifacts: dir.join("art"),
26842            stem: "impl-A".to_owned(),
26843            handover: None,
26844        }
26845    }
26846
26847    fn state(resource_wait_secs: u64) -> RunState {
26848        let mut config = Config::default();
26849        config.graph.timeout_resource_wait = resource_wait_secs;
26850        RunState::new(
26851            PathBuf::from("/repo"),
26852            "main".to_owned(),
26853            "abc1234".to_owned(),
26854            "task".to_owned(),
26855            config,
26856        )
26857    }
26858
26859    fn hold(cache: &Path) -> crate::cache::Guard {
26860        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
26861        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
26862            crate::cache::AcquireOutcome::Acquired(g) => g,
26863            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26864        }
26865    }
26866
26867    async fn run(
26868        jobs: Vec<SeatJob>,
26869        sem: Arc<Semaphore>,
26870        cache: Option<&Path>,
26871        st: &mut RunState,
26872    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26873        let prompts = Prompts::default();
26874        let ctx = WaveCtx {
26875            run: "r",
26876            node: "implement",
26877            prompts: &prompts,
26878            cache,
26879            round: None,
26880            carry_seats: false,
26881            pauses: None,
26882        };
26883        wave(jobs, sem, &ctx, st, 0).await
26884    }
26885
26886    #[tokio::test]
26887    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26888        crate::run::pin_test_home();
26889        let home = crate::run::home();
26890        let tmp = tempfile::tempdir().unwrap();
26891        let repo = tmp.path().join("repo");
26892        let checkout = tmp.path().join("checkout");
26893        std::fs::create_dir(&repo).unwrap();
26894        git::git(&repo, &["init"]).await.unwrap();
26895        git::git(
26896            &repo,
26897            &[
26898                "-c",
26899                "user.name=Fixture",
26900                "-c",
26901                "user.email=fixture@example.invalid",
26902                "commit",
26903                "--allow-empty",
26904                "-m",
26905                "initial",
26906            ],
26907        )
26908        .await
26909        .unwrap();
26910        git::worktree_add_detached(&repo, &checkout, "HEAD")
26911            .await
26912            .unwrap();
26913        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26914        let target_lease = hold(&target);
26915        let shared = tmp.path().join("unrelated");
26916        let _shared_lease = hold(&shared);
26917        let mut st = state(0);
26918        st.repo = repo.clone();
26919        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26920        st.config.verify.e2e = vec![format!(
26921            "CARGO_TARGET_DIR='{}' cargo test",
26922            git::path_arg(&shared)
26923        )];
26924        let config = tmp.path().join("config.toml");
26925        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26926        let prompts = Prompts::default();
26927        let run_id = st.id.clone();
26928        let ctx = WaveCtx {
26929            run: &run_id,
26930            node: "implement",
26931            prompts: &prompts,
26932            cache: None,
26933            round: None,
26934            carry_seats: false,
26935            pauses: None,
26936        };
26937        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26938        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26939        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26940        assert_eq!(results[0].1.turns, 0);
26941        let saved = RunState::load_under(&run_id, &home).unwrap();
26942        let block = saved.resource_block.unwrap();
26943        assert!(matches!(
26944            block.cause,
26945            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
26946                if actual == &target
26947        ));
26948        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
26949        let mut task = crate::queue::Task::new(
26950            "build".into(),
26951            "build".into(),
26952            repo,
26953            crate::queue::Source::Human,
26954        );
26955        task.runs.push(run_id);
26956        task.hold_machine(Some(format!(
26957            "{}{}",
26958            crate::cache::RESOURCE_HOLD,
26959            block.description()
26960        )));
26961        queue.put(&mut task).unwrap();
26962        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
26963        let triage =
26964            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
26965        let pending = triage();
26966        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
26967        assert_eq!(
26968            queue.get(&task.id).unwrap().status,
26969            crate::queue::TaskStatus::Held
26970        );
26971        drop(target_lease);
26972        assert_eq!(triage().resumed, vec![task.id.clone()]);
26973        assert_eq!(
26974            queue.get(&task.id).unwrap().status,
26975            crate::queue::TaskStatus::Queued
26976        );
26977        assert!(crate::cache::in_use(&home, &shared));
26978    }
26979
26980    #[tokio::test]
26981    async fn verification_cache_wait_preserves_the_command_budget() {
26982        crate::run::pin_test_home();
26983        let tmp = tempfile::tempdir().unwrap();
26984        let cache = tmp.path().join("target");
26985        let guard = hold(&cache);
26986        let release = tokio::spawn(async move {
26987            tokio::time::sleep(Duration::from_millis(100)).await;
26988            guard.release();
26989        });
26990        let mut st = state(10);
26991        let budget = Duration::from_millis(50);
26992        let wait = repository_wait(&st, None);
26993        let (outcomes, _) = with_cache_lease(
26994            &mut st,
26995            Some(&cache),
26996            "gate",
26997            "gate",
26998            tmp.path(),
26999            "abc1234",
27000            budget,
27001            "test gate",
27002            &wait,
27003            |_, available| async move {
27004                assert_eq!(
27005                    available, budget,
27006                    "contention must not shorten verification"
27007                );
27008                (Vec::new(), false, Vec::new())
27009            },
27010        )
27011        .await
27012        .unwrap();
27013        release.await.unwrap();
27014        assert!(outcomes.is_empty(), "{outcomes:?}");
27015        assert!(
27016            st.events
27017                .iter()
27018                .any(|event| event.message.contains("waiting for"))
27019        );
27020        assert!(st.resource_wait.is_none());
27021        // The verification body no longer owns the lease after returning.
27022        hold(&cache).release();
27023    }
27024
27025    #[tokio::test]
27026    async fn verification_cache_wait_expires_without_starting_commands() {
27027        crate::run::pin_test_home();
27028        let tmp = tempfile::tempdir().unwrap();
27029        let cache = tmp.path().join("target");
27030        let _held = hold(&cache);
27031        let mut st = state(0);
27032        let wait = repository_wait(&st, None);
27033        let (outcomes, _) = with_cache_lease(
27034            &mut st,
27035            Some(&cache),
27036            "gate",
27037            "gate",
27038            tmp.path(),
27039            "abc1234",
27040            Duration::from_secs(60),
27041            "test gate",
27042            &wait,
27043            |_, _| async { panic!("commands must not start without the cache lease") },
27044        )
27045        .await
27046        .unwrap();
27047        assert_eq!(outcomes.len(), 1);
27048        assert!(outcomes[0].resource_blocked);
27049        assert!(st.resource_wait.is_none());
27050        assert!(matches!(
27051            st.resource_block.unwrap().cause,
27052            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
27053        ));
27054    }
27055
27056    #[tokio::test]
27057    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
27058        crate::run::pin_test_home();
27059        let tmp = tempfile::tempdir().unwrap();
27060        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
27061        let cache = tmp.path().join("cache");
27062        let mut state = state(21600);
27063        let wait = repository_wait(&state, None);
27064        let (outcomes, _) = with_cache_lease(
27065            &mut state,
27066            Some(&cache),
27067            "gate",
27068            "gate",
27069            tmp.path(),
27070            "head",
27071            Duration::from_secs(60),
27072            "gate",
27073            &wait,
27074            |_, _| async { panic!("freshness failure must not start verification") },
27075        )
27076        .await
27077        .unwrap();
27078        assert_eq!(outcomes.len(), 1);
27079        assert!(outcomes[0].resource_blocked);
27080        let block = state.resource_block.unwrap();
27081        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
27082        assert!(!block.description().contains("timed out"));
27083    }
27084
27085    #[tokio::test]
27086    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
27087        crate::run::pin_test_home();
27088        let tmp = tempfile::tempdir().unwrap();
27089        let cache = tmp.path().join("cache");
27090        let _held = hold(&cache);
27091        let mut state = state(21600);
27092        let pause = Pause::new();
27093        let interrupt = Pause::new();
27094        let cause = ParkCause::Operator;
27095        pause.park_for(cause.clone());
27096        let prompts = Prompts::default();
27097        let ctx = WaveCtx {
27098            run: "test",
27099            node: "fix",
27100            prompts: &prompts,
27101            cache: Some(&cache),
27102            round: None,
27103            carry_seats: false,
27104            pauses: Some((&pause, &interrupt)),
27105        };
27106        let result = wave(
27107            vec![job(
27108                sh("writer", "exit 99"),
27109                tmp.path(),
27110                Duration::from_secs(1),
27111            )],
27112            Arc::new(Semaphore::new(1)),
27113            &ctx,
27114            &mut state,
27115            0,
27116        )
27117        .await;
27118        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
27119        assert_eq!(result[0].1.turns, 0);
27120        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27121        assert_eq!(
27122            state.resource_block.unwrap().cause,
27123            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
27124        );
27125        assert!(state.active.is_empty());
27126    }
27127
27128    #[tokio::test]
27129    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
27130        crate::run::pin_test_home();
27131        let tmp = tempfile::tempdir().unwrap();
27132        let cache = tmp.path().join("target-a");
27133        let guard = hold(&cache);
27134        // Held for longer than the agent's whole 1s budget.
27135        tokio::spawn(async move {
27136            tokio::time::sleep(Duration::from_millis(1500)).await;
27137            guard.release();
27138        });
27139        let mut st = state(60);
27140        let results = run(
27141            vec![job(
27142                sh("alpha", "echo ok"),
27143                tmp.path(),
27144                Duration::from_secs(1),
27145            )],
27146            Arc::new(Semaphore::new(1)),
27147            Some(&cache),
27148            &mut st,
27149        )
27150        .await;
27151        assert!(
27152            matches!(results[0].2, AgentOutcome::Ok(_)),
27153            "the wait must not be charged to the agent"
27154        );
27155        assert!(st.resource_block.is_none());
27156        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27157        assert!(st.resource_wait.is_none() && st.active.is_empty());
27158    }
27159
27160    #[tokio::test]
27161    #[cfg(unix)]
27162    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
27163        use std::os::fd::AsRawFd as _;
27164        crate::run::pin_test_home();
27165        let tmp = tempfile::tempdir().unwrap();
27166        crate::git::git(tmp.path(), &["init"]).await.unwrap();
27167        let common = tmp.path().join(".git");
27168        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
27169        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
27170        assert_eq!(
27171            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
27172            0
27173        );
27174        let mut st = state(1);
27175        st.config.coordination = crate::config::test_coordination();
27176        let mut reader = job(
27177            sh("reader", "echo must-not-run"),
27178            tmp.path(),
27179            Duration::from_secs(30),
27180        );
27181        reader.allow_write = false;
27182        let results = run(
27183            vec![reader.clone()],
27184            Arc::new(Semaphore::new(1)),
27185            None,
27186            &mut st,
27187        )
27188        .await;
27189        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27190        assert_eq!(results[0].1.turns, 0);
27191        assert!(FailClass::of(&results[0].2).is_none());
27192        assert_eq!(
27193            st.resource_block.as_ref().unwrap().kind,
27194            "repository coordination"
27195        );
27196        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27197        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27198        drop(external);
27199        let editor = crate::repo_lock::SeatLease::for_checkout(
27200            tmp.path(),
27201            true,
27202            crate::config::test_coordination().as_ref(),
27203        )
27204        .await
27205        .unwrap();
27206        let pause = Pause::new();
27207        let interrupt = Pause::new();
27208        let prompts = Prompts::default();
27209        let ctx = WaveCtx {
27210            run: "r",
27211            node: "review",
27212            prompts: &prompts,
27213            cache: None,
27214            round: None,
27215            carry_seats: false,
27216            pauses: Some((&pause, &interrupt)),
27217        };
27218        let (results, ()) = tokio::join!(
27219            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
27220            async {
27221                tokio::time::sleep(Duration::from_millis(50)).await;
27222                pause.park();
27223            }
27224        );
27225        assert!(
27226            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
27227        );
27228        assert_eq!(results[0].1.turns, 0);
27229        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27230        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27231        drop(editor);
27232    }
27233
27234    #[tokio::test]
27235    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
27236        crate::run::pin_test_home();
27237        let tmp = tempfile::tempdir().unwrap();
27238        let cache = tmp.path().join("target-b");
27239        let _held = hold(&cache);
27240        let mut st = state(1);
27241        let results = run(
27242            vec![job(
27243                sh("alpha", "echo ok"),
27244                tmp.path(),
27245                Duration::from_secs(1),
27246            )],
27247            Arc::new(Semaphore::new(1)),
27248            Some(&cache),
27249            &mut st,
27250        )
27251        .await;
27252        let (_, seat, out) = &results[0];
27253        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
27254        assert!(wave_blocked(&results));
27255        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
27256        assert_eq!(seat.turns, 0, "nothing was asked");
27257        assert!(
27258            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
27259            "no agent was spawned"
27260        );
27261        assert!(FailClass::of(out).is_none(), "not a failure class");
27262        let block = st.resource_block.as_ref().expect("recorded for the resume");
27263        assert_eq!(block.kind, "shared build cache");
27264        assert!(matches!(
27265            block.cause,
27266            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
27267        ));
27268        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27269        assert!(st.active.is_empty());
27270    }
27271
27272    #[tokio::test]
27273    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
27274        crate::run::pin_test_home();
27275        let tmp = tempfile::tempdir().unwrap();
27276        let mut st = state(1);
27277        let results = run(
27278            vec![job(
27279                sh("alpha", "echo ok"),
27280                tmp.path(),
27281                Duration::from_secs(1),
27282            )],
27283            Arc::new(Semaphore::new(0)),
27284            None,
27285            &mut st,
27286        )
27287        .await;
27288        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27289        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
27290        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
27291    }
27292
27293    #[tokio::test]
27294    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
27295        crate::run::pin_test_home();
27296        let tmp = tempfile::tempdir().unwrap();
27297        let mut st = state(60);
27298        let results = run(
27299            vec![job(
27300                sh("alpha", "sleep 30"),
27301                tmp.path(),
27302                Duration::from_secs(1),
27303            )],
27304            Arc::new(Semaphore::new(1)),
27305            None,
27306            &mut st,
27307        )
27308        .await;
27309        let out = &results[0].2;
27310        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
27311        let class = FailClass::of(out).expect("a failure");
27312        assert_eq!(class, FailClass::Timeout);
27313        assert!(should_hand_over(None, &class), "existing handover policy");
27314        assert!(st.resource_block.is_none());
27315    }
27316}
27317
27318/// A fold acts on the record it locked, and on nothing else.
27319#[cfg(test)]
27320mod fold_record_tests {
27321    use super::*;
27322
27323    fn refusal(error: &anyhow::Error) -> Option<&FoldRefusal> {
27324        error.downcast_ref::<FoldRefusal>()
27325    }
27326
27327    /// A deletion that lands after the fold's look at the record and before its
27328    /// locks must neither be undone (the fold's lock files bring the directory
27329    /// back, its stale copy the record) nor be acted on.
27330    #[tokio::test]
27331    async fn a_run_deleted_between_the_look_and_the_locks_is_refused_and_not_recreated() {
27332        let dir = tempfile::tempdir().unwrap();
27333        let home = dir.path();
27334        let repo = home.join("repo");
27335        std::fs::create_dir_all(&repo).unwrap();
27336        crate::clean::tests::init_repo(&repo);
27337        let (id, worktree) = crate::clean::tests::due_run_with_winner_worktree(
27338            &home.join("runs"),
27339            &home.join("wt"),
27340            &repo,
27341            "20260801-000000-y001",
27342            RunStatus::Superseded,
27343        )
27344        .await;
27345        let mut state = RunState::load_under(&id, home).unwrap();
27346        BEFORE_LOCKS.with(|hook| {
27347            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
27348                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
27349            }));
27350        });
27351
27352        let error = fold_run(&mut state, true, home).await.unwrap_err();
27353        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27354        assert!(
27355            !home.join("runs").join(&id).exists(),
27356            "the fold's own lock files must not bring a deleted run back"
27357        );
27358        assert!(worktree.exists(), "nothing of a deleted run is removed");
27359    }
27360
27361    /// The caller's `state` is only a first look: a record that was never
27362    /// saved is not a record the fold may write.
27363    #[tokio::test]
27364    async fn a_record_that_was_never_saved_is_not_folded_or_written() {
27365        let dir = tempfile::tempdir().unwrap();
27366        let home = dir.path();
27367        let mut state = RunState::new(
27368            home.join("repo"),
27369            "main".to_owned(),
27370            "abc".to_owned(),
27371            "fixture".to_owned(),
27372            crate::config::Config::default(),
27373        );
27374        state.status = RunStatus::Superseded;
27375        let error = fold_run(&mut state, true, home).await.unwrap_err();
27376        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27377        assert!(
27378            !home.join("runs").exists(),
27379            "nothing was created: {error:#}"
27380        );
27381    }
27382
27383    /// A refusal changes nothing. A directory whose record is another run's is
27384    /// not the run that was locked: every entry point answers `record gone`,
27385    /// the other run's worktree is left alone, the record stays as it was, and
27386    /// the lock files are not unlinked (an unlinked lock file lets the next
27387    /// caller lock a different inode - `pr_head::owner_lock`).
27388    #[tokio::test]
27389    async fn a_record_naming_another_run_is_refused_by_every_entry_point_and_nothing_is_touched() {
27390        let dir = tempfile::tempdir().unwrap();
27391        let home = dir.path();
27392        let repo = home.join("repo");
27393        std::fs::create_dir_all(&repo).unwrap();
27394        crate::clean::tests::init_repo(&repo);
27395        let runs = home.join("runs");
27396        let (id, own) = crate::clean::tests::due_run_with_winner_worktree(
27397            &runs,
27398            &home.join("wt"),
27399            &repo,
27400            "20260801-000000-y101",
27401            RunStatus::Superseded,
27402        )
27403        .await;
27404        let (other, theirs) = crate::clean::tests::due_run_with_winner_worktree(
27405            &runs,
27406            &home.join("wt"),
27407            &repo,
27408            "20260801-000000-y102",
27409            RunStatus::Superseded,
27410        )
27411        .await;
27412        let first_look = RunState::load_under(&id, home).unwrap();
27413        let record = runs.join(&id).join("run.json");
27414        std::fs::copy(runs.join(&other).join("run.json"), &record).unwrap();
27415        let before = std::fs::read(&record).unwrap();
27416        for entry in ["fold_run", "fold_run_when", "override"] {
27417            let mut state = first_look.clone();
27418            let result = match entry {
27419                "fold_run" => fold_run(&mut state, true, home).await,
27420                "fold_run_when" => fold_run_when(&mut state, home, &|_| Ok(true)).await,
27421                _ => fold_run_overriding_recovery_retention(&mut state, true, home).await,
27422            };
27423            let error = result.unwrap_err();
27424            assert_eq!(
27425                refusal(&error),
27426                Some(&FoldRefusal::RecordGone),
27427                "{entry}: {error:#}"
27428            );
27429            assert!(own.exists() && theirs.exists(), "{entry}");
27430            assert_eq!(std::fs::read(&record).unwrap(), before, "{entry}");
27431            for lock in ["pr-owner.lock", "driver.lock"] {
27432                assert!(
27433                    runs.join(&id).join(lock).exists(),
27434                    "{entry}: {lock} stays in place"
27435                );
27436            }
27437            assert!(
27438                !RunState::load_under(&other, home).unwrap().candidates[0].folded,
27439                "{entry}: the other run was not folded"
27440            );
27441        }
27442    }
27443
27444    /// The refusal is added to the error underneath, never substituted for it:
27445    /// callers match `ResourceBlocked` for a coordination wait.
27446    #[test]
27447    fn a_live_refusal_keeps_the_error_callers_match() {
27448        let blocked = anyhow::Error::new(crate::repo_lock::ResourceBlocked(
27449            "repository coordination".into(),
27450        ));
27451        let error = live_or(blocked);
27452        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
27453        assert!(matches!(refusal(&error), Some(FoldRefusal::Live(_))));
27454        // Anything that is not a held lock is passed through untouched.
27455        let other = live_or(anyhow::anyhow!("git exploded"));
27456        assert!(refusal(&other).is_none());
27457    }
27458
27459    /// Contention is `live`, a lock call that failed for another reason is a
27460    /// failure of its own (`failed`), missing evidence is an incomplete proof.
27461    #[test]
27462    fn source_verification_failures_are_told_apart() {
27463        let contended = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::WouldBlock))
27464            .context("Cargo build is active");
27465        let error = source_proof_failure(contended);
27466        assert!(
27467            matches!(refusal(&error), Some(FoldRefusal::Live(_))),
27468            "{error:#}"
27469        );
27470
27471        let failed = anyhow::Error::new(crate::retention::LockCallFailed::new(
27472            "Cargo lock target/debug/.cargo-lock".into(),
27473            std::io::Error::from(std::io::ErrorKind::Interrupted),
27474        ));
27475        let error = source_proof_failure(failed);
27476        assert!(refusal(&error).is_none(), "{error:#}");
27477        assert!(
27478            error
27479                .chain()
27480                .any(|cause| cause.is::<crate::retention::LockCallFailed>())
27481        );
27482
27483        let error = source_proof_failure(anyhow::anyhow!("Cargo residue changed"));
27484        assert!(matches!(
27485            refusal(&error),
27486            Some(FoldRefusal::ProofIncomplete(_))
27487        ));
27488    }
27489
27490    /// A run directory that is not there is `record gone` at the lock, not
27491    /// something to create for the lock's sake.
27492    #[test]
27493    fn a_missing_run_directory_at_the_lock_is_record_gone() {
27494        let dir = tempfile::tempdir().unwrap();
27495        let error = crate::pr_head::owner_lock(dir.path(), "20260801-000000-y103")
27496            .map(drop)
27497            .map_err(lock_refusal)
27498            .unwrap_err();
27499        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27500        assert!(!dir.path().join("runs").exists());
27501    }
27502}