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};
61use crate::worktree_setup;
62
63/// Bytes of a failing command's output kept in an event, so the reason a run
64/// stopped is readable from the report without opening `run.json`.
65const EVENT_OUTPUT_TAIL: usize = 2_000;
66
67/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
68/// command's pid before releasing the build cache's lease.
69const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
70
71/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
72/// command's pid to actually exit before giving up and releasing anyway.
73///
74/// A timeout means the process was asked to die (`kill_on_drop`,
75/// `start_kill`), not that it already has — on Windows in particular that can
76/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
77/// the instant the command returns would let the very next acquirer (this
78/// run's own next round, another run's verification, the janitor's prune)
79/// start touching the same directory while it might still be writing to it,
80/// so this polls the actual pid — real confirmation, not a fixed guess —
81/// until it is gone or this ceiling is reached. It is still not full
82/// process-tree reaping: a grandchild the timed-out process spawned and that
83/// outlives it independently is invisible to a pid check, and continuing to
84/// observe and collect *that* stays a different piece of work with its own
85/// owner. Set generously because the common case returns early the moment
86/// the pid is confirmed gone, not because every timeout pays this in full.
87const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
88
89/// Consecutive review rounds with no tree progress (see
90/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
91/// instead of spending the rest of the round budget.
92///
93/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
94/// legitimately finds nothing left to change (its previous round's fix already
95/// covered it, and this round's reviewers re-raised only nits) looks the same
96/// as one that is spinning, for exactly one round. Two in a row is where the
97/// two stop being distinguishable, and a review round on this workload has
98/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
99/// third attempt at a tree that has not moved twice running is pure cost.
100/// This does not touch `review_rounds` itself, which stays the operator's
101/// call.
102pub(crate) const STAGNANT_LIMIT: usize = 2;
103
104/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
105/// a base that moved before giving up and leaving the run `Blocked` for a
106/// person.
107///
108/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
109/// that keeps moving faster than a run can catch it is not something more
110/// rebasing fixes, it is a person's call. Not the same *number as*
111/// `land_rounds` - this budget is spent before a pull request exists, land's
112/// after - but bounded for the identical reason, so it uses the same
113/// default. Counted across both call sites in [`Runner::finish_after_tally`]
114/// (once before review, once before the gate), because either one finding
115/// the base still moving is the same signal.
116pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
117
118/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
119/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
120/// reply held no [`FixReport`].
121///
122/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
123/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
124/// "I'll pause here until the `cargo make check` background run reports
125/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
126/// No `FixReport` was ever collected from that seat, and the run moved on to
127/// the next review round regardless.
128///
129/// Bounded independently of `review_rounds` and `graph.retries`: this
130/// recovers one seat's missing report mid-round, not a new round of review or
131/// an ordinary parse retry, and must not itself become the unbounded wait the
132/// rest of this module exists to avoid.
133const MAX_FIX_CONTINUATIONS: usize = 2;
134
135/// One queued agent invocation.
136///
137/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
138/// CLI hung up on its own stream is asked again from the same job rather than
139/// rebuilt from scratch. See [`Runner::resume_undelivered`].
140#[derive(Clone)]
141struct SeatJob {
142    spec: AgentSpec,
143    seat: SeatState,
144    cwd: PathBuf,
145    prompt: String,
146    timeout: Duration,
147    allow_write: bool,
148    sessions: bool,
149    artifacts: PathBuf,
150    stem: String,
151    /// The prompt for a seat that has been handed to another roster agent
152    /// (a fresh session): everything the original seat would have
153    /// remembered. `None` when `prompt` already carries it, as the first
154    /// ranking and the implement prompt do. Never a resume-style prompt.
155    handover: Option<String>,
156}
157
158/// How the graph reads one agent invocation.
159///
160/// Quota is split out from an ordinary failure on purpose: a rate-limited call
161/// is known to fail again if retried now, so the retry loop must not spend an
162/// attempt on it. `Dropped` is split out for the opposite reason: unlike
163/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
164/// error JSON, never the agent's answer — a caller that matched only
165/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
166/// left to read that JSON as if it were usable output. `resume_undelivered`
167/// is the only caller that acts on it; everywhere else it is reported like an
168/// ordinary failure.
169enum AgentOutcome {
170    /// A usable output.
171    Ok(AgentOutput),
172    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
173    Quota(AgentOutput),
174    /// The CLI hung up on its own stream after billed work. See
175    /// [`agent::AgentOutput::work_undelivered`].
176    Dropped(AgentOutput),
177    /// Any other failure: a timeout, a bad exit code, an empty reply.
178    Failed(String),
179    /// A resource prevented admission or interrupted execution. Not an agent
180    /// failure: never advance a fallback chain or spend an attempt on it.
181    /// Post-spawn interruptions carry a typed error into wave, which records
182    /// implementation preservation before returning this outcome. This outcome
183    /// alone is not proof that no source changes were made.
184    /// [`RunState::resource_block`] says why.
185    ResourceBlocked(String),
186}
187
188/// A request to park the run at its next node boundary.
189///
190/// Cloning is how the request travels: the loop keeps one handle and hands a
191/// clone to each [`Runner`], and every clone points at the same flag. There
192/// is no channel because there is nothing to send - the only message is
193/// "park", it is idempotent, and a flag cannot be missed by a receiver that
194/// was not listening yet.
195///
196/// The boundary is what makes this cheap. Every node writes the run's state
197/// before the next one starts, and every node skips what is already recorded:
198/// `prep` returns early once candidates exist, `implement` asks only the seats
199/// with nothing on disk, `judge` returns early once judgements exist. So a
200/// parked run resumes into exactly the node it stopped before, and no agent
201/// work is thrown away. Killing the process mid-node, by contrast, loses
202/// whatever the seats in flight had not yet written - which for an implement
203/// wave is an hour of paid work.
204///
205/// A [`Runner`] watches two independent handles of this type - see
206/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
207/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
208/// clone covering the whole daemon's lifetime and is never asked to un-park,
209/// which is correct exactly because nothing is dispatched after it fires.
210/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
211/// that parks for an interrupted task must go on to run other tasks
212/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
213/// reusing the daemon-wide one.
214#[derive(Debug, Clone, Default)]
215pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
216
217impl Pause {
218    /// A pause nobody has asked for yet.
219    #[must_use]
220    pub fn new() -> Self {
221        Self::default()
222    }
223
224    /// Ask the run to park at its next node boundary. Idempotent.
225    pub fn park(&self) {
226        self.0.store(true, Ordering::SeqCst);
227    }
228
229    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
230    /// fold into the run's own `park` event - so an operator reading the run
231    /// later knows this was a deliberate interrupt rather than a shutdown or
232    /// a binary swap. The first reason recorded wins; a park already in
233    /// flight is not relabelled by a second, unrelated request.
234    pub fn park_because(&self, reason: impl Into<String>) {
235        self.park_for(ParkCause::Interrupt {
236            reason: reason.into(),
237        });
238    }
239
240    /// [`Pause::park`], recording the structured cause. The first cause
241    /// recorded wins, like [`Pause::park_because`].
242    pub fn park_for(&self, cause: ParkCause) {
243        let mut reason_guard = self
244            .1
245            .lock()
246            .unwrap_or_else(std::sync::PoisonError::into_inner);
247        if reason_guard.is_none() {
248            *reason_guard = Some(cause);
249        }
250        drop(reason_guard);
251        self.park();
252    }
253
254    /// Has a park been asked for?
255    #[must_use]
256    pub fn parked(&self) -> bool {
257        self.0.load(Ordering::SeqCst)
258    }
259
260    /// Why the park was asked for, when the caller used [`Pause::park_because`].
261    #[must_use]
262    pub fn reason(&self) -> Option<String> {
263        self.cause().map(|c| c.label())
264    }
265
266    /// The structured cause, when one was recorded.
267    #[must_use]
268    pub fn cause(&self) -> Option<ParkCause> {
269        self.1
270            .lock()
271            .unwrap_or_else(std::sync::PoisonError::into_inner)
272            .clone()
273    }
274}
275
276/// Drives one run.
277pub struct Runner {
278    /// Run state; public so the CLI can report on it.
279    pub state: RunState,
280    roles: ResolvedRoles,
281    sem: Arc<Semaphore>,
282    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
283    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
284    /// this is never the same handle as `interrupt`.
285    pause: Pause,
286    /// Set when `magi serve`'s interrupt scheduler wants this specific run
287    /// parked at its next node boundary, to let a task marked
288    /// [`crate::queue::Task::interrupt`] run alone before this one carries
289    /// on. Unlike `pause`, a fresh, unshared handle per run - see
290    /// [`Runner::watch_interrupt`].
291    interrupt: Pause,
292}
293
294/// Where the branch's own commits start: its merge base with the base branch
295/// as the remote has it now, else with the recorded `base_commit`. A branch
296/// rebased onto a base that moved past `base_commit` would otherwise count
297/// the base's commits as its own under `base_commit..branch`.
298async fn review_base(
299    repo: &Path,
300    remote: &str,
301    base_branch: &str,
302    base_commit: &str,
303    branch: &str,
304) -> String {
305    review_base_checked(repo, remote, base_branch, base_commit, branch)
306        .await
307        .0
308}
309
310/// [`review_base`] plus whether the base was read from a freshly fetched
311/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
312/// never older than `base_commit`'s view of the base), but the answer is then
313/// not trusted to rewrite a pull request's title.
314async fn review_base_checked(
315    repo: &Path,
316    remote: &str,
317    base_branch: &str,
318    base_commit: &str,
319    branch: &str,
320) -> (String, bool) {
321    let tracking = format!("{remote}/{base_branch}");
322    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
323    if git::rev_exists(repo, &tracking).await
324        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
325        && !mb.is_empty()
326    {
327        return (mb, fresh);
328    }
329    let mb = git::merge_base(repo, base_commit, branch)
330        .await
331        .ok()
332        .filter(|mb| !mb.is_empty())
333        .unwrap_or_else(|| base_commit.to_owned());
334    (mb, false)
335}
336
337/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
338/// when git cannot say or finds nothing: a stale list is better than a wrong
339/// or empty one.
340pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
341    if !is_review_run(state) {
342        return;
343    }
344    let base = review_base(
345        &state.repo,
346        &state.config.merge.remote,
347        &state.base_branch,
348        &state.base_commit,
349        branch,
350    )
351    .await;
352    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
353        && !subjects.is_empty()
354        && state.reviewed_commits.as_ref() != Some(&subjects)
355    {
356        state.reviewed_commits = Some(subjects);
357        state.save().ok();
358    }
359}
360
361/// Subjects of the base's commits between the recorded start and the branch's
362/// merge base: what a stale `base_commit..branch` would have mistaken for the
363/// branch's own work.
364async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
365    let (base, trusted) = review_base_checked(
366        &state.repo,
367        &state.config.merge.remote,
368        &state.base_branch,
369        &state.base_commit,
370        branch,
371    )
372    .await;
373    if !trusted {
374        return None;
375    }
376    git::subjects(&state.repo, &state.base_commit, &base)
377        .await
378        .ok()
379}
380
381/// May an adopted pull request's title be replaced with `computed`? Only when
382/// it is empty, magi's own shape, or a base commit's subject that leaked in;
383/// a title a person wrote stays. Never when `computed` is itself a leak.
384pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
385    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
386    if is_leak(computed) {
387        return false;
388    }
389    let cur = current.trim();
390    cur.is_empty()
391        || cur.starts_with(REVIEW_PROMPT_OPENING)
392        || cur.starts_with("chore: land candidate")
393        || cur.starts_with("magi: candidate")
394        || is_leak(cur)
395}
396
397/// The commit a run branches from: the base branch as the remote has it.
398///
399/// Two failures this replaces. A run used to branch off `HEAD` and so refused
400/// to start on a dirty tree, which made `magi serve` decline every task for as
401/// long as the operator had work in progress - most of the time. Branching off
402/// the *local* base branch fixed that and introduced a worse one: `land` merges
403/// the winner on GitHub, nothing updates the local ref, and the next run
404/// branches off a base missing everything the previous runs landed. Two tasks
405/// in a row from a phone would have had the second silently re-implementing
406/// against stale code and opening a pull request that reverted the first.
407///
408/// Only refs move here - no checkout, no local branch, no merge - so it is safe
409/// with uncommitted work in the tree. A machine with no network still starts:
410/// the fetch may fail and the local tip is used with a warning, because
411/// refusing to run offline is a worse failure than running against a base the
412/// operator can see for themselves.
413///
414/// One function, called by both entry points. Two answers to "where does a run
415/// branch from" is the kind of drift nobody notices until a diff is wrong.
416/// Bring the local `branch` in line with `<remote>/<branch>` before a review
417/// checks it out.
418///
419/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
420/// anything other than plain `git push` from this checkout (a jj colocated
421/// workspace, another clone) moves only the remote-tracking ref - so the local
422/// one can be a stale placeholder. It moves only when local is behind the remote or is an
423/// empty placeholder that diverged from it; unpushed local work is kept, and a real
424/// divergence is refused rather than guessed at.
425async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
426    let tracking = format!("{remote}/{branch}");
427    let fetched = git::fetch(repo, remote, branch).await;
428    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
429    let local_exists = git::branch_exists(repo, branch).await?;
430    if !fresh {
431        if !local_exists {
432            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
433        }
434        tracing::warn!(
435            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
436        );
437        return Ok(());
438    }
439    let remote_sha = git::rev_parse(repo, &tracking).await?;
440    if !local_exists {
441        git::git(repo, &["branch", branch, &tracking]).await?;
442        return Ok(());
443    }
444    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
445    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
446        return Ok(());
447    }
448    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
449        // Diverged. `reconcile` settles it only when it can prove nothing is
450        // lost: a local tip that is the remote's change rebased is pushed over
451        // it (lease pinned to the tip read here), a tip whose every extra
452        // commit is empty is a placeholder the remote's work replaced, and
453        // anything else is two different changes - a question for a person.
454        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
455            .await?
456        {
457            crate::reconcile::Reconciliation::Pushed => {
458                tracing::warn!(
459                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
460                    short(&local_sha),
461                    short(&remote_sha)
462                );
463                return Ok(());
464            }
465            crate::reconcile::Reconciliation::Placeholder => {}
466            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
467        }
468    }
469    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
470    if !out.ok() {
471        bail!(
472            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
473            short(&local_sha),
474            short(&remote_sha),
475            out.stderr
476        );
477    }
478    tracing::warn!(
479        "local `{branch}` was stale: fast-forwarded {} -> {}",
480        short(&local_sha),
481        short(&remote_sha)
482    );
483    Ok(())
484}
485
486async fn resolve_base(
487    repo: &Path,
488    base_branch: &str,
489    remote: &str,
490    coordination: Option<&crate::config::Coordination>,
491) -> Result<crate::run::FetchedBase> {
492    let _lease = crate::repo_lock::SeatLease::operation_with(
493        repo,
494        coordination,
495        &crate::repo_lock::WaitPolicy::current(),
496    )
497    .await?;
498    let tracking = format!("{remote}/{base_branch}");
499    let fetched = git::fetch(repo, remote, base_branch).await;
500    if let Ok(out) = &fetched
501        && out.ok()
502        && git::rev_exists(repo, &tracking).await
503    {
504        return Ok(crate::run::FetchedBase {
505            remote: remote.to_owned(),
506            branch: base_branch.to_owned(),
507            commit: git::rev_parse(repo, &tracking).await?,
508            fetched_at: jiff::Timestamp::now(),
509        });
510    }
511    let why = match &fetched {
512        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
513        Ok(_) => format!("{remote} has no {base_branch}"),
514        Err(e) => e.to_string(),
515    };
516    // No fallback to the local branch: it may be behind, and branching off an
517    // old commit is the stale-checkout bug this check exists to prevent.
518    bail!(
519        "cannot read {tracking} ({why}); refusing to branch off the local \
520         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
521         base / remote in magi.toml. This is launcher preparation: check the \
522         launcher's network, Git access and repository coordination before \
523         retrying"
524    )
525}
526
527/// Outcome of the shared fixer chain, before caller-owned stop policy.
528enum FixStep {
529    Resource,
530    Recorded { report_lost: bool },
531}
532
533/// Exclusive claim shared by targeted repairs and repository reassignment.
534/// Held before asynchronous fix preflight and released on every return or panic.
535///
536/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
537/// manual `magi fix` invocations against the same run are otherwise
538/// invisible to each other and would race to remove and recreate the same
539/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
540/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
541/// which is only ever reclaimed later, out of band, by
542/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
543/// `magi fix` invocation is not necessarily running under either of those, so
544/// nothing would ever sweep a lock a killed or crashed process left behind.
545/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
546/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
547/// lease use: an unreadable or unparsable pid, or a liveness query the
548/// platform cannot answer, reads as alive and the lock is left in place.
549pub(crate) struct FixClaim {
550    path: PathBuf,
551}
552
553impl FixClaim {
554    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
555        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
556        let path = dir.join("fix.lock");
557        let retry = crate::lock_file::Retry::new(None);
558        match Self::create(&path, retry) {
559            Ok(claim) => Ok(claim),
560            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
561                if Self::reclaim_if_dead(&path) {
562                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
563                } else {
564                    bail!(
565                        "another repair or `magi fix` is already running for this run ({} exists)",
566                        path.display()
567                    )
568                }
569            }
570            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
571        }
572    }
573
574    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
575        let mut f = retry.create(path)?;
576        use std::io::Write as _;
577        // Read back by `reclaim_if_dead` on a later, stuck invocation.
578        writeln!(f, "{}", std::process::id())?;
579        Ok(Self {
580            path: path.to_owned(),
581        })
582    }
583
584    /// True if the lock named a process confirmed dead, in which case it was
585    /// also removed. Never true on an unreadable file, an unparsable pid, or
586    /// a liveness query the platform cannot answer — see this type's own doc.
587    fn reclaim_if_dead(path: &Path) -> bool {
588        let dead = std::fs::read_to_string(path)
589            .ok()
590            .and_then(|body| body.trim().parse::<u32>().ok())
591            .is_some_and(|pid| !crate::proc::pid_alive(pid));
592        dead && std::fs::remove_file(path).is_ok()
593    }
594}
595
596impl Drop for FixClaim {
597    fn drop(&mut self) {
598        let _ = std::fs::remove_file(&self.path);
599    }
600}
601
602#[doc(hidden)]
603pub struct ExecutionLeaseGuard {
604    _lease: crate::driver::ExecutionLease,
605}
606
607#[doc(hidden)]
608pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
609    Ok(ExecutionLeaseGuard {
610        _lease: crate::driver::maintenance(home, run_id)?,
611    })
612}
613
614/// Holds the mutable runner as well as its durable lease: cancellation must
615/// clear both copies of ownership, including state a caller may save later.
616struct DriverExecution<'a> {
617    runner: &'a mut Runner,
618    driver: crate::driver::DriverGuard,
619}
620
621impl Drop for DriverExecution<'_> {
622    fn drop(&mut self) {
623        self.driver.release_local(&mut self.runner.state);
624    }
625}
626
627fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
628    if let Some(startup) = &mut state.startup {
629        startup.stage = stage.to_owned();
630    }
631    state.save()
632}
633
634/// Keep a reservation visible as blocked until startup finishes. A killed process
635/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
636struct StartupGuard {
637    id: String,
638    armed: bool,
639}
640
641impl StartupGuard {
642    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
643        state.startup = Some(crate::run::Startup {
644            kind: kind.to_owned(),
645            branch: branch.map(str::to_owned),
646            stage: "reserved".to_owned(),
647            complete: false,
648            failure: None,
649        });
650        state.status = RunStatus::Blocked;
651        state.reserve()?;
652        Ok(Self {
653            id: state.id.clone(),
654            armed: true,
655        })
656    }
657
658    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
659        startup_stage(state, stage)
660    }
661
662    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
663        let result = result.and_then(|()| {
664            state.startup.as_mut().expect("reserved startup").complete = true;
665            state.save()
666        });
667        self.armed = false;
668        match result {
669            Ok(()) => Ok(()),
670            Err(error) => {
671                let startup = state.startup.as_mut().expect("reserved startup");
672                startup.complete = false;
673                startup.failure = Some(format!("{error:#}"));
674                let context = crate::run::StartupFailure {
675                    run: state.id.clone(),
676                    stage: startup.stage.clone(),
677                };
678                // Repository assets may remain. Never infer that a failed startup
679                // is safe to resume or that an earlier owner has been restored.
680                state.status = RunStatus::Failed;
681                state.driver_exited = true;
682                state.event(
683                    "startup-failed",
684                    format!("{context}: {error:#}; retained assets require inspection"),
685                );
686                if let Err(save) = state.save() {
687                    tracing::warn!(
688                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
689                        state.id
690                    );
691                }
692                Err(error.context(context))
693            }
694        }
695    }
696}
697
698impl Drop for StartupGuard {
699    fn drop(&mut self) {
700        if self.armed
701            && let Ok(mut state) = RunState::load(&self.id)
702        {
703            state.status = RunStatus::Blocked;
704            state.driver_exited = true;
705            if let Some(startup) = &mut state.startup {
706                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
707            }
708            state.event(
709                "startup-interrupted",
710                "startup did not finish; inspect retained assets before recovery",
711            );
712            if let Err(error) = state.save() {
713                tracing::error!(
714                    "could not record interrupted startup {}: {error:#}",
715                    self.id
716                );
717            }
718        }
719    }
720}
721
722impl Runner {
723    /// A queue-side failure after construction must not strand an unexecuted run.
724    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
725        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
726            return error;
727        }
728        if let Some(startup) = &mut self.state.startup {
729            startup.stage = stage.to_owned();
730        } else {
731            // A resumed run already has execution history: do not rewrite it.
732            return error;
733        }
734        StartupGuard {
735            id: self.state.id.clone(),
736            armed: true,
737        }
738        .finish(&mut self.state, Err(error))
739        .expect_err("startup failed")
740    }
741
742    /// Start a fresh run against `repo`.
743    pub async fn start(
744        repo: &Path,
745        instruction: String,
746        config: Config,
747        origin: Origin,
748    ) -> Result<Self> {
749        Self::start_naming(repo, instruction, "", config, origin).await
750    }
751
752    /// [`Runner::start`] for a queued task. Titles and instructions never
753    /// select implementation sources. The title argument is retained for callers.
754    pub async fn start_naming(
755        repo: &Path,
756        instruction: String,
757        _also_scan: &str,
758        config: Config,
759        origin: Origin,
760    ) -> Result<Self> {
761        let repo = git::toplevel(repo).await?;
762        let missing = agent::missing_programs(&config.agents);
763        if !missing.is_empty() {
764            bail!(
765                "these agent programs are not on PATH: {}. Fix the roster in \
766                 magi.toml or install them.",
767                missing.join(", ")
768            );
769        }
770        let base_branch =
771            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
772                .await?;
773        let fetched_base = resolve_base(
774            &repo,
775            &base_branch,
776            &config.merge.remote,
777            config.coordination.as_ref(),
778        )
779        .await?;
780        let base_commit = fetched_base.commit.clone();
781        let roles = config.resolve_roles()?;
782        let max_parallel = config.graph.max_parallel.max(1);
783        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
784        // Capture task identity and repository assignment before the first
785        // save, so publication scope survives crashes and later task moves.
786        state.fetched_base = Some(fetched_base);
787        state.set_origin(origin)?;
788        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
789        state.status = RunStatus::Prep;
790        state.event("start", format!("run {} created", state.id));
791        startup.finish(&mut state, Ok(()))?;
792        Ok(Self {
793            state,
794            roles,
795            sem: Arc::new(Semaphore::new(max_parallel)),
796            pause: Pause::new(),
797            interrupt: Pause::new(),
798        })
799    }
800
801    /// Open a review-only run against work that already exists on `branch`.
802    ///
803    /// The expensive half of the graph is the implement wave — measured at
804    /// 111 and 134 internal tool-loop turns on this repository, against a
805    /// handful for a judge or a reviewer. The cheap half is worth running on
806    /// hand-written work too, and there was no way to reach it.
807    ///
808    /// No new state and no schema change are needed: a run with **one** viable
809    /// candidate and a tally already decided degrades `execute` to exactly
810    /// review → gate → merge, because `judge` skips a single-candidate field,
811    /// `deliberate` has fewer than two first choices to reconcile, `vote`
812    /// returns early, `tally` is already present and `fold_losers` has no
813    /// losers. Resuming such a run therefore does the right thing as well.
814    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
815        Self::review_taking_over(repo, branch, config, None, origin).await
816    }
817
818    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
819    /// at the same task still has `branch` checked out, its worktree is
820    /// released first if that is safe (see [`crate::handover`]), and the
821    /// review refuses with the reason if it is not. `None` is a hand-run
822    /// review: it has no earlier attempts, so only a worktree of a dead run
823    /// magi recorded itself can be released.
824    pub async fn review_taking_over(
825        repo: &Path,
826        branch: &str,
827        config: Config,
828        takeover: Option<crate::handover::Takeover>,
829        origin: Origin,
830    ) -> Result<Self> {
831        let repo = git::toplevel(repo).await?;
832        let missing = agent::missing_programs(&config.agents);
833        if !missing.is_empty() {
834            bail!(
835                "these agent programs are not on PATH: {}. Fix the roster in \
836                 magi.toml or install them.",
837                missing.join(", ")
838            );
839        }
840        let base_branch =
841            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
842                .await?;
843        if base_branch == branch {
844            bail!("`{branch}` is the base branch; there is nothing to review against");
845        }
846        let fetched_base = resolve_base(
847            &repo,
848            &base_branch,
849            &config.merge.remote,
850            config.coordination.as_ref(),
851        )
852        .await?;
853        let base_commit = fetched_base.commit.clone();
854
855        let roles = config.resolve_roles()?;
856        let max_parallel = config.graph.max_parallel.max(1);
857        let mut state = RunState::new(
858            repo.clone(),
859            base_branch,
860            base_commit.clone(),
861            format!("Review the work already on branch `{branch}`."),
862            config,
863        );
864        state.fetched_base = Some(fetched_base);
865        state.set_origin(origin)?;
866        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
867        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
868        let opened = async {
869            startup.stage(&mut state, "handover")?;
870
871            // Released before anything else touches the branch: a stale local
872            // branch is moved with `git branch -f`, which git refuses while an
873            // earlier attempt's worktree still has it checked out. Everything
874            // after this point that can fail puts the old run back.
875            // A hand-run review has no task, hence no earlier attempts, but a
876            // worktree of a dead run magi made may still be released.
877            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
878                earlier: Vec::new(),
879                home: crate::run::home(),
880                choice: None,
881                task_instruction: None,
882            });
883            let wait = repository_wait(&state, None);
884            let coordination_config = state.config.coordination.clone();
885            let coordination =
886                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
887                    .await?;
888            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
889            if let Some(released) = &released {
890                state.event(
891                    "release",
892                    format!(
893                        "took `{branch}` over from run {}: its worktree was released: {}",
894                        crate::run::short_of(&released.old_id),
895                        released.audit
896                    ),
897                );
898            }
899            let opened = async {
900                startup.stage(&mut state, "review-preflight")?;
901                // The owner's answer to an earlier divergence question is applied
902                // here: after the release (git will not move a checked-out branch)
903                // and before the sync that would otherwise ask again.
904                state.foreign_checkout = crate::handover::preflight_review(
905                    &repo,
906                    branch,
907                    &takeover.home,
908                    &state.config.merge.remote,
909                )
910                .await?;
911                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
912                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
913                }
914                if let Some(choice) = takeover.choice.as_ref()
915                    && let Err(e) =
916                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
917                            .await
918                {
919                    return Err(e.context("applying the owner's answer about the diverged branch"));
920                }
921                // An earlier attempt of this task that published the task head, and
922                // whose work is the branch under review, hands that head over: the
923                // review run updates the same pull request. Without one (a legacy
924                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
925                // own head and its own open pull request is adopted as before.
926                for id in takeover.earlier.iter().rev() {
927                    if let Ok(old) = RunState::load_under(id, &takeover.home)
928                        && let Some(head) = old.pr_head.clone()
929                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
930                    {
931                        state.pr_head = Some(head);
932                        break;
933                    }
934                }
935                drop(coordination);
936                startup.stage(&mut state, "open-review")?;
937                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
938            }
939            .await;
940            if opened.is_err()
941                && let Some(released) = &released
942            {
943                // Restoration is ownership checked and best effort. Keep the original
944                // startup cause even if reacquiring coordination is no longer possible.
945                match crate::repo_lock::SeatLease::operation_with(
946                    &repo,
947                    coordination_config.as_ref(),
948                    &wait,
949                )
950                .await
951                {
952                    Ok(_coordination) => {
953                        released.restore(&repo, branch).await;
954                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
955                            .map(|old| {
956                                format!(
957                                    "predecessor released_to={:?}; candidate path exists={}",
958                                    old.released_to,
959                                    old.candidates.iter().any(|c| {
960                                        c.branch == branch && c.worktree.exists()
961                                    }),
962                                )
963                            })
964                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
965                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
966                    }
967                    Err(error) => {
968                        tracing::warn!(
969                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
970                            state.id
971                        );
972                        state.event(
973                            "startup-restore",
974                            format!("restoration not attempted: {error:#}"),
975                        );
976                    }
977                }
978            }
979            opened
980        }
981        .await;
982        startup.finish(&mut state, opened)?;
983        Ok(Self {
984            state,
985            roles,
986            sem: Arc::new(Semaphore::new(max_parallel)),
987            pause: Pause::new(),
988            interrupt: Pause::new(),
989        })
990    }
991
992    /// Recover exactly the operator-selected public implementation, without touching old sources.
993    pub async fn recover_pr(
994        repo: &Path,
995        task: &str,
996        selection: crate::pr_recovery::Selection,
997        mut config: Config,
998    ) -> Result<Self> {
999        selection.configure(&mut config)?;
1000        let assignment = crate::run::task_assignment_for(task)?;
1001        selection.check_task_assignment(task, &selection.instruction, assignment)?;
1002        let base_branch =
1003            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1004                .await?;
1005        let fetched_base = resolve_base(
1006            repo,
1007            &base_branch,
1008            &config.merge.remote,
1009            config.coordination.as_ref(),
1010        )
1011        .await?;
1012        let base_commit = fetched_base.commit.clone();
1013        selection
1014            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1015            .await?;
1016        Box::pin(selection.verify_source(repo)).await?;
1017        if let Some(proof) = &selection.source_proof {
1018            anyhow::ensure!(
1019                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1020                "source rebase base is outside the fetched landing base"
1021            );
1022        }
1023        let roles = config.resolve_roles()?;
1024        let max_parallel = config.graph.max_parallel.max(1);
1025        let mut state = RunState::new(
1026            repo.to_path_buf(),
1027            base_branch,
1028            base_commit.clone(),
1029            selection.instruction.clone(),
1030            config,
1031        );
1032        state.fetched_base = Some(fetched_base);
1033        state.set_origin(crate::run::Origin::queue(task))?;
1034        state.pr_head = Some(selection.branch.clone());
1035        state.pr_recovery = Some(selection.clone());
1036        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1037    }
1038
1039    async fn open_selected(
1040        repo: &Path,
1041        mut state: RunState,
1042        roles: ResolvedRoles,
1043        max_parallel: usize,
1044        base_commit: String,
1045        selection: crate::pr_recovery::Selection,
1046    ) -> Result<Self> {
1047        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1048        let opened = async {
1049            startup.stage(&mut state, "predecessors")?;
1050            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1051            startup.stage(&mut state, "open-selected")?;
1052            let branch = state.branch_for('A');
1053            let wait = repository_wait(&state, None);
1054            let prepared = async {
1055                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1056                git::git(repo, &["branch", &branch, selection.source()]).await?;
1057                drop(coordination);
1058                anyhow::Ok(())
1059            }
1060            .await;
1061            prepared?;
1062            state.event(
1063                "recovery",
1064                format!(
1065                    "selected implementation {} for {} (public lease {})",
1066                    selection.source(),
1067                    selection.url,
1068                    selection.head
1069                ),
1070            );
1071            let takeover = crate::handover::Takeover {
1072                earlier: Vec::new(),
1073                home: crate::run::home(),
1074                choice: None,
1075                task_instruction: Some(selection.instruction.clone()),
1076            };
1077            state.save()?;
1078            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1079        }
1080        .await;
1081        startup.finish(&mut state, opened)?;
1082        Ok(Self {
1083            state,
1084            roles,
1085            sem: Arc::new(Semaphore::new(max_parallel)),
1086            pause: Pause::new(),
1087            interrupt: Pause::new(),
1088        })
1089    }
1090
1091    /// What the newest earlier attempt that reviewed `branch` leaves for this
1092    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1093    /// no earlier attempts. Reads the earlier record only: ownership of its
1094    /// worktree and branch is [`crate::handover`]'s business.
1095    async fn inherit(
1096        repo: &Path,
1097        branch: &str,
1098        base_commit: &str,
1099        takeover: &crate::handover::Takeover,
1100    ) -> Option<crate::recovery::RecoveryRecord> {
1101        use crate::recovery::{Relation, assess};
1102        let newest = takeover.earlier.last()?;
1103        let mut chosen = None;
1104        for id in takeover.earlier.iter().rev() {
1105            if let Ok(old) = RunState::load_under(id, &takeover.home)
1106                && !old.reviews.is_empty()
1107                && (old.winner().is_some_and(|w| w.branch == branch)
1108                    || old.pr_head.as_deref() == Some(branch))
1109            {
1110                chosen = Some(old);
1111                break;
1112            }
1113        }
1114        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1115            .await
1116            .unwrap_or_default();
1117        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1118            Some(last) if last.head == tip => Relation::Same,
1119            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1120            _ => Relation::Diverged,
1121        };
1122        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1123        Some(assess(from, chosen.as_ref(), base_commit, relation))
1124    }
1125
1126    /// The half of [`Runner::review_taking_over`] that can fail after an
1127    /// earlier attempt's worktree was released.
1128    async fn open_review(
1129        repo: &Path,
1130        branch: &str,
1131        state: &mut RunState,
1132        base_commit: String,
1133        takeover: &crate::handover::Takeover,
1134    ) -> Result<()> {
1135        startup_stage(state, "review-sync")?;
1136        let wait = repository_wait(state, None);
1137        let _coordination = coordinate_operation(state, repo, &wait).await?;
1138        if state.foreign_checkout.is_some() {
1139            // Never reconcile or force-move a ref checked out by the operator.
1140            if state.pr_head.is_none() {
1141                state.pr_head = Some(branch.to_owned());
1142            }
1143        } else if state.pr_recovery.is_none() {
1144            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1145        }
1146        // The commit subjects are the closest thing to a task statement that
1147        // existing work carries, and the reviewers are told as much.
1148        let start = review_base(
1149            repo,
1150            &state.config.merge.remote,
1151            &state.base_branch,
1152            &base_commit,
1153            branch,
1154        )
1155        .await;
1156        let log = git::log_oneline(repo, &start, branch)
1157            .await
1158            .unwrap_or_default();
1159        let log_text = if log.trim().is_empty() {
1160            "(no commit messages)"
1161        } else {
1162            log.trim()
1163        };
1164        let mut instruction = format!(
1165            "Review the work already on branch `{branch}`. There is no task \
1166             statement: what the change claims to do is whatever its commits \
1167             say.\n\n{log_text}"
1168        );
1169        // A retry of a task whose earlier attempt left reviews behind carries
1170        // that attempt's evidence, and the task's own statement with it: the
1171        // completion criteria are the task's, not whatever the commits claim.
1172        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1173            if let Some(task) = takeover
1174                .task_instruction
1175                .as_deref()
1176                .filter(|t| !t.trim().is_empty())
1177                && rec.reviewed_head.is_some()
1178            {
1179                instruction = format!(
1180                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1181                    task.trim()
1182                );
1183                rec.criteria_inherited = true;
1184            }
1185            state.event("recovery", rec.summary());
1186            state.recovery = Some(rec);
1187        }
1188        if let Some(selected) = &state.pr_recovery {
1189            instruction = selected.instruction.clone();
1190        }
1191        state.task_instruction = takeover.task_instruction.clone();
1192        state.instruction = instruction;
1193        state.reviewed_commits = Some(
1194            git::subjects(repo, &start, branch)
1195                .await
1196                .unwrap_or_default(),
1197        );
1198
1199        // A takeover must not forget a hold that a previous review observed,
1200        // even if repairs have since removed it from the branch.
1201        for id in &takeover.earlier {
1202            if let Ok(old) = RunState::load_under(id, &takeover.home)
1203                && old.repo == state.repo
1204                && (old.pr_head.as_deref() == Some(branch)
1205                    || old.winner().is_some_and(|w| w.branch == branch))
1206            {
1207                for hold in old.branch_owner_holds {
1208                    if !state.branch_owner_holds.contains(&hold) {
1209                        state.event(
1210                            "approval-policy",
1211                            format!(
1212                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1213                                hold.control.key(),
1214                                hold.file,
1215                                hold.head
1216                            ),
1217                        );
1218                        state.branch_owner_holds.push(hold);
1219                    }
1220                }
1221            }
1222        }
1223        // Select the actual review tip before observing owner policy. A foreign
1224        // checkout can lag its remote descendant, and repairs must not erase
1225        // holds introduced only on that selected commit.
1226        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1227            let tracking = format!("{}/{branch}", state.config.merge.remote);
1228            // A surviving tracking ref is not evidence that the remote still
1229            // offers this tip. Adopt it only after a successful fetch here.
1230            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1231            let mut head = checkout.synced_head.clone();
1232            if matches!(fetched, Ok(out) if out.ok()) {
1233                let remote = git::rev_parse(repo, &tracking).await?;
1234                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1235                    head = remote;
1236                }
1237            }
1238            head
1239        } else {
1240            git::rev_parse(repo, branch).await?
1241        };
1242        state.observe_branch_owner_holds(&reviewed_head).await;
1243
1244        // An attached worktree, so the fixer's commits land on the branch under
1245        // review rather than on a detached head nobody will look at again.
1246        let worktree = state.worktree_root().join("under-review");
1247        if let Some(parent) = worktree.parent() {
1248            tokio::fs::create_dir_all(parent).await.ok();
1249        }
1250        let path = worktree.to_string_lossy().to_string();
1251        let review_branch = if state.foreign_checkout.is_some() {
1252            let shadow = format!("magi/{}/review", state.short());
1253            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1254            shadow
1255        } else {
1256            branch.to_owned()
1257        };
1258        startup_stage(state, "review-checkout")?;
1259        git::git(repo, &["worktree", "add", &path, &review_branch])
1260            .await
1261            .with_context(|| {
1262                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1263            })?;
1264
1265        startup_stage(state, "worktree-setup")?;
1266        let setup = match ensure_setup_config(state, repo).await {
1267            Ok(()) => {
1268                worktree_setup::prepare_with(
1269                    &state.config,
1270                    repo,
1271                    &worktree,
1272                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1273                )
1274                .await
1275            }
1276            Err(e) => Err(e),
1277        };
1278        if let Err(e) = setup {
1279            git::worktree_remove_clean(repo, &worktree).await.ok();
1280            return Err(e);
1281        }
1282        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1283            .await
1284            .unwrap_or(0);
1285        if commits == 0 {
1286            git::worktree_remove_clean(repo, &worktree).await.ok();
1287            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1288        }
1289        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1290            .await
1291            .map(|f| f.len())
1292            .unwrap_or(0);
1293        if files == 0
1294            && let (Ok(head_tree), Ok(base_tree)) = (
1295                git::tree_of(&worktree, "HEAD").await,
1296                git::tree_of(&worktree, &base_commit).await,
1297            )
1298            && head_tree == base_tree
1299        {
1300            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1301            git::worktree_remove_clean(repo, &worktree).await.ok();
1302            bail!(
1303                "`{branch}` at {} has a tree identical to base {}; this usually means \
1304                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1305                 against `{}/{branch}`) rather than an empty change",
1306                short(&head),
1307                short(&base_commit),
1308                state.config.merge.remote
1309            );
1310        }
1311        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1312            .await
1313            .unwrap_or_default();
1314
1315        state.candidates.push(Candidate {
1316            index: 0,
1317            label: 'A',
1318            // Not an agent id on purpose: nothing in the roster wrote this, and
1319            // the stats tables must not credit anyone with a win for it.
1320            agent: EXISTING_BRANCH.to_owned(),
1321            branch: review_branch,
1322            worktree,
1323            summary: String::new(),
1324            stat,
1325            files,
1326            commits,
1327            empty: false,
1328            failed: None,
1329            verified_noop: None,
1330            duration_ms: 0,
1331            folded: false,
1332        });
1333        state.tally = Some(Tally {
1334            first_choice: BTreeMap::from([('A', 0)]),
1335            borda: BTreeMap::new(),
1336            winner: 'A',
1337            rankings: 0,
1338            unanimous_initial: false,
1339            deliberated: false,
1340            changed_votes: 0,
1341            unanimous_final: false,
1342            tie_break: None,
1343            // No panel sat, so no quorum applies. Zero judges is the correct
1344            // number for work that never competed, and must not be reported as
1345            // a collapsed panel.
1346            judges: 0,
1347            present: 0,
1348            quorum: 0,
1349            met_quorum: true,
1350            uncontested: Some("review-only run: nothing competed".to_owned()),
1351        });
1352        state.status = RunStatus::Reviewing;
1353        state.prep_complete = Some(true);
1354        state.event(
1355            "start",
1356            format!(
1357                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1358                state.id
1359            ),
1360        );
1361        Ok(())
1362    }
1363
1364    /// Authorize one bounded synchronization interval, under the caller's queue task
1365    /// claim and the same owner/execution locks used by run maintenance.
1366    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1367        Self::authorize_base_recovery_request(home, id, task, false, None).await
1368    }
1369
1370    /// Queue release uses its durable approval generation exactly once.
1371    pub(crate) async fn authorize_base_recovery_from_resumption(
1372        home: &Path,
1373        id: &str,
1374        task: &str,
1375    ) -> Result<()> {
1376        Self::authorize_base_recovery_request(home, id, task, true, None).await
1377    }
1378
1379    pub(crate) async fn authorize_base_recovery_control(
1380        home: &Path,
1381        task: &str,
1382        control: &mut crate::base_recovery_control::Transaction,
1383    ) -> Result<()> {
1384        let id = control.request.run.clone();
1385        Self::authorize_base_recovery_request(home, &id, task, false, Some(control)).await
1386    }
1387
1388    async fn authorize_base_recovery_request(
1389        home: &Path,
1390        id: &str,
1391        task: &str,
1392        resumption: bool,
1393        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1394    ) -> Result<()> {
1395        let _owner = crate::pr_head::owner_lock(home, id)?;
1396        let mut state = RunState::load_under(id, home)?;
1397        crate::pr_head::ensure_owner(&state)?;
1398        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1399        anyhow::ensure!(
1400            queued.execution_runs().last().is_some_and(|run| run == id)
1401                && queued.status != crate::queue::TaskStatus::Done
1402                && !queued.fresh_start
1403                && queued.review_branch.is_none(),
1404            "run task ownership changed"
1405        );
1406        anyhow::ensure!(
1407            state
1408                .origin
1409                .as_ref()
1410                .and_then(|o| o.task.as_deref())
1411                .is_none_or(|owner| owner == task),
1412            "run belongs to another task"
1413        );
1414        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1415        anyhow::ensure!(
1416            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1417            "run is live or its ownership is unknown"
1418        );
1419        // Judge the previous driver's lease before acquiring our maintenance
1420        // lease. The owner lock excludes new driver claims across both steps.
1421        let _execution = crate::driver::maintenance(home, id)?;
1422        anyhow::ensure!(
1423            state.status.resumable()
1424                && state.released_to.is_none()
1425                && state.retired_to.is_none()
1426                && state.pr_taken_over_by.is_none(),
1427            "run ownership is final"
1428        );
1429        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1430        anyhow::ensure!(
1431            !state.pr_publication_pending
1432                && !crate::handover::landing_checkpoint(&state)
1433                && state.merge_decision.is_none(),
1434            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1435        );
1436        let winner = state.winner().context("run has no retained winner")?;
1437        anyhow::ensure!(
1438            git::is_clean(&winner.worktree).await?,
1439            "retained worktree has uncommitted changes"
1440        );
1441        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1442        anyhow::ensure!(
1443            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1444            "retained worktree does not match the winner branch"
1445        );
1446        if let Some(control) = control.as_ref() {
1447            anyhow::ensure!(
1448                head.starts_with(&control.request.head),
1449                "retained HEAD changed since the owner request"
1450            );
1451            anyhow::ensure!(
1452                state
1453                    .base_sync_recovery
1454                    .stop
1455                    .as_ref()
1456                    .is_none_or(|stop| stop.head == head),
1457                "retained HEAD differs from the recorded stop head; inspect it first"
1458            );
1459        }
1460        state.ensure_base_episode();
1461        state.record_base_sync_stop(&head);
1462        anyhow::ensure!(
1463            state
1464                .base_sync_recovery
1465                .stop
1466                .as_ref()
1467                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted),
1468            "base recovery refused: missing eligible movement-exhaustion evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1469        );
1470        let fetched =
1471            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1472        anyhow::ensure!(
1473            fetched.ok(),
1474            "cannot authorize base recovery without a fetched base"
1475        );
1476        let approved_tip = git::rev_parse(
1477            &state.repo,
1478            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1479        )
1480        .await?;
1481        if let Some(control) = control.as_deref_mut() {
1482            let queue = crate::queue::Queue::at(home.join("queue"));
1483            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1484            if let Some(prior) = state
1485                .base_sync_recovery
1486                .authorizations
1487                .iter()
1488                .find(|a| a.request.as_deref() == Some(&control.key()))
1489            {
1490                anyhow::ensure!(
1491                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1492                    "recovery request was consumed or invalidated; it cannot queue again"
1493                );
1494                return control.enqueue(&queue);
1495            }
1496        }
1497        if resumption {
1498            anyhow::ensure!(
1499                crate::daemon::compatible_run_instruction(&state, &queued),
1500                "resumption instruction does not match the retained run"
1501            );
1502            let approval = queued
1503                .resumption
1504                .as_ref()
1505                .context("no operator resumption")?;
1506            anyhow::ensure!(
1507                approval.instruction == queued.instruction,
1508                "resumption approval does not match the current task instruction"
1509            );
1510            state.authorize_base_sync_resumption(task, approval)?;
1511        } else {
1512            state.authorize_base_sync(task)?;
1513        }
1514        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1515        state
1516            .base_sync_recovery
1517            .authorizations
1518            .last_mut()
1519            .unwrap()
1520            .scope = Some(crate::base_sync_recovery::Scope {
1521            tip: approved_tip,
1522            instruction: queued.instruction.clone(),
1523            episode,
1524        });
1525        if let Some(control) = control.as_deref_mut() {
1526            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1527            authorization.request = Some(control.key());
1528            authorization.generation = control.generation();
1529            authorization.decision = control.decision();
1530            authorization.question = control
1531                .request
1532                .decision
1533                .as_ref()
1534                .map(|_| control.request.request.clone());
1535        }
1536        state.event(
1537            "base-recovery",
1538            "owner authorized a bounded base synchronization interval; fresh verification required",
1539        );
1540        state.save_under(home)?;
1541        if let Some(control) = control {
1542            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1543        }
1544        Ok(())
1545    }
1546
1547    /// Reopen an existing run.
1548    pub fn resume(id: &str) -> Result<Self> {
1549        let state = RunState::load(id)?;
1550        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1551        if state.startup.as_ref().is_some_and(|s| !s.complete)
1552            || (state.status == RunStatus::Prep
1553                && state.instruction.trim().is_empty()
1554                && state.candidates.is_empty()
1555                && state.prep_complete == Some(false))
1556        {
1557            bail!(
1558                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1559            );
1560        }
1561        crate::pr_head::ensure_owner(&state)?;
1562        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1563            bail!(
1564                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1565            );
1566        }
1567        if let Some(to) = &state.released_to {
1568            bail!(
1569                "run {} cannot be resumed: its worktree was released to run {}",
1570                state.short(),
1571                crate::run::short_of(to)
1572            );
1573        }
1574        let roles = state.config.resolve_roles()?;
1575        if let Some(id) = &state.config.graph.selected_implementer
1576            && state.candidates.iter().any(|c| c.agent != *id)
1577        {
1578            bail!(
1579                "replacement implementer pin does not match the saved candidates; task must stay held"
1580            );
1581        }
1582        let max_parallel = state.config.graph.max_parallel.max(1);
1583        Ok(Self {
1584            state,
1585            roles,
1586            sem: Arc::new(Semaphore::new(max_parallel)),
1587            pause: Pause::new(),
1588            interrupt: Pause::new(),
1589        })
1590    }
1591
1592    /// Walk the graph to a terminal state, skipping nodes already recorded.
1593    ///
1594    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1595    /// the phone - ends here, so this is the one place a run that ended
1596    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1597    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1598    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1599        // Allocate before polling: boxing inside an async wrapper would still
1600        // retain its construction frame while the nested graph is polled.
1601        Box::pin(self.execute_inner(None))
1602    }
1603
1604    pub(crate) async fn execute_sync_only(
1605        &mut self,
1606        request: crate::base_sync_only::Request,
1607    ) -> Result<()> {
1608        Box::pin(self.execute_inner(Some(request))).await
1609    }
1610
1611    async fn execute_inner(
1612        &mut self,
1613        sync_only: Option<crate::base_sync_only::Request>,
1614    ) -> Result<()> {
1615        anyhow::ensure!(
1616            self.state.startup.as_ref().is_none_or(|s| s.complete),
1617            "startup incomplete; inspect retained evidence before explicit recovery"
1618        );
1619        if let Some(selection) = &self.state.pr_recovery
1620            && (selection.source_proof.is_some() || selection.source_run.is_some())
1621        {
1622            Box::pin(selection.verify_source(&self.state.repo)).await?;
1623        }
1624        // Queue claims cover daemon work; this also serializes manual drivers
1625        // consuming a repair answer, including the new review and decision.
1626        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1627            || self.state.land_approval.is_some()
1628            || self.state.merge_decision.is_some()
1629            || !self.state.merge_repairs.is_empty()
1630            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1631        {
1632            let claim = FixClaim::acquire(&self.state.dir())?;
1633            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1634            let disk = RunState::load(&self.state.id)?;
1635            let checkpoint = |s: &RunState| {
1636                (
1637                    s.merge_repairs.len(),
1638                    s.merge_repairs
1639                        .last()
1640                        .map(|r| (r.question.clone(), r.phase)),
1641                    s.land_approval
1642                        .as_ref()
1643                        .map(|a| (a.question.clone(), a.head.clone())),
1644                )
1645            };
1646            if checkpoint(&disk) != checkpoint(&self.state) {
1647                bail!(
1648                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1649                );
1650            }
1651            Some(claim)
1652        } else {
1653            None
1654        };
1655        let base_only = sync_only.is_some();
1656        let mut execution = self.claim_driver(sync_only).await?;
1657        let runner = &mut *execution.runner;
1658        let wait = runner.repository_wait();
1659        // Keep the graph's large future off the callers' stack, including
1660        // standalone task attempts running on a default-sized test thread.
1661        let result = if base_only {
1662            wait.scope(Box::pin(async {
1663                let repo = runner.state.repo.clone();
1664                let result = async {
1665                    let _coordination = runner.coordinate(&repo).await?;
1666                    anyhow::ensure!(
1667                        !runner.pause.parked() && !runner.interrupt.parked(),
1668                        "paused before base synchronization"
1669                    );
1670                    crate::base_sync_only::sync(&mut runner.state).await
1671                }
1672                .await;
1673                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1674                pass.result = match result {
1675                    Ok(outcome) => outcome,
1676                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1677                };
1678                let summary = pass.summary();
1679                runner.state.event("base-sync-only", summary);
1680                runner.state.save()
1681            }))
1682            .await
1683        } else {
1684            wait.scope(Box::pin(runner.execute_graph())).await
1685        };
1686        let result = match result {
1687            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1688                record_repository_block(&mut runner.state, &e);
1689                runner.park_here()?;
1690                Ok(())
1691            }
1692            other => other,
1693        };
1694        execution.driver.finish(&mut runner.state).await?;
1695        let ended = if result.is_err() {
1696            Some({
1697                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1698                if let Err(error) = &result {
1699                    notice.message = format!(
1700                        "Run {} stopped with an error: {}",
1701                        runner.state.id,
1702                        error.to_string().lines().next().unwrap_or("unknown error")
1703                    );
1704                }
1705                notice
1706            })
1707        } else {
1708            crate::notices::run_ended(&runner.state)
1709        };
1710        if let Some(notice) = ended {
1711            crate::notices::raise(notice);
1712        }
1713        result
1714    }
1715
1716    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1717        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1718    }
1719
1720    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1721        let wait = self.repository_wait();
1722        coordinate_operation(&mut self.state, cwd, &wait).await
1723    }
1724
1725    /// Validate ownership and persist the driver claim in one critical section.
1726    async fn claim_driver(
1727        &mut self,
1728        sync_only: Option<crate::base_sync_only::Request>,
1729    ) -> Result<DriverExecution<'_>> {
1730        let owner = match crate::pr_head::owner_lock_wait(
1731            &crate::run::home(),
1732            &self.state.id,
1733            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1734        )
1735        .await
1736        {
1737            Ok(owner) => owner,
1738            Err(error) => {
1739                let detail = format!("worktree maintenance or ownership update: {error:#}");
1740                // Admission did not own run.json: retain this resource outcome
1741                // in memory for queue settlement without overwriting a concurrent
1742                // retirement or publication transaction.
1743                self.state.resource_block = Some(crate::run::ResourceBlock {
1744                    cause: crate::run::ResourceBlockCause::Other,
1745                    node: "start".into(),
1746                    kind: "worktree maintenance".into(),
1747                    detail: detail.clone(),
1748                    at: Timestamp::now(),
1749                });
1750                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1751            }
1752        };
1753        let disk = RunState::load(&self.state.id)?;
1754        crate::pr_head::ensure_owner(&disk)?;
1755        let claimed =
1756            crate::daemon::is_working_on_other(&crate::run::home(), &disk.id, Timestamp::now())?;
1757        // Only proven-live ownership refuses here. Unknown records (legacy runs
1758        // with no claim marker or process identity) fall through to the
1759        // exclusive execution lease taken just below, which is what actually
1760        // keeps a second driver out.
1761        anyhow::ensure!(
1762            disk.liveness(claimed) != crate::run::Liveness::Live,
1763            "run already has a live driver; wait for its execution to end"
1764        );
1765        if let Some(to) = &disk.released_to {
1766            bail!(
1767                "run {} cannot continue: its worktree was released to run {}",
1768                self.state.short(),
1769                crate::run::short_of(to)
1770            );
1771        }
1772        anyhow::ensure!(
1773            serde_json::to_value(&disk.base_sync_recovery)?
1774                == serde_json::to_value(&self.state.base_sync_recovery)?,
1775            "base recovery changed since this run was loaded; reload the saved run"
1776        );
1777        anyhow::ensure!(
1778            disk.sync_only_passes == self.state.sync_only_passes,
1779            "base-only synchronization changed since this run was loaded; reload the saved run"
1780        );
1781        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1782        let mut execution = DriverExecution {
1783            runner: self,
1784            driver,
1785        };
1786        // Declare after the execution guard: on any claim error this short
1787        // lock must drop before that guard reloads and releases ownership.
1788        let _owner = owner;
1789        if let Some(request) = sync_only {
1790            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1791            anyhow::ensure!(
1792                request.run == disk.id,
1793                "sync-base-only request targets a different run"
1794            );
1795            let state = &mut execution.runner.state;
1796            let task_entry = state.next_pass_task_entry;
1797            *state = disk;
1798            state.next_pass_task_entry = task_entry;
1799            if state.pending_sync_only().is_some() {
1800                let pass_index = state.passes.len();
1801                let pass = state.sync_only_passes.last_mut().unwrap();
1802                anyhow::ensure!(
1803                    pass.request == request,
1804                    "interrupted base-only synchronization belongs to a different request"
1805                );
1806                pass.pass_index = pass_index;
1807            } else {
1808                let pass = crate::base_sync_only::Pass::new(request, state);
1809                state.sync_only_passes.push(pass);
1810            }
1811            if state.status == RunStatus::Failed {
1812                state.status = RunStatus::Blocked;
1813            }
1814        } else {
1815            anyhow::ensure!(
1816                disk.pending_sync_only().is_none(),
1817                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1818            );
1819            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1820                .await?;
1821        }
1822        let state = &mut execution.runner.state;
1823        // Moving again, so it is no longer parked. Set before the walk rather
1824        // than in `resume`, so every way of re-entering the graph clears it
1825        // and a card cannot claim a run is waiting to be resumed while the
1826        // agents are already working.
1827        state.parked = false;
1828        state.resource_wait = None;
1829        state.resource_block = None;
1830        // Any seat this state still lists as answering belongs to whatever
1831        // process last drove this run — this one included, if it crashed
1832        // mid-wave. Cleared and flushed immediately, before anything else
1833        // runs, so a resume can never show a seat as live when nothing is
1834        // asking it anything yet; the node that actually dispatches the next
1835        // wave repopulates it.
1836        state.clear_active();
1837        // Recorded in the same spot, and flushed together with the clear
1838        // above: this is the pid a reader checks (`RunState::liveness`) when
1839        // no daemon claim exists to answer "is a process still driving this
1840        // run" — a plain `magi run` / `magi review` typed into a terminal
1841        // claims nothing there. Always overwritten, never only-if-absent, so
1842        // a resumed run's stale pid from a previous, possibly-dead process
1843        // can never survive into this one's own report. Unlike
1844        // `clear_active`, this changes on every single `execute()` call, so
1845        // the save below is now unconditional rather than only-if-cleared.
1846        //
1847        // `driver_started_at` is recorded in the same breath, from this same
1848        // pid, so `liveness` can tell a live pid that is genuinely still us
1849        // apart from one the OS has since handed to an unrelated process —
1850        // see that field's own doc for why the pid alone is not enough.
1851        let pid = std::process::id();
1852        state.driver_pid = Some(pid);
1853        state.driver_started_at = crate::proc::process_started_at(pid);
1854        state.driver_exited = false;
1855        state.driver_claimed = Some(true);
1856        state.begin_pass();
1857        execution.driver.bind(state);
1858        state.save()?;
1859        execution.driver.record(state)?;
1860        Ok(execution)
1861    }
1862
1863    /// No conflict checkpoint proves dispatch was never reached. End that
1864    /// consumed generation so an owner can explicitly authorize a fresh one.
1865    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1866        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1867        if let Err(error) = &result
1868            && !error.is::<crate::repo_lock::ResourceBlocked>()
1869            && self
1870                .state
1871                .repair_grants
1872                .last()
1873                .is_some_and(|g| g.conflict.is_none())
1874        {
1875            self.state.repair_grants.last_mut().unwrap().phase =
1876                crate::repair_budget::Phase::Complete;
1877            self.state.status = RunStatus::Blocked;
1878            self.state.save()?;
1879            bail!(
1880                "{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",
1881                self.state.passes.last().map_or(0, |p| p.index)
1882            );
1883        }
1884        result
1885    }
1886
1887    /// A grant owns only these repair attempts. Confirmation reviews cannot
1888    /// create another fixer allowance, and every operation is restart-checkpointed.
1889    async fn execute_granted_repair(&mut self) -> Result<()> {
1890        use crate::repair_budget::{Kind, Phase};
1891        let index = self.state.repair_grants.len() - 1;
1892        let winner = self
1893            .state
1894            .winner()
1895            .cloned()
1896            .context("repair winner missing")?;
1897        loop {
1898            let grant = self.state.repair_grants[index].clone();
1899            match grant.phase {
1900                Phase::Pending => {
1901                    if grant.spent >= grant.receipt.request.rounds {
1902                        self.state.repair_grants[index].phase = Phase::Complete;
1903                        self.state.status = RunStatus::Blocked;
1904                        self.state.save()?;
1905                        return Ok(());
1906                    }
1907                    // Reserve before dispatch. A crash can consume an attempt,
1908                    // but can never duplicate it or reset saved fixer history.
1909                    self.state.repair_grants[index].spent += 1;
1910                    self.state.repair_grants[index].phase = Phase::Fixing;
1911                    self.state.save()?;
1912                    match grant.receipt.request.kind {
1913                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1914                        Kind::Gate => {
1915                            let failed = self.state.gate.clone();
1916                            let _ = self.gate_fix_round(&winner, &failed).await?;
1917                        }
1918                        Kind::Review => {
1919                            let mut record = self
1920                                .state
1921                                .reviews
1922                                .last()
1923                                .cloned()
1924                                .context("review failure missing")?;
1925                            let round = record.round;
1926                            let step = self.run_fix_round(&winner, &mut record).await?;
1927                            self.state.reviews[round - 1] = record;
1928                            if matches!(step, FixStep::Recorded { report_lost: true }) {
1929                                self.state.repair_grants[index].phase = Phase::Complete;
1930                                self.state.status = RunStatus::Blocked;
1931                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
1932                                self.state.save()?;
1933                                return Ok(());
1934                            }
1935                            if matches!(step, FixStep::Resource) {
1936                                self.stop_for_resource()?;
1937                                return Ok(());
1938                            }
1939                            self.state.save()?;
1940                        }
1941                    }
1942                    if self.resource_halt()? {
1943                        return Ok(());
1944                    }
1945                }
1946                Phase::Fixing => {
1947                    if grant.receipt.request.kind == Kind::BaseConflict {
1948                        self.repair_base_conflict(false).await?;
1949                    }
1950                    // Interrupted fixers may have left source changes or an
1951                    // unpushed commit. Preserve them before fresh assessment.
1952                    let _coordination = self.coordinate(&winner.worktree).await?;
1953                    let rescued = git::rescue_commit(
1954                        &winner.worktree,
1955                        "magi: preserve interrupted granted repair",
1956                    )
1957                    .await?;
1958                    self.state.note_withheld("repair-grant", &rescued.withheld);
1959                    // Fresh checks must supersede even a same-head failure.
1960                    // Archive rather than erase failure evidence or counters.
1961                    self.state
1962                        .verification_history
1963                        .push(crate::run::VerificationEvidence {
1964                            superseded_by: None,
1965                            archived_at: Some(Timestamp::now()),
1966                            fixes_spent: Some(self.state.gate_fixes.len()),
1967                            gate_head: self.state.gate_head.take(),
1968                            gate_ran: std::mem::take(&mut self.state.gate_ran),
1969                            gate: std::mem::take(&mut self.state.gate),
1970                            e2e: self.state.head_e2e.take(),
1971                        });
1972                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
1973                        self.state
1974                            .verification_history
1975                            .push(crate::run::VerificationEvidence {
1976                                superseded_by: None,
1977                                archived_at: Some(Timestamp::now()),
1978                                fixes_spent: Some(self.state.gate_fixes.len()),
1979                                gate_head: None,
1980                                gate_ran: false,
1981                                gate: Vec::new(),
1982                                e2e: Some(e2e),
1983                            });
1984                    }
1985                    self.state.repair_grants[index].review_start = self.state.reviews.len();
1986                    self.state.repair_grants[index].head =
1987                        git::rev_parse(&winner.worktree, "HEAD").await?;
1988                    self.state.repair_grants[index].phase = Phase::Reviewing;
1989                    if grant.receipt.request.kind == Kind::BaseConflict {
1990                        self.state.base_sync_recovery.stop = None;
1991                        if let Some(sync) = &mut self.state.base_sync {
1992                            sync.tip = grant
1993                                .receipt
1994                                .request
1995                                .tip
1996                                .clone()
1997                                .context("repair base tip missing")?;
1998                            sync.conflict = None;
1999                            sync.behind = 0;
2000                        }
2001                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2002                    }
2003                    self.state.save()?;
2004                }
2005                Phase::Reviewing => {
2006                    self.review_loop_pass().await?;
2007                    if self.resource_halt()? {
2008                        return Ok(());
2009                    }
2010                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2011                    let clean = self.state.reviews.len() > grant.review_start
2012                        && self.state.reviews.last().is_some_and(|r| {
2013                            r.head == head
2014                                && r.clean
2015                                && r.expected > 0
2016                                && r.answered == r.expected
2017                                && matches!(
2018                                    r.e2e_status(),
2019                                    E2eStatus::Passed | E2eStatus::NotConfigured
2020                                )
2021                        });
2022                    if !clean {
2023                        // A confirmation review carries no additional fix budget.
2024                        self.state.repair_grants[index].phase = if grant.receipt.request.kind
2025                            == Kind::Review
2026                            && grant.spent < grant.receipt.request.rounds
2027                            && self.state.reviews.last().is_some_and(|r| {
2028                                r.fix.is_none()
2029                                    && (r.blocking > 0 || r.e2e_status() == E2eStatus::Failed)
2030                            }) {
2031                            Phase::Pending
2032                        } else {
2033                            Phase::Complete
2034                        };
2035                        self.state.status = RunStatus::Blocked;
2036                        self.state.event(
2037                            "repair-grant",
2038                            "fresh review did not clear the repaired head; no publication",
2039                        );
2040                        self.state.save()?;
2041                        if self.state.repair_grants[index].phase == Phase::Pending {
2042                            continue;
2043                        }
2044                        return Ok(());
2045                    }
2046                    self.state.repair_grants[index].phase = Phase::Gating;
2047                    self.state.save()?;
2048                }
2049                Phase::Gating => {
2050                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2051                    self.state.reconcile_verification_head(&head);
2052                    let wait = self.repository_wait();
2053                    if self
2054                        .state
2055                        .reviews
2056                        .last()
2057                        .is_none_or(|r| r.head != head || !r.clean)
2058                    {
2059                        self.state.status = RunStatus::Blocked;
2060                        self.state.repair_grants[index].phase = Phase::Complete;
2061                        self.state.event(
2062                            "repair-grant",
2063                            "head changed since fresh review; repair held",
2064                        );
2065                        self.state.save()?;
2066                        return Ok(());
2067                    }
2068                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2069                        return Ok(());
2070                    }
2071                    let outcomes = self.run_gate(&winner).await?;
2072                    if verify_inconclusive(&outcomes) {
2073                        return Ok(());
2074                    }
2075                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2076                    if after != head {
2077                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2078                        self.state.repair_grants[index].head = after;
2079                        self.state.repair_grants[index].phase = Phase::Reviewing;
2080                        self.state.status = RunStatus::Blocked;
2081                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2082                        self.state.save()?;
2083                        return Ok(());
2084                    }
2085                    let passed = outcomes.iter().all(CommandOutcome::ok);
2086                    // Follow-up grants owe the same guarded checkout delivery
2087                    // as the conflict repair that introduced the new head.
2088                    if passed
2089                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2090                    {
2091                        return Ok(());
2092                    }
2093                    self.state.repair_grants[index].succeeded = passed;
2094                    self.state.gate = outcomes;
2095                    self.state.gate_ran = true;
2096                    self.state.status = if passed {
2097                        RunStatus::Gating
2098                    } else {
2099                        RunStatus::Blocked
2100                    };
2101                    self.state.repair_grants[index].phase = if !passed
2102                        && grant.receipt.request.kind == Kind::Gate
2103                        && grant.spent < grant.receipt.request.rounds
2104                    {
2105                        Phase::Pending
2106                    } else {
2107                        Phase::Complete
2108                    };
2109                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2110                        // Persist publication debt with the successful checkpoint.
2111                        self.state.pr_publication_pending = true;
2112                    } else if passed {
2113                        self.state.status = RunStatus::Ready;
2114                    }
2115                    self.state.save()?;
2116                    if !passed {
2117                        continue;
2118                    }
2119                    // Existing PR ownership and push lease stay in place. The
2120                    // normal publisher owes the new reviewed/gated SHA, and
2121                    // land's fresh owner approval remains mandatory.
2122                    if self.state.config.merge.mode != MergeMode::Pr {
2123                        self.state.status = RunStatus::Ready;
2124                        self.state.event(
2125                            "repair-grant",
2126                            "repair verified locally; grant carries no merge authorization",
2127                        );
2128                        self.state.save()?;
2129                        return Ok(());
2130                    }
2131                    return self.merge().await;
2132                }
2133                Phase::Complete => return Ok(()),
2134            }
2135        }
2136    }
2137
2138    async fn execute_graph(&mut self) -> Result<()> {
2139        // Even a terminal run may reenter through an explicit recovery action.
2140        // Restore before prep shortcuts, saved conversations or graph nodes use
2141        // a disposable path; GC may already have removed its original objects.
2142        let archive_home = crate::run::home().canonicalize()?;
2143        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2144            let repo = self.state.repo.clone();
2145            let _coordination = self.coordinate(&repo).await?;
2146            ensure_setup_config(&mut self.state, &repo).await?;
2147            crate::retention::restore_execution_seats(
2148                &archive_home,
2149                &self.state,
2150                _coordination.as_ref(),
2151            )
2152            .await?;
2153        }
2154        self.state.configure_recovery_resume()?;
2155        if self
2156            .state
2157            .repair_grants
2158            .last()
2159            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2160        {
2161            return self.execute_granted_repair().await;
2162        }
2163        if self
2164            .state
2165            .repair_grants
2166            .last()
2167            .is_some_and(|g| !g.succeeded)
2168        {
2169            self.state.status = RunStatus::Blocked;
2170            self.state.save()?;
2171            return Ok(());
2172        }
2173        // Preservation may invalidate an old empty classification. Resolve it
2174        // before any resume shortcut can reuse a verdict or publish a branch.
2175        self.persist_candidates().await?;
2176        // A saved base stop outranks stage markers, including legacy Voting.
2177        // Recovery never reenters implementation, deliberation or voting.
2178        if self.state.base_sync_blocked() {
2179            self.sync_to_base().await?;
2180            if !self.state.base_sync_blocked()
2181                && self.state.status != RunStatus::AlreadyInBase
2182                && !self.resource_halt()?
2183            {
2184                self.finish_after_tally().await?;
2185            }
2186            return Ok(());
2187        }
2188        if self
2189            .state
2190            .merge_decision
2191            .as_ref()
2192            .is_some_and(|decision| !decision.closed)
2193            && self.state.status != RunStatus::Landing
2194        {
2195            if crate::merge_decision::resumable_hold(&self.state) {
2196                self.state.merge = Some(MergeOutcome {
2197                    mode: MergeMode::Pr,
2198                    ok: false,
2199                    detail: self
2200                        .state
2201                        .merge_decision
2202                        .as_ref()
2203                        .unwrap()
2204                        .target
2205                        .pr
2206                        .clone(),
2207                    empty: false,
2208                });
2209                self.run_land().await?;
2210                self.settle_questions();
2211                return Ok(());
2212            }
2213            bail!(
2214                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2215            );
2216        }
2217        if self.state.config.graph.selected_implementer.is_some()
2218            && self.state.status == RunStatus::Blocked
2219            && self.state.tally.is_none()
2220            && self.state.candidate_preservation.is_empty()
2221            && self.state.interrupted_implementations.is_empty()
2222        {
2223            bail!(
2224                "selected implementation is held; explicitly release the owning task to retry it"
2225            );
2226        }
2227
2228        if self.state.merge_repairs.last().is_some_and(|r| {
2229            matches!(
2230                r.phase,
2231                crate::run::MergeRepairPhase::Requested
2232                    | crate::run::MergeRepairPhase::Fixing
2233                    | crate::run::MergeRepairPhase::Reviewing
2234            )
2235        }) {
2236            if self.repair_merge_review().await? {
2237                self.run_land().await?;
2238            }
2239            self.settle_questions();
2240            return Ok(());
2241        }
2242        // Publication already passed review and gate. Resume only that node:
2243        // syncing to a newer base here could change the verified commit.
2244        if self.state.pr_publication_pending {
2245            self.merge().await?;
2246            if self.resource_halt()? {
2247                return Ok(());
2248            }
2249            self.state.save()?;
2250            self.settle_questions();
2251            return Ok(());
2252        }
2253        // A run that already lost its quorum never resumes into the verdict
2254        // machinery: `deliberate` and `vote` would otherwise clobber the
2255        // stalled marker back to Voting and the run would keep going past a
2256        // verdict that is no longer trustworthy. Everything already recorded is
2257        // kept, so the run stays resumable (or foldable) for a human to pick up.
2258        //
2259        // On --resume the run gets one chance to repair itself: the seats a
2260        // rate limit took out are re-asked. If their quota has since reset and
2261        // the quorum is restored, the run picks up and finishes; otherwise it
2262        // stays stale and still-resumable for a later retry. If it does not
2263        // recover, the returned status stays `Stalled` and nothing was
2264        // clobbered (the recovery only mutates entries for the lost seats).
2265        if self.state.status == RunStatus::Stalled {
2266            if self.recover_stall().await? {
2267                self.finish_after_tally().await?;
2268            } else {
2269                // Still below quorum: persist the marker and stay resumable.
2270                self.state.save()?;
2271            }
2272            return Ok(());
2273        }
2274        // A run parked inside `land` - watching CI, mid fix-round, or
2275        // waiting on the owner's merge approval - resumes directly into it,
2276        // never back through `prep`. Everything before `merge` already
2277        // concluded; that is the only way `status` reaches `Landing` in the
2278        // first place. Re-walking `review_loop` first would also be actively
2279        // wrong: its own status recomputation (see its doc) treats any
2280        // clean round as reason to set `status` to `Gating`, which would
2281        // clobber this marker before `merge` ever ran, and this run would
2282        // never find its way back into `land` at all.
2283        if self.state.status == RunStatus::Landing
2284            || crate::handover::landing_checkpoint(&self.state)
2285        {
2286            self.state.land_sync_pending = true;
2287            self.state.save()?;
2288            self.run_land().await?;
2289            // `run_land` may have settled the run right here - CI came back
2290            // green and the PR merged, say - without ever passing back
2291            // through `merge`'s own trailing call. Whatever it left `status`
2292            // as is what this has to read.
2293            self.settle_questions();
2294            return Ok(());
2295        }
2296        // A run parked at `merge` on the owner's word about a withheld PR text
2297        // resumes straight into `merge`. Re-walking the tail would sync to the
2298        // base again (possibly rebasing, possibly spending the fixer) after the
2299        // gate had passed, and then push a tree nobody reviewed or gated.
2300        if self.state.github_text.is_some()
2301            && self.state.merge.is_none()
2302            && self.state.status == RunStatus::Gating
2303        {
2304            self.merge().await?;
2305            if self.resource_halt()? {
2306                return Ok(());
2307            }
2308            self.state.save()?;
2309            return Ok(());
2310        }
2311        if let Err(e) = self.prep().await {
2312            if e.is::<crate::repo_lock::ResourceBlocked>() {
2313                return Err(e);
2314            }
2315            self.state.status = RunStatus::Blocked;
2316            self.state
2317                .prep_failure
2318                .get_or_insert_with(|| format!("{e:#}"));
2319            self.state
2320                .event("prep", format!("preparation stopped: {e:#}"));
2321            self.state.save()?;
2322            return Err(e);
2323        }
2324        if self.park_here()? {
2325            return Ok(());
2326        }
2327        self.advise().await?;
2328        if self.park_here()? {
2329            return Ok(());
2330        }
2331        self.implement().await?;
2332        if self.park_here()? {
2333            return Ok(());
2334        }
2335        // `after_implement` already saved the state and settled any open
2336        // questions when it set this; nothing later in the graph has
2337        // anything to judge.
2338        if self.state.status == RunStatus::VerifiedNoop {
2339            return Ok(());
2340        }
2341        self.judge().await?;
2342        if self.park_here()? {
2343            return Ok(());
2344        }
2345        self.deliberate().await?;
2346        if self.park_here()? {
2347            return Ok(());
2348        }
2349        self.vote().await?;
2350        if self.park_here()? {
2351            return Ok(());
2352        }
2353        self.tally()?;
2354        // A verdict that lost its quorum is not trustworthy: do not review,
2355        // gate, or merge on it. Everything already done is kept, so the run
2356        // stays resumable (or foldable); the human can replace the agent that
2357        // ran out of quota and pick it up.
2358        if self.state.status == RunStatus::Stalled {
2359            // Persist the stalled marker now — the normal end-of-execute save
2360            // below is below this early return, and without it a resumed run
2361            // would reload a pre-tally status and keep going.
2362            self.state.save()?;
2363            return Ok(());
2364        }
2365        self.finish_after_tally().await?;
2366        Ok(())
2367    }
2368
2369    /// A wave could not start its agents because a shared resource stayed busy
2370    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2371    /// resumable. Unstarted seats have no result; completed peers retain
2372    /// their saved candidate state.
2373    fn stop_for_resource(&mut self) -> Result<()> {
2374        // Resource acquisition observes cancellation inside a node. Complete
2375        // the same durable park as every other node boundary before returning.
2376        if self.pause.parked() || self.interrupt.parked() {
2377            self.park_here()?;
2378            return Ok(());
2379        }
2380        if self.state.resource_block.is_some() {
2381            self.state.status = RunStatus::Blocked;
2382        }
2383        self.state.save()
2384    }
2385
2386    /// Stop walking the graph if a node ended on a resource block.
2387    fn resource_halt(&mut self) -> Result<bool> {
2388        if self.state.resource_block.is_none() {
2389            return Ok(false);
2390        }
2391        self.stop_for_resource()?;
2392        Ok(true)
2393    }
2394
2395    /// Park here if asked to, recording it in the run's own timeline.
2396    ///
2397    /// Returns whether the caller should stop walking the graph. The state is
2398    /// saved either way by the node that just finished; this adds the event so
2399    /// the operator's card says why a run that is neither finished nor moving
2400    /// is sitting where it is.
2401    fn park_here(&mut self) -> Result<bool> {
2402        let parking = self.pause.parked() || self.interrupt.parked();
2403        if !parking && self.state.resource_block.is_some() {
2404            self.stop_for_resource()?;
2405            return Ok(true);
2406        }
2407        // Either handle asking is enough - see `Pause`'s own doc for why
2408        // they are never the same one. `interrupt` is checked second so a
2409        // reason it carries is preferred in the message below over a plain
2410        // shutdown park racing it at the same boundary.
2411        if !self.pause.parked() && !self.interrupt.parked() {
2412            return Ok(false);
2413        }
2414        if self.state.parked {
2415            return Ok(true);
2416        }
2417        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2418        if let Some(block) = &mut self.state.resource_block
2419            && matches!(
2420                block.cause,
2421                crate::run::ResourceBlockCause::Cancelled { .. }
2422            )
2423        {
2424            block.cause = crate::run::ResourceBlockCause::Cancelled {
2425                park: cause.clone(),
2426            };
2427        }
2428        let why = match cause.as_ref().map(ParkCause::label) {
2429            Some(reason) => format!(
2430                "parked after `{}` ({reason}) — resume to carry on from here",
2431                self.state.status.as_str()
2432            ),
2433            None => format!(
2434                "parked after `{}` — resume to carry on from here",
2435                self.state.status.as_str()
2436            ),
2437        };
2438        self.state.event("park", why);
2439        self.state
2440            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2441        self.state.parked = true;
2442        self.state.save()?;
2443        Ok(true)
2444    }
2445
2446    /// Only a new explicit operator approval may retry failed preparation.
2447    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2448        if self.state.prep_failure.is_none() {
2449            return Ok(());
2450        }
2451        let failed_at = self
2452            .state
2453            .events
2454            .iter()
2455            .rev()
2456            .find(|event| event.node == "prep")
2457            .map_or(self.state.updated_at, |event| event.at);
2458        anyhow::ensure!(
2459            approval_at > failed_at,
2460            "preparation retry requires a new explicit release after the failure"
2461        );
2462        self.state.prep_failure = None;
2463        self.state.prep_complete = Some(false);
2464        self.state
2465            .event("prep-retry", "operator approved retry of preparation");
2466        Ok(())
2467    }
2468
2469    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2470    pub fn on_pause(&mut self, pause: Pause) {
2471        self.pause = pause;
2472    }
2473
2474    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2475    /// scheduler asking this one run - and no other - to park so a task
2476    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2477    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2478    /// handle.
2479    pub fn watch_interrupt(&mut self, pause: Pause) {
2480        self.interrupt = pause;
2481    }
2482
2483    /// Abandon this run's own open questions, once `status` has actually
2484    /// settled rather than merely paused.
2485    ///
2486    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2487    /// either back up with the candidates, the review round and the seat
2488    /// sessions already on disk, so a question an implementer asked mid-round
2489    /// may still get a real answer read by a real resume. Only the statuses
2490    /// `resumable` excludes are actually final: the run merged, it reached
2491    /// `Ready` with nothing left to do, it failed outright with no
2492    /// established point to continue from, or every candidate agreed, with
2493    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2494    /// every one of those the seat that asked is gone for good, exactly like
2495    /// the run being deleted under `magi run rm` - so the same cleanup
2496    /// applies, worded for what actually happened instead of "the run was
2497    /// deleted".
2498    ///
2499    /// Best-effort and silent on success: called from every place `status`
2500    /// can land on one of those three, including ones a resumed run revisits,
2501    /// so it must cost nothing when there was nothing open to begin with.
2502    fn settle_questions(&mut self) {
2503        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2504            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2505        }
2506    }
2507
2508    /// The tail of the graph after a trustworthy tally: fold losers, review,
2509    /// gate, merge, and persist.
2510    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2511        Box::pin(self.finish_after_tally_inner())
2512    }
2513
2514    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2515        // Before the losers are folded: their branches are what the graft
2516        // reads from.
2517        self.graft().await?;
2518        if self.resource_halt()? {
2519            return Ok(());
2520        }
2521        self.fold_losers().await?;
2522        // Before review starts, and again right before the gate: a run's
2523        // review rounds can themselves take long enough for the base to move
2524        // a second time, and the gate is the one node whose "green" gets
2525        // acted on.
2526        self.sync_to_base().await?;
2527        if self.hold_base_sync().await? || self.resource_halt()? {
2528            return Ok(());
2529        }
2530        if self.state.status == RunStatus::AlreadyInBase {
2531            return Ok(());
2532        }
2533        self.review_loop().await?;
2534        if self.resource_halt()? {
2535            return Ok(());
2536        }
2537        self.sync_to_base().await?;
2538        if self.hold_base_sync().await? || self.resource_halt()? {
2539            return Ok(());
2540        }
2541        if self.state.status == RunStatus::AlreadyInBase {
2542            return Ok(());
2543        }
2544        self.gate().await?;
2545        self.merge().await?;
2546        if self.resource_halt()? {
2547            return Ok(());
2548        }
2549        self.state.save()?;
2550        Ok(())
2551    }
2552
2553    // ---------------------------------------------------------------- prep
2554
2555    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2556    /// run with the step and its output in the event; it is never swallowed.
2557    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2558    /// resume starts over instead of finding candidates and missing seats.
2559    async fn setup_seat_worktree(
2560        &mut self,
2561        repo: &Path,
2562        wt: &Path,
2563        in_prep: bool,
2564        coordination: Option<&crate::repo_lock::SeatLease>,
2565    ) -> Result<()> {
2566        let result = match ensure_setup_config(&mut self.state, repo).await {
2567            Ok(()) => {
2568                worktree_setup::prepare_with(
2569                    &self.state.config,
2570                    repo,
2571                    wt,
2572                    crate::build_target::Coordination::Held(coordination),
2573                )
2574                .await
2575            }
2576            Err(e) => Err(e),
2577        };
2578        if let Err(e) = result {
2579            git::worktree_remove_clean(repo, wt).await.ok();
2580            if in_prep {
2581                self.rollback_prep(repo).await;
2582            }
2583            self.state.status = RunStatus::Blocked;
2584            self.state.event(
2585                "setup",
2586                format!("worktree setup failed in {}: {e:#}", wt.display()),
2587            );
2588            self.state.save()?;
2589            return Err(e);
2590        }
2591        Ok(())
2592    }
2593
2594    /// Undo everything `prep` created, so a resume re-runs it whole.
2595    async fn rollback_prep(&mut self, repo: &Path) {
2596        let root = self.state.worktree_root();
2597        for c in std::mem::take(&mut self.state.candidates) {
2598            if matches!(
2599                git::worktree_remove_clean(repo, &c.worktree).await,
2600                Ok(true)
2601            ) {
2602                git::branch_delete(repo, &c.branch).await.ok();
2603            } else {
2604                self.state.candidates.push(c);
2605            }
2606        }
2607        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2608        for j in 1..=seats {
2609            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2610                .await
2611                .ok();
2612        }
2613        for k in 1..=self.state.config.graph.advisors {
2614            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2615                .await
2616                .ok();
2617        }
2618    }
2619
2620    async fn prep(&mut self) -> Result<()> {
2621        if let Some(reason) = &self.state.prep_failure {
2622            bail!(
2623                "candidate preparation previously failed: {reason}; correct the source before retrying"
2624            );
2625        }
2626        if self
2627            .state
2628            .prep_complete
2629            .unwrap_or(!self.state.candidates.is_empty())
2630        {
2631            return Ok(());
2632        }
2633        let repo = self.state.repo.clone();
2634        // Includes rollback, config, refs, checkout creation and setup. No
2635        // repository mutation may precede the real shared lock acquisition.
2636        let _coordination = self.coordinate(&repo).await?;
2637        let base = self.state.base_commit.clone();
2638        let plan = self.state.sources.plan(&repo, &base).await?;
2639        self.rollback_prep(&repo).await;
2640        if !self.state.candidates.is_empty() {
2641            bail!(
2642                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2643            );
2644        }
2645        self.state.prep_complete = Some(false);
2646        self.state.status = RunStatus::Prep;
2647        self.state.save()?;
2648        let repo = self.state.repo.clone();
2649        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2650        let root = self.state.worktree_root();
2651        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2652
2653        // The hook is the write-time half of the blindness contract; the
2654        // presentation filter in `blind` is the half that cannot be bypassed.
2655        let hooks_dir = self.state.dir().join("hooks");
2656        if self.state.config.blind.commit_msg_hook {
2657            std::fs::create_dir_all(&hooks_dir)
2658                .with_context(|| format!("create {}", hooks_dir.display()))?;
2659            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2660            let path = hooks_dir.join("commit-msg");
2661            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2662            make_executable(&path)?;
2663            // Ref-counted rather than a plain idempotent set: with more than
2664            // one run able to be in flight in the same repository at once
2665            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2666            // true?" check cannot tell "another run of mine still needs
2667            // this" from "nobody does", and the run that happens to finish
2668            // first would disable the hook out from under a sibling still
2669            // relying on it.
2670            git::acquire_worktree_config(&repo).await?;
2671            self.state.enabled_worktree_config = true;
2672        }
2673
2674        // `[worktree] setup` hides its products per worktree, which needs the
2675        // same per-worktree config the hook does. Held until fold, like it.
2676        ensure_setup_config(&mut self.state, &repo).await?;
2677
2678        for (index, (spec, label)) in self
2679            .roles
2680            .implementers
2681            .clone()
2682            .into_iter()
2683            .zip(labels)
2684            .enumerate()
2685        {
2686            let branch = self.state.branch_for(label);
2687            let worktree = root.join(format!("cand-{label}"));
2688            // Persist intent before Git can leave a partially created tree.
2689            // Candidate registration follows setup, so it cannot inventory
2690            // crashes or refusals during creation itself.
2691            self.state.event(
2692                "prep-intent",
2693                serde_json::json!({
2694                    "branch": branch,
2695                    "worktree": worktree,
2696                    "start": start,
2697                    "picks": plan.picks,
2698                })
2699                .to_string(),
2700            );
2701            self.state.save()?;
2702            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2703            if self.state.config.blind.commit_msg_hook {
2704                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2705            }
2706            git::local_exclude(&worktree, "/.magi/").await?;
2707            if let Err(e) = worktree_setup::prepare_with(
2708                &self.state.config,
2709                &repo,
2710                &worktree,
2711                crate::build_target::Coordination::Held(_coordination.as_ref()),
2712            )
2713            .await
2714            {
2715                // Nothing of this prep may survive: a resume must start over,
2716                // not find half the candidates and skip the rest.
2717                git::worktree_remove_clean(&repo, &worktree).await.ok();
2718                git::branch_delete(&repo, &branch).await.ok();
2719                self.rollback_prep(&repo).await;
2720                self.state.status = RunStatus::Blocked;
2721                self.state
2722                    .event("prep", format!("worktree setup failed: {e:#}"));
2723                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2724                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2725                }
2726                self.state.save()?;
2727                return Err(e);
2728            }
2729            self.state.candidates.push(Candidate {
2730                index,
2731                label,
2732                agent: spec.id.clone(),
2733                branch,
2734                worktree,
2735                summary: String::new(),
2736                stat: String::new(),
2737                files: 0,
2738                commits: 0,
2739                empty: false,
2740                failed: None,
2741                verified_noop: None,
2742                duration_ms: 0,
2743                folded: false,
2744            });
2745            self.state.save()?;
2746            for pick in &plan.picks {
2747                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2748                {
2749                    self.state.status = RunStatus::Blocked;
2750                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2751                    self.state
2752                        .event("prep", format!("cannot apply referenced commit: {e}"));
2753                    self.state.save()?;
2754                    return Err(e);
2755                }
2756            }
2757        }
2758
2759        for j in 1..=self.roles.judges.len() {
2760            let wt = root.join(format!("judge-{j}"));
2761            if !wt.exists() {
2762                git::worktree_add_detached(&repo, &wt, &base).await?;
2763                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2764                    .await?;
2765            }
2766        }
2767
2768        // Disposable, detached checkouts for the design-deliberation stage's
2769        // advisor seats — the same shape as the judges' above, at the same
2770        // base commit, since advisors also only ever read. Sized off the
2771        // configured count directly rather than a resolved roster: unlike
2772        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2773        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2774        // `prep` has no `ResolvedRoles` field to read a count from here.
2775        if self.state.config.graph.advise {
2776            for k in 1..=self.state.config.graph.advisors {
2777                let wt = root.join(format!("advisor-{k}"));
2778                if !wt.exists() {
2779                    git::worktree_add_detached(&repo, &wt, &base).await?;
2780                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2781                        .await?;
2782                }
2783            }
2784        }
2785
2786        // A judge cannot tell it is looking at its own patch — the seats keep
2787        // separate conversations — but a panel that shares agents with the
2788        // field is less independent than it looks, and that is worth saying out
2789        // loud once per run rather than leaving it in the config.
2790        let authors: Vec<&str> = self
2791            .roles
2792            .implementers
2793            .iter()
2794            .map(|a| a.id.as_str())
2795            .collect();
2796        let overlap: Vec<String> = self
2797            .roles
2798            .judges
2799            .iter()
2800            .enumerate()
2801            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2802            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2803            .collect();
2804        if !overlap.is_empty() {
2805            let note = format!(
2806                "{} also authored a candidate; blind, but the panel is less \
2807                 independent than {} distinct agents would be",
2808                overlap.join(", "),
2809                self.roles.judges.len()
2810            );
2811            self.state.event("prep", note);
2812        }
2813
2814        self.state.event(
2815            "prep",
2816            format!(
2817                "{} candidates, {} judges, base {} ({})",
2818                self.state.candidates.len(),
2819                self.roles.judges.len(),
2820                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2821                self.state.base_branch
2822            ),
2823        );
2824        self.state.prep_complete = Some(true);
2825        self.state.status = RunStatus::Implementing;
2826        self.state.save()?;
2827        Ok(())
2828    }
2829
2830    // -------------------------------------------------------------- advise
2831
2832    /// The design-deliberation stage: independent, read-only advisor seats
2833    /// each sketch a design before any implementer touches the repository,
2834    /// and (when at least one produced a usable proposal) a synthesis seat
2835    /// blends them into a brief `implement` carries in every candidate's
2836    /// prompt.
2837    ///
2838    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2839    /// advisors` is the proposal count. Everything here is best-effort and
2840    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2841    /// that cannot reach quota, or a synthesis seat that produced nothing
2842    /// usable all leave `implement` exactly as it was before this stage
2843    /// existed — the task instruction alone — rather than failing the whole
2844    /// competition over an enrichment stage. Every outcome is still recorded
2845    /// as an event, so a run that got nothing from this stage says why.
2846    ///
2847    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2848    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2849    /// resumed run whose stage failed would re-run it, and re-spend the
2850    /// agent calls, on every reentry before `implement`.
2851    ///
2852    /// Also skipped once any candidate shows implementation progress — the
2853    /// exact predicate `implement` itself uses to decide a candidate is no
2854    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2855    /// is not enough: a run created by an older binary that predates this
2856    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2857    /// an already-`Implementing`-or-later run under this build would
2858    /// otherwise walk straight back through `prep` (a no-op once candidates
2859    /// exist) into this node and spawn every advisor seat against worktrees
2860    /// `prep` never recreated — after implementation has already started,
2861    /// which is exactly the invariant this stage exists to guarantee.
2862    async fn advise(&mut self) -> Result<()> {
2863        let implement_untouched = self
2864            .state
2865            .candidates
2866            .iter()
2867            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
2868        if !self.state.config.graph.advise || self.state.advise_attempted {
2869            return Ok(());
2870        }
2871        if !implement_untouched {
2872            self.state.event(
2873                "advise",
2874                "skipping the design-deliberation stage: at least one \
2875                 candidate already shows implementation progress, so this \
2876                 run is past the point the stage exists to run before"
2877                    .to_owned(),
2878            );
2879            self.state.advise_attempted = true;
2880            self.state.save()?;
2881            return Ok(());
2882        }
2883        let run_id = self.state.id.clone();
2884        let prompts = self.state.config.prompts.clone();
2885        let instruction = self.state.instruction.clone();
2886        let language = self.state.config.graph.language.clone();
2887        let root = self.state.worktree_root();
2888        let n = self.state.config.graph.advisors;
2889        let where_recorded = self.state.dir().join("run.json");
2890
2891        let seats = match self.state.config.advisors() {
2892            Ok(seats) if !seats.is_empty() => seats,
2893            Ok(_) => {
2894                self.state.event(
2895                    "advise",
2896                    format!(
2897                        "[graph] advisors is 0; skipping the design-deliberation \
2898                         stage and continuing without a synthesis brief (see {})",
2899                        where_recorded.display()
2900                    ),
2901                );
2902                self.state.advise_attempted = true;
2903                self.state.save()?;
2904                return Ok(());
2905            }
2906            Err(e) => {
2907                self.state.event(
2908                    "advise",
2909                    format!(
2910                        "could not resolve advisor seats ({e:#}); continuing \
2911                         without a design-deliberation brief (see {})",
2912                        where_recorded.display()
2913                    ),
2914                );
2915                self.state.advise_attempted = true;
2916                self.state.save()?;
2917                return Ok(());
2918            }
2919        };
2920
2921        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
2922        let artifacts = agent::artifacts_dir(&self.state.dir());
2923        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
2924
2925        let mut jobs = Vec::new();
2926        for (i, spec) in seats.iter().cloned().enumerate() {
2927            let seat_key = format!("advisor-{}", i + 1);
2928            let seat = self.seat(&seat_key, &spec.id);
2929            jobs.push(SeatJob {
2930                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
2931                spec,
2932                seat,
2933                cwd: worktrees[i % worktrees.len()].clone(),
2934                timeout,
2935                allow_write: false,
2936                sessions: false,
2937                artifacts: artifacts.clone(),
2938                stem: seat_key,
2939                handover: None,
2940            });
2941        }
2942
2943        self.state.event(
2944            "advise",
2945            format!(
2946                "{} advisor seat(s) sketching a design in parallel",
2947                jobs.len()
2948            ),
2949        );
2950        let mut quota_losses = Vec::new();
2951        let cache = self.state.config.cache_dir();
2952        let ctx = WaveCtx {
2953            carry_seats: false,
2954            pauses: Some((&self.pause, &self.interrupt)),
2955            run: &run_id,
2956            node: "advise",
2957            prompts: &prompts,
2958            cache: cache.as_deref(),
2959            round: None,
2960        };
2961        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
2962        let results = ask_json_wave::<Proposal>(
2963            jobs,
2964            Arc::clone(&self.sem),
2965            self.state.config.graph.retries,
2966            &advisor_roster,
2967            &ctx,
2968            &mut quota_losses,
2969            &mut self.state,
2970            &|p: &Proposal| p.validate(),
2971        )
2972        .await;
2973        if self.state.resource_block.is_some() {
2974            return self.stop_for_resource();
2975        }
2976        self.state.quota.extend(quota_losses);
2977
2978        let mut records = Vec::with_capacity(results.len());
2979        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
2980            let agent_id = seat.agent.clone();
2981            self.state.seats.insert(seat.key.clone(), seat);
2982            match res {
2983                Ok((proposal, out)) => {
2984                    self.state
2985                        .event("advise", format!("advisor-{} proposed a design", i + 1));
2986                    records.push(advise::AdvisorRecord::proposed(
2987                        i + 1,
2988                        agent_id,
2989                        proposal,
2990                        out.duration_ms,
2991                    ));
2992                }
2993                Err(e) => {
2994                    self.state.event(
2995                        "advise",
2996                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
2997                    );
2998                    records.push(advise::AdvisorRecord::failed(
2999                        i + 1,
3000                        agent_id,
3001                        e.to_string(),
3002                    ));
3003                }
3004            }
3005        }
3006
3007        let mut advice = advise::Advice {
3008            records,
3009            synthesis: None,
3010        };
3011        if advice.proposals().is_empty() {
3012            self.state.event(
3013                "advise",
3014                "no advisor produced a usable proposal; continuing without a \
3015                 synthesis brief"
3016                    .to_owned(),
3017            );
3018        } else {
3019            match self
3020                .synthesize_brief(
3021                    &advice,
3022                    &instruction,
3023                    &language,
3024                    &worktrees[0],
3025                    &artifacts,
3026                    &run_id,
3027                    &prompts,
3028                    cache.as_deref(),
3029                )
3030                .await
3031            {
3032                Ok(Some(text)) => {
3033                    self.state.event(
3034                        "advise",
3035                        "synthesized a design brief for the implementer".to_owned(),
3036                    );
3037                    advice.synthesis = Some(text);
3038                }
3039                Ok(None) => {
3040                    self.state.event(
3041                        "advise",
3042                        "the synthesis seat produced nothing usable; continuing \
3043                         without a design brief"
3044                            .to_owned(),
3045                    );
3046                }
3047                Err(e) => {
3048                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3049                        return Err(e);
3050                    }
3051                    self.state.event(
3052                        "advise",
3053                        format!("could not synthesize a design brief: {e:#}"),
3054                    );
3055                }
3056            }
3057        }
3058        advise::apply_reflection(&mut advice);
3059
3060        self.state.advice = Some(advice);
3061        self.state.advise_attempted = true;
3062        self.state.save()?;
3063        Ok(())
3064    }
3065
3066    /// The synthesis seat: reads every advisor's proposal and blends them
3067    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3068    /// out of [`Runner::advise`] only for readability — it is not called
3069    /// anywhere else.
3070    ///
3071    /// Picked the same way [`crate::talk`]'s standing conversation and
3072    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3073    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3074    /// order (a claude seat, else the first runnable agent in roster order)
3075    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3076    /// in [`crate::config`] for why a dedicated field exists here at all.
3077    #[allow(clippy::too_many_arguments)]
3078    async fn synthesize_brief(
3079        &mut self,
3080        advice: &advise::Advice,
3081        instruction: &str,
3082        language: &str,
3083        cwd: &Path,
3084        artifacts: &Path,
3085        run_id: &str,
3086        prompts: &Prompts,
3087        cache: Option<&Path>,
3088    ) -> Result<Option<String>> {
3089        let chain = agent::pick_chain(
3090            &self.state.config.agents,
3091            self.state.config.roles.synthesizer.as_ref(),
3092            &agent::installed,
3093            "synthesizer",
3094        )?;
3095        let proposals = advice.proposals();
3096        let mut prompt = prompt::with_overlay(
3097            prompt::synthesize_brief(instruction, &proposals, language),
3098            prompts.overlay("advise"),
3099        );
3100        if cache.is_some() {
3101            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3102            // below — see `prompt::build_cache_note`'s doc for why telling a
3103            // read-only seat to build through the shared cache is exactly how
3104            // a sandbox's write refusal gets misread as a defect.
3105            prompt.push('\n');
3106            prompt.push_str(&prompt::build_cache_note("advise", false));
3107        }
3108        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3109        // Each id is tried once, in order; a quota hit, error or unusable
3110        // answer moves to the next. The seat is single-turn (`sessions:
3111        // false`) and the prompt is the whole context, so a fallback agent
3112        // needs nothing carried over.
3113        let mut last = None;
3114        for (n, spec) in chain.iter().enumerate() {
3115            if n > 0 {
3116                self.state
3117                    .event("advise", format!("synthesis falling back to {}", spec.id));
3118            }
3119            let mut seat = self.seat("advise-synthesis", &spec.id);
3120            let wait = self.repository_wait();
3121            let outcome = wait
3122                .scope(agent::invoke(
3123                    spec,
3124                    &mut seat,
3125                    &Invocation {
3126                        coordination: self.state.config.coordination.as_ref(),
3127                        fetched_base: None,
3128                        cwd,
3129                        prompt: &prompt,
3130                        timeout,
3131                        allow_write: false,
3132                        sessions: false,
3133                        artifacts,
3134                        stem: &if n == 0 {
3135                            "advise-synthesis".to_owned()
3136                        } else {
3137                            format!("advise-synthesis-{}", spec.id)
3138                        },
3139                        run: run_id,
3140                        node: "advise",
3141                        cache_dir: None,
3142                        attachments: &[],
3143                        writable: &[],
3144                    },
3145                ))
3146                .await;
3147            if outcome.is_ok() {
3148                self.state.seats.insert(seat.key.clone(), seat);
3149            }
3150            let advance = agent::chain_advances(&outcome);
3151            last = Some(outcome);
3152            if !advance {
3153                break;
3154            }
3155        }
3156        // Exhausted: the last attempt's result is what a single failed seat
3157        // would have produced.
3158        let out = last.expect("a chain holds at least one agent")?;
3159        if !out.usable() {
3160            return Ok(None);
3161        }
3162        let text =
3163            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3164        Ok((!text.trim().is_empty()).then_some(text))
3165    }
3166
3167    // ----------------------------------------------------------- implement
3168
3169    async fn implement(&mut self) -> Result<()> {
3170        self.persist_candidates().await?;
3171        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3172        // agent files with `magi task add` name the run that paid for it. The
3173        // prompt overlay is cloned alongside it because the waves borrow it
3174        // while `self` is mutably borrowed by the node's own bookkeeping.
3175        let run_id = self.state.id.clone();
3176        let prompts = self.state.config.prompts.clone();
3177        let todo: Vec<usize> = self
3178            .state
3179            .candidates
3180            .iter()
3181            .enumerate()
3182            .filter(|(_, c)| {
3183                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3184                    && c.failed.is_none()
3185                    && !c.empty
3186            })
3187            .map(|(i, _)| i)
3188            .collect();
3189        if todo.is_empty() {
3190            return self.after_implement();
3191        }
3192        self.state.status = RunStatus::Implementing;
3193
3194        let language = self.state.config.graph.language.clone();
3195        let github_language = self.state.config.graph.github_language.clone();
3196        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3197        let sessions = self.state.config.graph.sessions;
3198        let artifacts = agent::artifacts_dir(&self.state.dir());
3199        // The design-deliberation stage's blended brief, when `advise` found
3200        // one — carried into every implementer's prompt the same way
3201        // regardless of which candidate it is.
3202        let brief = self
3203            .state
3204            .advice
3205            .as_ref()
3206            .and_then(|a| a.synthesis.as_deref())
3207            .map(str::to_owned);
3208        let attachments = self.state.attachments.clone();
3209
3210        let mut jobs = Vec::new();
3211        for &i in &todo {
3212            let (index, label, worktree) = {
3213                let c = &self.state.candidates[i];
3214                (c.index, c.label, c.worktree.clone())
3215            };
3216            let spec = self.roles.implementers[index].clone();
3217            let seat_key = format!("impl-{label}");
3218            let seat = self.seat(&seat_key, &spec.id);
3219            let instruction = seeded_instruction(&self.state);
3220            jobs.push(SeatJob {
3221                spec,
3222                seat,
3223                prompt: prompt::implement_in(
3224                    &instruction,
3225                    &worktree.to_string_lossy(),
3226                    &language,
3227                    &github_language,
3228                    brief.as_deref(),
3229                    &attachments,
3230                ),
3231                cwd: worktree,
3232                timeout,
3233                allow_write: true,
3234                sessions,
3235                artifacts: artifacts.clone(),
3236                stem: format!("impl-{label}"),
3237                handover: None,
3238            });
3239        }
3240
3241        self.state.event(
3242            "implement",
3243            format!("{} candidates in parallel", jobs.len()),
3244        );
3245        // Kept so a seat whose CLI hung up can be asked again from the same
3246        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3247        // can update a seat's own entry once a fallback agent takes it over —
3248        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3249        // whichever agent actually answered, not the one that quota'd out.
3250        let mut sent = jobs.clone();
3251        let cache = self.state.config.cache_dir();
3252        let ctx = WaveCtx {
3253            carry_seats: false,
3254            pauses: Some((&self.pause, &self.interrupt)),
3255            run: &run_id,
3256            node: "implement",
3257            prompts: &prompts,
3258            cache: cache.as_deref(),
3259            round: None,
3260        };
3261        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3262        if !wave_blocked(&results) {
3263            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3264                .await;
3265            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3266                .await?;
3267            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3268                .await;
3269        }
3270        // Do not finalize failed candidates when the entire wave needs machine
3271        // recovery: leaving them pending resumes this node with its work intact.
3272        if !results.is_empty()
3273            && results
3274                .iter()
3275                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3276        {
3277            let losses: Vec<_> = results
3278                .iter()
3279                .map(|(_, seat, out)| {
3280                    let AgentOutcome::Quota(o) = out else {
3281                        unreachable!()
3282                    };
3283                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3284                })
3285                .collect();
3286            self.state.quota.extend(losses.clone());
3287            for (_, seat, _) in results {
3288                self.state.seats.insert(seat.key.clone(), seat);
3289            }
3290            for &i in &todo {
3291                let label = self.state.candidates[i].label;
3292                self.state.interrupted_implementations.insert(label);
3293                self.state
3294                    .candidate_preservation
3295                    .insert(label, "machine outage awaiting persistence".into());
3296            }
3297            // Preserve partial edits too, while keeping every interrupted seat
3298            // pending even when its tree already contains an inherited patch.
3299            block_machine_outage(&mut self.state, "implement", &losses);
3300            self.state.save()?;
3301            self.persist_candidates().await?;
3302            for &i in &todo {
3303                self.state
3304                    .interrupted_implementations
3305                    .insert(self.state.candidates[i].label);
3306            }
3307            return self.stop_for_resource();
3308        }
3309        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3310
3311        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3312            && results
3313                .iter()
3314                .any(|(_, _, out)| FailClass::of(out).is_some());
3315        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3316            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3317                // Executed turns interrupted by disk pressure already carry
3318                // a preservation barrier from wave. Admission-only waits do
3319                // not. Keep the interrupted seat's session for recovery too.
3320                if self
3321                    .state
3322                    .candidate_preservation
3323                    .contains_key(&self.state.candidates[i].label)
3324                {
3325                    self.state.seats.insert(seat.key.clone(), seat);
3326                }
3327                continue;
3328            }
3329            let seat_key = seat.key.clone();
3330            // A quota fallback (`resume_seat_handovers`) may have handed this
3331            // seat to a different agent than the one `prep` recorded on the
3332            // candidate; the stats tables and any later fixer-defaults-to-
3333            // winner's-author lookup must credit whoever actually answered —
3334            // unless every fallback also quota'd out, in which case nobody
3335            // actually answered and crediting the last agent tried would
3336            // erase every earlier agent's own quota loss from the stats
3337            // tables instead of just this one seat's.
3338            let agent = seat.agent.clone();
3339            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3340            self.state.seats.insert(seat.key.clone(), seat);
3341            let label = self.state.candidates[i].label;
3342            self.state.interrupted_implementations.remove(&label);
3343
3344            let (summary, duration, failed, verified_claim) = match out {
3345                AgentOutcome::Ok(o) => {
3346                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3347                    let failed = (!o.usable()).then(|| {
3348                        if o.timed_out {
3349                            "agent timed out".to_owned()
3350                        } else {
3351                            format!(
3352                                "agent exited with {}",
3353                                crate::notices::exit_status(o.exit_code)
3354                            )
3355                        }
3356                    });
3357                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
3358                    (text, o.duration_ms, failed, verified_claim)
3359                }
3360                // Left un-resumed by `resume_undelivered` (a dirty tree
3361                // already rescues the work, or there was no session left to
3362                // resume into) — reported like the ordinary failure it is,
3363                // never as if `o.text` (the CLI's raw error JSON) were an
3364                // answer.
3365                AgentOutcome::Dropped(o) => {
3366                    let why = o
3367                        .dropped
3368                        .as_ref()
3369                        .map(|d| d.why.as_str())
3370                        .unwrap_or("the CLI ended the stream without delivering its answer");
3371                    (
3372                        String::new(),
3373                        o.duration_ms,
3374                        Some(format!("the CLI dropped the stream ({why})")),
3375                        None,
3376                    )
3377                }
3378                AgentOutcome::Quota(o) => {
3379                    self.state.quota.push(QuotaLoss::from_report(
3380                        seat_key,
3381                        "implement",
3382                        o.quota.as_ref(),
3383                    ));
3384                    (
3385                        String::new(),
3386                        o.duration_ms,
3387                        Some("rate limited (quota); produced no change".to_owned()),
3388                        None,
3389                    )
3390                }
3391                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3392                    (String::new(), 0, Some(e), None)
3393                }
3394            };
3395
3396            // Save every completed turn before any fallible Git operation. A failed
3397            // rescue must not erase the reply or prevent collection of other seats.
3398            let c = &mut self.state.candidates[i];
3399            if !exhausted_the_fallback_chain {
3400                c.agent = agent;
3401            }
3402            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
3403            c.duration_ms = duration;
3404            c.failed = failed;
3405            c.verified_noop = verified_claim;
3406            self.state
3407                .candidate_preservation
3408                .insert(label, "awaiting persistence".to_owned());
3409        }
3410        self.state.save()?;
3411        self.persist_candidates().await?;
3412
3413        if resource_blocked {
3414            return self.stop_for_resource();
3415        }
3416        if selected_failed {
3417            self.state.status = RunStatus::Blocked;
3418            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3419            self.state.save()?;
3420            bail!(
3421                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3422            );
3423        }
3424        self.after_implement()
3425    }
3426
3427    /// Retry only persistence after a completed implementation turn.
3428    async fn persist_candidates(&mut self) -> Result<()> {
3429        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3430        for label in labels {
3431            let i = self
3432                .state
3433                .candidates
3434                .iter()
3435                .position(|c| c.label == label)
3436                .context("pending candidate is missing")?;
3437            let c = self.state.candidates[i].clone();
3438            let interrupted = self.state.interrupted_implementations.contains(&label);
3439            let result = async {
3440                let wait = crate::repo_lock::WaitPolicy::new(
3441                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3442                    || false,
3443                );
3444                let _coordination =
3445                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3446                // Best effort evidence requires no index writes. A successful snapshot
3447                // never authorizes removal of a tree whose rescue failed.
3448                if let Err(e) = git::snapshot_uncommitted(
3449                    &c.worktree,
3450                    &self
3451                        .state
3452                        .dir()
3453                        .join("artifacts")
3454                        .join(format!("candidate-{label}-recovery")),
3455                )
3456                .await
3457                {
3458                    self.state.event(
3459                        "preserve",
3460                        format!("candidate {label} snapshot incomplete: {e:#}"),
3461                    );
3462                }
3463                let rescued = git::rescue_commit(
3464                    &c.worktree,
3465                    &format!("magi: candidate {label} (uncommitted work)"),
3466                )
3467                .await?;
3468                self.state.note_withheld("implement", &rescued.withheld);
3469                let base = &self.state.base_commit;
3470                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3471                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3472                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3473                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3474                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3475                if c.empty && commits > 0 && !patch.trim().is_empty()
3476                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3477                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3478                        || self.state.tally.is_some())
3479                {
3480                    // Keep the old classification and pending marker so every
3481                    // retry stops too. Retain decisions as recovery evidence;
3482                    // only a supported recovery operation may replace them.
3483                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3484                }
3485                let c = &mut self.state.candidates[i];
3486                c.commits = commits;
3487                c.stat = stat;
3488                c.files = files;
3489                let no_changes = commits == 0 || patch.trim().is_empty();
3490                c.empty = no_changes && !interrupted;
3491                if interrupted && no_changes {
3492                    c.failed = None;
3493                    c.verified_noop = None;
3494                }
3495                if !c.empty {
3496                    c.failed = None;
3497                    c.verified_noop = None;
3498                }
3499                self.state.event(
3500                    "preserve",
3501                    format!("candidate {label}: {files} files, {commits} commits"),
3502                );
3503                Ok::<_, anyhow::Error>(())
3504            }
3505            .await;
3506            match result {
3507                Ok(()) => {
3508                    self.state.candidate_preservation.remove(&label);
3509                    if !interrupted || self.state.candidates[i].files > 0 {
3510                        self.state.interrupted_implementations.remove(&label);
3511                    }
3512                }
3513                Err(e) => {
3514                    let reason = format!("candidate {label} preservation failed: {e:#}");
3515                    self.state.event("preserve", &reason);
3516                    self.state.candidate_preservation.insert(label, reason);
3517                }
3518            }
3519            if self.state.candidate_preservation.is_empty()
3520                && self.state.status == RunStatus::Blocked
3521                && self.state.candidates.iter().all(|c| c.failed.is_none())
3522            {
3523                // Persist the recovered phase with the cleared pending marker;
3524                // a crash between saves must not turn this into a selected-seat
3525                // failure hold on the next resume.
3526                self.state.status = RunStatus::Implementing;
3527                self.state.event(
3528                    "preserve",
3529                    "candidate persistence recovered; implementation can continue",
3530                );
3531            }
3532            self.state.save()?;
3533        }
3534        if !self.state.candidate_preservation.is_empty() {
3535            self.state.status = RunStatus::Blocked;
3536            self.state.save()?;
3537            bail!(
3538                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3539            );
3540        }
3541        Ok(())
3542    }
3543
3544    /// Ask again, once, for work a CLI did and then failed to hand over.
3545    ///
3546    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3547    /// status with an empty response and a usage report showing output tokens,
3548    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3549    /// seven minutes and 14,267 output tokens that arrived as an empty
3550    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3551    ///
3552    /// Two conditions, and both matter:
3553    ///
3554    /// - **Only when the tree is untouched.** Often the agent has already
3555    ///   written its files and only the closing message was lost; the rescue
3556    ///   commit below picks that up and there is nothing to ask for. Re-asking
3557    ///   then would pay for a second implementation of work already on disk.
3558    /// - **Once.** A CLI that drops one stream can drop the next, and this
3559    ///   node is the most expensive in the graph.
3560    ///
3561    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3562    /// dropped reply still carried its `conversation_id`, so the seat is asked
3563    /// to finish what it was doing rather than sent the whole task again. It
3564    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3565    /// node's - for the same reason a re-ranked judge does: restating finished
3566    /// work is not the work.
3567    ///
3568    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3569    /// same way until it resets, while an abandoned conversation is still
3570    /// there to be picked up.
3571    async fn resume_undelivered(
3572        &mut self,
3573        results: &mut [(usize, SeatState, AgentOutcome)],
3574        sent: &[SeatJob],
3575        prompts: &Prompts,
3576        run_id: &str,
3577    ) {
3578        for (wi, seat, out) in results.iter_mut() {
3579            let Some(dropped) = (match &*out {
3580                AgentOutcome::Dropped(o) => o.dropped.clone(),
3581                _ => None,
3582            }) else {
3583                continue;
3584            };
3585            let Some(job) = sent.get(*wi) else { continue };
3586            // Already on disk? Then only the closing message was lost.
3587            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3588                self.state.event(
3589                    "implement",
3590                    format!(
3591                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3592                         work is in the tree",
3593                        seat.key, dropped.output_tokens, dropped.why
3594                    ),
3595                );
3596                continue;
3597            }
3598            // The re-ask only makes sense as a resume: `resume_after_drop`
3599            // says nothing about the task, trusting the seat to still hold it.
3600            // Without a session to resume — sessions disabled, or this CLI's
3601            // drop shape happened not to carry a session id — that prompt
3602            // would open a brand-new conversation with no context at all,
3603            // which is worse than leaving this as the ordinary failure it
3604            // already is.
3605            if !has_context(&job.spec, seat, job.sessions) {
3606                self.state.event(
3607                    "implement",
3608                    format!(
3609                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3610                         is no session left to resume",
3611                        seat.key, dropped.output_tokens, dropped.why
3612                    ),
3613                );
3614                continue;
3615            }
3616            self.state.event(
3617                "implement",
3618                format!(
3619                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3620                     conversation",
3621                    seat.key, dropped.output_tokens, dropped.why
3622                ),
3623            );
3624            let mut retry = job.clone();
3625            retry.seat = seat.clone();
3626            retry.prompt = prompt::resume_after_drop(&dropped.why);
3627            retry.timeout = retry_budget(job.timeout, true);
3628            retry.stem = format!("{}-resume", job.stem);
3629            let cache = self.state.config.cache_dir();
3630            let ctx = WaveCtx {
3631                carry_seats: false,
3632                pauses: Some((&self.pause, &self.interrupt)),
3633                run: run_id,
3634                node: "implement",
3635                prompts,
3636                cache: cache.as_deref(),
3637                round: None,
3638            };
3639            let (resumed_seat, resumed) =
3640                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3641            *seat = resumed_seat;
3642            *out = resumed;
3643        }
3644    }
3645
3646    /// Fall an implement seat through to the next untried agent in the
3647    /// implementer roster when it lost to quota — or, since the handover was
3648    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3649    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3650    /// quota path itself being unchanged — instead of leaving the
3651    /// seat's loss final the moment one agent's account runs dry.
3652    ///
3653    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3654    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3655    /// truncates to the single slot rotation picked, so a solo task whose one
3656    /// implementer hits quota mid-run used to have nothing else to try. This
3657    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3658    /// unrotated roster — which is the only place the *other* candidates in
3659    /// the machine's roster still exist once `implementers` has been cut down
3660    /// to size.
3661    ///
3662    /// Walks forward from just past the seat's own original position in the
3663    /// roster, never wrapping back to the front: a later candidate slot (say
3664    /// `beta`, the roster's second entry) must fall through to the *next*
3665    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3666    /// almost certainly a different candidate's own agent already — and once
3667    /// the roster's tail is exhausted there is nothing left to fall through
3668    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3669    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3670    /// let this retry that id forever. The loop keeps falling through until
3671    /// an attempt lands something other than `Quota` or the roster's tail
3672    /// runs out of untried ids, at which point the seat is left exactly as
3673    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3674    /// `QuotaLoss` recorded, the candidate failed/empty.
3675    ///
3676    /// `sent` is taken mutably and updated with the fallback agent's spec:
3677    /// `resume_unconfirmed_commands`, which runs after this and also reads
3678    /// `sent`, must see whichever agent actually ended up answering the seat
3679    /// — reading the stale, original spec there would check session
3680    /// eligibility against the wrong CLI and could hand a fallback agent's
3681    /// session id to the agent that just lost the seat to quota.
3682    ///
3683    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3684    /// — `self.seat` only reuses state when the agent id is unchanged, so
3685    /// handing it a different id already gets this for free. Reusing the old
3686    /// seat would resume a different CLI's session as if it were a
3687    /// continuation of this one.
3688    ///
3689    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3690    /// a quota loss cuts an agent off mid-turn, so anything already in the
3691    /// tree is unfinished work, not a completed candidate a re-ask would pay
3692    /// for twice. A dirty tree is rescued into a commit first (the same
3693    /// neutral-identity rescue `implement`'s own outcome loop gives every
3694    /// candidate) so the next agent starts clean.
3695    ///
3696    /// The new agent gets the implementer's full prompt and full
3697    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3698    /// it has no session and no context, and is implementing the task from
3699    /// nothing, unlike a resumed drop which is only restating work already
3700    /// done.
3701    ///
3702    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3703    /// `implement` event, never into `self.state.quota` — that is what
3704    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3705    /// go unspent, and a seat that ultimately recovered on its second or
3706    /// third agent is not the stalled panel that check exists to catch. Only
3707    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3708    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3709    /// outcome loop already has — this helper never pushes to it itself.
3710    async fn resume_seat_handovers(
3711        &mut self,
3712        results: &mut [(usize, SeatState, AgentOutcome)],
3713        sent: &mut [SeatJob],
3714        prompts: &Prompts,
3715        run_id: &str,
3716    ) -> Result<()> {
3717        let instruction = seeded_instruction(&self.state);
3718        let language = self.state.config.graph.language.clone();
3719        let github_language = self.state.config.graph.github_language.clone();
3720        let brief = self
3721            .state
3722            .advice
3723            .as_ref()
3724            .and_then(|a| a.synthesis.as_deref())
3725            .map(str::to_owned);
3726        let attachments = self.state.attachments.clone();
3727        for (wi, seat, out) in results.iter_mut() {
3728            // Who holds the other candidate seats of this wave right now
3729            // (earlier handovers already written back to `sent`).
3730            let others: BTreeSet<String> = sent
3731                .iter()
3732                .enumerate()
3733                .filter(|(j, _)| j != wi)
3734                .map(|(_, j)| j.spec.id.clone())
3735                .collect();
3736            let Some(job) = sent.get_mut(*wi) else {
3737                continue;
3738            };
3739            // Where the seat's own original agent sits in the roster — the
3740            // fallback walk starts just past here, never at the front, so a
3741            // later candidate slot's quota loss does not fall back onto an
3742            // earlier slot's own agent.
3743            let start = self
3744                .roles
3745                .implementer_roster
3746                .iter()
3747                .position(|s| s.id == job.spec.id)
3748                .unwrap_or(0);
3749            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3750            let mut fallback_attempt = 0usize;
3751            let mut prev: Option<FailClass> = None;
3752            while let Some(cur) = FailClass::of(&*out) {
3753                if !should_hand_over(prev.as_ref(), &cur) {
3754                    break;
3755                }
3756                let Some(next) =
3757                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3758                        .cloned()
3759                else {
3760                    break;
3761                };
3762                tried.insert(next.id.clone());
3763                fallback_attempt += 1;
3764
3765                let coordination = self.coordinate(&job.cwd).await?;
3766                if let Ok(r) = git::rescue_commit(
3767                    &job.cwd,
3768                    &format!(
3769                        "magi: candidate {} (uncommitted work before {} fallback)",
3770                        seat.key,
3771                        if cur == FailClass::Quota {
3772                            "quota"
3773                        } else {
3774                            "handover"
3775                        }
3776                    ),
3777                )
3778                .await
3779                {
3780                    self.state.note_withheld("implement", &r.withheld);
3781                }
3782                drop(coordination);
3783
3784                record_handover(
3785                    &mut self.state,
3786                    "implement",
3787                    &seat.key,
3788                    &seat.agent,
3789                    &next.id,
3790                    &cur,
3791                    &fail_reason(&*out),
3792                );
3793                prev = Some(cur.clone());
3794
3795                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3796                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3797                // Kept in sync on `sent` itself, not just the local retry: a
3798                // later helper (`resume_unconfirmed_commands`) reads `sent`
3799                // after this one returns and must see whichever agent is now
3800                // occupying the seat, not the one that just quota'd out —
3801                // otherwise it would judge session/continuation eligibility
3802                // by the wrong CLI and could resend a fallback's session id
3803                // to the agent that lost it the seat in the first place.
3804                job.spec = next.clone();
3805                let mut retry = job.clone();
3806                retry.seat = new_seat;
3807                retry.prompt = prompt::implement_in(
3808                    &instruction,
3809                    &job.cwd.to_string_lossy(),
3810                    &language,
3811                    &github_language,
3812                    brief.as_deref(),
3813                    &attachments,
3814                );
3815                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3816                let cache = self.state.config.cache_dir();
3817                let ctx = WaveCtx {
3818                    carry_seats: false,
3819                    pauses: Some((&self.pause, &self.interrupt)),
3820                    run: run_id,
3821                    node: "implement",
3822                    prompts,
3823                    cache: cache.as_deref(),
3824                    round: None,
3825                };
3826                let (fallback_seat, fallback_out) = run_one(
3827                    retry,
3828                    Arc::clone(&self.sem),
3829                    &ctx,
3830                    &mut self.state,
3831                    fallback_attempt,
3832                )
3833                .await;
3834                *seat = fallback_seat;
3835                *out = fallback_out;
3836            }
3837        }
3838        Ok(())
3839    }
3840
3841    /// Ask an implement seat's own CLI to confirm what it started, once, when
3842    /// its reply reported a command whose completion status it never
3843    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3844    /// that does and does not mean.
3845    ///
3846    /// The completion contract this task asks for, extended to `implement`
3847    /// with the same signal `continue_fix_report` reads for the fixer,
3848    /// rather than a keyword search over the reply or a hard requirement on
3849    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3850    /// a candidate's CLI turn ended cleanly while a test run it had started
3851    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3852    /// named in it at all is untouched by this: `commands` is empty, so
3853    /// there is nothing to be unconfirmed.
3854    ///
3855    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3856    /// this is not about recovering edits that might already be on disk, it
3857    /// is about a result the seat itself never vouched for, which resuming
3858    /// asks for regardless of what the tree already holds. Bounded to one
3859    /// attempt for the same reason `resume_undelivered` is — this is the
3860    /// most expensive node in the graph — and a seat that still cannot
3861    /// confirm on that attempt is left as whatever its (possibly still
3862    /// unconfirmed) reply says; this does not invent a new "failed" reason
3863    /// for a candidate that otherwise produced a real, committed change.
3864    async fn resume_unconfirmed_commands(
3865        &mut self,
3866        results: &mut [(usize, SeatState, AgentOutcome)],
3867        sent: &[SeatJob],
3868        prompts: &Prompts,
3869        run_id: &str,
3870    ) {
3871        for (wi, seat, out) in results.iter_mut() {
3872            let AgentOutcome::Ok(o) = &*out else {
3873                continue;
3874            };
3875            if !has_unconfirmed_command(&o.commands) {
3876                continue;
3877            }
3878            let Some(job) = sent.get(*wi) else { continue };
3879            if !has_context(&job.spec, seat, job.sessions) {
3880                self.state.event(
3881                    "implement",
3882                    format!(
3883                        "{}: the reply named a command whose own CLI never confirmed the exit \
3884                         status of, but there is no session left to resume",
3885                        seat.key
3886                    ),
3887                );
3888                continue;
3889            }
3890            self.state.event(
3891                "implement",
3892                format!(
3893                    "{}: the reply named a command whose own CLI never confirmed the exit \
3894                     status of; resuming the conversation",
3895                    seat.key
3896                ),
3897            );
3898            let mut retry = job.clone();
3899            retry.seat = seat.clone();
3900            retry.prompt = prompt::resume_incomplete(
3901                "a command in your last reply had no confirmed exit status",
3902            );
3903            retry.timeout = retry_budget(job.timeout, true);
3904            retry.stem = format!("{}-confirm", job.stem);
3905            let cache = self.state.config.cache_dir();
3906            let ctx = WaveCtx {
3907                carry_seats: false,
3908                pauses: Some((&self.pause, &self.interrupt)),
3909                run: run_id,
3910                node: "implement",
3911                prompts,
3912                cache: cache.as_deref(),
3913                round: None,
3914            };
3915            let (resumed_seat, resumed) =
3916                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3917            *seat = resumed_seat;
3918            *out = resumed;
3919        }
3920    }
3921
3922    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
3923    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
3924    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
3925    /// that motivated this.
3926    ///
3927    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
3928    /// own nudge loop already covers for judge/review/vote seats, and not a
3929    /// dropped stream, which [`Runner::resume_undelivered`] covers for
3930    /// implement seats: here the CLI turn genuinely finished while the node's
3931    /// own work — the fixer's account of what it did — had not. Gated purely
3932    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
3933    /// reply, never on any wording in it, so a fixer whose valid, first-try
3934    /// `FixReport` happens to mention having waited on a background test is
3935    /// never resumed — the `Ok(report)` branch at the call site returns
3936    /// before this is ever invoked.
3937    ///
3938    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
3939    /// attempt ([`retry_budget`]), nothing attempted once the session is
3940    /// gone, and a quota hit ends the loop immediately rather than retrying a
3941    /// rate limit that fails the same way again.
3942    async fn continue_fix_report(
3943        &mut self,
3944        mut seat: SeatState,
3945        parse_err: String,
3946        job: &SeatJob,
3947        prompts: &Prompts,
3948        run_id: &str,
3949        round: usize,
3950    ) -> (
3951        SeatState,
3952        Option<FixReport>,
3953        Option<String>,
3954        ContinuationRecord,
3955    ) {
3956        let mut last_err = parse_err;
3957        let mut cumulative_wait_ms = 0u64;
3958        let mut attempts = 0usize;
3959        loop {
3960            if !has_context(&job.spec, &seat, job.sessions) {
3961                self.state.event(
3962                    "fix",
3963                    format!(
3964                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
3965                         session left to resume into"
3966                    ),
3967                );
3968                let outcome = if attempts == 0 {
3969                    ContinuationOutcome::NoSession
3970                } else {
3971                    ContinuationOutcome::Exhausted
3972                };
3973                return (
3974                    seat,
3975                    None,
3976                    Some(format!("unparsable fix report: {last_err}")),
3977                    ContinuationRecord {
3978                        attempts,
3979                        cumulative_wait_ms,
3980                        outcome,
3981                    },
3982                );
3983            }
3984            if attempts >= MAX_FIX_CONTINUATIONS {
3985                self.state.event(
3986                    "fix",
3987                    format!(
3988                        "round {round}: fixer's reply still had no adoption report after \
3989                         {attempts} continuation(s) ({last_err}); giving up"
3990                    ),
3991                );
3992                return (
3993                    seat,
3994                    None,
3995                    Some(format!(
3996                        "unparsable fix report after {attempts} continuation(s): {last_err}"
3997                    )),
3998                    ContinuationRecord {
3999                        attempts,
4000                        cumulative_wait_ms,
4001                        outcome: ContinuationOutcome::Exhausted,
4002                    },
4003                );
4004            }
4005            attempts += 1;
4006            self.state.event(
4007                "fix",
4008                format!(
4009                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4010                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4011                ),
4012            );
4013            let mut retry = job.clone();
4014            retry.seat = seat.clone();
4015            retry.prompt = prompt::resume_incomplete(&last_err);
4016            retry.timeout = retry_budget(job.timeout, true);
4017            retry.stem = format!("{}-continue{attempts}", job.stem);
4018            let cache = self.state.config.cache_dir();
4019            let ctx = WaveCtx {
4020                carry_seats: false,
4021                pauses: Some((&self.pause, &self.interrupt)),
4022                run: run_id,
4023                node: "fix",
4024                prompts,
4025                cache: cache.as_deref(),
4026                round: Some(round),
4027            };
4028            let (resumed_seat, resumed_out) = run_one(
4029                retry,
4030                Arc::clone(&self.sem),
4031                &ctx,
4032                &mut self.state,
4033                attempts,
4034            )
4035            .await;
4036            seat = resumed_seat;
4037            match resumed_out {
4038                AgentOutcome::Ok(o) => {
4039                    cumulative_wait_ms += o.duration_ms;
4040                    match verdict::extract_json::<FixReport>(&o.text) {
4041                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4042                            self.state.event(
4043                                "fix",
4044                                format!(
4045                                    "round {round}: fixer's adoption report recovered after \
4046                                     {attempts} continuation(s)"
4047                                ),
4048                            );
4049                            return (
4050                                seat,
4051                                Some(report),
4052                                None,
4053                                ContinuationRecord {
4054                                    attempts,
4055                                    cumulative_wait_ms,
4056                                    outcome: ContinuationOutcome::Resumed,
4057                                },
4058                            );
4059                        }
4060                        // The report parsed, but this same reply's own
4061                        // CommandEvidence — the identical record `state.jobs`
4062                        // renders — names a command whose CLI never
4063                        // confirmed an exit status. Read together, that is
4064                        // not a resolved answer: keep nudging rather than
4065                        // accept a report standing next to a command the
4066                        // seat's own CLI cannot vouch for.
4067                        Ok(_) => {
4068                            last_err = "the reply parsed, but it reported a command whose own CLI \
4069                                 never confirmed an exit status"
4070                                .to_owned();
4071                        }
4072                        Err(e) => last_err = e.to_string(),
4073                    }
4074                }
4075                AgentOutcome::Quota(o) => {
4076                    cumulative_wait_ms += o.duration_ms;
4077                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4078                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4079                    self.state.quota.push(loss);
4080                    self.state.event(
4081                        "fix",
4082                        format!(
4083                            "round {round}: continuation rate limited (quota); not retrying now"
4084                        ),
4085                    );
4086                    return (
4087                        seat,
4088                        None,
4089                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4090                        ContinuationRecord {
4091                            attempts,
4092                            cumulative_wait_ms,
4093                            outcome: ContinuationOutcome::QuotaLost,
4094                        },
4095                    );
4096                }
4097                AgentOutcome::Dropped(o) => {
4098                    cumulative_wait_ms += o.duration_ms;
4099                    let why = o
4100                        .dropped
4101                        .as_ref()
4102                        .map(|d| d.why.as_str())
4103                        .unwrap_or("the CLI ended the stream without delivering its answer");
4104                    last_err = format!("the CLI dropped the stream ({why})");
4105                }
4106                AgentOutcome::Failed(e) => last_err = e,
4107                // The continuation was never started; the report stays lost
4108                // and the caller records that, without any handover.
4109                AgentOutcome::ResourceBlocked(e) => {
4110                    return (
4111                        seat,
4112                        None,
4113                        Some(format!("the continuation was not started: {e}")),
4114                        ContinuationRecord {
4115                            attempts: attempts.saturating_sub(1),
4116                            cumulative_wait_ms,
4117                            outcome: ContinuationOutcome::NoSession,
4118                        },
4119                    );
4120                }
4121            }
4122        }
4123    }
4124
4125    fn after_implement(&mut self) -> Result<()> {
4126        if !self.state.candidate_preservation.is_empty() {
4127            bail!("candidate preservation incomplete; judging is unsafe");
4128        }
4129        // Scan every candidate patch once the set is complete.
4130        if self.state.leaks.is_empty() {
4131            let cfg = self.state.config.blind.clone();
4132            let mut leaks = Vec::new();
4133            for c in &self.state.candidates {
4134                let Some(patch) =
4135                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4136                else {
4137                    continue;
4138                };
4139                leaks.extend(blind::scan(
4140                    &format!("candidate {} patch", c.label),
4141                    &patch,
4142                    &cfg.vendor_tokens,
4143                ));
4144            }
4145            if !leaks.is_empty() {
4146                let summary = leaks
4147                    .iter()
4148                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4149                    .collect::<Vec<_>>()
4150                    .join(", ");
4151                match cfg.on_leak {
4152                    LeakPolicy::Fail => {
4153                        self.state.status = RunStatus::Failed;
4154                        self.state
4155                            .event("blind", format!("vendor text in a patch: {summary}"));
4156                        self.state.leaks = leaks;
4157                        self.state.save()?;
4158                        self.settle_questions();
4159                        bail!(
4160                            "blind.on_leak = \"fail\" and vendor text reached a \
4161                             judged patch: {summary}"
4162                        );
4163                    }
4164                    LeakPolicy::Redact => self.state.event(
4165                        "blind",
4166                        format!("redacting vendor text for judging: {summary}"),
4167                    ),
4168                    LeakPolicy::Warn => self.state.event(
4169                        "blind",
4170                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4171                    ),
4172                }
4173                self.state.leaks = leaks;
4174            }
4175        }
4176
4177        if self.state.viable().is_empty() {
4178            if self.state.all_candidates_verified_noop() {
4179                // Every candidate agreed, with evidence the adoption guard
4180                // accepted, that nothing belongs in this worktree. That is
4181                // not the same fact as a candidate that simply failed to
4182                // write anything, and settling it as an ordinary `Failed`
4183                // (see `SCHEMA`'s doc for schema 10) is what let two of
4184                // task 391f's attempts burn a retry each re-discovering the
4185                // same already-landed fix. Terminal either way, so `judge`
4186                // must never run over an empty candidate set — unlike the
4187                // `Failed` branch below this returns `Ok`, not an error:
4188                // nothing here failed.
4189                self.state.status = RunStatus::VerifiedNoop;
4190                self.state.save()?;
4191                self.settle_questions();
4192                return Ok(());
4193            }
4194            self.state.status = RunStatus::Failed;
4195            self.state.save()?;
4196            self.settle_questions();
4197            bail!("no candidate produced a change; nothing to judge");
4198        }
4199        self.state.status = RunStatus::Judging;
4200        self.state.save()?;
4201        Ok(())
4202    }
4203
4204    // --------------------------------------------------------------- judge
4205
4206    async fn judge(&mut self) -> Result<()> {
4207        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4208        // agent files with `magi task add` name the run that paid for it. The
4209        // prompt overlay is cloned alongside it because the waves borrow it
4210        // while `self` is mutably borrowed by the node's own bookkeeping.
4211        let run_id = self.state.id.clone();
4212        let prompts = self.state.config.prompts.clone();
4213        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4214            return Ok(());
4215        }
4216        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4217        if viable.len() == 1 {
4218            // Recorded so this is a one-time event: `judgements` stays empty
4219            // either way, which without this flag is indistinguishable from
4220            // "not yet judged" on the next reentry — and status is left
4221            // untouched, so a later node's conclusion (e.g. `Blocked` after
4222            // the review budget ran out) survives a resume instead of being
4223            // clobbered back to `Judging` by this node running again.
4224            self.state.judge_skipped = true;
4225            self.state.event(
4226                "judge",
4227                format!(
4228                    "only candidate {} produced a change; judging skipped",
4229                    viable[0].label
4230                ),
4231            );
4232            self.state.save()?;
4233            return Ok(());
4234        }
4235        self.state.status = RunStatus::Judging;
4236
4237        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4238        let language = self.state.config.graph.language.clone();
4239        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4240        let sessions = self.state.config.graph.sessions;
4241        let artifacts = agent::artifacts_dir(&self.state.dir());
4242        let root = self.state.worktree_root();
4243        let base_short = short(&self.state.base_commit);
4244
4245        let mut jobs = Vec::new();
4246        let mut orders = Vec::new();
4247        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4248            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4249            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4250            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4251            let seat_key = format!("judge-{}", j + 1);
4252            let seat = self.seat(&seat_key, &spec.id);
4253            jobs.push(SeatJob {
4254                prompt: prompt::judge(
4255                    &self.state.instruction,
4256                    &views,
4257                    self.roles.judges.len(),
4258                    &base_short,
4259                    &language,
4260                ),
4261                spec,
4262                seat,
4263                cwd: root.join(format!("judge-{}", j + 1)),
4264                timeout,
4265                allow_write: false,
4266                sessions,
4267                artifacts: artifacts.clone(),
4268                stem: format!("judge-{}", j + 1),
4269                handover: None,
4270            });
4271        }
4272
4273        self.state.event(
4274            "judge",
4275            format!(
4276                "{} judges ranking {} candidates blind",
4277                jobs.len(),
4278                viable.len()
4279            ),
4280        );
4281        let labels_for_check = labels.clone();
4282        let mut quota_losses = Vec::new();
4283        let cache = self.state.config.cache_dir();
4284        let ctx = WaveCtx {
4285            carry_seats: false,
4286            pauses: Some((&self.pause, &self.interrupt)),
4287            run: &run_id,
4288            node: "judge",
4289            prompts: &prompts,
4290            cache: cache.as_deref(),
4291            round: None,
4292        };
4293        let results = ask_json_wave::<Ranking>(
4294            jobs,
4295            Arc::clone(&self.sem),
4296            self.state.config.graph.retries,
4297            &self.roles.judge_roster,
4298            &ctx,
4299            &mut quota_losses,
4300            &mut self.state,
4301            &move |r: &Ranking| r.validate(&labels_for_check),
4302        )
4303        .await;
4304        if self.state.resource_block.is_some() {
4305            return self.stop_for_resource();
4306        }
4307        self.state.quota.extend(quota_losses);
4308
4309        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4310            let agent_id = seat.agent.clone();
4311            self.state.seats.insert(seat.key.clone(), seat);
4312            let mut record = Judgement {
4313                judge: j + 1,
4314                seat: format!("judge-{}", j + 1),
4315                agent: agent_id,
4316                ranking: Vec::new(),
4317                reasons: BTreeMap::new(),
4318                confidence: None,
4319                strengths: BTreeMap::new(),
4320                order: orders[j].clone(),
4321                failed: None,
4322                duration_ms: 0,
4323            };
4324            match res {
4325                Ok((ranking, out)) => {
4326                    record.ranking = ranking.normalized();
4327                    record.reasons = ranking.reasons;
4328                    record.strengths = ranking.strengths;
4329                    record.confidence = ranking.confidence;
4330                    record.duration_ms = out.duration_ms;
4331                    self.state.event(
4332                        "judge",
4333                        format!(
4334                            "judge {} ranked {}",
4335                            j + 1,
4336                            record.ranking.iter().collect::<String>()
4337                        ),
4338                    );
4339                }
4340                Err(e) => {
4341                    record.failed = Some(e.to_string());
4342                    self.state
4343                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4344                }
4345            }
4346            self.state.judgements.push(record);
4347            self.state.save()?;
4348        }
4349        Ok(())
4350    }
4351
4352    // ---------------------------------------------------------- deliberate
4353
4354    async fn deliberate(&mut self) -> Result<()> {
4355        if self.hold_base_sync().await? {
4356            return Ok(());
4357        }
4358        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4359        // agent files with `magi task add` name the run that paid for it. The
4360        // prompt overlay is cloned alongside it because the waves borrow it
4361        // while `self` is mutably borrowed by the node's own bookkeeping.
4362        let run_id = self.state.id.clone();
4363        let prompts = self.state.config.prompts.clone();
4364        let rounds = self.state.config.graph.deliberate_rounds;
4365        // Resume unfinished rounds after an outage, but never reopen a tally.
4366        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4367            return Ok(());
4368        }
4369        let tops: Vec<char> = self
4370            .state
4371            .judgements
4372            .iter()
4373            .filter_map(|j| j.ranking.first().copied())
4374            .collect();
4375        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4376            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4377                self.state.event(
4378                    "deliberate",
4379                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4380                );
4381            }
4382            self.state.status = RunStatus::Voting;
4383            self.state.save()?;
4384            return Ok(());
4385        }
4386
4387        self.state.status = RunStatus::Deliberating;
4388        self.state.event(
4389            "deliberate",
4390            format!(
4391                "split: first choices were {} — opening {rounds} round(s)",
4392                tops.iter().collect::<String>()
4393            ),
4394        );
4395
4396        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4397        let language = self.state.config.graph.language.clone();
4398        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4399        let sessions = self.state.config.graph.sessions;
4400        let artifacts = agent::artifacts_dir(&self.state.dir());
4401        let root = self.state.worktree_root();
4402        let base_short = short(&self.state.base_commit);
4403
4404        // Judges argue in sequence so that a turn can answer the one before it;
4405        // that is the difference between deliberation and three parallel
4406        // monologues.
4407        for round in self.state.deliberation.len() + 1..=rounds {
4408            let mut turns: Vec<DeliberationTurn> = Vec::new();
4409            let mut round_losses = Vec::new();
4410            let mut asked = 0;
4411            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4412                if self.state.judgements[j].failed.is_some() {
4413                    continue;
4414                }
4415                let seat_key = format!("judge-{}", j + 1);
4416                let spec = self.occupant(&seat_key, spec);
4417                let mut seat = self.seat(&seat_key, &spec.id);
4418                let transcript = self.transcript(&turns, j);
4419                let build = |context: Option<&str>| {
4420                    prompt::deliberate(
4421                        &self.state.instruction,
4422                        context,
4423                        &transcript,
4424                        round,
4425                        rounds,
4426                        &language,
4427                    )
4428                };
4429                let block = self.candidate_block(&viable, &base_short);
4430                let full = build(Some(&block));
4431                let text = if has_context(&spec, &seat, sessions) {
4432                    build(None)
4433                } else {
4434                    full.clone()
4435                };
4436                let job = SeatJob {
4437                    spec,
4438                    seat: seat.clone(),
4439                    prompt: text,
4440                    cwd: root.join(format!("judge-{}", j + 1)),
4441                    timeout,
4442                    allow_write: false,
4443                    sessions,
4444                    artifacts: artifacts.clone(),
4445                    stem: format!("delib-{round}-judge-{}", j + 1),
4446                    handover: Some(full),
4447                };
4448                let cache = self.state.config.cache_dir();
4449                let ctx = WaveCtx {
4450                    carry_seats: false,
4451                    pauses: Some((&self.pause, &self.interrupt)),
4452                    run: &run_id,
4453                    node: "deliberate",
4454                    prompts: &prompts,
4455                    cache: cache.as_deref(),
4456                    round: None,
4457                };
4458                // A turn is never nudged (`retries` 0): a failed seat is
4459                // handed to the next roster agent, which gets the full
4460                // context. An empty answer is a turn, not a failure.
4461                let mut losses = Vec::new();
4462                asked += 1;
4463                let mut results = ask_wave_with::<String>(
4464                    vec![job],
4465                    Arc::clone(&self.sem),
4466                    0,
4467                    &self.roles.judge_roster,
4468                    &ctx,
4469                    &mut losses,
4470                    &mut self.state,
4471                    &|text: &str| {
4472                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4473                    },
4474                )
4475                .await;
4476                if self.state.resource_block.is_some() {
4477                    return self.stop_for_resource();
4478                }
4479                round_losses.extend(losses.iter().cloned());
4480                self.state.quota.extend(losses);
4481                let (updated, res, _) = results.pop().expect("one job in, one result out");
4482                seat = updated;
4483                let agent_id = seat.agent.clone();
4484                self.state.seats.insert(seat.key.clone(), seat);
4485                let body = match res {
4486                    Ok((body, _)) => body,
4487                    // Skip the seat; a CLI's raw error JSON is never read as
4488                    // this judge's position.
4489                    Err(e) => {
4490                        self.state
4491                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4492                        continue;
4493                    }
4494                };
4495                let tentative = verdict::extract_json::<Position>(&body)
4496                    .ok()
4497                    .and_then(|p| p.tentative)
4498                    .and_then(|s| s.trim().chars().next())
4499                    .map(|c| c.to_ascii_uppercase());
4500                self.state.event(
4501                    "deliberate",
4502                    format!(
4503                        "round {round}: judge {} now favours {}",
4504                        j + 1,
4505                        tentative.map_or("—".to_owned(), |c| c.to_string())
4506                    ),
4507                );
4508                turns.push(DeliberationTurn {
4509                    judge: j + 1,
4510                    agent: agent_id,
4511                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4512                    tentative,
4513                });
4514            }
4515            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4516                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4517                return self.stop_for_resource();
4518            }
4519            self.state
4520                .deliberation
4521                .push(DeliberationRound { round, turns });
4522            self.state.save()?;
4523        }
4524
4525        self.state.status = RunStatus::Voting;
4526        self.state.save()?;
4527        Ok(())
4528    }
4529
4530    // ---------------------------------------------------------------- vote
4531
4532    async fn vote(&mut self) -> Result<()> {
4533        if self.hold_base_sync().await? {
4534            return Ok(());
4535        }
4536        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4537        // agent files with `magi task add` name the run that paid for it. The
4538        // prompt overlay is cloned alongside it because the waves borrow it
4539        // while `self` is mutably borrowed by the node's own bookkeeping.
4540        let run_id = self.state.id.clone();
4541        let prompts = self.state.config.prompts.clone();
4542        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4543            return Ok(());
4544        }
4545        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4546        if viable.len() == 1 {
4547            return Ok(());
4548        }
4549        self.state.status = RunStatus::Voting;
4550
4551        let language = self.state.config.graph.language.clone();
4552        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4553        let sessions = self.state.config.graph.sessions;
4554        let artifacts = agent::artifacts_dir(&self.state.dir());
4555        let root = self.state.worktree_root();
4556        let base_short = short(&self.state.base_commit);
4557        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4558
4559        let mut jobs = Vec::new();
4560        let mut seats_at = Vec::new();
4561        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4562            if self
4563                .state
4564                .judgements
4565                .get(j)
4566                .is_some_and(|r| r.failed.is_some())
4567            {
4568                continue;
4569            }
4570            let seat_key = format!("judge-{}", j + 1);
4571            let spec = self.occupant(&seat_key, spec);
4572            let seat = self.seat(&seat_key, &spec.id);
4573            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4574            let text = if has_context(&spec, &seat, sessions) {
4575                prompt::final_vote(&viable, &language)
4576            } else {
4577                full.clone()
4578            };
4579            jobs.push(SeatJob {
4580                spec,
4581                seat,
4582                prompt: text,
4583                cwd: root.join(format!("judge-{}", j + 1)),
4584                timeout,
4585                allow_write: false,
4586                sessions,
4587                artifacts: artifacts.clone(),
4588                stem: format!("vote-judge-{}", j + 1),
4589                handover: Some(full),
4590            });
4591            seats_at.push(j);
4592        }
4593
4594        self.state.event(
4595            "vote",
4596            format!(
4597                "collecting {} final votes one by one, privately",
4598                jobs.len()
4599            ),
4600        );
4601        let allowed = viable.clone();
4602        let mut quota_losses = Vec::new();
4603        let cache = self.state.config.cache_dir();
4604        let ctx = WaveCtx {
4605            carry_seats: false,
4606            pauses: Some((&self.pause, &self.interrupt)),
4607            run: &run_id,
4608            node: "vote",
4609            prompts: &prompts,
4610            cache: cache.as_deref(),
4611            round: None,
4612        };
4613        let results = ask_json_wave::<FinalVote>(
4614            jobs,
4615            Arc::clone(&self.sem),
4616            self.state.config.graph.retries,
4617            &self.roles.judge_roster,
4618            &ctx,
4619            &mut quota_losses,
4620            &mut self.state,
4621            &move |v: &FinalVote| match v.label() {
4622                Some(c) if allowed.contains(&c) => Ok(()),
4623                other => bail!("vote {other:?} is not one of {allowed:?}"),
4624            },
4625        )
4626        .await;
4627        if self.state.resource_block.is_some() {
4628            return self.stop_for_resource();
4629        }
4630        self.state.quota.extend(quota_losses);
4631
4632        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4633            let agent_id = seat.agent.clone();
4634            self.state.seats.insert(seat.key.clone(), seat);
4635            let initial = self
4636                .state
4637                .judgements
4638                .get(j)
4639                .and_then(|r| r.ranking.first().copied());
4640            let mut record = VoteRecord {
4641                judge: j + 1,
4642                agent: agent_id,
4643                vote: None,
4644                reason: String::new(),
4645                changed: false,
4646            };
4647            match res {
4648                Ok((v, _)) => {
4649                    record.vote = v.label();
4650                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4651                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4652                    self.state.event(
4653                        "vote",
4654                        format!(
4655                            "judge {} voted {}{}",
4656                            j + 1,
4657                            record.vote.unwrap_or('?'),
4658                            if record.changed { " (changed)" } else { "" }
4659                        ),
4660                    );
4661                }
4662                Err(e) => {
4663                    self.state
4664                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4665                }
4666            }
4667            self.state.votes.push(record);
4668            self.state.save()?;
4669        }
4670        Ok(())
4671    }
4672
4673    // --------------------------------------------------------------- tally
4674
4675    fn tally(&mut self) -> Result<()> {
4676        if self.state.tally.is_some() {
4677            return Ok(());
4678        }
4679        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4680        let tops: Vec<char> = self
4681            .state
4682            .judgements
4683            .iter()
4684            .filter_map(|j| j.ranking.first().copied())
4685            .collect();
4686        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4687
4688        // A judge whose private vote failed still counted once, in the initial
4689        // ranking; using it beats discarding a whole seat.
4690        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4691        let mut cast: Vec<char> = Vec::new();
4692        for (i, j) in self.state.judgements.iter().enumerate() {
4693            let vote = self
4694                .state
4695                .votes
4696                .iter()
4697                .find(|v| v.judge == i + 1)
4698                .and_then(|v| v.vote)
4699                .or_else(|| j.ranking.first().copied());
4700            if let Some(v) = vote {
4701                *first_choice.entry(v).or_insert(0) += 1;
4702                cast.push(v);
4703            }
4704        }
4705
4706        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4707        for j in &self.state.judgements {
4708            let n = j.ranking.len();
4709            for (pos, label) in j.ranking.iter().enumerate() {
4710                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4711            }
4712        }
4713
4714        let best = first_choice.values().copied().max().unwrap_or(0);
4715        let mut leaders: Vec<char> = first_choice
4716            .iter()
4717            .filter(|(_, v)| **v == best)
4718            .map(|(k, _)| *k)
4719            .collect();
4720        let mut tie_break = None;
4721        if leaders.len() > 1 {
4722            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4723            let borda_leaders: Vec<char> = leaders
4724                .iter()
4725                .copied()
4726                .filter(|l| borda[l] == top_borda)
4727                .collect();
4728            tie_break = Some(if borda_leaders.len() == 1 {
4729                format!(
4730                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4731                    leaders.len()
4732                )
4733            } else {
4734                format!(
4735                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4736                    leaders.len()
4737                )
4738            });
4739            leaders = borda_leaders;
4740            leaders.sort_unstable();
4741        }
4742        let winner = *leaders
4743            .first()
4744            .or(viable.first())
4745            .context("no candidate to declare a winner from")?;
4746
4747        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4748        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4749        let deliberated = !self.state.deliberation.is_empty();
4750
4751        // Whose verdict is this? A rate-limited seat is absent even if it
4752        // ranked before the limit hit, so presence is measured against the
4753        // recorded losses, not just "did a ranking ever appear".
4754        let quota_seats: std::collections::BTreeSet<&str> =
4755            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4756        let mut present = 0usize;
4757        for (i, j) in self.state.judgements.iter().enumerate() {
4758            if quota_seats.contains(j.seat.as_str()) {
4759                continue;
4760            }
4761            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4762            let voted = self
4763                .state
4764                .votes
4765                .iter()
4766                .any(|v| v.judge == i + 1 && v.vote.is_some());
4767            if ranked || voted {
4768                present += 1;
4769            }
4770        }
4771        // Strict majority of the configured panel. A bare majority is real
4772        // signal we can act on, while a minority verdict must never stand in
4773        // for a healthy one. A one-candidate run needs no panel at all, and
4774        // `judges` stays `0` rather than the roster size a panel that never
4775        // sat would otherwise be credited with.
4776        let needs_quorum = viable.len() > 1;
4777        let judges_total = if needs_quorum {
4778            self.roles.judges.len()
4779        } else {
4780            0
4781        };
4782        let quorum = if needs_quorum {
4783            judges_total / 2 + 1
4784        } else {
4785            0
4786        };
4787        let met_quorum = !needs_quorum || present >= quorum;
4788        let uncontested = (!needs_quorum).then(|| {
4789            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4790        });
4791
4792        self.state.event(
4793            "tally",
4794            match &uncontested {
4795                Some(reason) => format!("winner {winner} — {reason}"),
4796                None => format!(
4797                    "winner {winner} — votes {} | initial {} | {} changed | \
4798                     {present}/{judges_total} judges{}",
4799                    first_choice
4800                        .iter()
4801                        .map(|(k, v)| format!("{k}:{v}"))
4802                        .collect::<Vec<_>>()
4803                        .join(" "),
4804                    if unanimous_initial {
4805                        "unanimous"
4806                    } else {
4807                        "split"
4808                    },
4809                    changed_votes,
4810                    if met_quorum {
4811                        String::new()
4812                    } else {
4813                        format!(" — below quorum ({quorum} required)")
4814                    },
4815                ),
4816            },
4817        );
4818        if !met_quorum {
4819            self.state.event(
4820                "stall",
4821                format!(
4822                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4823                     the run stops here, resumable"
4824                ),
4825            );
4826        }
4827        self.state.tally = Some(Tally {
4828            first_choice,
4829            borda,
4830            winner,
4831            rankings: tops.len(),
4832            unanimous_initial,
4833            deliberated,
4834            changed_votes,
4835            unanimous_final,
4836            tie_break,
4837            judges: judges_total,
4838            present,
4839            quorum,
4840            met_quorum,
4841            uncontested,
4842        });
4843        self.state.status = if met_quorum {
4844            RunStatus::Reviewing
4845        } else {
4846            RunStatus::Stalled
4847        };
4848        self.state.save()?;
4849        Ok(())
4850    }
4851
4852    // ------------------------------------------------------------- recover
4853
4854    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
4855    /// resumed toward completion once the transient cause clears.
4856    ///
4857    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
4858    /// it toward the quorum, which is exactly the set of seats whose absence
4859    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
4860    /// not depend on which node happened to hit the limit), or an ordinary
4861    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
4862    /// seat is never disturbed.
4863    ///
4864    /// A seat that now answers with a usable ranking is "recovered": its
4865    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
4866    /// `tally` counts it present again), and its vote re-collected. A seat that
4867    /// still fails keeps its loss and stays absent.
4868    ///
4869    /// Returns `true` when the re-tally restores the quorum (the run may proceed
4870    /// to review/gate/merge), `false` when it is still below quorum (the run
4871    /// stays `Stalled`, still resumable for a later retry).
4872    #[allow(clippy::too_many_lines)]
4873    async fn recover_stall(&mut self) -> Result<bool> {
4874        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4875        // agent files with `magi task add` name the run that paid for it. The
4876        // prompt overlay is cloned alongside it because the waves borrow it
4877        // while `self` is mutably borrowed by the node's own bookkeeping.
4878        let run_id = self.state.id.clone();
4879        let prompts = self.state.config.prompts.clone();
4880        // Absent seats = quota-lost at any node, or failed outright. Mirroring
4881        // `tally`'s presence test (rather than the old quota-judge/vote filter)
4882        // is what keeps a non-quota collapse — or a quota loss recorded at the
4883        // deliberate node — from being a permanent dead-end on `--resume`.
4884        let quota_seats: BTreeSet<&str> =
4885            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4886        let absent: Vec<String> = self
4887            .state
4888            .judgements
4889            .iter()
4890            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
4891            .map(|j| j.seat.clone())
4892            .collect();
4893        if absent.is_empty() {
4894            return Ok(false);
4895        }
4896        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4897        if viable.len() <= 1 {
4898            return Ok(false);
4899        }
4900        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4901        let language = self.state.config.graph.language.clone();
4902        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4903        let sessions = self.state.config.graph.sessions;
4904        let artifacts = agent::artifacts_dir(&self.state.dir());
4905        let root = self.state.worktree_root();
4906        let base_short = short(&self.state.base_commit);
4907        let candidates: Vec<Candidate> = viable.clone();
4908
4909        // Map each absent seat key to its 0-based position in `roles.judges`.
4910        let mut positions: Vec<usize> = absent
4911            .iter()
4912            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
4913            .collect();
4914        if positions.is_empty() {
4915            return Ok(false);
4916        }
4917        positions.sort_unstable();
4918        positions.dedup();
4919
4920        // Re-rank the lost seats, one blind prompt each.
4921        let mut judge_jobs = Vec::new();
4922        for &j in &positions {
4923            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4924            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4925            let seat_key = format!("judge-{}", j + 1);
4926            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
4927            let seat = self.seat(&seat_key, &spec.id);
4928            judge_jobs.push(SeatJob {
4929                spec,
4930                seat,
4931                prompt: prompt::judge(
4932                    &self.state.instruction,
4933                    &views,
4934                    self.roles.judges.len(),
4935                    &base_short,
4936                    &language,
4937                ),
4938                cwd: root.join(seat_key),
4939                timeout,
4940                allow_write: false,
4941                sessions,
4942                artifacts: artifacts.clone(),
4943                stem: format!("judge-{}-recover", j + 1),
4944                handover: None,
4945            });
4946        }
4947
4948        let labels_for_check = labels.clone();
4949        let mut judge_losses = Vec::new();
4950        let retries = self.state.config.graph.retries;
4951        let cache = self.state.config.cache_dir();
4952        let ctx = WaveCtx {
4953            carry_seats: false,
4954            pauses: Some((&self.pause, &self.interrupt)),
4955            run: &run_id,
4956            node: "judge",
4957            prompts: &prompts,
4958            cache: cache.as_deref(),
4959            round: None,
4960        };
4961        let results = ask_json_wave::<Ranking>(
4962            judge_jobs,
4963            Arc::clone(&self.sem),
4964            retries,
4965            &self.roles.judge_roster,
4966            &ctx,
4967            &mut judge_losses,
4968            &mut self.state,
4969            &move |r: &Ranking| r.validate(&labels_for_check),
4970        )
4971        .await;
4972        if self.state.resource_block.is_some() {
4973            self.stop_for_resource()?;
4974            return Ok(false);
4975        }
4976
4977        // Refresh the judgement of every seat that ranked again.
4978        let mut recovered: BTreeSet<usize> = BTreeSet::new();
4979        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
4980            let agent_id = seat.agent.clone();
4981            self.state.seats.insert(seat.key.clone(), seat);
4982            let record = &mut self.state.judgements[j];
4983            match res {
4984                Ok((ranking, out)) => {
4985                    record.agent = agent_id;
4986                    record.ranking = ranking.normalized();
4987                    record.reasons = ranking.reasons;
4988                    record.strengths = ranking.strengths;
4989                    record.confidence = ranking.confidence;
4990                    record.failed = None;
4991                    record.duration_ms = out.duration_ms;
4992                    recovered.insert(j);
4993                    self.state.event(
4994                        "recover",
4995                        format!("judge {} ranked again after the limit", j + 1),
4996                    );
4997                }
4998                Err(e) => {
4999                    self.state
5000                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5001                }
5002            }
5003        }
5004
5005        // Re-ask the votes of the seats that recovered a ranking.
5006        let mut vote_jobs = Vec::new();
5007        let mut vote_pos: Vec<usize> = Vec::new();
5008        for &j in &recovered {
5009            let seat_key = format!("judge-{}", j + 1);
5010            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5011            let seat = self.seat(&seat_key, &spec.id);
5012            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5013            let text = if has_context(&spec, &seat, sessions) {
5014                prompt::final_vote(&labels, &language)
5015            } else {
5016                full.clone()
5017            };
5018            vote_jobs.push(SeatJob {
5019                spec,
5020                seat,
5021                prompt: text,
5022                cwd: root.join(seat_key),
5023                timeout,
5024                allow_write: false,
5025                sessions,
5026                artifacts: artifacts.clone(),
5027                stem: format!("vote-judge-{}-recover", j + 1),
5028                handover: Some(full),
5029            });
5030            vote_pos.push(j);
5031        }
5032        let allowed = labels.clone();
5033        let mut vote_losses = Vec::new();
5034        let vote_retries = self.state.config.graph.retries;
5035        let vote_cache = self.state.config.cache_dir();
5036        let ctx = WaveCtx {
5037            carry_seats: false,
5038            pauses: Some((&self.pause, &self.interrupt)),
5039            run: &run_id,
5040            node: "vote",
5041            prompts: &prompts,
5042            cache: vote_cache.as_deref(),
5043            round: None,
5044        };
5045        let votes = ask_json_wave::<FinalVote>(
5046            vote_jobs,
5047            Arc::clone(&self.sem),
5048            vote_retries,
5049            &self.roles.judge_roster,
5050            &ctx,
5051            &mut vote_losses,
5052            &mut self.state,
5053            &move |v: &FinalVote| match v.label() {
5054                Some(c) if allowed.contains(&c) => Ok(()),
5055                other => bail!("vote {other:?} is not one of {allowed:?}"),
5056            },
5057        )
5058        .await;
5059        if self.state.resource_block.is_some() {
5060            self.stop_for_resource()?;
5061            return Ok(false);
5062        }
5063        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5064            let agent_id = seat.agent.clone();
5065            self.state.seats.insert(seat.key.clone(), seat);
5066            match res {
5067                Ok((v, _)) => {
5068                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5069                        rec.vote = v.label();
5070                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5071                    } else {
5072                        self.state.votes.push(VoteRecord {
5073                            judge: j + 1,
5074                            agent: agent_id,
5075                            vote: v.label(),
5076                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5077                            changed: false,
5078                        });
5079                    }
5080                    self.state.event(
5081                        "recover",
5082                        format!("judge {} voted again after the limit", j + 1),
5083                    );
5084                }
5085                Err(e) => {
5086                    self.state
5087                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5088                }
5089            }
5090        }
5091
5092        // A seat that ranked again is present even if its re-vote failed —
5093        // `tally` falls back to the initial ranking's first choice — so clear
5094        // its quota loss. Seats that still fail keep theirs and stay absent.
5095        let recovered_keys: BTreeSet<String> = recovered
5096            .iter()
5097            .map(|&j| format!("judge-{}", j + 1))
5098            .collect();
5099        self.state
5100            .quota
5101            .retain(|q| !recovered_keys.contains(&q.seat));
5102        // A seat that hit the limit again is a fresh loss, not the old one:
5103        // replace the stale entry so the history stays one-per-seat and the
5104        // daemon can tell this attempt's loss from a previous session's.
5105        for loss in judge_losses.into_iter().chain(vote_losses) {
5106            if recovered_keys.contains(&loss.seat) {
5107                continue;
5108            }
5109            self.state.quota.retain(|q| q.seat != loss.seat);
5110            self.state.quota.push(loss);
5111        }
5112
5113        // Recompute the verdict from the refreshed panel.
5114        self.state.tally = None;
5115        self.tally()?;
5116        Ok(self
5117            .state
5118            .tally
5119            .as_ref()
5120            .map(|t| t.met_quorum)
5121            .unwrap_or(false))
5122    }
5123
5124    // ---------------------------------------------------------------- graft
5125
5126    /// Port the strengths the judges attributed to the losing candidates onto
5127    /// the winner, once, between the tally and the review loop.
5128    ///
5129    /// Best-effort by construction: it returns nothing and fails nothing. A
5130    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5131    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5132    /// the run carries on as if the phase were off. See [`graft`] for the
5133    /// decisions and `AGENTS.md` for the invariants.
5134    ///
5135    /// The one exception is a rollback that could not be confirmed: the
5136    /// rejected commit may still be the winner's tip, so the run is blocked
5137    /// (resumable; the record stays `Running`, which makes a resume retry the
5138    /// restore) instead of reviewing, gating and merging it.
5139    async fn graft(&mut self) -> Result<()> {
5140        let Err(e) = self.graft_inner().await else {
5141            return Ok(());
5142        };
5143        if e.is::<crate::repo_lock::ResourceBlocked>() {
5144            return Err(e);
5145        }
5146        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5147            self.state.status = RunStatus::Blocked;
5148            self.state.event("graft", format!("blocked: {e:#}"));
5149            self.state.save()?;
5150            return Err(e);
5151        }
5152        // An error after the `Running` record was saved may have left the
5153        // fixer's work in the tree: the record must not stay unsettled
5154        // (a later resume would reset past the review fixes), so confirm the
5155        // restore now, or block.
5156        if let Some(rec) = self.state.graft.clone()
5157            && !rec.outcome.settled()
5158        {
5159            if let Some(winner) = self.state.winner().cloned() {
5160                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5161                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5162                        return Err(re);
5163                    }
5164                    self.state.status = RunStatus::Blocked;
5165                    self.state.event("graft", format!("blocked: {re:#}"));
5166                    self.state.save()?;
5167                    return Err(re);
5168                }
5169            }
5170            if let Some(g) = self.state.graft.as_mut() {
5171                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5172            }
5173        }
5174        self.state.event("graft", format!("skipped: {e:#}"));
5175        if let Err(e) = self.state.save() {
5176            tracing::warn!("save after graft: {e:#}");
5177        }
5178        Ok(())
5179    }
5180
5181    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5182    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5183    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5184        let _coordination = self.coordinate(wt).await?;
5185        crate::recovery::restore_repair(wt, pre)
5186            .await
5187            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5188    }
5189
5190    /// A skip is a run event, recorded once however often the node is re-entered.
5191    fn graft_skipped(&mut self, why: &str) {
5192        let message = format!("skipped: {why}");
5193        if !self
5194            .state
5195            .events
5196            .iter()
5197            .any(|e| e.node == "graft" && e.message == message)
5198        {
5199            self.state.event("graft", message);
5200        }
5201    }
5202
5203    async fn graft_inner(&mut self) -> Result<()> {
5204        // A round that was started and never finished (crash, kill): the
5205        // fixer may have left anything in the tree, so put the winner back.
5206        if let Some(rec) = self.state.graft.clone()
5207            && !rec.outcome.settled()
5208        {
5209            // Reviews exist only if the graft ended without its record being
5210            // settled (a swallowed error): the tree has moved on since, and
5211            // a reset to `pre` would discard the review fixes.
5212            if self.state.reviews.is_empty()
5213                && let Some(winner) = self.state.winner().cloned()
5214            {
5215                self.graft_restore(&winner.worktree, &rec.pre).await?;
5216            }
5217            if rec.outcome == GraftOutcome::WaitingForRestore {
5218                self.state.graft = None;
5219                self.state.save()?;
5220            } else {
5221                if let Some(g) = self.state.graft.as_mut() {
5222                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5223                }
5224                self.state.event(
5225                    "graft",
5226                    "rolled back: the previous round was interrupted; the winner is untouched",
5227                );
5228                self.state.save()?;
5229                return Ok(());
5230            }
5231        }
5232        let plan = match graft::plan(&self.state) {
5233            Ok(plan) => plan,
5234            Err(skip) => {
5235                if skip != graft::Skip::AlreadyDone {
5236                    self.graft_skipped(skip.reason());
5237                    self.state.save()?;
5238                }
5239                return Ok(());
5240            }
5241        };
5242        let Some(winner) = self.state.winner().cloned() else {
5243            return Ok(());
5244        };
5245        let wt = winner.worktree.clone();
5246        if !git::is_clean(&wt).await? {
5247            self.graft_skipped("the winner's worktree has uncommitted changes");
5248            self.state.save()?;
5249            return Ok(());
5250        }
5251        let pre = git::rev_parse(&wt, "HEAD").await?;
5252        // Saved before the fixer is called: a stop from here on is repaired
5253        // by the branch above on the next entry.
5254        self.state.graft = Some(GraftRecord {
5255            pre: pre.clone(),
5256            post: None,
5257            lines: None,
5258            limit: None,
5259            agent: None,
5260            outcome: GraftOutcome::Running,
5261            requested: graft::requested(&plan),
5262            adoption: None,
5263            adoption_error: None,
5264        });
5265        self.state.event(
5266            "graft",
5267            format!(
5268                "porting strengths of candidate(s) {} onto {}",
5269                plan.strengths
5270                    .iter()
5271                    .map(|(l, _, _)| l.to_string())
5272                    .collect::<Vec<_>>()
5273                    .join(", "),
5274                plan.winner
5275            ),
5276        );
5277        self.state.save()?;
5278
5279        let fix_prompt = prompt::graft(
5280            &self.state.instruction,
5281            plan.winner,
5282            &plan.strengths,
5283            &self.state.config.graph.language,
5284        );
5285        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5286        let sessions = self.state.config.graph.sessions;
5287        let artifacts = agent::artifacts_dir(&self.state.dir());
5288        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5289        let (_, seat, out) = self
5290            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5291                SeatJob {
5292                    prompt: fix_prompt.clone(),
5293                    spec,
5294                    seat,
5295                    cwd: wt.clone(),
5296                    timeout,
5297                    allow_write: true,
5298                    sessions,
5299                    artifacts: artifacts.clone(),
5300                    stem: "graft".to_owned(),
5301                    handover: None,
5302                }
5303            })
5304            .await;
5305        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5306            // Preserve the need to restore earlier fallback edits without
5307            // confusing an unstarted seat with an interrupted invocation.
5308            self.state.graft.as_mut().expect("graft record").outcome =
5309                GraftOutcome::WaitingForRestore;
5310            return self.stop_for_resource();
5311        }
5312        let mut why: Option<String> = None;
5313        match &out {
5314            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5315                why = Some("the fixer produced nothing usable".to_owned());
5316            }
5317            AgentOutcome::Ok(_) => {}
5318            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5319            AgentOutcome::Quota(o) => {
5320                self.state.quota.push(QuotaLoss::from_report(
5321                    seat.key.clone(),
5322                    "graft",
5323                    o.quota.as_ref(),
5324                ));
5325                why = Some("rate limited (quota)".to_owned());
5326            }
5327            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5328                why = Some(format!(
5329                    "the fixer failed: {}",
5330                    e.lines()
5331                        .next()
5332                        .unwrap_or("")
5333                        .chars()
5334                        .take(160)
5335                        .collect::<String>()
5336                ));
5337            }
5338        }
5339        let agent_id = seat.agent.clone();
5340        self.state.seats.insert(seat.key.clone(), seat);
5341
5342        let mut post = None;
5343        let mut lines = None;
5344        let _coordination = self.coordinate(&wt).await?;
5345        if why.is_none() {
5346            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5347            if let Ok(r) = &rescued {
5348                self.state.note_withheld("graft", &r.withheld);
5349            }
5350            let head = git::rev_parse(&wt, "HEAD").await?;
5351            // What is measured must be what gets reviewed and gated: a failed
5352            // rescue, or anything still uncommitted (withheld lockfiles
5353            // aside, which are never part of the tree), rejects the graft.
5354            let dirty = match &rescued {
5355                Ok(r) => git::status_porcelain(&wt)
5356                    .await
5357                    .map(|st| {
5358                        st.lines().any(|l| {
5359                            !r.withheld
5360                                .iter()
5361                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5362                        })
5363                    })
5364                    .unwrap_or(true),
5365                Err(_) => true,
5366            };
5367            if dirty {
5368                why = Some("the fixer left changes that could not be committed".to_owned());
5369            } else if head == pre {
5370                why = Some("the fixer changed nothing".to_owned());
5371            } else {
5372                lines = git::changed_lines(&wt, &pre, &head).await;
5373                post = Some(head);
5374            }
5375        }
5376        let (adoption, adoption_error) = match &out {
5377            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5378            _ => (None, None),
5379        };
5380        let requested = graft::requested(&plan);
5381        let outcome = match why {
5382            None => {
5383                self.state.event(
5384                    "graft",
5385                    format!(
5386                        "applied: {}",
5387                        lines.map_or_else(
5388                            || "changed lines unavailable".to_owned(),
5389                            |n| format!("{n} changed lines")
5390                        )
5391                    ),
5392                );
5393                GraftOutcome::Applied
5394            }
5395            Some(why) => {
5396                // Not settled until the restore is confirmed: the record
5397                // stays `Running`, so a resume retries it.
5398                crate::recovery::restore_repair(&wt, &pre)
5399                    .await
5400                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5401                self.state.event(
5402                    "graft",
5403                    format!("rolled back: {why}; the winner is untouched"),
5404                );
5405                GraftOutcome::RolledBack(why)
5406            }
5407        };
5408        self.state.graft = Some(GraftRecord {
5409            pre,
5410            post,
5411            lines,
5412            limit: None,
5413            agent: Some(agent_id),
5414            outcome,
5415            requested,
5416            adoption,
5417            adoption_error,
5418        });
5419        self.state.save()?;
5420        Ok(())
5421    }
5422
5423    // ----------------------------------------------------------------- fold
5424
5425    async fn fold_losers(&mut self) -> Result<()> {
5426        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5427            return Ok(());
5428        };
5429        if !self.state.candidate_preservation.is_empty() {
5430            bail!("candidate preservation incomplete; refusing cleanup");
5431        }
5432        let repo = self.state.repo.clone();
5433        let _coordination = self.coordinate(&repo).await?;
5434        let home = crate::run::home();
5435        let root = self.state.worktree_root();
5436        let isolated = crate::build_target::isolated(&self.state.config);
5437        let mut folded = Vec::new();
5438        for i in 0..self.state.candidates.len() {
5439            let c = &self.state.candidates[i];
5440            if c.label == winner || c.folded {
5441                continue;
5442            }
5443            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5444            let target = fold_target(&home, &root, &wt, isolated);
5445            remove_preserved_worktree(&repo, &wt).await?;
5446            reclaim_fold_target(&home, target);
5447            if git::branch_exists(&repo, &branch).await?
5448                && !git::branch_delete(&repo, &branch).await?
5449            {
5450                bail!("candidate branch removal refused");
5451            }
5452            self.state.candidates[i].folded = true;
5453            self.state.save()?;
5454            folded.push(label.to_string());
5455        }
5456        // The judges are finished; their checkouts are pure cost from here.
5457        for j in 1..=self.roles.judges.len() {
5458            let wt = root.join(format!("judge-{j}"));
5459            if wt.exists() {
5460                let target = fold_target(&home, &root, &wt, isolated);
5461                remove_read_seat_worktree(&mut self.state, &wt).await?;
5462                reclaim_fold_target(&home, target);
5463                self.state.save()?;
5464            }
5465        }
5466        // The design-deliberation stage is finished by the time a tally
5467        // exists — same reasoning as the judges above.
5468        if self.state.config.graph.advise {
5469            for k in 1..=self.state.config.graph.advisors {
5470                let wt = root.join(format!("advisor-{k}"));
5471                if wt.exists() {
5472                    let target = fold_target(&home, &root, &wt, isolated);
5473                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5474                    reclaim_fold_target(&home, target);
5475                    self.state.save()?;
5476                }
5477            }
5478        }
5479        if !folded.is_empty() {
5480            self.state
5481                .event("fold", format!("folded candidates {}", folded.join(", ")));
5482            self.state.save()?;
5483        }
5484        Ok(())
5485    }
5486
5487    // ------------------------------------------------------------ base sync
5488
5489    async fn hold_base_sync(&mut self) -> Result<bool> {
5490        self.hold_base_sync_as(None).await
5491    }
5492
5493    async fn hold_base_sync_kind(
5494        &mut self,
5495        kind: crate::base_sync_recovery::StopKind,
5496    ) -> Result<()> {
5497        self.hold_base_sync_as(Some(kind)).await?;
5498        Ok(())
5499    }
5500
5501    async fn hold_base_sync_as(
5502        &mut self,
5503        kind: Option<crate::base_sync_recovery::StopKind>,
5504    ) -> Result<bool> {
5505        if !self.state.base_sync_blocked() {
5506            self.state.base_sync_recovery.stop = None;
5507            return Ok(false);
5508        }
5509        let head = match self.state.winner() {
5510            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5511                .await
5512                .unwrap_or_default(),
5513            None => String::new(),
5514        };
5515        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5516            && !authorization.consumed
5517            && authorization.stop.head != head
5518        {
5519            authorization.refuse(format!(
5520                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5521                authorization.stop.head
5522            ));
5523        }
5524        self.state.record_base_sync_stop(&head);
5525        if let Some(kind) = kind {
5526            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5527            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5528                stop.kind = kind;
5529            }
5530        }
5531        self.state.save()?;
5532        Ok(true)
5533    }
5534
5535    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5536    /// anything verifies it.
5537    ///
5538    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5539    /// read whatever is checked out in the winner's worktree. Left alone that
5540    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5541    /// it when the run *branched* - and a run takes long enough that the base
5542    /// has usually moved by the time it gets here. A gate that ran there
5543    /// answers "green on the commit this run started from", not "green on
5544    /// what is about to land", and the difference showed up three times in
5545    /// one day as a green run whose merge would have reverted a file another
5546    /// pull request had already landed.
5547    ///
5548    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5549    /// `land::Step::Rebase` calls, rather than a second implementation of the
5550    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5551    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5552    /// doc warns about ("two answers to a question nobody notices until a
5553    /// diff is wrong").
5554    ///
5555    /// Foreign-checkout reviews instead merge the base into the owned shadow
5556    /// worktree, preserving the ancestry required for fast-forward delivery.
5557    /// A conflicting merge is aborted and held for operator resolution.
5558    ///
5559    /// A conflict is not the end of the road: the standing rebase is handed
5560    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5561    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5562    /// land). Once it finishes, review and the gate run as usual on the
5563    /// rebased tree, which is where a breakage the new base caused is caught
5564    /// by the ordinary gate-fix round. magi resolves nothing itself.
5565    ///
5566    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5567    /// the current durable recovery interval, bounds how often the base is
5568    /// synchronized during active recovery (lifetime attempts remain evidence).
5569    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5570    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5571    /// what was tried (rounds spent, paths still conflicted) and the branch
5572    /// and worktree stay exactly as they were - untouched, for a person to
5573    /// look at - which is also what makes re-entering this function
5574    /// afterwards a no-op instead of a second attempt at the same wall. A
5575    /// push failure ends the same way.
5576    async fn sync_to_base(&mut self) -> Result<()> {
5577        if self.state.status == RunStatus::AlreadyInBase {
5578            return Ok(());
5579        }
5580        self.hold_base_sync().await?;
5581        let conflicted = self
5582            .state
5583            .base_sync
5584            .as_ref()
5585            .is_some_and(|s| s.conflict.is_some());
5586        let Some(winner) = self.state.winner().cloned() else {
5587            return Ok(());
5588        };
5589
5590        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5591
5592        let repo = self.state.repo.clone();
5593        let remote = self.state.config.merge.remote.clone();
5594        let base_branch = self.state.base_branch.clone();
5595        let tracking = format!("{remote}/{base_branch}");
5596
5597        let fetched_base =
5598            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5599        if !fetched_base
5600            && self
5601                .state
5602                .base_sync_recovery
5603                .stop
5604                .as_ref()
5605                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
5606        {
5607            self.state.event(
5608                "land",
5609                "cannot recheck recorded public branch divergence without a fresh base",
5610            );
5611            self.state.save()?;
5612            return Ok(());
5613        }
5614        // No network, or the remote never had this branch: the run already
5615        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5616        // otherwise), and one that got this far is not blocked by a fetch
5617        // that fails now. It just has no newer tip to compare against.
5618        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5619            return Ok(());
5620        };
5621
5622        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5623        self.state.ensure_base_episode();
5624        let mut pending = self
5625            .state
5626            .base_sync_recovery
5627            .operations
5628            .last()
5629            .filter(|o| !o.finished)
5630            .cloned();
5631        let scratch = self.state.dir().join("base-sync");
5632        if git::rebase_in_progress(&scratch).await {
5633            // Older resource stops predate operation reservations. Import the
5634            // standing Git operation, never retarget it to today's main.
5635            if pending.is_none()
5636                && self.state.base_sync_recovery.operations.is_empty()
5637                && !conflicted
5638                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5639                    .await
5640                    .ok()
5641                    .as_deref()
5642                    == Some(head.as_str())
5643                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5644                && git::is_clean(&winner.worktree).await?
5645            {
5646                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5647                if self.state.base_sync.is_none() {
5648                    self.state.base_sync = Some(BaseSync {
5649                        tip: saved_tip.clone(),
5650                        behind: 0,
5651                        attempts: 0,
5652                        conflict: None,
5653                        already_in: None,
5654                    });
5655                }
5656                self.state.reserve_base_operation(&head, &saved_tip);
5657                self.state.event(
5658                    "base-recovery",
5659                    "imported standing legacy rebase as a spent synchronization reservation",
5660                );
5661                self.state.save()?;
5662                pending = self.state.base_sync_recovery.operations.last().cloned();
5663            }
5664            let expected = pending.as_ref().map(|op| op.tip.as_str());
5665            if expected.is_none()
5666                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5667            {
5668                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5669                if self.state.base_sync.is_none() {
5670                    self.state.base_sync = Some(BaseSync {
5671                        tip: tip.clone(),
5672                        behind: 0,
5673                        attempts: 0,
5674                        conflict: None,
5675                        already_in: None,
5676                    });
5677                }
5678                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5679                self.state.event("land", why);
5680                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5681                    .await?;
5682                return Ok(());
5683            }
5684        }
5685        if let Some(op) = &pending {
5686            // A replay may add the pinned base's commits, never foreign work.
5687            let mut replay_proven =
5688                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5689            if !replay_proven && scratch.exists() && !git::rebase_in_progress(&scratch).await {
5690                let wait = repository_wait(&self.state, None);
5691                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5692                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5693                    Ok(true) => {
5694                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5695                        self.state.save()?;
5696                        git::worktree_remove(&repo, &scratch).await.ok();
5697                        replay_proven = true;
5698                    }
5699                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5700                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5701                }
5702            }
5703            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5704                if self.state.foreign_checkout.is_some() {
5705                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5706                        .await
5707                        .ok()
5708                        .as_deref()
5709                        == Some(op.head.as_str())
5710                        && git::rev_parse(&repo, &format!("{head}^2"))
5711                            .await
5712                            .ok()
5713                            .as_deref()
5714                            == Some(op.tip.as_str());
5715                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5716                    .await
5717                    .is_ok_and(|m| m.is_empty())
5718                    && let Ok(added) =
5719                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5720                {
5721                    replay_proven = true;
5722                    for commit in added {
5723                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5724                            replay_proven = false;
5725                            break;
5726                        }
5727                    }
5728                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5729                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5730                }
5731            }
5732            // Never retarget an operation across a crash, even if main moved.
5733            // sync_to_head resets and cleans with -x, so even ignored untracked
5734            // files must stop recovery independently of the old tracked tree.
5735            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5736                || (head != op.head
5737                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5738                        .await?
5739                        .is_empty())
5740                || (!git::is_clean(&winner.worktree).await?
5741                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5742                        .await
5743                        .is_ok_and(|o| o.ok()))
5744                || !replay_proven
5745            {
5746                let why = format!(
5747                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
5748                    op.id
5749                );
5750                let sync = self
5751                    .state
5752                    .base_sync
5753                    .as_mut()
5754                    .context("reserved synchronization has no lifetime accounting")?;
5755                sync.conflict = Some(why.clone());
5756                self.state.event("land", why);
5757                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5758                    .await?;
5759                return Ok(());
5760            }
5761            if head != op.head {
5762                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5763            }
5764            tip = op.tip.clone();
5765        }
5766        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
5767        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
5768        if pending.is_none()
5769            && !conflicted
5770            && fetched_base
5771            && self
5772                .state
5773                .base_sync_recovery
5774                .episodes
5775                .last()
5776                .is_some_and(|e| e.boundary.is_some())
5777            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
5778            && let Ok(owner) = crate::queue::Queue::open().get(&task)
5779            && owner.execution_runs().last() == Some(&self.state.id)
5780            && owner.status != crate::queue::TaskStatus::Done
5781            && !owner.fresh_start
5782            && owner.review_branch.is_none()
5783            && crate::daemon::compatible_run_instruction(&self.state, &owner)
5784            && let Some(approval) = owner.resumption.as_ref()
5785            && approval.instruction == owner.instruction
5786            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5787            && git::is_clean(&winner.worktree).await?
5788            && self.state.renew_base_episode(&task, approval, &head, &tip)
5789        {
5790            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
5791            self.state.save()?;
5792        }
5793
5794        // Before any rebase, and before a recorded conflict is honoured: a
5795        // branch whose change reached the base under other commit ids has
5796        // nothing to rebase and nothing to conflict with, and a run that
5797        // already stopped on that phantom conflict recovers here on resume.
5798        // `behind == 0` with head == tip is a branch the base has since taken
5799        // in whole, whether or not a conflict was ever recorded: the ancestry
5800        // proof must still run (`classify` ignores a head still on the start
5801        // commit).
5802        if (behind > 0 || conflicted || head == tip)
5803            && self
5804                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
5805                .await?
5806        {
5807            return Ok(());
5808        }
5809        if conflicted && self.state.base_recovery_pending() {
5810            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
5811            let owner =
5812                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
5813            let owner_valid = owner.as_ref().is_ok_and(|t| {
5814                t.execution_runs().last() == Some(&self.state.id)
5815                    && t.status != crate::queue::TaskStatus::Done
5816                    && !t.fresh_start
5817                    && t.review_branch.is_none()
5818            });
5819            let invalidation = if !owner_valid {
5820                Some("latest task ownership changed")
5821            } else if !owner.as_ref().is_ok_and(|t| {
5822                authorization
5823                    .generation
5824                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
5825            }) {
5826                Some("owner approval generation changed")
5827            } else if authorization.question.as_ref().is_some_and(|question| {
5828                !crate::base_recovery_control::decision_current(
5829                    &crate::queue::Queue::at(crate::run::home().join("queue")),
5830                    &self.state,
5831                    &authorization.task,
5832                    question,
5833                )
5834            }) {
5835                Some("recovery decision ownership, routing or stop evidence changed")
5836            } else if authorization.request.is_some()
5837                && !owner
5838                    .as_ref()
5839                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
5840            {
5841                Some("owner decision changed")
5842            } else if let Some(scope) = &authorization.scope {
5843                if scope.tip != tip {
5844                    Some("fetched base changed")
5845                } else if !self
5846                    .state
5847                    .base_sync_recovery
5848                    .episodes
5849                    .last()
5850                    .is_some_and(|e| e.id == scope.episode)
5851                {
5852                    Some("active synchronization interval changed")
5853                } else if !owner
5854                    .as_ref()
5855                    .is_ok_and(|t| t.instruction == scope.instruction)
5856                {
5857                    Some("task instruction changed")
5858                } else {
5859                    None
5860                }
5861            } else {
5862                None
5863            };
5864            if let Some(reason) = invalidation {
5865                let authorization = self
5866                    .state
5867                    .base_sync_recovery
5868                    .authorizations
5869                    .last_mut()
5870                    .unwrap();
5871                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
5872                self.state.save()?;
5873                return Ok(());
5874            }
5875            if !fetched_base
5876                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5877                || !git::is_clean(&winner.worktree).await?
5878                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
5879            {
5880                return Ok(());
5881            }
5882        }
5883        let recovery = conflicted && self.state.consume_base_recovery(&head);
5884        if conflicted {
5885            // Consumption (including a refused changed HEAD) is durable before Git.
5886            self.state.save()?;
5887            if !recovery {
5888                return Ok(());
5889            }
5890        }
5891
5892        if behind == 0 {
5893            // A fixer-finished rebase moves the branch ref before the
5894            // winner's worktree is told (`sync_to_head` below). A run that
5895            // died in between resumes here with `behind == 0` and a tree still
5896            // holding the pre-rebase files, which review and the gate would
5897            // then read. That state is exactly: HEAD moved off the tip the
5898            // rebase started from, yet the tree is still identical to that
5899            // tip. A tree with edits of its own differs from it, so nothing
5900            // is thrown away.
5901            if let Some(from) = self
5902                .state
5903                .rebase_fixes
5904                .iter()
5905                .rev()
5906                .find_map(|r| r.from.clone())
5907                && from != head
5908                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
5909                    .await
5910                    .is_ok_and(|o| o.ok())
5911            {
5912                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5913            }
5914            // An earlier attempt may have rebased the branch locally and died
5915            // before pushing it (only the fresh-rebase arm below pushes).
5916            // Publish it now, so the plain push at PR time is not refused as
5917            // a non-fast-forward. A run already holding a recorded conflict
5918            // never reaches here; that case is out of scope.
5919            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
5920            if let Some(why) = &conflict {
5921                self.state.status = RunStatus::Blocked;
5922                self.state.event("land", why.clone());
5923            }
5924            self.state.base_sync = Some(BaseSync {
5925                tip,
5926                behind: 0,
5927                attempts,
5928                conflict,
5929                already_in: None,
5930            });
5931            if pending.is_some() {
5932                self.state.finish_base_operation(Some(&head));
5933            }
5934            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
5935                .await?;
5936            self.state.save()?;
5937            return Ok(());
5938        }
5939
5940        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
5941            let why = format!(
5942                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
5943                 synchronization(s); synchronizing again would only race it",
5944                winner.branch
5945            );
5946            self.state.status = RunStatus::Blocked;
5947            self.state.base_sync = Some(BaseSync {
5948                tip,
5949                behind,
5950                attempts,
5951                conflict: Some(why.clone()),
5952                already_in: None,
5953            });
5954            self.state.event("land", why);
5955            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
5956                .await?;
5957            self.state.save()?;
5958            return Ok(());
5959        }
5960
5961        if self.state.foreign_checkout.is_some() {
5962            // Delivery to the operator's checkout is fast-forward only. A
5963            // rebase here would discard its saved head from our ancestry.
5964            let wait = repository_wait(&self.state, None);
5965            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5966            if self.state.base_sync.is_none() {
5967                self.state.base_sync = Some(BaseSync {
5968                    tip: tip.clone(),
5969                    behind,
5970                    attempts: 0,
5971                    conflict: None,
5972                    already_in: None,
5973                });
5974            }
5975            self.state.reserve_base_operation(&head, &tip);
5976            self.state.save()?;
5977            let merged = git::git_raw(
5978                &winner.worktree,
5979                &[
5980                    "-c",
5981                    "core.hooksPath=/dev/null",
5982                    "merge",
5983                    "--no-ff",
5984                    "--no-autostash",
5985                    "--no-edit",
5986                    "-m",
5987                    &format!("Merge {tracking} before verifying"),
5988                    &tip,
5989                ],
5990            )
5991            .await?;
5992            let conflict = if merged.ok() {
5993                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
5994                self.state.event(
5995                    "land",
5996                    format!("merged {tracking} into {} before verifying", winner.branch),
5997                );
5998                None
5999            } else {
6000                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6001                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6002                }
6003                let why = format!(
6004                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6005                    winner.branch,
6006                    merged.stderr.chars().take(600).collect::<String>()
6007                );
6008                self.state.status = RunStatus::Blocked;
6009                self.state.event("land", &why);
6010                Some(why)
6011            };
6012            let synced = conflict.is_none();
6013            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6014            self.state
6015                .finish_base_operation(synced.then_some(fresh.as_str()));
6016            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6017            self.state.base_sync = Some(BaseSync {
6018                tip,
6019                behind: if synced { 0 } else { behind },
6020                attempts,
6021                conflict,
6022                already_in: None,
6023            });
6024            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6025                .await?;
6026            self.state.save()?;
6027            return Ok(());
6028        }
6029
6030        self.state.event(
6031            "land",
6032            format!(
6033                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6034                winner.branch
6035            ),
6036        );
6037        self.state.save()?;
6038
6039        // The remote's copy of the branch, read now and only if the fetch
6040        // really succeeded (a stale tracking ref must never pin a lease). It is
6041        // pushed over after a rebase only when it is a commit this branch
6042        // already contains, by ancestry or by patch (an earlier rebase of ours
6043        // that never reached the remote): anything else is somebody else's work.
6044        let branch_tracking = format!("{remote}/{}", winner.branch);
6045        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6046        let remote_tip = if self.state.task_pr_branch().is_none()
6047            && matches!(&fetched_branch, Ok(o) if o.ok())
6048        {
6049            git::rev_parse(&repo, &branch_tracking).await.ok()
6050        } else {
6051            None
6052        };
6053        // A remote tip this branch does not contain is somebody else's work:
6054        // rebasing would leave a local tip that can never be pushed. Stop
6055        // before touching anything and say so.
6056        if let Some(theirs) = &remote_tip
6057            && !git::is_ancestor(&repo, theirs, &head).await
6058            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6059                .await
6060                .is_ok_and(|missing| missing.is_empty())
6061        {
6062            let why = format!(
6063                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6064                 them",
6065                short(theirs),
6066                winner.branch
6067            );
6068            self.state.status = RunStatus::Blocked;
6069            self.state.base_sync = Some(BaseSync {
6070                tip,
6071                behind,
6072                attempts,
6073                conflict: Some(why.clone()),
6074                already_in: None,
6075            });
6076            self.state.event("land", why);
6077            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6078                .await?;
6079            self.state.save()?;
6080            return Ok(());
6081        }
6082
6083        if self.state.base_sync.is_none() {
6084            self.state.base_sync = Some(BaseSync {
6085                tip: tip.clone(),
6086                behind,
6087                attempts: 0,
6088                conflict: None,
6089                already_in: None,
6090            });
6091        }
6092        let scratch = self.state.dir().join("base-sync");
6093        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6094        {
6095            if error.is::<crate::repo_lock::ResourceBlocked>() {
6096                return Ok(());
6097            }
6098            return Err(error);
6099        }
6100        self.state.reserve_base_operation(&head, &tip);
6101        self.state.save()?;
6102        let rebased =
6103            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6104                .await
6105            {
6106                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6107                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6108                Err(e) => Err(e),
6109            };
6110        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6111        let stop_kind = match &rebased {
6112            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6113            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6114            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6115        };
6116        match rebased {
6117            Ok(None) => {
6118                // The branch ref moved, but a worktree that already had it
6119                // checked out (the winner's) was not told; sync its index and
6120                // files before anything reads them.
6121                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6122                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6123                self.state.finish_base_operation(Some(&fresh));
6124                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6125                let mut conflict = None;
6126                if let Some(pinned) = &remote_tip {
6127                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6128                    match pushed {
6129                        Ok(o) if o.ok() => self.state.event(
6130                            "land",
6131                            format!("pushed rebased {} to {remote}", winner.branch),
6132                        ),
6133                        Ok(o) => {
6134                            conflict = Some(format!(
6135                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6136                                winner.branch,
6137                                short(pinned),
6138                                o.stderr.chars().take(600).collect::<String>()
6139                            ));
6140                        }
6141                        Err(e) => {
6142                            conflict = Some(format!(
6143                                "rebased {} locally but could not push it: {e:#}",
6144                                winner.branch
6145                            ));
6146                        }
6147                    }
6148                }
6149                if let Some(why) = &conflict {
6150                    self.state.status = RunStatus::Blocked;
6151                    self.state.event("land", why.clone());
6152                }
6153                self.state.base_sync = Some(BaseSync {
6154                    tip: tip.clone(),
6155                    behind: 0,
6156                    attempts,
6157                    conflict,
6158                    already_in: None,
6159                });
6160                self.state
6161                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6162            }
6163            Ok(Some(conflict)) => {
6164                self.state.finish_base_operation(None);
6165                let why = format!(
6166                    "{} conflicts with {tracking} and did not rebase: {}",
6167                    winner.branch,
6168                    conflict.chars().take(600).collect::<String>()
6169                );
6170                self.state.status = RunStatus::Blocked;
6171                self.state.base_sync = Some(BaseSync {
6172                    tip,
6173                    behind,
6174                    attempts,
6175                    conflict: Some(why.clone()),
6176                    already_in: None,
6177                });
6178                self.state.event("land", why);
6179            }
6180            // A refused Git write or a busy repository: nothing is wrong with
6181            // the branch. The scratch rebase stays standing and the run
6182            // resumes into it (`base_sync` must not claim a conflict).
6183            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6184                self.state.save()?;
6185                return Ok(());
6186            }
6187            Err(e) => {
6188                self.state.finish_base_operation(None);
6189                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6190                self.state.status = RunStatus::Blocked;
6191                self.state.base_sync = Some(BaseSync {
6192                    tip,
6193                    behind,
6194                    attempts,
6195                    conflict: Some(why.clone()),
6196                    already_in: None,
6197                });
6198                self.state.event("land", why);
6199            }
6200        }
6201        if !self.state.base_sync_blocked() {
6202            self.state.base_sync_recovery.stop = None;
6203        }
6204        self.hold_base_sync_kind(stop_kind).await?;
6205        self.state.save()?;
6206        Ok(())
6207    }
6208
6209    /// Push a branch an earlier attempt rebased locally but never published,
6210    /// pinned to the remote tip read right after a successful fetch. Returns
6211    /// the reason when the run must stop; `None` when there was nothing to do
6212    /// (no remote copy, the same tip, or a remote copy this branch already
6213    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6214    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6215        // Task competitions publish only after the PR text gate, to their
6216        // public head; never resurrect a candidate branch on the remote.
6217        if self.state.task_pr_branch().is_some() {
6218            return None;
6219        }
6220        let repo = self.state.repo.clone();
6221        let remote = self.state.config.merge.remote.clone();
6222        let fetched = git::fetch(&repo, &remote, branch).await;
6223        if !matches!(&fetched, Ok(o) if o.ok()) {
6224            return None;
6225        }
6226        let branch_tracking = format!("{remote}/{branch}");
6227        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6228        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6229            return None;
6230        }
6231        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6232            .await
6233            .is_ok_and(|missing| missing.is_empty())
6234        {
6235            return Some(format!(
6236                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6237                 them",
6238                short(&theirs)
6239            ));
6240        }
6241        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6242            Ok(o) if o.ok() => {
6243                self.state
6244                    .event("land", format!("pushed rebased {branch} to {remote}"));
6245                None
6246            }
6247            Ok(o) => Some(format!(
6248                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6249                 someone may have pushed): {}",
6250                short(&theirs),
6251                o.stderr.chars().take(600).collect::<String>()
6252            )),
6253            Err(e) => Some(format!(
6254                "{branch} is rebased locally but could not be pushed: {e:#}"
6255            )),
6256        }
6257    }
6258
6259    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6260    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6261    /// whether it did.
6262    ///
6263    /// Checked only when the base is ahead of the branch. A failing check is
6264    /// "not proven" - the ordinary rebase path then decides - never a reason to
6265    /// stop the run.
6266    ///
6267    /// The remote copy of the branch is held to the same standard as the local
6268    /// one: if it carries a tip this worktree does not, that tip must itself be
6269    /// proven in the base, or nothing is settled (a pull request would
6270    /// otherwise be closed over commits nobody checked). The pull request is
6271    /// closed *before* the terminal status is saved; if that fails for a
6272    /// reason other than a refusal (no network, a `gh` error) the run is left
6273    /// `Blocked` with the reason as its conflict, which a resume retries -
6274    /// the same recovery a phantom conflict gets.
6275    async fn settle_already_in(
6276        &mut self,
6277        branch: &str,
6278        tip: &str,
6279        head: &str,
6280        attempts: usize,
6281        behind: usize,
6282    ) -> Result<bool> {
6283        let repo = self.state.repo.clone();
6284        let remote = self.state.config.merge.remote.clone();
6285        let start = self.state.base_commit.clone();
6286        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6287            Ok(Some(e)) => e,
6288            Ok(None) => return Ok(false),
6289            Err(e) => {
6290                tracing::warn!("already-in-base check for {branch}: {e:#}");
6291                return Ok(false);
6292            }
6293        };
6294        let mut verified = vec![head.to_owned()];
6295        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6296        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6297        let divergence = self
6298            .state
6299            .base_sync_recovery
6300            .stop
6301            .as_ref()
6302            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6303        if matches!(&fetched, Ok(o) if o.ok()) {
6304            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6305                Ok(theirs) if theirs != head => {
6306                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6307                        Ok(Some(_)) => verified.push(theirs),
6308                        _ => return Ok(false),
6309                    }
6310                }
6311                Err(_) if divergence => return Ok(false),
6312                _ => {}
6313            }
6314        } else if divergence
6315            && !matches!(
6316                git::remote_has_branch(&repo, &remote, &public_branch).await,
6317                Ok(false)
6318            )
6319        {
6320            // A failed fetch cannot discharge a recorded divergence.
6321            return Ok(false);
6322        }
6323        let base_branch = self.state.base_branch.clone();
6324        let message = format!(
6325            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6326             land",
6327            evidence.names(),
6328            evidence.proof.as_str()
6329        );
6330        let closed =
6331            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6332                .await;
6333        match closed {
6334            Ok(Ok(url)) => self
6335                .state
6336                .event("land", format!("closed {url}: superseded on {base_branch}")),
6337            Ok(Err(why)) => self
6338                .state
6339                .event("land", format!("did not close a pull request: {why}")),
6340            Err(e) => {
6341                let why = format!(
6342                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6343                     not be closed ({e:#}); resume to retry"
6344                );
6345                self.state.status = RunStatus::Blocked;
6346                self.state.base_sync = Some(BaseSync {
6347                    tip: tip.to_owned(),
6348                    behind,
6349                    attempts,
6350                    conflict: Some(why.clone()),
6351                    already_in: None,
6352                });
6353                self.state.event("land", why);
6354                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6355                    .await?;
6356                self.state.save()?;
6357                return Ok(true);
6358            }
6359        }
6360        self.state.status = RunStatus::AlreadyInBase;
6361        self.state.base_sync_recovery.stop = None;
6362        self.state.base_sync = Some(BaseSync {
6363            tip: tip.to_owned(),
6364            behind,
6365            attempts,
6366            conflict: None,
6367            already_in: Some(evidence),
6368        });
6369        self.state.event("land", message);
6370        self.state.save()?;
6371        self.settle_questions();
6372        Ok(true)
6373    }
6374
6375    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6376    /// last landed the winner on, once it has run, else the commit the run
6377    /// branched from.
6378    ///
6379    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6380    /// and `vote` all happen before there is a winner to rebase, so they
6381    /// compare every candidate against the branch point on purpose, and a
6382    /// base that moves after they are already done cannot change an answer
6383    /// they already gave.
6384    fn landing_base(&self) -> String {
6385        self.state
6386            .base_sync
6387            .as_ref()
6388            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6389    }
6390
6391    // ------------------------------------------------------- operator fix
6392
6393    /// Route specific, already-recorded review findings to a fixer for a
6394    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6395    /// entry point.
6396    ///
6397    /// Distinct from `review_loop`'s own fix step in three ways: it never
6398    /// runs a reviewer wave, it never spends review-round budget, and what
6399    /// happened is recorded as an [`OperatorFixRequest`] appended to
6400    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6401    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6402    /// and vote must never be rewritten to look like a manufactured blocking
6403    /// verdict.
6404    ///
6405    /// Only meaningful once review has actually concluded: `Ready` (handed
6406    /// off with findings still open, or simply concluded clean while minor
6407    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6408    /// gate failed). Everything else is refused: a run still in progress
6409    /// should simply be resumed, and a `Merged` run's branch has already
6410    /// landed — reopening *this* run's own record cannot change that, so the
6411    /// answer there is a fresh `magi review <branch>`.
6412    ///
6413    /// A real commit here re-verifies through a fresh, ordinary review-only
6414    /// run on the same branch ([`Self::review`]) rather than reopening this
6415    /// run's own `review_loop`: once any round in this run's history went
6416    /// clean, `review_conclusion` treats that as permanent by design (the
6417    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6418    /// way to force one more genuine reviewer wave out of *this* run without
6419    /// either rewriting history or weakening that guarantee for every other
6420    /// caller. A review-only run costs nothing extra — no implementation, no
6421    /// judging, no vote — and exercises the exact same review → verify →
6422    /// gate → (human) merge path, unmodified.
6423    pub async fn fix_selected(
6424        &mut self,
6425        ids: &[String],
6426        reason: &str,
6427        allow_stale: bool,
6428    ) -> Result<()> {
6429        let reason = reason.trim();
6430        if reason.is_empty() {
6431            bail!("a fix request needs a reason — that is the operator's own record of why");
6432        }
6433        if ids.is_empty() {
6434            bail!("no finding id given");
6435        }
6436        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6437            bail!(
6438                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6439                 has already concluded — can be given a targeted fix. A run still \
6440                 in progress should simply be resumed; a `merged` run's branch has \
6441                 already landed, so its answer is a fresh `magi review <branch>`, \
6442                 not reopening this run's own record",
6443                self.state.id,
6444                self.state.status.as_str()
6445            );
6446        }
6447        // Reassignment shares this claim through its atomic task save. Check
6448        // the canonical run identity inside it, before preflight or any await.
6449        let _claim = FixClaim::acquire(&self.state.dir())?;
6450        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6451        let home = crate::run::home();
6452        // The ordinary driver takes these same locks at admission. Keep the
6453        // execution lease through the fix, but never the owner lock across Git
6454        // or agent awaits.
6455        let execution = {
6456            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6457            let disk = RunState::load(&self.state.id)?;
6458            crate::pr_head::ensure_owner(&disk)?;
6459            anyhow::ensure!(
6460                disk.status == self.state.status && disk.released_to.is_none(),
6461                "run changed since it was loaded; reload before fixing"
6462            );
6463            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6464            anyhow::ensure!(
6465                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6466                "run {} is currently being worked on or its ownership is unknown",
6467                disk.id
6468            );
6469            let lease = crate::driver::maintenance(&home, &disk.id).context(
6470                "run is currently being worked on or its execution lease is unavailable",
6471            )?;
6472            self.state = disk;
6473            lease
6474        };
6475        let Some(winner) = self.state.winner().cloned() else {
6476            bail!("run {} has no winning candidate to fix", self.state.id);
6477        };
6478        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6479            bail!(
6480                "branch `{}` no longer exists; this run cannot be extended",
6481                winner.branch
6482            );
6483        }
6484        // Resolve every id before spending anything — an unknown id refuses
6485        // the whole request rather than silently dropping it — and dedup
6486        // while keeping the operator's own order.
6487        let mut seen = BTreeSet::new();
6488        let mut findings = Vec::new();
6489        let mut missing = Vec::new();
6490        for id in ids {
6491            if !seen.insert(id.clone()) {
6492                continue;
6493            }
6494            match self.state.finding(id) {
6495                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6496                    id: f.id.clone(),
6497                    severity: f.severity,
6498                    reviewer_vote: rec.vote,
6499                    round: round.round,
6500                    round_head: round.head.clone(),
6501                    reviewer: rec.reviewer,
6502                    agent: rec.agent.clone(),
6503                    file: f.file.clone(),
6504                    line: f.line,
6505                    title: f.title.clone(),
6506                    detail: f.detail.clone(),
6507                    outcome: OperatorFixOutcome::Pending,
6508                }),
6509                None => missing.push(id.clone()),
6510            }
6511        }
6512        if !missing.is_empty() {
6513            bail!(
6514                "unknown finding id(s): {}; nothing was changed",
6515                missing.join(", ")
6516            );
6517        }
6518
6519        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6520        let stale_details: Vec<(String, String)> = findings
6521            .iter()
6522            .filter(|f| f.round_head != head_at_request)
6523            .map(|f| (f.id.clone(), f.round_head.clone()))
6524            .collect();
6525        let stale = !stale_details.is_empty();
6526        if stale && !allow_stale {
6527            bail!(
6528                "the branch has moved since some finding(s) were raised — {} — now \
6529                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6530                stale_details
6531                    .iter()
6532                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6533                    .collect::<Vec<_>>()
6534                    .join(", "),
6535                short(&head_at_request)
6536            );
6537        }
6538
6539        let request = OperatorFixRequest {
6540            requested_at: Timestamp::now(),
6541            reason: reason.to_owned(),
6542            findings,
6543            head_at_request: head_at_request.clone(),
6544            allow_stale,
6545            stale,
6546            fix: None,
6547            result_head: None,
6548            follow_up_review_run: None,
6549        };
6550        self.state.event(
6551            "fix",
6552            format!(
6553                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6554                request.findings.len(),
6555                request
6556                    .findings
6557                    .iter()
6558                    .map(|f| f.id.as_str())
6559                    .collect::<Vec<_>>()
6560                    .join(", "),
6561            ),
6562        );
6563        // Recorded now, before any worktree work or the fixer call itself —
6564        // and re-saved at each checkpoint below: a crash at any point after
6565        // this (mid fixer call, mid follow-up review) must not lose the fact
6566        // that this was requested, for which findings, and why. Everything
6567        // past this point reads and writes through `request_index` rather
6568        // than a local variable, since `request` itself is moved here.
6569        self.state.operator_fixes.push(request);
6570        self.state.save()?;
6571        let request_index = self.state.operator_fixes.len() - 1;
6572
6573        // A fresh, dedicated worktree for this one call, never the winner's
6574        // own worktree in place: that one may already be gone (folded away),
6575        // and reusing it in place would leave the branch checked out there
6576        // when the follow-up review below tries to check it out again. Freed
6577        // immediately after, either way — but only once confirmed clean:
6578        // `worktree_remove` is a `git worktree remove --force`, which would
6579        // otherwise discard uncommitted work left there by the operator or
6580        // another process before this had a chance to even look at it.
6581        let repo = self.state.repo.clone();
6582        let coordination = self.coordinate(&repo).await?;
6583        if winner.worktree.exists() {
6584            // Lockfiles a rescue commit withheld stay untracked on purpose and
6585            // are already recorded; they are not the operator's work to protect.
6586            let dirty = git::git(
6587                &winner.worktree,
6588                &["status", "--porcelain", "--untracked-files=all"],
6589            )
6590            .await?;
6591            let only_withheld = dirty.lines().all(|l| {
6592                l.strip_prefix("?? ")
6593                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6594            });
6595            if !only_withheld {
6596                bail!(
6597                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6598                     discard them first",
6599                    winner.worktree.display()
6600                );
6601            }
6602            git::worktree_remove(&self.state.repo, &winner.worktree)
6603                .await
6604                .ok();
6605        }
6606        let fix_worktree = self.state.worktree_root().join("operator-fix");
6607        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6608        git::git(
6609            &self.state.repo,
6610            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6611        )
6612        .await
6613        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6614        if !git::is_clean(&fix_worktree).await? {
6615            git::worktree_remove(&self.state.repo, &fix_worktree)
6616                .await
6617                .ok();
6618            bail!(
6619                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6620                winner.branch
6621            );
6622        }
6623        let repo_for_setup = self.state.repo.clone();
6624        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6625            Ok(()) => {
6626                worktree_setup::prepare_with(
6627                    &self.state.config,
6628                    &repo_for_setup,
6629                    &fix_worktree,
6630                    crate::build_target::Coordination::Held(coordination.as_ref()),
6631                )
6632                .await
6633            }
6634            Err(e) => Err(e),
6635        };
6636        if let Err(e) = setup {
6637            git::worktree_remove(&self.state.repo, &fix_worktree)
6638                .await
6639                .ok();
6640            return Err(e);
6641        }
6642
6643        // This explicit operator request retries availability independently
6644        // of execute(); the previous call has already saved and cleaned up.
6645        self.state.resource_block = None;
6646
6647        let run_id = self.state.id.clone();
6648        let prompts = self.state.config.prompts.clone();
6649        let language = self.state.config.graph.language.clone();
6650        let sessions = self.state.config.graph.sessions;
6651        let artifacts = agent::artifacts_dir(&self.state.dir());
6652        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6653            .findings
6654            .iter()
6655            .map(|f| Finding {
6656                id: f.id.clone(),
6657                severity: f.severity,
6658                file: f.file.clone(),
6659                line: f.line,
6660                title: f.title.clone(),
6661                detail: f.detail.clone(),
6662            })
6663            .collect();
6664        let fix_prompt = prompt::operator_fix_in(
6665            &self.state.instruction,
6666            &finding_list,
6667            reason,
6668            &stale_details,
6669            &head_at_request,
6670            &language,
6671            &self.state.config.graph.github_language,
6672        );
6673        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6674        drop(coordination);
6675        let (job, seat, out) = self
6676            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6677                prompt: fix_prompt.clone(),
6678                spec,
6679                seat,
6680                cwd: fix_worktree.clone(),
6681                timeout,
6682                allow_write: true,
6683                sessions,
6684                artifacts: artifacts.clone(),
6685                stem: "operator-fix".to_owned(),
6686                handover: None,
6687            })
6688            .await;
6689        let agent_id = seat.agent.clone();
6690
6691        let mut fix = FixRecord {
6692            agent: agent_id,
6693            addressed: Vec::new(),
6694            rejected: Vec::new(),
6695            notes: String::new(),
6696            committed: false,
6697            failed: None,
6698            duration_ms: 0,
6699            continuation: None,
6700        };
6701        let mut final_seat = seat.clone();
6702        match out {
6703            AgentOutcome::Ok(o) => {
6704                fix.duration_ms = o.duration_ms;
6705                let parsed = verdict::extract_json::<FixReport>(&o.text);
6706                let incomplete_reason = match &parsed {
6707                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6708                        "the reply parsed, but it reported a command whose own CLI \
6709                         never confirmed an exit status"
6710                            .to_owned(),
6711                    ),
6712                    Ok(_) => None,
6713                    Err(e) => Some(e.to_string()),
6714                };
6715                match incomplete_reason {
6716                    None => {
6717                        let report = parsed.expect("checked Ok above");
6718                        fix.addressed = report.addressed;
6719                        fix.rejected = report.rejected;
6720                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6721                    }
6722                    Some(reason) => {
6723                        let (resumed_seat, resolved, failure, cont) = self
6724                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6725                            .await;
6726                        fix.duration_ms += cont.cumulative_wait_ms;
6727                        fix.continuation = Some(cont);
6728                        final_seat = resumed_seat;
6729                        match resolved {
6730                            Some(report) => {
6731                                fix.addressed = report.addressed;
6732                                fix.rejected = report.rejected;
6733                                fix.notes =
6734                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6735                            }
6736                            None => fix.failed = failure,
6737                        }
6738                    }
6739                }
6740            }
6741            AgentOutcome::Dropped(o) => {
6742                fix.duration_ms = o.duration_ms;
6743                let why = o
6744                    .dropped
6745                    .as_ref()
6746                    .map(|d| d.why.as_str())
6747                    .unwrap_or("the CLI ended the stream without delivering its answer");
6748                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
6749            }
6750            AgentOutcome::Quota(o) => {
6751                self.state.quota.push(QuotaLoss::from_report(
6752                    final_seat.key.clone(),
6753                    "fix",
6754                    o.quota.as_ref(),
6755                ));
6756                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
6757            }
6758            AgentOutcome::Failed(e) => fix.failed = Some(e),
6759            AgentOutcome::ResourceBlocked(e) => {
6760                fix.failed = Some(format!("the fixer was not started: {e}"));
6761            }
6762        }
6763        // Even a deferred call must rescue edits, release the worktree and
6764        // finalize its record below so an explicit `magi fix` can retry.
6765        if fix.continuation.is_none() {
6766            fix.continuation = Some(ContinuationRecord::not_needed());
6767        }
6768        self.state.seats.insert(final_seat.key.clone(), final_seat);
6769
6770        let rescue_message = format!(
6771            "magi: operator-selected fix ({}) (uncommitted work)",
6772            self.state.operator_fixes[request_index]
6773                .findings
6774                .iter()
6775                .map(|f| f.id.as_str())
6776                .collect::<Vec<_>>()
6777                .join(", ")
6778        );
6779        let repo = self.state.repo.clone();
6780        let coordination = self.coordinate(&repo).await?;
6781        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
6782            self.state.note_withheld("fix", &r.withheld);
6783        }
6784        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
6785        fix.committed = after != head_at_request;
6786        git::worktree_remove(&self.state.repo, &fix_worktree)
6787            .await
6788            .ok();
6789        drop(coordination);
6790
6791        self.state.event(
6792            "fix",
6793            match &fix.failed {
6794                Some(reason) => format!(
6795                    "operator fix: adoption report was lost ({reason}); {}",
6796                    if fix.committed {
6797                        "committed"
6798                    } else {
6799                        "NO new commit"
6800                    }
6801                ),
6802                None => format!(
6803                    "operator fix: {} addressed, {} rejected, {}",
6804                    fix.addressed.len(),
6805                    fix.rejected.len(),
6806                    if fix.committed {
6807                        "committed"
6808                    } else {
6809                        "NO new commit"
6810                    }
6811                ),
6812            },
6813        );
6814
6815        // Every selected finding gets an outcome — never left `Pending` once
6816        // the fixer's own turn is over. A report that never came back at all
6817        // marks every one of them `Unreported`, not silently "not addressed":
6818        // quota, a dropped stream, or an exhausted continuation are gaps in
6819        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
6820        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
6821        for f in &mut self.state.operator_fixes[request_index].findings {
6822            f.outcome = if fix.failed.is_some() {
6823                OperatorFixOutcome::Unreported
6824            } else if fix.addressed.contains(&f.id) {
6825                OperatorFixOutcome::Addressed
6826            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
6827                OperatorFixOutcome::Rejected { why: r.why.clone() }
6828            } else {
6829                OperatorFixOutcome::Unreported
6830            };
6831        }
6832
6833        let committed = fix.committed;
6834        if committed {
6835            self.state.operator_fixes[request_index].result_head = Some(after.clone());
6836        }
6837        self.state.operator_fixes[request_index].fix = Some(fix);
6838        // Saved again now that the fixer's own outcome is final, on top of
6839        // the save right after the request was first pushed above.
6840        self.state.save()?;
6841        if self.state.resource_block.is_some() {
6842            return self.stop_for_resource();
6843        }
6844
6845        if committed {
6846            self.state.event(
6847                "fix",
6848                format!(
6849                    "operator fix committed {}; opening a follow-up review-only run",
6850                    short(&after)
6851                ),
6852            );
6853            self.state.save()?;
6854            drop(execution);
6855            // The new review owns its own execution. Update only its audit link
6856            // afterwards, since publication may have changed the old record.
6857            let event_count = self.state.events.len();
6858            let save_follow_up = |state: &mut RunState| -> Result<()> {
6859                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
6860                let _execution = crate::driver::maintenance(&home, &state.id)?;
6861                let mut disk = RunState::load(&state.id)?;
6862                disk.events.extend(state.events.drain(event_count..));
6863                let follow_up = state.operator_fixes[request_index]
6864                    .follow_up_review_run
6865                    .clone();
6866                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
6867                disk.save()?;
6868                *state = disk;
6869                Ok(())
6870            };
6871            // The operator asked for the fix, and the follow-up serves whatever
6872            // task the run it follows served.
6873            let origin =
6874                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
6875            match Self::review(
6876                &self.state.repo,
6877                &winner.branch,
6878                self.state.config.clone(),
6879                origin,
6880            )
6881            .await
6882            {
6883                Ok(mut follow_up) => {
6884                    follow_up.state.event(
6885                        "start",
6886                        format!(
6887                            "requested by an operator fix on run {} for finding(s) {}",
6888                            self.state.id,
6889                            self.state.operator_fixes[request_index]
6890                                .findings
6891                                .iter()
6892                                .map(|f| f.id.as_str())
6893                                .collect::<Vec<_>>()
6894                                .join(", "),
6895                        ),
6896                    );
6897                    follow_up.state.save()?;
6898                    let follow_up_id = follow_up.state.id.clone();
6899                    // The follow-up is a run like any other: it belongs to the
6900                    // task of the run it follows, or to one filed for it.
6901                    let adopted = match crate::direct::adopt(
6902                        &follow_up.state,
6903                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
6904                    ) {
6905                        Ok(a) => a,
6906                        Err(e) => {
6907                            // An ownerless run must not spend agent calls; it
6908                            // stays saved, and `magi run --resume` adopts it.
6909                            self.state.event(
6910                                "fix",
6911                                format!(
6912                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
6913                                ),
6914                            );
6915                            save_follow_up(&mut self.state)?;
6916                            return Ok(());
6917                        }
6918                    };
6919                    let executed = follow_up.execute().await;
6920                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
6921                    if let Some(a) = adopted {
6922                        a.finish(&follow_up.state, executed);
6923                    }
6924                    if let Some(e) = failure {
6925                        self.state.event(
6926                            "fix",
6927                            format!(
6928                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
6929                            ),
6930                        );
6931                    }
6932                    self.state.operator_fixes[request_index].follow_up_review_run =
6933                        Some(follow_up_id);
6934                }
6935                Err(e) => {
6936                    self.state.event(
6937                        "fix",
6938                        format!("committed the fix but could not open a follow-up review: {e:#}"),
6939                    );
6940                }
6941            }
6942            save_follow_up(&mut self.state)?;
6943        }
6944
6945        Ok(())
6946    }
6947
6948    // --------------------------------------------------------------- review
6949
6950    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
6951    /// names, in order, each at most once, moving on only when the call
6952    /// advances (an error, a quota hit or nothing usable - the same decision
6953    /// point `agent::chain_advances` is for the other chained roles).
6954    ///
6955    /// Each agent gets its own seat from `Runner::seat`: the same agent
6956    /// continues its conversation (the winner's own implementer seat when it
6957    /// is the winner's author, now that the competition is over), another
6958    /// takes a fresh one so the full prompt is sent again. A handover is
6959    /// recorded under `node`, which is what makes the fallback stick for the
6960    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
6961    /// is returned, so an exhausted chain reads exactly like a single failed
6962    /// fixer: one quota loss, the same wording, the same refund. An earlier
6963    /// attempt's edits are left in the tree and judged, with the final
6964    /// attempt's, by what git says afterwards.
6965    ///
6966    /// Returns the job that produced the outcome, for `continue_fix_report`.
6967    async fn ask_fixer(
6968        &mut self,
6969        winner: &Candidate,
6970        node: &'static str,
6971        round: Option<usize>,
6972        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6973    ) -> (SeatJob, SeatState, AgentOutcome) {
6974        let attempts = fixer::attempts(&self.state, &self.roles, winner);
6975        self.ask_fixer_among(attempts, node, round, None, build)
6976            .await
6977    }
6978
6979    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
6980    /// worktree and a commit: before the next agent is asked after one that
6981    /// did not satisfy the call, the worktree is put back on that commit, so
6982    /// a failed agent's partial edits are not carried into the next one.
6983    async fn ask_fixer_among(
6984        &mut self,
6985        attempts: Vec<(AgentSpec, String)>,
6986        node: &'static str,
6987        round: Option<usize>,
6988        restore: Option<(&Path, &str)>,
6989        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6990    ) -> (SeatJob, SeatState, AgentOutcome) {
6991        let run_id = self.state.id.clone();
6992        let prompts = self.state.config.prompts.clone();
6993        let cache = self.state.config.cache_dir();
6994        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6995        let mut last = None;
6996        for (i, (spec, key)) in attempts.into_iter().enumerate() {
6997            let seat = self.seat(&key, &spec.id);
6998            let mut job = build(spec.clone(), seat);
6999            if i > 0 {
7000                job.stem = format!("{}-{}", job.stem, spec.id);
7001            }
7002            let ctx = WaveCtx {
7003                carry_seats: false,
7004                pauses: Some((&self.pause, &self.interrupt)),
7005                run: &run_id,
7006                node,
7007                prompts: &prompts,
7008                cache: cache.as_deref(),
7009                round,
7010            };
7011            let (seat, out) =
7012                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7013            // A resource block never advances the chain: the chosen agent
7014            // was not asked, so it must be the one asked again on resume.
7015            let advances = match &out {
7016                AgentOutcome::Ok(o) => agent::output_advances(o),
7017                AgentOutcome::ResourceBlocked(_) => false,
7018                _ => true,
7019            };
7020            if let Some(next) = ids.get(i + 1)
7021                && advances
7022            {
7023                self.state.seats.insert(seat.key.clone(), seat.clone());
7024                let class =
7025                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7026                let reason = match &out {
7027                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7028                    other => fail_reason(other),
7029                };
7030                // A failed agent's edits must not reach the next one, and a
7031                // restore that did not work ends the chain: the call fails
7032                // and the caller's own (confirmed) restore decides.
7033                if let Some((wt, rev)) = restore
7034                    && let Err(e) = self.graft_restore(wt, rev).await
7035                {
7036                    let why =
7037                        format!("could not restore the worktree before the next fixer: {e:#}");
7038                    tracing::warn!("{why}");
7039                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7040                        AgentOutcome::ResourceBlocked(why)
7041                    } else {
7042                        AgentOutcome::Failed(why)
7043                    };
7044                    last = Some((job, seat, out));
7045                    break;
7046                }
7047                record_handover(
7048                    &mut self.state,
7049                    node,
7050                    &seat.key,
7051                    &spec.id,
7052                    next,
7053                    &class,
7054                    &reason,
7055                );
7056                continue;
7057            }
7058            last = Some((job, seat, out));
7059            break;
7060        }
7061        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7062        if let AgentOutcome::Quota(output) = &out
7063            && node != "graft"
7064        {
7065            // Graft is best effort: its caller records the loss and restores
7066            // the pre-graft tree, then proceeds to review and gate.
7067            // Every fallback was tried. Machine outages cannot be repaired by
7068            // spending a fix round; use each caller's resumable resource path.
7069            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7070            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7071            self.state.quota.push(loss);
7072            self.state.seats.insert(seat.key.clone(), seat.clone());
7073            self.state.status = RunStatus::Blocked;
7074            return (
7075                job,
7076                seat,
7077                AgentOutcome::ResourceBlocked(
7078                    "fixer unavailable; restore agent availability and resume".into(),
7079                ),
7080            );
7081        }
7082        (job, seat, out)
7083    }
7084
7085    /// The one repair a verification-only failure earns (see
7086    /// [`crate::recovery`]), before the first review round of a run that took
7087    /// a branch over.
7088    ///
7089    /// Saved as started *before* the fixer is called, so a resume never
7090    /// repairs twice; a start found on re-entry is rolled back to the commit
7091    /// it began from. A failed or unusable fixer leaves the tree as it was and
7092    /// the review goes on over it, so the first round's own verification
7093    /// reports the failure again. The failure is never carried into a round as
7094    /// a result: verification is re-run on whatever commit this leaves.
7095    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7096        use crate::recovery::{Mode, Repair};
7097        if !self.state.reviews.is_empty() {
7098            return Ok(());
7099        }
7100        let Some(mut rec) = self.state.recovery.clone() else {
7101            return Ok(());
7102        };
7103        if rec.mode != Mode::VerifyRepair {
7104            return Ok(());
7105        }
7106        let wt = winner.worktree.clone();
7107        let mut head = git::rev_parse(&wt, "HEAD").await?;
7108        match rec.repair.clone() {
7109            Repair::Done { .. } => return Ok(()),
7110            Repair::WaitingForRestore { before } => {
7111                self.graft_restore(&wt, &before).await?;
7112                head = before;
7113                rec.repair = Repair::NotStarted;
7114                self.state.recovery = Some(rec.clone());
7115                self.state.save()?;
7116            }
7117            Repair::Started { before } => {
7118                // Interrupted: the unfinished edits are not trusted.
7119                // An unconfirmed rollback blocks the run with `Started` kept,
7120                // so a resume retries it; the tree is never reviewed as is.
7121                if let Err(e) = self.graft_restore(&wt, &before).await {
7122                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7123                        return Err(e);
7124                    }
7125                    return self
7126                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7127                        .await;
7128                }
7129                rec.repair = Repair::Done {
7130                    before: before.clone(),
7131                    after: before,
7132                    committed: false,
7133                    failed: Some("interrupted; rolled back".to_owned()),
7134                };
7135                self.state
7136                    .event("recovery", "the repair was interrupted and rolled back");
7137                self.state.recovery = Some(rec);
7138                self.state.save()?;
7139                return Ok(());
7140            }
7141            Repair::NotStarted => {}
7142        }
7143        if crate::recovery::recheck(&mut rec, &head) {
7144            self.state.event("recovery", rec.summary());
7145            self.state.recovery = Some(rec);
7146            self.state.save()?;
7147            return Ok(());
7148        }
7149        rec.repair = Repair::Started {
7150            before: head.clone(),
7151        };
7152        self.state.recovery = Some(rec.clone());
7153        self.state.save()?;
7154
7155        let language = self.state.config.graph.language.clone();
7156        let sessions = self.state.config.graph.sessions;
7157        let artifacts = agent::artifacts_dir(&self.state.dir());
7158        let fix_prompt = prompt::recovery_fix(
7159            &self.state.instruction,
7160            &rec,
7161            self.state.config.graph.review_rounds,
7162            &language,
7163        );
7164        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7165        self.state.event(
7166            "recovery",
7167            format!(
7168                "repair: the fixer starts from the failed verification on {}",
7169                short(&head)
7170            ),
7171        );
7172        let (_job, seat, out) = self
7173            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7174                prompt: fix_prompt.clone(),
7175                spec,
7176                seat,
7177                cwd: wt.clone(),
7178                timeout,
7179                allow_write: true,
7180                sessions,
7181                artifacts: artifacts.clone(),
7182                stem: "fix-recovery".to_owned(),
7183                handover: None,
7184            })
7185            .await;
7186        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7187            rec.repair = Repair::WaitingForRestore { before: head };
7188            self.state.recovery = Some(rec);
7189            return self.stop_for_resource();
7190        }
7191        let failed = match &out {
7192            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7193            AgentOutcome::Quota(o) => {
7194                self.state.quota.push(QuotaLoss::from_report(
7195                    seat.key.clone(),
7196                    "fix",
7197                    o.quota.as_ref(),
7198                ));
7199                Some("rate limited (quota); the fixer could not run".to_owned())
7200            }
7201            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7202            AgentOutcome::Failed(e) => Some(e.clone()),
7203        };
7204        self.state.seats.insert(seat.key.clone(), seat);
7205        let coordination = self.coordinate(&wt).await?;
7206        let failed = match failed {
7207            // The agent's partial edits are not kept.
7208            Some(why) => {
7209                if let Err(e) = git::restore_to(&wt, &head).await {
7210                    return self
7211                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7212                        .await;
7213                }
7214                Some(why)
7215            }
7216            None => {
7217                if let Ok(r) = git::rescue_commit(
7218                    &wt,
7219                    "magi: recovery repair of the failed verification (uncommitted work)",
7220                )
7221                .await
7222                {
7223                    self.state.note_withheld("fix", &r.withheld);
7224                }
7225                None
7226            }
7227        };
7228        let after = git::rev_parse(&wt, "HEAD").await?;
7229        drop(coordination);
7230        self.state.event(
7231            "recovery",
7232            match &failed {
7233                Some(why) => format!("repair: nothing kept ({why})"),
7234                None if after != head => {
7235                    format!("repair: committed {}", short(&after))
7236                }
7237                None => "repair: the fixer made no commit".to_owned(),
7238            },
7239        );
7240        rec.repair = Repair::Done {
7241            before: head.clone(),
7242            committed: after != head,
7243            after,
7244            failed,
7245        };
7246        self.state.recovery = Some(rec);
7247        self.state.save()?;
7248        Ok(())
7249    }
7250
7251    /// A repair whose rollback could not be confirmed: the run is blocked and
7252    /// resumable, and the unconfirmed state is never reviewed.
7253    async fn stop_recovery(
7254        &mut self,
7255        mut rec: crate::recovery::RecoveryRecord,
7256        head: &str,
7257        why: String,
7258    ) -> Result<()> {
7259        // `Started` stays recorded: a resume retries the restore.
7260        rec.repair = crate::recovery::Repair::Started {
7261            before: head.to_owned(),
7262        };
7263        self.state.recovery = Some(rec);
7264        self.state
7265            .event("recovery", format!("repair could not be undone: {why}"));
7266        self.state.status = RunStatus::Blocked;
7267        self.state.save()?;
7268        bail!("recovery repair could not be rolled back: {why}")
7269    }
7270
7271    async fn review_loop(&mut self) -> Result<()> {
7272        if self.hold_base_sync().await? {
7273            return Ok(());
7274        }
7275        loop {
7276            if self
7277                .state
7278                .base_sync
7279                .as_ref()
7280                .is_some_and(|s| s.conflict.is_some())
7281            {
7282                return Ok(());
7283            }
7284            if self.catchup_repairable() {
7285                let record = self.state.reviews.last().expect("repairable round").clone();
7286                let winner = self
7287                    .state
7288                    .winner()
7289                    .cloned()
7290                    .context("catch-up repair has no winner")?;
7291                if !self.fix_review_round(&winner, record).await? {
7292                    return Ok(());
7293                }
7294            }
7295            self.review_loop_pass().await?;
7296            if !self.catchup_repairable() {
7297                return Ok(());
7298            }
7299        }
7300    }
7301
7302    /// Derive an owed catch-up repair from durable round evidence, including
7303    /// reentry after a crash before the fixer was dispatched.
7304    fn catchup_repairable(&self) -> bool {
7305        self.state.reviews.len() < self.state.config.graph.review_rounds
7306            && self.state.reviews.last().is_some_and(|r| {
7307                !r.clean
7308                    && r.blocking == 0
7309                    && r.fix.is_none()
7310                    && r.e2e_status() == E2eStatus::Failed
7311            })
7312    }
7313
7314    async fn review_loop_pass(&mut self) -> Result<()> {
7315        // A base that would not rebase is a person's decision, not a review
7316        // round: nothing here would change the answer, and reviewers and a
7317        // fixer would be spending real budget on a tree that cannot land
7318        // regardless of what they find.
7319        if self
7320            .state
7321            .base_sync
7322            .as_ref()
7323            .is_some_and(|s| s.conflict.is_some())
7324        {
7325            return Ok(());
7326        }
7327        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7328        // agent files with `magi task add` name the run that paid for it. The
7329        // prompt overlay is cloned alongside it because the waves borrow it
7330        // while `self` is mutably borrowed by the node's own bookkeeping.
7331        let run_id = self.state.id.clone();
7332        let prompts = self.state.config.prompts.clone();
7333        let Some(winner) = self.state.winner().cloned() else {
7334            return Ok(());
7335        };
7336        let granted_review = self
7337            .state
7338            .repair_grants
7339            .last()
7340            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7341            .cloned();
7342        let fresh_review = granted_review
7343            .as_ref()
7344            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7345        let max_rounds = granted_review
7346            .as_ref()
7347            .map_or(self.state.config.graph.review_rounds, |g| {
7348                g.review_start.saturating_add(1)
7349            });
7350        // A clean round, an exhausted round budget, or a stalled tree (see
7351        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7352        // they are recorded — recomputed here, not read off `status`, so a
7353        // reentry into a run that already stopped restates the identical
7354        // verdict instead of silently handing back whatever an earlier node
7355        // in this same walk clobbered `status` to (a solo-candidate
7356        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7357        // below runs an empty range once the budget is spent, and would
7358        // otherwise fall through without touching `status` at all.
7359        if let Some(status) =
7360            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7361        {
7362            // A reentry after a crash between the last round's save and
7363            // `stop_reviewing` reaches the hand-off here, not there.
7364            if status == RunStatus::Gating {
7365                self.record_contested_handoff();
7366            }
7367            self.state.status = status;
7368            self.state.save()?;
7369            return Ok(());
7370        }
7371        self.state.status = RunStatus::Reviewing;
7372        // A last recorded round whose own verification never resolved
7373        // (`ResourceBlocked` — the shared build cache, not the patch) is
7374        // never a concluded round, whatever the round budget says: starting
7375        // a fresh round on top of it would spend a whole new reviewer wave
7376        // re-reading an unchanged patch instead of just retrying the one
7377        // check that actually needs it, and once the budget is spent the
7378        // loop below has nothing left to do at all (its range is empty).
7379        // Retry that check directly instead, exactly the same retry
7380        // `stop_reviewing` already does for its own catch-up case.
7381        if !fresh_review
7382            && self.state.reviews.last().is_some_and(|r| {
7383                r.e2e_status() == E2eStatus::ResourceBlocked
7384                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7385            })
7386        {
7387            let shell = self.state.config.shell();
7388            return self
7389                .stop_unresolved_review(
7390                    "the last round's own verification never resolved",
7391                    &shell,
7392                    &winner.worktree,
7393                )
7394                .await;
7395        }
7396
7397        if granted_review.is_none() {
7398            self.recovery_repair(&winner).await?;
7399        }
7400        if self.resource_halt()? {
7401            return Ok(());
7402        }
7403
7404        let repo = self.state.repo.clone();
7405        let root = self.state.worktree_root();
7406        let language = self.state.config.graph.language.clone();
7407        let sessions = self.state.config.graph.sessions;
7408        let artifacts = self.merge_repair_artifacts();
7409        let base = self.landing_base();
7410        let base_short = short(&base);
7411        let reviewers = self.roles.reviewers.clone();
7412        let shell = self.state.config.shell();
7413
7414        for round in (self.state.reviews.len() + 1)..=max_rounds {
7415            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7416            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7417            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7418            // The prior round's own record, already persisted — never a
7419            // hand-carried variable of just its failing output: that is
7420            // exactly what let a round's e2e result drift out of sync with
7421            // which commit it was actually about (see `SCHEMA`'s doc for
7422            // schema 8). Judged against `head`, the commit reviewers are
7423            // about to look at now, so the summary always reads as "an
7424            // earlier head" here — this round's own patch has not been
7425            // checked yet.
7426            let prev_verification = self
7427                .state
7428                .reviews
7429                .last()
7430                .and_then(|r| r.verification_summary(&head));
7431            // Only the first round of a run that took a branch over: later
7432            // rounds have this run's own history.
7433            let prior_section = match (&self.state.recovery, round) {
7434                (Some(rec), 1) if self.state.reviews.is_empty() => {
7435                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7436                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7437                            Some(crate::recovery::head_of(
7438                                &git::diff(&winner.worktree, reviewed, "HEAD")
7439                                    .await
7440                                    .unwrap_or_default(),
7441                                crate::recovery::SINCE_DIFF_MAX,
7442                            ))
7443                        }
7444                        _ => None,
7445                    };
7446                    Some(prompt::recovery_review(rec, since.as_deref()))
7447                }
7448                _ => None,
7449            };
7450
7451            // Each reviewer gets its own detached checkout of exactly this
7452            // commit: nobody can perturb the winner's tree, and the fixer can
7453            // keep working without racing a reviewer.
7454            let mut jobs = Vec::new();
7455            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7456                self.coordinate(&repo).await?
7457            } else {
7458                None
7459            };
7460            for (r, spec) in reviewers.iter().cloned().enumerate() {
7461                let wt = root.join(format!("review-{}", r + 1));
7462                // `clean -fdx` in a reset wipes setup's products, so every
7463                // round sets the seat up again.
7464                if wt.exists() {
7465                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7466                } else {
7467                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7468                        None
7469                    } else {
7470                        self.coordinate(&repo).await?
7471                    };
7472                    git::worktree_add_detached(&repo, &wt, &head).await?;
7473                }
7474                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7475                    None
7476                } else {
7477                    self.coordinate(&repo).await?
7478                };
7479                self.setup_seat_worktree(
7480                    &repo,
7481                    &wt,
7482                    false,
7483                    coordination.as_ref().or(_setup_lease.as_ref()),
7484                )
7485                .await?;
7486                let seat_key = format!("review-{}", r + 1);
7487                // The seat starts the round on whoever answered it last, not
7488                // on the agent the spec names, so a failure is not re-paid.
7489                let spec = pick_start_spec(
7490                    &self.roles.reviewer_roster,
7491                    spec,
7492                    self.state.seat_history.get(&seat_key),
7493                );
7494                let seat = self.seat(&seat_key, &spec.id);
7495                jobs.push(SeatJob {
7496                    prompt: prompt::review(&prompt::ReviewCtx {
7497                        instruction: &self.state.instruction,
7498                        branch: &winner.branch,
7499                        base_short: &base_short,
7500                        stat: &stat,
7501                        patch: &patch,
7502                        verification: prev_verification.as_ref(),
7503                        prior: prior_section.as_deref(),
7504                        reviewers: reviewers.len(),
7505                        round,
7506                        rounds: max_rounds,
7507                        // A review-only run has no rankings, so nothing
7508                        // competed for this patch and the reviewer is told so.
7509                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7510                        lens: Lens::for_seat(r),
7511                        language: &language,
7512                        github_language: &self.state.config.graph.github_language,
7513                    }),
7514                    spec,
7515                    seat,
7516                    cwd: wt,
7517                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7518                    allow_write: false,
7519                    sessions,
7520                    artifacts: artifacts.clone(),
7521                    stem: format!("review-{round}-{}", r + 1),
7522                    handover: None,
7523                });
7524            }
7525
7526            drop(coordination);
7527            self.state.event(
7528                "review",
7529                format!(
7530                    "round {round}: {} reviewers on {}",
7531                    jobs.len(),
7532                    short(&head)
7533                ),
7534            );
7535            let mut quota_losses = Vec::new();
7536            let review_retries = self.state.config.graph.retries;
7537            let review_cache = self.state.config.cache_dir();
7538            let ctx = WaveCtx {
7539                carry_seats: true,
7540                pauses: Some((&self.pause, &self.interrupt)),
7541                run: &run_id,
7542                node: "review",
7543                prompts: &prompts,
7544                cache: review_cache.as_deref(),
7545                round: Some(round),
7546            };
7547            let results = ask_json_wave::<Review>(
7548                jobs,
7549                Arc::clone(&self.sem),
7550                review_retries,
7551                &self.roles.reviewer_roster,
7552                &ctx,
7553                &mut quota_losses,
7554                &mut self.state,
7555                &|_: &Review| Ok(()),
7556            )
7557            .await;
7558            if self.state.resource_block.is_some() {
7559                return self.stop_for_resource();
7560            }
7561            // Counted before the move below: how many of *this* round's
7562            // reviewer seats were lost to their own rate limit, as opposed to
7563            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7564            let round_quota_missing = quota_losses.len();
7565            self.state.quota.extend(quota_losses);
7566
7567            let mut records = Vec::new();
7568            let mut all_findings = Vec::new();
7569            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7570                let agent_id = seat.agent.clone();
7571                self.state.seats.insert(seat.key.clone(), seat);
7572                let mut record = ReviewRecord {
7573                    reviewer: r + 1,
7574                    agent: agent_id,
7575                    summary: String::new(),
7576                    findings: Vec::new(),
7577                    vote: None,
7578                    failed: None,
7579                    duration_ms: 0,
7580                    // Set for both outcomes: `failed: Some(_)` with
7581                    // `attempts > 0` is a seat every retry still lost, not a
7582                    // recovered one — only `failed: None` with `attempts > 0`
7583                    // reads as "answered after a nudge" (see this field's own
7584                    // doc).
7585                    attempts,
7586                };
7587                match res {
7588                    Ok((review, out)) => {
7589                        // Sanitized here, at the point every other piece of
7590                        // agent prose in this file is (candidate summaries,
7591                        // deliberation turns, vote reasons): a reviewer's own
7592                        // words are the one thing about it that could name
7593                        // it, and reconsideration below broadcasts this same
7594                        // summary and these same findings to every other
7595                        // seat on the panel.
7596                        record.summary =
7597                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7598                        record.vote = Some(review.vote);
7599                        record.duration_ms = out.duration_ms;
7600                        for (n, mut f) in review.findings.into_iter().enumerate() {
7601                            // ids are magi's, never the agent's: the fixer's
7602                            // adoption report is keyed by them.
7603                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7604                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7605                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7606                            // `file` is agent-supplied prose too, never
7607                            // checked against the real tree — the same
7608                            // exposure `title`/`detail` above have, just in
7609                            // a field easy to forget because it looks like a
7610                            // path rather than free text.
7611                            f.file = f
7612                                .file
7613                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7614                            all_findings.push(f.clone());
7615                            record.findings.push(f);
7616                        }
7617                        self.state.event(
7618                            "review",
7619                            format!(
7620                                "round {round}: reviewer {} voted {} with {} finding(s)",
7621                                r + 1,
7622                                review.vote.label(),
7623                                record.findings.len()
7624                            ),
7625                        );
7626                    }
7627                    Err(e) => {
7628                        record.failed = Some(e.to_string());
7629                        self.state.event(
7630                            "review",
7631                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7632                        );
7633                    }
7634                }
7635                records.push(record);
7636            }
7637
7638            // Tally the round's votes and, if they split, spend the one
7639            // round of reconsideration the split -> deliberate -> revote
7640            // shape `judge`/`vote` use for the panel, sized down to what a
7641            // read-only review round can afford: one round, and a revote
7642            // rather than an argument, because the panel already wrote its
7643            // reasoning down as findings the first time around.
7644            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7645            let vote_split =
7646                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7647            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7648            if vote_split {
7649                self.state.event(
7650                    "review",
7651                    format!(
7652                        "round {round}: votes split ({}) — one round of reconsideration",
7653                        initial_votes
7654                            .iter()
7655                            .map(|v| v.label())
7656                            .collect::<Vec<_>>()
7657                            .join(", ")
7658                    ),
7659                );
7660                // Seats read every seat's findings and votes, still numbered
7661                // and never named — the same anonymity `review` itself keeps.
7662                let panel: Vec<ReviewSeatReport<'_>> = records
7663                    .iter()
7664                    .filter_map(|r| {
7665                        r.vote.map(|vote| ReviewSeatReport {
7666                            reviewer: r.reviewer,
7667                            vote,
7668                            summary: &r.summary,
7669                            findings: &r.findings,
7670                        })
7671                    })
7672                    .collect();
7673
7674                let mut jobs = Vec::new();
7675                let mut seats_at = Vec::new();
7676                for (r, spec) in reviewers.iter().cloned().enumerate() {
7677                    // A seat with no initial vote has nothing to reconsider
7678                    // from and stays absent, the same as it stayed absent
7679                    // from `panel` above.
7680                    if records[r].vote.is_none() {
7681                        continue;
7682                    }
7683                    let wt = root.join(format!("review-{}", r + 1));
7684                    let seat_key = format!("review-{}", r + 1);
7685                    let spec = self.occupant(&seat_key, spec);
7686                    let seat = self.seat(&seat_key, &spec.id);
7687                    // A seat with no live session has already forgotten the
7688                    // initial review's prompt — restate the patch it is
7689                    // voting on, the same as `deliberate`/`vote` do for a
7690                    // judge in the same position.
7691                    // The panel already carries this seat's own review and
7692                    // vote, so restating the patch makes the prompt whole for
7693                    // a seat handed to another agent.
7694                    let build = |with_patch: bool| {
7695                        prompt::review_reconsider(&ReviewReconsiderCtx {
7696                            instruction: &self.state.instruction,
7697                            reviewer: r + 1,
7698                            lens: Lens::for_seat(r),
7699                            panel: &panel,
7700                            patch: with_patch.then_some(ReviewPatch {
7701                                branch: &winner.branch,
7702                                base_short: &base_short,
7703                                stat: &stat,
7704                                patch: &patch,
7705                            }),
7706                            round,
7707                            rounds: max_rounds,
7708                            language: &language,
7709                        })
7710                    };
7711                    let full = build(true);
7712                    let prompt = if has_context(&spec, &seat, sessions) {
7713                        build(false)
7714                    } else {
7715                        full.clone()
7716                    };
7717                    jobs.push(SeatJob {
7718                        prompt,
7719                        spec,
7720                        seat,
7721                        cwd: wt,
7722                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7723                        allow_write: false,
7724                        sessions,
7725                        artifacts: artifacts.clone(),
7726                        stem: format!("review-{round}-reconsider-{}", r + 1),
7727                        handover: Some(full),
7728                    });
7729                    seats_at.push(r);
7730                }
7731
7732                let mut recon_quota_losses = Vec::new();
7733                let recon_cache = self.state.config.cache_dir();
7734                let recon_ctx = WaveCtx {
7735                    carry_seats: true,
7736                    pauses: Some((&self.pause, &self.interrupt)),
7737                    run: &run_id,
7738                    node: "review",
7739                    prompts: &prompts,
7740                    cache: recon_cache.as_deref(),
7741                    round: Some(round),
7742                };
7743                let recon_results = ask_json_wave::<ReviewRevote>(
7744                    jobs,
7745                    Arc::clone(&self.sem),
7746                    review_retries,
7747                    &self.roles.reviewer_roster,
7748                    &recon_ctx,
7749                    &mut recon_quota_losses,
7750                    &mut self.state,
7751                    &|_: &ReviewRevote| Ok(()),
7752                )
7753                .await;
7754                if self.state.resource_block.is_some() {
7755                    return self.stop_for_resource();
7756                }
7757                self.state.quota.extend(recon_quota_losses);
7758
7759                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
7760                    let agent_id = seat.agent.clone();
7761                    self.state.seats.insert(seat.key.clone(), seat);
7762                    let mut rec = ReviewRevoteRecord {
7763                        reviewer: r + 1,
7764                        agent: agent_id,
7765                        vote: None,
7766                        reason: String::new(),
7767                        failed: None,
7768                    };
7769                    match res {
7770                        Ok((rv, _)) => {
7771                            rec.vote = Some(rv.vote);
7772                            rec.reason =
7773                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
7774                            self.state.event(
7775                                "review",
7776                                format!(
7777                                    "round {round}: reviewer {} revoted {}",
7778                                    r + 1,
7779                                    rv.vote.label()
7780                                ),
7781                            );
7782                        }
7783                        Err(e) => {
7784                            rec.failed = Some(e.to_string());
7785                            self.state.event(
7786                                "review",
7787                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
7788                            );
7789                        }
7790                    }
7791                    reconsideration.push(rec);
7792                }
7793            } else if initial_votes.len() > 1 {
7794                self.state.event(
7795                    "review",
7796                    format!(
7797                        "round {round}: votes agreed ({}) — no reconsideration",
7798                        initial_votes[0].label()
7799                    ),
7800                );
7801            }
7802
7803            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
7804            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
7805            // A round that already has a blocking finding and a round left to
7806            // try is going back to the fixer no matter what `verify.e2e`
7807            // says, so running it first only spends the loop's slowest step
7808            // (minutes, for a Rust repo's full test suite) on a head about
7809            // to be rewritten. Deferred, never skipped: `verify.e2e` still
7810            // runs once a round has no blocking findings left (see
7811            // `round_is_clean`, which a deferred — empty — `e2e` can never
7812            // satisfy since `blocking` is nonzero whenever this branch is
7813            // taken), and `stop_reviewing` forces a real run before it will
7814            // ever read a deferred round as green.
7815            let defer_e2e =
7816                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
7817            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
7818                let reason =
7819                    format!("{blocking} blocking finding(s) already required a fix this round");
7820                self.state.event(
7821                    "verify",
7822                    format!(
7823                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
7824                         {}); it will run once a round has none left",
7825                        short(&head)
7826                    ),
7827                );
7828                (Vec::new(), false, true, Some(reason))
7829            } else {
7830                let e2e_commands = self.state.config.verify.e2e.clone();
7831                let cache_dir = self.state.config.cache_dir();
7832                let context = format!("round {round}");
7833                let wait = self.repository_wait();
7834                let (e2e, verify_retried) = with_cache_lease(
7835                    &mut self.state,
7836                    cache_dir.as_deref(),
7837                    "e2e",
7838                    "e2e",
7839                    &winner.worktree,
7840                    &head,
7841                    verify_timeout,
7842                    &context,
7843                    &wait,
7844                    |state, budget| {
7845                        let shell = shell.clone();
7846                        let e2e_commands = e2e_commands.clone();
7847                        let worktree = winner.worktree.clone();
7848                        let context = context.clone();
7849                        let winner = winner.clone();
7850                        async move {
7851                            if !e2e_commands.is_empty() {
7852                                // The suite certifies one SHA. Format before it
7853                                // runs, or the commit `pre_gate` makes at the
7854                                // gate owes the whole suite again.
7855                                Self::run_pre_gate(state, &winner).await;
7856                            }
7857                            run_e2e_with_retry(
7858                                state,
7859                                &shell,
7860                                &e2e_commands,
7861                                &worktree,
7862                                budget,
7863                                &context,
7864                                Some(round),
7865                            )
7866                            .await
7867                        }
7868                    },
7869                )
7870                .await?;
7871                (e2e, verify_retried, false, None)
7872            };
7873
7874            let expected = records.len();
7875            let answered = records.iter().filter(|r| r.failed.is_none()).count();
7876            let incomplete = answered < expected;
7877            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
7878            let policy = self.state.config.graph.incomplete_review;
7879            let clean = round_is_clean(
7880                blocking,
7881                e2e_ok,
7882                answered,
7883                expected,
7884                round_quota_missing,
7885                policy,
7886            );
7887
7888            let mut round_record = ReviewRound {
7889                round,
7890                head: head.clone(),
7891                verified_head: None,
7892                verified_at: None,
7893                reviews: records,
7894                e2e,
7895                verify_retried,
7896                e2e_deferred,
7897                e2e_defer_reason,
7898                fix: None,
7899                blocking,
7900                answered,
7901                expected,
7902                clean,
7903                progressed: false,
7904                vote_split,
7905                reconsideration,
7906                verdict: None,
7907            };
7908            // The final vote per seat is its revote where reconsideration
7909            // ran and answered, its initial vote otherwise — the same
7910            // fallback `tally` uses for a judge whose private vote failed.
7911            round_record.verdict = ReviewVote::worst(
7912                round_record
7913                    .final_votes()
7914                    .into_iter()
7915                    .map(|(_, _, vote)| vote),
7916            );
7917            // Which commit and when magi actually attempted to check —
7918            // known the moment a command was dispatched against `head`,
7919            // whether or not it finished: a resource-blocked attempt still
7920            // targeted a specific commit at a specific time, and leaving
7921            // that unrecorded is exactly what made `verification_summary`
7922            // report a fresh attempt as "commit unknown ... recorded before
7923            // this was tracked", indistinguishable from a genuinely old,
7924            // untracked record. Only a deferred or unconfigured round never
7925            // ran at all and has nothing to record — see
7926            // `ReviewRound::verified_head`'s own doc.
7927            if !matches!(
7928                round_record.e2e_status(),
7929                E2eStatus::Deferred | E2eStatus::NotConfigured
7930            ) {
7931                // HEAD, not the reviewed `head`: `pre_gate` may have committed
7932                // mechanical fixes before the commands ran.
7933                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
7934                round_record.verified_at = Some(Timestamp::now());
7935            }
7936
7937            if incomplete {
7938                let missing: Vec<String> = round_record
7939                    .reviews
7940                    .iter()
7941                    .filter(|r| r.failed.is_some())
7942                    .map(|r| format!("review-{}", r.reviewer))
7943                    .collect();
7944                self.state.event(
7945                    "review",
7946                    format!(
7947                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
7948                        missing.join(", ")
7949                    ),
7950                );
7951            }
7952
7953            if clean {
7954                self.state.event(
7955                    "review",
7956                    if incomplete && policy == IncompleteReviewPolicy::Warn {
7957                        format!(
7958                            "round {round}: clean (warn policy, incomplete panel) — no \
7959                             blocking findings from the seats that answered, verification green"
7960                        )
7961                    } else if incomplete {
7962                        format!(
7963                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
7964                             quorum) — no blocking findings from the seats that answered, \
7965                             verification green",
7966                            expected - answered
7967                        )
7968                    } else {
7969                        format!("round {round}: clean — no blocking findings, verification green")
7970                    },
7971                );
7972                self.state.reviews.push(round_record);
7973                self.state.status = RunStatus::Gating;
7974                self.state.save()?;
7975                return Ok(());
7976            }
7977
7978            // Nothing was raised and verification passed, but not every seat
7979            // answered and `round_is_clean` still refused to call it clean —
7980            // either a seat is missing for a reason other than its own quota
7981            // (a crash, a timeout, unparsable output — worth another try), or
7982            // every seat that could have answered lost its quota and nobody
7983            // is left to decide on: re-review rather than send the fixer
7984            // after a round with nothing to fix.
7985            if incomplete && blocking == 0 && e2e_ok {
7986                self.state.reviews.push(round_record);
7987                self.state.save()?;
7988                if round == max_rounds {
7989                    self.state.status = RunStatus::Blocked;
7990                    self.state.event(
7991                        "review",
7992                        format!(
7993                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
7994                             refusing to call it clean",
7995                            expected - answered
7996                        ),
7997                    );
7998                    return Ok(());
7999                }
8000                continue;
8001            }
8002
8003            // Nothing for the fixer to act on (`blocking == 0`) and the only
8004            // reason this round is not clean is that magi itself never got
8005            // a command to run — the shared build cache, not the patch (see
8006            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8007            // the fixer would invite a change to appease contention that has
8008            // nothing to do with the diff, and would leave this attempt
8009            // sitting in the next round's prompt as if it were about an
8010            // earlier, superseded commit rather than what it actually is:
8011            // the same head, still waiting to be checked. Wait for it the
8012            // same way the final round's own contention is already handled,
8013            // whatever round this happens to be.
8014            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8015                self.state.reviews.push(round_record);
8016                return self
8017                    .stop_unresolved_review(
8018                        "the round's own verification could not run",
8019                        &shell,
8020                        &winner.worktree,
8021                    )
8022                    .await;
8023            }
8024
8025            if round == max_rounds {
8026                self.state.reviews.push(round_record);
8027                return self
8028                    .stop_reviewing(
8029                        &format!(
8030                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8031                        ),
8032                        &shell,
8033                        &winner.worktree,
8034                    )
8035                    .await;
8036            }
8037
8038            if !self.fix_review_round(&winner, round_record).await? {
8039                return Ok(());
8040            }
8041        }
8042        Ok(())
8043    }
8044
8045    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8046    /// False means admission or continuation policy stopped the review loop.
8047    async fn fix_review_round(
8048        &mut self,
8049        winner: &Candidate,
8050        mut round_record: ReviewRound,
8051    ) -> Result<bool> {
8052        let round = round_record.round;
8053        let shell = self.state.config.shell();
8054        let step = self.run_fix_round(winner, &mut round_record).await?;
8055        if matches!(step, FixStep::Resource) {
8056            self.stop_for_resource()?;
8057            return Ok(false);
8058        }
8059        if self.state.reviews.len() < round {
8060            self.state.reviews.push(round_record);
8061        } else {
8062            self.state.reviews[round - 1] = round_record;
8063        }
8064        self.state.save()?;
8065
8066        // The fixer's own report never came back this round, even after
8067        // `continue_fix_report`'s own budget was spent on it — not an
8068        // ordinary "no report" (dropped stream, quota, plain failure),
8069        // which already reads that way and is left to the existing round
8070        // budget. Stopping here, rather than opening another round, is
8071        // what keeps a next reviewer/fixer wave from ever being
8072        // dispatched onto `winner.worktree` while whatever the seat's
8073        // last call may still have running there is unaccounted for: no
8074        // process liveness check exists (and none is being added — see
8075        // AGENTS.md/this task's own scope), so the only way to honour
8076        // "nothing starts before a valid report returns" is to not start
8077        // anything further on this worktree from this run at all.
8078        if matches!(step, FixStep::Recorded { report_lost: true }) {
8079            self.stop_reviewing(
8080                "the fixer's adoption report never came back, even after resuming its \
8081                         own seat; refusing to start another round against the same worktree \
8082                         while that is unresolved",
8083                &shell,
8084                &winner.worktree,
8085            )
8086            .await?;
8087            return Ok(false);
8088        }
8089
8090        let streak = self
8091            .state
8092            .reviews
8093            .iter()
8094            .rev()
8095            .take_while(|r| !r.progressed)
8096            .count();
8097        if streak >= STAGNANT_LIMIT {
8098            self.stop_reviewing(
8099                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8100                &shell,
8101                &winner.worktree,
8102            )
8103            .await?;
8104            return Ok(false);
8105        }
8106        Ok(true)
8107    }
8108
8109    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8110    async fn run_fix_round(
8111        &mut self,
8112        winner: &Candidate,
8113        round_record: &mut ReviewRound,
8114    ) -> Result<FixStep> {
8115        let round = round_record.round;
8116        let max_rounds = self.state.config.graph.review_rounds;
8117        let run_id = self.state.id.clone();
8118        let prompts = self.state.config.prompts.clone();
8119        let language = self.state.config.graph.language.clone();
8120        let sessions = self.state.config.graph.sessions;
8121        let artifacts = self.merge_repair_artifacts();
8122        let base = self.landing_base();
8123        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8124        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8125        let this_round_verification = round_record.verification_summary(&head);
8126        let all_findings: Vec<_> = round_record
8127            .reviews
8128            .iter()
8129            .flat_map(|r| r.findings.iter().cloned())
8130            .collect();
8131        // Fix. The winner's own implementer seat continues its conversation:
8132        // the competition is over, so context is pure benefit now.
8133        let blocking_findings: Vec<_> = all_findings
8134            .iter()
8135            .filter(|f| f.severity.blocks())
8136            .cloned()
8137            .collect();
8138        let fix_prompt = prompt::fix_in(
8139            &self.state.instruction,
8140            &blocking_findings,
8141            this_round_verification.as_ref(),
8142            round,
8143            max_rounds,
8144            &language,
8145            &self.state.config.graph.github_language,
8146        );
8147        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8148        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8149        let (job, seat, out) = self
8150            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8151                prompt: fix_prompt.clone(),
8152                spec,
8153                seat,
8154                cwd: winner.worktree.clone(),
8155                timeout,
8156                allow_write: true,
8157                sessions,
8158                artifacts: artifacts.clone(),
8159                stem: format!("fix-{round}"),
8160                handover: None,
8161            })
8162            .await;
8163        // Not asked: the round is not recorded (so a resume repeats it),
8164        // no fixer was handed over to, and the seat is left as it was.
8165        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8166            return Ok(FixStep::Resource);
8167        }
8168        let agent_id = seat.agent.clone();
8169
8170        let mut fix = FixRecord {
8171            agent: agent_id,
8172            addressed: Vec::new(),
8173            rejected: Vec::new(),
8174            notes: String::new(),
8175            committed: false,
8176            failed: None,
8177            duration_ms: 0,
8178            continuation: None,
8179        };
8180        let mut continuation = ContinuationRecord::not_needed();
8181        let mut final_seat = seat.clone();
8182        match out {
8183            AgentOutcome::Ok(o) => {
8184                fix.duration_ms = o.duration_ms;
8185                let parsed = verdict::extract_json::<FixReport>(&o.text);
8186                // A parsed report standing next to a command this same
8187                // reply's own CLI never confirmed the exit status of is
8188                // not a resolved answer — the identical `CommandEvidence`
8189                // `state.jobs` renders, read here instead of only on
8190                // display, per the completion judgment and the shown
8191                // record needing to agree.
8192                let incomplete_reason = match &parsed {
8193                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8194                        "the reply parsed, but it reported a command whose own CLI never \
8195                             confirmed an exit status"
8196                            .to_owned(),
8197                    ),
8198                    Ok(_) => None,
8199                    Err(e) => Some(e.to_string()),
8200                };
8201                match incomplete_reason {
8202                    None => {
8203                        let report = parsed.expect("checked Ok above");
8204                        fix.addressed = report.addressed;
8205                        fix.rejected = report.rejected;
8206                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8207                    }
8208                    Some(reason) => {
8209                        let (resumed_seat, resolved, failure, cont) = self
8210                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8211                            .await;
8212                        fix.duration_ms += cont.cumulative_wait_ms;
8213                        continuation = cont;
8214                        final_seat = resumed_seat;
8215                        match resolved {
8216                            Some(report) => {
8217                                fix.addressed = report.addressed;
8218                                fix.rejected = report.rejected;
8219                                fix.notes =
8220                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8221                            }
8222                            None => fix.failed = failure,
8223                        }
8224                    }
8225                }
8226            }
8227            // The CLI's raw error JSON is not a fix report to parse.
8228            AgentOutcome::Dropped(o) => {
8229                fix.duration_ms = o.duration_ms;
8230                let why = o
8231                    .dropped
8232                    .as_ref()
8233                    .map(|d| d.why.as_str())
8234                    .unwrap_or("the CLI ended the stream without delivering its answer");
8235                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8236            }
8237            AgentOutcome::Quota(o) => {
8238                self.state.quota.push(QuotaLoss::from_report(
8239                    final_seat.key.clone(),
8240                    "fix",
8241                    o.quota.as_ref(),
8242                ));
8243                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8244            }
8245            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8246        }
8247        if self.state.resource_block.is_some() {
8248            self.state.seats.insert(final_seat.key.clone(), final_seat);
8249            return Ok(FixStep::Resource);
8250        }
8251        fix.continuation = Some(continuation);
8252        self.state.seats.insert(final_seat.key.clone(), final_seat);
8253        let coordination = self.coordinate(&winner.worktree).await?;
8254        if let Ok(r) = git::rescue_commit(
8255            &winner.worktree,
8256            &format!("magi: review round {round} fixes (uncommitted work)"),
8257        )
8258        .await
8259        {
8260            self.state.note_withheld("fix", &r.withheld);
8261        }
8262        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8263        fix.committed = after != before;
8264        // Judged by what `git` says moved against base, never by the
8265        // fixer's own `addressed`/`rejected` count — see
8266        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8267        // `patch` snapshot above: swallowing this error would default
8268        // `diff_after` to empty, which almost always differs from a
8269        // non-empty `patch` and reads as "progressed" — exactly backwards
8270        // for a `git` failure the stagnation check cannot see through.
8271        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8272        drop(coordination);
8273        let progressed = diff_after != patch;
8274        let commit_note = if fix.committed {
8275            "committed"
8276        } else {
8277            "NO new commit"
8278        };
8279        let tree_note = if progressed {
8280            "changed vs base"
8281        } else {
8282            "unchanged vs base"
8283        };
8284        self.state.event(
8285            "fix",
8286            match &fix.failed {
8287                // Distinct on purpose from "0 addressed, 0 rejected": the
8288                // fixer's own diff still landed (blocking counts do keep
8289                // falling round over round), only its adoption report did
8290                // not come back, so this must never read like every
8291                // finding was reviewed and declined.
8292                Some(reason) => {
8293                    format!(
8294                        "round {round}: fixer's adoption report was lost ({reason}); \
8295                             {commit_note}, tree {tree_note}"
8296                    )
8297                }
8298                None => format!(
8299                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8300                         {tree_note}{}",
8301                    fix.addressed.len(),
8302                    fix.rejected.len(),
8303                    if continuation.outcome == ContinuationOutcome::Resumed {
8304                        format!(
8305                            " (adoption report recovered after {} continuation(s))",
8306                            continuation.attempts
8307                        )
8308                    } else {
8309                        String::new()
8310                    },
8311                ),
8312            },
8313        );
8314        round_record.fix = Some(fix);
8315        round_record.progressed = progressed;
8316        Ok(FixStep::Recorded {
8317            report_lost: matches!(
8318                continuation.outcome,
8319                ContinuationOutcome::Exhausted
8320                    | ContinuationOutcome::QuotaLost
8321                    | ContinuationOutcome::NoSession
8322            ),
8323        })
8324    }
8325
8326    /// Decide, from the last recorded round's own verification, whether
8327    /// stopping the review loop is a hand-off or a genuine block.
8328    ///
8329    /// Called once the loop has given up trying — the round budget is spent,
8330    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8331    /// findings still open, never while a round is still clean or the
8332    /// incomplete-panel case handled inline above. Gate and e2e are facts
8333    /// about the tree; a lingering review finding is an opinion, and this
8334    /// workload's own `magi stats` puts reviewer precision low enough
8335    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8336    /// must not by itself stand between a green, verified change and the
8337    /// human who decides what to do with it. A red e2e is not an opinion, so
8338    /// that case still blocks, with the failing command and a tail of its
8339    /// output recorded here rather than left in `run.json` for someone to go
8340    /// find.
8341    ///
8342    /// A round that deferred its own e2e (see [`Config::graph`]'s
8343    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8344    /// only because nothing ran, and treating an empty list as a passing one
8345    /// here is exactly the "deferred painted green" bug this function exists
8346    /// to not have. When the last round's own verification never resolved —
8347    /// deferred on purpose, or a real attempt the shared build cache blocked
8348    /// — this makes (or retries) the real run, on the actual worktree this
8349    /// loop is about to stop touching, before deciding anything. A
8350    /// resource-blocked attempt is likewise never read as either green or
8351    /// red: it is evidence about the machine, not the patch (see
8352    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8353    /// blocked cache leaves this call without deciding rather than guessing
8354    /// — the caller retries on a later reentry.
8355    /// Record, once, that the review loop handed off over a blocking finding
8356    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8357    /// `land` asks the owner even with `land_approval` off. Called from every
8358    /// path that concludes `Gating`; a reentry keeps the first record.
8359    fn record_contested_handoff(&mut self) {
8360        if self.state.contested_handoff.is_some() {
8361            return;
8362        }
8363        let Some(contested) = self
8364            .state
8365            .reviews
8366            .last()
8367            .and_then(ReviewRound::contested_handoff)
8368        else {
8369            return;
8370        };
8371        self.state.event(
8372            "review",
8373            format!(
8374                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8375                 wait for the owner's approval",
8376                contested.findings.len(),
8377                contested.rejecters.len()
8378            ),
8379        );
8380        self.state.contested_handoff = Some(contested);
8381    }
8382
8383    async fn stop_unresolved_review(
8384        &mut self,
8385        why: &str,
8386        shell: &[String],
8387        worktree: &Path,
8388    ) -> Result<()> {
8389        self.stop_reviewing_inner(why, shell, worktree, true).await
8390    }
8391
8392    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8393        self.stop_reviewing_inner(why, shell, worktree, false).await
8394    }
8395
8396    async fn stop_reviewing_inner(
8397        &mut self,
8398        why: &str,
8399        shell: &[String],
8400        worktree: &Path,
8401        repairable: bool,
8402    ) -> Result<()> {
8403        let round_idx = self.state.reviews.len() - 1;
8404        // A deferred round and a resource-blocked one are the same shape
8405        // here: neither has a real result yet, and both get one more
8406        // attempt. Read off `e2e_status` — the single source for this —
8407        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8408        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8409        // still retries instead of being read as a settled result the
8410        // instant it stops being empty.
8411        let needs_catchup_run = matches!(
8412            self.state.reviews[round_idx].e2e_status(),
8413            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8414        );
8415        if needs_catchup_run {
8416            let round = self.state.reviews[round_idx].round;
8417            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8418            let commands = self.state.config.verify.e2e.clone();
8419            let before_head = git::rev_parse(worktree, "HEAD").await?;
8420            let winner = self.state.winner().cloned();
8421            let cache_dir = self.state.config.cache_dir();
8422            let context = format!(
8423                "round {round}: verification unresolved, catching up before the final decision"
8424            );
8425            let wait = self.repository_wait();
8426            let (outcomes, verify_retried) = with_cache_lease(
8427                &mut self.state,
8428                cache_dir.as_deref(),
8429                "e2e",
8430                "e2e",
8431                worktree,
8432                &before_head,
8433                timeout,
8434                &context,
8435                &wait,
8436                |state, budget| {
8437                    let shell = shell.to_vec();
8438                    let commands = commands.clone();
8439                    let context = context.clone();
8440                    async move {
8441                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8442                            // Same reason as in the round itself: format before
8443                            // the suite, not after it.
8444                            Self::run_pre_gate(state, &winner).await;
8445                        }
8446                        run_e2e_with_retry(
8447                            state,
8448                            &shell,
8449                            &commands,
8450                            worktree,
8451                            budget,
8452                            &context,
8453                            Some(round),
8454                        )
8455                        .await
8456                    }
8457                },
8458            )
8459            .await?;
8460            // After `pre_gate`: the commit the commands actually ran against.
8461            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8462            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8463                self.state.record_base_progress(&attempted_head);
8464            }
8465            let last = &mut self.state.reviews[round_idx];
8466            last.e2e = outcomes;
8467            last.verify_retried = verify_retried;
8468            // Always the commit and time this attempt actually targeted,
8469            // whether or not it happens to equal the reviewed `head` and
8470            // whether or not a command finished — see
8471            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8472            // attempt is recorded too, so a later reader sees "attempted
8473            // again at T2" rather than silence.
8474            last.verified_head = Some(attempted_head);
8475            last.verified_at = Some(Timestamp::now());
8476            if verify_inconclusive(&last.e2e) {
8477                // Still not a real result: `e2e_deferred` is left exactly
8478                // as it was, so `needs_catchup_run` above reads
8479                // `ResourceBlocked` (via `e2e_status`, which checks
8480                // `resource_blocked` before `e2e_deferred`) and retries
8481                // again on the next reentry, rather than recording
8482                // contention as a red e2e and blocking the run on it.
8483                self.state.save()?;
8484                return Ok(());
8485            }
8486            last.e2e_deferred = false;
8487            // A complete panel may have been saved as unclean solely because
8488            // verification could not run. Refresh that verdict with the new
8489            // outcomes before a granted repair consumes the round's result.
8490            // Incomplete panels retain their original policy/quota decision.
8491            if last.answered == last.expected {
8492                last.clean = round_is_clean(
8493                    last.blocking,
8494                    last.e2e.iter().all(CommandOutcome::ok),
8495                    last.answered,
8496                    last.expected,
8497                    0,
8498                    self.state.config.graph.incomplete_review,
8499                );
8500            }
8501        }
8502        let last = &self.state.reviews[round_idx];
8503        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8504
8505        match last.e2e_status() {
8506            E2eStatus::Failed => {
8507                let red: Vec<String> = last
8508                    .e2e
8509                    .iter()
8510                    .filter(|o| !o.ok())
8511                    .map(|o| {
8512                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8513                            .map(|c| format!(" ({c})"))
8514                            .unwrap_or_default();
8515                        format!(
8516                            "`{}` -> {:?}{comparison}\n{}",
8517                            o.command,
8518                            o.code,
8519                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8520                        )
8521                    })
8522                    .collect();
8523                let can_repair = last.blocking == 0 && last.fix.is_none();
8524                self.state.reviews[round_idx].clean = false;
8525                self.state
8526                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8527                self.state.status = RunStatus::Blocked;
8528                if repairable
8529                    && can_repair
8530                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8531                {
8532                    self.state.status = RunStatus::Reviewing;
8533                }
8534            }
8535            // `needs_catchup_run` above already retried once this call; if
8536            // it is still blocked, this is magi's own admission it could
8537            // not get a command to run, never a verdict on the patch — the
8538            // run is left exactly where a later reentry can retry again.
8539            E2eStatus::ResourceBlocked => {
8540                self.state.event(
8541                    "review",
8542                    format!(
8543                        "{why}; e2e could not run (resource unavailable); not \
8544                         deciding yet"
8545                    ),
8546                );
8547            }
8548            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8549                self.state.event(
8550                    "review",
8551                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8552                );
8553                self.record_contested_handoff();
8554                self.state.status = RunStatus::Gating;
8555            }
8556        }
8557        self.state.save()?;
8558        Ok(())
8559    }
8560
8561    // ----------------------------------------------------------------- gate
8562
8563    async fn gate(&mut self) -> Result<()> {
8564        if self.hold_base_sync().await? {
8565            return Ok(());
8566        }
8567        // Judged by the review record itself, not by `status`: a solo
8568        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8569        // reentry (see `judge`), and trusting it here is exactly how a run
8570        // that exhausted its review budget got gated and merged a second
8571        // time around. `review_conclusion` recomputes the review loop's own
8572        // verdict from the round records themselves — `Gating` for a clean
8573        // round or a hand-off (see `stop_reviewing`), anything else means the
8574        // loop is still going or genuinely blocked.
8575        // A base the winner could not be replayed onto is a decision, not a
8576        // round: there is no landing tree to gate. Read as its own record for
8577        // the same reason the review verdict is.
8578        if self.state.status == RunStatus::Failed
8579            || self
8580                .state
8581                .base_sync
8582                .as_ref()
8583                .is_some_and(|s| s.conflict.is_some())
8584            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8585                != Some(RunStatus::Gating)
8586        {
8587            return Ok(());
8588        }
8589        let Some(winner) = self.state.winner().cloned() else {
8590            return Ok(());
8591        };
8592        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8593        self.state.reconcile_verification_head(&head);
8594        self.state.save()?;
8595        let wait = self.repository_wait();
8596        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8597            return Ok(());
8598        }
8599        if self.state.gate_ran {
8600            // `review_loop` derives its conclusion from the clean review
8601            // record on every reentry and therefore puts a completed run back
8602            // in `Gating`. A recorded gate is a stronger, terminal fact:
8603            // retain its original command output (or lack of any, for a repo
8604            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8605            // doc) and restore `Blocked` on a real failure rather than
8606            // pretending the command is still running or running it a second
8607            // time. `gate_ran == false` remains the only shape — unattempted,
8608            // or a resource-blocked retry — that may still need to execute a
8609            // command.
8610            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8611                self.state.status = RunStatus::Blocked;
8612                self.state.save()?;
8613            }
8614            return Ok(());
8615        }
8616        self.state.status = RunStatus::Gating;
8617        let mut outcomes = self.run_gate(&winner).await?;
8618        let mut attempted_head = self.state.gate_head.clone();
8619        loop {
8620            // A resource-blocked outcome means the gate command never actually
8621            // ran - the shared build cache could not be acquired or confirmed
8622            // fresh in time - which is evidence about the machine, not about
8623            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8624            // Recording it as a red gate would mark a run `Blocked` on nothing
8625            // but contention magi has already logged; leaving `self.state.gate`
8626            // empty and `self.state.gate_ran` false instead keeps the shape
8627            // this function already treats as "still needs to run" (see the
8628            // early-return above), so the next call retries the command
8629            // rather than concluding anything.
8630            if verify_inconclusive(&outcomes) {
8631                self.state.save()?;
8632                return Ok(());
8633            }
8634            if outcomes.iter().all(CommandOutcome::ok) {
8635                break;
8636            }
8637            let fixes_before = self.state.gate_fixes.len();
8638            match self.gate_fix_round(&winner, &outcomes).await? {
8639                GateFix::Retry => {
8640                    outcomes = self.run_gate(&winner).await?;
8641                    attempted_head = self.state.gate_head.clone();
8642                }
8643                GateFix::Stop => {
8644                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8645                    if self.state.gate_fixes.len() > fixes_before
8646                        && attempted_head.as_deref() != Some(current.as_str())
8647                        && verify_current_head(&mut self.state, &winner, &wait).await?
8648                    {
8649                        // A new SHA owes a gate even when a spent fixer changed only
8650                        // commit metadata. This does not grant another repair round.
8651                        outcomes = self.run_gate(&winner).await?;
8652                        attempted_head = self.state.gate_head.clone();
8653                    } else {
8654                        break;
8655                    }
8656                }
8657                GateFix::Defer => {
8658                    self.state.save()?;
8659                    return Ok(());
8660                }
8661            }
8662        }
8663        let passed = outcomes.iter().all(CommandOutcome::ok);
8664        self.state.gate = outcomes;
8665        self.state.gate_ran = true;
8666        self.state.gate_head = attempted_head;
8667        if !self.state.gate.is_empty()
8668            && !verify_inconclusive(&self.state.gate)
8669            && let Some(head) = self.state.gate_head.clone()
8670        {
8671            self.state.record_base_progress(&head);
8672        }
8673        self.state.save()?;
8674        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8675            return Ok(());
8676        }
8677        if !passed {
8678            self.state.status = RunStatus::Blocked;
8679            let spent = self.state.gate_fixes.len();
8680            self.state.event(
8681                "gate",
8682                if spent == 0 {
8683                    "gate failed; not merging".to_owned()
8684                } else {
8685                    format!("gate failed after {spent} gate-fix round(s); not merging")
8686                },
8687            );
8688        }
8689        self.state.save()?;
8690        Ok(())
8691    }
8692
8693    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8694    /// changed into one commit. Runs before `verify.e2e` in the review loop
8695    /// and again before the gate commands, always on the winner and never on
8696    /// a candidate awaiting judging.
8697    ///
8698    /// Before e2e as well as before the gate because command evidence belongs
8699    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8700    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8701    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8702    /// own call then finds nothing left to change. The commands must be
8703    /// idempotent; one that is not makes a commit per call.
8704    ///
8705    /// Never fails the run: a non-zero exit or timeout is a warning and a
8706    /// recorded outcome, and the gate remains the single arbiter. Nothing
8707    /// configured means nothing happens - no event, no commit. `commit_all`
8708    /// commits any leftover change under the neutral identity and returns
8709    /// `false` when the tree is clean, so no empty commit is ever made.
8710    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8711        let commands = state.config.verify.pre_gate.clone();
8712        if commands.is_empty() {
8713            return;
8714        }
8715        let shell = state.config.shell();
8716        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8717        let (outcomes, _) = run_commands(
8718            state,
8719            "pre_gate",
8720            "pre_gate",
8721            0,
8722            &shell,
8723            &commands,
8724            &winner.worktree,
8725            timeout,
8726        )
8727        .await;
8728        for o in &outcomes {
8729            if !o.ok() {
8730                tracing::warn!(
8731                    "pre_gate `{}` failed ({:?}); the gate decides",
8732                    o.command,
8733                    o.code
8734                );
8735            }
8736            state.event(
8737                "pre_gate",
8738                format!(
8739                    "`{}` -> {}",
8740                    o.command,
8741                    if o.ok() {
8742                        "pass".to_owned()
8743                    } else {
8744                        format!(
8745                            "FAIL ({:?})\n{}",
8746                            o.code,
8747                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8748                        )
8749                    }
8750                ),
8751            );
8752        }
8753        state.pre_gate = outcomes;
8754        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
8755            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
8756                Ok(head) => {
8757                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
8758                    state.pre_gate_commit = Some(head);
8759                }
8760                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
8761            },
8762            Ok(false) => {}
8763            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
8764        }
8765        if let Err(e) = state.save() {
8766            tracing::warn!("could not persist the pre_gate record: {e:#}");
8767        }
8768    }
8769
8770    /// Run `verify.gate` once against the winner's current tree, logging one
8771    /// event per command. Empty when nothing is configured.
8772    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
8773        let wait = self.repository_wait();
8774        run_landing_gate(&mut self.state, winner, &wait).await
8775    }
8776
8777    /// One bounded fix round for a failing gate.
8778    ///
8779    /// The fixer is told the failure came from the gate itself, not from a
8780    /// reviewer, and is shown the failed commands, their exit codes and a tail
8781    /// of their output - whatever `[verify].gate` holds, nothing here knows
8782    /// what those commands run. Only a normal non-zero exit that printed
8783    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
8784    /// command or a full disk says nothing about the code, and a fixer sent
8785    /// after it can only appease the machine. The round is judged by what git
8786    /// says moved, never by the fixer's own report, and `verify.e2e` runs
8787    /// again before the gate does, so a fix cannot trade a green gate for a
8788    /// red e2e unnoticed.
8789    async fn gate_fix_round(
8790        &mut self,
8791        winner: &Candidate,
8792        outcomes: &[CommandOutcome],
8793    ) -> Result<GateFix> {
8794        let cap = if self.state.repair_grants.last().is_some_and(|g| {
8795            g.phase == crate::repair_budget::Phase::Fixing
8796                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
8797        }) {
8798            self.state.gate_fixes.len().saturating_add(1)
8799        } else {
8800            self.state.config.graph.gate_fix_rounds
8801        };
8802        let spent = self.state.gate_fixes.len();
8803        if spent >= cap {
8804            if cap > 0 {
8805                self.state.event(
8806                    "gate",
8807                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
8808                );
8809            }
8810            return Ok(GateFix::Stop);
8811        }
8812        if !gate_fixable(outcomes) {
8813            self.state.event(
8814                "gate",
8815                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
8816                 command or similar); not spending a fix round on it",
8817            );
8818            return Ok(GateFix::Stop);
8819        }
8820        let min_free = self.state.config.disk.min_free_bytes;
8821        if min_free > 0 {
8822            match crate::disk::free_bytes(&winner.worktree) {
8823                Ok(free) if crate::disk::enough_space(free, min_free) => {}
8824                Ok(free) => {
8825                    self.state.event(
8826                        "gate",
8827                        format!(
8828                            "only {free} bytes free ({min_free} required by `[disk] \
8829                             min_free_bytes`); not spending a fix round on a failure the disk \
8830                             may explain"
8831                        ),
8832                    );
8833                    return Ok(GateFix::Stop);
8834                }
8835                Err(e) => {
8836                    self.state.event(
8837                        "gate",
8838                        format!("free disk space could not be measured ({e:#}); no fix round"),
8839                    );
8840                    return Ok(GateFix::Stop);
8841                }
8842            }
8843        }
8844
8845        let attempt = spent + 1;
8846        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
8847        let base = self.landing_base();
8848        let fix_prompt = prompt::gate_fix_in(
8849            &self.state.instruction,
8850            &failed,
8851            attempt,
8852            cap,
8853            &self.state.config.graph.language,
8854            &self.state.config.graph.github_language,
8855        );
8856        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8857        let sessions = self.state.config.graph.sessions;
8858        let artifacts = self.merge_repair_artifacts();
8859        self.state.event(
8860            "gate",
8861            format!("gate failed; gate-fix round {attempt} of {cap}"),
8862        );
8863        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8864        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8865        // Persist before invoking the fixer: it may commit and then be
8866        // interrupted before its result (or the following e2e) is saved.
8867        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8868            head: before.clone(),
8869            passed: false,
8870            outcomes: Vec::new(),
8871        });
8872        self.state.save()?;
8873        let (_, seat, out) = self
8874            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
8875                prompt: fix_prompt.clone(),
8876                spec,
8877                seat,
8878                cwd: winner.worktree.clone(),
8879                timeout,
8880                allow_write: true,
8881                sessions,
8882                artifacts: artifacts.clone(),
8883                stem: format!("gate-fix-{attempt}"),
8884                handover: None,
8885            })
8886            .await;
8887        // The fixer was never asked: no round is spent (nothing is recorded)
8888        // and a later reentry asks the same agent again.
8889        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8890            return Ok(GateFix::Defer);
8891        }
8892        let mut record = GateFixRecord {
8893            agent: seat.agent.clone(),
8894            failed,
8895            notes: String::new(),
8896            committed: false,
8897            error: None,
8898        };
8899        match out {
8900            AgentOutcome::Ok(o) => {
8901                // A missing report is not a failed fix: the round is judged
8902                // by the tree below, and the report only carries prose.
8903                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
8904                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8905                }
8906            }
8907            AgentOutcome::Dropped(_) => {
8908                record.error = Some("the CLI dropped the stream".to_owned());
8909            }
8910            AgentOutcome::Quota(o) => {
8911                self.state.quota.push(QuotaLoss::from_report(
8912                    seat.key.clone(),
8913                    "gate-fix",
8914                    o.quota.as_ref(),
8915                ));
8916                record.error = Some("rate limited (quota); fixer could not run".to_owned());
8917            }
8918            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
8919        }
8920        self.state.seats.insert(seat.key.clone(), seat);
8921        let coordination = self.coordinate(&winner.worktree).await?;
8922        if let Ok(r) = git::rescue_commit(
8923            &winner.worktree,
8924            &format!("magi: gate fix {attempt} (uncommitted work)"),
8925        )
8926        .await
8927        {
8928            self.state.note_withheld("gate-fix", &r.withheld);
8929        }
8930        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8931        record.committed = after != before;
8932        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
8933        let note = record.error.clone();
8934        self.state.gate_fixes.push(record);
8935        self.state.save()?;
8936        if !changed {
8937            self.state.event(
8938                "gate",
8939                match note {
8940                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
8941                    None => format!("gate-fix round {attempt}: the tree did not change"),
8942                },
8943            );
8944            return Ok(GateFix::Stop);
8945        }
8946        self.state.event(
8947            "gate",
8948            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
8949        );
8950
8951        drop(coordination);
8952        let wait = self.repository_wait();
8953        check_gate_repair_e2e(&mut self.state, winner, &wait).await
8954    }
8955
8956    // ---------------------------------------------------------------- merge
8957
8958    /// One read-only rewrite by the summary's author; a text the gate still
8959    /// withholds goes to the owner (see `github_text`) and the fixed fallback
8960    /// applies on their word or on silence. `None` means the run is parked on
8961    /// that question and nothing may be pushed or opened yet.
8962    async fn guarded_pr_message(
8963        &mut self,
8964        winner: &Candidate,
8965        facts: Option<&BranchFacts>,
8966        posting: bool,
8967    ) -> Result<Option<PrMessage>> {
8968        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
8969        let head = match final_head.as_deref() {
8970            Some(h) => crate::pr_outcome::FinalHead::At(h),
8971            None => crate::pr_outcome::FinalHead::Unknown,
8972        };
8973        // Only a pull request that is about to be posted pays for a summary.
8974        let summarized = if posting {
8975            Some(self.summarize_change(winner, final_head.as_deref()).await)
8976        } else {
8977            None
8978        };
8979        // A busy shared resource is not a permanent cause: publishing an
8980        // "unavailable" description would stick (a later head move never
8981        // edits the body). Stop before anything is pushed or opened; the
8982        // run is `Blocked` and a resume asks the summary again.
8983        if self.state.resource_block.is_some() {
8984            self.state.event(
8985                "pr-summary",
8986                "a shared resource was busy; nothing was published, resume to summarize again",
8987            );
8988            return Ok(None);
8989        }
8990        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
8991            anyhow::bail!(
8992                "the final commit moved during public description generation; retry before publishing"
8993            );
8994        }
8995        let note = match (&summarized, &self.state.change_summary) {
8996            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
8997            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
8998            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
8999            (None, _) => ChangeNote::NotAsked,
9000        };
9001        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9002        if !posting {
9003            let identity = crate::scrub::Identity::current();
9004            return Ok(Some(PrMessage {
9005                title: crate::scrub::scrub(&pr.title, &identity),
9006                body: crate::scrub::scrub(&pr.body, &identity),
9007            }));
9008        }
9009        // This very text was already rejected and asked about: no second
9010        // judge call, rewrite or question, just carry the record on.
9011        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9012        if let Some(known) = self
9013            .state
9014            .github_text
9015            .clone()
9016            .filter(|g| g.fingerprint == raw_fp)
9017        {
9018            return self.settle_withheld(winner, &pr, known).await;
9019        }
9020        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9021        let mut violations =
9022            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9023        let identity = crate::scrub::Identity::current();
9024        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9025            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9026            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9027        {
9028            violations.push(crate::github_text::Violation::SensitiveData);
9029        }
9030        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9031        // only a language violation starts one; sensitive data alone goes
9032        // straight to the owner, with the redacted text as the fallback.
9033        let has_language = violations
9034            .iter()
9035            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9036        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9037            self.state.event(
9038                "github-text",
9039                if has_language {
9040                    format!("description rejected: {violations:?}; requesting one rewrite")
9041                } else {
9042                    format!("description rejected: {violations:?}; asking the owner")
9043                },
9044            );
9045            let mut rewritten = false;
9046            let mut rejected_rewrite = None;
9047            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9048            {
9049                let output = text;
9050                if let Some(title) = summary_title(&output) {
9051                    // Judge the redacted candidate that will actually be posted.
9052                    // Sensitive data alone must not discard a useful rewrite.
9053                    let raw_body = summary_without_title(&output);
9054                    let clean_title = crate::scrub::scrub(&title, &identity);
9055                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9056                    let redacted = clean_title != title || body != raw_body;
9057                    let title = clean_title;
9058                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9059                    if !complete {
9060                        self.state.event(
9061                            "github-text",
9062                            "description rewrite omitted required findings",
9063                        );
9064                    }
9065                    if !body.trim().is_empty() {
9066                        body.push_str("\n\n");
9067                        body.push_str(&public_pr_evidence(&self.state, head));
9068                    }
9069                    let marker = format!("magi:run/{}", self.state.id);
9070                    if !body.trim().is_empty() && !body.contains(&marker) {
9071                        body.push_str(&format!("\n\n{marker}"));
9072                    }
9073                    let rewrite = PrMessage {
9074                        title: title.clone(),
9075                        body: body.clone(),
9076                    };
9077                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9078                    let mut failed = crate::github_text::check_for(
9079                        &self.state.config.graph,
9080                        &title,
9081                        &body,
9082                        redecision,
9083                    );
9084                    if (!crate::github_text::shareable(&title)
9085                        || !crate::github_text::shareable(&body))
9086                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9087                    {
9088                        failed.push(crate::github_text::Violation::SensitiveData);
9089                    }
9090                    if complete
9091                        && !title.trim().is_empty()
9092                        && !body.trim().is_empty()
9093                        && !failed.is_empty()
9094                    {
9095                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9096                            title: title.clone(),
9097                            body: body.clone(),
9098                            failed: failed
9099                                .iter()
9100                                .map(|v| crate::github_text::category(*v).to_owned())
9101                                .collect(),
9102                        });
9103                    }
9104                    if complete
9105                        && !title.trim().is_empty()
9106                        && !raw_body.trim().is_empty()
9107                        && failed.is_empty()
9108                    {
9109                        decision = redecision;
9110                        pr = PrMessage { title, body };
9111                        rewritten = true;
9112                        self.state
9113                            .event("github-text", "description rewrite passed");
9114                        if redacted {
9115                            self.state.event(
9116                                "github-text",
9117                                "sensitive data removed from description rewrite",
9118                            );
9119                        }
9120                    }
9121                }
9122            }
9123            if !rewritten {
9124                self.state.event(
9125                    "github-text",
9126                    "description rewrite unavailable or rejected; asking the owner",
9127                );
9128                if let Some(w) =
9129                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9130                {
9131                    // A different text than the one asked about before: that
9132                    // question no longer describes anything.
9133                    self.retire_github_text_question("the withheld text changed");
9134                    let record = crate::run::GithubTextAsk {
9135                        rewrite: rejected_rewrite,
9136                        fingerprint: raw_fp,
9137                        title: w.title,
9138                        body: w.body,
9139                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9140                        question: None,
9141                        asks: 0,
9142                        resolved: false,
9143                        chosen_title: None,
9144                        choice: None,
9145                        publication: None,
9146                    };
9147                    return self.settle_withheld(winner, &pr, record).await;
9148                }
9149            }
9150        }
9151        let (title, body) =
9152            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9153        Ok(Some(PrMessage { title, body }))
9154    }
9155
9156    /// Describe the whole change from its final diff in either run mode.
9157    ///
9158    /// The summary is tied to the final commit and to the merge base of the
9159    /// resolved remote base; a record for any other pair is dropped and the
9160    /// agent asked again, so a description never outlives the diff it was
9161    /// written from. The seat is read-only and the prompt tells it to read the
9162    /// diff and the code around it. `[roles] synthesizer` selects the agents
9163    /// (unset: the default pick), each asked at most once, advancing on an
9164    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9165    /// carries the reason it is unavailable; nothing is invented then.
9166    async fn summarize_change(
9167        &mut self,
9168        winner: &Candidate,
9169        head: Option<&str>,
9170    ) -> std::result::Result<(), String> {
9171        let Some(head) = head else {
9172            return Err("the final commit could not be read".to_owned());
9173        };
9174        let remote = self.state.config.merge.remote.clone();
9175        let tracking = format!("{remote}/{}", self.state.base_branch);
9176        if !git::rev_exists(&winner.worktree, &tracking).await {
9177            return Err(format!("the remote base `{tracking}` could not be read"));
9178        }
9179        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9180            Ok(b) if !b.is_empty() => b,
9181            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9182        };
9183        let evidence = crate::pr_outcome::summary_evidence(
9184            &self.state,
9185            crate::pr_outcome::FinalHead::At(head),
9186        );
9187        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9188        if self
9189            .state
9190            .change_summary
9191            .as_ref()
9192            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9193        {
9194            return Ok(());
9195        }
9196        if self.state.change_summary.take().is_some() {
9197            self.state.event(
9198                "pr-summary",
9199                "the final diff or evidence changed; the earlier change summary was discarded",
9200            );
9201        }
9202        // Save the source snapshot even if no generation agent is available.
9203        if let Err(e) = write_artifact(
9204            &self.state,
9205            &format!("public-description-{fingerprint}.md"),
9206            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9207        ) {
9208            tracing::warn!("could not save public description evidence: {e:#}");
9209        }
9210        let chain = match agent::pick_chain(
9211            &self.state.config.agents,
9212            self.state.config.roles.synthesizer.as_ref(),
9213            &agent::installed,
9214            "synthesizer",
9215        ) {
9216            Ok(chain) => chain,
9217            Err(e) => {
9218                tracing::warn!("no agent for the change summary: {e:#}");
9219                self.state.event("pr-summary", "no summary agent available");
9220                return Err("no agent was available to summarize it".to_owned());
9221            }
9222        };
9223        let subjects = git::subjects(&winner.worktree, &base, head)
9224            .await
9225            .unwrap_or_default();
9226        let stat = git::diff_stat(&winner.worktree, &base, head)
9227            .await
9228            .unwrap_or_default();
9229        let stat: String = stat.chars().take(6_000).collect();
9230        let mut prompt = crate::prompt::change_summary_in(
9231            &base,
9232            head,
9233            &subjects,
9234            stat.trim(),
9235            &self.state.config.graph.github_language,
9236        );
9237        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."));
9238        let sessions = self.state.config.graph.sessions;
9239        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9240        let prompts = self.state.config.prompts.clone();
9241        let cache = self.state.config.cache_dir();
9242        let run = self.state.id.clone();
9243        for (i, spec) in chain.into_iter().enumerate() {
9244            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9245            let github_spec = match agent::for_github_text(
9246                &spec,
9247                &self.state.config.graph.github_language,
9248                &winner.worktree,
9249            ) {
9250                Ok(spec) => spec,
9251                Err(e) => {
9252                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9253                    continue;
9254                }
9255            };
9256            let job = SeatJob {
9257                spec: github_spec,
9258                seat,
9259                cwd: winner.worktree.clone(),
9260                prompt: prompt.clone(),
9261                timeout,
9262                allow_write: false,
9263                sessions,
9264                artifacts: agent::artifacts_dir(&self.state.dir()),
9265                stem: if i == 0 {
9266                    "change-summary".to_owned()
9267                } else {
9268                    format!("change-summary-{}", spec.id)
9269                },
9270                handover: None,
9271            };
9272            let ctx = WaveCtx {
9273                run: &run,
9274                node: "pr-summary",
9275                prompts: &prompts,
9276                cache: cache.as_deref(),
9277                round: None,
9278                carry_seats: false,
9279                pauses: Some((&self.pause, &self.interrupt)),
9280            };
9281            let (seat, outcome) =
9282                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9283            self.state.seats.insert(seat.key.clone(), seat);
9284            let text = match outcome {
9285                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9286                AgentOutcome::ResourceBlocked(why) => {
9287                    // No agent was asked: the run stops resumably before
9288                    // anything is published (see `guarded_pr_message`).
9289                    if self.state.resource_block.is_none() {
9290                        self.state.resource_block = Some(crate::run::ResourceBlock {
9291                            cause: crate::run::ResourceBlockCause::Other,
9292                            node: "pr-summary".to_owned(),
9293                            kind: "shared resource".to_owned(),
9294                            detail: why,
9295                            at: Timestamp::now(),
9296                        });
9297                    }
9298                    return Err("a shared resource was busy".to_owned());
9299                }
9300                _ => continue,
9301            };
9302            let blind = &self.state.config.blind;
9303            let Some(title) = summary_title(&text) else {
9304                continue;
9305            };
9306            let body: String = summary_without_title(&text)
9307                .lines()
9308                .filter(|l| !l.contains("magi:run/"))
9309                .collect::<Vec<_>>()
9310                .join("\n");
9311            let body = blind::sanitize_prose(body.trim(), blind);
9312            let title = blind::sanitize_prose(&title, blind);
9313            if body.trim().is_empty() || title.trim().is_empty() {
9314                continue;
9315            }
9316            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9317                continue;
9318            }
9319            // The branch must still be the one the agent was shown.
9320            if git::rev_parse(&winner.worktree, "HEAD")
9321                .await
9322                .ok()
9323                .as_deref()
9324                != Some(head)
9325            {
9326                return Err("the branch moved while the summary was written".to_owned());
9327            }
9328            if git::merge_base(&winner.worktree, &tracking, head)
9329                .await
9330                .ok()
9331                .as_deref()
9332                != Some(base.as_str())
9333                || crate::pr_outcome::summary_evidence(
9334                    &self.state,
9335                    crate::pr_outcome::FinalHead::At(head),
9336                ) != evidence
9337            {
9338                return Err("the summary evidence changed while it was written".to_owned());
9339            }
9340            self.state.change_summary = Some(crate::run::ChangeSummary {
9341                head: head.to_owned(),
9342                base,
9343                evidence: fingerprint,
9344                title,
9345                body,
9346            });
9347            self.state.event(
9348                "pr-summary",
9349                format!("change summary written by {} for the final diff", spec.id),
9350            );
9351            if let Err(e) = self.state.save() {
9352                tracing::warn!("could not save the change summary: {e:#}");
9353            }
9354            return Ok(());
9355        }
9356        self.state
9357            .event("pr-summary", "no agent produced a change summary");
9358        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9359    }
9360
9361    /// One read-only rewrite request for a withheld description. The
9362    /// implementer's own conversation is tried first when it exists and can be
9363    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9364    /// writes it in a separate conversation, skipping the implementer's agent.
9365    /// The prompt carries the whole text, so no agent needs any memory. Each
9366    /// agent is asked at most once and the chain advances on an error, quota,
9367    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9368    /// that has run out of quota must not end the rewrite. Nothing is recorded
9369    /// as a handover.
9370    async fn rewrite_pr_text(
9371        &mut self,
9372        winner: &Candidate,
9373        pr: &PrMessage,
9374        violations: &[crate::github_text::Violation],
9375    ) -> Option<String> {
9376        let prompt = format!(
9377            "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{}",
9378            pr.title, pr.body
9379        );
9380        let sessions = self.state.config.graph.sessions;
9381        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9382        // (spec, the resumed implementer's seat). A fallback seat is created
9383        // only when its turn comes, so an unused fallback leaves no record.
9384        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9385        let key = format!("impl-{}", winner.label);
9386        if let Some(spec) = self
9387            .state
9388            .config
9389            .agents
9390            .iter()
9391            .find(|a| a.id == winner.agent)
9392            .cloned()
9393            && let Some(existing) = self.state.seats.get(&key)
9394            && existing.agent == spec.id
9395            && agent::has_session(spec.kind, existing, sessions)
9396        {
9397            attempts.push((spec, Some(existing.clone())));
9398        }
9399        match agent::pick_chain(
9400            &self.state.config.agents,
9401            self.state.config.roles.language_judge.as_ref(),
9402            &agent::installed,
9403            "language_judge",
9404        ) {
9405            Ok(chain) => {
9406                for spec in chain {
9407                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9408                        continue;
9409                    }
9410                    attempts.push((spec, None));
9411                }
9412            }
9413            Err(e) if attempts.is_empty() => {
9414                tracing::warn!("no agent for the description rewrite: {e:#}");
9415                self.state
9416                    .event("github-text", "no rewrite agent available");
9417                return None;
9418            }
9419            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9420        }
9421        let prompts = self.state.config.prompts.clone();
9422        let cache = self.state.config.cache_dir();
9423        let run = self.state.id.clone();
9424        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9425            let resumed = resumed_seat.is_some();
9426            let seat = resumed_seat.unwrap_or_else(|| {
9427                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9428            });
9429            let github_spec = match agent::for_github_text(
9430                &spec,
9431                &self.state.config.graph.github_language,
9432                &winner.worktree,
9433            ) {
9434                Ok(spec) => spec,
9435                Err(e) => {
9436                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9437                    continue;
9438                }
9439            };
9440            let job = SeatJob {
9441                spec: github_spec,
9442                seat,
9443                cwd: winner.worktree.clone(),
9444                prompt: prompt.clone(),
9445                timeout: retry_budget(timeout_full, resumed),
9446                allow_write: false,
9447                sessions,
9448                artifacts: agent::artifacts_dir(&self.state.dir()),
9449                stem: if i == 0 {
9450                    "github-text-rewrite".to_owned()
9451                } else {
9452                    format!("github-text-rewrite-{}", spec.id)
9453                },
9454                handover: None,
9455            };
9456            let ctx = WaveCtx {
9457                run: &run,
9458                node: "github-text",
9459                prompts: &prompts,
9460                cache: cache.as_deref(),
9461                round: None,
9462                carry_seats: false,
9463                pauses: Some((&self.pause, &self.interrupt)),
9464            };
9465            let (seat, outcome) =
9466                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9467            self.state.seats.insert(seat.key.clone(), seat);
9468            match outcome {
9469                AgentOutcome::Ok(o)
9470                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9471                {
9472                    return Some(o.text);
9473                }
9474                AgentOutcome::ResourceBlocked(_) => return None,
9475                _ => {}
9476            }
9477        }
9478        None
9479    }
9480
9481    /// Abandon the standing posting-gate question, if any.
9482    fn retire_github_text_question(&mut self, why: &str) {
9483        let Some(id) = self
9484            .state
9485            .github_text
9486            .as_ref()
9487            .and_then(|g| g.question.clone())
9488        else {
9489            return;
9490        };
9491        let _ = ask::Questions::open().update(&id, |q| {
9492            q.abandon(why);
9493            Ok(())
9494        });
9495    }
9496
9497    /// Carry a withheld text to its end: file the question, park while it is
9498    /// open, and on an answer, silence or timeout pick the text to post. The
9499    /// decision is saved before it is used, so it applies once.
9500    async fn settle_withheld(
9501        &mut self,
9502        winner: &Candidate,
9503        pr: &PrMessage,
9504        mut g: crate::run::GithubTextAsk,
9505    ) -> Result<Option<PrMessage>> {
9506        use crate::github_text as gt;
9507        let store = ask::Questions::open();
9508        let timeout = self.state.config.graph.answer_timeout;
9509        if !g.resolved {
9510            let mut standing = g
9511                .question
9512                .as_ref()
9513                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9514            if let Some(q) = standing.as_ref()
9515                && q.status.open()
9516                && !store.held_reply(&q.id)
9517                && gt::expired(q, timeout)
9518            {
9519                let why = format!("no answer within {}s of asking", timeout.max(1));
9520                standing = store
9521                    .update(&q.id, |q| {
9522                        q.abandon(&why);
9523                        Ok(())
9524                    })
9525                    .ok()
9526                    .map(|(q, ())| q);
9527            }
9528            let mut ask_again: Option<Option<Vec<String>>> = None;
9529            match standing {
9530                // Recorded but never written (a stop between the two saves),
9531                // or removed: ask again without spending the retry.
9532                None if g.asks <= 1 => {
9533                    g.asks = 0;
9534                    ask_again = Some(None);
9535                }
9536                None => {
9537                    g.resolved = true;
9538                    g.chosen_title = None;
9539                    g.choice = Some(GithubTextChoice::Fallback);
9540                }
9541                Some(q) if q.status.open() => {
9542                    self.park_on_github_text(&g)?;
9543                    return Ok(None);
9544                }
9545                Some(q) => match gt::read_reply(&q) {
9546                    gt::Reply::Fallback => {
9547                        g.resolved = true;
9548                        g.chosen_title = None;
9549                        g.choice = Some(GithubTextChoice::Fallback);
9550                    }
9551                    gt::Reply::Original => {
9552                        g.resolved = true;
9553                        g.chosen_title = None;
9554                        g.choice = Some(GithubTextChoice::Original);
9555                    }
9556                    gt::Reply::Rewrite => {
9557                        g.resolved = true;
9558                        g.chosen_title = None;
9559                        g.choice = Some(if g.rewrite.is_some() {
9560                            GithubTextChoice::Rewrite
9561                        } else {
9562                            GithubTextChoice::Fallback
9563                        });
9564                    }
9565                    gt::Reply::Title(text) => {
9566                        let first = text
9567                            .lines()
9568                            .map(str::trim)
9569                            .find(|l| !l.is_empty())
9570                            .unwrap_or("");
9571                        let decision = if first.is_empty() {
9572                            None
9573                        } else {
9574                            let candidate = PrMessage {
9575                                title: first.to_owned(),
9576                                body: String::new(),
9577                            };
9578                            self.judge_pr_language(&winner.worktree, &candidate).await
9579                        };
9580                        match gt::vet_title(
9581                            &text,
9582                            decision,
9583                            self.state.config.graph.github_english(),
9584                        ) {
9585                            Ok(title) => {
9586                                g.resolved = true;
9587                                g.chosen_title = Some(title);
9588                                g.choice = Some(GithubTextChoice::MyTitle);
9589                            }
9590                            Err(cats) if g.asks < 2 => {
9591                                ask_again = Some(Some(
9592                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9593                                ))
9594                            }
9595                            Err(_) => {
9596                                g.resolved = true;
9597                                g.chosen_title = None;
9598                                g.choice = Some(GithubTextChoice::Fallback);
9599                            }
9600                        }
9601                    }
9602                },
9603            }
9604            if let Some(rejected) = ask_again {
9605                // A retry (after a rejected replacement title) is still about
9606                // the original text: the same ORIGINAL / FALLBACK comparison.
9607                let w = gt::Withheld {
9608                    title: g.title,
9609                    body: g.body,
9610                    categories: g.categories.clone(),
9611                };
9612                // Named by the original text's fingerprint alone, so a resume
9613                // rewrites the same file and the detail stays identical.
9614                let artifact = match crate::run::write_artifact(
9615                    &self.state,
9616                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9617                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9618                ) {
9619                    Ok(p) => Some(p),
9620                    Err(e) => {
9621                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9622                        None
9623                    }
9624                };
9625                let (detail, comparison) = gt::question_content(
9626                    &w,
9627                    &pr.title,
9628                    &pr.body,
9629                    &self.state.id,
9630                    rejected.as_deref(),
9631                    artifact.as_deref(),
9632                    g.rewrite.as_ref(),
9633                );
9634                let mut q = ask::Question::new(
9635                    self.state.id.clone(),
9636                    gt::ASK_NODE.to_owned(),
9637                    gt::ASK_SEAT.to_owned(),
9638                    gt::question_summary(&self.state.config.graph.language, &w),
9639                    detail,
9640                    gt::question_choices(&w, g.rewrite.as_ref()),
9641                );
9642                q.posting_comparison = Some(comparison);
9643                q.answer_timeout = timeout;
9644                // Recorded before it is written: a stop in between leaves a
9645                // record naming a question the resume then files again.
9646                g.question = Some(q.id.clone());
9647                g.asks += 1;
9648                self.state.github_text = Some(g.clone());
9649                self.state.event(
9650                    "github-text",
9651                    format!("asking the owner about the withheld text ({})", q.short()),
9652                );
9653                self.state.save()?;
9654                store
9655                    .put_executable(&mut q)
9656                    .context("file the posting-gate question")?;
9657                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9658                    tracing::warn!(
9659                        "could not notify about posting-gate question {}: {e:#}",
9660                        q.short()
9661                    );
9662                }
9663                self.park_on_github_text(&g)?;
9664                return Ok(None);
9665            }
9666        }
9667        let resolved = g.chosen_title.clone();
9668        let original = g.choice == Some(GithubTextChoice::Original);
9669        // Field names only: the event log never records the text.
9670        self.state.event(
9671            "github-text",
9672            if original {
9673                format!(
9674                    "posting the original text for: {}",
9675                    match (g.title, g.body) {
9676                        (true, true) => "title, description",
9677                        (true, false) => "title",
9678                        _ => "description",
9679                    }
9680                )
9681            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9682                "posting the saved rewrite title and description".to_owned()
9683            } else if resolved.is_some() {
9684                "posting the owner's replacement title".to_owned()
9685            } else {
9686                "posting the neutral text for the withheld fields".to_owned()
9687            },
9688        );
9689        self.state.github_text = Some(g.clone());
9690        self.state.save()?;
9691        if g.choice == Some(GithubTextChoice::Rewrite)
9692            && let Some(r) = g.rewrite.as_ref()
9693        {
9694            return Ok(Some(PrMessage {
9695                title: r.title.clone(),
9696                body: r.body.clone(),
9697            }));
9698        }
9699        let w = gt::Withheld {
9700            title: g.title,
9701            body: g.body,
9702            categories: g.categories.clone(),
9703        };
9704        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9705        if let Some(t) = resolved {
9706            title = t;
9707        }
9708        // Every withheld field is now neutral or vetted English.
9709        let english = gt::LanguageDecision {
9710            title_english: true,
9711            body_english: true,
9712            body_complete: true,
9713        };
9714        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9715        if original {
9716            // The owner's explicit choice overrides the gate for the fields it
9717            // was made for; the others keep what the gate produced.
9718            if g.title {
9719                title = pr.title.clone();
9720            }
9721            if g.body {
9722                body = pr.body.clone();
9723            }
9724        }
9725        Ok(Some(PrMessage { title, body }))
9726    }
9727
9728    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9729        self.state.github_text = Some(g.clone());
9730        self.state.end_pass_parked(ParkCause::Question);
9731        self.state.parked = true;
9732        self.state.event(
9733            "github-text",
9734            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9735        );
9736        self.state.save()
9737    }
9738
9739    /// Ask `[roles] language_judge` about this text and record which source
9740    /// decided; the text itself is never recorded.
9741    async fn judge_pr_language(
9742        &mut self,
9743        cwd: &Path,
9744        pr: &PrMessage,
9745    ) -> Option<crate::github_text::LanguageDecision> {
9746        self.state.config.roles.language_judge.as_ref()?;
9747        if !self.state.config.graph.language_gate() {
9748            return None;
9749        }
9750        let decision =
9751            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
9752        self.state.event(
9753            "github-text",
9754            if decision.is_some() {
9755                "language decided by the language judge"
9756            } else {
9757                "language judge unavailable; using built-in heuristics"
9758            },
9759        );
9760        decision
9761    }
9762
9763    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
9764        Box::pin(self.merge_inner())
9765    }
9766
9767    async fn merge_inner(&mut self) -> Result<()> {
9768        if self.resource_halt()? || self.hold_base_sync().await? {
9769            return Ok(());
9770        }
9771        // Same reasoning as `gate`: ask the review and gate records directly
9772        // rather than `status`, which a solo-candidate `judge`/`deliberate`
9773        // skip can rewrite on reentry to something that no longer says
9774        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
9775        // so a hand-off (open findings, green verification) reaches merge
9776        // exactly like a genuinely clean round does.
9777        //
9778        // A run resumed mid-`land` never reaches here at all: `execute`
9779        // recognises `RunStatus::Landing` before it even calls `prep`, and
9780        // routes straight to `run_land` instead. That has to happen a level
9781        // up from this function, not with a check in here, because
9782        // `review_loop`'s own status recomputation (see its doc) runs
9783        // *before* `merge` on every reentry and would otherwise overwrite
9784        // the `Landing` marker with `Gating` before this node ever saw it.
9785        if self
9786            .state
9787            .base_sync
9788            .as_ref()
9789            .is_some_and(|s| s.conflict.is_some())
9790            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9791                != Some(RunStatus::Gating)
9792            // `gate_ran == false` is not "passed" - `gate` leaves it false
9793            // both before it has ever run and when its last attempt was
9794            // resource-blocked (see `Runner::gate`'s own doc), and neither is
9795            // permission to merge on nothing but the review record. Only a
9796            // gate that actually ran may proceed; an intentional local
9797            // review can also finish with verification explicitly not configured.
9798            // `RunState::gate_status` computes that distinction.
9799            || !self.state.gate_allows_progress()
9800        {
9801            return Ok(());
9802        }
9803        // This node's own record, not `status`: `status == Ready` is not
9804        // unique to the harmless `MergeMode::None` path this line was
9805        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
9806        // run's PR was closed without merging — and on that run `mode` is
9807        // still `Pr`, so a reentry that fell through here would push and
9808        // open a second pull request. `self.state.merge` is set exactly once
9809        // this node (or `land`) has already produced a verdict, under every
9810        // mode, which is what "already done" actually means here.
9811        if self.state.merge.is_some() && !self.state.pr_publication_pending {
9812            return Ok(());
9813        }
9814        let Some(winner) = self.state.winner().cloned() else {
9815            return Ok(());
9816        };
9817        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9818        if self.state.gate_head.as_deref() != Some(head.as_str()) {
9819            self.state.status = RunStatus::Blocked;
9820            self.state.event(
9821                "gate",
9822                "winner changed after gate; fresh verification required",
9823            );
9824            self.state.save()?;
9825            return Ok(());
9826        }
9827        let wait = self.repository_wait();
9828        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9829            return Ok(());
9830        }
9831        let repo = self.state.repo.clone();
9832        let base = self.state.base_branch.clone();
9833        let mode = self.state.config.merge.mode;
9834        let style = self.state.config.merge.style;
9835        let facts = if is_review_run(&self.state) {
9836            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
9837            let start = review_base(
9838                &repo,
9839                &self.state.config.merge.remote,
9840                &base,
9841                &self.state.base_commit,
9842                &winner.branch,
9843            )
9844            .await;
9845            branch_facts(&repo, &start, &winner.branch).await
9846        } else {
9847            None
9848        };
9849        // `None` when the base could not be freshly read: then an adopted
9850        // pull request's title is left alone.
9851        let leaked = if is_review_run(&self.state) {
9852            leaked_subjects(&self.state, &winner.branch).await
9853        } else {
9854            Some(Vec::new())
9855        };
9856        // `None`: parked on the owner's word about a withheld title or body.
9857        // Nothing has been pushed or opened, and `merge` stays unrecorded so
9858        // the resume arrives here again.
9859        let Some(pr) = self
9860            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
9861            .await?
9862        else {
9863            return Ok(());
9864        };
9865        let message = pr.commit_message();
9866
9867        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
9868        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
9869            return Ok(());
9870        }
9871        let outcome = match mode {
9872            MergeMode::None => MergeOutcome {
9873                mode,
9874                ok: true,
9875                detail: manual_merge_command(style, &repo, &winner.branch, &message),
9876                empty: false,
9877            },
9878            MergeMode::Pr | MergeMode::Local
9879                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
9880            {
9881                MergeOutcome {
9882                    mode,
9883                    ok: false,
9884                    detail: empty_candidate_detail(&self.state, &base),
9885                    empty: true,
9886                }
9887            }
9888            MergeMode::Local => {
9889                let on = git::current_branch(&repo).await?;
9890                if on.as_deref() != Some(base.as_str()) {
9891                    MergeOutcome {
9892                        mode,
9893                        ok: false,
9894                        detail: format!(
9895                            "{} has {} checked out, not the base branch {base}",
9896                            repo.display(),
9897                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
9898                        ),
9899                        empty: false,
9900                    }
9901                } else if !git::is_clean(&repo).await? {
9902                    MergeOutcome {
9903                        mode,
9904                        ok: false,
9905                        detail: format!("{} is dirty; refusing to merge", repo.display()),
9906                        empty: false,
9907                    }
9908                } else {
9909                    let out = match style {
9910                        MergeStyle::Merge => {
9911                            git::merge_no_ff(&repo, &winner.branch, &message).await?
9912                        }
9913                        MergeStyle::Squash => {
9914                            git::merge_squash(&repo, &winner.branch, &message).await?
9915                        }
9916                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
9917                    };
9918                    MergeOutcome {
9919                        mode,
9920                        ok: out.ok(),
9921                        detail: if out.ok() { out.stdout } else { out.stderr },
9922                        empty: false,
9923                    }
9924                }
9925            }
9926            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
9927                self.state.pr_publication_pending = true;
9928                self.state.save()?;
9929                let out =
9930                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
9931                self.state.pr_publication_pending = out.is_err();
9932                MergeOutcome {
9933                    mode,
9934                    ok: out.is_ok(),
9935                    detail: match out {
9936                        Ok(url) => url,
9937                        Err(e) => format!("{e:#}"),
9938                    },
9939                    empty: false,
9940                }
9941            }
9942            MergeMode::Pr => {
9943                let remote = self.state.config.merge.remote.clone();
9944                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
9945                let pushed = if self.state.foreign_checkout.is_some() {
9946                    let refspec = format!("{delivery_head}:refs/heads/{public}");
9947                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
9948                } else {
9949                    git::push(&winner.worktree, &remote, &winner.branch).await?
9950                };
9951                if !pushed.ok() {
9952                    MergeOutcome {
9953                        mode,
9954                        ok: false,
9955                        detail: pushed.stderr,
9956                        empty: false,
9957                    }
9958                } else {
9959                    if self.state.foreign_checkout.is_some() {
9960                        self.state.pr_pushed_head = Some(delivery_head.clone());
9961                    }
9962                    // A retry or resume of a run whose branch already has an
9963                    // open pull request adopts it rather than failing on a
9964                    // duplicate. Only this winner branch into this base:
9965                    // `branch_for` derives the name from the run id, so a
9966                    // different run's pull request never matches.
9967                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
9968                    let out = match pr_merge_plan(found) {
9969                        PrPlan::Create => {
9970                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
9971                                .await
9972                        }
9973                        PrPlan::Adopt { url, title } => {
9974                            self.state
9975                                .event("merge", format!("Pr: adopted open pull request {url}"));
9976                            if self.state.explicit_github_text_selection() {
9977                                // An explicit publication selection applies the prepared
9978                                // payload; acceptance alone is not publication proof.
9979                                land::set_pr_text_verbatim(
9980                                    &winner.worktree,
9981                                    &url,
9982                                    &pr.title,
9983                                    &pr.body,
9984                                )
9985                                .await
9986                                .map(|()| url)
9987                            } else {
9988                                if title != pr.title
9989                                    && (!is_review_run(&self.state)
9990                                        || leaked
9991                                            .as_deref()
9992                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
9993                                    && let Err(e) =
9994                                        if self.state.github_text.as_ref().is_some_and(|g| {
9995                                            g.resolved
9996                                                && g.title
9997                                                && g.choice == Some(GithubTextChoice::Original)
9998                                        }) {
9999                                            // The owner chose to post this title unmodified.
10000                                            land::set_pr_title_verbatim(
10001                                                &winner.worktree,
10002                                                &url,
10003                                                &pr.title,
10004                                            )
10005                                            .await
10006                                        } else {
10007                                            land::set_pr_title(
10008                                                &mut self.state,
10009                                                &winner.worktree,
10010                                                &url,
10011                                                &pr.title,
10012                                            )
10013                                            .await
10014                                        }
10015                                {
10016                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10017                                    self.state
10018                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10019                                }
10020                                Ok(url)
10021                            }
10022                        }
10023                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10024                    };
10025                    match out {
10026                        Ok(url) => MergeOutcome {
10027                            mode,
10028                            ok: true,
10029                            detail: url,
10030                            empty: false,
10031                        },
10032                        Err(e) => MergeOutcome {
10033                            mode,
10034                            ok: false,
10035                            detail: e.to_string(),
10036                            empty: false,
10037                        },
10038                    }
10039                }
10040            }
10041        };
10042
10043        self.state.status = match (mode, outcome.ok) {
10044            (MergeMode::None, _) => RunStatus::Ready,
10045            (_, true) if outcome.empty => RunStatus::Ready,
10046            (MergeMode::Pr, true) => RunStatus::Ready,
10047            (_, true) => RunStatus::Merged,
10048            (_, false) => RunStatus::Blocked,
10049        };
10050        self.state.event(
10051            "merge",
10052            format!(
10053                "{:?}: {}",
10054                mode,
10055                outcome.detail.lines().next().unwrap_or("")
10056            ),
10057        );
10058        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10059            self.state.record_github_text_publication(&outcome.detail);
10060        }
10061        self.state.merge = Some(outcome);
10062        self.state.save()?;
10063
10064        // The PR is open and the run would historically stop here, leaving the
10065        // operator to watch checks, feed review comments back to a fixer, and
10066        // merge. That was done by hand six times in one session before this
10067        // existed. Opt-in, because merging is the one irreversible thing magi
10068        // can do to a repository.
10069        if self.state.config.graph.land
10070            && mode == MergeMode::Pr
10071            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10072        {
10073            self.run_land().await?;
10074        }
10075        // `run_land` may have left `status` at `Landing` - still waiting on
10076        // CI or the owner's approval, not actually settled - so this has to
10077        // read whatever `status` ended up as here, not the `Merged` this
10078        // function set a few lines up.
10079        self.settle_questions();
10080        Ok(())
10081    }
10082
10083    /// Enter `land`.
10084    ///
10085    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10086    /// a resumed run's re-entry. `land::land` itself is what serialises the
10087    /// two git-mutating moments inside the loop — the rebase push and
10088    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10089    /// to hold a lock across the whole call, and doing so would serialise
10090    /// this run's CI wait against a *different* run's land-approval resume
10091    /// in the same repository, which is exactly the "must not wait on
10092    /// another task" property the daemon's slot-freeing exists to give.
10093    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10094        Box::pin(self.run_land_inner())
10095    }
10096
10097    async fn run_land_inner(&mut self) -> Result<()> {
10098        crate::pr_head::ensure_owner(&self.state)?;
10099        let url = self
10100            .state
10101            .pr
10102            .as_ref()
10103            .map(|pr| pr.url.clone())
10104            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10105            .unwrap_or_default();
10106        let url = url.lines().next().unwrap_or("").trim().to_owned();
10107        if !url.starts_with("http") {
10108            return Ok(());
10109        }
10110        // A land failure is not a lost run: the work is on a branch and the
10111        // pull request is open, which is exactly where a human takes over.
10112        loop {
10113            match land::land(&mut self.state, &url).await {
10114                Ok(_)
10115                    if self
10116                        .state
10117                        .merge_repairs
10118                        .last()
10119                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10120                {
10121                    if self.repair_merge_review().await? {
10122                        continue;
10123                    }
10124                }
10125                Ok(_) if self.state.resource_block.is_some() => {
10126                    return self.stop_for_resource();
10127                }
10128                Ok(pr) if self.state.parked => {
10129                    // `land` already saved the parked marker; nothing here
10130                    // overrides `status` back to a terminal value while an
10131                    // approval is still outstanding.
10132                    let _ = pr;
10133                }
10134                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10135                    self.state.status = RunStatus::Superseded;
10136                    self.state.save()?;
10137                }
10138                Ok(pr) => {
10139                    self.state.status = match pr.state {
10140                        land::PrLifecycle::Merged => RunStatus::Merged,
10141                        _ => RunStatus::Blocked,
10142                    };
10143                    // Downstream of a confirmed merge only - see
10144                    // `bump::should_release_bump`'s own doc for why this one
10145                    // check covers all three of `land`'s success paths.
10146                    // Best-effort: the run already landed, so a failure here
10147                    // (the decision call, `gh`, `cargo`) is recorded and never
10148                    // turns a landed run into a failed one.
10149                    if bump::should_release_bump(self.state.status)
10150                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10151                    {
10152                        // The event is the run's own record. Not-eligible cases
10153                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10154                        // `Err` is a bump that was tried and failed:
10155                        // `after_merge` itself raises the operator notice for
10156                        // that, whether or not a release PR exists yet.
10157                        self.state
10158                            .event("bump", format!("release bump skipped: {e:#}"));
10159                    }
10160                    // Independent of the bump, and best-effort in the same way:
10161                    // findings the merge left open become follow-up tasks.
10162                    if self.state.status == RunStatus::Merged {
10163                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10164                    }
10165                    self.state.save()?;
10166                }
10167                Err(e) => {
10168                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10169                        return Err(e);
10170                    }
10171                    self.state.status = RunStatus::Blocked;
10172                    self.state.event("land", format!("gave up: {e}"));
10173                    self.state.save()?;
10174                }
10175            }
10176            break;
10177        }
10178        Ok(())
10179    }
10180
10181    /// One repair cycle stays under the existing driver/task claim. An
10182    /// interrupted fixer is rolled back and held rather than run twice.
10183    async fn repair_merge_review(&mut self) -> Result<bool> {
10184        use crate::run::MergeRepairPhase as Phase;
10185        crate::pr_head::ensure_owner(&self.state)?;
10186        let i = self.state.merge_repairs.len() - 1;
10187        let request = self.state.merge_repairs[i].clone();
10188        if request.phase == Phase::Fixing {
10189            let restored = match self.state.winner().cloned() {
10190                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10191                None => Err(anyhow::anyhow!("repair has no winning branch")),
10192            };
10193            let why = match restored {
10194                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10195                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10196                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10197            };
10198            self.hold_merge_repair(i, why)?;
10199            return Ok(false);
10200        }
10201        // A completed repair gate is a publication checkpoint. On reentry,
10202        // reject external changes before the ordinary gate path can replace
10203        // that evidence by verifying a new head. Requested repairs still
10204        // start their own review generation below.
10205        if request.phase == Phase::Reviewing && self.state.gate_ran {
10206            let winner = self
10207                .state
10208                .winner()
10209                .context("repair has no winning branch")?;
10210            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10211            if self.state.gate_head.as_deref() != Some(head.as_str())
10212                || !git::is_clean(&winner.worktree).await?
10213            {
10214                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())?;
10215                return Ok(false);
10216            }
10217        }
10218        let failure = if i >= self.state.config.graph.land_rounds
10219            || self.state.config.graph.review_rounds == 0
10220        {
10221            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10222        } else {
10223            None
10224        };
10225        if let Some(why) = failure {
10226            self.hold_merge_repair(i, why)?;
10227            return Ok(false);
10228        }
10229        if request.phase == Phase::Requested {
10230            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10231                Ok(pr) => pr,
10232                Err(e) => {
10233                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10234                    return Ok(false);
10235                }
10236            };
10237            self.state.merge_repairs[i].phase = Phase::Fixing;
10238            self.state.land_approval = None;
10239            self.state.land_armed_head = None;
10240            self.state.save()?;
10241            // Serialize the exact records, including finding ids/details,
10242            // reconsideration reasons, final votes and verification output.
10243            let evidence = serde_json::to_string_pretty(&request)?;
10244            let reason = format!(
10245                "The owner requested fix findings and re-review, without merging. Address the unresolved Major findings and final rejecting votes in this exact review evidence. Do not merge or approve the PR.\n\n{evidence}"
10246            );
10247            let budget = self.state.config.graph.land_rounds;
10248            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10249            match result {
10250                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10251                Ok(land::Fixed::Deferred) => {
10252                    // An unavailable fixer did not spend this repair request.
10253                    // Restore partial fallback work before retrying it, as for
10254                    // an interrupted repair, without closing the request.
10255                    let worktree = self
10256                        .state
10257                        .winner()
10258                        .context("repair has no winning branch")?
10259                        .worktree
10260                        .clone();
10261                    self.graft_restore(&worktree, &request.head).await?;
10262                    self.state.merge_repairs[i].phase = Phase::Requested;
10263                    self.stop_for_resource()?;
10264                    return Ok(false);
10265                }
10266                Ok(land::Fixed::Failed(why)) => {
10267                    self.hold_merge_repair(
10268                        i,
10269                        format!(
10270                            "repair failed: {why}; inspect the branch and run an explicit review"
10271                        ),
10272                    )?;
10273                    return Ok(false);
10274                }
10275                Err(e) => {
10276                    self.hold_merge_repair(
10277                        i,
10278                        format!(
10279                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10280                        ),
10281                    )?;
10282                    return Ok(false);
10283                }
10284            }
10285            // Even no change gets a real new reviewer wave. The previous
10286            // evidence remains in the request; a former clean/concluded round
10287            // cannot short-circuit the new review or gate.
10288            self.begin_merge_repair_review(i)?;
10289        }
10290        self.review_loop().await?;
10291        self.gate().await?;
10292        if self.resource_halt()? || self.state.parked {
10293            return Ok(false);
10294        }
10295        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10296            != Some(RunStatus::Gating)
10297            || !self.state.gate_allows_progress()
10298        {
10299            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10300            return Ok(false);
10301        }
10302        // Review and gate may have added commits after the initial repair.
10303        // Publish exactly their final head to the existing PR, with a lease.
10304        let winner = self
10305            .state
10306            .winner()
10307            .cloned()
10308            .context("repair has no winning branch")?;
10309        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10310        if self.state.gate_head.as_deref() != Some(after.as_str())
10311            || !git::is_clean(&winner.worktree).await?
10312        {
10313            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())?;
10314            return Ok(false);
10315        }
10316        let expected = self
10317            .state
10318            .pr_pushed_head
10319            .as_deref()
10320            .unwrap_or(&request.head)
10321            .to_owned();
10322        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10323        // Push the checked commit itself: a local ref moving after the check
10324        // must not change which commit the forge receives.
10325        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10326            return Ok(false);
10327        }
10328        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10329        let refspec = format!("{after}:refs/heads/{public}");
10330        let push = git::git_raw(
10331            &winner.worktree,
10332            &["push", &lease, &self.state.config.merge.remote, &refspec],
10333        )
10334        .await;
10335        match push {
10336            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10337            Ok(out) => {
10338                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10339                return Ok(false);
10340            }
10341            Err(e) => {
10342                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10343                return Ok(false);
10344            }
10345        }
10346        self.state.merge_repairs[i].phase = Phase::Complete;
10347        self.state.status = RunStatus::Landing;
10348        self.state.event(
10349            "repair",
10350            "new review and gate completed; fresh owner merge decision required",
10351        );
10352        self.state.save()?;
10353        Ok(true)
10354    }
10355
10356    fn merge_repair_artifacts(&self) -> PathBuf {
10357        let artifacts = agent::artifacts_dir(&self.state.dir());
10358        match self
10359            .state
10360            .merge_repairs
10361            .last()
10362            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10363        {
10364            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10365            None => artifacts,
10366        }
10367    }
10368
10369    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10370        if let Some(e2e) = self.state.head_e2e.take() {
10371            self.state
10372                .verification_history
10373                .push(crate::run::VerificationEvidence {
10374                    superseded_by: None,
10375                    archived_at: Some(Timestamp::now()),
10376                    fixes_spent: Some(self.state.gate_fixes.len()),
10377                    gate_head: None,
10378                    gate_ran: false,
10379                    gate: Vec::new(),
10380                    e2e: Some(e2e),
10381                });
10382        }
10383        self.state.reviews.clear();
10384        self.state.gate.clear();
10385        self.state.gate_ran = false;
10386        self.state.gate_head = None;
10387        self.state.gate_fixes.clear();
10388        self.state.gate_repair_e2e = None;
10389        self.state.pre_gate.clear();
10390        self.state.pre_gate_commit = None;
10391        self.state.contested_handoff = None;
10392        self.state.land_reruns = None;
10393        self.state.land_approval = None;
10394        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10395        self.state.status = RunStatus::Reviewing;
10396        self.state.save()
10397    }
10398
10399    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10400        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10401        self.state.merge_repairs[index].failure = Some(why.clone());
10402        self.state.status = RunStatus::Blocked;
10403        self.state.event("repair", why);
10404        self.state.save()
10405    }
10406
10407    // -------------------------------------------------------------- helpers
10408
10409    /// Fetch or create a seat, keeping its conversation across nodes.
10410    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10411        if let Some(existing) = self.state.seats.get(key)
10412            && existing.agent == agent
10413        {
10414            return existing.clone();
10415        }
10416        // A seat that changes agent mints its session id from the agent too,
10417        // like a handover: the old agent's uuid is already taken by the CLI.
10418        let fresh = if self.state.seats.contains_key(key) {
10419            handover_seat(key, agent, self.state.next_seat_seed())
10420        } else {
10421            SeatState::new(key, agent, self.state.seed)
10422        };
10423        self.state.seats.insert(key.to_owned(), fresh.clone());
10424        fresh
10425    }
10426
10427    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10428    /// seat to another roster agent, in which case that agent. Nodes that
10429    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10430    /// reconsideration) must keep talking to whoever answered it, not slip
10431    /// back to the agent that failed it.
10432    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10433        match self.state.seats.get(key) {
10434            Some(s) if s.agent != spec.id => {
10435                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10436            }
10437            _ => spec,
10438        }
10439    }
10440
10441    /// A candidate rendered for judging, with the leak policy applied.
10442    fn view(&self, c: &Candidate) -> CandidateView {
10443        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10444            .unwrap_or_default();
10445        let (patch, _) = blind::sanitize_patch(
10446            &format!("candidate {} patch", c.label),
10447            &raw,
10448            &self.state.config.blind,
10449        );
10450        CandidateView {
10451            label: c.label,
10452            branch: c.branch.clone(),
10453            summary: c.summary.clone(),
10454            stat: c.stat.clone(),
10455            patch,
10456        }
10457    }
10458
10459    /// The full candidate set as prompt text, for seats with no live session.
10460    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10461        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10462        prompt::judge(
10463            "(see above)",
10464            &views,
10465            self.roles.judges.len(),
10466            base_short,
10467            "en",
10468        )
10469    }
10470
10471    /// The final-vote prompt with everything a seat that has no session of its
10472    /// own needs: the candidates, the seat's own ranking and reasons, and the
10473    /// anonymised deliberation it took part in (only when there was one, so a
10474    /// handed-over seat never sees more than the seat it replaces did). The
10475    /// `Final vote` heading stays first.
10476    fn vote_prompt_full(
10477        &self,
10478        j: usize,
10479        labels: &[char],
10480        language: &str,
10481        candidates: &[Candidate],
10482        base_short: &str,
10483    ) -> String {
10484        let mut text = format!(
10485            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10486            prompt::final_vote(labels, language),
10487            self.state.instruction,
10488            self.candidate_block(candidates, base_short)
10489        );
10490        if let Some(own) = self
10491            .state
10492            .judgements
10493            .get(j)
10494            .filter(|r| !r.ranking.is_empty())
10495        {
10496            let reasons = own
10497                .reasons
10498                .iter()
10499                .map(|(k, v)| format!("- {k}: {v}"))
10500                .collect::<Vec<_>>()
10501                .join("\n");
10502            text.push_str(&format!(
10503                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10504                own.ranking.iter().collect::<String>(),
10505                if reasons.is_empty() {
10506                    ""
10507                } else {
10508                    ", because:\n"
10509                }
10510            ));
10511        }
10512        if !self.state.deliberation.is_empty() {
10513            text.push_str("\n# What was argued before this vote\n");
10514            for t in self.transcript(&[], j) {
10515                text.push_str(&format!(
10516                    "\n## {}{}\n\n{}\n",
10517                    t.who,
10518                    if t.is_self { " (you)" } else { "" },
10519                    t.body.trim()
10520                ));
10521            }
10522        }
10523        text
10524    }
10525
10526    /// Anonymised transcript for judge `self_idx`.
10527    ///
10528    /// The initial rankings are always the opening statements. Seeding them
10529    /// only when no turn had been taken yet meant every judge after the first
10530    /// argued against a single voice instead of against the actual split — the
10531    /// disagreement is the information, so it is always on the table.
10532    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10533        let mut turns = Vec::new();
10534        for j in &self.state.judgements {
10535            if j.ranking.is_empty() {
10536                continue;
10537            }
10538            let reasons = j
10539                .reasons
10540                .iter()
10541                .map(|(k, v)| format!("- {k}: {v}"))
10542                .collect::<Vec<_>>()
10543                .join("\n");
10544            turns.push(Turn {
10545                who: format!("Judge {} (opening ranking)", j.judge),
10546                is_self: j.judge == self_idx + 1,
10547                body: format!(
10548                    "Ranked {}{}{reasons}",
10549                    j.ranking.iter().collect::<String>(),
10550                    if reasons.is_empty() {
10551                        ""
10552                    } else {
10553                        ", because:\n"
10554                    }
10555                ),
10556            });
10557        }
10558        for t in self
10559            .state
10560            .deliberation
10561            .iter()
10562            .flat_map(|r| r.turns.iter())
10563            .chain(current)
10564        {
10565            turns.push(Turn {
10566                who: format!("Judge {}", t.judge),
10567                is_self: t.judge == self_idx + 1,
10568                body: t.body.clone(),
10569            });
10570        }
10571        turns
10572    }
10573}
10574
10575/// Does this seat still hold the context a follow-up prompt would rely on?
10576fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10577    agent::has_session(spec.kind, seat, sessions)
10578}
10579
10580/// The next entry in `roster` after `start`, never wrapping back to the
10581/// front, whose id is not in `tried` yet.
10582///
10583/// Starts one past `start` rather than at the front of `roster`: `start` is
10584/// the seat's own original position, and a seat whose candidate slot already
10585/// sits on the roster's second entry must fall through to the third next, not
10586/// restart at the first — which is very likely a different candidate's own
10587/// agent already. Never wraps back past `start`, for the same reason: an
10588/// entry earlier in the roster than the seat's own position is almost
10589/// certainly some *other* candidate slot's own agent, and once the tail of
10590/// the roster is exhausted there are no more untried agents for *this* seat
10591/// to fall through to — the caller's fallback chain ends there, exactly as
10592/// "no further untried agents remain in the list for that seat" asks for.
10593///
10594/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10595/// the same id twice (an operator's `roles.implementers` typo, or a
10596/// `[[agents]]` list reused across roles) must not let
10597/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10598/// over `roster` either finds an untried id or runs out, so this always
10599/// terminates regardless of duplicates.
10600fn next_untried_in_roster<'a>(
10601    roster: &'a [AgentSpec],
10602    start: usize,
10603    tried: &BTreeSet<String>,
10604) -> Option<&'a AgentSpec> {
10605    roster
10606        .get(start + 1..)?
10607        .iter()
10608        .find(|s| !tried.contains(&s.id))
10609}
10610
10611/// The successor for a seat, shared by all four seat kinds (implement, judge,
10612/// review, advise). `others` holds the ids that *currently* occupy the other
10613/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10614/// sees them), so roster entries beyond the seat count act as spares: a failed
10615/// seat goes to an agent no other seat holds whenever the roster permits.
10616///
10617/// `carried` is `Some` only for the review loop's carried failure history.
10618/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10619/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10620/// whole roster: untried and not another seat's occupant; (3) the plain walk
10621/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10622/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10623/// a better outcome than an empty seat, and it keeps the answer to "is there
10624/// a successor at all" exactly what it was before occupants were considered,
10625/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10626/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10627/// carried failure is a cheaper bet than doubling an agent on the panel, and
10628/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10629/// the same round are handled one at a time, so a seat later in the batch
10630/// sees an earlier one's new occupant but not yet its own freed agent.
10631fn pick_successor<'a>(
10632    roster: &'a [AgentSpec],
10633    start: usize,
10634    tried: &BTreeSet<String>,
10635    carried: Option<&BTreeSet<String>>,
10636    others: &BTreeSet<String>,
10637) -> Option<&'a AgentSpec> {
10638    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10639    roster
10640        .get(start + 1..)
10641        .and_then(|tail| {
10642            tail.iter()
10643                .filter(free)
10644                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10645        })
10646        .or_else(|| {
10647            carried
10648                .is_some()
10649                .then(|| roster.iter().find(free))
10650                .flatten()
10651        })
10652        .or_else(|| match carried {
10653            Some(c) => next_for_seat(roster, start, tried, c),
10654            None => next_untried_in_roster(roster, start, tried),
10655        })
10656}
10657
10658/// The next agent for a seat that carries its failure history across rounds
10659/// (the review loop). `round_tried` is this round's own bound and starts
10660/// empty every round; `carried_failed` only decides priority.
10661///
10662/// First: an id walking forward from `start`, never wrapping, that is neither
10663/// tried this round nor failed in an earlier one. Only when that is exhausted
10664/// does it rescue: the first roster id (in roster order, so this one *does*
10665/// look before `start`) not yet tried this round, which is by then a carried
10666/// failure. Each id is rescued at most once per round, so it cannot loop.
10667fn next_for_seat<'a>(
10668    roster: &'a [AgentSpec],
10669    start: usize,
10670    round_tried: &BTreeSet<String>,
10671    carried_failed: &BTreeSet<String>,
10672) -> Option<&'a AgentSpec> {
10673    roster
10674        .get(start + 1..)?
10675        .iter()
10676        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10677        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10678}
10679
10680/// Where a reviewer seat starts a round: the agent that last answered it when
10681/// it is still on the roster and not marked failed, else the spec's own agent
10682/// unless it failed, else the next roster agent that has not failed, else the
10683/// spec's own agent again (the whole roster failed). Ids no longer on the
10684/// roster are ignored. An empty roster has no handover, so the spec stands.
10685fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10686    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10687        return spec;
10688    };
10689    let ok = |id: &str| !h.failed.contains(id);
10690    if let Some(last) = h.last_ok.as_deref()
10691        && ok(last)
10692        && let Some(s) = roster.iter().find(|s| s.id == last)
10693    {
10694        return s.clone();
10695    }
10696    if ok(&spec.id) {
10697        return spec;
10698    }
10699    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10700    roster
10701        .get(from + 1..)
10702        .into_iter()
10703        .flatten()
10704        .chain(roster.iter())
10705        .find(|s| ok(&s.id))
10706        .cloned()
10707        .unwrap_or(spec)
10708}
10709
10710/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10711/// seed so a CLI that mints its session id up front (`--session-id`) never
10712/// reuses the uuid the previous agent already opened under the same seat key.
10713pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10714    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10715}
10716
10717/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10718/// so the classifier below and the code that builds the message cannot drift.
10719const TIMED_OUT: &str = "timed out";
10720
10721impl FailClass {
10722    /// `None` for an answer; otherwise how the turn failed.
10723    fn of(out: &AgentOutcome) -> Option<Self> {
10724        match out {
10725            AgentOutcome::Ok(_) => None,
10726            AgentOutcome::Quota(_) => Some(Self::Quota),
10727            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10728            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10729            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10730            // Not a failure of the agent. Callers check for it first; `None`
10731            // here means "no class to hand over on".
10732            AgentOutcome::ResourceBlocked(_) => None,
10733        }
10734    }
10735
10736    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
10737    fn stem_word(&self) -> &'static str {
10738        match self {
10739            Self::Quota => "quota",
10740            _ => "handover",
10741        }
10742    }
10743}
10744
10745/// The message's first line with its variable parts removed — digit runs and
10746/// path-like tokens — so "exit code 2" and "exit code 7" read
10747/// as one kind of failure.
10748fn failure_signature(msg: &str) -> String {
10749    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
10750    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
10751    // the historical machine key while the process diagnosis uses readable prose.
10752    if let Some(code) = line
10753        .strip_prefix("process exited with no usable output (exit code ")
10754        .and_then(|s| s.strip_suffix(')'))
10755        .and_then(|s| s.parse::<i32>().ok())
10756    {
10757        line = format!("exited with some({code}) and no usable output");
10758    } else if matches!(
10759        line.as_str(),
10760        "process exited with no usable output (no exit code reported)"
10761            | "process exited with no usable output (exit code unavailable)"
10762    ) {
10763        line = "exited with none and no usable output".to_owned();
10764    }
10765    let mut out = Vec::new();
10766    for word in line.split_whitespace() {
10767        if word.contains('/') || word.contains('\\') {
10768            out.push("<path>".to_owned());
10769            continue;
10770        }
10771        let mut w = String::new();
10772        let mut in_digits = false;
10773        for c in word.chars() {
10774            if c.is_ascii_digit() {
10775                if !in_digits {
10776                    w.push('#');
10777                }
10778                in_digits = true;
10779            } else {
10780                in_digits = false;
10781                w.push(c);
10782            }
10783        }
10784        out.push(w);
10785    }
10786    out.join(" ").chars().take(120).collect()
10787}
10788
10789/// Whether a seat that just failed with `cur` may go to the next roster agent.
10790/// A quota or a timeout always may. Any other failure may not when the agent
10791/// before it failed the same way: an error the prompt causes would otherwise
10792/// walk the whole roster. `prev` is the class of the immediately preceding
10793/// agent's failure, so a quota or timeout in between breaks the run of
10794/// identical failures by itself.
10795fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
10796    match cur {
10797        FailClass::Quota | FailClass::Timeout => true,
10798        FailClass::Other(_) => prev != Some(cur),
10799    }
10800}
10801
10802/// A short human reason for a failed outcome, for the handover record.
10803fn fail_reason(out: &AgentOutcome) -> String {
10804    match out {
10805        AgentOutcome::Ok(_) => String::new(),
10806        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
10807        AgentOutcome::Dropped(o) => format!(
10808            "the CLI dropped the stream ({})",
10809            o.dropped
10810                .as_ref()
10811                .map(|d| d.why.as_str())
10812                .unwrap_or("it ended without delivering its answer")
10813        ),
10814        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
10815            e.lines().next().unwrap_or("").chars().take(160).collect()
10816        }
10817    }
10818}
10819
10820/// Note one handover in the run: the structured record and, in the timeline,
10821/// the sentence a person reads. A quota keeps the wording it always had.
10822pub(crate) fn record_handover(
10823    state: &mut RunState,
10824    node: &str,
10825    seat: &str,
10826    from: &str,
10827    to: &str,
10828    class: &FailClass,
10829    reason: &str,
10830) {
10831    let message = if *class == FailClass::Quota {
10832        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
10833    } else {
10834        format!("{seat}: handed over {from} -> {to} ({reason})")
10835    };
10836    state.event(node, message);
10837    state.handovers.push(Handover {
10838        at: Timestamp::now(),
10839        node: node.to_owned(),
10840        seat: seat.to_owned(),
10841        from: from.to_owned(),
10842        to: to.to_owned(),
10843        reason: reason.to_owned(),
10844    });
10845}
10846
10847/// Did this reply report running a command whose own CLI never confirmed an
10848/// exit status?
10849///
10850/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
10851/// command *finished* (see that type's own doc), so this can only be `true`
10852/// for a command whose completion event carried no readable exit code — not
10853/// for one that simply is not mentioned at all. That is the one signal this
10854/// crate can read, from the same record `state.jobs` renders, about a reply
10855/// standing next to work its own CLI cannot vouch for finishing; it is
10856/// deliberately not a check on the exit code's *value* (a fixer legitimately
10857/// runs a command that fails mid-iteration before it succeeds) and not a
10858/// guess at a command still running in the background (which emits no event
10859/// at all, and so leaves no evidence here to find).
10860fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
10861    commands.iter().any(|c| c.exit_code.is_none())
10862}
10863
10864/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
10865/// trusted as a verified no-op — the adoption guard's own text-level half.
10866///
10867/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
10868/// timed out): a marker only earns the benefit of the doubt from a turn the
10869/// CLI itself vouches for finishing properly, the same house style
10870/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
10871/// *fix* report to for `commands`. A candidate that timed out, exited
10872/// non-zero, or left a command unconfirmed is read as the ordinary loss it
10873/// is, whatever prose it wrote — this returns `None` before it ever looks at
10874/// `text`. The remaining guards (the tree really is empty, the evidence is
10875/// non-empty) are the caller's: this only reads what the reply *claimed*.
10876fn verified_noop_claim(
10877    usable: bool,
10878    commands: &[agent::CommandEvidence],
10879    text: &str,
10880) -> Option<String> {
10881    (usable && !has_unconfirmed_command(commands))
10882        .then(|| verdict::verified_noop(text))
10883        .flatten()
10884}
10885
10886fn short(commit: &str) -> String {
10887    commit.chars().take(7).collect()
10888}
10889
10890fn make_executable(path: &Path) -> Result<()> {
10891    #[cfg(unix)]
10892    {
10893        use std::os::unix::fs::PermissionsExt as _;
10894        let mut perms = std::fs::metadata(path)?.permissions();
10895        perms.set_mode(0o755);
10896        std::fs::set_permissions(path, perms)?;
10897    }
10898    #[cfg(not(unix))]
10899    {
10900        let _ = path;
10901    }
10902    Ok(())
10903}
10904
10905/// What every seat in one batch shares: where the answers are attributed, the
10906/// prompt overlay they inherit, and the build cache they are told to use.
10907///
10908/// A struct rather than four more parameters: `wave` also needs the run's
10909/// state (to record who is answering right now) and the attempt number, and
10910/// eight positional arguments is both unreadable and a clippy error.
10911struct WaveCtx<'a> {
10912    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
10913    /// paid for it.
10914    run: &'a str,
10915    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
10916    node: &'a str,
10917    prompts: &'a Prompts,
10918    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
10919    cache: Option<&'a Path>,
10920    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
10921    /// `JobRecord::round`. `None` for every other node.
10922    round: Option<usize>,
10923    /// Carry each seat's failed-agent history across waves (the review loop
10924    /// only): start-of-round priority and handover choice read
10925    /// [`RunState::seat_history`], and every answer or failure writes it.
10926    carry_seats: bool,
10927    /// The run's park / interrupt requests, so a wait for a shared resource
10928    /// can be abandoned the moment the operator asks to park.
10929    pauses: Option<(&'a Pause, &'a Pause)>,
10930}
10931
10932/// Shared scheduling policy for operations and spawned seat invocations.
10933fn repository_wait(
10934    state: &RunState,
10935    pauses: Option<(&Pause, &Pause)>,
10936) -> crate::repo_lock::WaitPolicy {
10937    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
10938    let inherited = crate::repo_lock::WaitPolicy::current();
10939    crate::repo_lock::WaitPolicy::new(
10940        Duration::from_secs(state.config.graph.timeout_resource_wait),
10941        move || {
10942            inherited.cancelled()
10943                || pauses
10944                    .as_ref()
10945                    .is_some_and(|(a, b)| a.parked() || b.parked())
10946        },
10947    )
10948}
10949
10950fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
10951    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
10952        state.event("resource", timeout.0.description());
10953        state.resource_block = Some(timeout.0.clone());
10954        return;
10955    }
10956    if error.is::<crate::repo_lock::ResourceBlocked>() {
10957        state.resource_block = Some(crate::run::ResourceBlock {
10958            cause: crate::run::ResourceBlockCause::Other,
10959            node: "repository".into(),
10960            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
10961                "disk admission"
10962            } else if error.to_string().contains("disk pressure") {
10963                "disk pressure"
10964            } else if error.to_string().contains("disk admission") {
10965                "disk admission"
10966            } else if error.to_string().contains(crate::incremental::BLOCKED) {
10967                "incremental cache admission"
10968            } else {
10969                "repository coordination"
10970            }
10971            .into(),
10972            detail: format!("{error:#}"),
10973            at: Timestamp::now(),
10974        });
10975        state.event("resource", error.to_string());
10976    }
10977}
10978
10979async fn coordinate_operation(
10980    state: &mut RunState,
10981    cwd: &Path,
10982    wait: &crate::repo_lock::WaitPolicy,
10983) -> Result<Option<crate::repo_lock::SeatLease>> {
10984    let result =
10985        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
10986            .await;
10987    if let Err(e) = &result {
10988        record_repository_block(state, e);
10989    }
10990    result
10991}
10992
10993/// Run one job, honouring the parallelism budget.
10994async fn run_one(
10995    job: SeatJob,
10996    sem: Arc<Semaphore>,
10997    ctx: &WaveCtx<'_>,
10998    state: &mut RunState,
10999    attempt: usize,
11000) -> (SeatState, AgentOutcome) {
11001    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11002        .await
11003        .pop()
11004        .expect("one job in, one result out");
11005    (seat, out)
11006}
11007
11008/// Run every job concurrently, capped by the semaphore, preserving order.
11009///
11010/// Every seat in the batch is recorded into [`RunState::active`] before the
11011/// wave starts and cleared as each answer lands, so the run's own record says
11012/// who is still being waited on rather than only who finished.
11013async fn wave(
11014    jobs: Vec<SeatJob>,
11015    sem: Arc<Semaphore>,
11016    ctx: &WaveCtx<'_>,
11017    state: &mut RunState,
11018    attempt: usize,
11019) -> Vec<(usize, SeatState, AgentOutcome)> {
11020    let WaveCtx {
11021        run,
11022        node,
11023        prompts,
11024        cache,
11025        round,
11026        carry_seats: _,
11027        pauses,
11028    } = *ctx;
11029    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11030    for job in &jobs {
11031        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11032    }
11033    if let Err(e) = state.save() {
11034        // A failed persist of "who is answering right now" must not abort the
11035        // wave: the seats are already being asked, and the alternative is
11036        // losing the answers to save a status line nobody may even be
11037        // watching.
11038        tracing::warn!("could not persist in-progress seats: {e:#}");
11039    }
11040    // Shared-mode waves keep their existing single lease. Isolated writers
11041    // acquire their own checkout's target at seat admission.
11042    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11043    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11044    // never borrowed from a job's agent budget (and never charged to it either,
11045    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11046    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11047    let cache_guard = if let Some(cache_dir) = cache {
11048        if jobs_had_a_writer {
11049            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11050            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11051            match acquire_cache_lease(
11052                state,
11053                cache_dir,
11054                &owner,
11055                resource_limit,
11056                node,
11057                node,
11058                &cancel,
11059            )
11060            .await
11061            {
11062                Ok(Some(g)) => Some(g),
11063                // Parking: leave without spawning anything. The run parks at
11064                // the next boundary and the seats are asked afresh on resume.
11065                Ok(None) => {
11066                    if let Some(block) = &mut state.resource_block {
11067                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11068                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11069                        };
11070                    }
11071                    return block_wave(
11072                        jobs,
11073                        state,
11074                        node,
11075                        attempt,
11076                        "parked while waiting for the shared build cache",
11077                    );
11078                }
11079                // An unreadable lease is not contention: keep the old
11080                // fallback (no shared cache for this wave's seats).
11081                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11082                Err(e) => {
11083                    // Writing seats may not build into a cache this run does
11084                    // not hold, and an agent that cannot be given one is not
11085                    // asked at all: the run stops resumably instead.
11086                    let why = format!("{e:#}");
11087                    state.event(
11088                        "resource",
11089                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11090                    );
11091                    return block_wave(jobs, state, node, attempt, &why);
11092                }
11093            }
11094        } else {
11095            None
11096        }
11097    } else {
11098        None
11099    };
11100    // Every job keeps its whole budget: the wait above was not the agent's.
11101    // Restart the seats' clocks so "started" means "being spawned now".
11102    state.seats_spawning(node, attempt);
11103    if let Err(e) = state.save() {
11104        tracing::warn!("could not persist the start of a wave: {e:#}");
11105    }
11106    // Queueing behind this wave's own seats for a parallelism slot is normal
11107    // (each of them is bounded by its own agent timeout); only a wait beyond
11108    // all of them plus the resource limit means the slots never came back.
11109    let slot_limit = resource_limit
11110        + jobs
11111            .iter()
11112            .map(|j| j.timeout)
11113            .max()
11114            .unwrap_or_default()
11115            .saturating_mul(jobs.len() as u32);
11116    let mut set = tokio::task::JoinSet::new();
11117    // Seats announce themselves here the moment they hold a parallelism
11118    // permit, i.e. just before their CLI is spawned.
11119    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11120    let overlay = prompts.overlay(node);
11121    let repository_wait = repository_wait(state, pauses);
11122    for (i, mut job) in jobs.into_iter().enumerate() {
11123        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11124        if cache.is_some() {
11125            job.prompt.push('\n');
11126            job.prompt
11127                .push_str(&prompt::build_cache_note(node, job.allow_write));
11128        }
11129        let sem = Arc::clone(&sem);
11130        let run = run.to_owned();
11131        let node = node.to_owned();
11132        // Only implementers were told about the task's attachments, so only
11133        // their seats get the directory widened for reading.
11134        let attachments = if node == "implement" {
11135            state.attachments.clone()
11136        } else {
11137            Vec::new()
11138        };
11139        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11140        // `prompt::build_cache_note`'s doc for why setting it anyway is
11141        // exactly how a sandboxed reviewer's write refusal got reported as a
11142        // defect in the patch, not a property of its own seat. And a
11143        // write-allowed one is handed it only when the lease above was
11144        // actually acquired: a wave that could not get it (`cache_guard` is
11145        // `None`, see its own comment) must not send seats to build into a
11146        // directory this run does not hold - that is the exact concurrent,
11147        // unmanaged-write race this module exists to prevent, not something
11148        // "proceeding anyway" is allowed to reintroduce.
11149        let cache = cache
11150            .filter(|_| job.allow_write && cache_guard.is_some())
11151            .map(Path::to_path_buf);
11152        let spawned_tx = spawned_tx.clone();
11153        let repository_wait = repository_wait.clone();
11154        let coordination = state.config.coordination.clone();
11155        let fetched_base = state.fetched_base.clone();
11156        set.spawn(async move {
11157            // A wait for a parallelism slot is scheduling, not the agent: it
11158            // is bounded by its own limit and ends as a resource block, never
11159            // as a timeout of the agent that was not started.
11160            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11161                Ok(p) => p,
11162                Err(_) => {
11163                    return (
11164                        i,
11165                        job.seat,
11166                        AgentOutcome::ResourceBlocked(format!(
11167                            "no parallel slot became free within {}s",
11168                            slot_limit.as_secs()
11169                        )),
11170                        None,
11171                        false,
11172                    );
11173                }
11174            };
11175            spawned_tx.send(job.seat.key.clone()).ok();
11176            let mut seat = job.seat;
11177            let out = repository_wait
11178                .scope(agent::invoke(
11179                    &job.spec,
11180                    &mut seat,
11181                    &Invocation {
11182                        coordination: coordination.as_ref(),
11183                        fetched_base: fetched_base.as_ref(),
11184                        cwd: &job.cwd,
11185                        prompt: &job.prompt,
11186                        timeout: job.timeout,
11187                        allow_write: job.allow_write,
11188                        sessions: job.sessions,
11189                        artifacts: &job.artifacts,
11190                        stem: &job.stem,
11191                        run: &run,
11192                        node: &node,
11193                        cache_dir: cache.as_deref(),
11194                        attachments: &attachments,
11195                        writable: &[],
11196                    },
11197                ))
11198                .await;
11199            let cache_block = out
11200                .as_ref()
11201                .err()
11202                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11203                .map(|timeout| timeout.0.clone());
11204            let interrupted = out
11205                .as_ref()
11206                .err()
11207                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11208            let out = match out {
11209                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11210                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11211                // Billed work the CLI failed to hand over is not an ordinary
11212                // failure, but its text is the CLI's raw error JSON, not an
11213                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11214                // read it as one by forgetting to check. `usable()` is always
11215                // false here (dropped implies an empty response), so this has
11216                // to be checked before the catch-all `Failed` below or the
11217                // one shape this exists for is lost with the rest.
11218                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11219                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11220                Ok(o) => AgentOutcome::Failed(format!(
11221                    "process exited with no usable output ({})",
11222                    crate::notices::exit_status(o.exit_code)
11223                )),
11224                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11225                    AgentOutcome::ResourceBlocked(e.to_string())
11226                }
11227                Err(e) => AgentOutcome::Failed(e.to_string()),
11228            };
11229            (i, seat, out, cache_block, interrupted)
11230        });
11231    }
11232    drop(spawned_tx);
11233    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11234    loop {
11235        let joined = tokio::select! {
11236            Some(key) = spawned_rx.recv() => {
11237                // The clock of this seat starts now, not when it queued.
11238                state.seat_spawned(&key);
11239                if let Err(e) = state.save() {
11240                    tracing::warn!("could not persist a seat's start: {e:#}");
11241                }
11242                continue;
11243            }
11244            joined = set.join_next() => joined,
11245        };
11246        let Some(joined) = joined else {
11247            break;
11248        };
11249        let (i, seat, out, cache_block, interrupted) = match joined {
11250            Ok(v) => v,
11251            // No seat to clear: a panicked task never reported which one it
11252            // was. The defensive sweep below this loop is what stops that
11253            // seat's `active` entry from surviving forever.
11254            Err(e) => {
11255                tracing::error!("agent task panicked: {e}");
11256                continue;
11257            }
11258        };
11259        state.seat_finished(&seat.key);
11260        if interrupted
11261            && node == "implement"
11262            && let Some(label) = state
11263                .candidates
11264                .iter()
11265                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11266                .map(|candidate| candidate.label)
11267        {
11268            state.candidate_preservation.insert(
11269                label,
11270                "interrupted implementation awaiting persistence".into(),
11271            );
11272            state.interrupted_implementations.insert(label);
11273        }
11274        if let Some(block) = cache_block
11275            && state.resource_block.is_none()
11276        {
11277            state.event("resource", block.description());
11278            state.resource_block = Some(block);
11279        }
11280        if let AgentOutcome::ResourceBlocked(why) = &out
11281            && state.resource_block.is_none()
11282        {
11283            state.resource_block = Some(crate::run::ResourceBlock {
11284                cause: crate::run::ResourceBlockCause::Other,
11285                node: node.to_owned(),
11286                kind: if why.contains("disk pressure") {
11287                    "disk pressure"
11288                } else if why.contains("disk admission") {
11289                    "disk admission"
11290                } else if why.contains(crate::incremental::BLOCKED) {
11291                    "incremental cache admission"
11292                } else if why.contains(crate::build_target::KIND) {
11293                    crate::build_target::KIND
11294                } else if why.contains("repository coordination") {
11295                    "repository coordination"
11296                } else {
11297                    "parallel slot"
11298                }
11299                .to_owned(),
11300                detail: why.clone(),
11301                at: Timestamp::now(),
11302            });
11303            let activity = if interrupted {
11304                "agent execution interrupted"
11305            } else {
11306                "no agent was started"
11307            };
11308            state.event("resource", format!("{node}: {activity} - {why}"));
11309        }
11310        record_jobs(state, node, round, &seat.key, &out);
11311        if let Err(e) = state.save() {
11312            tracing::warn!("could not persist a seat's completion: {e:#}");
11313        }
11314        if collected.len() <= i {
11315            collected.resize_with(i + 1, || None);
11316        }
11317        collected[i] = Some((i, seat, out));
11318    }
11319    // Belt-and-braces for the panic branch above: every seat this exact batch
11320    // started shares this `(node, attempt)` pair, and every seat that finished
11321    // normally already cleared itself, so anything left tagged with it here
11322    // can only be a panicked task's leftover. Cleared unconditionally rather
11323    // than left to read as still answering forever.
11324    if state
11325        .active
11326        .values()
11327        .any(|a| a.node == node && a.attempt == attempt)
11328    {
11329        state
11330            .active
11331            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11332        if let Err(e) = state.save() {
11333            tracing::warn!("could not persist the end of a wave: {e:#}");
11334        }
11335    }
11336    // Whether or not the lease above was actually held, several worktrees
11337    // may just have built into the cache with nothing here able to name one
11338    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11339    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11340    // clean it might not have strictly needed; trusting a stale match would
11341    // cost it a wrong answer.
11342    if let Some(cache_dir) = cache
11343        && jobs_had_a_writer
11344    {
11345        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11346    }
11347    if let Some(guard) = cache_guard {
11348        guard.release();
11349    }
11350    collected.into_iter().flatten().collect()
11351}
11352
11353/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11354/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11355/// this is data collection, not the fix-specific completion contract in
11356/// [`Runner::continue_fix_report`], and applies regardless of which node
11357/// asked.
11358///
11359/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11360/// evidence from; `Failed` does not, and correctly contributes nothing — a
11361/// timeout or crash is not itself evidence about a command the seat may have
11362/// started.
11363fn record_jobs(
11364    state: &mut RunState,
11365    node: &str,
11366    round: Option<usize>,
11367    seat: &str,
11368    out: &AgentOutcome,
11369) {
11370    let commands: &[agent::CommandEvidence] = match out {
11371        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11372        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11373    };
11374    let checked_at = Timestamp::now();
11375    for c in commands {
11376        state.jobs.push(JobRecord {
11377            node: node.to_owned(),
11378            round,
11379            seat: seat.to_owned(),
11380            id: c.id.clone(),
11381            description: c.description.clone(),
11382            checked_at,
11383            status: match c.exit_code {
11384                Some(0) => JobStatus::Completed,
11385                Some(_) => JobStatus::Failed,
11386                None => JobStatus::Unknown,
11387            },
11388            exit_code: c.exit_code,
11389            result_summary: c.result_summary.clone(),
11390            source: c.source.clone(),
11391        });
11392    }
11393}
11394
11395/// Is a review round clean, given how many reviewer seats answered against
11396/// how many the round expected?
11397///
11398/// A seat that never answered (timeout, crash, unparsable output) is not a
11399/// seat that read the patch and found nothing — treating it as such is
11400/// exactly the bug this function exists to close. Under the default `block`
11401/// policy a missing seat can never be clean; `warn` still requires the seats
11402/// that *did* answer to have found nothing blocking and verification to be
11403/// green.
11404///
11405/// `quota_missing` narrows that `block` default for exactly one cause of
11406/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11407/// a session limit lifts by the very next round buys nothing — the seat is
11408/// asked again with the same quota — so once every missing seat is accounted
11409/// for by a quota loss (and at least one seat *did* answer, so a decision has
11410/// something to rest on) the round is decided on the panel that could answer,
11411/// same as `warn` would. A panel that lost every seat to quota is not
11412/// decided here: `answered == 0` falls through to the existing `block`
11413/// fallback so a fully collapsed panel still waits rather than landing on no
11414/// review at all.
11415fn round_is_clean(
11416    blocking: usize,
11417    e2e_ok: bool,
11418    answered: usize,
11419    expected: usize,
11420    quota_missing: usize,
11421    policy: IncompleteReviewPolicy,
11422) -> bool {
11423    if blocking != 0 || !e2e_ok {
11424        return false;
11425    }
11426    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11427        return true;
11428    }
11429    answered > 0 && expected - answered <= quota_missing
11430}
11431
11432/// The review loop's own conclusion, derived entirely from its persisted
11433/// round records and the round budget that produced them — never from
11434/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11435/// recomputes the identical answer regardless of what an earlier node in the
11436/// same walk, or a previous walk, did to `status`.
11437///
11438/// `None` while more rounds remain to try, including when review never ran
11439/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11440/// gone clean, or the budget is spent, or the tree has stopped moving (see
11441/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11442///
11443/// - An incomplete panel that raised nothing is missing input, not a
11444///   verified tree — never a hand-off candidate, whatever verification said
11445///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11446/// - Otherwise, green e2e on the last round hands off (see
11447///   [`Runner::stop_reviewing`]); red e2e blocks.
11448///
11449/// A last round whose own verification is still `ResourceBlocked` — magi
11450/// itself never got a command to run, not evidence the patch is broken —
11451/// is neither: this returns `None` for it too, the same as "more rounds
11452/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11453/// handling of that shape) instead of this cheap recomputation guessing a
11454/// verdict a real attempt never produced.
11455pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11456    if max_rounds == 0
11457        || reviews.last().is_some_and(|r| {
11458            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11459        })
11460    {
11461        return Some(RunStatus::Gating);
11462    }
11463    let last = reviews.last()?;
11464    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11465    if reviews.len() < max_rounds && !stagnant {
11466        return None;
11467    }
11468    if last.incomplete() && last.blocking == 0 {
11469        return Some(RunStatus::Blocked);
11470    }
11471    if last.e2e_status() == E2eStatus::ResourceBlocked
11472        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11473    {
11474        return None;
11475    }
11476    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11477        RunStatus::Gating
11478    } else {
11479        RunStatus::Blocked
11480    })
11481}
11482
11483/// How long a re-ask may take, given the budget the first attempt had.
11484///
11485/// A `nudged` retry is a request to restate an answer the seat has already
11486/// worked out: it carries no new work, so it does not deserve the original
11487/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11488/// 133 seconds while a third sat for over ten minutes on a resumed session
11489/// holding 410 KB of prior output - and because the retry had inherited the
11490/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11491/// judging round whose other seats were long finished.
11492///
11493/// A quarter of the budget, with a floor so that a deliberately short timeout
11494/// does not collapse to nothing. A retry that re-sends the whole prompt
11495/// (because the seat kept no context) is the original job again, and keeps the
11496/// original budget.
11497pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11498    if nudged {
11499        (full / 4).max(Duration::from_secs(120)).min(full)
11500    } else {
11501        full
11502    }
11503}
11504
11505/// Run a wave and parse each reply, re-asking the seats whose reply was
11506/// unusable.
11507///
11508/// The re-ask is a nudge rather than the whole prompt again when the seat still
11509/// holds its conversation, which is the difference between a cheap retry and
11510/// paying for the entire candidate set twice.
11511///
11512/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11513/// successor in `roster` is handed to it instead of being re-asked: the
11514/// handover is the retry. A seat with no successor left (a single-agent
11515/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11516/// the asks to one seat in one node number at most
11517/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11518/// is asked once (a dropped stream is nudged first), and only the last agent
11519/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11520/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11521/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11522/// other failure stops the chain when the previous agent failed the same way
11523/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11524/// [`has_context`] is false and the job's own full prompt and full budget are
11525/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11526/// intermediate ones are not losses) and is returned as a failure like any
11527/// other absent seat — the caller decides whether the panel still has a
11528/// quorum. An empty `roster` disables handover: failures are nudged as they
11529/// always were, and a quota is simply lost. A reply that fails to parse or
11530/// validate is the prompt's doing and is only ever nudged, never handed over.
11531///
11532/// The returned [`SeatState`] names the agent that answered (or tried last).
11533#[allow(clippy::too_many_arguments)]
11534async fn ask_json_wave<T>(
11535    jobs: Vec<SeatJob>,
11536    sem: Arc<Semaphore>,
11537    retries: usize,
11538    roster: &[AgentSpec],
11539    ctx: &WaveCtx<'_>,
11540    losses: &mut Vec<QuotaLoss>,
11541    state: &mut RunState,
11542    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
11543) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11544where
11545    T: serde::de::DeserializeOwned + Send + 'static,
11546{
11547    ask_wave_with(
11548        jobs,
11549        sem,
11550        retries,
11551        roster,
11552        ctx,
11553        losses,
11554        state,
11555        &|text: &str| {
11556            let v = verdict::extract_json::<T>(text)?;
11557            validate(&v)?;
11558            Ok(v)
11559        },
11560    )
11561    .await
11562}
11563
11564/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
11565/// a node whose answer is prose (deliberation) shares the same handover,
11566/// failure classification, quota bookkeeping and bounds instead of a copy.
11567///
11568/// A seat handed to another roster agent is sent the job's `handover` prompt
11569/// (when it has one) rather than `prompt`: the new agent has no session, so a
11570/// resume-style prompt would be incomplete. That holds for the handover ask
11571/// and for every nudge to that agent whose `has_context` is false.
11572#[allow(clippy::too_many_arguments)]
11573async fn ask_wave_with<T>(
11574    jobs: Vec<SeatJob>,
11575    sem: Arc<Semaphore>,
11576    retries: usize,
11577    roster: &[AgentSpec],
11578    ctx: &WaveCtx<'_>,
11579    losses: &mut Vec<QuotaLoss>,
11580    state: &mut RunState,
11581    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
11582) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11583where
11584    T: Send + 'static,
11585{
11586    let n = jobs.len();
11587    let originals: Vec<SeatJob> = jobs;
11588    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
11589    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
11590    // Nudges each seat's *current* agent has taken — 0 for a first-ask
11591    // answer, N once it has gone through N nudges. Read back once this
11592    // returns, so a caller building a history record (`ReviewRecord`) can
11593    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
11594    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
11595    // field's own doc.
11596    let mut nudges: Vec<usize> = vec![0; n];
11597    // The agent now occupying each seat, the ids it has already been through,
11598    // where in the roster the walk began, the class of the last failure, and
11599    // the stem word of a handover not yet asked (full prompt, full budget).
11600    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
11601    let mut tried: Vec<BTreeSet<String>> = specs
11602        .iter()
11603        .map(|s| BTreeSet::from([s.id.clone()]))
11604        .collect();
11605    let starts: Vec<usize> = specs
11606        .iter()
11607        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
11608        .collect();
11609    let carry = ctx.carry_seats && !roster.is_empty();
11610    // Carried across rounds: ids that failed the seat earlier, and how the
11611    // last failure went (so a repeat of it is not handed over again).
11612    let carried: Vec<BTreeSet<String>> = originals
11613        .iter()
11614        .map(|j| {
11615            state
11616                .seat_history
11617                .get(&j.seat.key)
11618                .filter(|_| carry)
11619                .map(|h| h.failed.clone())
11620                .unwrap_or_default()
11621        })
11622        .collect();
11623    let mut prev: Vec<Option<FailClass>> = originals
11624        .iter()
11625        .map(|j| {
11626            state
11627                .seat_history
11628                .get(&j.seat.key)
11629                .filter(|_| carry)
11630                .and_then(|h| h.last_fail.clone())
11631        })
11632        .collect();
11633    let next_agent =
11634        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
11635            let others: BTreeSet<String> = specs
11636                .iter()
11637                .enumerate()
11638                .filter(|(j, _)| *j != i)
11639                .map(|(_, s)| s.id.clone())
11640                .collect();
11641            pick_successor(
11642                roster,
11643                starts[i],
11644                tried,
11645                carry.then(|| &carried[i]),
11646                &others,
11647            )
11648            .cloned()
11649        };
11650    let mut fresh: Vec<Option<String>> = vec![None; n];
11651    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
11652    let mut pending: Vec<usize> = (0..n).collect();
11653
11654    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
11655    // asks: an agent with a successor is asked once and handed over, and only
11656    // a seat with no successor spends `retries` nudges on the same agent. This
11657    // only guarantees the loop's own termination whatever those say.
11658    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
11659    for round in 0..max_rounds {
11660        if pending.is_empty() {
11661            break;
11662        }
11663        let mut batch = Vec::with_capacity(pending.len());
11664        let mut renudged: Vec<&str> = Vec::new();
11665        for &i in &pending {
11666            let src = &originals[i];
11667            // A seat now held by another agent than the job named has no
11668            // session of its own: it gets the full-context prompt whenever
11669            // it is asked in full (the handover ask, a nudge it cannot
11670            // resume).
11671            let full: &str = match &src.handover {
11672                Some(h) if specs[i].id != src.spec.id => h,
11673                _ => &src.prompt,
11674            };
11675            // The prompt and the budget are one decision: a nudge restates
11676            // finished work, a re-sent prompt redoes it.
11677            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
11678                (
11679                    full.to_owned(),
11680                    src.timeout,
11681                    format!("{}-{word}-{}", src.stem, specs[i].id),
11682                )
11683            } else if nudges[i] == 0 {
11684                (full.to_owned(), src.timeout, src.stem.clone())
11685            } else {
11686                renudged.push(src.seat.key.as_str());
11687                let why = done[i]
11688                    .as_ref()
11689                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
11690                    .unwrap_or_else(|| "no parsable answer".to_owned());
11691                let nudge = prompt::nudge(&why);
11692                let nudged = has_context(&specs[i], &seats[i], src.sessions);
11693                let prompt = if nudged {
11694                    nudge
11695                } else {
11696                    format!("{full}\n\n---\n\n{nudge}")
11697                };
11698                (
11699                    prompt,
11700                    retry_budget(src.timeout, nudged),
11701                    format!("{}-retry{}", src.stem, nudges[i]),
11702                )
11703            };
11704            batch.push(SeatJob {
11705                spec: specs[i].clone(),
11706                seat: seats[i].clone(),
11707                cwd: src.cwd.clone(),
11708                prompt,
11709                timeout,
11710                allow_write: src.allow_write,
11711                sessions: src.sessions,
11712                artifacts: src.artifacts.clone(),
11713                stem,
11714                handover: None,
11715            });
11716        }
11717
11718        if !renudged.is_empty() {
11719            state.event(
11720                ctx.node,
11721                format!("retry {round}: re-asking {}", renudged.join(", ")),
11722            );
11723        }
11724        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
11725        let mut still = Vec::new();
11726        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
11727            seats[i] = seat;
11728            // No agent was asked: nothing to hand over, nudge, remember or
11729            // charge. The caller sees `resource_block` and stops the node.
11730            if let AgentOutcome::ResourceBlocked(why) = &out {
11731                done[i] = Some(Err(anyhow::anyhow!("{why}")));
11732                continue;
11733            }
11734            let class = FailClass::of(&out);
11735            // A dropped stream is nudged first (the conversation is still
11736            // there to pick up); only a seat whose nudges are spent hands over.
11737            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
11738                && nudges[i] < retries
11739                && !roster.is_empty();
11740            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
11741                let next = should_hand_over(prev[i].as_ref(), &cur)
11742                    .then(|| next_agent(i, &tried[i], &specs))
11743                    .flatten();
11744                if carry {
11745                    let h = state
11746                        .seat_history
11747                        .entry(originals[i].seat.key.clone())
11748                        .or_default();
11749                    h.failed.insert(specs[i].id.clone());
11750                    h.last_fail = Some(cur.clone());
11751                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
11752                        h.last_ok = None;
11753                    }
11754                    // Saved before the next agent is asked, so a restart in
11755                    // between does not forget who failed.
11756                    if let Err(e) = state.save() {
11757                        tracing::warn!("could not persist a seat's failure history: {e:#}");
11758                    }
11759                }
11760                if let Some(next) = next {
11761                    record_handover(
11762                        state,
11763                        ctx.node,
11764                        &originals[i].seat.key,
11765                        &specs[i].id,
11766                        &next.id,
11767                        &cur,
11768                        &fail_reason(&out),
11769                    );
11770                    tried[i].insert(next.id.clone());
11771                    prev[i] = Some(cur.clone());
11772                    seats[i] =
11773                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
11774                    specs[i] = next;
11775                    fresh[i] = Some(cur.stem_word().to_owned());
11776                    nudges[i] = 0;
11777                    done[i] = Some(Err(anyhow::anyhow!(
11778                        "handed over after: {}",
11779                        fail_reason(&out)
11780                    )));
11781                    still.push(i);
11782                    continue;
11783                }
11784            }
11785            if carry
11786                && !nudge_first
11787                && let Some(cur) = class.clone()
11788            {
11789                // The chain ended here (no successor, or a repeated failure).
11790                let h = state
11791                    .seat_history
11792                    .entry(originals[i].seat.key.clone())
11793                    .or_default();
11794                h.failed.insert(specs[i].id.clone());
11795                h.last_fail = Some(cur);
11796            }
11797            let parsed = match out {
11798                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
11799                AgentOutcome::Quota(o) => {
11800                    last_quota[i] = o.quota.clone();
11801                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
11802                }
11803                // Not a parseable answer: the nudge loop re-asks it, which is
11804                // exactly what a dropped stream needs. Just don't hand its raw
11805                // error JSON to `extract_json`.
11806                AgentOutcome::Dropped(o) => {
11807                    let why = o
11808                        .dropped
11809                        .as_ref()
11810                        .map(|d| d.why.as_str())
11811                        .unwrap_or("the CLI ended the stream without delivering its answer");
11812                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
11813                }
11814                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11815                    Err(anyhow::anyhow!(e))
11816                }
11817            };
11818            let quota = class == Some(FailClass::Quota);
11819            let failed = parsed.is_err();
11820            if !failed && matches!(ctx.node, "judge" | "vote") {
11821                // A validated answer restores this seat's quorum presence,
11822                // including on the normal path after an all-seat block.
11823                state
11824                    .quota
11825                    .retain(|loss| loss.seat != originals[i].seat.key);
11826            }
11827            done[i] = Some(parsed);
11828            if carry && !failed {
11829                let h = state
11830                    .seat_history
11831                    .entry(originals[i].seat.key.clone())
11832                    .or_default();
11833                h.failed.remove(&specs[i].id);
11834                h.last_ok = Some(specs[i].id.clone());
11835                h.last_fail = None;
11836            }
11837            // Do not re-ask a rate-limited seat (quota) — a retry is known to
11838            // fail the same way; and never re-ask a seat that already parsed.
11839            // A failed agent that still has a successor is not re-asked
11840            // either: the handover was its remedy and has just been refused
11841            // (the chain stops on a repeated failure class). A seat with no
11842            // successor left (a single-agent roster, the roster's tail, or an
11843            // empty roster) keeps the same-agent nudge, bounded by `retries`.
11844            let agent_failure = class.is_some()
11845                && !nudge_first
11846                && !roster.is_empty()
11847                && next_agent(i, &tried[i], &specs).is_some();
11848            if failed && !quota && !agent_failure && nudges[i] < retries {
11849                nudges[i] += 1;
11850                still.push(i);
11851            }
11852        }
11853        pending = still;
11854    }
11855
11856    // One loss per seat whose chain ended on a quota: the intermediate ones
11857    // were absorbed by a handover and are not losses.
11858    for (i, q) in last_quota.into_iter().enumerate() {
11859        if let Some(quota) = q {
11860            losses.push(QuotaLoss::from_report(
11861                originals[i].seat.key.clone(),
11862                ctx.node,
11863                Some(&quota),
11864            ));
11865        }
11866    }
11867
11868    // A stalled quorum already has its own recovery checkpoint. Refresh
11869    // its missing seats before deciding whether it can resume.
11870    if state.status != RunStatus::Stalled
11871        && ctx.node != "deliberate"
11872        && n > 0
11873        && losses.len() == n
11874        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
11875    {
11876        block_machine_outage(state, ctx.node, losses);
11877        state.quota.append(losses);
11878    }
11879
11880    seats
11881        .into_iter()
11882        .zip(done)
11883        .zip(nudges)
11884        .map(|((seat, res), attempts)| {
11885            (
11886                seat,
11887                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
11888                attempts,
11889            )
11890        })
11891        .collect()
11892}
11893
11894/// A node with no available agent has no task verdict. Preserve the node
11895/// checkpoint and record why a subsequent explicit resume is needed.
11896pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
11897    let mut auth: Vec<_> = losses
11898        .iter()
11899        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
11900        .map(|loss| loss.agent.clone())
11901        .collect();
11902    auth.sort();
11903    auth.dedup();
11904    let (kind, detail) = if auth.is_empty() {
11905        (
11906            "agent usage limit",
11907            "All seats reached their agent usage limits; resume after usage is available"
11908                .to_owned(),
11909        )
11910    } else {
11911        (
11912            "agent authentication",
11913            format!(
11914                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
11915                auth.join(", ")
11916            ),
11917        )
11918    };
11919    state.resource_block = Some(crate::run::ResourceBlock {
11920        node: node.to_owned(),
11921        kind: kind.to_owned(),
11922        cause: crate::run::ResourceBlockCause::Other,
11923        detail: detail.clone(),
11924        at: Timestamp::now(),
11925    });
11926    state.event(node, detail);
11927}
11928
11929/// Did the wave end without asking any agent (see [`block_wave`])?
11930fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
11931    results
11932        .iter()
11933        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
11934}
11935
11936/// Settle a wave that never spawned anything: every job answers
11937/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
11938/// else about the seat (session, history, quota) is touched.
11939fn block_wave(
11940    jobs: Vec<SeatJob>,
11941    state: &mut RunState,
11942    node: &str,
11943    attempt: usize,
11944    why: &str,
11945) -> Vec<(usize, SeatState, AgentOutcome)> {
11946    state.resource_wait = None;
11947    state
11948        .active
11949        .retain(|_, a| !(a.node == node && a.attempt == attempt));
11950    if let Err(e) = state.save() {
11951        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
11952    }
11953    jobs.into_iter()
11954        .enumerate()
11955        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
11956        .collect()
11957}
11958
11959/// Acquire the shared build cache's lease, waiting out contention within
11960/// `budget` (never past it — see AGENTS.md's build-cache section on why an
11961/// unbounded wait is never acceptable).
11962///
11963/// A first, non-blocking check happens before ever waiting; if it finds the
11964/// lease busy, that fact is logged as a `verify` event *and* flushed with
11965/// [`RunState::save`] immediately — not only once the wait finally succeeds
11966/// or gives up — so a `magi show` run by a different process while this one
11967/// is still waiting reads a `run.json` that says so, rather than whatever it
11968/// looked like before the wait started. The same applies to the terminal
11969/// failure: logged and saved before this returns `Err`, so a caller that
11970/// could not get the lease at all still leaves a legible record of why.
11971async fn acquire_cache_lease(
11972    state: &mut RunState,
11973    cache_dir: &Path,
11974    owner: &crate::cache::Owner,
11975    budget: Duration,
11976    node: &str,
11977    context: &str,
11978    cancel: &(dyn Fn() -> bool + Sync),
11979) -> Result<Option<crate::cache::Guard>> {
11980    let home = crate::run::home();
11981    let kind = if crate::build_target::isolated(&state.config) {
11982        crate::build_target::KIND
11983    } else {
11984        "shared build cache"
11985    };
11986    let started = Instant::now();
11987    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
11988        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
11989        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
11990        Err(e) => {
11991            state.event(
11992                "verify",
11993                format!(
11994                    "{context}: could not check the {kind} at {}: {e:#}",
11995                    cache_dir.display()
11996                ),
11997            );
11998            if let Err(e2) = state.save() {
11999                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12000            }
12001            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12002        }
12003    };
12004    state.event(
12005        "verify",
12006        format!(
12007            "{context}: waiting for the {kind} at {} ({})",
12008            cache_dir.display(),
12009            busy.describe()
12010        ),
12011    );
12012    // Seats of this node are waiting, not running: say so, so the countdown a
12013    // reader sees only ever measures an agent that has been spawned.
12014    state.resource_wait = Some(crate::run::ResourceWait {
12015        node: context.to_owned(),
12016        kind: kind.to_owned(),
12017        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12018        since: Timestamp::now(),
12019        limit_secs: budget.as_secs(),
12020    });
12021    if let Err(e) = state.save() {
12022        tracing::warn!("could not persist a cache wait: {e:#}");
12023    }
12024    let remaining = budget.saturating_sub(started.elapsed());
12025    let waited = crate::cache::wait_for_unless(
12026        &home,
12027        cache_dir,
12028        owner,
12029        remaining,
12030        Duration::from_secs(5),
12031        cancel,
12032    )
12033    .await;
12034    state.resource_wait = None;
12035    let cause = match &waited {
12036        Ok(Some(_)) => None,
12037        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12038        Err(error)
12039            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12040        {
12041            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12042                target: cache_dir.to_owned(),
12043                waited_secs: started.elapsed().as_secs(),
12044                limit_secs: budget.as_secs(),
12045            })
12046        }
12047        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12048            Some(crate::run::ResourceBlockCause::Timeout {
12049                waited_secs: started.elapsed().as_secs(),
12050                limit_secs: budget.as_secs(),
12051            })
12052        }
12053        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12054    };
12055    if let Some(cause) = cause {
12056        let detail = match &waited {
12057            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12058            Err(error) => format!("{error:#}"),
12059        };
12060        state.resource_block = Some(crate::run::ResourceBlock {
12061            cause,
12062            node: node.to_owned(),
12063            kind: kind.into(),
12064            detail: format!("{}: {detail}", cache_dir.display()),
12065            at: Timestamp::now(),
12066        });
12067        state.event(
12068            "resource",
12069            state.resource_block.as_ref().unwrap().description(),
12070        );
12071    }
12072    if let Err(error) = state.save() {
12073        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12074    }
12075    waited
12076}
12077
12078/// The lease state could not be read at all (unreadable lease file, a
12079/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12080/// known to be contended, so a wave degrades to running without a shared cache
12081/// instead of stopping on a hold that [`crate::triage`] could never release.
12082#[derive(Debug)]
12083struct CacheCheckError(String);
12084
12085impl std::fmt::Display for CacheCheckError {
12086    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12087        f.write_str(&self.0)
12088    }
12089}
12090
12091impl std::error::Error for CacheCheckError {}
12092
12093/// Keep a specific acquisition outcome when the caller adds command evidence.
12094fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12095    let kind = if crate::build_target::isolated(&state.config) {
12096        crate::build_target::KIND
12097    } else {
12098        "shared build cache"
12099    };
12100    state
12101        .resource_block
12102        .get_or_insert_with(|| crate::run::ResourceBlock {
12103            cause: crate::run::ResourceBlockCause::Other,
12104            node: node.to_owned(),
12105            kind: kind.into(),
12106            detail: format!("{error:#}"),
12107            at: Timestamp::now(),
12108        });
12109    if let Err(error) = state.save() {
12110        tracing::warn!("could not persist cache resource block: {error:#}");
12111    }
12112}
12113
12114tokio::task_local! {
12115    static VERIFY_TARGET: PathBuf;
12116}
12117
12118/// Run `body` — a verify command batch — while holding the shared build
12119/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12120/// never interleave with another borrower's build against the same
12121/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12122/// timeout, or a human's own `magi review`. See the `cache` module doc for
12123/// why this matters more than Cargo's own per-target locking covers — two
12124/// *different* worktrees building the same package name/version into one
12125/// cache directory is a staleness bug, not a lock contention one.
12126///
12127/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12128/// agent waves do. Repository scheduling also has its own bounded,
12129/// cancellable resource-wait policy. Contention must not consume the
12130/// verification budget: `body` receives the full `budget` after both leases
12131/// are acquired and the cache is fresh. Without a shared cache, only
12132/// repository coordination is acquired before handing over the full budget.
12133///
12134/// A lease that cannot be acquired within the resource wait is reported as a single
12135/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12136/// verification — the same shape a spawn failure already takes in
12137/// [`run_commands`], so a caller need not special-case it.
12138#[allow(clippy::too_many_arguments)]
12139async fn with_cache_lease<'s, F, Fut>(
12140    state: &'s mut RunState,
12141    cache_dir: Option<&Path>,
12142    node: &str,
12143    seat: &str,
12144    worktree: &Path,
12145    head: &str,
12146    budget: Duration,
12147    context: &str,
12148    wait: &crate::repo_lock::WaitPolicy,
12149    body: F,
12150) -> Result<(Vec<CommandOutcome>, bool)>
12151where
12152    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12153    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12154{
12155    // Match editing waves: cache first, repository second. In particular,
12156    // pre_gate must never hold the repository while waiting for a wave's cache.
12157    let started = Instant::now();
12158    let home = crate::run::home();
12159    let isolated = crate::build_target::isolated(&state.config);
12160    let planned_target = if isolated {
12161        let plan = (|| -> Result<PathBuf> {
12162            crate::build_target::supports(&state.config)?;
12163            crate::build_target::resolve(&home, worktree)
12164        })();
12165        match plan {
12166            Ok(path) => Some(path),
12167            Err(error) => {
12168                record_cache_error(state, node, &error);
12169                return Ok((
12170                    vec![CommandOutcome {
12171                        command: "(planning isolated build cache)".into(),
12172                        code: None,
12173                        output_tail: format!("{error:#}"),
12174                        duration_ms: 0,
12175                        resource_blocked: true,
12176                        ..Default::default()
12177                    }],
12178                    false,
12179                ));
12180            }
12181        }
12182    } else {
12183        None
12184    };
12185    let cache_dir = planned_target.as_deref().or(cache_dir);
12186    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12187    let guard = if let Some(cache_dir) = cache_dir {
12188        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12189        match acquire_cache_lease(
12190            state,
12191            cache_dir,
12192            &owner,
12193            resource_limit,
12194            node,
12195            context,
12196            &|| wait.cancelled(),
12197        )
12198        .await
12199        .and_then(|g| {
12200            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12201        }) {
12202            Ok(g) => Some(g),
12203            Err(e) => {
12204                record_cache_error(state, node, &e);
12205                return Ok((
12206                    vec![CommandOutcome {
12207                        command: if isolated {
12208                            "(waiting for the isolated build cache)"
12209                        } else {
12210                            "(waiting for the shared build cache)"
12211                        }
12212                        .into(),
12213                        code: None,
12214                        output_tail: e.to_string(),
12215                        duration_ms: started.elapsed().as_millis() as u64,
12216                        resource_blocked: true,
12217                        ..Default::default()
12218                    }],
12219                    false,
12220                ));
12221            }
12222        }
12223    } else {
12224        None
12225    };
12226    let _coordination = coordinate_operation(state, worktree, wait).await?;
12227    if let Some(path) = &planned_target {
12228        state.event(node, format!("isolated build target: {}", path.display()));
12229    }
12230    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12231        let identity = crate::cache::Identity::new(worktree, head);
12232        let fresh = crate::cache::ensure_fresh(
12233            &home,
12234            cache_dir,
12235            &identity,
12236            &state.config.verify.cargo_manifests(),
12237        );
12238        if let Err(e) = fresh {
12239            record_cache_error(state, node, &e);
12240            state.event(
12241                "verify",
12242                format!(
12243                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12244                    worktree.display(),
12245                    short(head)
12246                ),
12247            );
12248            if let Some(guard) = guard {
12249                guard.release();
12250            }
12251            return Ok((
12252                vec![CommandOutcome {
12253                    command: "(confirming the build cache is fresh)".into(),
12254                    code: None,
12255                    output_tail: e.to_string(),
12256                    duration_ms: started.elapsed().as_millis() as u64,
12257                    resource_blocked: true,
12258                    ..Default::default()
12259                }],
12260                false,
12261            ));
12262        }
12263    }
12264    let future = body(state, budget);
12265    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12266        VERIFY_TARGET.scope(target, future).await
12267    } else {
12268        future.await
12269    };
12270    if !timed_out_pids.is_empty() {
12271        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12272    }
12273    // Drop repository coordination before releasing the cache, reversing the
12274    // acquisition order. A cancelled/error future also drops both guards.
12275    drop(_coordination);
12276    if let Some(guard) = guard {
12277        guard.release();
12278    }
12279    Ok((outcomes, retried))
12280}
12281
12282/// Poll `pids` — commands [`run_commands`] reports as still running when its
12283/// own timeout elapsed — until every one is confirmed gone, or
12284/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12285///
12286/// Real confirmation where confirmation is possible, not a substitute for
12287/// full process-tree observation: a grandchild the timed-out process spawned
12288/// and that survives independently of it is invisible to a pid check the
12289/// same way it always was, and continuing to observe and collect *that*
12290/// stays a different piece of work with its own owner. This only narrows a
12291/// fixed blind wait into an actual check of the pids this process does know
12292/// about.
12293async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12294    wait_for_pids_with(
12295        pids,
12296        crate::proc::pid_alive,
12297        LEASE_RELEASE_POLL,
12298        LEASE_RELEASE_MAX_WAIT,
12299    )
12300    .await;
12301}
12302
12303/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12304/// interval and ceiling supplied by the caller, so the polling *logic* -
12305/// returns as soon as every pid reports dead, gives up at the ceiling
12306/// otherwise - is testable on millisecond durations without asking the real
12307/// OS about a pid at all.
12308async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12309    pids: &[u32],
12310    alive: F,
12311    poll: Duration,
12312    max_wait: Duration,
12313) {
12314    let deadline = Instant::now() + max_wait;
12315    loop {
12316        if pids.iter().all(|&pid| !alive(pid)) {
12317            return;
12318        }
12319        if Instant::now() >= deadline {
12320            return;
12321        }
12322        tokio::time::sleep(poll).await;
12323    }
12324}
12325
12326/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12327/// admission that it could not even get a verify command to run, as opposed
12328/// to evidence the command actually produced? A caller that would otherwise
12329/// read a resource-blocked outcome as a red command must check this first:
12330/// see [`Runner::gate`], which retries rather than records `Blocked` when
12331/// this is true.
12332fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12333    outcomes.iter().any(|o| o.resource_blocked)
12334}
12335
12336/// What [`Runner::gate_fix_round`] decided.
12337pub(crate) enum GateFix {
12338    /// The tree changed and `verify.e2e` is still green: run the gate again.
12339    Retry,
12340    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12341    /// last failure stands and the run ends blocked.
12342    Stop,
12343    /// `verify.e2e` could not run after the fix (magi's own contention):
12344    /// decide nothing now, a later reentry retries.
12345    Defer,
12346}
12347
12348/// Is every red command in `outcomes` an ordinary failure the code could
12349/// explain: it ran, exited non-zero, and said something?
12350///
12351/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12352/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12353/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12354/// what the command is stays the gate's business.
12355pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12356    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12357    red.peek().is_some()
12358        && red.all(|o| {
12359            !o.resource_blocked
12360                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12361                && !o.output_tail.trim().is_empty()
12362        })
12363}
12364
12365/// Describe one verify command's outcome for the event log, distinguishing a
12366/// build/link failure — the toolchain never produced a binary to run — from
12367/// an actual test failure, since only the latter is a verdict on the patch.
12368fn e2e_outcome_label(o: &CommandOutcome) -> String {
12369    if o.ok() {
12370        return "pass".to_owned();
12371    }
12372    let reason = if o.build_failed() {
12373        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12374    } else {
12375        format!("FAIL ({:?})", o.code)
12376    };
12377    format!(
12378        "{reason}\n{}",
12379        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12380    )
12381}
12382
12383/// Does `outcomes` hold a failure worth one more run on the same commit?
12384///
12385/// Only an ordinary test result qualifies: every red command ran, exited
12386/// non-zero and said which way (not a build/link failure, a timeout or kill,
12387/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12388/// evidence about the machine or the toolchain, never about a flaky test.
12389fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12390    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12391    red.peek().is_some()
12392        && !verify_inconclusive(outcomes)
12393        && red.all(|o| {
12394            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12395        })
12396}
12397
12398/// Run `verify.e2e`, retrying once if the first attempt could not build or
12399/// link — a build/link failure is frequently a race against a shared
12400/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12401/// `verify` event per command, tagged with `context` (normally `"round N"`)
12402/// so the call sites that need this — the ordinary per-round leg in
12403/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12404/// will ever call a round green, `verify_current_head` and the gate-repair
12405/// check — read identically in the event log.
12406///
12407/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12408/// only after the failed commands have run once more on the same commit, in
12409/// the same worktree and — because the caller holds it around this whole
12410/// function — under the same cache lease, with a full `timeout` of their own
12411/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12412/// flake: the head is verified, the first failure is recorded and filed
12413/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12414/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
12415/// preserving bounded evidence and artifact references for both attempts;
12416/// it claims a matching reproduction only when both attempts yield identical
12417/// confirmed terminal test failures. One verification is therefore run at most
12418/// three times: the build/link retry, then this one rerun. `round` is the
12419/// review round the verification belongs to, if any.
12420async fn run_e2e_with_retry(
12421    state: &mut RunState,
12422    shell: &[String],
12423    commands: &[String],
12424    worktree: &Path,
12425    timeout: Duration,
12426    context: &str,
12427    round: Option<usize>,
12428) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12429    let (mut e2e, mut timed_out_pids) = run_commands(
12430        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12431    )
12432    .await;
12433    for o in &e2e {
12434        state.event(
12435            "verify",
12436            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12437        );
12438    }
12439    // A build/link failure is not a verdict on the patch — it is frequently a
12440    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12441    // one retry before letting a red like that decide the round.
12442    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12443    if verify_retried {
12444        state.event(
12445            "verify",
12446            format!(
12447                "{context}: verify could not build/link, not a test result — retrying once \
12448                 before concluding"
12449            ),
12450        );
12451        let retried = run_commands(
12452            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12453        )
12454        .await;
12455        e2e = retried.0;
12456        // Both attempts' timeouts matter, not just the last one: the first
12457        // attempt's descendants may still be alive alongside the retry's.
12458        timed_out_pids.extend(retried.1);
12459        for o in &e2e {
12460            state.event(
12461                "verify",
12462                format!(
12463                    "{context}: retry `{}` -> {}",
12464                    o.command,
12465                    e2e_outcome_label(o)
12466                ),
12467            );
12468        }
12469    }
12470    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12471        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12472        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12473        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12474        state.event(
12475            "verify",
12476            format!(
12477                "{context}: {} failed with a test result — running it once more on the same \
12478                 commit {} before deciding",
12479                rerun_commands
12480                    .iter()
12481                    .map(|c| format!("`{c}`"))
12482                    .collect::<Vec<_>>()
12483                    .join(", "),
12484                short(&head)
12485            ),
12486        );
12487        let (second, pids) = run_commands(
12488            state,
12489            "verify",
12490            "e2e",
12491            1 + usize::from(verify_retried),
12492            shell,
12493            &rerun_commands,
12494            worktree,
12495            timeout,
12496        )
12497        .await;
12498        timed_out_pids.extend(pids);
12499        for o in &second {
12500            state.event(
12501                "verify",
12502                format!(
12503                    "{context}: rerun `{}` -> {}",
12504                    o.command,
12505                    e2e_outcome_label(o)
12506                ),
12507            );
12508        }
12509        for (slot, &i) in failed.iter().enumerate() {
12510            let Some(again) = second.get(slot) else {
12511                break;
12512            };
12513            let first = std::mem::replace(&mut e2e[i], again.clone());
12514            if again.ok() {
12515                let signature = crate::flake::signature(&first.output_tail, first.code);
12516                let flake = crate::run::VerifyFlake {
12517                    round,
12518                    context: context.to_owned(),
12519                    head: head.clone(),
12520                    command: first.command.clone(),
12521                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12522                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12523                    at: Timestamp::now(),
12524                    task: None,
12525                    filed: false,
12526                    filing_error: None,
12527                };
12528                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12529            } else if !again.resource_blocked {
12530                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
12531                let message = crate::verify_evidence::rerun_event_message(
12532                    context,
12533                    &e2e[i].command,
12534                    &comparison,
12535                );
12536                e2e[i].rerun_comparison = Some(comparison);
12537                state.event("verify", message);
12538            }
12539        }
12540    }
12541    (e2e, verify_retried, timed_out_pids)
12542}
12543
12544/// Run configured shell commands in `cwd`, in order. The second element is
12545/// the pid of every command that hit `timeout` and was still running when
12546/// this stopped waiting on it (best-effort: `None` when the platform did not
12547/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
12548/// that releases a shared resource afterward needs to know.
12549///
12550/// Records `task` into [`RunState::active`] at every command boundary
12551/// (`RunState::task_command`) and clears it once the whole list has run
12552/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
12553/// for minutes with no seat and no output of its own to show for it (see
12554/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
12555/// apart from "not yet run" without this), and this is the only place that
12556/// knows which command is running right now and how many are left. Three
12557/// saves per command — start, not per second — matching the same "only at a
12558/// boundary" rule [`wave`] already follows for seats.
12559#[allow(clippy::too_many_arguments)]
12560async fn run_commands(
12561    state: &mut RunState,
12562    node: &str,
12563    task: &str,
12564    attempt: usize,
12565    shell: &[String],
12566    commands: &[String],
12567    cwd: &Path,
12568    timeout: Duration,
12569) -> (Vec<CommandOutcome>, Vec<u32>) {
12570    let isolated = crate::build_target::isolated(&state.config);
12571    if isolated && let Some(block) = &state.resource_block {
12572        return (
12573            vec![CommandOutcome {
12574                command: "(isolated build admission)".into(),
12575                code: None,
12576                output_tail: block.description(),
12577                duration_ms: 0,
12578                resource_blocked: true,
12579                ..Default::default()
12580            }],
12581            Vec::new(),
12582        );
12583    }
12584    if commands.is_empty() {
12585        // Nothing to mark as running and nothing to clear — an empty list
12586        // means "not configured", and touching `active` (or the disk) over
12587        // that would be a write for every round of a repo with no
12588        // `verify.e2e` / `verify.gate` commands at all.
12589        return (Vec::new(), Vec::new());
12590    }
12591    let mut out = Vec::new();
12592    let mut timed_out_pids = Vec::new();
12593    let total = commands.len();
12594    for (idx, command) in commands.iter().enumerate() {
12595        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
12596        if let Err(e) = state.save() {
12597            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
12598        }
12599        let started = Instant::now();
12600        let mut cmd = tokio::process::Command::new(&shell[0]);
12601        cmd.quiet();
12602        // Verify the checkout as a standalone caller. Worker ownership and
12603        // pinned executable selection belong to this driver, not to tests or
12604        // tools it runs. Preserve home/seat context and Running's containment.
12605        for key in crate::worker::INVOCATION_ENV {
12606            cmd.env_remove(key);
12607        }
12608        cmd.env_remove(crate::build_id::EXPECT_ENV);
12609        cmd.args(&shell[1..])
12610            .current_dir(cwd)
12611            .stdin(std::process::Stdio::null())
12612            .stdout(std::process::Stdio::piped())
12613            .stderr(std::process::Stdio::piped())
12614            .kill_on_drop(true);
12615        let mut outputs = Vec::new();
12616        let mut cache = None;
12617        let home = crate::run::home();
12618        let head = if isolated {
12619            Some(git::rev_parse(cwd, "HEAD").await)
12620        } else {
12621            None
12622        };
12623        let protected = (|| -> Result<()> {
12624            crate::incremental::configure(&mut cmd, cwd)?;
12625            cache = if isolated {
12626                let target = VERIFY_TARGET
12627                    .try_with(Clone::clone)
12628                    .context("isolated verification has no target lease")?;
12629                cmd.arg(crate::build_target::command::normalize(command)?);
12630                crate::build_target::command::configure(&mut cmd, &target)?;
12631                Some(target)
12632            } else {
12633                crate::build_target::command::clear(&mut cmd)?;
12634                cmd.arg(command);
12635                state.config.cache_dir()
12636            };
12637            let mut paths = vec![cwd.to_owned()];
12638            if let Some(cache) = &cache {
12639                paths.push(cache.clone());
12640            }
12641            let admit = if isolated {
12642                crate::retention::OutputLease::admit_isolated
12643            } else {
12644                crate::retention::OutputLease::admit
12645            };
12646            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
12647            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
12648                outputs.push(guard);
12649            }
12650            if let Some(cache) = &cache {
12651                outputs.push(crate::retention::OutputLease::cache(
12652                    &crate::run::home(),
12653                    cache,
12654                    false,
12655                )?);
12656                if let Some(head) = head {
12657                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
12658                    if task == "pre_gate" {
12659                        crate::cache::invalidate_identity(&home, cache);
12660                    }
12661                }
12662            }
12663            Ok(())
12664        })();
12665        if let Err(e) = protected {
12666            let detail = format!("execution admission unavailable: {e:#}");
12667            state.resource_block = Some(crate::run::ResourceBlock {
12668                cause: crate::run::ResourceBlockCause::Other,
12669                node: node.to_owned(),
12670                kind: if detail.contains("disk admission") {
12671                    "disk admission"
12672                } else {
12673                    "output ownership"
12674                }
12675                .to_owned(),
12676                detail: detail.clone(),
12677                at: Timestamp::now(),
12678            });
12679            out.push(CommandOutcome {
12680                command: command.clone(),
12681                code: None,
12682                output_tail: detail,
12683                duration_ms: 0,
12684                resource_blocked: true,
12685                ..Default::default()
12686            });
12687            break;
12688        }
12689        let spawned = if isolated {
12690            crate::seat_process::Running::spawn_build(cmd, None, outputs)
12691        } else {
12692            crate::seat_process::Running::spawn(cmd, None, outputs)
12693        };
12694        let (code, out_text, err_text, body) = match spawned {
12695            Ok(mut running) => {
12696                let pid = running.child().id();
12697                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
12698                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
12699                let mut paths = vec![cwd.to_owned()];
12700                if let Some(cache) = cache {
12701                    paths.push(cache);
12702                }
12703                let mut pressure = None;
12704                let status = tokio::select! {
12705                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
12706                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
12707                        pressure = Some(reason); None
12708                    }
12709                };
12710                let (code, failure) = match status {
12711                    Some(Ok(Ok(status))) => (
12712                        status.code(),
12713                        status
12714                            .code()
12715                            .is_none()
12716                            .then(|| format!("command terminated: {status}")),
12717                    ),
12718                    Some(Ok(Err(error))) => {
12719                        (None, Some(format!("failed waiting for command: {error}")))
12720                    }
12721                    Some(Err(_)) => {
12722                        // Leased cleanup confirms process-tree death itself.
12723                        // Unleased commands still need the caller's PID check
12724                        // after kill-on-drop, before releasing cache ownership.
12725                        if !running.coordinated()
12726                            && let Some(pid) = pid
12727                        {
12728                            timed_out_pids.push(pid);
12729                        }
12730                        (
12731                            None,
12732                            Some(format!("timed out after {}s", timeout.as_secs())),
12733                        )
12734                    }
12735                    None => (None, None),
12736                };
12737                running.finish().await;
12738                if let Some(reason) = pressure {
12739                    state.resource_block = Some(crate::run::ResourceBlock {
12740                        cause: crate::run::ResourceBlockCause::Other,
12741                        node: node.to_owned(),
12742                        kind: "disk pressure".to_owned(),
12743                        detail: reason.clone(),
12744                        at: Timestamp::now(),
12745                    });
12746                    out.push(CommandOutcome {
12747                        command: command.clone(),
12748                        code: None,
12749                        output_tail: reason,
12750                        duration_ms: started.elapsed().as_millis() as u64,
12751                        resource_blocked: true,
12752                        ..Default::default()
12753                    });
12754                    break;
12755                }
12756                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
12757                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
12758                let mut body = out_text.clone();
12759                body.push_str(&err_text);
12760                if let Some(failure) = failure {
12761                    body.push('\n');
12762                    body.push_str(&failure);
12763                }
12764                (code, out_text, err_text, body)
12765            }
12766            Err(e) if isolated => {
12767                let e = anyhow::Error::new(e)
12768                    .context(format!("could not start managed build `{}`", shell[0]));
12769                record_cache_error(state, node, &e);
12770                out.push(CommandOutcome {
12771                    command: command.clone(),
12772                    code: None,
12773                    output_tail: format!("{e:#}"),
12774                    duration_ms: 0,
12775                    resource_blocked: true,
12776                    ..Default::default()
12777                });
12778                break;
12779            }
12780            Err(e) => (
12781                None,
12782                String::new(),
12783                String::new(),
12784                format!("failed to spawn `{}`: {e}", shell[0]),
12785            ),
12786        };
12787        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
12788        let mut artifact = None;
12789        if !body.is_empty() {
12790            // The full text is kept whatever the summary dropped. A fresh
12791            // name per command so a resume or retry never overwrites an
12792            // earlier run's output. A failed write changes no verdict.
12793            match crate::run::write_verification_artifact(state, task, &body) {
12794                Ok(name) => {
12795                    let rel = format!("artifacts/{name}");
12796                    if summary != body {
12797                        summary = format!("[full output: {rel}]\n{summary}");
12798                    }
12799                    artifact = Some(rel);
12800                }
12801                Err(e) => {
12802                    let warning = format!("could not save the full {task} output: {e:#}");
12803                    tracing::warn!("{warning}");
12804                    state.event(node, warning);
12805                    if summary != body {
12806                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
12807                    }
12808                }
12809            }
12810        }
12811        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
12812        let mut outcome = CommandOutcome {
12813            command: command.clone(),
12814            code,
12815            output_tail: summary,
12816            duration_ms: started.elapsed().as_millis() as u64,
12817            resource_blocked,
12818            artifact,
12819            failure_evidence: None,
12820            rerun_comparison: None,
12821        };
12822        if !outcome.ok() && !outcome.resource_blocked {
12823            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
12824                code,
12825                outcome.build_failed(),
12826                &out_text,
12827                &err_text,
12828            ));
12829        }
12830        out.push(outcome);
12831        if resource_blocked {
12832            state.resource_block = Some(crate::run::ResourceBlock {
12833                cause: crate::run::ResourceBlockCause::Other,
12834                node: node.to_owned(),
12835                kind: "incremental cache admission".into(),
12836                detail: body,
12837                at: Timestamp::now(),
12838            });
12839            break;
12840        }
12841    }
12842    state.task_finished(task);
12843    if let Err(e) = state.save() {
12844        tracing::warn!("could not persist the end of {task}: {e:#}");
12845    }
12846    (out, timed_out_pids)
12847}
12848
12849/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
12850/// section (`report::run`) and in the `merge` event this node records — for
12851/// the operator to run by hand.
12852///
12853/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
12854/// branch whose ruleset forbids merge commits (GitHub's "must not contain
12855/// merge commits", or "require linear history") rejects the push a `--no-ff`
12856/// merge would produce, which is exactly the guidance this function replaces.
12857/// `message`'s first line becomes the squash commit's subject, matching the
12858/// note `report::run` prints alongside this command — see that function for
12859/// why an explicit subject is not optional there.
12860fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
12861    let repo = repo.display();
12862    match style {
12863        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
12864        MergeStyle::Squash => {
12865            // The subject sits inside double quotes, and a title an agent
12866            // wrote may carry the characters that break out of them.
12867            let subject = message
12868                .lines()
12869                .next()
12870                .unwrap_or(branch)
12871                .replace(['\\', '"', '$', '`'], "");
12872            format!(
12873                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
12874            )
12875        }
12876        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
12877    }
12878}
12879
12880/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
12881/// under the hood, rejects a `title` over 256 characters and the whole
12882/// command fails — no PR at all, for a run whose body was otherwise fine
12883/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
12884/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
12885/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
12886/// this bound. It is a margin, not a guarantee — a title packed
12887/// with multi-unit characters could still in principle land close to the
12888/// edge, but a real task title's occasional emoji or accented letter fits
12889/// comfortably inside it.
12890const PR_TITLE_MAX: usize = 240;
12891
12892/// A pull request title from the opening line of `text`, or `None` when that
12893/// line is not English (GitHub text is) or has no letters.
12894///
12895/// A line within `max` is kept as is. A longer one is cut at the end of its
12896/// first sentence when that falls inside `max`, else at a word boundary with a
12897/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
12898/// make every merely-truncated title look non-English). The language check
12899/// runs on the kept text before any mark is added, so only what GitHub will
12900/// show is judged: an English opening followed by non-ASCII far past the cut
12901/// still passes.
12902fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
12903    let line = queue::first_line(text)?;
12904    let chars: Vec<char> = line.chars().collect();
12905    let (kept, mark) = if chars.len() <= max {
12906        (line.to_owned(), "")
12907    } else if let Some(end) = sentence_end(&chars, max) {
12908        (chars[..end].iter().collect::<String>(), "")
12909    } else {
12910        let room = max.saturating_sub(3);
12911        // Cut at the last space inside the room; when the char just past the
12912        // room is a space the room already ends on a word.
12913        let cut = if chars[room].is_whitespace() {
12914            room
12915        } else {
12916            chars[..room]
12917                .iter()
12918                .rposition(|c| c.is_whitespace())
12919                .unwrap_or(room)
12920        };
12921        let head: String = chars[..cut].iter().collect();
12922        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
12923        (head.to_owned(), "...")
12924    };
12925    if kept.is_empty() {
12926        return None;
12927    }
12928    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
12929        return None;
12930    }
12931    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
12932        return None;
12933    }
12934    Some(format!("{kept}{mark}"))
12935}
12936
12937/// The char length of the first sentence of `chars` when it ends within `max`
12938/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
12939/// abbreviations so `e.g. foo` does not end a title early.
12940fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
12941    const MIN: usize = 20;
12942    for i in MIN..max.min(chars.len()) {
12943        if !matches!(chars[i], '.' | '!' | '?') {
12944            continue;
12945        }
12946        let Some(&next) = chars.get(i + 1) else {
12947            continue;
12948        };
12949        if !next.is_whitespace() {
12950            continue;
12951        }
12952        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
12953        if after.is_some_and(|c| c.is_ascii_lowercase()) {
12954            continue;
12955        }
12956        let word: String = chars[..i]
12957            .iter()
12958            .rev()
12959            .take_while(|c| !c.is_whitespace())
12960            .collect::<Vec<_>>()
12961            .into_iter()
12962            .rev()
12963            .collect();
12964        let word = word.to_ascii_lowercase();
12965        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
12966            continue;
12967        }
12968        let end = chars[..i]
12969            .iter()
12970            .rposition(|c| !c.is_whitespace())
12971            .map_or(i, |p| p + 1);
12972        return Some(end);
12973    }
12974    None
12975}
12976
12977/// What `merge = "pr"` (and the merge commit of the other modes) says about a
12978/// change: a title and a body describing what was *implemented*, not the task
12979/// that asked for it. A task reads as a request; a reader of the merged
12980/// history wants the change.
12981struct PrMessage {
12982    title: String,
12983    body: String,
12984}
12985
12986impl PrMessage {
12987    /// Title, blank line, body. The first line is the squash/merge commit
12988    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
12989    /// has to stay one sensible line.
12990    fn commit_message(&self) -> String {
12991        format!("{}\n\n{}", self.title, self.body)
12992    }
12993}
12994
12995/// The text after a leading `TITLE:` (any case) on `line`.
12996fn title_marker(line: &str) -> Option<&str> {
12997    let line = line.trim();
12998    let head = line.get(..6)?;
12999    head.eq_ignore_ascii_case("title:")
13000        .then(|| line[6..].trim())
13001}
13002
13003/// The implementer's own one-line title: the `TITLE:` line the implement
13004/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13005/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13006/// source, and a title that says as much is refused here too.
13007fn summary_title(summary: &str) -> Option<String> {
13008    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13009    let raw = title_marker(first)?;
13010    if raw.is_empty() {
13011        return None;
13012    }
13013    let title = queue::title_from(raw, PR_TITLE_MAX);
13014    let lower = title.to_ascii_lowercase();
13015    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13016        return None;
13017    }
13018    Some(title)
13019}
13020
13021/// How `open_review`'s instruction begins; see [`landing_title`].
13022const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13023
13024/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13025pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13026
13027/// Does this run review work that already existed, rather than implement a
13028/// task? Runs recorded before `reviewed_commits` existed carry only the
13029/// candidate marker.
13030pub(crate) fn is_review_run(state: &RunState) -> bool {
13031    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13032}
13033
13034/// The title of a review-only run: the subject of the oldest commit under
13035/// review. Later commits are usually fixups, and `instruction` is the review
13036/// prompt, which says nothing about the change. GitHub text is English, so a
13037/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13038fn review_title(state: &RunState) -> Option<String> {
13039    english_subject(
13040        state.reviewed_commits.as_ref()?.first()?,
13041        state.config.graph.github_english(),
13042    )
13043}
13044
13045/// `raw` as a pull request title, or `None` when it is blank, not English
13046/// (GitHub text is), or one of magi's own candidate commit subjects.
13047fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13048    let raw = raw.trim();
13049    if raw.is_empty() {
13050        return None;
13051    }
13052    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13053        return None;
13054    }
13055    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13056        return None;
13057    }
13058    let title = queue::title_from(raw, PR_TITLE_MAX);
13059    let lower = title.to_ascii_lowercase();
13060    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13061        return None;
13062    }
13063    Some(title)
13064}
13065
13066/// What a review-only run's branch says about itself, read at the moment the
13067/// pull request is opened.
13068#[derive(Debug, Clone, PartialEq, Eq)]
13069struct BranchFacts {
13070    /// `(subject, body)` of each commit, oldest first.
13071    commits: Vec<(String, String)>,
13072    /// Trimmed `git diff --stat`.
13073    stat: String,
13074}
13075
13076/// Longest diff stat shown: this many file lines plus the summary line.
13077const STAT_FILE_LINES: usize = 25;
13078/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13079const COMMITS_MAX_CHARS: usize = 20_000;
13080
13081/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13082/// say or finds nothing, so the caller falls back to what the run recorded.
13083async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13084    let commits = git::commit_log(repo, base, branch).await.ok()?;
13085    if commits.is_empty() {
13086        return None;
13087    }
13088    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13089    let lines: Vec<&str> = stat.lines().collect();
13090    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13091        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13092        let more = format!(" ... {omitted} more file(s)");
13093        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13094        kept.push(&more);
13095        kept.push(lines[lines.len() - 1]);
13096        kept.join("\n")
13097    } else {
13098        lines.join("\n")
13099    };
13100    Some(BranchFacts { commits, stat })
13101}
13102
13103/// Defang what would break the surrounding markdown: a closing `</details>`
13104/// and a code fence.
13105fn markdown_safe(text: &str) -> String {
13106    text.replace("</details>", "&lt;/details&gt;")
13107        .replace("\x60\x60\x60", "~~~")
13108}
13109
13110fn neutral_title(state: &RunState, winner: char) -> String {
13111    format!(
13112        "chore: land candidate {} of run {}",
13113        winner.to_ascii_uppercase(),
13114        state.id
13115    )
13116}
13117
13118/// Reuse the graph's bounded fixer without starting another graph or driver.
13119/// Copy the working state back even on errors so spent rounds remain visible.
13120pub(crate) async fn repair_landing_gate(
13121    state: &mut RunState,
13122    winner: &Candidate,
13123    outcomes: &[CommandOutcome],
13124) -> Result<GateFix> {
13125    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13126        return Ok(GateFix::Stop);
13127    }
13128    let mut runner = Runner {
13129        roles: state.config.resolve_roles()?,
13130        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13131        state: state.clone(),
13132        pause: Pause::new(),
13133        interrupt: Pause::new(),
13134    };
13135    let result = runner.gate_fix_round(winner, outcomes).await;
13136    *state = runner.state;
13137    result
13138}
13139
13140/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13141/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13142pub(crate) async fn verify_current_head(
13143    state: &mut RunState,
13144    winner: &Candidate,
13145    wait: &crate::repo_lock::WaitPolicy,
13146) -> Result<bool> {
13147    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13148    // Preserve the previous record before replacing it, including on crash recovery.
13149    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13150        state
13151            .verification_history
13152            .push(crate::run::VerificationEvidence {
13153                superseded_by: Some(head.clone()),
13154                archived_at: Some(Timestamp::now()),
13155                fixes_spent: Some(state.gate_fixes.len()),
13156                gate_head: None,
13157                gate_ran: false,
13158                gate: Vec::new(),
13159                e2e: state.head_e2e.take(),
13160            });
13161    }
13162    if let Some(e) = &state.head_e2e
13163        && e.head == head
13164    {
13165        if e.passed {
13166            return Ok(true);
13167        }
13168        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13169            state.status = RunStatus::Blocked;
13170            state.save()?;
13171            return Ok(false);
13172        }
13173    } else if state.reviews.last().is_some_and(|r| {
13174        r.verified_head.as_deref() == Some(head.as_str())
13175            && (r.e2e_status() == E2eStatus::Passed
13176                || (r.e2e_status() == E2eStatus::NotConfigured
13177                    && state.config.verify.e2e.is_empty()))
13178    }) || state
13179        .gate_repair_e2e
13180        .as_ref()
13181        .is_some_and(|e| e.head == head && e.passed)
13182    {
13183        return Ok(true);
13184    }
13185    if let Some(e) = &state.gate_repair_e2e
13186        && e.head == head
13187        && !e.passed
13188        && !e.outcomes.is_empty()
13189        && !verify_inconclusive(&e.outcomes)
13190    {
13191        state.status = RunStatus::Blocked;
13192        state.save()?;
13193        return Ok(false);
13194    }
13195    state.head_e2e = Some(crate::run::GateRepairE2e {
13196        head: head.clone(),
13197        passed: false,
13198        outcomes: Vec::new(),
13199    });
13200    state.save()?;
13201    let commands = state.config.verify.e2e.clone();
13202    let shell = state.config.shell();
13203    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13204    let cache_dir = state.config.cache_dir();
13205    let outcomes = if commands.is_empty() {
13206        Vec::new()
13207    } else {
13208        let (outcomes, _) = with_cache_lease(
13209            state,
13210            cache_dir.as_deref(),
13211            "e2e",
13212            "e2e",
13213            &winner.worktree,
13214            &head,
13215            timeout,
13216            "current head e2e",
13217            wait,
13218            |state, budget| async move {
13219                run_e2e_with_retry(
13220                    state,
13221                    &shell,
13222                    &commands,
13223                    &winner.worktree,
13224                    budget,
13225                    "current head e2e",
13226                    None,
13227                )
13228                .await
13229            },
13230        )
13231        .await?;
13232        outcomes
13233    };
13234    let unresolved = verify_inconclusive(&outcomes);
13235    let passed = !unresolved
13236        && outcomes.iter().all(CommandOutcome::ok)
13237        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13238    if !outcomes.is_empty() && !unresolved {
13239        state.record_base_progress(&head);
13240    }
13241    state.head_e2e = Some(crate::run::GateRepairE2e {
13242        head: head.clone(),
13243        passed,
13244        outcomes,
13245    });
13246    if !passed && !unresolved {
13247        let detail = state
13248            .head_e2e
13249            .as_ref()
13250            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13251            .map(|d| format!(" ({d})"))
13252            .unwrap_or_default();
13253        state.status = RunStatus::Blocked;
13254        state.event(
13255            "e2e",
13256            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13257        );
13258    }
13259    state.save()?;
13260    Ok(passed)
13261}
13262
13263/// Recheck a repair's e2e requirement across failures, resource deferrals and
13264/// process interruptions. A successful result only applies to its exact SHA.
13265pub(crate) async fn check_gate_repair_e2e(
13266    state: &mut RunState,
13267    winner: &Candidate,
13268    wait: &crate::repo_lock::WaitPolicy,
13269) -> Result<GateFix> {
13270    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13271        return Ok(GateFix::Retry);
13272    }
13273    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13274    if let Some(record) = &state.gate_repair_e2e
13275        && record.head == head
13276    {
13277        if record.passed {
13278            return Ok(GateFix::Retry);
13279        }
13280        if !record.outcomes.is_empty()
13281            && record.outcomes.iter().all(|o| {
13282                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13283            })
13284        {
13285            return Ok(GateFix::Stop);
13286        }
13287    }
13288    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13289        head: head.clone(),
13290        passed: false,
13291        outcomes: Vec::new(),
13292    });
13293    state.save()?;
13294    let commands = state.config.verify.e2e.clone();
13295    let outcomes = if commands.is_empty() {
13296        Vec::new()
13297    } else {
13298        let shell = state.config.shell();
13299        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13300        let cache_dir = state.config.cache_dir();
13301        let (outcomes, _) = with_cache_lease(
13302            state,
13303            cache_dir.as_deref(),
13304            "e2e",
13305            "e2e",
13306            &winner.worktree,
13307            &head,
13308            timeout,
13309            "gate repair e2e",
13310            wait,
13311            |state, budget| async move {
13312                run_e2e_with_retry(
13313                    state,
13314                    &shell,
13315                    &commands,
13316                    &winner.worktree,
13317                    budget,
13318                    "gate repair e2e",
13319                    None,
13320                )
13321                .await
13322            },
13323        )
13324        .await?;
13325        outcomes
13326    };
13327    let deferred = verify_inconclusive(&outcomes);
13328    let passed = outcomes.iter().all(CommandOutcome::ok)
13329        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13330    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13331        head,
13332        passed,
13333        outcomes,
13334    });
13335    state.save()?;
13336    if deferred {
13337        Ok(GateFix::Defer)
13338    } else if !passed {
13339        let detail = state
13340            .gate_repair_e2e
13341            .as_ref()
13342            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13343            .map(|d| format!(" ({d})"))
13344            .unwrap_or_default();
13345        state.event(
13346            "gate",
13347            format!("verify.e2e failed after gate repair{detail}; nothing published"),
13348        );
13349        Ok(GateFix::Stop)
13350    } else {
13351        Ok(GateFix::Retry)
13352    }
13353}
13354
13355/// Run the same configured gate for a landing head and a fresh graph.
13356pub(crate) async fn run_landing_gate(
13357    state: &mut RunState,
13358    winner: &Candidate,
13359    wait: &crate::repo_lock::WaitPolicy,
13360) -> Result<Vec<CommandOutcome>> {
13361    let shell = state.config.shell();
13362    let gate_commands = state.config.verify.gate.clone();
13363    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13364    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13365        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13366        Vec::new()
13367    } else {
13368        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13369        let cache_dir = state.config.cache_dir();
13370        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13371        let (outcomes, _) = with_cache_lease(
13372            state,
13373            cache_dir.as_deref(),
13374            "gate",
13375            "gate",
13376            &winner.worktree,
13377            &head,
13378            timeout,
13379            "final gate",
13380            wait,
13381            |state, budget| {
13382                let shell = shell.clone();
13383                let gate_commands = gate_commands.clone();
13384                let winner = winner.clone();
13385                async move {
13386                    Runner::run_pre_gate(state, &winner).await;
13387                    // Bind command evidence after mechanical fixes, before commands start.
13388                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13389                    let (outcomes, timed_out_pids) = run_commands(
13390                        state,
13391                        "gate",
13392                        "gate",
13393                        0,
13394                        &shell,
13395                        &gate_commands,
13396                        &winner.worktree,
13397                        budget,
13398                    )
13399                    .await;
13400                    (outcomes, false, timed_out_pids)
13401                }
13402            },
13403        )
13404        .await?;
13405        outcomes
13406    };
13407    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13408    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13409        let mut outcomes = outcomes;
13410        outcomes.push(CommandOutcome {
13411            command: "gate head stability".into(), code: None,
13412            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13413            duration_ms: 0, resource_blocked: false,
13414            ..Default::default()
13415        });
13416        return Ok(outcomes);
13417    }
13418    if outcomes.is_empty() {
13419        // Nothing configured to check — distinct from every other
13420        // silence in this run's event log, since an empty `gate` alone
13421        // no longer says whether the gate ran at all (see
13422        // `RunState::gate_ran`'s own doc).
13423        state.event("gate", "no gate commands configured; not tested");
13424    }
13425    for o in &outcomes {
13426        state.event(
13427            "gate",
13428            format!(
13429                "`{}` -> {}",
13430                o.command,
13431                if o.ok() {
13432                    "pass".to_owned()
13433                } else {
13434                    format!(
13435                        "FAIL ({:?})\n{}",
13436                        o.code,
13437                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13438                    )
13439                }
13440            ),
13441        );
13442    }
13443    Ok(outcomes)
13444}
13445
13446/// The pull request title to hand to `land::merge_subject`. A review-only run
13447/// opened by an earlier build titled its pull request with the review prompt;
13448/// that title is dropped (empty, so the fallback applies) rather than landed.
13449/// Any other title, including an operator's rename, passes through untouched,
13450/// and so does every title of a run that implements a task.
13451pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13452    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13453        ""
13454    } else {
13455        pr_title
13456    }
13457}
13458
13459/// What the squash subject falls back to when the pull request title is empty
13460/// or candidate-shaped: for a review-only run the derived title, never the
13461/// review prompt held in `instruction`.
13462pub fn landing_subject_source(state: &RunState) -> String {
13463    if is_review_run(state) {
13464        let winner = state.candidates.first().map_or('A', |c| c.label);
13465        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13466    }
13467    state.instruction.clone()
13468}
13469
13470/// `summary` without its `TITLE:` line, which the pull request title already
13471/// carries.
13472fn summary_without_title(summary: &str) -> String {
13473    let mut lines = summary.trim().lines().peekable();
13474    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13475        lines.next();
13476    }
13477    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13478}
13479
13480/// The pull request title and body for the winning candidate.
13481///
13482/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13483/// the task's own opening line via [`queue::title_from`] when there is none.
13484/// `state.instruction` can open with blank lines (`task_text` only rejects a
13485/// body that is blank *entirely*), which `title_from` skips.
13486///
13487/// Publishing uses an independent description generated from the final diff
13488/// and structured evidence. Internal summaries and reports remain local.
13489/// Non-publishing previews may display the original task and candidate summary.
13490/// The footer retains the run and candidate provenance.
13491#[cfg(test)]
13492fn pr_message(state: &RunState, winner: char) -> PrMessage {
13493    pr_message_with(state, winner, None)
13494}
13495
13496/// [`pr_message`] with what the branch of a review-only run says about itself.
13497/// `facts` is ignored for a run that implements a task.
13498#[cfg(test)]
13499fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13500    let raw = pr_message_raw(
13501        state,
13502        winner,
13503        facts,
13504        crate::pr_outcome::FinalHead::Unreported,
13505        ChangeNote::NotAsked,
13506    );
13507    let id = crate::scrub::Identity::current();
13508    PrMessage {
13509        title: crate::scrub::scrub(&raw.title, &id),
13510        body: crate::scrub::scrub(&raw.body, &id),
13511    }
13512}
13513
13514/// What the public description may say about the change itself.
13515#[derive(Debug, Clone, Copy)]
13516enum ChangeNote<'a> {
13517    /// A local preview or non-publishing merge mode: no public generation needed.
13518    NotAsked,
13519    /// A summary written from the final diff.
13520    Summary(&'a crate::run::ChangeSummary),
13521    /// A summary was asked for and could not be produced; the text says why.
13522    Unavailable(&'a str),
13523}
13524
13525fn pr_message_raw(
13526    state: &RunState,
13527    winner: char,
13528    facts: Option<&BranchFacts>,
13529    head: crate::pr_outcome::FinalHead<'_>,
13530    change: ChangeNote<'_>,
13531) -> PrMessage {
13532    if !matches!(change, ChangeNote::NotAsked) {
13533        let (title, mut body) = match change {
13534            ChangeNote::Summary(c) => (
13535                c.title.clone(),
13536                format!("## Summary\n\n{}\n\n", c.body.trim()),
13537            ),
13538            ChangeNote::Unavailable(why) => (
13539                neutral_title(state, winner),
13540                format!(
13541                    "## 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"
13542                ),
13543            ),
13544            ChangeNote::NotAsked => unreachable!(),
13545        };
13546        body.push_str(&public_pr_evidence(state, head));
13547        body.push_str(&format!(
13548            "\n---\nmagi:run/{} magi:candidate-{}\n",
13549            state.id,
13550            winner.to_ascii_lowercase()
13551        ));
13552        return PrMessage { title, body };
13553    }
13554    pr_preview(state, winner, facts, head)
13555}
13556
13557/// Append public facts from the run records after every prose generation,
13558/// including posting-gate rewrites. The agent cannot drop this provenance.
13559fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
13560    let mut body = crate::pr_outcome::review_rounds(state);
13561    body.push_str(&crate::pr_outcome::final_verification(state, head));
13562    let open = state.last_round_findings();
13563    if !open.is_empty() {
13564        body.push_str("## Open review findings\n\n");
13565        for f in open {
13566            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
13567        }
13568        body.push('\n');
13569    }
13570    if let Some(c) = state.change_summary.as_ref()
13571        && head == crate::pr_outcome::FinalHead::At(&c.head)
13572    {
13573        body.push_str(&format!(
13574            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
13575            c.base, c.head
13576        ));
13577    }
13578    body
13579}
13580
13581/// Local-only preview of the operator's task and candidate summary.
13582fn pr_preview(
13583    state: &RunState,
13584    winner: char,
13585    facts: Option<&BranchFacts>,
13586    head: crate::pr_outcome::FinalHead<'_>,
13587) -> PrMessage {
13588    let summary = state
13589        .candidates
13590        .iter()
13591        .find(|c| c.label == winner)
13592        .map(|c| c.summary.as_str())
13593        .unwrap_or_default();
13594    // The fallback is the operator's own words and may not be English; GitHub
13595    // text always is, so a non-English task gets a neutral title instead.
13596    let review = is_review_run(state);
13597    let title = if review {
13598        facts
13599            .and_then(|f| {
13600                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
13601            })
13602            .or_else(|| review_title(state))
13603            .or_else(|| {
13604                state
13605                    .candidates
13606                    .iter()
13607                    .find(|c| c.label == winner)
13608                    .filter(|c| !c.branch.starts_with("magi/"))
13609                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
13610            })
13611            .unwrap_or_else(|| neutral_title(state, winner))
13612    } else {
13613        summary_title(summary).unwrap_or_else(|| {
13614            english_title(
13615                &state.instruction,
13616                PR_TITLE_MAX,
13617                state.config.graph.github_english(),
13618            )
13619            .unwrap_or_else(|| neutral_title(state, winner))
13620        })
13621    };
13622
13623    let mut body = String::new();
13624    let what = summary_without_title(summary);
13625    if !what.is_empty() {
13626        body.push_str("## Summary\n\n");
13627        body.push_str(&what);
13628        body.push_str("\n\n");
13629    }
13630
13631    // Review history uses structured facts across all rounds, never reports.
13632    body.push_str(&crate::pr_outcome::review_rounds(state));
13633    body.push_str(&crate::pr_outcome::final_verification(state, head));
13634    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
13635
13636    let open = state.open_findings();
13637    if !open.is_empty() {
13638        body.push_str("## Open review findings\n\n");
13639        for f in &open {
13640            body.push_str(&format!(
13641                "- `{}` [{:?}] {}\n",
13642                f.id, f.severity, "Context retained in local review records."
13643            ));
13644        }
13645        body.push('\n');
13646    }
13647
13648    if let Some(fix) = fix
13649        && !fix.rejected.is_empty()
13650    {
13651        body.push_str("## Declined by the fixer\n\n");
13652        for r in &fix.rejected {
13653            body.push_str(&format!(
13654                "- `{}`: {}\n",
13655                r.id, "Reason retained in local review records."
13656            ));
13657        }
13658        body.push('\n');
13659    }
13660
13661    if review {
13662        // The review prompt is not the task; list what the branch carries.
13663        body.push_str("## Commits under review\n\n");
13664        if let Some(facts) = facts {
13665            let mut left = COMMITS_MAX_CHARS;
13666            for (i, (subject, text)) in facts.commits.iter().enumerate() {
13667                let mut entry = format!("- {}\n", markdown_safe(subject));
13668                for l in markdown_safe(text).lines() {
13669                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
13670                }
13671                if left == 0 {
13672                    body.push_str(&format!(
13673                        "- ... {} more commit(s)\n",
13674                        facts.commits.len() - i
13675                    ));
13676                    break;
13677                }
13678                if entry.len() > left {
13679                    // Even the first commit is cut: one huge body must not
13680                    // push the whole description past GitHub's limit.
13681                    let mut end = left;
13682                    while !entry.is_char_boundary(end) {
13683                        end -= 1;
13684                    }
13685                    entry.truncate(end);
13686                    entry.push_str("\n  ... (truncated)\n");
13687                    left = 0;
13688                } else {
13689                    left -= entry.len();
13690                }
13691                body.push_str(&entry);
13692            }
13693            if !facts.stat.trim().is_empty() {
13694                body.push_str(&format!(
13695                    "\n## Diff stat\n\n```\n{}\n```\n",
13696                    markdown_safe(facts.stat.trim())
13697                ));
13698            }
13699        } else {
13700            match &state.reviewed_commits {
13701                Some(subjects) => {
13702                    for s in subjects {
13703                        body.push_str(&format!("- {}\n", s.trim()));
13704                    }
13705                }
13706                None => {
13707                    // An older run kept only the prompt, with the commit list
13708                    // after its first paragraph.
13709                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
13710                    body.push_str(rest.trim());
13711                    body.push('\n');
13712                }
13713            }
13714        }
13715    } else {
13716        let task = state.instruction.trim();
13717        let task = if task.is_empty() {
13718            "(empty task)"
13719        } else {
13720            task
13721        };
13722        body.push_str(&format!(
13723            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
13724            task.replace("</details>", "&lt;/details&gt;")
13725        ));
13726    }
13727
13728    body.push_str(&format!(
13729        "\n---\nmagi:run/{} magi:candidate-{}\n",
13730        state.id,
13731        winner.to_ascii_lowercase()
13732    ));
13733
13734    PrMessage { title, body }
13735}
13736
13737/// Source imports have already been prepared from structured inputs. Legacy
13738/// inferred references must never instruct a seat to reconstruct those imports.
13739fn seeded_instruction(state: &RunState) -> String {
13740    let mut inputs = Vec::new();
13741    if let Some(start) = &state.sources.start_from {
13742        inputs.push(format!(
13743            "Start from `{}` at `{}` (including ancestry).",
13744            start.token, start.sha
13745        ));
13746    }
13747    for pick in &state.sources.pick_commits {
13748        inputs.push(format!(
13749            "Pick `{}` at `{}` (single commit).",
13750            pick.token, pick.sha
13751        ));
13752    }
13753    if inputs.is_empty() {
13754        state.instruction.clone()
13755    } else {
13756        format!(
13757            "{}\n\n# Explicit source inputs already prepared\n\n{}",
13758            state.instruction,
13759            inputs.join("\n")
13760        )
13761    }
13762}
13763
13764/// Does the winner have no commits ahead of the base it would land on?
13765/// Any failure to find out reads as "not empty": the merge then behaves as it
13766/// always did rather than refusing on a guess.
13767async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
13768    let base = &state.base_branch;
13769    let mut against = base.clone();
13770    if mode == MergeMode::Pr {
13771        // A pull request lands on the remote's base, never the local branch
13772        // of the same name: if that cannot be read, "not empty" is the safe
13773        // answer.
13774        let remote = &state.config.merge.remote;
13775        let tracking = format!("{remote}/{base}");
13776        let fetched = git::fetch(repo, remote, base).await;
13777        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
13778            against = tracking;
13779        } else {
13780            return false;
13781        }
13782    }
13783    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
13784}
13785
13786/// Why nothing was opened for an empty winner, with what the task's own
13787/// references resolved to.
13788fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
13789    let mut detail = format!(
13790        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
13791         nothing to open a pull request for"
13792    );
13793    detail.push_str(
13794        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
13795    );
13796    detail
13797}
13798
13799/// What the `Pr` merge does once it knows whether the branch already has an
13800/// open pull request.
13801#[derive(Debug, PartialEq, Eq)]
13802enum PrPlan {
13803    Create,
13804    Adopt { url: String, title: String },
13805    Stop(String),
13806}
13807
13808/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
13809/// a failed lookup -> stop with the real reason. Never guesses.
13810fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
13811    match found {
13812        Ok(land::OpenPr::None) => PrPlan::Create,
13813        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
13814        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
13815            "several open pull requests exist for this branch, not picking one: {}",
13816            urls.join(" ")
13817        )),
13818        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
13819    }
13820}
13821
13822/// `gh pr create`, returning the PR url.
13823pub(crate) async fn gh_pr_create(
13824    cwd: &Path,
13825    base: &str,
13826    head: &str,
13827    title: &str,
13828    body: &str,
13829) -> Result<String> {
13830    let out = tokio::process::Command::new("gh")
13831        .args([
13832            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
13833        ])
13834        .current_dir(cwd)
13835        .quiet()
13836        .stdin(std::process::Stdio::null())
13837        .output()
13838        .await
13839        .context("spawn gh")?;
13840    if out.status.success() {
13841        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
13842    } else {
13843        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
13844    }
13845}
13846
13847/// Never force deletion of uncommitted work, including unknown legacy trees.
13848async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
13849    match std::fs::symlink_metadata(path) {
13850        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
13851            // A previous cleanup may have removed the tree before a branch
13852            // deletion or state save failed. Unregister it if still present.
13853            git::worktree_remove_clean(repo, path).await?;
13854            return Ok(());
13855        }
13856        Err(e) => return Err(e.into()),
13857        Ok(_) => {}
13858    }
13859    if !git::is_clean(path).await? {
13860        bail!(
13861            "worktree has uncommitted work; refusing removal: {}",
13862            path.display()
13863        );
13864    }
13865    if !git::worktree_remove_clean(repo, path).await? {
13866        bail!("worktree removal refused: {}", path.display());
13867    }
13868    Ok(())
13869}
13870
13871/// Read seats return replies, not working-tree changes. Only registered,
13872/// detached seats directly inside this run's root may discard those changes.
13873async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
13874    if !crate::retention::read_seat(path) || !path.exists() {
13875        return remove_preserved_worktree(&state.repo, path).await;
13876    }
13877    let owned = std::fs::symlink_metadata(path)?.is_dir()
13878        && path.parent().map(Path::canonicalize).transpose()?
13879            == Some(state.worktree_root().canonicalize()?)
13880        && crate::retention::worktrees(state)
13881            .await?
13882            .contains(&path.canonicalize()?);
13883    let common = crate::repo_lock::common_dir(&state.repo).await?;
13884    if !owned
13885        || common.is_none()
13886        || crate::repo_lock::common_dir(path).await? != common
13887        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
13888            .await?
13889            .ok()
13890        || state.candidates.iter().any(|c| c.worktree == path)
13891    {
13892        return remove_preserved_worktree(&state.repo, path).await;
13893    }
13894    let changes = git::status_porcelain(path).await?;
13895    if !git::worktree_remove(&state.repo, path).await? {
13896        bail!(
13897            "read-only seat worktree removal refused: {}",
13898            path.display()
13899        );
13900    }
13901    if !changes.is_empty() {
13902        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
13903        let paths: String = paths.chars().take(1024).collect();
13904        state.event(
13905            "fold",
13906            format!(
13907                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
13908                path.file_name().unwrap_or_default().to_string_lossy(),
13909                changes.lines().count()
13910            ),
13911        );
13912    }
13913    Ok(())
13914}
13915
13916fn fold_target(
13917    home: &Path,
13918    root: &Path,
13919    path: &Path,
13920    isolated: bool,
13921) -> Option<crate::build_target::FoldTarget> {
13922    if !isolated {
13923        return None;
13924    }
13925    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
13926        Ok(target) => target,
13927        Err(error) => {
13928            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
13929            None
13930        }
13931    }
13932}
13933
13934fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
13935    if let Some(target) = target
13936        && let Err(error) = target.reclaim_orphaned_target(home)
13937    {
13938        tracing::warn!(%error, "isolated target retained after fold");
13939    }
13940}
13941
13942/// Tear a run's worktrees and branches down.
13943///
13944/// `home` is where the updated `run.json` is saved (via
13945/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
13946/// a housekeeping pass already has its own honest `home` handed to it, and
13947/// falling through to the global here would write back through whichever
13948/// directory some other process or test pinned into that `OnceLock` first,
13949/// not the one the caller actually resolved its `runs` and `state` from.
13950pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
13951    fold_run_with_policy(state, drop_winner, home, false).await
13952}
13953
13954/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
13955pub async fn fold_run_overriding_recovery_retention(
13956    state: &mut RunState,
13957    drop_winner: bool,
13958    home: &Path,
13959) -> Result<Vec<String>> {
13960    fold_run_with_policy(state, drop_winner, home, true).await
13961}
13962
13963async fn fold_run_with_policy(
13964    state: &mut RunState,
13965    drop_winner: bool,
13966    home: &Path,
13967    override_recovery_retention: bool,
13968) -> Result<Vec<String>> {
13969    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
13970        && !override_recovery_retention
13971    {
13972        bail!("refusing fold: {reason}");
13973    }
13974    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
13975        bail!("candidate preservation incomplete; refusing cleanup");
13976    }
13977    // Serialize ordinary folding with the same starts/resumes as target-only
13978    // eviction. Otherwise a second janitor could remove the whole worktree
13979    // around a live output borrower even though target eviction was fenced.
13980    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
13981    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
13982    // An override must use current durable ownership, not a pre-lock snapshot.
13983    if override_recovery_retention {
13984        *state = RunState::load_under(&state.id, home)?;
13985        anyhow::ensure!(
13986            state.status.done() && !state.status.resumable(),
13987            "recovery retention override requires a finished, non-resumable run"
13988        );
13989        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
13990        anyhow::ensure!(
13991            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
13992            "run is live or its ownership is unknown"
13993        );
13994        anyhow::ensure!(
13995            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
13996            "candidate preservation incomplete; refusing cleanup"
13997        );
13998    }
13999    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14000    if let Some(reason) = &retention_reason
14001        && !override_recovery_retention
14002    {
14003        bail!("refusing fold: {reason}");
14004    }
14005    let _driver = crate::driver::maintenance(home, &state.id)?;
14006    let mut output_guards = Vec::new();
14007    for entry in std::fs::read_dir(state.worktree_root())
14008        .into_iter()
14009        .flatten()
14010        .flatten()
14011    {
14012        if entry.path().join(".git").is_file() {
14013            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
14014        }
14015    }
14016    let repo = state.repo.clone();
14017    // CLI, Web and automatic cleanup all enter here, independently of
14018    // Runner::fold_losers. Protect deletion and shared config release too.
14019    let wait = repository_wait(state, None);
14020    let _coordination = match coordinate_operation(state, &repo, &wait).await {
14021        Ok(lease) => lease,
14022        Err(e) => {
14023            state.save_under(home)?;
14024            return Err(e);
14025        }
14026    };
14027    // Confirmed merges dispose of their owned sources after durable evidence
14028    // capture. Preflight every source before removing anything.
14029    let _source_outputs = if retention_reason.is_some()
14030        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
14031    {
14032        verify_merged_fold_sources(state, drop_winner, home).await?
14033    } else {
14034        Vec::new()
14035    };
14036    if let Some(reason) = retention_reason {
14037        state.event(
14038            "fold",
14039            format!(
14040                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
14041                state.id
14042            ),
14043        );
14044        state.save_under(home)?;
14045    }
14046    let root = state.worktree_root();
14047    let winner = state.tally.as_ref().map(|t| t.winner);
14048    let mut removed = Vec::new();
14049    let isolated = crate::build_target::isolated(&state.config);
14050
14051    for i in 0..state.candidates.len() {
14052        let c = state.candidates[i].clone();
14053        let is_winner = Some(c.label) == winner;
14054        if is_winner && !drop_winner {
14055            continue;
14056        }
14057        let existed = c.worktree.exists();
14058        let target = fold_target(home, &root, &c.worktree, isolated);
14059        // A vanished directory can still have a Git registration that keeps
14060        // its branch checked out. Remove that registration before the branch.
14061        remove_preserved_worktree(&repo, &c.worktree).await?;
14062        reclaim_fold_target(home, target);
14063        if existed {
14064            removed.push(c.worktree.to_string_lossy().into_owned());
14065        }
14066        // A branch handed to a later run (and its pull request) is not this
14067        // run's to delete.
14068        let handed_over = state.released_branches.contains(&c.branch);
14069        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
14070            if !git::branch_delete(&repo, &c.branch).await? {
14071                bail!("candidate branch removal refused");
14072            }
14073            removed.push(c.branch.clone());
14074        }
14075        state.candidates[i].folded = true;
14076    }
14077
14078    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
14079        let path = name.path();
14080        let keep = !drop_winner
14081            && winner.is_some_and(|w| {
14082                path.file_name()
14083                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14084            });
14085        if keep {
14086            continue;
14087        }
14088        let target = fold_target(home, &root, &path, isolated);
14089        remove_read_seat_worktree(state, &path).await?;
14090        reclaim_fold_target(home, target);
14091        removed.push(path.to_string_lossy().into_owned());
14092    }
14093
14094    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14095    // judge worktrees, so once the loop above has cleared all of them out,
14096    // the parent is a bare directory nobody else was ever going to remove -
14097    // git only ever managed what was inside it. Left alone, one of these
14098    // accumulates per fully-folded run; the operator's own machine had 74.
14099    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14100    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14101    // so does anything a run never claimed that happens to share the bay.
14102    remove_if_empty(&root);
14103
14104    if state.enabled_worktree_config && drop_winner {
14105        // A release, not a raw disable: some sibling run in this repository
14106        // may still hold its own reference (see `git::acquire_worktree_config`),
14107        // and only the last release actually turns the setting back off.
14108        git::release_worktree_config(&repo).await.ok();
14109        state.enabled_worktree_config = false;
14110    }
14111    state.save_under(home)?;
14112    Ok(removed)
14113}
14114
14115async fn verify_merged_fold_sources(
14116    state: &RunState,
14117    drop_winner: bool,
14118    home: &Path,
14119) -> Result<Vec<std::fs::File>> {
14120    let winner = state.tally.as_ref().map(|t| t.winner);
14121    let mut heads = BTreeSet::new();
14122    for candidate in &state.candidates {
14123        if Some(candidate.label) == winner && !drop_winner {
14124            continue;
14125        }
14126        anyhow::ensure!(
14127            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14128            "candidate recovery source is outside the inventoried run root: {}",
14129            candidate.worktree.display()
14130        );
14131        match std::fs::symlink_metadata(&candidate.worktree) {
14132            Ok(_) => {}
14133            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14134            Err(error) => return Err(error.into()),
14135        }
14136        if !state.released_branches.contains(&candidate.branch)
14137            && git::branch_exists(&state.repo, &candidate.branch).await?
14138        {
14139            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14140        }
14141    }
14142    let mut cargo_guards = Vec::new();
14143    let entries = match std::fs::read_dir(state.worktree_root()) {
14144        Ok(entries) => Some(entries),
14145        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14146        Err(error) => return Err(error.into()),
14147    };
14148    for entry in entries.into_iter().flatten() {
14149        let path = entry?.path();
14150        let metadata = std::fs::symlink_metadata(&path)?;
14151        anyhow::ensure!(
14152            metadata.is_dir() && !metadata.file_type().is_symlink(),
14153            "non-directory or symlink recovery source retained: {}",
14154            path.display()
14155        );
14156        if !drop_winner
14157            && winner.is_some_and(|w| {
14158                path.file_name()
14159                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14160            })
14161        {
14162            continue;
14163        }
14164        anyhow::ensure!(
14165            path.join(".git").is_file(),
14166            "unregistered recovery source retained: {}",
14167            path.display()
14168        );
14169        anyhow::ensure!(
14170            git::git(
14171                &path,
14172                &[
14173                    "status",
14174                    "--porcelain",
14175                    "--untracked-files=all",
14176                    "--ignored",
14177                    "--",
14178                    ".",
14179                    ":(exclude)target"
14180                ]
14181            )
14182            .await?
14183            .is_empty(),
14184            "source changes or ignored recovery files retained: {}",
14185            path.display()
14186        );
14187        match std::fs::symlink_metadata(path.join("target")) {
14188            Ok(_) => {
14189                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14190            }
14191            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14192            Err(error) => return Err(error.into()),
14193        }
14194        for checkpoint in [
14195            "rebase-merge",
14196            "rebase-apply",
14197            "sequencer",
14198            "CHERRY_PICK_HEAD",
14199            "MERGE_HEAD",
14200            "REBASE_HEAD",
14201            "REVERT_HEAD",
14202            "BISECT_LOG",
14203            "AUTO_MERGE",
14204            "MERGE_MSG",
14205        ] {
14206            let location = git::git(
14207                &path,
14208                &[
14209                    "rev-parse",
14210                    "--path-format=absolute",
14211                    "--git-path",
14212                    checkpoint,
14213                ],
14214            )
14215            .await?;
14216            anyhow::ensure!(
14217                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14218                if e.kind() == std::io::ErrorKind::NotFound),
14219                "Git recovery checkpoint retained: {checkpoint}"
14220            );
14221        }
14222        heads.insert(git::rev_parse(&path, "HEAD").await?);
14223    }
14224    crate::fold_evidence::preserve(state, home, &heads).await?;
14225
14226    Ok(cargo_guards)
14227}
14228
14229/// Remove `dir` if it exists and has nothing in it.
14230///
14231/// Best-effort and silent by design: a directory that is not empty (a run
14232/// whose winner is still parked there, a stray file some other process left)
14233/// is exactly the case this must refuse, and a directory that is already gone
14234/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14235/// already refuses a non-empty directory, so the emptiness check below is
14236/// belt, not suspenders - it is what keeps this from ever attempting the
14237/// removal in the case that matters, rather than trusting `remove_dir`'s
14238/// error path to have no side effects if it ever changed.
14239fn remove_if_empty(dir: &Path) {
14240    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14241        std::fs::remove_dir(dir).ok();
14242    }
14243}
14244
14245/// Severity of the worst open finding in the last review round, for reporting.
14246pub fn worst_open(state: &RunState) -> Option<Severity> {
14247    state
14248        .reviews
14249        .last()?
14250        .reviews
14251        .iter()
14252        .flat_map(|r| r.findings.iter())
14253        .map(|f| f.severity)
14254        .max()
14255}
14256
14257/// `[worktree] setup` hides its products per worktree, which needs
14258/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14259/// worktrees, like the hook's; every place that runs setup calls this first.
14260async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14261    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14262        git::acquire_worktree_config(repo).await?;
14263        state.enabled_worktree_config = true;
14264    }
14265    Ok(())
14266}
14267
14268#[cfg(test)]
14269mod tests {
14270    #[tokio::test]
14271    async fn launcher_base_fetch_requires_remote_success() {
14272        let tmp = tempfile::tempdir().unwrap();
14273        let repo = tmp.path().join("repo");
14274        let remote = tmp.path().join("remote");
14275        std::fs::create_dir(&repo).unwrap();
14276        std::fs::create_dir(&remote).unwrap();
14277        git::git(&remote, &["init", "--bare", "-b", "main"])
14278            .await
14279            .unwrap();
14280        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14281        git::git(
14282            &repo,
14283            &[
14284                "-c",
14285                "user.name=Fixture",
14286                "-c",
14287                "user.email=fixture@example.invalid",
14288                "commit",
14289                "--allow-empty",
14290                "-m",
14291                "fixture",
14292            ],
14293        )
14294        .await
14295        .unwrap();
14296        git::git(
14297            &repo,
14298            &["remote", "add", "origin", remote.to_str().unwrap()],
14299        )
14300        .await
14301        .unwrap();
14302        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14303        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14304        assert_eq!(
14305            resolve_base(&repo, "main", "origin", None)
14306                .await
14307                .unwrap()
14308                .commit,
14309            head
14310        );
14311        #[cfg(unix)]
14312        {
14313            let policy: crate::config::Coordination = toml::from_str(
14314                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14315            ).unwrap();
14316            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14317            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14318            let held = crate::repo_lock::SeatLease::operation_with(
14319                &repo,
14320                Some(&policy),
14321                &crate::repo_lock::WaitPolicy::default(),
14322            )
14323            .await
14324            .unwrap();
14325            assert!(held.is_some());
14326            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14327            tokio::pin!(fetch);
14328            assert!(
14329                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14330                    .await
14331                    .is_err()
14332            );
14333            assert!(
14334                !repo.join(".git/FETCH_HEAD").exists(),
14335                "no fetch before admission"
14336            );
14337            drop(held);
14338            let fetched = fetch.await.unwrap();
14339            assert_eq!(fetched.commit, head);
14340            assert_eq!(fetched.remote, "origin");
14341            assert_eq!(fetched.branch, "main");
14342        }
14343        // A surviving tracking ref is not successful fetch evidence.
14344        git::git(
14345            &repo,
14346            &[
14347                "remote",
14348                "set-url",
14349                "origin",
14350                tmp.path().join("missing").to_str().unwrap(),
14351            ],
14352        )
14353        .await
14354        .unwrap();
14355        let error = resolve_base(&repo, "main", "origin", None)
14356            .await
14357            .unwrap_err()
14358            .to_string();
14359        assert!(error.contains("cannot read origin/main"));
14360        assert!(error.contains("refusing to branch off"));
14361    }
14362
14363    #[test]
14364    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14365        let leaked = vec!["chore(deps): update a crate".to_owned()];
14366        let own = "fix(daemon): apply a chosen action";
14367        assert!(should_retitle("", own, &leaked));
14368        assert!(should_retitle(
14369            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14370            own,
14371            &leaked
14372        ));
14373        assert!(should_retitle(
14374            "chore: land candidate A of run 1",
14375            own,
14376            &leaked
14377        ));
14378        assert!(should_retitle(
14379            "magi: candidate A (uncommitted work)",
14380            own,
14381            &leaked
14382        ));
14383        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14384        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14385        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14386    }
14387
14388    #[test]
14389    fn pr_merge_plan_creates_adopts_or_stops() {
14390        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14391        assert_eq!(
14392            pr_merge_plan(Ok(land::OpenPr::One {
14393                url: "u".into(),
14394                title: "t".into()
14395            })),
14396            PrPlan::Adopt {
14397                url: "u".into(),
14398                title: "t".into()
14399            }
14400        );
14401        let PrPlan::Stop(many) =
14402            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14403        else {
14404            panic!("many must stop");
14405        };
14406        assert!(many.contains('a') && many.contains('b'));
14407        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14408            panic!("a failed lookup must stop");
14409        };
14410        assert!(err.contains("bad token"));
14411    }
14412
14413    use super::*;
14414    use crate::run::GateStatus;
14415    use std::collections::BTreeMap;
14416    use std::time::Duration;
14417
14418    fn conductor() -> AgentSpec {
14419        AgentSpec {
14420            id: "conductor".to_owned(),
14421            kind: crate::config::AgentKind::Command,
14422            model: None,
14423            command: vec!["true".to_owned()],
14424            extra_args: Vec::new(),
14425            env: BTreeMap::new(),
14426            prompt_delivery: None,
14427            max_turn_secs: None,
14428        }
14429    }
14430
14431    fn spec(id: &str) -> AgentSpec {
14432        AgentSpec {
14433            id: id.to_owned(),
14434            kind: crate::config::AgentKind::Command,
14435            model: None,
14436            command: vec!["true".to_owned()],
14437            extra_args: Vec::new(),
14438            env: BTreeMap::new(),
14439            prompt_delivery: None,
14440            max_turn_secs: None,
14441        }
14442    }
14443
14444    fn ids(xs: &[&str]) -> BTreeSet<String> {
14445        xs.iter().map(|s| (*s).to_owned()).collect()
14446    }
14447
14448    #[test]
14449    fn pick_successor_skips_an_agent_another_seat_holds() {
14450        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14451        let roster = [spec("a"), spec("b"), spec("c")];
14452        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14453        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14454    }
14455
14456    #[test]
14457    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14458        // The other seat started on c but was handed to d; c is free again.
14459        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14460        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14461        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14462        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14463        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14464    }
14465
14466    #[test]
14467    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14468        let roster = [spec("a"), spec("b")];
14469        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14470        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14471        let carried = ids(&["b"]);
14472        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14473        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14474    }
14475
14476    #[test]
14477    fn pick_successor_returns_none_without_any_untried_successor() {
14478        let roster = [spec("a"), spec("b")];
14479        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14480        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14481        let carried = ids(&["a"]);
14482        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14483    }
14484
14485    #[test]
14486    fn pick_successor_rescue_avoids_another_seats_occupant() {
14487        // b is a carried failure and free; a is held by the other seat.
14488        let roster = [spec("a"), spec("b"), spec("c")];
14489        let carried = ids(&["b", "c"]);
14490        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14491        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14492    }
14493
14494    #[test]
14495    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14496        let roster = [spec("a"), spec("b"), spec("c")];
14497        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14498        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14499    }
14500
14501    #[test]
14502    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14503        let roster = [spec("a"), spec("b"), spec("c")];
14504        let failed = ids(&["a", "b", "c"]);
14505        // Rescue looks at the whole roster, once per id, then runs out.
14506        let mut tried = ids(&["b"]);
14507        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14508        assert_eq!(first.id, "a");
14509        tried.insert(first.id.clone());
14510        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14511        assert_eq!(second.id, "c");
14512        tried.insert(second.id.clone());
14513        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14514    }
14515
14516    #[test]
14517    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14518        let roster = [spec("a"), spec("b")];
14519        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14520        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14521    }
14522
14523    #[test]
14524    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
14525        let roster = [spec("a"), spec("b"), spec("c")];
14526        let h = SeatHistory {
14527            failed: ids(&["a"]),
14528            last_ok: Some("b".to_owned()),
14529            last_fail: None,
14530        };
14531        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
14532        // A last answerer that left the roster, or later failed, is ignored.
14533        let gone = SeatHistory {
14534            last_ok: Some("zzz".to_owned()),
14535            ..h.clone()
14536        };
14537        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
14538        let failed = SeatHistory {
14539            failed: ids(&["a", "b"]),
14540            last_ok: Some("b".to_owned()),
14541            last_fail: None,
14542        };
14543        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
14544    }
14545
14546    #[test]
14547    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
14548        let first = SeatState::new("review-1", "alpha", 7);
14549        let next = handover_seat("review-1", "gamma", 7);
14550        assert_ne!(first.claude_session, next.claude_session);
14551    }
14552
14553    #[test]
14554    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
14555        let mut state = state_with_summary("x", "y");
14556        let a = handover_seat("review-1", "beta", state.next_seat_seed());
14557        let b = handover_seat("review-1", "beta", state.next_seat_seed());
14558        assert_ne!(a.claude_session, b.claude_session);
14559    }
14560
14561    #[test]
14562    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
14563        let roster = [spec("a"), spec("b")];
14564        let h = SeatHistory {
14565            failed: ids(&["a", "b"]),
14566            ..SeatHistory::default()
14567        };
14568        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
14569        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
14570        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
14571    }
14572
14573    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
14574    // fallback loop depends on to terminate: it must walk forward from the
14575    // seat's own position, never restart at the front of the roster, and it
14576    // must never hand back an id already tried, however many times that id
14577    // happens to appear.
14578
14579    #[test]
14580    fn failure_signature_ignores_numbers_and_paths() {
14581        assert_eq!(
14582            failure_signature("exited with Some(2) and no usable output"),
14583            failure_signature("exited with Some(137) and no usable output")
14584        );
14585        assert_eq!(
14586            failure_signature("process exited with no usable output (exit code 2)"),
14587            failure_signature("process exited with no usable output (exit code 137)")
14588        );
14589        for (old, new) in [
14590            (
14591                "exited with Some(2) and no usable output",
14592                "process exited with no usable output (exit code 2)",
14593            ),
14594            (
14595                "exited with None and no usable output",
14596                "process exited with no usable output (exit code unavailable)",
14597            ),
14598        ] {
14599            let previous = FailClass::Other(failure_signature(old));
14600            let current = FailClass::Other(failure_signature(new));
14601            assert_eq!(previous, current, "resumption retains the failure class");
14602            assert!(!should_hand_over(Some(&previous), &current));
14603        }
14604        assert_eq!(
14605            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
14606            failure_signature("cannot open /var/x.txt: denied")
14607        );
14608        assert_ne!(failure_signature("boom"), failure_signature("bang"));
14609    }
14610
14611    #[test]
14612    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
14613        let other = FailClass::Other("x".into());
14614        assert!(should_hand_over(None, &FailClass::Quota));
14615        assert!(should_hand_over(Some(&other), &FailClass::Quota));
14616        assert!(should_hand_over(
14617            Some(&FailClass::Timeout),
14618            &FailClass::Timeout
14619        ));
14620        assert!(should_hand_over(None, &other));
14621        assert!(!should_hand_over(Some(&other), &other));
14622        assert!(should_hand_over(
14623            Some(&other),
14624            &FailClass::Other("y".into())
14625        ));
14626        // A quota or timeout in between ends the run of identical failures.
14627        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
14628        assert!(should_hand_over(Some(&FailClass::Quota), &other));
14629    }
14630
14631    #[test]
14632    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
14633        let a = SeatState::new("judge-1", "alpha", 7);
14634        let b = handover_seat("judge-1", "beta", 7);
14635        assert_ne!(a.claude_session, b.claude_session);
14636        assert_eq!(b.turns, 0);
14637    }
14638
14639    #[test]
14640    fn a_timeout_is_classified_apart_from_other_failures() {
14641        assert_eq!(
14642            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
14643            Some(FailClass::Timeout)
14644        );
14645        assert!(matches!(
14646            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
14647            Some(FailClass::Other(_))
14648        ));
14649    }
14650
14651    #[test]
14652    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
14653        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14654        let tried = BTreeSet::from(["beta".to_owned()]);
14655        // beta sits at index 1; the next candidate is gamma, never alpha —
14656        // which is very likely a different candidate slot's own agent.
14657        let next = next_untried_in_roster(&roster, 1, &tried);
14658        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
14659    }
14660
14661    #[test]
14662    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
14663        let roster = vec![spec("alpha"), spec("beta")];
14664        let tried = BTreeSet::from(["beta".to_owned()]);
14665        // beta is the roster's last entry: nothing follows it, and alpha —
14666        // earlier in the roster, almost certainly a different candidate
14667        // slot's own agent — must not be reached by wrapping back to it.
14668        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14669    }
14670
14671    #[test]
14672    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
14673        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14674        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
14675        // beta (index 1) and gamma (index 2, the only entry after it) have
14676        // both been tried; alpha (index 0) never has, but it comes before
14677        // beta's own position, so there is nothing further for this seat.
14678        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14679    }
14680
14681    #[test]
14682    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
14683        let roster = vec![spec("a"), spec("a"), spec("b")];
14684        let tried = BTreeSet::from(["a".to_owned()]);
14685        let next = next_untried_in_roster(&roster, 0, &tried);
14686        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14687    }
14688
14689    #[test]
14690    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
14691        let roster = vec![spec("a"), spec("b")];
14692        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
14693        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
14694    }
14695
14696    #[test]
14697    fn remove_if_empty_only_ever_takes_a_bare_directory() {
14698        let dir = tempfile::tempdir().unwrap();
14699        let bay = dir.path().join("ffff");
14700
14701        // Not there yet: nothing to do, nothing to panic on.
14702        remove_if_empty(&bay);
14703        assert!(!bay.exists());
14704
14705        // Something still inside - the winner's worktree, or a stray file -
14706        // keeps the directory standing.
14707        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
14708        remove_if_empty(&bay);
14709        assert!(bay.exists(), "non-empty directory must survive");
14710
14711        // Once the last entry is gone, so is the directory itself.
14712        std::fs::remove_dir(bay.join("cand-A")).unwrap();
14713        remove_if_empty(&bay);
14714        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
14715    }
14716
14717    // `round_is_clean` is the exact decision this task fixed: a round with a
14718    // seat that never answered must not read the same as a round every seat
14719    // actually reviewed. These are deterministic and process-free by design —
14720    // the equivalent end-to-end check (a real reviewer timing out under a
14721    // live graph run) is a genuine race against wall-clock contention, and a
14722    // spawn slow enough to blow even a generous budget under a loaded test
14723    // run must not turn this specific regression check flaky.
14724
14725    #[test]
14726    fn a_full_panel_that_found_nothing_is_clean() {
14727        assert!(round_is_clean(
14728            0,
14729            true,
14730            2,
14731            2,
14732            0,
14733            IncompleteReviewPolicy::Block
14734        ));
14735    }
14736
14737    #[test]
14738    fn a_missing_seat_is_never_clean_under_the_default_policy() {
14739        assert!(!round_is_clean(
14740            0,
14741            true,
14742            1,
14743            2,
14744            0,
14745            IncompleteReviewPolicy::Block
14746        ));
14747    }
14748
14749    #[test]
14750    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
14751        assert!(!round_is_clean(
14752            1,
14753            true,
14754            1,
14755            2,
14756            0,
14757            IncompleteReviewPolicy::Warn
14758        ));
14759    }
14760
14761    #[test]
14762    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
14763        assert!(round_is_clean(
14764            0,
14765            true,
14766            1,
14767            2,
14768            0,
14769            IncompleteReviewPolicy::Warn
14770        ));
14771    }
14772
14773    #[test]
14774    fn a_full_panel_with_an_open_finding_is_not_clean() {
14775        assert!(!round_is_clean(
14776            1,
14777            true,
14778            2,
14779            2,
14780            0,
14781            IncompleteReviewPolicy::Block
14782        ));
14783    }
14784
14785    #[test]
14786    fn a_full_panel_with_a_red_e2e_is_not_clean() {
14787        assert!(!round_is_clean(
14788            0,
14789            false,
14790            2,
14791            2,
14792            0,
14793            IncompleteReviewPolicy::Block
14794        ));
14795    }
14796
14797    // The stall this task closes: under the default `block` policy, a seat
14798    // missing only because it was rate limited must not force a wait for a
14799    // session limit that will not lift by the next round. `round_is_clean`
14800    // is where that quorum carve-out lives; the review loop around it never
14801    // changes what a reviewer's vote or a finding's severity means.
14802
14803    #[test]
14804    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
14805        // 1 of 2 answered, and the one missing was quota'd — the exact
14806        // "review-2 rate limited (quota)" shape from the field report.
14807        assert!(round_is_clean(
14808            0,
14809            true,
14810            1,
14811            2,
14812            1,
14813            IncompleteReviewPolicy::Block
14814        ));
14815    }
14816
14817    #[test]
14818    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
14819        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
14820        // not a quota loss (`quota_missing` stays 0) — worth another try.
14821        assert!(!round_is_clean(
14822            0,
14823            true,
14824            1,
14825            2,
14826            0,
14827            IncompleteReviewPolicy::Block
14828        ));
14829    }
14830
14831    #[test]
14832    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
14833        assert!(!round_is_clean(
14834            1,
14835            true,
14836            1,
14837            2,
14838            1,
14839            IncompleteReviewPolicy::Block
14840        ));
14841        assert!(!round_is_clean(
14842            0,
14843            false,
14844            1,
14845            2,
14846            1,
14847            IncompleteReviewPolicy::Block
14848        ));
14849    }
14850
14851    #[test]
14852    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
14853        // Every seat quota'd, nobody answered: there is no panel to decide
14854        // on, so this must fall through to the existing block-and-retry
14855        // fallback rather than call an unreviewed patch clean.
14856        assert!(!round_is_clean(
14857            0,
14858            true,
14859            0,
14860            2,
14861            2,
14862            IncompleteReviewPolicy::Block
14863        ));
14864    }
14865
14866    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
14867        CommandOutcome {
14868            command: "test".to_owned(),
14869            code,
14870            output_tail: String::new(),
14871            duration_ms: 0,
14872            resource_blocked,
14873            ..Default::default()
14874        }
14875    }
14876
14877    #[cfg(unix)]
14878    #[tokio::test]
14879    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
14880        ask_test_home();
14881        let temp = tempfile::tempdir().unwrap();
14882        let mut runner = runner_at(RunStatus::Gating);
14883        let shell = vec!["sh".to_owned(), "-c".to_owned()];
14884        let commands = vec![
14885            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
14886            "touch must-not-run".to_owned(),
14887        ];
14888        let (outcomes, retried, pids) = run_e2e_with_retry(
14889            &mut runner.state,
14890            &shell,
14891            &commands,
14892            temp.path(),
14893            Duration::from_secs(5),
14894            "fixture",
14895            None,
14896        )
14897        .await;
14898        assert_eq!(outcomes.len(), 1);
14899        assert!(outcomes[0].resource_blocked);
14900        assert!(!outcomes[0].build_failed());
14901        assert!(!retried);
14902        assert!(pids.is_empty());
14903        assert!(!temp.path().join("must-not-run").exists());
14904        assert_eq!(
14905            runner.state.resource_block.as_ref().unwrap().kind,
14906            "incremental cache admission"
14907        );
14908    }
14909
14910    #[test]
14911    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
14912        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
14913        assert!(
14914            !verify_inconclusive(&[outcome(Some(1), false)]),
14915            "an ordinary failure is still evidence about the patch"
14916        );
14917        assert!(verify_inconclusive(&[outcome(None, true)]));
14918        assert!(
14919            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
14920            "one inconclusive outcome taints the whole batch"
14921        );
14922        assert!(!verify_inconclusive(&[]));
14923    }
14924
14925    #[tokio::test]
14926    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
14927        // Alive for the first two checks, then dead - confirms the loop
14928        // actually re-polls rather than deciding once and sleeping out the
14929        // ceiling regardless.
14930        let calls = std::sync::atomic::AtomicUsize::new(0);
14931        let started = Instant::now();
14932        wait_for_pids_with(
14933            &[123],
14934            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
14935            Duration::from_millis(5),
14936            Duration::from_secs(5),
14937        )
14938        .await;
14939        assert!(
14940            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
14941            "must keep checking rather than deciding on the first answer"
14942        );
14943        assert!(
14944            started.elapsed() < Duration::from_secs(1),
14945            "must return the moment it is confirmed dead, not wait out the ceiling"
14946        );
14947    }
14948
14949    #[tokio::test]
14950    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
14951        let started = Instant::now();
14952        wait_for_pids_with(
14953            &[123],
14954            |_| true, // never reports dead
14955            Duration::from_millis(5),
14956            Duration::from_millis(30),
14957        )
14958        .await;
14959        let elapsed = started.elapsed();
14960        assert!(
14961            elapsed >= Duration::from_millis(30),
14962            "must not give up before its own ceiling: {elapsed:?}"
14963        );
14964        assert!(
14965            elapsed < Duration::from_secs(1),
14966            "must not wait past its own ceiling either: {elapsed:?}"
14967        );
14968    }
14969
14970    #[tokio::test]
14971    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
14972        let started = Instant::now();
14973        wait_for_pids_with(
14974            &[],
14975            |_| true,
14976            Duration::from_secs(5),
14977            Duration::from_secs(5),
14978        )
14979        .await;
14980        assert!(
14981            started.elapsed() < Duration::from_millis(200),
14982            "an empty pid list has nothing to confirm"
14983        );
14984    }
14985
14986    // `review_conclusion` is the exact decision the review hand-off task
14987    // fixed: a round budget spent (or a tree that stopped moving) must not
14988    // collapse into `Blocked` regardless of what verification actually
14989    // said. Deterministic and process-free for the same reason the
14990    // `round_is_clean` family above is.
14991    fn review_round(
14992        clean: bool,
14993        blocking: usize,
14994        answered: usize,
14995        expected: usize,
14996        progressed: bool,
14997        e2e_ok: bool,
14998    ) -> ReviewRound {
14999        ReviewRound {
15000            round: 1,
15001            head: "h".to_owned(),
15002            verified_head: None,
15003            verified_at: None,
15004            reviews: Vec::new(),
15005            e2e: vec![CommandOutcome {
15006                command: "test".to_owned(),
15007                code: Some(if e2e_ok { 0 } else { 1 }),
15008                output_tail: String::new(),
15009                duration_ms: 0,
15010                resource_blocked: false,
15011                ..Default::default()
15012            }],
15013            verify_retried: false,
15014            e2e_deferred: false,
15015            e2e_defer_reason: None,
15016            fix: None,
15017            blocking,
15018            answered,
15019            expected,
15020            clean,
15021            progressed,
15022            vote_split: false,
15023            reconsideration: Vec::new(),
15024            verdict: None,
15025        }
15026    }
15027
15028    #[test]
15029    fn review_conclusion_is_none_when_nothing_has_run() {
15030        assert_eq!(review_conclusion(&[], 3), None);
15031    }
15032
15033    #[test]
15034    fn review_conclusion_is_none_while_rounds_remain() {
15035        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
15036        assert_eq!(review_conclusion(&rounds, 3), None);
15037    }
15038
15039    #[test]
15040    fn review_conclusion_is_gating_once_a_round_is_clean() {
15041        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
15042        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
15043    }
15044
15045    #[test]
15046    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
15047        let rounds = vec![
15048            review_round(false, 1, 2, 2, true, true),
15049            review_round(false, 1, 2, 2, true, true),
15050        ];
15051        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
15052    }
15053
15054    #[test]
15055    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
15056        let rounds = vec![
15057            review_round(false, 1, 2, 2, true, true),
15058            review_round(false, 1, 2, 2, true, false),
15059        ];
15060        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
15061    }
15062
15063    #[test]
15064    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
15065        // Magi never got a command to run against this round's own head — a
15066        // resource-blocked attempt, not a red one — so this must never
15067        // settle on `Blocked` the way a genuine e2e failure would. `None`
15068        // here is what tells `Runner::review_loop` to retry the check
15069        // itself rather than trust this cheap recomputation with a verdict
15070        // it cannot actually produce.
15071        let mut blocked = review_round(false, 1, 2, 2, true, false);
15072        blocked.e2e[0].resource_blocked = true;
15073        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
15074        assert_eq!(review_conclusion(&rounds, 2), None);
15075    }
15076
15077    #[test]
15078    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
15079        // Missing input, not a verified tree — never a hand-off candidate.
15080        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
15081        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
15082    }
15083
15084    #[test]
15085    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15086        let rounds = vec![
15087            review_round(false, 1, 2, 2, false, true),
15088            review_round(false, 1, 2, 2, false, true),
15089        ];
15090        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15091    }
15092
15093    fn secs(n: u64) -> Duration {
15094        Duration::from_secs(n)
15095    }
15096
15097    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15098    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15099    #[tokio::test]
15100    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15101        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15102        if std::env::var_os(CHILD).is_none() {
15103            // Other tests reconcile every run in the process-global home,
15104            // briefly taking owner locks. This ancestry test expects an idle
15105            // predecessor, so give it its own process and pinned test home.
15106            let output = std::process::Command::new(std::env::current_exe().unwrap())
15107                .args([
15108                    "--exact",
15109                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15110                    "--nocapture",
15111                ])
15112                .env(CHILD, "1")
15113                .env_remove("MAGI_WORKER_HOME")
15114                .env_remove("MAGI_WORKER_ID")
15115                .output()
15116                .unwrap();
15117            assert!(
15118                output.status.success()
15119                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15120                "{}\n{}",
15121                String::from_utf8_lossy(&output.stdout),
15122                String::from_utf8_lossy(&output.stderr)
15123            );
15124            return;
15125        }
15126        ask_test_home();
15127        let tmp = tempfile::tempdir().unwrap();
15128        let repo = tmp.path().join("repo");
15129        std::fs::create_dir_all(&repo).unwrap();
15130        init_repo(&repo);
15131        let g = |args: &[&str]| {
15132            let out = std::process::Command::new("git")
15133                .args(args)
15134                .current_dir(&repo)
15135                .quiet()
15136                .output()
15137                .unwrap();
15138            assert!(
15139                out.status.success(),
15140                "{}",
15141                String::from_utf8_lossy(&out.stderr)
15142            );
15143        };
15144        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15145        g(&["checkout", "-b", "historical"]);
15146        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15147        g(&["add", "."]);
15148        g(&["commit", "-m", "old alternative"]);
15149        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15150        g(&["checkout", "-b", "magi/task-selected", &base]);
15151        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15152        g(&["add", "."]);
15153        g(&["commit", "-m", "measurement infrastructure"]);
15154        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15155        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15156        g(&["add", "."]);
15157        g(&["commit", "-m", "dependent implementation"]);
15158        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15159        g(&["checkout", "main"]);
15160        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15161        g(&["add", "."]);
15162        g(&["commit", "-m", "unrelated base change"]);
15163        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15164        let origin = tmp.path().join("origin.git");
15165        g(&[
15166            "clone",
15167            "--bare",
15168            repo.to_str().unwrap(),
15169            origin.to_str().unwrap(),
15170        ]);
15171        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15172        g(&["fetch", "origin"]);
15173        let selection = crate::pr_recovery::Selection {
15174            url: "https://example.test/project/pull/1".into(),
15175            branch: "magi/task-selected".into(),
15176            head: head.clone(),
15177            source_head: None,
15178            source_run: None,
15179            source_proof: None,
15180            disposition: Some(crate::pr_recovery::Disposition::Review),
15181            instruction: "preserve measured behavior".into(),
15182            approved_at: jiff::Timestamp::now(),
15183        };
15184        let mut template = runner_at(RunStatus::Reviewing);
15185        template.state.repo = repo.clone();
15186        template.state.base_commit = current.clone();
15187        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15188        template.state.origin = Some(crate::run::Origin::queue("selected"));
15189        template.state.pr_head = Some(selection.branch.clone());
15190        template.state.pr_recovery = Some(selection.clone());
15191        let mut runner =
15192            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15193                .await
15194                .unwrap();
15195        let wt = runner.state.winner().unwrap().worktree.clone();
15196        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15197        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15198        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15199        assert!(runner.state.seeds.is_empty());
15200        assert_eq!(runner.state.instruction, "preserve measured behavior");
15201        runner.sync_to_base().await.unwrap();
15202        assert_eq!(
15203            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15204            "prerequisite"
15205        );
15206        assert_eq!(
15207            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15208            "measured implementation"
15209        );
15210        assert_eq!(
15211            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15212            "current main change"
15213        );
15214        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15215        assert_eq!(
15216            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15217            head
15218        );
15219
15220        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15221        let mut partial = runner_at(RunStatus::Reviewing);
15222        partial.state.repo = repo.clone();
15223        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15224        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15225            run: Some("exit 1".into()),
15226            ..Default::default()
15227        }];
15228        let selection = runner.state.pr_recovery.clone().unwrap();
15229        partial.state.pr_recovery = Some(selection.clone());
15230        partial.state.pr_head = Some(selection.branch.clone());
15231        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15232        let id = partial.state.id.clone();
15233        let error = match Runner::open_selected(
15234            &repo,
15235            partial.state,
15236            partial.roles,
15237            1,
15238            runner.state.base_commit.clone(),
15239            selection,
15240        )
15241        .await
15242        {
15243            Ok(_) => panic!("setup must fail"),
15244            Err(e) => e,
15245        };
15246        assert_eq!(
15247            error
15248                .downcast_ref::<crate::run::StartupFailure>()
15249                .unwrap()
15250                .run,
15251            id
15252        );
15253        let failed = RunState::load(&id).unwrap();
15254        assert_eq!(failed.status, RunStatus::Failed);
15255        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15256        assert!(Runner::resume(&id).is_err());
15257        runner.state.status = RunStatus::Ready;
15258        runner.state.driver_exited = true;
15259        runner.state.save().unwrap();
15260        let mut retry = runner_at(RunStatus::Reviewing);
15261        retry.state.repo = repo.clone();
15262        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15263        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15264        reselected.approved_at = jiff::Timestamp::now();
15265        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15266        retry.state.pr_head = Some(reselected.branch.clone());
15267        retry.state.pr_recovery = Some(reselected.clone());
15268        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15269            .await
15270            .unwrap();
15271        let restarted = Runner::open_selected(
15272            &repo,
15273            retry.state,
15274            retry.roles,
15275            1,
15276            runner.state.base_commit.clone(),
15277            reselected,
15278        )
15279        .await
15280        .unwrap();
15281        assert_eq!(
15282            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15283                .await
15284                .unwrap(),
15285            head
15286        );
15287        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15288        assert_eq!(
15289            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15290            head
15291        );
15292    }
15293
15294    #[tokio::test]
15295    #[cfg(unix)]
15296    async fn fallback_and_interrupted_restoration_require_coordination() {
15297        use std::os::fd::AsRawFd as _;
15298        ask_test_home();
15299        let tmp = tempfile::tempdir().unwrap();
15300        let mut runner = registered_runner(tmp.path()).await;
15301        runner.state.config.graph.timeout_resource_wait = 1;
15302        let winner = runner.state.candidates[0].clone();
15303        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15304        let leftover = winner.worktree.join("leftover");
15305        std::fs::write(&leftover, "untrusted edits").unwrap();
15306        let next = tmp.path().join("next-fixer");
15307        let mut failed = spec("first");
15308        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15309        let mut successor = spec("second");
15310        successor.command = vec![
15311            "sh".into(),
15312            "-c".into(),
15313            format!("touch '{}'; echo done", next.display()),
15314        ];
15315        let attempts = vec![
15316            (failed.clone(), "first".into()),
15317            (successor.clone(), "second".into()),
15318        ];
15319        let lock_path = runner.state.repo.join(".git/updater.lock");
15320        let external = std::fs::File::create(&lock_path).unwrap();
15321        assert_eq!(
15322            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15323            0
15324        );
15325        let artifacts = tmp.path().join("artifacts");
15326        let build = |spec, seat| SeatJob {
15327            spec,
15328            seat,
15329            cwd: winner.worktree.clone(),
15330            prompt: "fixture".into(),
15331            timeout: Duration::from_secs(10),
15332            allow_write: true,
15333            sessions: false,
15334            artifacts: artifacts.clone(),
15335            stem: "fix".into(),
15336            handover: None,
15337        };
15338        let (_, _, out) = runner
15339            .ask_fixer_among(
15340                attempts.clone(),
15341                "graft",
15342                None,
15343                Some((&winner.worktree, &head)),
15344                build,
15345            )
15346            .await;
15347        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15348        assert!(leftover.exists(), "contention must prevent clean");
15349        assert!(!next.exists());
15350        assert!(runner.state.handovers.is_empty());
15351        // Early interrupted-repair rollback uses the same protected route.
15352        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15353            from_run: "earlier".into(),
15354            generation: 1,
15355            mode: crate::recovery::Mode::VerifyRepair,
15356            reasons: Vec::new(),
15357            reviewed_head: None,
15358            rounds: Vec::new(),
15359            open_findings: Vec::new(),
15360            evidence: None,
15361            criteria_inherited: true,
15362            repair: crate::recovery::Repair::Started {
15363                before: head.clone(),
15364            },
15365        });
15366        assert!(
15367            runner
15368                .recovery_repair(&winner)
15369                .await
15370                .unwrap_err()
15371                .is::<crate::repo_lock::ResourceBlocked>()
15372        );
15373        assert!(matches!(
15374            runner.state.recovery.as_ref().unwrap().repair,
15375            crate::recovery::Repair::Started { .. }
15376        ));
15377        assert!(leftover.exists());
15378        drop(external);
15379        runner.recovery_repair(&winner).await.unwrap();
15380        assert!(!leftover.exists());
15381        assert!(matches!(
15382            runner.state.recovery.as_ref().unwrap().repair,
15383            crate::recovery::Repair::Done { .. }
15384        ));
15385        // A hard lock-open failure also leaves HEAD and untracked work intact.
15386        std::fs::remove_file(&lock_path).unwrap();
15387        std::fs::create_dir(&lock_path).unwrap();
15388        std::fs::write(&leftover, "untrusted edits").unwrap();
15389        let (_, _, out) = runner
15390            .ask_fixer_among(
15391                attempts,
15392                "graft",
15393                None,
15394                Some((&winner.worktree, &head)),
15395                build,
15396            )
15397            .await;
15398        assert!(matches!(out, AgentOutcome::Failed(_)));
15399        assert!(leftover.exists());
15400        assert!(!next.exists());
15401        assert_eq!(
15402            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15403            head
15404        );
15405    }
15406
15407    #[cfg(unix)]
15408    async fn registered_runner(root: &Path) -> Runner {
15409        repository_runner(root, crate::config::test_coordination()).await
15410    }
15411
15412    async fn repository_runner(
15413        root: &Path,
15414        coordination: Option<crate::config::Coordination>,
15415    ) -> Runner {
15416        ask_test_home();
15417        let repo = root.join("repo");
15418        std::fs::create_dir_all(&repo).unwrap();
15419        init_repo(&repo);
15420        if coordination.is_some() {
15421            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15422        }
15423        let mut runner = runner_at(RunStatus::Prep);
15424        runner.state.repo = repo.clone();
15425        runner.state.config.coordination = coordination;
15426        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15427        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15428        runner.state.config.graph.advise = false;
15429        runner.roles.implementers = vec![spec("implement")];
15430        runner.roles.judges = vec![spec("judge")];
15431        runner.prep().await.unwrap();
15432        runner
15433    }
15434
15435    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15436
15437    #[tokio::test]
15438    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15439        let tmp = tempfile::tempdir().unwrap();
15440        let mut runner = repository_runner(tmp.path(), None).await;
15441        let prompts = runner.state.config.prompts.clone();
15442        let run = runner.state.id.clone();
15443        let ctx = WaveCtx {
15444            carry_seats: false,
15445            pauses: None,
15446            run: &run,
15447            node: "advise",
15448            prompts: &prompts,
15449            cache: None,
15450            round: None,
15451        };
15452        let jobs: Vec<_> = ["alpha", "beta"]
15453            .into_iter()
15454            .map(|id| SeatJob {
15455                spec: scripted(id, AUTH_OUTAGE),
15456                seat: SeatState::new(id, id, 7),
15457                prompt: "propose".into(),
15458                cwd: runner.state.candidates[0].worktree.clone(),
15459                timeout: Duration::from_secs(10),
15460                allow_write: false,
15461                sessions: false,
15462                artifacts: agent::artifacts_dir(&runner.state.dir()),
15463                stem: id.into(),
15464                handover: None,
15465            })
15466            .collect();
15467        let mut losses = Vec::new();
15468        let results = ask_wave_with(
15469            jobs.clone(),
15470            runner.sem.clone(),
15471            2,
15472            &[],
15473            &ctx,
15474            &mut losses,
15475            &mut runner.state,
15476            &|_: &str| Ok(()),
15477        )
15478        .await;
15479        assert!(
15480            results
15481                .iter()
15482                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15483        );
15484        assert_eq!(runner.state.quota.len(), 2);
15485        assert!(
15486            runner
15487                .state
15488                .quota
15489                .iter()
15490                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15491        );
15492        assert!(!runner.state.advise_attempted);
15493        runner.stop_for_resource().unwrap();
15494        assert_eq!(runner.state.status, RunStatus::Blocked);
15495        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15496        assert_eq!(
15497            runner.state.resource_block.as_ref().unwrap().kind,
15498            "agent authentication"
15499        );
15500        // A machine loss followed by an ordinary failure is not evidence
15501        // that the whole node was unavailable, and must not earn a refund.
15502        runner.state.resource_block = None;
15503        runner.state.quota.clear();
15504        let mut mixed = jobs;
15505        mixed[1].spec.command = vec!["false".into()];
15506        let results = ask_wave_with(
15507            mixed,
15508            runner.sem.clone(),
15509            0,
15510            &[],
15511            &ctx,
15512            &mut losses,
15513            &mut runner.state,
15514            &|_: &str| Ok(()),
15515        )
15516        .await;
15517        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15518        assert!(runner.state.resource_block.is_none());
15519        assert_eq!(losses.len(), 1);
15520    }
15521
15522    #[tokio::test]
15523    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
15524        let tmp = tempfile::tempdir().unwrap();
15525        let mut runner = repository_runner(tmp.path(), None).await;
15526        let implementer = scripted("implement", AUTH_OUTAGE);
15527        runner.roles.implementers = vec![implementer.clone()];
15528        runner.state.config.agents = vec![implementer];
15529        runner.implement().await.unwrap();
15530        assert_eq!(runner.state.status, RunStatus::Blocked);
15531        assert_eq!(runner.state.quota.len(), 1);
15532        assert_eq!(
15533            runner.state.quota[0].cause,
15534            agent::QuotaCause::Authentication
15535        );
15536        let candidate = &runner.state.candidates[0];
15537        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
15538        assert_eq!(runner.state.seats["impl-A"].turns, 1);
15539    }
15540
15541    #[tokio::test]
15542    #[cfg(unix)]
15543    async fn parked_implementer_persists_completed_work() {
15544        for registered in [false, true] {
15545            let tmp = tempfile::tempdir().unwrap();
15546            let mut runner = registered_runner(tmp.path()).await;
15547            if !registered {
15548                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
15549            }
15550            let marker = tmp.path().join("started");
15551            let release = tmp.path().join("release");
15552            let mut implementer = spec("implement");
15553            implementer.command = vec![
15554                "sh".into(),
15555                "-c".into(),
15556                format!(
15557                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
15558                    marker.display(),
15559                    release.display()
15560                ),
15561            ];
15562            runner.roles.implementers = vec![implementer.clone()];
15563            runner.state.config.agents = vec![implementer];
15564            let pause = runner.pause.clone();
15565            let (result, ()) = tokio::join!(runner.implement(), async {
15566                tokio::time::timeout(Duration::from_secs(10), async {
15567                    while !marker.exists() {
15568                        tokio::time::sleep(Duration::from_millis(10)).await;
15569                    }
15570                })
15571                .await
15572                .unwrap();
15573                pause.park();
15574                std::fs::write(&release, "go").unwrap();
15575            });
15576            result.unwrap();
15577            let candidate = &runner.state.candidates[0];
15578            assert!(candidate.commits > 0, "{candidate:?}");
15579            assert!(candidate.summary.contains("saved-result"));
15580            assert_eq!(candidate.files, 1);
15581            let before = candidate.commits;
15582            runner.implement().await.unwrap();
15583            assert_eq!(runner.state.candidates[0].commits, before);
15584        }
15585    }
15586
15587    #[tokio::test]
15588    #[cfg(unix)]
15589    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
15590        let tmp = tempfile::tempdir().unwrap();
15591        let mut runner = registered_runner(tmp.path()).await;
15592        let winner = runner.state.candidates[0].clone();
15593        let cache = tmp.path().join("cache");
15594        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
15595        runner.state.config.graph.timeout_resource_wait = 0;
15596        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
15597        let crate::cache::AcquireOutcome::Acquired(held) =
15598            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
15599        else {
15600            panic!("cache must be free")
15601        };
15602        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15603            from_run: "earlier".into(),
15604            generation: 1,
15605            mode: crate::recovery::Mode::VerifyRepair,
15606            reasons: Vec::new(),
15607            reviewed_head: None,
15608            rounds: Vec::new(),
15609            open_findings: Vec::new(),
15610            evidence: None,
15611            criteria_inherited: true,
15612            repair: crate::recovery::Repair::NotStarted,
15613        });
15614        runner.recovery_repair(&winner).await.unwrap();
15615        assert!(matches!(
15616            runner.state.recovery.as_ref().unwrap().repair,
15617            crate::recovery::Repair::WaitingForRestore { .. }
15618        ));
15619        drop(held);
15620        runner.state.resource_block = None;
15621        runner.state.config.graph.timeout_resource_wait = 1;
15622        runner.recovery_repair(&winner).await.unwrap();
15623        assert!(matches!(
15624            runner.state.recovery.as_ref().unwrap().repair,
15625            crate::recovery::Repair::Done { .. }
15626        ));
15627        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
15628    }
15629
15630    #[tokio::test]
15631    #[cfg(unix)]
15632    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
15633        use std::os::fd::AsRawFd as _;
15634        for graft in [false, true] {
15635            let tmp = tempfile::tempdir().unwrap();
15636            let mut runner = registered_runner(tmp.path()).await;
15637            runner.state.config.graph.timeout_resource_wait = 1;
15638            let winner = runner.state.candidates[0].clone();
15639            let marker = tmp.path().join("fixer-started");
15640            let mut fixer = spec("fixer");
15641            fixer.command = vec![
15642                "sh".into(),
15643                "-c".into(),
15644                format!("echo started >> '{}'; echo done", marker.display()),
15645            ];
15646            runner.roles.fixer = Some(vec![fixer]);
15647            if graft {
15648                let mut loser = winner.clone();
15649                loser.label = 'B';
15650                loser.index = 1;
15651                runner.state.candidates.push(loser);
15652                runner.state.config.graph.graft_runner_up = true;
15653                runner.state.tally = Some(Tally {
15654                    first_choice: BTreeMap::new(),
15655                    borda: BTreeMap::new(),
15656                    winner: winner.label,
15657                    rankings: 1,
15658                    unanimous_initial: true,
15659                    deliberated: false,
15660                    changed_votes: 0,
15661                    unanimous_final: true,
15662                    tie_break: None,
15663                    judges: 1,
15664                    present: 1,
15665                    quorum: 1,
15666                    met_quorum: true,
15667                    uncontested: None,
15668                });
15669                runner.state.judgements.push(crate::run::Judgement {
15670                    judge: 1,
15671                    seat: "judge-1".into(),
15672                    agent: "judge".into(),
15673                    ranking: vec![winner.label, 'B'],
15674                    reasons: BTreeMap::new(),
15675                    confidence: None,
15676                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
15677                    order: vec![0, 1],
15678                    failed: None,
15679                    duration_ms: 0,
15680                });
15681            } else {
15682                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15683                    from_run: "earlier".into(),
15684                    generation: 1,
15685                    mode: crate::recovery::Mode::VerifyRepair,
15686                    reasons: Vec::new(),
15687                    reviewed_head: None,
15688                    rounds: Vec::new(),
15689                    open_findings: Vec::new(),
15690                    evidence: None,
15691                    criteria_inherited: true,
15692                    repair: crate::recovery::Repair::NotStarted,
15693                });
15694            }
15695            let reader = crate::repo_lock::SeatLease::for_checkout(
15696                &winner.worktree,
15697                false,
15698                crate::config::test_coordination().as_ref(),
15699            )
15700            .await
15701            .unwrap();
15702            let pause = runner.pause.clone();
15703            let (result, ()) = tokio::join!(
15704                async {
15705                    if graft {
15706                        runner.graft().await
15707                    } else {
15708                        runner.recovery_repair(&winner).await
15709                    }
15710                },
15711                async {
15712                    tokio::time::sleep(Duration::from_millis(100)).await;
15713                    pause.park();
15714                }
15715            );
15716            result.unwrap();
15717            assert!(!marker.exists(), "a blocked seat must not spawn");
15718            // Exercise the persisted state, as a binary replacement/resume does.
15719            runner.state = RunState::load(&runner.state.id).unwrap();
15720            if graft {
15721                assert_eq!(
15722                    runner.state.graft.as_ref().unwrap().outcome,
15723                    GraftOutcome::WaitingForRestore
15724                );
15725            } else {
15726                assert!(matches!(
15727                    runner.state.recovery.as_ref().unwrap().repair,
15728                    crate::recovery::Repair::WaitingForRestore { .. }
15729                ));
15730            }
15731            drop(reader);
15732            runner.pause = Pause::new();
15733            runner.state.resource_block = None;
15734            // Deferred restoration must still respect an external lock owner.
15735            let external =
15736                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15737            assert_eq!(
15738                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15739                0
15740            );
15741            let leftover = winner.worktree.join("leftover");
15742            std::fs::write(&leftover, "earlier fallback edits").unwrap();
15743            let result = if graft {
15744                runner.graft().await
15745            } else {
15746                runner.recovery_repair(&winner).await
15747            };
15748            assert!(
15749                result
15750                    .unwrap_err()
15751                    .is::<crate::repo_lock::ResourceBlocked>()
15752            );
15753            assert!(leftover.exists());
15754            assert!(!marker.exists());
15755            drop(external);
15756            runner.state.resource_block = None;
15757            let result = if graft {
15758                runner.graft().await
15759            } else {
15760                runner.recovery_repair(&winner).await
15761            };
15762            result.unwrap();
15763            assert!(!leftover.exists(), "restore must precede retry");
15764            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
15765            if graft {
15766                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15767            } else {
15768                assert!(matches!(
15769                    runner.state.recovery.as_ref().unwrap().repair,
15770                    crate::recovery::Repair::Done { .. }
15771                ));
15772            }
15773        }
15774    }
15775
15776    #[tokio::test]
15777    #[cfg(unix)]
15778    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
15779        use std::os::fd::AsRawFd as _;
15780        let tmp = tempfile::tempdir().unwrap();
15781        let mut runner = registered_runner(tmp.path()).await;
15782        runner.state.config.graph.timeout_resource_wait = 1;
15783        let winner = runner.state.candidates[0].clone();
15784        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15785        runner.state.tally = Some(Tally {
15786            first_choice: BTreeMap::new(),
15787            borda: BTreeMap::new(),
15788            winner: winner.label,
15789            rankings: 0,
15790            unanimous_initial: false,
15791            deliberated: false,
15792            changed_votes: 0,
15793            unanimous_final: false,
15794            tie_break: None,
15795            judges: 0,
15796            present: 0,
15797            quorum: 0,
15798            met_quorum: true,
15799            uncontested: Some("fixture".into()),
15800        });
15801        runner.state.graft = Some(GraftRecord {
15802            pre: pre.clone(),
15803            post: None,
15804            lines: None,
15805            limit: None,
15806            agent: None,
15807            outcome: GraftOutcome::Running,
15808            requested: Vec::new(),
15809            adoption: None,
15810            adoption_error: None,
15811        });
15812        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
15813        git::commit_all(&winner.worktree, "unfinished graft")
15814            .await
15815            .unwrap();
15816        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15817        let leftover = winner.worktree.join("leftover");
15818        std::fs::write(&leftover, "untrusted edits").unwrap();
15819        let path = runner.state.repo.join(".git/updater.lock");
15820        let external = std::fs::File::create(&path).unwrap();
15821        assert_eq!(
15822            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15823            0
15824        );
15825        assert!(
15826            runner
15827                .graft()
15828                .await
15829                .unwrap_err()
15830                .is::<crate::repo_lock::ResourceBlocked>()
15831        );
15832        assert!(matches!(
15833            runner.state.graft.as_ref().unwrap().outcome,
15834            GraftOutcome::Running
15835        ));
15836        assert_eq!(
15837            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15838            unfinished
15839        );
15840        assert!(leftover.exists());
15841        drop(external);
15842        std::fs::remove_file(&path).unwrap();
15843        std::fs::create_dir(&path).unwrap();
15844        assert!(runner.graft().await.is_err());
15845        assert!(matches!(
15846            runner.state.graft.as_ref().unwrap().outcome,
15847            GraftOutcome::Running
15848        ));
15849        assert_eq!(
15850            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15851            unfinished
15852        );
15853        assert!(leftover.exists());
15854        std::fs::remove_dir(&path).unwrap();
15855        runner.graft().await.unwrap();
15856        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15857        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
15858        assert!(!leftover.exists());
15859    }
15860
15861    #[tokio::test]
15862    #[cfg(unix)]
15863    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
15864        use std::os::fd::AsRawFd as _;
15865        let tmp = tempfile::tempdir().unwrap();
15866        let mut runner = registered_runner(tmp.path()).await;
15867        runner.state.prep_complete = Some(false);
15868        runner.state.config.graph.timeout_resource_wait = 1;
15869        runner.state.save().unwrap();
15870        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15871        assert_eq!(
15872            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15873            0
15874        );
15875        runner.execute().await.unwrap();
15876        let disk = RunState::load(&runner.state.id).unwrap();
15877        assert!(disk.driver_exited);
15878        assert_eq!(disk.driver_pid, None);
15879        assert_eq!(runner.state.status, RunStatus::Blocked);
15880        assert_eq!(
15881            runner.state.resource_block.as_ref().unwrap().kind,
15882            "repository coordination"
15883        );
15884        assert!(runner.state.prep_failure.is_none());
15885        assert!(runner.state.seats.is_empty());
15886        runner.pause.park();
15887        // Include headroom for Git subprocesses under parallel test load;
15888        // the repository contention deadline itself remains one second.
15889        tokio::time::timeout(Duration::from_secs(10), runner.execute())
15890            .await
15891            .unwrap()
15892            .unwrap();
15893        assert!(runner.state.parked);
15894        assert!(runner.state.prep_failure.is_none());
15895        let disk = RunState::load(&runner.state.id).unwrap();
15896        assert!(disk.driver_exited);
15897        assert_eq!(disk.driver_pid, None);
15898    }
15899
15900    #[tokio::test]
15901    #[cfg(unix)]
15902    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
15903        use std::os::fd::AsRawFd as _;
15904        let tmp = tempfile::tempdir().unwrap();
15905        let mut runner = registered_runner(tmp.path()).await;
15906        runner.state.prep_complete = Some(false);
15907        runner.state.config.graph.timeout_resource_wait = 30;
15908        runner.state.save().unwrap();
15909        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15910        assert_eq!(
15911            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15912            0
15913        );
15914        assert!(
15915            tokio::time::timeout(Duration::from_millis(100), runner.execute())
15916                .await
15917                .is_err()
15918        );
15919        let disk = RunState::load(&runner.state.id).unwrap();
15920        assert!(disk.driver_exited);
15921        assert_eq!(disk.driver_pid, None);
15922        assert!(disk.status.resumable());
15923        assert!(runner.state.driver_exited);
15924        assert_eq!(runner.state.driver_pid, None);
15925        runner.state.save().unwrap();
15926        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
15927    }
15928
15929    #[tokio::test]
15930    #[cfg(unix)]
15931    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
15932        let tmp = tempfile::tempdir().unwrap();
15933        let mut runner = registered_runner(tmp.path()).await;
15934        let winner = runner.state.candidates[0].clone();
15935        let cache = tmp.path().join("cache");
15936        let started = tmp.path().join("pre-gate-started");
15937        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
15938        runner.state.config.verify.gate =
15939            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
15940        let home = crate::run::home();
15941        let owner =
15942            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
15943        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
15944            crate::cache::AcquireOutcome::Acquired(g) => g,
15945            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
15946        };
15947        let mut gate = Box::pin(runner.run_gate(&winner));
15948        assert!(
15949            tokio::time::timeout(Duration::from_millis(150), &mut gate)
15950                .await
15951                .is_err()
15952        );
15953        assert!(!started.exists(), "pre-gate must wait for the cache too");
15954        // Simulate the wave that already owns the cache entering invoke.
15955        // It must obtain the editor reservation and finish without waiting
15956        // for the gate that is queued behind its cache.
15957        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
15958        let editor = crate::repo_lock::SeatLease::checkout_with(
15959            &winner.worktree,
15960            true,
15961            crate::config::test_coordination().as_ref(),
15962            &wait,
15963        )
15964        .await
15965        .unwrap();
15966        drop(editor);
15967        guard.release();
15968        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
15969            .await
15970            .unwrap()
15971            .unwrap();
15972        drop(gate);
15973        assert!(outcomes.iter().all(CommandOutcome::ok));
15974        assert!(started.exists());
15975    }
15976
15977    #[tokio::test]
15978    #[cfg(unix)]
15979    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
15980        use std::os::fd::AsRawFd as _;
15981
15982        ask_test_home();
15983        let tmp = tempfile::tempdir().unwrap();
15984        let repo = tmp.path().join("repo");
15985        std::fs::create_dir_all(&repo).unwrap();
15986        init_repo(&repo);
15987        let common = repo.join(".git");
15988        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
15989        let mut runner = runner_at(RunStatus::Prep);
15990        runner.state.repo = repo.clone();
15991        runner.state.config.coordination = crate::config::test_coordination();
15992        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15993        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
15994        runner.state.config.graph.advise = false;
15995        runner.roles.implementers = vec![spec("implement")];
15996        runner.roles.judges = vec![spec("judge")];
15997        runner.prep().await.unwrap();
15998        let winner = runner.state.candidates[0].clone();
15999        // Emulate edits already left by a completed seat. The fixture CLI
16000        // only reports completion; it performs no repository operations.
16001        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16002        let completed = tmp.path().join("seat-completed");
16003        runner.roles.implementers[0].command = vec![
16004            "sh".into(),
16005            "-c".into(),
16006            format!("touch '{}'; echo completed", completed.display()),
16007        ];
16008        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16009        assert_eq!(
16010            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16011            0
16012        );
16013        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16014        let mut implement = Box::pin(runner.implement());
16015        tokio::select! {
16016            result = &mut implement => panic!("rescue must wait: {result:?}"),
16017            result = tokio::time::timeout(Duration::from_secs(10), async {
16018                while !completed.exists() {
16019                    tokio::time::sleep(Duration::from_millis(20)).await;
16020                }
16021            }) => result.unwrap(),
16022        }
16023        assert!(
16024            tokio::time::timeout(Duration::from_millis(200), &mut implement)
16025                .await
16026                .is_err()
16027        );
16028        assert_eq!(
16029            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16030            before
16031        );
16032        assert_eq!(
16033            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16034            0
16035        );
16036        tokio::time::timeout(Duration::from_secs(10), &mut implement)
16037            .await
16038            .unwrap()
16039            .unwrap();
16040        drop(implement);
16041        assert_ne!(
16042            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16043            before
16044        );
16045        assert!(git::is_clean(&winner.worktree).await.unwrap());
16046
16047        let started = tmp.path().join("pre-gate-started");
16048        let proceed = tmp.path().join("pre-gate-proceed");
16049        let checked = tmp.path().join("gate-ran");
16050        runner.state.config.verify.pre_gate = vec![format!(
16051            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16052            started.display(),
16053            proceed.display()
16054        )];
16055        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
16056        assert_eq!(
16057            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16058            0
16059        );
16060        let mut gate = Box::pin(runner.run_gate(&winner));
16061        assert!(
16062            tokio::time::timeout(Duration::from_millis(200), &mut gate)
16063                .await
16064                .is_err()
16065        );
16066        assert!(!started.exists());
16067        assert!(!checked.exists());
16068        assert!(git::is_clean(&winner.worktree).await.unwrap());
16069        assert_eq!(
16070            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16071            0
16072        );
16073        tokio::select! {
16074            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
16075            result = tokio::time::timeout(Duration::from_secs(10), async {
16076                while !started.exists() {
16077                    tokio::time::sleep(Duration::from_millis(20)).await;
16078                }
16079            }) => result.unwrap(),
16080        }
16081        assert_eq!(
16082            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16083            -1,
16084            "mechanical edits must hold the real lock"
16085        );
16086        std::fs::write(proceed, "ready").unwrap();
16087        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16088            .await
16089            .unwrap()
16090            .unwrap();
16091        drop(gate);
16092        assert!(outcomes.iter().all(CommandOutcome::ok));
16093        assert!(checked.exists());
16094        assert!(runner.state.pre_gate_commit.is_some());
16095        assert!(git::is_clean(&winner.worktree).await.unwrap());
16096        assert_eq!(
16097            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16098            0,
16099            "gate completion must release coordination"
16100        );
16101        drop(outsider);
16102        std::fs::remove_file(common.join("updater.lock")).unwrap();
16103        std::fs::create_dir(common.join("updater.lock")).unwrap();
16104        std::fs::remove_file(&started).unwrap();
16105        std::fs::remove_file(&checked).unwrap();
16106        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16107        let error = runner.run_gate(&winner).await.unwrap_err();
16108        assert!(
16109            error
16110                .to_string()
16111                .contains("acquire mandatory repository lock")
16112        );
16113        assert!(
16114            !started.exists(),
16115            "failed acquisition must prevent pre-gate"
16116        );
16117        assert!(!checked.exists(), "failed acquisition must prevent gate");
16118        assert!(git::is_clean(&winner.worktree).await.unwrap());
16119        assert_eq!(
16120            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16121            head
16122        );
16123    }
16124
16125    #[tokio::test]
16126    #[cfg(unix)]
16127    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16128        use std::os::fd::AsRawFd as _;
16129        use std::time::Duration;
16130
16131        ask_test_home();
16132        let tmp = tempfile::tempdir().unwrap();
16133        let repo = tmp.path().join("repo");
16134        std::fs::create_dir_all(&repo).unwrap();
16135        init_repo(&repo);
16136        let common = repo.join(".git");
16137        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16138        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16139        assert_eq!(
16140            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16141            0
16142        );
16143        let mut runner = runner_at(RunStatus::Prep);
16144        runner.state.repo = repo.clone();
16145        runner.state.config.coordination = crate::config::test_coordination();
16146        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16147        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16148        runner.state.config.graph.advise = true;
16149        runner.state.config.graph.advisors = 1;
16150        runner.roles.implementers = vec![spec("implement")];
16151        runner.roles.judges = vec![spec("judge")];
16152        let root = runner.state.worktree_root();
16153        let started = tmp.path().join("setup-started");
16154        let proceed = tmp.path().join("setup-proceed");
16155        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16156            run: Some(format!(
16157                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16158                started.display(),
16159                proceed.display()
16160            )),
16161            ..Default::default()
16162        }];
16163        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16164        let config = git::git(&repo, &["config", "--local", "--list"])
16165            .await
16166            .unwrap();
16167        let mut prep = Box::pin(runner.prep());
16168        assert!(
16169            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16170                .await
16171                .is_err()
16172        );
16173        assert!(
16174            !root.exists(),
16175            "contention must prevent even checkout creation"
16176        );
16177        assert!(!started.exists(), "contention must prevent setup");
16178        assert_eq!(
16179            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16180            branches
16181        );
16182        assert_eq!(
16183            git::git(&repo, &["config", "--local", "--list"])
16184                .await
16185                .unwrap(),
16186            config
16187        );
16188        drop(lock);
16189        tokio::select! {
16190            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16191            result = tokio::time::timeout(Duration::from_secs(10), async {
16192                while !started.exists() {
16193                    tokio::time::sleep(Duration::from_millis(20)).await;
16194                }
16195            }) => result.unwrap(),
16196        }
16197        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16198        assert_eq!(
16199            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16200            -1
16201        );
16202        assert!(
16203            tokio::time::timeout(
16204                Duration::from_millis(100),
16205                crate::repo_lock::SeatLease::for_checkout(
16206                    &repo,
16207                    true,
16208                    crate::config::test_coordination().as_ref()
16209                )
16210            )
16211            .await
16212            .is_err(),
16213            "preparation must also exclude local editors"
16214        );
16215        std::fs::write(proceed, "ready").unwrap();
16216        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16217            .await
16218            .unwrap()
16219            .unwrap();
16220        drop(prep);
16221        assert_eq!(runner.state.prep_complete, Some(true));
16222        assert!(root.join("judge-1").exists());
16223        assert!(root.join("advisor-1").exists());
16224        assert_eq!(
16225            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16226            0
16227        );
16228    }
16229
16230    #[tokio::test]
16231    #[cfg(unix)]
16232    async fn preparation_lock_failure_prevents_repository_changes() {
16233        ask_test_home();
16234        let tmp = tempfile::tempdir().unwrap();
16235        let repo = tmp.path().join("repo");
16236        std::fs::create_dir_all(&repo).unwrap();
16237        init_repo(&repo);
16238        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16239        // A directory at the required lock path makes opening the real lock
16240        // fail, rather than merely exercising an invalid registration.
16241        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16242        let mut runner = runner_at(RunStatus::Prep);
16243        runner.state.repo = repo.clone();
16244        runner.state.config.coordination = crate::config::test_coordination();
16245        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16246        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16247        runner.roles.implementers = vec![spec("implement")];
16248        let error = runner.prep().await.unwrap_err();
16249        assert!(
16250            error
16251                .to_string()
16252                .contains("acquire mandatory repository lock")
16253        );
16254        assert!(!runner.state.worktree_root().exists());
16255        assert!(runner.state.candidates.is_empty());
16256        assert!(!repo.join(".git/config.worktree").exists());
16257        assert_eq!(
16258            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16259            "* main"
16260        );
16261    }
16262
16263    #[tokio::test]
16264    async fn preparation_records_creation_intent_before_git_can_fail() {
16265        ask_test_home();
16266        let tmp = tempfile::tempdir().unwrap();
16267        let repo = tmp.path().join("repo");
16268        std::fs::create_dir_all(&repo).unwrap();
16269        init_repo(&repo);
16270        let mut runner = runner_at(RunStatus::Prep);
16271        runner.state.repo = repo.clone();
16272        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16273        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16274        runner.state.config.blind.commit_msg_hook = false;
16275        runner.roles.implementers = vec![spec("one")];
16276        let label = blind::assign_labels(1, runner.state.seed)[0];
16277        let branch = runner.state.branch_for(label);
16278        // A conflicting branch makes Git refuse creation before a candidate
16279        // can be registered. The durable intent must still identify it.
16280        git::git(&repo, &["branch", &branch]).await.unwrap();
16281        assert!(runner.prep().await.is_err());
16282        let saved = RunState::load(&runner.state.id).unwrap();
16283        assert!(saved.candidates.is_empty());
16284        let event = saved
16285            .events
16286            .iter()
16287            .find(|e| e.node == "prep-intent")
16288            .unwrap();
16289        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16290        assert_eq!(intent["branch"], branch);
16291        assert_eq!(intent["start"], runner.state.base_commit);
16292        assert_eq!(
16293            intent["worktree"],
16294            runner
16295                .state
16296                .worktree_root()
16297                .join(format!("cand-{label}"))
16298                .to_string_lossy()
16299                .as_ref()
16300        );
16301        assert_eq!(intent["picks"], serde_json::json!([]));
16302    }
16303
16304    #[tokio::test]
16305    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16306        ask_test_home();
16307        let tmp = tempfile::tempdir().unwrap();
16308        let repo = tmp.path().join("repo");
16309        std::fs::create_dir_all(&repo).unwrap();
16310        init_repo(&repo);
16311        let mut runner = runner_at(RunStatus::Prep);
16312        runner.state.repo = repo.clone();
16313        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16314        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16315        runner.state.sources.pick_commits.push(refs::Input {
16316            token: "missing".into(),
16317            sha: "0".repeat(40),
16318            provenance: refs::Provenance::ExplicitCli,
16319        });
16320        assert!(runner.prep().await.is_err());
16321        assert!(runner.state.candidates.is_empty());
16322        assert!(!runner.state.worktree_root().exists());
16323    }
16324
16325    #[tokio::test]
16326    async fn prose_and_legacy_inference_never_import_into_candidates() {
16327        ask_test_home();
16328        let tmp = tempfile::tempdir().unwrap();
16329        let repo = tmp.path().join("repo");
16330        std::fs::create_dir_all(&repo).unwrap();
16331        init_repo(&repo);
16332        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16333        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16334            .await
16335            .unwrap();
16336        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16337        git::git(&repo, &["add", "."]).await.unwrap();
16338        git::git(&repo, &["commit", "-m", "historical implementation"])
16339            .await
16340            .unwrap();
16341        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16342        git::git(&repo, &["checkout", "main"]).await.unwrap();
16343        for instruction in [
16344            format!("Example: magi/history/A at {source}"),
16345            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16346            format!("Never import magi/history/A or {source}"),
16347            format!("Conversation answer: I mentioned {source} only as background"),
16348        ] {
16349            let mut runner = runner_at(RunStatus::Prep);
16350            runner.state.repo = repo.clone();
16351            runner.state.base_commit = base.clone();
16352            runner.state.instruction = instruction.clone();
16353            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16354            runner.state.config.blind.commit_msg_hook = false;
16355            runner.state.seeds = vec![refs::Seed {
16356                token: "magi/history/A".into(),
16357                sha: source.clone(),
16358                kind: refs::SeedKind::Unmerged,
16359                branch: true,
16360                detail: String::new(),
16361            }];
16362            runner.roles.implementers = vec![spec("one")];
16363            assert_eq!(seeded_instruction(&runner.state), instruction);
16364            // Model an old record with inferred seeds but no structured input field.
16365            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16366            legacy.as_object_mut().unwrap().remove("sources");
16367            runner.state = serde_json::from_value(legacy).unwrap();
16368            assert_eq!(runner.state.sources, refs::Sources::default());
16369            runner.state.save().unwrap();
16370            runner.state = RunState::load(&runner.state.id).unwrap();
16371            runner.prep().await.unwrap();
16372            for candidate in &runner.state.candidates {
16373                assert_eq!(
16374                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16375                    base
16376                );
16377                assert!(!candidate.worktree.join("unwanted").exists());
16378            }
16379        }
16380    }
16381
16382    #[tokio::test]
16383    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16384        ask_test_home();
16385        let tmp = tempfile::tempdir().unwrap();
16386        let repo = tmp.path().join("repo");
16387        std::fs::create_dir_all(&repo).unwrap();
16388        init_repo(&repo);
16389        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16390        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16391        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16392        git::git(&repo, &["add", "."]).await.unwrap();
16393        git::git(&repo, &["commit", "-m", "required seed"])
16394            .await
16395            .unwrap();
16396        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16397        git::git(&repo, &["checkout", "main"]).await.unwrap();
16398        let mut runner = runner_at(RunStatus::Prep);
16399        runner.state.repo = repo.clone();
16400        runner.state.base_commit = base.clone();
16401        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16402        runner.state.config.graph.advise = false;
16403        runner.state.config.blind.commit_msg_hook = false;
16404        runner.state.sources =
16405            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16406                .await
16407                .unwrap();
16408        runner.roles.implementers = vec![spec("one"), spec("two")];
16409        runner.roles.judges = vec![spec("judge")];
16410        let label = blind::assign_labels(2, runner.state.seed)[0];
16411        let branch = runner.state.branch_for(label);
16412        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16413        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16414            .await
16415            .unwrap();
16416        runner.state.candidates.push(Candidate {
16417            index: 0,
16418            label,
16419            agent: "one".into(),
16420            branch,
16421            worktree,
16422            summary: String::new(),
16423            stat: String::new(),
16424            files: 0,
16425            commits: 0,
16426            empty: false,
16427            failed: None,
16428            verified_noop: None,
16429            duration_ms: 0,
16430            folded: false,
16431        });
16432        runner.state.save().unwrap();
16433        // Reload the checkpoint immediately before its first cherry-pick.
16434        runner.state = RunState::load(&runner.state.id).unwrap();
16435        assert_eq!(runner.state.prep_complete, Some(false));
16436        runner.prep().await.unwrap();
16437        assert_eq!(runner.state.prep_complete, Some(true));
16438        assert_eq!(runner.state.candidates.len(), 2);
16439        for candidate in &runner.state.candidates {
16440            assert_eq!(
16441                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16442                git::tree_of(&repo, &seed).await.unwrap()
16443            );
16444            assert_eq!(
16445                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16446                "required commit"
16447            );
16448        }
16449        assert!(runner.state.worktree_root().join("judge-1").exists());
16450        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16451        runner.prep().await.unwrap();
16452        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16453
16454        runner.state.prep_complete = Some(false);
16455        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16456            run: Some(format!(
16457                "test -f '{}'",
16458                tmp.path().join("dependency-ready").display()
16459            )),
16460            ..Default::default()
16461        }];
16462        assert!(runner.prep().await.is_err());
16463        assert!(runner.state.prep_failure.is_some());
16464        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16465        runner.state = RunState::load(&runner.state.id).unwrap();
16466        assert!(
16467            runner.prep().await.is_err(),
16468            "correcting the cause alone must not auto-retry"
16469        );
16470        let failed_at = runner.state.events.last().unwrap().at;
16471        assert!(
16472            runner.retry_preparation(failed_at).is_err(),
16473            "old approvals cannot unlock the hold"
16474        );
16475        let mut task = crate::queue::Task::new(
16476            "retry".into(),
16477            "retry setup".into(),
16478            repo.clone(),
16479            crate::queue::Source::Human,
16480        );
16481        task.start(runner.state.id.clone());
16482        task.hold_machine(Some("setup failed".into()));
16483        task.release_operator("cli", None);
16484        runner
16485            .retry_preparation(task.resumption.as_ref().unwrap().at)
16486            .unwrap();
16487        runner.prep().await.unwrap();
16488        assert!(runner.state.prep_failure.is_none());
16489        assert_eq!(runner.state.prep_complete, Some(true));
16490        assert_eq!(runner.state.candidates.len(), 2);
16491        assert!(runner.state.worktree_root().join("judge-1").exists());
16492        for candidate in &runner.state.candidates {
16493            assert_eq!(
16494                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16495                git::tree_of(&repo, &seed).await.unwrap()
16496            );
16497        }
16498    }
16499
16500    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16501        let mut heads = Vec::new();
16502        for candidate in candidates {
16503            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16504        }
16505        heads
16506    }
16507
16508    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16509        ask_test_home();
16510        let tmp = tempfile::tempdir().unwrap();
16511        let repo = tmp.path().join("repo");
16512        std::fs::create_dir(&repo).unwrap();
16513        init_repo(&repo);
16514        let mut runner = runner_at(RunStatus::Reviewing);
16515        runner.state.repo = repo.clone();
16516        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16517        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16518        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16519            let branch = format!("candidate-{label}");
16520            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16521            git::worktree_add_branch(&repo, &worktree, &branch, "main")
16522                .await
16523                .unwrap();
16524            if label == 'B' {
16525                std::fs::write(worktree.join("change"), "winner").unwrap();
16526                git::rescue_commit(&worktree, "candidate change")
16527                    .await
16528                    .unwrap();
16529            }
16530            runner.state.candidates.push(Candidate {
16531                index,
16532                label,
16533                agent: "alpha".into(),
16534                branch,
16535                worktree,
16536                summary: "completed reply".into(),
16537                stat: String::new(),
16538                files: usize::from(label == 'B'),
16539                commits: usize::from(label == 'B'),
16540                empty: label == 'A',
16541                failed: None,
16542                verified_noop: None,
16543                duration_ms: 1,
16544                folded: false,
16545            });
16546        }
16547        runner.state.judge_skipped = true;
16548        runner.state.tally = Some(Tally {
16549            first_choice: BTreeMap::new(),
16550            borda: BTreeMap::new(),
16551            winner: 'B',
16552            rankings: 0,
16553            unanimous_initial: false,
16554            deliberated: false,
16555            changed_votes: 0,
16556            unanimous_final: false,
16557            tie_break: None,
16558            judges: 0,
16559            present: 0,
16560            quorum: 0,
16561            met_quorum: true,
16562            uncontested: Some("only B produced a change".into()),
16563        });
16564        runner.state.save().unwrap();
16565        (tmp, runner)
16566    }
16567
16568    #[tokio::test]
16569    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
16570        let (_tmp, mut runner) = preservation_resume_fixture().await;
16571        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
16572        runner.state.config.disk.cache_limit_bytes = 0;
16573        runner.state.config.graph.advise = true;
16574        runner.state.config.graph.advisors = 1;
16575        let advisor = runner.state.worktree_root().join("advisor-1");
16576        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
16577            .await
16578            .unwrap();
16579        let home = crate::run::home();
16580        let loser =
16581            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
16582        let winner =
16583            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
16584        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
16585        for target in [&loser, &winner, &advisor] {
16586            std::fs::write(target.join("build-output"), "compiled").unwrap();
16587        }
16588
16589        runner.fold_losers().await.unwrap();
16590
16591        assert!(!loser.join("build-output").exists());
16592        assert!(!advisor.join("build-output").exists());
16593        assert!(winner.join("build-output").is_file());
16594    }
16595
16596    #[tokio::test]
16597    async fn fold_losers_persists_discard_before_later_teardown_failure() {
16598        let (_tmp, mut runner) = preservation_resume_fixture().await;
16599        runner.state.candidates[0].folded = true;
16600        runner.state.config.graph.advise = true;
16601        runner.state.config.graph.advisors = 2;
16602        let repo = runner.state.repo.clone();
16603        let root = runner.state.worktree_root();
16604        let discarded = root.join("advisor-1");
16605        git::worktree_add_detached(&repo, &discarded, "main")
16606            .await
16607            .unwrap();
16608        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
16609        let protected = root.join("advisor-2");
16610        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
16611            .await
16612            .unwrap();
16613        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
16614        runner.state.save().unwrap();
16615
16616        assert!(runner.fold_losers().await.is_err());
16617        assert!(!discarded.exists());
16618        assert!(protected.join("keep").exists());
16619        let saved = RunState::load(&runner.state.id).unwrap();
16620        assert!(saved.events.iter().any(|event| {
16621            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
16622        }));
16623    }
16624
16625    #[tokio::test]
16626    async fn read_seat_teardown_discards_only_owned_detached_seats() {
16627        let (tmp, mut runner) = preservation_resume_fixture().await;
16628        let repo = runner.state.repo.clone();
16629        let root = runner.state.worktree_root();
16630        for name in ["advisor-3", "judge-1", "review-2"] {
16631            let path = root.join(name);
16632            git::worktree_add_detached(&repo, &path, "main")
16633                .await
16634                .unwrap();
16635            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
16636            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
16637            remove_read_seat_worktree(&mut runner.state, &path)
16638                .await
16639                .unwrap();
16640            assert!(!path.exists());
16641        }
16642        let outside = tmp.path().join("advisor-1");
16643        let unknown = root.join("unknown");
16644        let attached = root.join("advisor-4");
16645        git::worktree_add_detached(&repo, &outside, "main")
16646            .await
16647            .unwrap();
16648        git::worktree_add_detached(&repo, &unknown, "main")
16649            .await
16650            .unwrap();
16651        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
16652            .await
16653            .unwrap();
16654        let foreign = tmp.path().join("foreign");
16655        std::fs::create_dir(&foreign).unwrap();
16656        init_repo(&foreign);
16657        let wrong_repo = root.join("judge-2");
16658        git::worktree_add_detached(&foreign, &wrong_repo, "main")
16659            .await
16660            .unwrap();
16661        let candidate = runner.state.candidates[0].worktree.clone();
16662        for path in [outside, unknown, attached, wrong_repo, candidate] {
16663            std::fs::write(path.join("uncommitted"), "keep").unwrap();
16664            assert!(
16665                remove_read_seat_worktree(&mut runner.state, &path)
16666                    .await
16667                    .is_err()
16668            );
16669            assert_eq!(
16670                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
16671                "keep"
16672            );
16673        }
16674    }
16675
16676    #[tokio::test]
16677    #[cfg(unix)]
16678    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
16679        for (solo, failed_checkpoint) in
16680            [(true, false), (false, false), (true, true), (false, true)]
16681        {
16682            let (_tmp, mut runner) = preservation_resume_fixture().await;
16683            if solo {
16684                runner.state.candidates.retain(|c| c.label == 'A');
16685            }
16686            runner.state.candidates[0].empty = false;
16687            runner.state.candidates[0].summary.clear();
16688            runner.state.tally = None;
16689            runner.state.judge_skipped = false;
16690            runner.state.status = RunStatus::Implementing;
16691            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16692            let mut implementer = spec("alpha");
16693            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16694            runner.roles.implementers = vec![implementer];
16695            let patch = runner.state.dir().join("artifacts/cand-A.patch");
16696            if failed_checkpoint {
16697                std::fs::create_dir_all(&patch).unwrap();
16698            }
16699            runner.state.save().unwrap();
16700            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
16701            drop(pressure);
16702            runner.state = RunState::load(&runner.state.id).unwrap();
16703            assert_eq!(runner.state.status, RunStatus::Blocked);
16704            assert!(runner.state.interrupted_implementations.contains(&'A'));
16705            assert_eq!(runner.state.candidates[0].commits, 0);
16706            assert!(!runner.state.candidates[0].empty);
16707            assert!(runner.state.candidates[0].failed.is_none());
16708            if failed_checkpoint {
16709                assert!(runner.state.candidate_preservation.contains_key(&'A'));
16710                std::fs::remove_dir(patch).unwrap();
16711            }
16712            runner.state.resource_block = None;
16713            runner.state.config.disk.min_free_bytes = 0;
16714            runner.roles.implementers[0].command = vec![
16715                "sh".into(),
16716                "-c".into(),
16717                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
16718            ];
16719            runner.implement().await.unwrap();
16720            assert!(runner.state.interrupted_implementations.is_empty());
16721            assert!(runner.state.candidate_preservation.is_empty());
16722            assert_eq!(runner.state.candidates[0].commits, 1);
16723            assert!(!runner.state.candidates[0].empty);
16724            assert!(
16725                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
16726                    .unwrap()
16727                    .contains("retried empty interrupted seat")
16728            );
16729            if !solo {
16730                assert_eq!(runner.state.candidates[1].commits, 1);
16731            }
16732        }
16733    }
16734
16735    #[tokio::test]
16736    #[cfg(unix)]
16737    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
16738        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
16739            let (_tmp, mut runner) = preservation_resume_fixture().await;
16740            runner.state.candidates.retain(|c| c.label == 'A');
16741            runner.state.candidates[0].empty = false;
16742            runner.state.candidates[0].summary.clear();
16743            runner.state.tally = None;
16744            runner.state.judge_skipped = false;
16745            runner.state.status = RunStatus::Implementing;
16746            // Force only the real post-spawn watchdog, without failing the
16747            // separate admission check. Existing edits predate its measurement.
16748            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16749            let wt = runner.state.candidates[0].worktree.clone();
16750            std::fs::write(
16751                wt.join("interrupted-source"),
16752                "retain implementation work\n",
16753            )
16754            .unwrap();
16755            if committed {
16756                git::rescue_commit(&wt, "implementation checkpoint")
16757                    .await
16758                    .unwrap();
16759            }
16760            let lock = git::git(
16761                &wt,
16762                &[
16763                    "rev-parse",
16764                    "--path-format=absolute",
16765                    "--git-path",
16766                    "index.lock",
16767                ],
16768            )
16769            .await
16770            .unwrap();
16771            if block_rescue {
16772                std::fs::write(&lock, "fixture-owned lock").unwrap();
16773            }
16774            let mut implementer = spec("alpha");
16775            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16776            runner.roles.implementers = vec![implementer];
16777            runner.state.save().unwrap();
16778            let result = runner.implement().await;
16779            drop(pressure);
16780            assert_eq!(result.is_err(), block_rescue);
16781            assert_eq!(
16782                runner.state.resource_block.as_ref().unwrap().kind,
16783                "disk pressure"
16784            );
16785            assert!(
16786                runner
16787                    .state
16788                    .events
16789                    .iter()
16790                    .any(|e| e.message.contains("agent execution interrupted"))
16791            );
16792            assert!(
16793                runner
16794                    .state
16795                    .dir()
16796                    .join("artifacts/candidate-A-recovery/staged.patch")
16797                    .exists()
16798            );
16799            if block_rescue {
16800                let saved = RunState::load(&runner.state.id).unwrap();
16801                assert!(saved.candidate_preservation.contains_key(&'A'));
16802                assert!(!saved.candidates[0].empty);
16803                assert_eq!(
16804                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
16805                    "retain implementation work\n"
16806                );
16807                std::fs::remove_file(lock).unwrap();
16808                runner.state = saved;
16809            } else {
16810                assert_eq!(runner.state.status, RunStatus::Blocked);
16811                assert_eq!(runner.state.candidates[0].commits, 1);
16812            }
16813            // Recovery must save the candidate before deciding whether another
16814            // implementation is needed. No implementer is available on retry.
16815            runner.roles.implementers.clear();
16816            runner.state.config.disk.min_free_bytes = 0;
16817            runner.state.resource_block = None;
16818            runner.implement().await.unwrap();
16819            assert!(runner.state.candidate_preservation.is_empty());
16820            assert_eq!(runner.state.candidates[0].commits, 1);
16821            assert!(!runner.state.candidates[0].empty);
16822            assert!(git::is_clean(&wt).await.unwrap());
16823            assert!(
16824                crate::run::read_artifact(&runner.state, "cand-A.patch")
16825                    .unwrap()
16826                    .contains("retain implementation work")
16827            );
16828        }
16829    }
16830
16831    #[tokio::test]
16832    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
16833        let (_tmp, mut runner) = preservation_resume_fixture().await;
16834        // Schema 15 already confirmed the unfolded no-change result.
16835        runner.implement().await.unwrap();
16836        assert!(runner.state.candidate_preservation.is_empty());
16837        assert!(
16838            !runner
16839                .state
16840                .dir()
16841                .join("artifacts/candidate-A-recovery")
16842                .exists()
16843        );
16844        runner.fold_losers().await.unwrap();
16845        assert!(!runner.state.candidates[0].worktree.exists());
16846        for schema in [14, crate::run::SCHEMA] {
16847            runner.state.schema = schema;
16848            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16849            runner.state.save().unwrap();
16850            runner.state = RunState::load(&runner.state.id).unwrap();
16851            runner.implement().await.unwrap();
16852            assert!(runner.state.candidate_preservation.is_empty());
16853            assert!(runner.state.candidates[0].folded);
16854            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16855        }
16856    }
16857
16858    #[tokio::test]
16859    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
16860        let (_tmp, mut runner) = preservation_resume_fixture().await;
16861        runner.state.candidates.retain(|c| c.label == 'A');
16862        runner.state.tally = None;
16863        runner.state.judge_skipped = false;
16864        let candidate = &mut runner.state.candidates[0];
16865        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
16866        candidate.failed = Some("deployment validation unavailable".into());
16867        std::fs::write(
16868            candidate.worktree.join("repair"),
16869            "future launcher policy\n",
16870        )
16871        .unwrap();
16872        runner
16873            .state
16874            .candidate_preservation
16875            .insert('A', "awaiting persistence".into());
16876        runner.persist_candidates().await.unwrap();
16877        let candidate = &runner.state.candidates[0];
16878        assert!(!candidate.empty);
16879        assert_eq!(candidate.commits, 1);
16880        assert_eq!(candidate.files, 1);
16881        assert!(candidate.failed.is_none());
16882        assert!(candidate.summary.contains("EPERM"));
16883        assert!(
16884            crate::run::read_artifact(&runner.state, "cand-A.patch")
16885                .unwrap()
16886                .contains("future launcher policy")
16887        );
16888        assert!(runner.state.candidate_preservation.is_empty());
16889    }
16890
16891    #[tokio::test]
16892    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
16893        let (_tmp, mut runner) = preservation_resume_fixture().await;
16894        let wt = runner.state.candidates[0].worktree.clone();
16895        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
16896        runner.state.schema = 14;
16897        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16898        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16899        let tally = serde_json::to_value(&runner.state.tally).unwrap();
16900        for _ in 0..2 {
16901            assert!(runner.implement().await.is_err());
16902            assert_eq!(runner.state.status, RunStatus::Blocked);
16903            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16904            assert!(
16905                runner.state.candidates[0].empty,
16906                "old verdict must remain unusable"
16907            );
16908            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
16909            assert!(runner.state.judge_skipped);
16910            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
16911            assert!(
16912                crate::run::read_artifact(&runner.state, "cand-A.patch")
16913                    .unwrap()
16914                    .contains("owned edits")
16915            );
16916            assert!(wt.exists());
16917            assert_eq!(
16918                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
16919                    .await
16920                    .unwrap(),
16921                1
16922            );
16923            runner.state = RunState::load(&runner.state.id).unwrap();
16924        }
16925    }
16926
16927    #[tokio::test]
16928    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
16929        let (_tmp, mut runner) = preservation_resume_fixture().await;
16930        let wt = runner.state.candidates[0].worktree.clone();
16931        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
16932        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
16933        let index_lock = PathBuf::from(
16934            git::git(
16935                &wt,
16936                &[
16937                    "rev-parse",
16938                    "--path-format=absolute",
16939                    "--git-path",
16940                    "index.lock",
16941                ],
16942            )
16943            .await
16944            .unwrap(),
16945        );
16946        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16947        runner.state.schema = 14;
16948        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16949        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16950        assert!(runner.implement().await.is_err());
16951        assert!(runner.after_implement().is_err());
16952        assert!(runner.fold_losers().await.is_err());
16953        assert_eq!(
16954            std::fs::read_to_string(wt.join("recovered")).unwrap(),
16955            "failed seat edits"
16956        );
16957        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16958        runner.state = RunState::load(&runner.state.id).unwrap();
16959        std::fs::remove_file(index_lock).unwrap();
16960        // Recovery finds changes that the old uncontested result never judged.
16961        assert!(runner.implement().await.is_err());
16962        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16963        assert!(runner.state.candidates[0].empty);
16964        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16965        assert!(
16966            crate::run::read_artifact(&runner.state, "cand-A.patch")
16967                .unwrap()
16968                .contains("failed seat edits")
16969        );
16970        assert!(wt.exists());
16971    }
16972
16973    #[tokio::test]
16974    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
16975        let (_tmp, mut runner) = preservation_resume_fixture().await;
16976        let repo = runner.state.repo.clone();
16977        let common = git::git(
16978            &repo,
16979            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
16980        )
16981        .await
16982        .unwrap();
16983        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
16984        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
16985        assert!(runner.fold_losers().await.is_err());
16986        assert!(!runner.state.candidates[0].worktree.exists());
16987        assert!(!runner.state.candidates[0].folded);
16988        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
16989        runner.state = RunState::load(&runner.state.id).unwrap();
16990        std::fs::remove_file(branch_lock).unwrap();
16991        let judge = runner.state.worktree_root().join("judge-1");
16992        git::worktree_add_detached(&repo, &judge, "main")
16993            .await
16994            .unwrap();
16995        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
16996        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
16997            .await
16998            .unwrap();
16999        runner.roles.judges = vec![spec("judge")];
17000        assert!(runner.fold_losers().await.is_err());
17001        runner.state = RunState::load(&runner.state.id).unwrap();
17002        assert!(
17003            runner.state.candidates[0].folded,
17004            "candidate progress saved before judge failure"
17005        );
17006        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17007        assert!(judge.join("uncommitted").exists());
17008        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17009            .await
17010            .unwrap();
17011        runner.fold_losers().await.unwrap();
17012        assert!(!judge.exists());
17013        runner.fold_losers().await.unwrap();
17014    }
17015
17016    #[tokio::test]
17017    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
17018        let (_tmp, mut runner) = preservation_resume_fixture().await;
17019        runner.state.candidates.retain(|c| c.label == 'B');
17020        runner.state.tally = None;
17021        runner.state.judge_skipped = false;
17022        runner.state.prep_complete = Some(true);
17023        runner.state.config.graph.advise = false;
17024        runner.state.config.graph.selected_implementer = Some("alpha".into());
17025        let wt = runner.state.candidates[0].worktree.clone();
17026        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
17027        runner
17028            .state
17029            .candidate_preservation
17030            .insert('B', "awaiting persistence".into());
17031        let index_lock = git::git(
17032            &wt,
17033            &[
17034                "rev-parse",
17035                "--path-format=absolute",
17036                "--git-path",
17037                "index.lock",
17038            ],
17039        )
17040        .await
17041        .unwrap();
17042        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17043        runner.state.save().unwrap();
17044        assert!(runner.execute_graph().await.is_err());
17045        assert_eq!(runner.state.status, RunStatus::Blocked);
17046        assert!(runner.state.candidate_preservation.contains_key(&'B'));
17047        std::fs::remove_file(index_lock).unwrap();
17048        // Park at the next graph boundary: this tests the real selected-seat
17049        // hold guard without dispatching reviewers or publishing anything.
17050        for _ in 0..2 {
17051            runner.state = RunState::load(&runner.state.id).unwrap();
17052            runner.pause.park();
17053            runner.execute_graph().await.unwrap();
17054            assert_eq!(runner.state.status, RunStatus::Implementing);
17055            assert!(runner.state.candidate_preservation.is_empty());
17056            assert_eq!(runner.state.candidates[0].commits, 2);
17057            assert!(runner.state.tally.is_none());
17058        }
17059        runner.implement().await.unwrap();
17060        assert_eq!(runner.state.status, RunStatus::Judging);
17061        // A genuine selected-implementer hold must still require release.
17062        runner.state.status = RunStatus::Blocked;
17063        runner.state.candidates[0].failed = Some("implementation failed".into());
17064        runner.state.save().unwrap();
17065        let error = runner.execute_graph().await.unwrap_err();
17066        assert!(
17067            error
17068                .to_string()
17069                .contains("selected implementation is held")
17070        );
17071    }
17072
17073    #[tokio::test]
17074    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
17075        let (_tmp, mut runner) = preservation_resume_fixture().await;
17076        let repo = runner.state.repo.clone();
17077        let candidate = runner.state.candidates[0].clone();
17078        // Remove only the disposable fixture directory, leaving Git's linked
17079        // worktree registration and branch intact, as in a vanished checkout.
17080        let registered = git::worktree_holding(&repo, &candidate.branch)
17081            .await
17082            .unwrap()
17083            .unwrap();
17084        assert_eq!(
17085            registered.canonicalize().unwrap(),
17086            candidate.worktree.canonicalize().unwrap()
17087        );
17088        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17089        assert_eq!(
17090            git::worktree_holding(&repo, &candidate.branch)
17091                .await
17092                .unwrap(),
17093            Some(registered)
17094        );
17095        assert!(
17096            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17097            "the stale registration initially keeps the branch checked out"
17098        );
17099        runner.fold_losers().await.unwrap();
17100        assert!(runner.state.candidates[0].folded);
17101        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17102        assert_eq!(
17103            git::worktree_holding(&repo, &candidate.branch)
17104                .await
17105                .unwrap(),
17106            None
17107        );
17108        runner.state = RunState::load(&runner.state.id).unwrap();
17109        runner.fold_losers().await.unwrap();
17110    }
17111
17112    #[tokio::test]
17113    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17114        let (_tmp, mut runner) = preservation_resume_fixture().await;
17115        let repo = runner.state.repo.clone();
17116        let candidate = runner.state.candidates[0].clone();
17117        let winner = runner.state.candidates[1].clone();
17118        let registered = git::worktree_holding(&repo, &candidate.branch)
17119            .await
17120            .unwrap()
17121            .unwrap();
17122        assert_eq!(
17123            registered.canonicalize().unwrap(),
17124            candidate.worktree.canonicalize().unwrap()
17125        );
17126        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17127        assert_eq!(
17128            git::worktree_holding(&repo, &candidate.branch)
17129                .await
17130                .unwrap(),
17131            Some(registered)
17132        );
17133        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17134
17135        for _ in 0..2 {
17136            fold_run(&mut runner.state, false, &crate::run::home())
17137                .await
17138                .unwrap();
17139            runner.state = RunState::load(&runner.state.id).unwrap();
17140            assert!(runner.state.candidates[0].folded);
17141            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17142            assert_eq!(
17143                git::worktree_holding(&repo, &candidate.branch)
17144                    .await
17145                    .unwrap(),
17146                None
17147            );
17148            assert!(!runner.state.candidates[1].folded);
17149            assert!(winner.worktree.exists());
17150            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17151        }
17152    }
17153    #[tokio::test]
17154    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17155        for sidecar in [false, true] {
17156            let tmp = tempfile::tempdir().unwrap();
17157            let home = tmp.path().join("home");
17158            let repo = tmp.path().join("repo");
17159            std::fs::create_dir(&repo).unwrap();
17160            init_repo(&repo);
17161            let mut state = runner_at(RunStatus::Superseded).state;
17162            state.repo = repo.clone();
17163            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17164            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17165            state.driver_exited = true;
17166            state.reserve_under(&home).unwrap();
17167            git::git(
17168                &repo,
17169                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17170            )
17171            .await
17172            .unwrap();
17173            let wt = state.worktree_root().join("cand-A");
17174            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17175                .await
17176                .unwrap();
17177            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17178            git::commit_all(&wt, "fixture: independent source")
17179                .await
17180                .unwrap();
17181            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17182            state.candidates.push(Candidate {
17183                index: 0,
17184                label: 'A',
17185                agent: "fixture".into(),
17186                branch: "candidate".into(),
17187                worktree: wt.clone(),
17188                summary: String::new(),
17189                stat: String::new(),
17190                files: 0,
17191                commits: 0,
17192                empty: false,
17193                failed: None,
17194                verified_noop: None,
17195                duration_ms: 0,
17196                folded: false,
17197            });
17198            let mut task = crate::queue::Task::new(
17199                "task".into(),
17200                "task".into(),
17201                repo.clone(),
17202                crate::queue::Source::Human,
17203            );
17204            task.runs.push(state.id.clone());
17205            crate::queue::Queue::at(home.join("queue"))
17206                .put(&mut task)
17207                .unwrap();
17208            if sidecar {
17209                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17210            }
17211            state.save_under(&home).unwrap();
17212            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17213            assert!(
17214                fold_run(&mut state, true, &home)
17215                    .await
17216                    .unwrap_err()
17217                    .to_string()
17218                    .contains(&reason)
17219            );
17220            let mut disk = state.config.disk.clone();
17221            disk.fold_grace_secs = 0;
17222            assert_eq!(
17223                crate::clean::fold_due(
17224                    &home.join("runs"),
17225                    &home,
17226                    &state.worktree_root(),
17227                    &disk,
17228                    Timestamp::now() + std::time::Duration::from_secs(10),
17229                )
17230                .await
17231                .unwrap(),
17232                (0, 0)
17233            );
17234            assert!(wt.exists());
17235            state.status = RunStatus::Blocked;
17236            state.save_under(&home).unwrap();
17237            assert!(
17238                fold_run_overriding_recovery_retention(&mut state, true, &home)
17239                    .await
17240                    .is_err()
17241            );
17242            state.status = RunStatus::Superseded;
17243            state.driver_exited = false;
17244            state.driver_claimed = None;
17245            state.save_under(&home).unwrap();
17246            assert!(
17247                fold_run_overriding_recovery_retention(&mut state, true, &home)
17248                    .await
17249                    .is_err()
17250            );
17251            state.driver_pid = Some(std::process::id());
17252            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17253            state.save_under(&home).unwrap();
17254            assert!(
17255                fold_run_overriding_recovery_retention(&mut state, true, &home)
17256                    .await
17257                    .is_err()
17258            );
17259            state.driver_exited = true;
17260            state.driver_pid = None;
17261            state.driver_started_at = None;
17262            state.save_under(&home).unwrap();
17263            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17264            assert!(
17265                fold_run_overriding_recovery_retention(&mut state, true, &home)
17266                    .await
17267                    .is_err()
17268            );
17269            drop(lease);
17270            #[cfg(unix)]
17271            {
17272                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17273                assert!(
17274                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17275                        .await
17276                        .is_err()
17277                );
17278                drop(output);
17279            }
17280            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17281            assert!(
17282                fold_run_overriding_recovery_retention(&mut state, true, &home)
17283                    .await
17284                    .is_err()
17285            );
17286            drop(owner);
17287            let checkpoint = git::git(
17288                &wt,
17289                &[
17290                    "rev-parse",
17291                    "--path-format=absolute",
17292                    "--git-path",
17293                    "CHERRY_PICK_HEAD",
17294                ],
17295            )
17296            .await
17297            .unwrap();
17298            std::fs::write(&checkpoint, &head).unwrap();
17299            assert!(
17300                fold_run_overriding_recovery_retention(&mut state, true, &home)
17301                    .await
17302                    .is_err()
17303            );
17304            std::fs::remove_file(checkpoint).unwrap();
17305            std::fs::write(wt.join("dirty"), "keep").unwrap();
17306            assert!(
17307                fold_run_overriding_recovery_retention(&mut state, true, &home)
17308                    .await
17309                    .is_err()
17310            );
17311            assert!(wt.join("dirty").exists());
17312            std::fs::remove_file(wt.join("dirty")).unwrap();
17313            let evidence = home
17314                .join("runs")
17315                .join(&state.id)
17316                .join("artifacts/fold-evidence");
17317            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17318            std::fs::write(&evidence, "blocked archive").unwrap();
17319            assert!(
17320                fold_run_overriding_recovery_retention(&mut state, true, &home)
17321                    .await
17322                    .is_err()
17323            );
17324            assert!(wt.exists());
17325            assert!(
17326                !RunState::load_under(&state.id, &home)
17327                    .unwrap()
17328                    .events
17329                    .iter()
17330                    .any(|event| event.message.contains("--override-recovery-retention"))
17331            );
17332            std::fs::remove_file(&evidence).unwrap();
17333            fold_run_overriding_recovery_retention(&mut state, true, &home)
17334                .await
17335                .unwrap();
17336            assert!(!wt.exists());
17337            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17338            assert!(
17339                git::worktree_holding(&repo, "candidate")
17340                    .await
17341                    .unwrap()
17342                    .is_none()
17343            );
17344            assert!(
17345                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17346                    .unwrap()
17347                    .contains("retained implementation")
17348            );
17349            assert!(evidence.join(format!("{head}.index")).is_file());
17350            let saved = RunState::load_under(&state.id, &home).unwrap();
17351            assert_eq!(saved.status, RunStatus::Superseded);
17352            assert!(saved.candidates[0].folded);
17353            assert!(saved.events.iter().any(|event| {
17354                event.message.contains("--override-recovery-retention")
17355                    && event.message.contains(&state.id)
17356                    && event.message.contains(&reason)
17357            }));
17358            assert_eq!(
17359                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17360                sidecar
17361            );
17362        }
17363    }
17364
17365    #[tokio::test]
17366    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17367        ask_test_home();
17368        let tmp = tempfile::tempdir().unwrap();
17369        let repo = tmp.path().join("repo");
17370        std::fs::create_dir(&repo).unwrap();
17371        init_repo(&repo);
17372        let mut runner = runner_at(RunStatus::Implementing);
17373        runner.state.repo = repo.clone();
17374        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17375        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17376        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17377            let branch = format!("candidate-{label}");
17378            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17379            git::worktree_add_branch(&repo, &wt, &branch, "main")
17380                .await
17381                .unwrap();
17382            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17383            git::git(&wt, &["add", "README.md"]).await.unwrap();
17384            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17385            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17386            runner.state.candidates.push(Candidate {
17387                index,
17388                label,
17389                agent: "alpha".to_owned(),
17390                branch,
17391                worktree: wt,
17392                summary: "completed implementation".to_owned(),
17393                stat: String::new(),
17394                files: 0,
17395                commits: 0,
17396                empty: false,
17397                failed: None,
17398                verified_noop: None,
17399                duration_ms: 42,
17400                folded: false,
17401            });
17402            runner
17403                .state
17404                .candidate_preservation
17405                .insert(label, "awaiting persistence".to_owned());
17406        }
17407        let wt = runner.state.candidates[0].worktree.clone();
17408        let index_lock = git::git(
17409            &wt,
17410            &[
17411                "rev-parse",
17412                "--path-format=absolute",
17413                "--git-path",
17414                "index.lock",
17415            ],
17416        )
17417        .await
17418        .unwrap();
17419        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17420        runner.state.save().unwrap();
17421        assert!(runner.persist_candidates().await.is_err());
17422        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17423        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17424        assert_eq!(
17425            runner.state.candidates[1].commits, 1,
17426            "other results are still collected"
17427        );
17428        assert!(
17429            !runner.state.candidates[0].empty,
17430            "failed rescue is not no change"
17431        );
17432        assert_eq!(
17433            runner.state.candidates[0].summary,
17434            "completed implementation"
17435        );
17436        assert!(runner.after_implement().is_err());
17437        let home = tmp.path().join("fold-home");
17438        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17439        assert!(wt.join("new-file").exists());
17440        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17441        assert!(recovery.join("staged.patch").exists());
17442        assert!(recovery.join("unstaged.patch").exists());
17443        assert_eq!(
17444            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17445            "untracked edits\n"
17446        );
17447        runner.state.begin_pass();
17448        runner.state.end_pass_parked(ParkCause::Upgrade {
17449            from: "1.0".into(),
17450            to: Some("1.1".into()),
17451        });
17452        runner.state.save().unwrap();
17453        runner.state = RunState::load(&runner.state.id).unwrap();
17454        assert!(matches!(
17455            runner.state.passes.last().unwrap().end,
17456            Some(crate::run::PassEnd::Parked {
17457                cause: ParkCause::Upgrade { .. }
17458            })
17459        ));
17460        std::fs::remove_file(index_lock).unwrap();
17461        // No implementer is configured: a persistence retry cannot dispatch a seat.
17462        runner.implement().await.unwrap();
17463        assert!(runner.state.candidate_preservation.is_empty());
17464        assert!(
17465            runner
17466                .state
17467                .candidates
17468                .iter()
17469                .all(|c| c.commits == 1 && !c.empty)
17470        );
17471        assert!(git::is_clean(&wt).await.unwrap());
17472        assert!(
17473            crate::run::read_artifact(&runner.state, "cand-A.patch")
17474                .unwrap()
17475                .contains("later tracked edits")
17476        );
17477    }
17478
17479    #[tokio::test]
17480    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17481        ask_test_home();
17482        let tmp = tempfile::tempdir().unwrap();
17483        let repo = tmp.path().join("repo");
17484        std::fs::create_dir(&repo).unwrap();
17485        init_repo(&repo);
17486        let wt = tmp.path().join("candidate");
17487        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17488            .await
17489            .unwrap();
17490        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17491        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17492        assert!(wt.join("uncommitted").exists());
17493        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17494        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17495        let mut runner = runner_at(RunStatus::Implementing);
17496        runner.state.repo = repo.clone();
17497        runner.state.base_commit = "missing-base".to_owned();
17498        runner.state.candidates.push(Candidate {
17499            index: 0,
17500            label: 'A',
17501            agent: "alpha".into(),
17502            branch: "candidate".into(),
17503            worktree: wt.clone(),
17504            summary: "completed".into(),
17505            stat: String::new(),
17506            files: 0,
17507            commits: 0,
17508            empty: false,
17509            failed: None,
17510            verified_noop: None,
17511            duration_ms: 1,
17512            folded: false,
17513        });
17514        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17515        assert!(
17516            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17517                .await
17518                .is_err()
17519        );
17520        assert!(!runner.state.candidates[0].folded);
17521        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17522        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17523        runner
17524            .state
17525            .candidate_preservation
17526            .insert('A', "pending".into());
17527        assert!(runner.persist_candidates().await.is_err());
17528        assert!(!runner.state.candidates[0].empty);
17529        assert!(!runner.state.candidates[0].folded);
17530        assert!(wt.exists());
17531        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17532        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
17533        std::fs::create_dir_all(&patch_path).unwrap();
17534        assert!(
17535            runner.persist_candidates().await.is_err(),
17536            "artifact failure stays pending"
17537        );
17538        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17539        assert!(!runner.state.candidates[0].empty);
17540        std::fs::remove_dir(patch_path).unwrap();
17541        runner.persist_candidates().await.unwrap();
17542        assert!(
17543            runner.state.candidates[0].empty,
17544            "only successful inspection confirms no change"
17545        );
17546    }
17547
17548    fn init_repo(dir: &Path) {
17549        let run = |args: &[&str]| {
17550            let out = std::process::Command::new("git")
17551                .args(args)
17552                .current_dir(dir)
17553                .quiet()
17554                .output()
17555                .expect("spawn git");
17556            assert!(
17557                out.status.success(),
17558                "git {args:?} failed: {}",
17559                String::from_utf8_lossy(&out.stderr)
17560            );
17561        };
17562        run(&["init", "-b", "main"]);
17563        run(&["config", "user.name", "magi test"]);
17564        run(&["config", "user.email", "magi@example.com"]);
17565        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
17566        run(&["add", "-A"]);
17567        run(&["commit", "-m", "init"]);
17568    }
17569
17570    // `settle_questions` is what closes the ghost the phone showed: a run's
17571    // seat asked something, the run then ended, and nothing was left to
17572    // abandon the question it left `open`. `HOME` is a process-wide
17573    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
17574    // first time it runs in the binary — every test below still reaches the
17575    // same directory whichever call won, and each gets its own run id from
17576    // `RunState::new`, so they never collide there.
17577    fn ask_test_home() {
17578        crate::run::pin_test_home();
17579    }
17580
17581    #[test]
17582    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
17583        ask_test_home();
17584        let mut runner = runner_at(RunStatus::Prep);
17585        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17586        // A blocked temporary output path makes the terminal save fail while
17587        // preserving the already published reservation.
17588        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
17589        let error = guard
17590            .finish(
17591                &mut runner.state,
17592                Err(
17593                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
17594                        .into(),
17595                ),
17596            )
17597            .unwrap_err();
17598        assert_eq!(
17599            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17600            std::io::ErrorKind::PermissionDenied
17601        );
17602        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
17603        let message = format!("{error:#}");
17604        assert!(message.contains("original refusal"));
17605        assert!(!message.contains("could not save terminal"));
17606        assert_eq!(
17607            error.chain().count(),
17608            2,
17609            "only startup attribution wraps the original error"
17610        );
17611        let saved = RunState::load(&runner.state.id).unwrap();
17612        assert_eq!(saved.status, RunStatus::Blocked);
17613        assert!(!saved.startup.unwrap().complete);
17614    }
17615
17616    #[test]
17617    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
17618        ask_test_home();
17619        let mut runner = runner_at(RunStatus::Prep);
17620        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17621        let id = runner.state.id.clone();
17622        drop(guard);
17623        let saved = RunState::load(&id).unwrap();
17624        assert_eq!(saved.status, RunStatus::Blocked);
17625        assert!(!saved.startup.as_ref().unwrap().complete);
17626        assert!(
17627            saved
17628                .startup
17629                .unwrap()
17630                .failure
17631                .unwrap()
17632                .contains("interrupted")
17633        );
17634        assert!(Runner::resume(&id).is_err());
17635    }
17636
17637    #[test]
17638    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
17639        ask_test_home();
17640        let mut runner = runner_at(RunStatus::Prep);
17641        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17642        let error = guard
17643            .finish(
17644                &mut runner.state,
17645                Err(
17646                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
17647                        .into(),
17648                ),
17649            )
17650            .unwrap_err();
17651        assert_eq!(
17652            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17653            std::io::ErrorKind::PermissionDenied
17654        );
17655        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
17656        let mut task = crate::queue::Task::new(
17657            "review".into(),
17658            "criteria".into(),
17659            runner.state.repo.clone(),
17660            crate::queue::Source::Human,
17661        );
17662        task.record_startup_failure(failure.clone());
17663        task.record_startup_failure(failure.clone());
17664        assert_eq!(task.startup_failures.len(), 1);
17665        assert!(task.runs.is_empty());
17666        assert_eq!(task.attempts, 0);
17667    }
17668
17669    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
17670        ask_test_home();
17671        let tmp = tempfile::tempdir().unwrap();
17672        let repo = tmp.path().join("repo");
17673        std::fs::create_dir(&repo).unwrap();
17674        init_repo(&repo);
17675        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17676        let origin = tmp.path().join("origin.git");
17677        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
17678            .await
17679            .unwrap();
17680        git::git(
17681            &repo,
17682            &["remote", "add", "origin", origin.to_str().unwrap()],
17683        )
17684        .await
17685        .unwrap();
17686        git::git(&repo, &["checkout", "-b", "fix/retained"])
17687            .await
17688            .unwrap();
17689        std::fs::write(repo.join("retained"), "retained change").unwrap();
17690        git::git(&repo, &["add", "."]).await.unwrap();
17691        git::git(&repo, &["commit", "-m", "retained implementation"])
17692            .await
17693            .unwrap();
17694        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
17695        git::git(&repo, &["checkout", "main"]).await.unwrap();
17696        std::fs::write(repo.join("base-change"), "new base").unwrap();
17697        git::git(&repo, &["add", "."]).await.unwrap();
17698        git::git(&repo, &["commit", "-m", "base moved"])
17699            .await
17700            .unwrap();
17701        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17702        git::git(&repo, &["checkout", "fix/retained"])
17703            .await
17704            .unwrap();
17705        let mut runner = runner_at(RunStatus::Voting);
17706        runner.state.repo = repo.clone();
17707        runner.state.base_commit = base;
17708        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17709        runner.state.config.disk.min_free_bytes = 0;
17710        runner.state.config.graph.review_rounds = 1;
17711        runner.state.config.verify.e2e = vec!["true".into()];
17712        runner.state.config.verify.gate = vec!["true".into()];
17713        runner.state.candidates = vec![Candidate {
17714            index: 0,
17715            label: 'A',
17716            agent: "fixture".into(),
17717            branch: "fix/retained".into(),
17718            worktree: repo.clone(),
17719            summary: String::new(),
17720            stat: String::new(),
17721            files: 1,
17722            commits: 1,
17723            empty: false,
17724            failed: None,
17725            verified_noop: None,
17726            duration_ms: 0,
17727            folded: false,
17728        }];
17729        runner.state.tally = Some(Tally {
17730            first_choice: BTreeMap::new(),
17731            borda: BTreeMap::new(),
17732            winner: 'A',
17733            rankings: 0,
17734            unanimous_initial: true,
17735            deliberated: false,
17736            changed_votes: 0,
17737            unanimous_final: true,
17738            tie_break: None,
17739            judges: 0,
17740            present: 0,
17741            quorum: 0,
17742            met_quorum: true,
17743            uncontested: Some("review-only".into()),
17744        });
17745        let mut task = crate::queue::Task::new(
17746            "fixture".into(),
17747            "fixture".into(),
17748            repo,
17749            crate::queue::Source::Human,
17750        );
17751        task.link_run(&runner.state.id);
17752        crate::queue::Queue::open().put(&mut task).unwrap();
17753        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
17754        runner.state.base_sync = Some(BaseSync {
17755            tip: String::new(),
17756            behind: 1,
17757            attempts: BASE_SYNC_ROUNDS,
17758            conflict: None,
17759            already_in: None,
17760        });
17761        runner.sync_to_base().await.unwrap();
17762        assert_eq!(runner.state.status, RunStatus::Blocked);
17763        (tmp, runner, head, task.id)
17764    }
17765
17766    #[tokio::test]
17767    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
17768        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
17769        runner.state.status = RunStatus::Voting;
17770        runner.state.base_sync = None;
17771        runner.state.base_sync_recovery = Default::default();
17772        let scratch = runner.state.dir().join("base-sync");
17773        std::fs::create_dir_all(&scratch).unwrap();
17774        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
17775        runner.sync_to_base().await.unwrap();
17776        assert!(runner.state.resource_block.is_some());
17777        assert!(!runner.state.base_sync_blocked());
17778        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 0);
17779        assert_eq!(runner.state.base_episode_used(), 0);
17780        assert!(runner.state.base_sync_recovery.operations.is_empty());
17781        assert!(runner.state.rebase_fixes.is_empty());
17782        assert_eq!(
17783            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17784            head
17785        );
17786        std::fs::remove_dir_all(&scratch).unwrap();
17787        runner.state.resource_block = None;
17788        runner.sync_to_base().await.unwrap();
17789        assert!(!runner.state.base_sync_blocked());
17790        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
17791        assert_eq!(runner.state.base_episode_used(), 1);
17792        assert!(runner.state.base_sync_recovery.operations[0].finished);
17793        assert!(runner.state.rebase_fixes.is_empty());
17794        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
17795        assert!(git::is_clean(&runner.state.repo).await.unwrap());
17796    }
17797
17798    #[cfg(unix)]
17799    #[tokio::test]
17800    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
17801        for routed in [false, true] {
17802            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
17803            let home = crate::run::home();
17804            let queue = crate::queue::Queue::open();
17805            let task = queue.get(&owner).unwrap();
17806            runner.state.task_instruction = Some(task.instruction.clone());
17807            runner.state.driver_exited = true;
17808            runner.state.save().unwrap();
17809            let questions = crate::ask::Questions::at(home.join("questions"));
17810            let mut q = crate::ask::Question::new(
17811                runner.state.id.clone(),
17812                "base-recovery".into(),
17813                "owner".into(),
17814                "Recover bounded base movement?".into(),
17815                String::new(),
17816                vec!["recover".into()],
17817            );
17818            q.actions.insert(
17819                "recover".into(),
17820                crate::ask::ChoiceAction::RecoverBase {
17821                    run: runner.state.id.clone(),
17822                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
17823                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
17824                },
17825            );
17826            q.routed_task = Some(owner.clone());
17827            q.answer(crate::ask::Answer::Choice("recover".into()))
17828                .unwrap();
17829            questions.put(&mut q).unwrap();
17830            crate::base_recovery_control::recover(
17831                &queue,
17832                &home,
17833                crate::base_recovery_control::Request {
17834                    run: runner.state.id.clone(),
17835                    head: head.clone(),
17836                    actor: "decisions".into(),
17837                    request: q.id.clone(),
17838                    decision: Some((owner.clone(), q.answered_at.unwrap())),
17839                    expected_stop: Some((
17840                        runner.state.base_sync_recovery.stop.clone().unwrap(),
17841                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
17842                    )),
17843                },
17844            )
17845            .await
17846            .unwrap();
17847            if routed {
17848                questions
17849                    .update(&q.id, |q| {
17850                        q.routed_task = Some("another-owner".into());
17851                        Ok(())
17852                    })
17853                    .unwrap();
17854            } else {
17855                let mut task = queue.get(&owner).unwrap();
17856                task.hold_manual(Some("new owner decision".into()));
17857                // Keep the generation to exercise the separate owner-decision binding.
17858                task.status = crate::queue::TaskStatus::Queued;
17859                queue.put(&mut task).unwrap();
17860            }
17861            runner.state = RunState::load(&runner.state.id).unwrap();
17862            runner.sync_to_base().await.unwrap();
17863            let approval = runner
17864                .state
17865                .base_sync_recovery
17866                .authorizations
17867                .last()
17868                .unwrap();
17869            assert!(approval.consumed);
17870            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
17871                "routing"
17872            } else {
17873                "owner decision"
17874            }));
17875            assert_eq!(
17876                runner.state.base_sync.as_ref().unwrap().attempts,
17877                BASE_SYNC_ROUNDS
17878            );
17879            assert_eq!(
17880                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17881                head
17882            );
17883        }
17884    }
17885
17886    #[cfg(unix)]
17887    #[tokio::test]
17888    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
17889        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
17890        if std::env::var_os(CHILD).is_none() {
17891            let home = tempfile::tempdir().unwrap();
17892            let output = std::process::Command::new(std::env::current_exe().unwrap())
17893                .args([
17894                    "--exact",
17895                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
17896                    "--nocapture",
17897                ])
17898                .env(CHILD, "1")
17899                .env("MAGI_HOME", home.path())
17900                .env("MAGI_WORKER_HOME", home.path())
17901                .env("MAGI_WORKER_ID", "abcdef")
17902                .output()
17903                .unwrap();
17904            assert!(
17905                output.status.success()
17906                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17907                "{}\n{}",
17908                String::from_utf8_lossy(&output.stdout),
17909                String::from_utf8_lossy(&output.stderr)
17910            );
17911            return;
17912        }
17913        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
17914        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17915        let home = crate::run::home();
17916        let queue = crate::queue::Queue::open();
17917        let mut owner = queue.get(&task).unwrap();
17918        owner.release_operator("test-release", None);
17919        owner.start(runner.state.id.clone());
17920        queue.put(&mut owner).unwrap();
17921        runner.state.driver_exited = true;
17922        runner.state.task_instruction = Some(owner.instruction.clone());
17923        runner.state.save().unwrap();
17924        let _claim = queue.claim(&task).unwrap();
17925        let reserve = |id: &str| {
17926            let directory = home.join("workers/jobs").join(id);
17927            std::fs::create_dir_all(&directory).unwrap();
17928            let job = crate::worker::Job {
17929                id: id.into(),
17930                sequence: 1,
17931                kind: "task".into(),
17932                key: format!("task:{task}"),
17933                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
17934                generation: "fixture-generation".into(),
17935                version: None,
17936                status: crate::worker::Status::Running,
17937                result: None,
17938                pid: Some(std::process::id()),
17939                created_at: 0,
17940                finished_at: None,
17941            };
17942            std::fs::write(
17943                directory.join("job.json"),
17944                serde_json::to_vec(&job).unwrap(),
17945            )
17946            .unwrap();
17947            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
17948        };
17949        let _own = reserve("abcdef");
17950        let other = reserve("fedcba");
17951        assert!(
17952            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17953                .await
17954                .is_err()
17955        );
17956        assert!(
17957            RunState::load(&runner.state.id)
17958                .unwrap()
17959                .base_sync_recovery
17960                .authorizations
17961                .is_empty()
17962        );
17963        drop(other);
17964        assert!(crate::daemon::is_working_on(
17965            &home,
17966            &runner.state.id,
17967            Timestamp::now()
17968        ));
17969        assert!(
17970            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
17971        );
17972        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17973            .await
17974            .unwrap();
17975        assert!(
17976            RunState::load(&runner.state.id)
17977                .unwrap()
17978                .base_recovery_pending()
17979        );
17980    }
17981
17982    #[cfg(unix)]
17983    #[tokio::test]
17984    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
17985        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17986        let home = crate::run::home();
17987        runner.state.driver_pid = Some(std::process::id());
17988        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
17989        runner.state.driver_exited = false;
17990        runner.state.begin_pass();
17991        runner.state.save().unwrap();
17992        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
17993        driver.record(&runner.state).unwrap();
17994        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
17995        // Preserve the durable claim as if the process died before Drop saved.
17996        drop(driver);
17997        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
17998        assert_eq!(
17999            runner.state.liveness_under(&home, false),
18000            crate::run::Liveness::Dead
18001        );
18002        let queue = crate::queue::Queue::open();
18003        let _claim = queue.claim(&task).unwrap();
18004        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18005            .await
18006            .unwrap();
18007        let disk = RunState::load(&runner.state.id).unwrap();
18008        assert!(!disk.driver_exited);
18009        assert!(disk.base_recovery_pending());
18010    }
18011
18012    #[cfg(unix)]
18013    #[tokio::test]
18014    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
18015        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
18016        if std::env::var_os(CHILD).is_none() {
18017            use std::os::unix::fs::PermissionsExt;
18018            let tmp = tempfile::tempdir().unwrap();
18019            let gh = tmp.path().join("gh");
18020            std::fs::write(&gh, r#"#!/bin/sh
18021case "$1 $2" in
18022  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
18023  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
18024  *) exit 2 ;;
18025esac
18026"#).unwrap();
18027            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
18028            let mut paths = vec![tmp.path().to_path_buf()];
18029            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
18030            let output = std::process::Command::new(std::env::current_exe().unwrap())
18031                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
18032                .env(CHILD, "1")
18033                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
18034                .env("PATH", std::env::join_paths(paths).unwrap())
18035                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
18036                .output().unwrap();
18037            assert!(
18038                output.status.success()
18039                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18040                "{}\n{}",
18041                String::from_utf8_lossy(&output.stdout),
18042                String::from_utf8_lossy(&output.stderr)
18043            );
18044            return;
18045        }
18046        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18047        let repo = runner.state.repo.clone();
18048        git::git(&repo, &["checkout", "main"]).await.unwrap();
18049        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
18050        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18051        git::git(&repo, &["checkout", "fix/retained"])
18052            .await
18053            .unwrap();
18054        runner.state.pr = Some(crate::run::PrRecord {
18055            url: "https://example.test/project/pull/1".into(),
18056            number: 1,
18057            state: "open".into(),
18058            checks: "unknown".into(),
18059            round: 0,
18060            rounds: 1,
18061            red_at_merge: Vec::new(),
18062        });
18063        runner.sync_to_base().await.unwrap();
18064        assert_eq!(runner.state.status, RunStatus::Blocked);
18065        assert_eq!(
18066            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18067            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
18068        );
18069        assert!(runner.state.base_sync_closure_pending());
18070        assert!(crate::handover::can_resume(&runner.state));
18071        let queue = crate::queue::Queue::open();
18072        assert!(!crate::base_sync_recovery::held_task(
18073            &queue,
18074            &queue.get(&task).unwrap()
18075        ));
18076        assert!(runner.state.authorize_base_sync(&task).is_err());
18077        // Legacy closure stops have no typed stop but must retain the checkpoint.
18078        runner.state.base_sync_recovery.stop = None;
18079        runner.state.status = RunStatus::Voting;
18080        runner.state.gate_ran = true;
18081        runner.state.config.graph.review_rounds = 0;
18082        runner.state.save().unwrap();
18083        assert!(crate::handover::can_resume(&runner.state));
18084        runner.state = RunState::load(&runner.state.id).unwrap();
18085        runner.execute_graph().await.unwrap();
18086        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18087        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18088        assert_eq!(
18089            runner.state.base_sync.as_ref().unwrap().attempts,
18090            BASE_SYNC_ROUNDS
18091        );
18092        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18093        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18094        assert!(runner.state.reviews.is_empty());
18095        assert!(runner.state.gate.is_empty());
18096    }
18097
18098    #[cfg(unix)]
18099    #[tokio::test]
18100    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18101        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18102        runner.state.driver_exited = true;
18103        runner.state.save().unwrap();
18104        let home = crate::run::home();
18105        let queue = crate::queue::Queue::open();
18106        let _claim = queue.claim(&task).unwrap();
18107        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18108        assert!(
18109            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18110                .await
18111                .is_err()
18112        );
18113        drop(lease);
18114        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18115        assert!(
18116            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18117                .await
18118                .is_err()
18119        );
18120        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18121        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18122            .await
18123            .unwrap();
18124        let disk = RunState::load(&runner.state.id).unwrap();
18125        assert!(disk.base_recovery_pending());
18126        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18127        assert!(
18128            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18129                .await
18130                .is_err()
18131        );
18132        assert_eq!(
18133            RunState::load(&runner.state.id)
18134                .unwrap()
18135                .base_sync_recovery
18136                .authorizations
18137                .len(),
18138            1
18139        );
18140        let mut owner = queue.get(&task).unwrap();
18141        owner.runs.push("20260101-000000-ffff".into());
18142        queue.put(&mut owner).unwrap();
18143        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18144            .await
18145            .unwrap_err();
18146        assert!(error.to_string().contains("run task ownership changed"));
18147    }
18148
18149    #[cfg(unix)]
18150    #[tokio::test]
18151    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18152        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18153        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18154        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18155        legacy["status"] = serde_json::json!("voting");
18156        runner.state = serde_json::from_value(legacy).unwrap();
18157        runner.state.save().unwrap();
18158        for _ in 0..3 {
18159            runner.execute_graph().await.unwrap();
18160            assert_eq!(runner.state.status, RunStatus::Blocked);
18161            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18162            assert!(!crate::handover::can_resume(&runner.state));
18163            assert_eq!(
18164                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18165                head
18166            );
18167            assert!(runner.state.reviews.is_empty());
18168            assert!(!runner.state.gate_ran);
18169        }
18170        let notice = crate::notices::run_ended(&runner.state).unwrap();
18171        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18172        runner.state.begin_pass();
18173        runner.state.status = RunStatus::Voting;
18174        runner.deliberate().await.unwrap();
18175        runner.vote().await.unwrap();
18176        runner.finish_after_tally().await.unwrap();
18177        assert_eq!(runner.state.status, RunStatus::Blocked);
18178        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18179        assert_eq!(
18180            crate::notices::run_ended(&runner.state).unwrap().since,
18181            notice.since
18182        );
18183    }
18184
18185    #[cfg(unix)]
18186    #[tokio::test]
18187    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18188        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18189        for detail in [
18190            "fix/retained conflicts with origin/main and did not rebase: conflict",
18191            "rebased fix/retained locally but origin refused the push",
18192            "unknown failure",
18193        ] {
18194            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18195            runner.state.record_base_sync_stop(&head);
18196            assert!(runner.state.authorize_base_sync(&task).is_err());
18197            runner.state.status = RunStatus::Voting;
18198            runner.execute_graph().await.unwrap();
18199            assert_eq!(runner.state.status, RunStatus::Blocked);
18200            assert!(!crate::handover::can_resume(&runner.state));
18201            assert_eq!(
18202                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18203                head
18204            );
18205        }
18206    }
18207
18208    #[cfg(unix)]
18209    #[tokio::test]
18210    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18211        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18212        runner.state.authorize_base_sync(&task).unwrap();
18213        assert!(runner.state.consume_base_recovery(&head));
18214        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18215        runner.state.reserve_base_operation(&head, &tip);
18216        runner.state.save().unwrap();
18217        runner.state = RunState::load(&runner.state.id).unwrap();
18218        assert!(!runner.state.consume_base_recovery(&head));
18219        runner.sync_to_base().await.unwrap();
18220        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18221        assert_eq!(runner.state.base_episode_used(), 1);
18222        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18223        assert!(
18224            runner
18225                .state
18226                .base_sync_recovery
18227                .operations
18228                .last()
18229                .unwrap()
18230                .finished
18231        );
18232        assert!(!runner.state.base_sync_blocked());
18233        runner.sync_to_base().await.unwrap();
18234        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18235    }
18236
18237    #[cfg(unix)]
18238    #[tokio::test]
18239    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18240        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18241        // Both historical diagnostic spellings retain an exhaustion identity.
18242        let original = runner
18243            .state
18244            .base_sync
18245            .as_ref()
18246            .unwrap()
18247            .conflict
18248            .clone()
18249            .unwrap();
18250        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18251            original
18252                .replace("synchronization(s)", "rebase(s)")
18253                .replace("synchronizing", "rebasing"),
18254        );
18255        runner.state.base_sync_recovery = Default::default();
18256        runner.state.record_base_sync_stop(&head);
18257        assert_eq!(
18258            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18259            crate::base_sync_recovery::StopKind::Exhausted
18260        );
18261        runner.state.authorize_base_sync(&task).unwrap();
18262        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18263        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18264            .as_object_mut()
18265            .unwrap();
18266        auth.remove("interval");
18267        auth.remove("scope");
18268        runner.state = serde_json::from_value(legacy).unwrap();
18269        assert!(runner.state.consume_base_recovery(&head));
18270        assert_eq!(runner.state.base_episode_used(), 3);
18271        runner.sync_to_base().await.unwrap();
18272        assert_eq!(runner.state.base_episode_used(), 4);
18273        runner.state.resource_block = Some(crate::run::ResourceBlock {
18274            node: "gate".into(),
18275            kind: "cache".into(),
18276            detail: "legacy wait".into(),
18277            at: Timestamp::now(),
18278            cause: crate::run::ResourceBlockCause::Unrecorded,
18279        });
18280        runner.state.save().unwrap();
18281        assert!(
18282            runner
18283                .state
18284                .base_sync_recovery
18285                .episodes
18286                .last()
18287                .unwrap()
18288                .boundary
18289                .is_none()
18290        );
18291        runner.state.resource_block = None;
18292        advance_base_fixture(&runner).await;
18293        runner.sync_to_base().await.unwrap();
18294        assert!(runner.state.base_sync_blocked());
18295        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18296    }
18297
18298    #[cfg(unix)]
18299    async fn advance_base_fixture(runner: &Runner) {
18300        let repo = &runner.state.repo;
18301        for args in [
18302            vec!["checkout", "main"],
18303            vec!["commit", "--allow-empty", "-m", "base advanced"],
18304            vec!["push", "origin", "main"],
18305            vec!["checkout", "fix/retained"],
18306        ] {
18307            git::git(repo, &args).await.unwrap();
18308        }
18309    }
18310
18311    #[cfg(unix)]
18312    fn fresh_base_interval_fixture(runner: &mut Runner) {
18313        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18314        runner.state.base_sync.as_mut().unwrap().conflict = None;
18315        runner.state.base_sync_recovery = Default::default();
18316        runner.state.status = RunStatus::Voting;
18317    }
18318
18319    #[cfg(unix)]
18320    #[tokio::test]
18321    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18322        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18323        fresh_base_interval_fixture(&mut runner);
18324        runner.state.begin_pass();
18325        runner.sync_to_base().await.unwrap();
18326        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18327        runner.state.resource_block = Some(crate::run::ResourceBlock {
18328            node: "gate".into(),
18329            kind: "build cache".into(),
18330            detail: "busy".into(),
18331            at: Timestamp::now(),
18332            cause: crate::run::ResourceBlockCause::Timeout {
18333                waited_secs: 1,
18334                limit_secs: 1,
18335            },
18336        });
18337        runner.state.save().unwrap();
18338        let queue = crate::queue::Queue::open();
18339        let mut owner = queue.get(&task).unwrap();
18340        runner.state.task_instruction = Some(owner.instruction.clone());
18341        owner.release_operator("fixture-owner", None);
18342        queue.put(&mut owner).unwrap();
18343        let approval = owner.resumption.clone().unwrap();
18344        runner.state.resource_block = None;
18345        runner.state.save().unwrap();
18346        runner.state = RunState::load(&runner.state.id).unwrap();
18347        advance_base_fixture(&runner).await;
18348        runner.sync_to_base().await.unwrap();
18349        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18350        assert_eq!(runner.state.base_episode_used(), 1);
18351        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18352        assert!(
18353            runner.state.base_sync_recovery.episodes[0]
18354                .boundary
18355                .as_ref()
18356                .unwrap()
18357                .consumed
18358        );
18359        assert!(
18360            !runner
18361                .state
18362                .renew_base_episode(&task, &approval, &head, "base")
18363        );
18364        for _ in 0..3 {
18365            owner.release_operator("fixture-owner", None);
18366            queue.put(&mut owner).unwrap();
18367            runner.state = RunState::load(&runner.state.id).unwrap();
18368            runner.state.begin_pass();
18369            runner.sync_to_base().await.unwrap();
18370            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18371            assert_eq!(runner.state.base_episode_used(), 1);
18372        }
18373        runner.state.resource_block = Some(crate::run::ResourceBlock {
18374            node: "gate".into(),
18375            kind: "disk pressure".into(),
18376            detail: "free space required".into(),
18377            at: Timestamp::now(),
18378            cause: crate::run::ResourceBlockCause::Other,
18379        });
18380        runner.state.end_pass_parked(ParkCause::Interrupt {
18381            reason: "disk pressure".into(),
18382        });
18383        runner.state.save().unwrap();
18384        owner.release_operator("fixture-owner-after-disk", None);
18385        queue.put(&mut owner).unwrap();
18386        runner.state.resource_block = None;
18387        advance_base_fixture(&runner).await;
18388        runner.sync_to_base().await.unwrap();
18389        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
18390        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
18391        assert_eq!(runner.state.base_episode_used(), 1);
18392        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
18393    }
18394
18395    #[cfg(unix)]
18396    #[tokio::test]
18397    async fn base_recovery_continuous_advancement_stops_at_four() {
18398        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
18399        fresh_base_interval_fixture(&mut runner);
18400        for spent in 1..=BASE_SYNC_ROUNDS {
18401            runner.sync_to_base().await.unwrap();
18402            assert!(!runner.state.base_sync_blocked());
18403            assert_eq!(runner.state.base_episode_used(), spent);
18404            advance_base_fixture(&runner).await;
18405        }
18406        runner.sync_to_base().await.unwrap();
18407        assert_eq!(
18408            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18409            crate::base_sync_recovery::StopKind::Exhausted
18410        );
18411        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
18412        assert!(stop.unverified_sync);
18413        let action = runner.state.base_sync_next_action();
18414        assert!(action.contains("never reached its gate"));
18415        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
18416        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18417        runner.state = RunState::load(&runner.state.id).unwrap();
18418        runner.sync_to_base().await.unwrap();
18419        assert_eq!(runner.state.base_episode_used(), 4);
18420        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18421    }
18422
18423    #[cfg(unix)]
18424    #[tokio::test]
18425    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
18426        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18427        runner.state.ensure_base_episode();
18428        // Verification progress alone is not evidence of a successful sync.
18429        runner.state.record_base_progress(&head);
18430        runner.state.base_sync_recovery.stop = None;
18431        runner.state.record_base_sync_stop(&head);
18432        assert!(
18433            !runner
18434                .state
18435                .base_sync_recovery
18436                .stop
18437                .as_ref()
18438                .unwrap()
18439                .unverified_sync
18440        );
18441
18442        runner.state.finish_base_operation(Some(&head));
18443        // A gate for another head cannot verify this synchronization.
18444        runner.state.gate_ran = true;
18445        runner.state.gate_head = Some("older-head".into());
18446        runner.state.base_sync_recovery.stop = None;
18447        runner.state.record_base_sync_stop(&head);
18448        runner.state.save().unwrap();
18449        runner.state = RunState::load(&runner.state.id).unwrap();
18450        assert!(
18451            runner
18452                .state
18453                .base_sync_recovery
18454                .stop
18455                .as_ref()
18456                .unwrap()
18457                .unverified_sync
18458        );
18459
18460        runner.state.gate_head = Some(head.clone());
18461        runner.state.base_sync_recovery.stop = None;
18462        runner.state.record_base_sync_stop(&head);
18463        assert!(
18464            !runner
18465                .state
18466                .base_sync_recovery
18467                .stop
18468                .as_ref()
18469                .unwrap()
18470                .unverified_sync
18471        );
18472        assert!(
18473            !runner
18474                .state
18475                .base_sync_next_action()
18476                .contains("never reached its gate")
18477        );
18478
18479        // Historical records cannot establish the missing synchronization evidence.
18480        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18481        legacy["base_sync_recovery"]["stop"]
18482            .as_object_mut()
18483            .unwrap()
18484            .remove("unverified_sync");
18485        legacy["base_sync_recovery"]["episodes"][0]
18486            .as_object_mut()
18487            .unwrap()
18488            .remove("last_sync_head");
18489        runner.state = serde_json::from_value(legacy).unwrap();
18490        assert!(
18491            !runner
18492                .state
18493                .base_sync_recovery
18494                .stop
18495                .as_ref()
18496                .unwrap()
18497                .unverified_sync
18498        );
18499        assert!(
18500            runner.state.base_sync_recovery.episodes[0]
18501                .last_sync_head
18502                .is_none()
18503        );
18504    }
18505
18506    #[cfg(unix)]
18507    #[tokio::test]
18508    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
18509        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18510        runner.state.authorize_base_sync(&task).unwrap();
18511        assert!(
18512            runner
18513                .state
18514                .base_sync_next_action()
18515                .contains("Approval recorded")
18516        );
18517        assert!(
18518            runner
18519                .state
18520                .base_sync_next_action()
18521                .contains("4/4 in episode 0, 4 lifetime")
18522        );
18523        assert!(runner.state.consume_base_recovery(&head));
18524        assert!(
18525            runner
18526                .state
18527                .base_sync_next_action()
18528                .contains("0/4 in episode 1, 4 lifetime")
18529        );
18530    }
18531
18532    #[cfg(unix)]
18533    #[tokio::test]
18534    async fn base_recovery_changed_head_invalidates_without_spending() {
18535        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18536        runner.state.authorize_base_sync(&task).unwrap();
18537        git::git(
18538            &runner.state.repo,
18539            &["commit", "--allow-empty", "-m", "external head change"],
18540        )
18541        .await
18542        .unwrap();
18543        runner.sync_to_base().await.unwrap();
18544        let a = runner
18545            .state
18546            .base_sync_recovery
18547            .authorizations
18548            .last()
18549            .unwrap();
18550        assert!(a.consumed);
18551        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
18552        runner.state = RunState::load(&runner.state.id).unwrap();
18553        assert!(
18554            runner
18555                .state
18556                .base_sync_next_action()
18557                .contains("Approval invalidated")
18558        );
18559        assert!(!runner.state.base_recovery_pending());
18560        assert!(runner.state.base_sync_blocked());
18561        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18562    }
18563
18564    #[cfg(unix)]
18565    #[tokio::test]
18566    async fn base_recovery_stale_fetched_base_invalidates_approval() {
18567        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18568        runner.state.driver_exited = true;
18569        runner.state.save().unwrap();
18570        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18571            .await
18572            .unwrap();
18573        runner.state = RunState::load(&runner.state.id).unwrap();
18574        advance_base_fixture(&runner).await;
18575        runner.sync_to_base().await.unwrap();
18576        let a = runner
18577            .state
18578            .base_sync_recovery
18579            .authorizations
18580            .last()
18581            .unwrap();
18582        assert!(
18583            a.consumed
18584                && a.invalidated
18585                    .as_deref()
18586                    .unwrap()
18587                    .contains("fetched base changed")
18588        );
18589        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18590        assert_eq!(
18591            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18592            head
18593        );
18594        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18595            .await
18596            .unwrap();
18597        runner.state = RunState::load(&runner.state.id).unwrap();
18598        runner.sync_to_base().await.unwrap();
18599        assert!(!runner.state.base_sync_blocked());
18600        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18601    }
18602
18603    #[cfg(unix)]
18604    #[tokio::test]
18605    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
18606        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18607        runner.state.authorize_base_sync(&task).unwrap();
18608        assert!(runner.state.consume_base_recovery(&head));
18609        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18610        runner.state.reserve_base_operation(&head, &tip);
18611        runner.state.save().unwrap();
18612        let scratch = runner.state.dir().join("base-sync");
18613        assert_eq!(
18614            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18615                .await
18616                .unwrap(),
18617            crate::rebase::Rebased::Applied
18618        );
18619        runner.state = RunState::load(&runner.state.id).unwrap();
18620        runner.sync_to_base().await.unwrap();
18621        assert!(
18622            runner
18623                .state
18624                .base_sync_recovery
18625                .operations
18626                .last()
18627                .unwrap()
18628                .finished
18629        );
18630        assert_eq!(runner.state.base_episode_used(), 1);
18631        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18632        assert!(!runner.state.base_sync_blocked());
18633    }
18634
18635    #[cfg(unix)]
18636    #[tokio::test]
18637    async fn base_recovery_crash_preserves_untracked_files() {
18638        for ignored in [false, true] {
18639            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18640            runner.state.authorize_base_sync(&task).unwrap();
18641            assert!(runner.state.consume_base_recovery(&head));
18642            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18643            runner.state.reserve_base_operation(&head, &tip);
18644            runner.state.save().unwrap();
18645            let scratch = runner.state.dir().join("base-sync");
18646            assert_eq!(
18647                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18648                    .await
18649                    .unwrap(),
18650                crate::rebase::Rebased::Applied
18651            );
18652            let repo = &runner.state.repo;
18653            let result = git::rev_parse(repo, "HEAD").await.unwrap();
18654            assert_ne!(result, head);
18655            if ignored {
18656                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
18657                    .await
18658                    .unwrap();
18659                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
18660            }
18661            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
18662            assert!(
18663                git::git_raw(repo, &["diff", "--quiet", &head])
18664                    .await
18665                    .unwrap()
18666                    .ok()
18667            );
18668            // Resume after the branch moved, before its checkout was reset.
18669            runner.state = RunState::load(&runner.state.id).unwrap();
18670            runner.sync_to_base().await.unwrap();
18671            assert!(runner.state.base_sync_blocked());
18672            assert!(!runner.state.base_sync_recovery.operations[0].finished);
18673            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18674            assert_eq!(
18675                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18676                result
18677            );
18678            assert_eq!(
18679                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
18680                "retained work\n"
18681            );
18682            assert!(
18683                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
18684                    .await
18685                    .unwrap()
18686                    .ok()
18687            );
18688        }
18689    }
18690
18691    #[cfg(unix)]
18692    #[tokio::test]
18693    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
18694        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18695        runner.state.authorize_base_sync(&task).unwrap();
18696        assert!(runner.state.consume_base_recovery(&head));
18697        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18698        runner.state.reserve_base_operation(&head, &tip);
18699        runner.state.save().unwrap();
18700        let scratch = runner.state.dir().join("base-sync");
18701        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18702            .await
18703            .unwrap();
18704        git::sync_to_head(&runner.state.repo).await.unwrap();
18705        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
18706        git::git(&runner.state.repo, &["add", "foreign"])
18707            .await
18708            .unwrap();
18709        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
18710            .await
18711            .unwrap();
18712        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18713        runner.state = RunState::load(&runner.state.id).unwrap();
18714        runner.sync_to_base().await.unwrap();
18715        assert!(runner.state.base_sync_blocked());
18716        assert!(
18717            !runner
18718                .state
18719                .base_sync_recovery
18720                .operations
18721                .last()
18722                .unwrap()
18723                .finished
18724        );
18725        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18726        assert_eq!(
18727            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18728            foreign_head
18729        );
18730    }
18731
18732    #[cfg(unix)]
18733    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
18734    {
18735        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18736        fresh_base_interval_fixture(&mut runner);
18737        let repo = &runner.state.repo;
18738        git::git(repo, &["checkout", "main"]).await.unwrap();
18739        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
18740        git::git(repo, &["add", "retained"]).await.unwrap();
18741        git::git(repo, &["commit", "-m", "upstream retained change"])
18742            .await
18743            .unwrap();
18744        git::git(repo, &["push", "origin", "main"]).await.unwrap();
18745        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
18746        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
18747        let scratch = runner.state.dir().join("base-sync");
18748        assert!(matches!(
18749            git::rebase_start(repo, &scratch, "fix/retained", &tip)
18750                .await
18751                .unwrap(),
18752            git::RebaseStart::Conflicted(_)
18753        ));
18754        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18755            agent: "fixture".into(),
18756            paths: vec!["retained".into()],
18757            from: Some(head.clone()),
18758            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
18759            index_outside: None,
18760            finished: false,
18761            error: None,
18762            launcher: None,
18763            infra: None,
18764            outage: None,
18765        });
18766        (tmp, runner, head, tip, scratch)
18767    }
18768
18769    #[cfg(unix)]
18770    #[tokio::test]
18771    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
18772        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18773        // A resource stop from before reservations existed, with resolved
18774        // contents left for the launcher's ordinary staging continuation.
18775        std::fs::write(
18776            scratch.join("retained"),
18777            "upstream and retained resolution\n",
18778        )
18779        .unwrap();
18780        runner.state.resource_block = Some(crate::run::ResourceBlock {
18781            node: "rebase".into(),
18782            kind: "repository coordination".into(),
18783            detail: "busy".into(),
18784            at: Timestamp::now(),
18785            cause: crate::run::ResourceBlockCause::Other,
18786        });
18787        runner.state.save().unwrap();
18788        // Advance the remote without moving either checkout participating
18789        // in the standing rebase.
18790        let newer = git::git(
18791            &runner.state.repo,
18792            &[
18793                "commit-tree",
18794                "main^{tree}",
18795                "-p",
18796                "main",
18797                "-m",
18798                "base advanced during wait",
18799            ],
18800        )
18801        .await
18802        .unwrap();
18803        git::git(
18804            &runner.state.repo,
18805            &[
18806                "push",
18807                "origin",
18808                &format!("{}:refs/heads/main", newer.trim()),
18809            ],
18810        )
18811        .await
18812        .unwrap();
18813        runner.state = RunState::load(&runner.state.id).unwrap();
18814        runner.state.resource_block = None;
18815        runner.sync_to_base().await.unwrap();
18816        assert!(!runner.state.base_sync_blocked());
18817        let op = &runner.state.base_sync_recovery.operations[0];
18818        assert_eq!(op.head, head);
18819        assert_eq!(op.tip, tip);
18820        assert!(op.finished);
18821        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18822        assert_eq!(runner.state.rebase_fixes.len(), 1);
18823        let latest = git::rev_parse(&runner.state.repo, "origin/main")
18824            .await
18825            .unwrap();
18826        assert_ne!(latest, tip);
18827        runner.state = RunState::load(&runner.state.id).unwrap();
18828        runner.sync_to_base().await.unwrap();
18829        assert!(!runner.state.base_sync_blocked());
18830        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
18831        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
18832        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18833    }
18834
18835    #[cfg(unix)]
18836    #[tokio::test]
18837    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
18838        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18839        runner.state.reserve_base_operation(&head, &tip);
18840        runner.state.save().unwrap();
18841        std::fs::write(
18842            scratch.join("retained"),
18843            "upstream and retained resolution\n",
18844        )
18845        .unwrap();
18846        git::git(&scratch, &["add", "retained"]).await.unwrap();
18847        git::git(
18848            &scratch,
18849            &["-c", "core.editor=true", "rebase", "--continue"],
18850        )
18851        .await
18852        .unwrap();
18853        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18854        assert!(
18855            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18856                .await
18857                .unwrap()
18858                .is_empty()
18859        );
18860        assert_eq!(
18861            crate::rebase::finish(
18862                &mut runner.state,
18863                &scratch,
18864                "fix/retained",
18865                &head,
18866                &tip,
18867                &["retained".into()],
18868                ""
18869            )
18870            .await
18871            .unwrap(),
18872            crate::rebase::Rebased::Applied
18873        );
18874        assert!(!scratch.exists());
18875        // Simulate losing the caller before finish_base_operation/save.
18876        runner.state = RunState::load(&runner.state.id).unwrap();
18877        let op = &runner.state.base_sync_recovery.operations[0];
18878        assert!(!op.finished);
18879        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
18880        runner.sync_to_base().await.unwrap();
18881        assert!(!runner.state.base_sync_blocked());
18882        assert!(runner.state.base_sync_recovery.operations[0].finished);
18883        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18884        assert_eq!(runner.state.rebase_fixes.len(), 1);
18885        let winner = runner.state.winner().unwrap().clone();
18886        let wait = runner.repository_wait();
18887        assert!(
18888            verify_current_head(&mut runner.state, &winner, &wait)
18889                .await
18890                .unwrap()
18891        );
18892        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18893    }
18894
18895    #[cfg(unix)]
18896    #[tokio::test]
18897    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
18898        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
18899            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18900            runner.state.reserve_base_operation(&head, &tip);
18901            runner.state.save().unwrap();
18902            std::fs::write(
18903                scratch.join("retained"),
18904                "upstream and retained resolution\n",
18905            )
18906            .unwrap();
18907            git::git(&scratch, &["add", "retained"]).await.unwrap();
18908            git::git(
18909                &scratch,
18910                &["-c", "core.editor=true", "rebase", "--continue"],
18911            )
18912            .await
18913            .unwrap();
18914            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18915            assert!(!git::rebase_in_progress(&scratch).await);
18916            assert!(
18917                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18918                    .await
18919                    .unwrap()
18920                    .is_empty()
18921            );
18922            match damage {
18923                Some("record") => {
18924                    let path =
18925                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
18926                            .await
18927                            .unwrap();
18928                    std::fs::write(scratch.join(path), "").unwrap();
18929                }
18930                Some("foreign") => {
18931                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
18932                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
18933                    git::git(&scratch, &["commit", "-m", "foreign work"])
18934                        .await
18935                        .unwrap();
18936                }
18937                Some("dirty") => {
18938                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
18939                }
18940                _ => {}
18941            }
18942            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18943            // Crash immediately after Git continuation, before finish runs.
18944            runner.state = RunState::load(&runner.state.id).unwrap();
18945            assert!(
18946                runner.state.base_sync_recovery.operations[0]
18947                    .validated_head
18948                    .is_none()
18949            );
18950            runner.sync_to_base().await.unwrap();
18951            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18952            assert_eq!(runner.state.base_episode_used(), 1);
18953            assert_eq!(runner.state.rebase_fixes.len(), 1);
18954            assert_eq!(
18955                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18956                retained_head
18957            );
18958            if damage.is_some() {
18959                assert!(runner.state.base_sync_blocked());
18960                assert!(scratch.exists());
18961                assert!(!runner.state.base_sync_recovery.operations[0].finished);
18962                assert!(
18963                    runner.state.base_sync_recovery.operations[0]
18964                        .validated_head
18965                        .is_none()
18966                );
18967            } else {
18968                assert!(!runner.state.base_sync_blocked());
18969                assert!(!scratch.exists());
18970                assert!(runner.state.base_sync_recovery.operations[0].finished);
18971                assert_eq!(
18972                    runner.state.base_sync_recovery.operations[0]
18973                        .validated_head
18974                        .as_deref(),
18975                    Some(result.as_str())
18976                );
18977                let winner = runner.state.winner().unwrap().clone();
18978                let wait = runner.repository_wait();
18979                assert!(
18980                    verify_current_head(&mut runner.state, &winner, &wait)
18981                        .await
18982                        .unwrap()
18983                );
18984                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18985                runner.state = RunState::load(&runner.state.id).unwrap();
18986                runner.sync_to_base().await.unwrap();
18987                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18988            }
18989        }
18990    }
18991
18992    #[cfg(unix)]
18993    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
18994        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18995        // This is an ordinary gate stop, not an authorized base-budget recovery.
18996        runner.state.prep_complete = Some(true);
18997        runner.state.base_sync = None;
18998        runner.state.base_sync_recovery = Default::default();
18999        runner.state.config.graph.gate_fix_rounds = 1;
19000        let mut review = review_round(true, 0, 1, 1, false, true);
19001        review.head = head.clone();
19002        review.verified_head = Some(head.clone());
19003        runner.state.reviews = vec![review];
19004        runner.state.gate = vec![CommandOutcome {
19005            command: "old gate".into(),
19006            code: Some(1),
19007            output_tail: "old failure".into(),
19008            duration_ms: 0,
19009            resource_blocked: false,
19010            ..Default::default()
19011        }];
19012        runner.state.gate_head = Some(head.clone());
19013        runner.state.gate_ran = true;
19014        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
19015            agent: "fixture".into(),
19016            failed: runner.state.gate.clone(),
19017            notes: "spent".into(),
19018            committed: false,
19019            error: None,
19020        }];
19021        runner.state.land_approval = Some(crate::run::LandApproval {
19022            question: "old approval".into(),
19023            head: head.clone(),
19024        });
19025        runner.state.status = RunStatus::Blocked;
19026        (tmp, runner, head)
19027    }
19028
19029    #[cfg(unix)]
19030    #[tokio::test]
19031    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
19032        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
19033            let (tmp, mut runner, old) = resumed_gate_fixture().await;
19034            let phases = tmp.path().join("phases");
19035            runner.state.config.verify.e2e = vec![format!(
19036                "echo e2e >> '{}'; {}",
19037                phases.display(),
19038                if e2e_ok {
19039                    "true"
19040                } else {
19041                    "echo new-e2e-failure; false"
19042                }
19043            )];
19044            runner.state.config.verify.gate = vec![format!(
19045                "echo gate >> '{}'; {}",
19046                phases.display(),
19047                if gate_ok {
19048                    "true"
19049                } else {
19050                    "echo new-gate-failure; false"
19051                }
19052            )];
19053            runner.state.save().unwrap();
19054            runner.state = RunState::load(&runner.state.id).unwrap();
19055            runner.sync_to_base().await.unwrap();
19056            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19057            assert_ne!(head, old);
19058            // Reentry after Git updated but before verification was invalidated.
19059            runner.state = RunState::load(&runner.state.id).unwrap();
19060            runner.execute_graph().await.unwrap();
19061            assert_eq!(runner.state.gate_fixes.len(), 1);
19062            assert_eq!(runner.state.reviews.len(), 1);
19063            assert_eq!(runner.state.reviews[0].head, old);
19064            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
19065            assert_eq!(runner.state.verification_history.len(), 1);
19066            let history = &runner.state.verification_history[0];
19067            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
19068            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19069            assert!(history.archived_at.is_some());
19070            assert_eq!(history.fixes_spent, Some(1));
19071            assert_eq!(history.gate[0].output_tail, "old failure");
19072            let archive_events: Vec<_> = runner
19073                .state
19074                .events
19075                .iter()
19076                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
19077                .collect();
19078            assert_eq!(archive_events.len(), 1);
19079            assert!(archive_events[0].message.contains(&short(&old)));
19080            assert!(archive_events[0].message.contains(&short(&head)));
19081            assert!(
19082                archive_events[0]
19083                    .message
19084                    .contains("1 gate-fix round(s) already spent stay spent")
19085            );
19086            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19087            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19088            if e2e_ok {
19089                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19090                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19091            } else {
19092                assert!(!runner.state.gate_ran);
19093            }
19094            assert_eq!(
19095                runner.state.status,
19096                if e2e_ok && gate_ok {
19097                    RunStatus::Ready
19098                } else {
19099                    RunStatus::Blocked
19100                }
19101            );
19102            if !e2e_ok || !gate_ok {
19103                let cause = runner.state.verification_blocking_cause().unwrap();
19104                assert!(cause.contains(&head));
19105                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19106                // A later successful progress event must not become the cause.
19107                runner.state.event("land", "rebased successfully");
19108                let notice = crate::notices::run_ended(&runner.state).unwrap();
19109                assert!(!format!("{notice:?}").contains("rebased successfully"));
19110                assert!(runner.state.merge.is_none());
19111            }
19112            let before = std::fs::read_to_string(&phases).unwrap();
19113            runner.state.save().unwrap();
19114            runner.state = RunState::load(&runner.state.id).unwrap();
19115            runner.review_loop().await.unwrap();
19116            runner.gate().await.unwrap();
19117            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19118            assert_eq!(runner.state.verification_history.len(), 1);
19119            let history = &runner.state.verification_history[0];
19120            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19121            assert!(history.archived_at.is_some());
19122            assert_eq!(history.fixes_spent, Some(1));
19123        }
19124    }
19125
19126    #[cfg(unix)]
19127    #[tokio::test]
19128    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19129        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19130        let marker = tmp.path().join("gate-ran");
19131        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19132        runner.review_loop().await.unwrap();
19133        runner.gate().await.unwrap();
19134        assert_eq!(runner.state.status, RunStatus::Blocked);
19135        assert!(!marker.exists());
19136        assert!(runner.state.verification_history.is_empty());
19137        runner.state.gate_head = None;
19138        runner.gate().await.unwrap();
19139        assert!(marker.exists());
19140        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19141        assert_eq!(runner.state.verification_history.len(), 1);
19142        assert_eq!(runner.state.gate_fixes.len(), 1);
19143    }
19144
19145    #[cfg(unix)]
19146    #[tokio::test]
19147    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19148        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19149        runner.sync_to_base().await.unwrap();
19150        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19151        runner.state.reconcile_verification_head(&head);
19152        // Both crash-before-command and resource wait are unresolved evidence.
19153        for outcomes in [
19154            Vec::new(),
19155            vec![CommandOutcome {
19156                command: "true".into(),
19157                code: None,
19158                output_tail: "cache unavailable".into(),
19159                duration_ms: 0,
19160                resource_blocked: true,
19161                ..Default::default()
19162            }],
19163        ] {
19164            runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19165                head: head.clone(),
19166                passed: false,
19167                outcomes,
19168            });
19169            runner.state.gate_ran = false;
19170            runner.state.gate.clear();
19171            runner.state.save().unwrap();
19172            runner.state = RunState::load(&runner.state.id).unwrap();
19173            runner.merge().await.unwrap();
19174            assert!(runner.state.merge.is_none());
19175            runner.review_loop().await.unwrap();
19176            runner.gate().await.unwrap();
19177            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19178            assert!(runner.state.gate_allows_progress());
19179            assert_eq!(runner.state.gate_fixes.len(), 1);
19180            assert!(runner.state.merge.is_none());
19181        }
19182        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19183        git::git(
19184            &runner.state.repo,
19185            &["commit", "--allow-empty", "-m", "external update"],
19186        )
19187        .await
19188        .unwrap();
19189        runner.merge().await.unwrap();
19190        assert!(runner.state.merge.is_none());
19191        assert_eq!(runner.state.status, RunStatus::Blocked);
19192    }
19193
19194    #[cfg(unix)]
19195    #[tokio::test]
19196    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19197        for waiting_on_gate in [false, true] {
19198            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19199            runner.sync_to_base().await.unwrap();
19200            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19201            runner.state.reconcile_verification_head(&head);
19202            if waiting_on_gate {
19203                runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19204                    head: head.clone(),
19205                    passed: true,
19206                    outcomes: Vec::new(),
19207                });
19208            }
19209            let cache = tmp.path().join("cache");
19210            runner.state.config.verify.e2e =
19211                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19212            runner.state.config.verify.gate = vec!["true".into()];
19213            runner.state.config.graph.timeout_resource_wait = 1;
19214            let owner =
19215                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19216            let guard =
19217                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19218                    crate::cache::AcquireOutcome::Acquired(g) => g,
19219                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19220                };
19221            runner.review_loop().await.unwrap();
19222            runner.gate().await.unwrap();
19223            assert!(!runner.state.gate_ran);
19224            assert_eq!(runner.state.gate_fixes.len(), 1);
19225            assert!(runner.state.resource_block.is_some());
19226            runner.merge().await.unwrap();
19227            assert!(runner.state.merge.is_none());
19228            drop(guard);
19229            runner.state = RunState::load(&runner.state.id).unwrap();
19230            // The driver clears the previous pass's resource stop on resume.
19231            runner.state.resource_block = None;
19232            runner.review_loop().await.unwrap();
19233            runner.gate().await.unwrap();
19234            assert!(runner.state.gate_allows_progress());
19235            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19236            assert_eq!(runner.state.gate_fixes.len(), 1);
19237        }
19238    }
19239
19240    #[cfg(unix)]
19241    #[tokio::test]
19242    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19243        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19244        runner.sync_to_base().await.unwrap();
19245        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19246        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19247        // Verification passes before pre_gate and fails on the mechanically changed head.
19248        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19249        runner.review_loop().await.unwrap();
19250        runner.gate().await.unwrap();
19251        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19252        assert_ne!(before, after);
19253        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19254        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19255        assert!(!runner.state.gate_allows_progress());
19256        runner.merge().await.unwrap();
19257        assert!(runner.state.merge.is_none());
19258        assert!(
19259            runner
19260                .state
19261                .verification_history
19262                .iter()
19263                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19264        );
19265
19266        // An incomplete review is still an independent hold on a changed head.
19267        runner.state.reviews[0].clean = false;
19268        runner.state.reviews[0].answered = 0;
19269        runner.state.config.verify.e2e = vec!["true".into()];
19270        runner.review_loop().await.unwrap();
19271        runner.gate().await.unwrap();
19272        runner.merge().await.unwrap();
19273        assert_eq!(runner.state.status, RunStatus::Blocked);
19274        assert!(runner.state.merge.is_none());
19275        assert!(
19276            runner
19277                .state
19278                .verification_blocking_cause()
19279                .unwrap()
19280                .contains("review blocked")
19281        );
19282    }
19283
19284    #[cfg(unix)]
19285    #[tokio::test]
19286    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19287        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
19288        runner.state.gate_head = None;
19289        runner.state.config.verify.gate =
19290            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
19291        runner.review_loop().await.unwrap();
19292        runner.gate().await.unwrap();
19293        assert_ne!(
19294            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19295            old
19296        );
19297        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
19298        assert!(!runner.state.gate_allows_progress());
19299        assert_eq!(runner.state.status, RunStatus::Blocked);
19300        runner.merge().await.unwrap();
19301        assert!(runner.state.merge.is_none());
19302    }
19303
19304    #[cfg(unix)]
19305    #[tokio::test]
19306    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
19307        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19308        let mut old_review = review_round(true, 0, 1, 1, false, true);
19309        old_review.head = head.clone();
19310        old_review.verified_head = Some(head.clone());
19311        runner.state.reviews = vec![old_review];
19312        runner.state.gate = vec![CommandOutcome {
19313            command: "old gate".into(),
19314            code: None,
19315            output_tail: "timed out after 2400s".into(),
19316            duration_ms: 2_400_000,
19317            resource_blocked: false,
19318            ..Default::default()
19319        }];
19320        runner.state.gate_ran = true;
19321        runner.state.gate_head = Some(head.clone());
19322        runner.state.land_approval = Some(crate::run::LandApproval {
19323            question: "old-head-approval".into(),
19324            head: head.clone(),
19325        });
19326        runner.state.authorize_base_sync(&task).unwrap();
19327        runner.sync_to_base().await.unwrap();
19328        assert!(!runner.state.base_sync_blocked());
19329        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19330        assert_ne!(head, fresh);
19331        assert_eq!(runner.state.reviews.len(), 1);
19332        assert!(!runner.state.gate_ran);
19333        let saved = &runner.state.base_sync_recovery.authorizations[0];
19334        assert_eq!(saved.reviews[0].head, head);
19335        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
19336        assert!(saved.gate_ran);
19337        assert!(!saved.gate[0].ok());
19338        runner.review_loop().await.unwrap();
19339        runner.gate().await.unwrap();
19340        assert_eq!(runner.state.reviews[0].head, head);
19341        assert_eq!(
19342            runner.state.reviews[0].verified_head.as_deref(),
19343            Some(head.as_str())
19344        );
19345        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
19346        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19347        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
19348        assert!(runner.state.gate_ran);
19349        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
19350        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
19351        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
19352        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19353        assert_eq!(
19354            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
19355            "retained change"
19356        );
19357    }
19358
19359    #[cfg(unix)]
19360    #[tokio::test]
19361    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
19362        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19363        let queue = crate::queue::Queue::open();
19364        let mut owner = queue.get(&task).unwrap();
19365        owner.release_operator("test-resume", None);
19366        queue.put(&mut owner).unwrap();
19367        let generation = owner.resumption.as_ref().unwrap().generation;
19368        runner.state.task_instruction = Some(owner.instruction.clone());
19369        runner.state.driver_exited = true;
19370        runner.state.save().unwrap();
19371        let home = crate::run::home();
19372        let _claim = queue.claim(&task).unwrap();
19373        owner.resumption.as_mut().unwrap().at =
19374            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
19375        queue.put(&mut owner).unwrap();
19376        assert!(
19377            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19378                .await
19379                .is_err(),
19380            "an approval from before the stop grants nothing"
19381        );
19382        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19383        queue.put(&mut owner).unwrap();
19384        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19385            .await
19386            .unwrap();
19387        assert!(
19388            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19389                .await
19390                .is_err()
19391        );
19392        runner.state = RunState::load(&runner.state.id).unwrap();
19393        assert_eq!(
19394            runner.state.base_sync_recovery.authorizations[0].generation,
19395            Some(generation)
19396        );
19397        runner.sync_to_base().await.unwrap();
19398        let repo = runner.state.repo.clone();
19399        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
19400        git::git(&repo, &["checkout", "main"]).await.unwrap();
19401        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
19402        git::git(&repo, &["add", "."]).await.unwrap();
19403        git::git(&repo, &["commit", "-m", "move base again"])
19404            .await
19405            .unwrap();
19406        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19407        git::git(&repo, &["checkout", "fix/retained"])
19408            .await
19409            .unwrap();
19410        runner.sync_to_base().await.unwrap();
19411        assert!(!runner.state.base_sync_blocked());
19412        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19413        assert_eq!(runner.state.base_episode_used(), 2);
19414        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
19415        assert_ne!(fresh, head);
19416        assert!(!runner.state.base_recovery_pending());
19417        // Even replaying the generation with a later timestamp grants nothing.
19418        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19419        queue.put(&mut owner).unwrap();
19420        assert!(
19421            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19422                .await
19423                .is_err()
19424        );
19425        runner.state = RunState::load(&runner.state.id).unwrap();
19426        runner.sync_to_base().await.unwrap();
19427        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19428        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
19429        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
19430    }
19431
19432    #[cfg(unix)]
19433    #[tokio::test]
19434    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
19435        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19436        runner.state.base_sync = None;
19437        runner.state.status = RunStatus::Blocked;
19438        let mut second = runner.state.candidates[0].clone();
19439        second.label = 'B';
19440        runner.state.candidates.push(second);
19441        assert!(runner.state.votes.is_empty());
19442        assert!(runner.state.deliberation.is_empty());
19443        runner.deliberate().await.unwrap();
19444        runner.vote().await.unwrap();
19445        assert_eq!(runner.state.status, RunStatus::Blocked);
19446        assert!(runner.state.votes.is_empty());
19447        assert!(runner.state.deliberation.is_empty());
19448    }
19449
19450    /// A minimal, git-free `Runner` at a given status — `settle_questions`
19451    /// reads nothing else off it.
19452    fn runner_at(status: RunStatus) -> Runner {
19453        let mut state = RunState::new(
19454            PathBuf::from("/nonexistent/repo"),
19455            "main".to_owned(),
19456            "deadbeef".to_owned(),
19457            "task".to_owned(),
19458            Config::default(),
19459        );
19460        // These fixtures test execution flow, independent of host disk capacity.
19461        state.config.disk.min_free_bytes = 0;
19462        // These fixtures share one home and save concurrently. Short clock
19463        // IDs can collide, making an ownership test read another test's run.
19464        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19465        state.id = format!(
19466            "20000101-000000-{:04x}",
19467            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
19468        );
19469        state.status = status;
19470        Runner {
19471            state,
19472            roles: ResolvedRoles {
19473                implementers: Vec::new(),
19474                judges: Vec::new(),
19475                reviewers: Vec::new(),
19476                fixer: None,
19477                conductor: conductor(),
19478                implementer_roster: Vec::new(),
19479                judge_roster: Vec::new(),
19480                reviewer_roster: Vec::new(),
19481            },
19482            sem: Arc::new(Semaphore::new(1)),
19483            pause: Pause::new(),
19484            interrupt: Pause::new(),
19485        }
19486    }
19487
19488    #[tokio::test]
19489    async fn targeted_fix_refuses_independent_ownership_conflicts() {
19490        crate::run::pin_test_home();
19491        let home = crate::run::home();
19492        let mut runner = runner_at(RunStatus::Ready);
19493        runner.state.driver_exited = true;
19494        runner.state.save().unwrap();
19495        let id = runner.state.id.clone();
19496        let path = runner.state.dir().join("run.json");
19497        let ids = ["R1-1-1".into()];
19498        let lease = crate::driver::maintenance(&home, &id).unwrap();
19499        for (guard, expected) in [
19500            (Some(lease), "currently being worked on"),
19501            (None, "ownership is being updated"),
19502        ] {
19503            let owner = if guard.is_none() {
19504                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
19505            } else {
19506                None
19507            };
19508            let before = std::fs::read(&path).unwrap();
19509            let err = runner
19510                .fix_selected(&ids, "ownership conflict", false)
19511                .await
19512                .unwrap_err();
19513            assert!(format!("{err:#}").contains(expected), "{err:#}");
19514            assert_eq!(std::fs::read(&path).unwrap(), before);
19515            assert!(!runner.state.dir().join("fix.lock").exists());
19516            drop(owner);
19517            drop(guard);
19518        }
19519        let mut disk = RunState::load(&id).unwrap();
19520        disk.driver_exited = false;
19521        disk.driver_pid = Some(std::process::id());
19522        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
19523        disk.save().unwrap();
19524        assert_eq!(
19525            disk.liveness_under(&home, false),
19526            crate::run::Liveness::Live
19527        );
19528        let before = std::fs::read(&path).unwrap();
19529        let err = runner
19530            .fix_selected(&ids, "live driver", false)
19531            .await
19532            .unwrap_err();
19533        assert!(
19534            err.to_string().contains("currently being worked on"),
19535            "{err:#}"
19536        );
19537        assert_eq!(std::fs::read(&path).unwrap(), before);
19538        assert!(!runner.state.dir().join("fix.lock").exists());
19539        disk.driver_exited = true;
19540        disk.driver_pid = None;
19541        disk.driver_started_at = None;
19542        disk.status = RunStatus::Reviewing;
19543        disk.save().unwrap();
19544        let before = std::fs::read(&path).unwrap();
19545        let err = runner
19546            .fix_selected(&ids, "stale state", false)
19547            .await
19548            .unwrap_err();
19549        assert!(
19550            err.to_string().contains("run changed since it was loaded"),
19551            "{err:#}"
19552        );
19553        assert_eq!(std::fs::read(&path).unwrap(), before);
19554        assert!(!runner.state.dir().join("fix.lock").exists());
19555        assert!(runner.state.operator_fixes.is_empty());
19556    }
19557
19558    #[tokio::test]
19559    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
19560        use std::future::Future;
19561        use std::task::Poll;
19562
19563        crate::run::pin_test_home();
19564        let home = crate::run::home();
19565        let repo = tempfile::tempdir().unwrap();
19566        let mut runner = runner_at(RunStatus::Ready);
19567        runner.state.repo = repo.path().to_path_buf();
19568        runner.state.driver_exited = true;
19569        runner.state.candidates.push(Candidate {
19570            index: 0,
19571            label: 'A',
19572            agent: "mock".into(),
19573            branch: "magi/test/A".into(),
19574            worktree: repo.path().join("wt"),
19575            summary: String::new(),
19576            stat: String::new(),
19577            files: 0,
19578            commits: 0,
19579            empty: false,
19580            failed: None,
19581            verified_noop: None,
19582            duration_ms: 0,
19583            folded: false,
19584        });
19585        runner.state.tally = Some(Tally {
19586            first_choice: BTreeMap::from([('A', 1)]),
19587            borda: BTreeMap::new(),
19588            winner: 'A',
19589            rankings: 1,
19590            unanimous_initial: true,
19591            deliberated: false,
19592            changed_votes: 0,
19593            unanimous_final: true,
19594            tie_break: None,
19595            judges: 1,
19596            present: 1,
19597            quorum: 1,
19598            met_quorum: true,
19599            uncontested: None,
19600        });
19601        runner.state.save().unwrap();
19602        let id = runner.state.id.clone();
19603        let dir = runner.state.dir();
19604        let before = std::fs::read(dir.join("run.json")).unwrap();
19605        let ids = ["R1-1-1".into()];
19606        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
19607        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
19608            Poll::Pending => Poll::Ready(()),
19609            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
19610        })
19611        .await;
19612        assert!(FixClaim::acquire(&dir).is_err());
19613        assert!(crate::driver::maintenance(&home, &id).is_err());
19614        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
19615        drop(fix);
19616        assert!(FixClaim::acquire(&dir).is_ok());
19617        assert!(crate::driver::maintenance(&home, &id).is_ok());
19618        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
19619    }
19620
19621    #[tokio::test]
19622    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
19623        crate::run::pin_test_home();
19624        let temp = tempfile::tempdir().unwrap();
19625        let root = temp.path().canonicalize().unwrap();
19626        let repo = root.join("repo");
19627        std::fs::create_dir(&repo).unwrap();
19628        init_repo(&repo);
19629        git::git(&repo, &["config", "core.autocrlf", "false"])
19630            .await
19631            .unwrap();
19632        let mut runner = runner_at(RunStatus::Blocked);
19633        runner.state.repo = repo.clone();
19634        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
19635        runner.state.config.agents = vec![conductor()];
19636        runner.state.config.graph.selected_implementer = Some("conductor".into());
19637        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
19638        let (shell, command, setup_output) = if cfg!(windows) {
19639            (
19640                vec!["cmd".into(), "/C".into()],
19641                "echo ready>seat-ready",
19642                "ready\r\n",
19643            )
19644        } else {
19645            (
19646                vec!["sh".into(), "-c".into()],
19647                "printf ready > seat-ready",
19648                "ready",
19649            )
19650        };
19651        runner.state.config.verify.shell = Some(shell);
19652        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
19653            run: Some(command.into()),
19654            ..Default::default()
19655        }];
19656        runner.state.save().unwrap();
19657        let path = runner.state.worktree_root().join("judge-1");
19658        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
19659            .await
19660            .unwrap();
19661        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
19662        git::git(&path, &["add", "."]).await.unwrap();
19663        let tree = git::git(&path, &["write-tree"]).await.unwrap();
19664        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
19665            .await
19666            .unwrap();
19667        git::git(&path, &["checkout", "--detach", &head])
19668            .await
19669            .unwrap();
19670        let evidence = crate::fold_evidence::snapshot(
19671            &runner.state,
19672            &crate::run::home().canonicalize().unwrap(),
19673            &head,
19674            64 * 1024 * 1024,
19675        )
19676        .await
19677        .unwrap();
19678        let mut contents = BTreeMap::new();
19679        contents.insert(
19680            repo.join("logs/HEAD"),
19681            format!("{head} {head} fixture\n").into_bytes(),
19682        );
19683        let record = serde_json::json!({
19684            "version":1, "run":runner.state.id, "source":path, "head":head,
19685            "evidence":evidence, "admin":{}, "admin_contents":contents,
19686            "history":{head.clone():evidence}, "phase":"evicted"
19687        });
19688        std::fs::write(
19689            runner.state.dir().join("artifacts/eviction-judge-1.json"),
19690            serde_json::to_vec(&record).unwrap(),
19691        )
19692        .unwrap();
19693        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
19694        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
19695            .await
19696            .unwrap();
19697        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
19698        assert!(
19699            !git::git_raw(&repo, &["cat-file", "-e", &head])
19700                .await
19701                .unwrap()
19702                .ok()
19703        );
19704        let mut resumed = Runner::resume(&runner.state.id).unwrap();
19705        let error = resumed.execute().await.unwrap_err();
19706        assert!(
19707            error
19708                .to_string()
19709                .contains("selected implementation is held"),
19710            "{error:#}"
19711        );
19712        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
19713        assert_eq!(
19714            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
19715            setup_output
19716        );
19717        assert_eq!(
19718            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
19719            "unrelated seat"
19720        );
19721        let error = resumed.execute().await.unwrap_err();
19722        assert!(
19723            error
19724                .to_string()
19725                .contains("selected implementation is held"),
19726            "{error:#}"
19727        );
19728        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
19729        git::git(&path, &["add", "."]).await.unwrap();
19730        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
19731        let next = git::git(
19732            &path,
19733            &[
19734                "commit-tree",
19735                &next_tree,
19736                "-p",
19737                &head,
19738                "-m",
19739                "next review checkpoint",
19740            ],
19741        )
19742        .await
19743        .unwrap();
19744        git::git(&path, &["checkout", "--detach", &next])
19745            .await
19746            .unwrap();
19747        resumed.state.reviews.push(
19748            serde_json::from_value(serde_json::json!({
19749                "round":1, "head":next, "reviews":[]
19750            }))
19751            .unwrap(),
19752        );
19753        resumed.state.save().unwrap();
19754        let error = resumed.execute().await.unwrap_err();
19755        assert!(
19756            error
19757                .to_string()
19758                .contains("selected implementation is held"),
19759            "{error:#}"
19760        );
19761        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
19762    }
19763
19764    #[tokio::test]
19765    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
19766        crate::run::pin_test_home();
19767        let mut runner = runner_at(RunStatus::Gating);
19768        runner.state.save().unwrap();
19769        let id = runner.state.id.clone();
19770        let passes = runner.state.passes.len();
19771        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19772        let mut claiming = Box::pin(runner.claim_driver(None));
19773        std::future::poll_fn(|cx| {
19774            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
19775            std::task::Poll::Ready(())
19776        })
19777        .await;
19778        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
19779        drop(owner);
19780        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
19781            .await
19782            .unwrap()
19783            .unwrap();
19784        assert_eq!(execution.runner.state.passes.len(), passes + 1);
19785        assert!(execution.runner.state.resource_block.is_none());
19786        assert_eq!(
19787            execution.runner.state.liveness(false),
19788            crate::run::Liveness::Live
19789        );
19790        drop(execution);
19791        assert!(RunState::load(&id).unwrap().driver_exited);
19792    }
19793
19794    #[tokio::test]
19795    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
19796        crate::run::pin_test_home();
19797        let mut runner = runner_at(RunStatus::Gating);
19798        runner.state.save().unwrap();
19799        // run.json can commit, but the subsequent lease metadata write fails.
19800        // Cleanup must run after releasing the short ownership lock.
19801        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
19802        assert!(runner.claim_driver(None).await.is_err());
19803        assert!(runner.state.driver_exited);
19804        assert_eq!(runner.state.driver_pid, None);
19805        let disk = RunState::load(&runner.state.id).unwrap();
19806        assert!(disk.driver_exited);
19807        assert_eq!(disk.driver_pid, None);
19808        assert_eq!(disk.status, RunStatus::Gating);
19809    }
19810
19811    #[tokio::test]
19812    async fn an_early_graph_error_releases_its_driver() {
19813        crate::run::pin_test_home();
19814        let mut runner = runner_at(RunStatus::Blocked);
19815        runner.state.config.graph.selected_implementer = Some("selected".into());
19816        runner.state.save().unwrap();
19817        assert!(runner.execute().await.is_err());
19818        let disk = RunState::load(&runner.state.id).unwrap();
19819        assert!(disk.driver_exited);
19820        assert_eq!(disk.driver_pid, None);
19821        assert_eq!(disk.status, RunStatus::Blocked);
19822    }
19823
19824    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
19825        crate::run::MergeRepair {
19826            question: "repair-question".into(),
19827            head: "old-head".into(),
19828            pr: "https://github.com/o/r/pull/42".into(),
19829            reviews: vec![review_round(false, 1, 1, 1, false, true)],
19830            gate: vec![outcome(Some(0), false)],
19831            gate_head: Some("old-head".into()),
19832            gate_fixes: Vec::new(),
19833            pre_gate: Vec::new(),
19834            phase,
19835            failure: None,
19836        }
19837    }
19838
19839    #[tokio::test]
19840    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
19841        crate::run::pin_test_home();
19842        let mut runner = runner_at(RunStatus::Landing);
19843        runner.state.merge_repairs.push(merge_repair_request(
19844            crate::run::MergeRepairPhase::Requested,
19845        ));
19846        runner.state.save().unwrap();
19847        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
19848        assert!(
19849            runner
19850                .execute()
19851                .await
19852                .unwrap_err()
19853                .to_string()
19854                .contains("already running")
19855        );
19856        assert_eq!(
19857            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19858            crate::run::MergeRepairPhase::Requested
19859        );
19860        drop(claim);
19861        let mut disk = runner.state.clone();
19862        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
19863        disk.save().unwrap();
19864        assert!(
19865            runner
19866                .execute()
19867                .await
19868                .unwrap_err()
19869                .to_string()
19870                .contains("decision changed")
19871        );
19872        assert_eq!(
19873            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19874            crate::run::MergeRepairPhase::Complete
19875        );
19876    }
19877
19878    #[test]
19879    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
19880        crate::run::pin_test_home();
19881        let mut runner = runner_at(RunStatus::Landing);
19882        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
19883        runner.state.reviews = request.reviews.clone();
19884        runner.state.gate = request.gate.clone();
19885        runner.state.gate_ran = true;
19886        runner.state.land_approval = Some(crate::run::LandApproval {
19887            question: "old".into(),
19888            head: "old-head".into(),
19889        });
19890        runner.state.merge_repairs.push(request);
19891        runner.begin_merge_repair_review(0).unwrap();
19892        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
19893        assert!(!runner.state.gate_status().ok());
19894        assert!(runner.state.land_approval.is_none());
19895        let disk = RunState::load(&runner.state.id).unwrap();
19896        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
19897        assert!(disk.merge_repairs[0].gate[0].ok());
19898        assert_eq!(
19899            disk.merge_repairs[0].phase,
19900            crate::run::MergeRepairPhase::Reviewing
19901        );
19902        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
19903        assert!(disk.reviews.is_empty());
19904    }
19905
19906    #[tokio::test]
19907    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
19908        crate::run::pin_test_home();
19909        for phase in [
19910            crate::run::MergeRepairPhase::Fixing,
19911            crate::run::MergeRepairPhase::Requested,
19912        ] {
19913            let mut runner = runner_at(RunStatus::Landing);
19914            runner.state.config.graph.land_rounds = 0;
19915            runner.state.merge_repairs.push(merge_repair_request(phase));
19916            runner.state.save().unwrap();
19917            assert!(!runner.repair_merge_review().await.unwrap());
19918            assert_eq!(runner.state.status, RunStatus::Blocked);
19919            assert_eq!(
19920                runner.state.merge_repairs[0].phase,
19921                crate::run::MergeRepairPhase::Failed
19922            );
19923            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
19924            assert!(
19925                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
19926                    "interrupted"
19927                } else {
19928                    "budget exhausted"
19929                })
19930            );
19931            assert!(runner.state.merge.is_none());
19932        }
19933    }
19934
19935    /// `park_here` folding in the reason `Pause::park_because` recorded -
19936    /// this is what lets an operator reading a run's events tell an
19937    /// interrupt-driven park from an ordinary shutdown park.
19938    #[test]
19939    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
19940        crate::run::pin_test_home();
19941        let mut runner = runner_at(RunStatus::Implementing);
19942        let interrupt = Pause::new();
19943        runner.watch_interrupt(interrupt.clone());
19944
19945        interrupt.park_because("task a1b2 asked to run first");
19946
19947        assert!(runner.park_here().expect("park_here"));
19948        assert!(runner.state.parked);
19949        let last = runner.state.events.last().expect("a park event");
19950        assert_eq!(last.node, "park");
19951        assert!(
19952            last.message.contains("task a1b2 asked to run first"),
19953            "expected the interrupt reason in {:?}",
19954            last.message
19955        );
19956    }
19957
19958    /// The cause is stored on the pass when it parks, and the first cause a
19959    /// shared pause was given is the one that stays.
19960    #[test]
19961    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
19962        crate::run::pin_test_home();
19963        let mut runner = runner_at(RunStatus::Implementing);
19964        runner.state.begin_pass();
19965        let shutdown = Pause::new();
19966        runner.on_pause(shutdown.clone());
19967        let upgrade = ParkCause::Upgrade {
19968            from: "0.121.0".to_owned(),
19969            to: Some("0.121.1".to_owned()),
19970        };
19971        shutdown.park_for(upgrade.clone());
19972        shutdown.park_for(ParkCause::Operator);
19973
19974        assert!(runner.park_here().expect("park_here"));
19975        assert_eq!(
19976            runner.state.passes[0].end,
19977            Some(crate::run::PassEnd::Parked { cause: upgrade })
19978        );
19979        let last = runner.state.events.last().expect("a park event");
19980        assert!(last.message.contains("0.121.0"), "{}", last.message);
19981    }
19982
19983    #[tokio::test]
19984    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
19985        crate::run::pin_test_home();
19986        let mut runner = runner_at(RunStatus::Reviewing);
19987        runner.state.save().unwrap();
19988        let mut execution = runner.claim_driver(None).await.expect("first execution");
19989        assert_eq!(execution.runner.state.passes.len(), 1);
19990        execution
19991            .driver
19992            .finish(&mut execution.runner.state)
19993            .await
19994            .unwrap();
19995    }
19996
19997    #[tokio::test]
19998    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
19999        crate::run::pin_test_home();
20000        let mut runner = runner_at(RunStatus::Reviewing);
20001        runner.state.config.agents = vec![conductor()];
20002        runner.state.config.graph.timeout_resource_wait = 0;
20003        runner.state.save().unwrap();
20004        let id = runner.state.id.clone();
20005        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20006        assert!(runner.claim_driver(None).await.is_err());
20007        drop(owner);
20008        drop(runner);
20009        let mut resumed = Runner::resume(&id).unwrap();
20010        assert_eq!(resumed.state.driver_claimed, Some(false));
20011        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
20012        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
20013        let mut execution = resumed
20014            .claim_driver(None)
20015            .await
20016            .expect("retry initial claim after reload");
20017        assert_eq!(execution.runner.state.driver_claimed, Some(true));
20018        assert_eq!(execution.runner.state.passes.len(), 1);
20019        execution
20020            .driver
20021            .finish(&mut execution.runner.state)
20022            .await
20023            .unwrap();
20024    }
20025
20026    #[tokio::test]
20027    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
20028        crate::run::pin_test_home();
20029        let mut runner = runner_at(RunStatus::Reviewing);
20030        runner.state.config.agents = vec![conductor()];
20031        runner.state.save().unwrap();
20032        let id = runner.state.id.clone();
20033        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
20034        let mut resumed = Runner::resume(&id).unwrap();
20035        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
20036        assert!(resumed.claim_driver(None).await.is_err());
20037        assert!(RunState::load(&id).unwrap().passes.is_empty());
20038        drop(lease);
20039        let mut execution = resumed.claim_driver(None).await.unwrap();
20040        execution
20041            .driver
20042            .finish(&mut execution.runner.state)
20043            .await
20044            .unwrap();
20045    }
20046
20047    #[tokio::test]
20048    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
20049        crate::run::pin_test_home();
20050        let mut runner = runner_at(RunStatus::Reviewing);
20051        let state = &mut runner.state;
20052        state.config.agents = vec![conductor()];
20053        state.driver_claimed = None;
20054        state.driver_pid = Some(std::process::id());
20055        state.driver_started_at = None;
20056        state.begin_pass();
20057        state.save().unwrap();
20058        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
20059        std::fs::write(
20060            state.dir().join("driver.json"),
20061            serde_json::to_vec(&serde_json::json!({
20062                "pid": state.driver_pid, "started_at": null,
20063                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
20064            }))
20065            .unwrap(),
20066        )
20067        .unwrap();
20068        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
20069        drop(lease);
20070        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
20071        let mut resumed = Runner::resume(&state.id).unwrap();
20072        assert!(!resumed.state.driver_exited);
20073        let mut execution = resumed
20074            .claim_driver(None)
20075            .await
20076            .expect("lease proves previous execution ended");
20077        assert_eq!(execution.runner.state.passes.len(), 2);
20078        execution
20079            .driver
20080            .finish(&mut execution.runner.state)
20081            .await
20082            .unwrap();
20083    }
20084
20085    #[tokio::test]
20086    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
20087        crate::run::pin_test_home();
20088        let mut runner = runner_at(RunStatus::Reviewing);
20089        let mut json = serde_json::to_value(&runner.state).unwrap();
20090        json.as_object_mut().unwrap().remove("driver_claimed");
20091        runner.state = serde_json::from_value(json).unwrap();
20092        assert_eq!(runner.state.driver_claimed, None);
20093        runner.state.save().unwrap();
20094        let mut execution = runner
20095            .claim_driver(None)
20096            .await
20097            .expect("the execution lease, not a missing marker, excludes a second driver");
20098        assert_eq!(execution.runner.state.passes.len(), 1);
20099        execution
20100            .driver
20101            .finish(&mut execution.runner.state)
20102            .await
20103            .unwrap();
20104    }
20105
20106    #[tokio::test]
20107    async fn driver_admission_refuses_a_proven_live_driver() {
20108        crate::run::pin_test_home();
20109        let mut runner = runner_at(RunStatus::Reviewing);
20110        let pid = std::process::id();
20111        runner.state.driver_pid = Some(pid);
20112        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20113        assert!(runner.state.driver_started_at.is_some());
20114        runner.state.save().unwrap();
20115        let error = runner
20116            .claim_driver(None)
20117            .await
20118            .err()
20119            .expect("a live driver must refuse");
20120        assert!(error.to_string().contains("live driver"), "{error:#}");
20121        let saved = RunState::load(&runner.state.id).unwrap();
20122        assert_eq!(saved.driver_pid, Some(pid));
20123        assert_eq!(saved.status, RunStatus::Reviewing);
20124        assert!(saved.passes.is_empty());
20125    }
20126
20127    #[test]
20128    fn parking_resource_halt_persists_the_pass_once() {
20129        crate::run::pin_test_home();
20130        let mut runner = runner_at(RunStatus::Reviewing);
20131        runner.state.begin_pass();
20132        runner.state.resource_block = Some(crate::run::ResourceBlock {
20133            node: "fix".into(),
20134            kind: "shared build cache".into(),
20135            detail: "cancelled".into(),
20136            at: Timestamp::now(),
20137            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20138        });
20139        let cause = ParkCause::Upgrade {
20140            from: "old".into(),
20141            to: Some("new".into()),
20142        };
20143        runner.pause.park_for(cause.clone());
20144        // Both direct fixer exits and graph resource boundaries must complete
20145        // parking, rather than returning a stale Reviewing record.
20146        runner.stop_for_resource().unwrap();
20147        assert!(runner.resource_halt().unwrap());
20148        assert!(runner.park_here().unwrap());
20149        let saved = RunState::load(&runner.state.id).unwrap();
20150        assert!(saved.parked);
20151        assert_eq!(saved.status, RunStatus::Reviewing);
20152        assert!(saved.passes[0].ended_at.is_some());
20153        assert_eq!(
20154            saved.passes[0].end,
20155            Some(crate::run::PassEnd::Parked {
20156                cause: cause.clone()
20157            })
20158        );
20159        assert_eq!(
20160            saved.resource_block.unwrap().cause,
20161            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20162        );
20163        assert_eq!(
20164            saved
20165                .events
20166                .iter()
20167                .filter(|event| event.node == "park")
20168                .count(),
20169            1
20170        );
20171    }
20172
20173    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
20174    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
20175    /// cleared) must not make a *different* run - one only watching its own,
20176    /// unshared interrupt `Pause` - see itself as parked. If a future change
20177    /// ever collapsed these back into one handle, the interrupt scheduler
20178    /// would park every run for the rest of the daemon's life, not just the
20179    /// one it meant to interrupt.
20180    #[test]
20181    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
20182        crate::run::pin_test_home();
20183        let mut runner = runner_at(RunStatus::Implementing);
20184        let shutdown = Pause::new();
20185        runner.on_pause(shutdown.clone());
20186        let interrupt = Pause::new();
20187        runner.watch_interrupt(interrupt.clone());
20188
20189        // Nobody has asked for anything yet.
20190        assert!(!runner.park_here().expect("park_here"));
20191        assert!(!runner.state.parked);
20192
20193        // Only the interrupt handle fires; the shutdown handle stays clear.
20194        interrupt.park_because("test");
20195        assert!(!shutdown.parked());
20196        assert!(runner.park_here().expect("park_here"));
20197    }
20198
20199    /// The property every prior attempt at this feature failed to pin down:
20200    /// asking a run to park while one of its nodes has a real, in-flight
20201    /// async operation running (an agent call, in production) must not cut
20202    /// that operation short. `park_here` is only ever consulted *between*
20203    /// `execute`'s node calls - see its own doc - so nothing inside a node
20204    /// can observe a park request until the node itself returns. This proves
20205    /// that structurally, with real `tokio` concurrency and a channel
20206    /// handshake (never a sleep, which would only prove "usually", not
20207    /// "cannot"): the "node" below reports that it has genuinely started,
20208    /// and only then is the park requested; the node still has to be told to
20209    /// finish before `park_here` is ever called, exactly mirroring every
20210    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
20211    /// in `execute`.
20212    #[tokio::test]
20213    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
20214        crate::run::pin_test_home();
20215        let mut runner = runner_at(RunStatus::Implementing);
20216        let interrupt = Pause::new();
20217        runner.watch_interrupt(interrupt.clone());
20218
20219        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
20220        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
20221
20222        // Stands in for one node's in-flight agent call: it proves it has
20223        // genuinely started, then blocks - exactly as a spawned CLI process
20224        // does - until told to finish.
20225        let node = async move {
20226            started_tx.send(()).expect("send started");
20227            finish_rx.await.expect("recv finish");
20228            "node finished"
20229        };
20230
20231        let interrupter = async move {
20232            started_rx.await.expect("recv started");
20233            // The call is now genuinely in flight. Ask it to park.
20234            interrupt.park_because("higher-priority task waiting");
20235            // Nothing the node does can observe this yet - there is no
20236            // check inside it, by construction - so let the executor run
20237            // anything pending and then let the node finish on its own.
20238            tokio::task::yield_now().await;
20239            finish_tx.send(()).expect("send finish");
20240        };
20241
20242        let (node_result, ()) = tokio::join!(node, interrupter);
20243        assert_eq!(
20244            node_result, "node finished",
20245            "the in-flight call ran to completion"
20246        );
20247
20248        // Only now, at the boundary the real `execute` would check right
20249        // after this node, does the park take effect.
20250        assert!(runner.park_here().expect("park_here"));
20251        assert!(runner.state.parked);
20252    }
20253
20254    /// A run parked mid-competition carries every field it had accumulated
20255    /// through the exact same disk round-trip an ordinary resume uses -
20256    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
20257    /// Nothing about parking for an interrupt is a special case of that path;
20258    /// this is what proves it rather than assuming it.
20259    #[test]
20260    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
20261        crate::run::pin_test_home();
20262        let mut runner = runner_at(RunStatus::Judging);
20263        // `Runner::resume` re-resolves roles from the saved config, which
20264        // refuses an empty roster - give it the same minimal one `conductor`
20265        // itself uses.
20266        runner.state.config.agents = vec![conductor()];
20267        runner.state.candidates = vec![Candidate {
20268            index: 0,
20269            label: 'A',
20270            agent: "alpha".to_owned(),
20271            branch: "magi/x/A".to_owned(),
20272            worktree: PathBuf::from("/nonexistent/worktree"),
20273            summary: "did the thing".to_owned(),
20274            stat: "1 file changed".to_owned(),
20275            files: 1,
20276            commits: 1,
20277            empty: false,
20278            failed: None,
20279            verified_noop: None,
20280            duration_ms: 1234,
20281            folded: false,
20282        }];
20283        let run_id = runner.state.id.clone();
20284
20285        let interrupt = Pause::new();
20286        runner.watch_interrupt(interrupt.clone());
20287        interrupt.park_because("task c3d4 asked to run first");
20288        assert!(runner.park_here().expect("park_here"));
20289
20290        let resumed = Runner::resume(&run_id).expect("resume");
20291        assert_eq!(resumed.state.candidates.len(), 1);
20292        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
20293        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
20294        assert_eq!(resumed.state.status, runner.state.status);
20295        assert!(
20296            resumed.state.parked,
20297            "still parked until `execute` actually walks the graph again"
20298        );
20299        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
20300    }
20301
20302    /// A fresh open question on `run`, stored and handed back for assertions.
20303    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
20304        let mut q = ask::Question::new(
20305            run.to_owned(),
20306            "implement".to_owned(),
20307            "impl-A".to_owned(),
20308            "Which storage backend should the cache use?".to_owned(),
20309            String::new(),
20310            vec!["SQLite".to_owned(), "Redis".to_owned()],
20311        );
20312        store.put(&mut q).unwrap();
20313        q
20314    }
20315
20316    #[test]
20317    fn a_failed_runs_open_question_is_abandoned() {
20318        ask_test_home();
20319        let store = ask::Questions::open();
20320        let mut runner = runner_at(RunStatus::Failed);
20321        let run = runner.state.id.clone();
20322        let q = ask_open_question(&store, &run);
20323
20324        runner.settle_questions();
20325
20326        let back = store.get(&q.id).unwrap();
20327        assert!(
20328            !back.status.open(),
20329            "the seat that asked died with the run; nobody is left to read an answer"
20330        );
20331        assert!(
20332            back.detail.contains(&run) && back.detail.contains("failed"),
20333            "the reason names what the run became, not just that it is gone: {}",
20334            back.detail
20335        );
20336    }
20337
20338    #[test]
20339    fn a_merged_runs_open_question_is_abandoned_too() {
20340        ask_test_home();
20341        let store = ask::Questions::open();
20342        // A run that finishes cleanly still leaves nobody to read an answer -
20343        // this is not only a failure-path cleanup.
20344        for status in [RunStatus::Merged, RunStatus::Ready] {
20345            let mut runner = runner_at(status);
20346            let run = runner.state.id.clone();
20347            let q = ask_open_question(&store, &run);
20348
20349            runner.settle_questions();
20350
20351            let back = store.get(&q.id).unwrap();
20352            assert!(
20353                !back.status.open(),
20354                "{status:?} run's question must not outlive the run"
20355            );
20356        }
20357    }
20358
20359    #[test]
20360    fn a_still_resumable_runs_open_question_is_left_alone() {
20361        ask_test_home();
20362        let store = ask::Questions::open();
20363        // `Blocked` and `Stalled` can still be resumed — the candidates, the
20364        // review round and the seat sessions are all still on disk — so a
20365        // question asked mid-round may yet get a real answer from a real
20366        // resume. Sweeping it here would be exactly the failure mode this
20367        // whole feature exists to avoid on the other side.
20368        for status in [RunStatus::Blocked, RunStatus::Stalled] {
20369            let mut runner = runner_at(status);
20370            let run = runner.state.id.clone();
20371            let q = ask_open_question(&store, &run);
20372
20373            runner.settle_questions();
20374
20375            let back = store.get(&q.id).unwrap();
20376            assert!(
20377                back.status.open(),
20378                "{status:?} is still alive; the question must still be waiting"
20379            );
20380        }
20381    }
20382
20383    #[test]
20384    fn settle_questions_never_touches_an_already_answered_question() {
20385        ask_test_home();
20386        let store = ask::Questions::open();
20387        let mut runner = runner_at(RunStatus::Failed);
20388        let run = runner.state.id.clone();
20389        let mut q = ask_open_question(&store, &run);
20390        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
20391            .unwrap();
20392        store.put(&mut q).unwrap();
20393
20394        // Called twice, the way a crash-recovered daemon reclaim and the
20395        // graph's own cleanup both can for the same run — `abandon_for_run`
20396        // only ever touches what is still open, so this must be inert both
20397        // times, not merely the second.
20398        runner.settle_questions();
20399        runner.settle_questions();
20400
20401        let back = store.get(&q.id).unwrap();
20402        assert_eq!(
20403            back.status,
20404            ask::QuestionStatus::Answered,
20405            "a real answer is a decision on record, never overwritten by a sweep"
20406        );
20407    }
20408
20409    #[tokio::test]
20410    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
20411        let tmp = tempfile::tempdir().unwrap();
20412        let home = tmp.path().join("home");
20413        let repo = tmp.path().join("repo");
20414        std::fs::create_dir(&home).unwrap();
20415        std::fs::create_dir(&repo).unwrap();
20416        init_repo(&repo);
20417
20418        let mut config = Config::default();
20419        config.graph.worktree_root = Some(tmp.path().join("wt"));
20420        config.verify.build_cache = crate::config::BuildCache::Isolated;
20421        let mut state = RunState::new(
20422            repo.clone(),
20423            "main".into(),
20424            "base".into(),
20425            "fold fixture".into(),
20426            config,
20427        );
20428        let root = state.worktree_root();
20429        let mut outputs = Vec::new();
20430        for name in ["idle", "busy"] {
20431            let checkout = root.join(name);
20432            git::worktree_add_detached(&repo, &checkout, "main")
20433                .await
20434                .unwrap();
20435            let target = crate::build_target::resolve(&home, &checkout).unwrap();
20436            let output = target.join("generated");
20437            std::fs::write(&output, name).unwrap();
20438            outputs.push((target, output));
20439        }
20440        let unknown = crate::build_target::root(&home)
20441            .join("00000000-0000-0000-0000-000000000000")
20442            .join("target");
20443        std::fs::create_dir_all(&unknown).unwrap();
20444        let unowned = unknown.join("generated");
20445        std::fs::write(&unowned, "keep").unwrap();
20446        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
20447        let crate::cache::AcquireOutcome::Acquired(_lease) =
20448            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
20449        else {
20450            panic!("fixture target must be free");
20451        };
20452
20453        fold_run(&mut state, true, &home).await.unwrap();
20454        assert!(!root.exists());
20455        assert!(!outputs[0].1.exists());
20456        assert!(outputs[1].1.is_file());
20457        assert!(unowned.is_file());
20458    }
20459
20460    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
20461    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
20462    /// without merging, whose winner is still the operator's answer to read.
20463    /// Nothing previously called `fold_run` itself with a real `tally`, so
20464    /// this is the first test to pin down the one distinction the whole
20465    /// automatic-fold feature depends on: the winner's worktree and branch
20466    /// must survive, everything else sharing the run's worktree bay - a
20467    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
20468    /// second sweep treats every non-winner directory under the bay alike -
20469    /// must not.
20470    #[tokio::test]
20471    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
20472        crate::run::pin_test_home();
20473        let tmp = tempfile::tempdir().expect("tempdir");
20474        let repo = tmp.path().join("repo");
20475        std::fs::create_dir_all(&repo).unwrap();
20476        init_repo(&repo);
20477
20478        let mut config = Config::default();
20479        config.graph.worktree_root = Some(tmp.path().join("wt"));
20480
20481        let mut state = RunState::new(
20482            repo.clone(),
20483            "main".to_owned(),
20484            "deadbeef".to_owned(),
20485            "task".to_owned(),
20486            config,
20487        );
20488        let root = state.worktree_root();
20489        let wt_a = root.join("cand-A");
20490        let wt_b = root.join("cand-B");
20491        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
20492            .await
20493            .expect("worktree A");
20494        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
20495            .await
20496            .expect("worktree B");
20497
20498        state.candidates = vec![
20499            Candidate {
20500                index: 0,
20501                label: 'A',
20502                agent: "alpha".to_owned(),
20503                branch: "magi/x/A".to_owned(),
20504                worktree: wt_a.clone(),
20505                summary: String::new(),
20506                stat: String::new(),
20507                files: 0,
20508                commits: 0,
20509                empty: false,
20510                failed: None,
20511                verified_noop: None,
20512                duration_ms: 0,
20513                folded: false,
20514            },
20515            Candidate {
20516                index: 1,
20517                label: 'B',
20518                agent: "beta".to_owned(),
20519                branch: "magi/x/B".to_owned(),
20520                worktree: wt_b.clone(),
20521                summary: String::new(),
20522                stat: String::new(),
20523                files: 0,
20524                commits: 0,
20525                empty: false,
20526                failed: None,
20527                verified_noop: None,
20528                duration_ms: 0,
20529                folded: false,
20530            },
20531        ];
20532        state.tally = Some(Tally {
20533            first_choice: BTreeMap::from([('A', 1)]),
20534            borda: BTreeMap::new(),
20535            winner: 'A',
20536            rankings: 1,
20537            unanimous_initial: true,
20538            deliberated: false,
20539            changed_votes: 0,
20540            unanimous_final: true,
20541            tie_break: None,
20542            judges: 1,
20543            present: 1,
20544            quorum: 1,
20545            met_quorum: true,
20546            uncontested: None,
20547        });
20548        state.status = RunStatus::Ready;
20549
20550        fold_run(&mut state, false, &crate::run::home())
20551            .await
20552            .expect("fold_run");
20553
20554        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
20555        assert!(
20556            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20557            "the unmerged winner's branch survives"
20558        );
20559        assert!(
20560            !state.candidates[0].folded,
20561            "the winner is not marked folded"
20562        );
20563
20564        assert!(!wt_b.exists(), "the loser's worktree is removed");
20565        assert!(
20566            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
20567            "the loser's branch is removed"
20568        );
20569        assert!(state.candidates[1].folded, "the loser is marked folded");
20570    }
20571
20572    #[tokio::test]
20573    #[cfg(unix)]
20574    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
20575        use std::os::fd::AsRawFd as _;
20576        use std::time::Duration;
20577
20578        let tmp = tempfile::tempdir().unwrap();
20579        let repo = tmp.path().join("repo");
20580        std::fs::create_dir_all(&repo).unwrap();
20581        init_repo(&repo);
20582        let common = repo.join(".git");
20583        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
20584        let home = tmp.path().join("home");
20585        let mut config = Config::default();
20586        config.coordination = crate::config::test_coordination();
20587        config.graph.worktree_root = Some(tmp.path().join("wt"));
20588        config.graph.timeout_resource_wait = 1;
20589        let mut state = RunState::new(
20590            repo.clone(),
20591            "main".into(),
20592            "deadbeef".into(),
20593            "task".into(),
20594            config,
20595        );
20596        let root = state.worktree_root();
20597        let candidate = root.join("cand-A");
20598        let reviewer = root.join("review-1");
20599        let branch = state.branch_for('A');
20600        git::worktree_add_branch(&repo, &candidate, &branch, "main")
20601            .await
20602            .unwrap();
20603        git::worktree_add_detached(&repo, &reviewer, "main")
20604            .await
20605            .unwrap();
20606        git::acquire_worktree_config(&repo).await.unwrap();
20607        state.enabled_worktree_config = true;
20608        state.status = RunStatus::Ready;
20609        state.candidates.push(Candidate {
20610            index: 0,
20611            label: 'A',
20612            agent: "implement".into(),
20613            branch: branch.clone(),
20614            worktree: candidate.clone(),
20615            summary: String::new(),
20616            stat: String::new(),
20617            files: 0,
20618            commits: 0,
20619            empty: false,
20620            failed: None,
20621            verified_noop: None,
20622            duration_ms: 0,
20623            folded: false,
20624        });
20625        state.save_under(&home).unwrap();
20626        let config_before = std::fs::read(common.join("config")).unwrap();
20627        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
20628            .await
20629            .unwrap();
20630        // A separate OS handle bypasses the launcher's local gate, exactly as
20631        // an external updater does, and must still prevent all folding work.
20632        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
20633        assert_eq!(
20634            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
20635            0
20636        );
20637        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20638        assert!(
20639            tokio::time::timeout(Duration::from_millis(200), &mut fold)
20640                .await
20641                .is_err()
20642        );
20643        assert!(candidate.exists());
20644        assert!(reviewer.exists());
20645        assert!(git::branch_exists(&repo, &branch).await.unwrap());
20646        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20647        assert_eq!(
20648            git::git(&repo, &["worktree", "list", "--porcelain"])
20649                .await
20650                .unwrap(),
20651            worktrees_before
20652        );
20653        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
20654            .await
20655            .unwrap()
20656            .unwrap_err();
20657        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
20658        drop(fold);
20659        assert!(candidate.exists() && reviewer.exists());
20660        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
20661        assert_eq!(
20662            state.resource_block.as_ref().unwrap().kind,
20663            "repository coordination"
20664        );
20665        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20666        drop(external);
20667        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20668        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
20669            .await
20670            .unwrap()
20671            .unwrap();
20672        drop(fold);
20673        assert!(removed.contains(&branch));
20674        assert!(!root.exists());
20675        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
20676        assert!(state.candidates[0].folded);
20677        assert!(!state.enabled_worktree_config);
20678        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
20679        let enabled = git::git_raw(
20680            &repo,
20681            &["config", "--local", "--get", "extensions.worktreeConfig"],
20682        )
20683        .await
20684        .unwrap();
20685        assert!(!enabled.ok(), "the last config reference was released");
20686    }
20687
20688    /// A branch handed to a later run is that run's (and its pull request's):
20689    /// folding the run that released it must not delete it.
20690    #[tokio::test]
20691    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
20692        let tmp = tempfile::tempdir().expect("tempdir");
20693        let repo = tmp.path().join("repo");
20694        std::fs::create_dir_all(&repo).unwrap();
20695        init_repo(&repo);
20696        let home = tmp.path().join("home");
20697
20698        let mut config = Config::default();
20699        config.graph.worktree_root = Some(tmp.path().join("wt"));
20700        let mut state = RunState::new(
20701            repo.clone(),
20702            "main".to_owned(),
20703            "deadbeef".to_owned(),
20704            "task".to_owned(),
20705            config,
20706        );
20707        // The worktree is already gone (released); the branch survives.
20708        git::git(&repo, &["branch", "magi/x/A", "main"])
20709            .await
20710            .expect("branch");
20711        state.candidates = vec![Candidate {
20712            index: 0,
20713            label: 'A',
20714            agent: "alpha".to_owned(),
20715            branch: "magi/x/A".to_owned(),
20716            worktree: state.worktree_root().join("cand-A"),
20717            summary: String::new(),
20718            stat: String::new(),
20719            files: 0,
20720            commits: 0,
20721            empty: false,
20722            failed: None,
20723            verified_noop: None,
20724            duration_ms: 0,
20725            folded: true,
20726        }];
20727        state.released_to = Some("20260901-000000-new1".to_owned());
20728        state.released_branches = vec!["magi/x/A".to_owned()];
20729
20730        fold_run(&mut state, true, &home).await.expect("fold_run");
20731        state.status = RunStatus::Merged;
20732        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
20733        state.merge = Some(crate::run::MergeOutcome {
20734            mode: MergeMode::Pr,
20735            ok: true,
20736            detail: "confirmed merged".into(),
20737            empty: false,
20738        });
20739        fold_run(&mut state, true, &home)
20740            .await
20741            .expect("merged fold");
20742
20743        assert!(
20744            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20745            "the handed-over branch survives a fold"
20746        );
20747    }
20748
20749    /// A winner with nothing ahead of the base is caught before `gh` is ever
20750    /// asked for a pull request, and the message carries what the task's
20751    /// references resolved to.
20752    #[tokio::test]
20753    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
20754        let tmp = tempfile::tempdir().expect("tempdir");
20755        let repo = tmp.path().join("repo");
20756        std::fs::create_dir_all(&repo).unwrap();
20757        init_repo(&repo);
20758        let run = |args: &[&str]| {
20759            let out = std::process::Command::new("git")
20760                .quiet()
20761                .args(args)
20762                .current_dir(&repo)
20763                .output()
20764                .expect("spawn git");
20765            assert!(out.status.success(), "git {args:?}");
20766        };
20767        run(&["branch", "magi/x/A"]);
20768        run(&["checkout", "-q", "-b", "magi/x/B"]);
20769        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
20770        run(&["add", "-A"]);
20771        run(&["commit", "-q", "-m", "work"]);
20772        run(&["checkout", "-q", "main"]);
20773
20774        // A pull request is compared against the remote's base, so the
20775        // fixture needs one. Before it exists nothing can be read, and the
20776        // answer must be "not empty".
20777        let probe = RunState::new(
20778            repo.clone(),
20779            "main".to_owned(),
20780            "deadbeef".to_owned(),
20781            "task".to_owned(),
20782            Config::default(),
20783        );
20784        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
20785        let bare = tmp.path().join("origin.git");
20786        let out = std::process::Command::new("git")
20787            .quiet()
20788            .args(["init", "-q", "--bare"])
20789            .arg(&bare)
20790            .output()
20791            .expect("spawn git");
20792        assert!(out.status.success(), "git init --bare");
20793        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
20794        run(&["push", "-q", "origin", "main"]);
20795
20796        let mut state = RunState::new(
20797            repo.clone(),
20798            "main".to_owned(),
20799            "deadbeef".to_owned(),
20800            "task".to_owned(),
20801            Config::default(),
20802        );
20803        state.seeds = vec![refs::Seed {
20804            token: "magi/27b2/A".to_owned(),
20805            kind: refs::SeedKind::Unresolved,
20806            sha: String::new(),
20807            branch: true,
20808            detail: "no branch or commit named magi/27b2/A".to_owned(),
20809        }];
20810
20811        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
20812        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
20813        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
20814        let detail = empty_candidate_detail(&state, "main");
20815        assert!(detail.starts_with("empty candidate"), "{detail}");
20816        assert!(!detail.contains("magi/27b2/A"), "{detail}");
20817        assert!(detail.contains("--start-from"), "{detail}");
20818    }
20819
20820    /// `status == Ready` used to be read as "this is the harmless
20821    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
20822    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
20823    /// run's PR was closed without merging — and reentering `merge` with
20824    /// `mode` still `Pr` does not know the difference, so it pushed and
20825    /// opened a second pull request. `mode == Local` reproduces the same
20826    /// blind spot without a network call: reentry must not attempt another
20827    /// git merge once this node has already recorded an outcome.
20828    #[tokio::test]
20829    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
20830        let tmp = tempfile::tempdir().expect("tempdir");
20831        let repo = tmp.path().join("repo");
20832        std::fs::create_dir_all(&repo).unwrap();
20833        init_repo(&repo);
20834
20835        let mut config = Config::default();
20836        config.merge.mode = MergeMode::Local;
20837
20838        let mut state = RunState::new(
20839            repo.clone(),
20840            "main".to_owned(),
20841            "deadbeef".to_owned(),
20842            "task".to_owned(),
20843            config,
20844        );
20845        state.candidates = vec![Candidate {
20846            index: 0,
20847            label: 'A',
20848            agent: "alpha".to_owned(),
20849            branch: "does-not-exist".to_owned(),
20850            worktree: repo.clone(),
20851            summary: String::new(),
20852            stat: String::new(),
20853            files: 0,
20854            commits: 0,
20855            empty: false,
20856            failed: None,
20857            verified_noop: None,
20858            duration_ms: 0,
20859            folded: false,
20860        }];
20861        state.tally = Some(Tally {
20862            first_choice: BTreeMap::from([('A', 1)]),
20863            borda: BTreeMap::new(),
20864            winner: 'A',
20865            rankings: 1,
20866            unanimous_initial: true,
20867            deliberated: false,
20868            changed_votes: 0,
20869            unanimous_final: true,
20870            tie_break: None,
20871            judges: 0,
20872            present: 0,
20873            quorum: 0,
20874            met_quorum: true,
20875            uncontested: Some("only candidate A produced a change".to_owned()),
20876        });
20877        state.reviews = vec![ReviewRound {
20878            round: 1,
20879            head: "deadbeef".to_owned(),
20880            verified_head: None,
20881            verified_at: None,
20882            reviews: Vec::new(),
20883            e2e: Vec::new(),
20884            fix: None,
20885            blocking: 0,
20886            answered: 0,
20887            expected: 0,
20888            clean: true,
20889            verify_retried: false,
20890            e2e_deferred: false,
20891            e2e_defer_reason: None,
20892            progressed: false,
20893            vote_split: false,
20894            reconsideration: Vec::new(),
20895            verdict: None,
20896        }];
20897        state.gate = vec![CommandOutcome {
20898            command: "test".to_owned(),
20899            code: Some(0),
20900            output_tail: String::new(),
20901            duration_ms: 0,
20902            resource_blocked: false,
20903            ..Default::default()
20904        }];
20905        state.gate_ran = true;
20906        // Reached its conclusion already — e.g. `land` closing the PR without
20907        // merging it, which (like the honest `MergeMode::None` path) leaves
20908        // `status` at `Ready`. The recorded outcome is what actually marks
20909        // this node done.
20910        state.status = RunStatus::Ready;
20911        state.merge = Some(MergeOutcome {
20912            mode: MergeMode::Local,
20913            ok: false,
20914            detail: "already concluded".to_owned(),
20915            empty: false,
20916        });
20917
20918        let mut runner = Runner {
20919            state,
20920            roles: ResolvedRoles {
20921                implementers: Vec::new(),
20922                judges: Vec::new(),
20923                reviewers: Vec::new(),
20924                fixer: None,
20925                conductor: conductor(),
20926                implementer_roster: Vec::new(),
20927                judge_roster: Vec::new(),
20928                reviewer_roster: Vec::new(),
20929            },
20930            sem: Arc::new(Semaphore::new(1)),
20931            pause: Pause::new(),
20932            interrupt: Pause::new(),
20933        };
20934
20935        runner.merge().await.expect("merge");
20936
20937        assert_eq!(
20938            runner.state.status,
20939            RunStatus::Ready,
20940            "a concluded run's status must not change on reentry"
20941        );
20942        assert_eq!(
20943            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
20944            Some("already concluded"),
20945            "merge must not run again once the node already recorded an outcome"
20946        );
20947    }
20948
20949    /// `gate` leaves `state.gate_ran` false both before it has ever run and
20950    /// when its last attempt was resource-blocked (the shared build cache
20951    /// could not be acquired or confirmed fresh in time - see
20952    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
20953    /// `Vec` this also leaves behind used to read as "nothing failed" and let
20954    /// a run merge a tree the gate never actually checked - exactly the case
20955    /// a contended cache produces on every retry until it clears. `merge`
20956    /// must refuse until `gate` has actually recorded an attempt.
20957    #[tokio::test]
20958    async fn merge_refuses_a_gate_that_has_not_actually_run() {
20959        let tmp = tempfile::tempdir().expect("tempdir");
20960        let repo = tmp.path().join("repo");
20961        std::fs::create_dir_all(&repo).unwrap();
20962        init_repo(&repo);
20963
20964        let mut config = Config::default();
20965        config.merge.mode = MergeMode::Local;
20966
20967        let mut state = RunState::new(
20968            repo.clone(),
20969            "main".to_owned(),
20970            "deadbeef".to_owned(),
20971            "task".to_owned(),
20972            config,
20973        );
20974        state.candidates = vec![Candidate {
20975            index: 0,
20976            label: 'A',
20977            agent: "alpha".to_owned(),
20978            branch: "does-not-exist".to_owned(),
20979            worktree: repo.clone(),
20980            summary: String::new(),
20981            stat: String::new(),
20982            files: 0,
20983            commits: 0,
20984            empty: false,
20985            failed: None,
20986            verified_noop: None,
20987            duration_ms: 0,
20988            folded: false,
20989        }];
20990        state.tally = Some(Tally {
20991            first_choice: BTreeMap::from([('A', 1)]),
20992            borda: BTreeMap::new(),
20993            winner: 'A',
20994            rankings: 1,
20995            unanimous_initial: true,
20996            deliberated: false,
20997            changed_votes: 0,
20998            unanimous_final: true,
20999            tie_break: None,
21000            judges: 0,
21001            present: 0,
21002            quorum: 0,
21003            met_quorum: true,
21004            uncontested: Some("only candidate A produced a change".to_owned()),
21005        });
21006        state.reviews = vec![ReviewRound {
21007            round: 1,
21008            head: "deadbeef".to_owned(),
21009            verified_head: None,
21010            verified_at: None,
21011            reviews: Vec::new(),
21012            e2e: Vec::new(),
21013            fix: None,
21014            blocking: 0,
21015            answered: 0,
21016            expected: 0,
21017            clean: true,
21018            verify_retried: false,
21019            e2e_deferred: false,
21020            e2e_defer_reason: None,
21021            progressed: false,
21022            vote_split: false,
21023            reconsideration: Vec::new(),
21024            verdict: None,
21025        }];
21026        // The point: `gate` has not recorded anything yet.
21027        state.gate = Vec::new();
21028        state.gate_ran = false;
21029        state.status = RunStatus::Gating;
21030
21031        let mut runner = Runner {
21032            state,
21033            roles: ResolvedRoles {
21034                implementers: Vec::new(),
21035                judges: Vec::new(),
21036                reviewers: Vec::new(),
21037                fixer: None,
21038                conductor: conductor(),
21039                implementer_roster: Vec::new(),
21040                judge_roster: Vec::new(),
21041                reviewer_roster: Vec::new(),
21042            },
21043            sem: Arc::new(Semaphore::new(1)),
21044            pause: Pause::new(),
21045            interrupt: Pause::new(),
21046        };
21047
21048        runner.merge().await.expect("merge");
21049
21050        assert!(
21051            runner.state.merge.is_none(),
21052            "an empty gate must never be read as a passing one: {:?}",
21053            runner.state.merge
21054        );
21055    }
21056
21057    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
21058    /// commands configured and `merge.mode` is `none` (a review-only run).
21059    /// `gate` must still record a real attempt — zero commands, vacuously
21060    /// passed — rather than leaving `state.gate` empty in a way `merge`
21061    /// cannot tell apart from "never ran"; otherwise the run reaches
21062    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
21063    #[tokio::test]
21064    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
21065        let tmp = tempfile::tempdir().expect("tempdir");
21066        let repo = tmp.path().join("repo");
21067        std::fs::create_dir_all(&repo).unwrap();
21068        init_repo(&repo);
21069
21070        // Default config: `verify.gate` empty, `merge.mode` is `none`.
21071        let config = Config::default();
21072
21073        let mut state = RunState::new(
21074            repo.clone(),
21075            "main".to_owned(),
21076            "deadbeef".to_owned(),
21077            "task".to_owned(),
21078            config,
21079        );
21080        state.candidates = vec![Candidate {
21081            index: 0,
21082            label: 'A',
21083            agent: "alpha".to_owned(),
21084            branch: "does-not-exist".to_owned(),
21085            worktree: repo.clone(),
21086            summary: String::new(),
21087            stat: String::new(),
21088            files: 0,
21089            commits: 0,
21090            empty: false,
21091            failed: None,
21092            verified_noop: None,
21093            duration_ms: 0,
21094            folded: false,
21095        }];
21096        state.tally = Some(Tally {
21097            first_choice: BTreeMap::from([('A', 1)]),
21098            borda: BTreeMap::new(),
21099            winner: 'A',
21100            rankings: 1,
21101            unanimous_initial: true,
21102            deliberated: false,
21103            changed_votes: 0,
21104            unanimous_final: true,
21105            tie_break: None,
21106            judges: 0,
21107            present: 0,
21108            quorum: 0,
21109            met_quorum: true,
21110            uncontested: Some("only candidate A produced a change".to_owned()),
21111        });
21112        state.reviews = vec![ReviewRound {
21113            round: 1,
21114            head: "deadbeef".to_owned(),
21115            verified_head: None,
21116            verified_at: None,
21117            reviews: Vec::new(),
21118            e2e: Vec::new(),
21119            fix: None,
21120            blocking: 0,
21121            answered: 0,
21122            expected: 0,
21123            clean: true,
21124            verify_retried: false,
21125            e2e_deferred: false,
21126            e2e_defer_reason: None,
21127            progressed: false,
21128            vote_split: false,
21129            reconsideration: Vec::new(),
21130            verdict: None,
21131        }];
21132
21133        let mut runner = Runner {
21134            state,
21135            roles: ResolvedRoles {
21136                implementers: Vec::new(),
21137                judges: Vec::new(),
21138                reviewers: Vec::new(),
21139                fixer: None,
21140                conductor: conductor(),
21141                implementer_roster: Vec::new(),
21142                judge_roster: Vec::new(),
21143                reviewer_roster: Vec::new(),
21144            },
21145            sem: Arc::new(Semaphore::new(1)),
21146            pause: Pause::new(),
21147            interrupt: Pause::new(),
21148        };
21149
21150        runner.gate().await.expect("gate");
21151        assert!(
21152            runner.state.gate_ran,
21153            "zero configured commands is still a real attempt, not an unrun gate"
21154        );
21155        assert!(runner.state.gate.is_empty());
21156        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21157        assert_ne!(
21158            runner.state.status,
21159            RunStatus::Blocked,
21160            "a gate with nothing to check must not read as failed"
21161        );
21162
21163        runner.merge().await.expect("merge");
21164        assert_eq!(
21165            runner.state.status,
21166            RunStatus::Ready,
21167            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21168        );
21169    }
21170
21171    /// `Config::cache_dir` is derived from `verify.e2e` as well as
21172    /// `verify.gate` (so the e2e leg and the final gate never build against
21173    /// different directories). With zero `verify.gate` commands but a
21174    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
21175    /// that lease before discovering it had nothing to run - so a repo with
21176    /// no gate commands could come back `resource_blocked` (and therefore
21177    /// still `gate_ran == false`) on nothing but an unrelated run holding the
21178    /// cache, exactly the contention this run's own zero commands could
21179    /// never have touched. `gate` must recognise there is nothing to check
21180    /// before it ever asks for the lease.
21181    #[tokio::test]
21182    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
21183        crate::run::pin_test_home();
21184        let home = crate::run::home();
21185
21186        let tmp = tempfile::tempdir().expect("tempdir");
21187        let repo = tmp.path().join("repo");
21188        std::fs::create_dir_all(&repo).unwrap();
21189        init_repo(&repo);
21190        // Unique to this test, so holding its lease cannot collide with
21191        // another test sharing the same process-wide `home`.
21192        let cache_dir = tmp.path().join("target");
21193
21194        let mut config = Config::default();
21195        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
21196        // `verify.gate` stays empty (the default). Any accidental cache
21197        // acquisition must report contention immediately, regardless of how
21198        // long unrelated Git subprocesses take under parallel test load.
21199        config.graph.timeout_verify = Some(2);
21200        config.graph.timeout_resource_wait = 0;
21201
21202        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21203        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21204            .expect("no io error acquiring directly")
21205        {
21206            crate::cache::AcquireOutcome::Acquired(g) => g,
21207            crate::cache::AcquireOutcome::Busy(b) => {
21208                panic!("expected the direct acquire to win the lease first: {b:?}")
21209            }
21210        };
21211
21212        let mut state = RunState::new(
21213            repo.clone(),
21214            "main".to_owned(),
21215            "deadbeef".to_owned(),
21216            "task".to_owned(),
21217            config,
21218        );
21219        state.candidates = vec![Candidate {
21220            index: 0,
21221            label: 'A',
21222            agent: "alpha".to_owned(),
21223            branch: "does-not-exist".to_owned(),
21224            worktree: repo.clone(),
21225            summary: String::new(),
21226            stat: String::new(),
21227            files: 0,
21228            commits: 0,
21229            empty: false,
21230            failed: None,
21231            verified_noop: None,
21232            duration_ms: 0,
21233            folded: false,
21234        }];
21235        state.tally = Some(Tally {
21236            first_choice: BTreeMap::from([('A', 1)]),
21237            borda: BTreeMap::new(),
21238            winner: 'A',
21239            rankings: 1,
21240            unanimous_initial: true,
21241            deliberated: false,
21242            changed_votes: 0,
21243            unanimous_final: true,
21244            tie_break: None,
21245            judges: 0,
21246            present: 0,
21247            quorum: 0,
21248            met_quorum: true,
21249            uncontested: Some("only candidate A produced a change".to_owned()),
21250        });
21251        state.reviews = vec![ReviewRound {
21252            round: 1,
21253            head: "deadbeef".to_owned(),
21254            verified_head: None,
21255            verified_at: None,
21256            reviews: Vec::new(),
21257            e2e: Vec::new(),
21258            fix: None,
21259            blocking: 0,
21260            answered: 0,
21261            expected: 0,
21262            clean: true,
21263            verify_retried: false,
21264            e2e_deferred: false,
21265            e2e_defer_reason: None,
21266            progressed: false,
21267            vote_split: false,
21268            reconsideration: Vec::new(),
21269            verdict: None,
21270        }];
21271
21272        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
21273        state.reviews[0].e2e = vec![CommandOutcome {
21274            command: state.config.verify.e2e[0].clone(),
21275            code: Some(0),
21276            output_tail: String::new(),
21277            duration_ms: 0,
21278            resource_blocked: false,
21279            ..Default::default()
21280        }];
21281        let mut runner = Runner {
21282            state,
21283            roles: ResolvedRoles {
21284                implementers: Vec::new(),
21285                judges: Vec::new(),
21286                reviewers: Vec::new(),
21287                fixer: None,
21288                conductor: conductor(),
21289                implementer_roster: Vec::new(),
21290                judge_roster: Vec::new(),
21291                reviewer_roster: Vec::new(),
21292            },
21293            sem: Arc::new(Semaphore::new(1)),
21294            pause: Pause::new(),
21295            interrupt: Pause::new(),
21296        };
21297
21298        runner.gate().await.expect("gate");
21299        assert!(runner.state.resource_block.is_none());
21300        assert!(
21301            !runner
21302                .state
21303                .events
21304                .iter()
21305                .any(|event| { event.message.contains("waiting for the shared build cache") }),
21306            "a gate with nothing to run must never request the held cache lease"
21307        );
21308        assert!(
21309            runner.state.gate_ran,
21310            "zero commands is still a real, immediate attempt"
21311        );
21312        assert!(runner.state.gate.is_empty());
21313        assert_ne!(
21314            runner.state.status,
21315            RunStatus::Blocked,
21316            "must not read as resource-blocked on a lease it never asked for"
21317        );
21318    }
21319
21320    /// A separate process carries a live worker's environment throughout all
21321    /// verification entry points; the parallel harness never changes its env.
21322    #[cfg(unix)]
21323    #[tokio::test]
21324    async fn verification_is_standalone_inside_a_live_worker() {
21325        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
21326        if std::env::var_os(CHILD).is_none() {
21327            let home = tempfile::tempdir().unwrap();
21328            let generation = crate::worker::pin_current(home.path()).unwrap();
21329            let output = std::process::Command::new(std::env::current_exe().unwrap())
21330                .args([
21331                    "--exact",
21332                    "graph::tests::verification_is_standalone_inside_a_live_worker",
21333                    "--nocapture",
21334                ])
21335                .env(CHILD, "1")
21336                .env("MAGI_HOME", home.path())
21337                .env("MAGI_WORKER_HOME", home.path())
21338                .env("MAGI_WORKER_ID", "abcdef")
21339                .env("MAGI_WORKER_GENERATION", &generation.id)
21340                .env("MAGI_WORKER_EXE", &generation.executable)
21341                .env("MAGI_RUN", "verification-parent")
21342                .env("MAGI_NODE", "gate")
21343                .env("MAGI_SEAT", "worker-fixture")
21344                .env("MAGI_PROCESS_OWNER", "fixture-owner")
21345                .env("MAGI_NO_AUTOUPDATE", "0")
21346                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
21347                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
21348                .env(
21349                    "VERIFY_EXPECT_TOOLCHAIN",
21350                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
21351                )
21352                .env(
21353                    "VERIFY_EXPECT_CACHE",
21354                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
21355                )
21356                .output()
21357                .unwrap();
21358            assert!(
21359                output.status.success()
21360                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
21361                "{}\n{}",
21362                String::from_utf8_lossy(&output.stdout),
21363                String::from_utf8_lossy(&output.stderr)
21364            );
21365            return;
21366        }
21367        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
21368        let home = crate::run::home();
21369        let directory = home.join("workers/jobs/abcdef");
21370        std::fs::create_dir_all(&directory).unwrap();
21371        let job = crate::worker::Job {
21372            id: "abcdef".into(),
21373            sequence: 1,
21374            kind: "task".into(),
21375            key: "task:verification".into(),
21376            payload: serde_json::json!({}),
21377            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
21378            version: Some(env!("CARGO_PKG_VERSION").into()),
21379            status: crate::worker::Status::Running,
21380            result: None,
21381            pid: Some(std::process::id()),
21382            created_at: 0,
21383            finished_at: None,
21384        };
21385        std::fs::write(
21386            directory.join("job.json"),
21387            serde_json::to_vec(&job).unwrap(),
21388        )
21389        .unwrap();
21390        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
21391        let assert_worker = || {
21392            assert_eq!(
21393                crate::worker::current_job(&home).unwrap().unwrap().id,
21394                job.id
21395            );
21396            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
21397            assert_eq!(
21398                crate::worker::helper_executable(&home).unwrap(),
21399                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
21400            );
21401            assert!(
21402                crate::updater::Checker::new(&crate::config::Update {
21403                    mode: crate::config::UpdateMode::Notify,
21404                    interval: None,
21405                    auto_restart: false,
21406                })
21407                .is_none(),
21408                "the driver remains pinned, even while tests are standalone"
21409            );
21410        };
21411        assert_worker();
21412        let repo = home.join("repo");
21413        std::fs::create_dir_all(&repo).unwrap();
21414        init_repo(&repo);
21415        // Keep storage, seat/control context, containment and tool lookup.
21416        // No inherited values (or credentials) are printed on success.
21417        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
21418            test -z "${MAGI_WORKER_GENERATION+x}" &&
21419            test -z "${MAGI_WORKER_HOME+x}" &&
21420            test -z "${MAGI_WORKER_EXE+x}" &&
21421            test "$MAGI_HOME/repo" -ef . &&
21422            test "$MAGI_RUN" = verification-parent &&
21423            test "$MAGI_NODE" = gate &&
21424            test "$MAGI_SEAT" = worker-fixture &&
21425            test -n "$MAGI_PROCESS_OWNER" &&
21426            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
21427            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
21428            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
21429            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
21430        // Negative control: an ordinary child inherits the contamination.
21431        assert!(
21432            !std::process::Command::new("sh")
21433                .args(["-c", probe])
21434                .current_dir(&repo)
21435                .status()
21436                .unwrap()
21437                .success()
21438        );
21439        let unrelated_home = tempfile::tempdir().unwrap();
21440        assert!(
21441            crate::worker::current_job(unrelated_home.path()).is_err(),
21442            "an inherited worker id cannot be resolved in a unit fixture's home"
21443        );
21444        let mut runner = runner_at(RunStatus::Gating);
21445        runner.state.repo = repo.clone();
21446        runner.state.config.disk.min_free_bytes = 0;
21447        runner.state.config.coordination = crate::config::test_coordination();
21448        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
21449        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
21450        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
21451        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
21452        let winner = Candidate {
21453            index: 0,
21454            label: 'A',
21455            agent: "fixture".into(),
21456            branch: "main".into(),
21457            worktree: repo.clone(),
21458            summary: String::new(),
21459            stat: String::new(),
21460            files: 0,
21461            commits: 0,
21462            empty: false,
21463            failed: None,
21464            verified_noop: None,
21465            duration_ms: 0,
21466            folded: false,
21467        };
21468        let (e2e, retried, pids) = run_e2e_with_retry(
21469            &mut runner.state,
21470            &["sh".into(), "-c".into()],
21471            &[format!("{probe} && printf initial")],
21472            &repo,
21473            Duration::from_secs(10),
21474            "initial",
21475            None,
21476        )
21477        .await;
21478        assert!(!retried && pids.is_empty());
21479        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
21480        assert_eq!(e2e[0].output_tail, "initial");
21481        let gate = runner.run_gate(&winner).await.unwrap();
21482        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
21483        // An interrupted repair must recheck e2e from saved state. Landing
21484        // reuses that state and must run both pre-gate and gate again.
21485        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
21486            head: git::rev_parse(&repo, "HEAD").await.unwrap(),
21487            passed: false,
21488            outcomes: Vec::new(),
21489        });
21490        runner.state.save().unwrap();
21491        let mut resumed = RunState::load(&runner.state.id).unwrap();
21492        let wait = crate::repo_lock::WaitPolicy::default();
21493        assert!(matches!(
21494            check_gate_repair_e2e(&mut resumed, &winner, &wait)
21495                .await
21496                .unwrap(),
21497            GateFix::Retry
21498        ));
21499        let saved = RunState::load(&resumed.id).unwrap();
21500        let repair = saved.gate_repair_e2e.unwrap();
21501        assert!(repair.passed);
21502        assert_eq!(repair.outcomes.len(), 1);
21503        assert!(repair.outcomes[0].ok());
21504        let landing = run_landing_gate(&mut resumed, &winner, &wait)
21505            .await
21506            .unwrap();
21507        assert_eq!(landing.len(), 1);
21508        assert!(landing[0].ok(), "{landing:?}");
21509        assert_eq!(
21510            std::fs::read_to_string(repo.join("phases")).unwrap(),
21511            "pre\ngate\ne2e\npre\ngate\n"
21512        );
21513        assert_worker();
21514    }
21515
21516    #[cfg(unix)]
21517    #[tokio::test]
21518    async fn verification_keeps_the_panic_and_the_full_output() {
21519        crate::run::pin_test_home();
21520        let tmp = tempfile::tempdir().unwrap();
21521        let mut config = Config::default();
21522        config.disk.min_free_bytes = 0;
21523        let mut state = RunState::new(
21524            tmp.path().to_owned(),
21525            "main".into(),
21526            "base".into(),
21527            "verification evidence".into(),
21528            config,
21529        );
21530        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
21531                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
21532                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
21533        let mut names = Vec::new();
21534        for _ in 0..2 {
21535            let (outcomes, _) = run_commands(
21536                &mut state,
21537                "gate",
21538                "gate",
21539                0,
21540                &["sh".into(), "-c".into()],
21541                &[script.into()],
21542                tmp.path(),
21543                Duration::from_secs(60),
21544            )
21545            .await;
21546            let tail = &outcomes[0].output_tail;
21547            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
21548            assert!(tail.contains("boom assertion"));
21549            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
21550            let line = tail.lines().next().unwrap();
21551            names.push(line.to_owned());
21552        }
21553        assert_ne!(names[0], names[1], "the second run must not overwrite");
21554        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
21555        assert!(full.len() > 500_000 && full.contains("boom assertion"));
21556        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
21557
21558        // Storage failures are evidence too; preserve the command's verdict.
21559        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
21560        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
21561        let (outcomes, _) = run_commands(
21562            &mut state,
21563            "gate",
21564            "gate",
21565            0,
21566            &["sh".into(), "-c".into()],
21567            &["echo failure-output; exit 7".into()],
21568            tmp.path(),
21569            Duration::from_secs(10),
21570        )
21571        .await;
21572        assert_eq!(outcomes[0].code, Some(7));
21573        assert!(state.events.iter().any(|e| {
21574            e.node == "gate" && e.message.contains("could not save the full gate output:")
21575        }));
21576    }
21577
21578    #[cfg(unix)]
21579    #[tokio::test]
21580    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
21581        crate::run::pin_test_home();
21582        let tmp = tempfile::tempdir().unwrap();
21583        let mut config = Config::default();
21584        config.disk.min_free_bytes = 0;
21585        let mut state = RunState::new(
21586            tmp.path().to_owned(),
21587            "main".into(),
21588            "base".into(),
21589            "verification evidence".into(),
21590            config,
21591        );
21592        let (outcomes, pids) = run_commands(
21593            &mut state,
21594            "gate",
21595            "gate",
21596            1,
21597            &["sh".into(), "-c".into()],
21598            &[
21599                "printf before-timeout; exec sleep 30".into(),
21600                "kill -TERM $$".into(),
21601                "exit 7".into(),
21602                "printf success".into(),
21603            ],
21604            tmp.path(),
21605            Duration::from_secs(1),
21606        )
21607        .await;
21608        wait_for_timed_out_children_to_die(&pids).await;
21609        assert_eq!(
21610            pids.len(),
21611            1,
21612            "unleased timeout retains its death-check PID"
21613        );
21614        assert_eq!(outcomes.len(), 4);
21615        assert_eq!(outcomes[0].code, None);
21616        assert!(outcomes[0].output_tail.contains("before-timeout"));
21617        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
21618        assert_eq!(outcomes[1].code, None);
21619        assert!(outcomes[1].output_tail.contains("command terminated:"));
21620        assert!(!outcomes[1].output_tail.contains("timed out"));
21621        assert_eq!(outcomes[2].code, Some(7));
21622        assert!(!outcomes[2].output_tail.contains("timed out"));
21623        assert_eq!(outcomes[3].code, Some(0));
21624        assert_eq!(outcomes[3].output_tail, "success");
21625        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
21626    }
21627
21628    /// The addendum's second gap: a `verify.gate` command running for real
21629    /// wall-clock time had nothing at all to show for it in `active` before
21630    /// `run_commands` learned to record it — a run could sit in `Gating` for
21631    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
21632    /// what was actually happening. Proven with a genuinely still-running
21633    /// command, not just a before/after check on the final state: a poller
21634    /// task reads the same `run.json` `gate()` is writing, the same way the
21635    /// phone or `magi show` would, while the shell command is still blocked
21636    /// on its own release marker.
21637    #[tokio::test]
21638    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
21639        crate::run::pin_test_home();
21640
21641        let tmp = tempfile::tempdir().expect("tempdir");
21642        let repo = tmp.path().join("repo");
21643        std::fs::create_dir_all(&repo).unwrap();
21644        init_repo(&repo);
21645
21646        let mut config = Config::default();
21647        config.disk.min_free_bytes = 0;
21648        config.verify.gate = vec![
21649            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
21650             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
21651                .to_owned(),
21652        ];
21653
21654        let mut state = RunState::new(
21655            repo.clone(),
21656            "main".to_owned(),
21657            "deadbeef".to_owned(),
21658            "task".to_owned(),
21659            config,
21660        );
21661        let run_id = state.id.clone();
21662        state.candidates = vec![Candidate {
21663            index: 0,
21664            label: 'A',
21665            agent: "alpha".to_owned(),
21666            branch: "does-not-exist".to_owned(),
21667            worktree: repo.clone(),
21668            summary: String::new(),
21669            stat: String::new(),
21670            files: 0,
21671            commits: 0,
21672            empty: false,
21673            failed: None,
21674            verified_noop: None,
21675            duration_ms: 0,
21676            folded: false,
21677        }];
21678        state.tally = Some(Tally {
21679            first_choice: BTreeMap::from([('A', 1)]),
21680            borda: BTreeMap::new(),
21681            winner: 'A',
21682            rankings: 1,
21683            unanimous_initial: true,
21684            deliberated: false,
21685            changed_votes: 0,
21686            unanimous_final: true,
21687            tie_break: None,
21688            judges: 0,
21689            present: 0,
21690            quorum: 0,
21691            met_quorum: true,
21692            uncontested: Some("only candidate A produced a change".to_owned()),
21693        });
21694        state.reviews = vec![ReviewRound {
21695            round: 1,
21696            head: "deadbeef".to_owned(),
21697            verified_head: None,
21698            verified_at: None,
21699            reviews: Vec::new(),
21700            e2e: Vec::new(),
21701            fix: None,
21702            blocking: 0,
21703            answered: 0,
21704            expected: 0,
21705            clean: true,
21706            verify_retried: false,
21707            e2e_deferred: false,
21708            e2e_defer_reason: None,
21709            progressed: false,
21710            vote_split: false,
21711            reconsideration: Vec::new(),
21712            verdict: None,
21713        }];
21714
21715        let mut runner = Runner {
21716            state,
21717            roles: ResolvedRoles {
21718                implementers: Vec::new(),
21719                judges: Vec::new(),
21720                reviewers: Vec::new(),
21721                fixer: None,
21722                conductor: conductor(),
21723                implementer_roster: Vec::new(),
21724                judge_roster: Vec::new(),
21725                reviewer_roster: Vec::new(),
21726            },
21727            sem: Arc::new(Semaphore::new(1)),
21728            pause: Pause::new(),
21729            interrupt: Pause::new(),
21730        };
21731
21732        let started_marker = repo.join("started.marker");
21733        let release_marker = repo.join("release.marker");
21734        let observe = async {
21735            loop {
21736                if started_marker.exists()
21737                    && let Ok(s) = crate::run::RunState::load(&run_id)
21738                    && let Some(a) = s.active.get("gate")
21739                {
21740                    std::fs::write(&release_marker, b"go").expect("release marker");
21741                    break a.clone();
21742                }
21743                tokio::time::sleep(Duration::from_millis(50)).await;
21744            }
21745        };
21746        let captured = {
21747            let gate = runner.gate();
21748            tokio::pin!(gate);
21749            let captured = tokio::select! {
21750                observed = observe => observed,
21751                result = &mut gate => panic!(
21752                    "gate exited before its in-flight entry was observed: {result:?}"
21753                ),
21754            };
21755            gate.await.expect("gate");
21756            captured
21757        };
21758
21759        assert_eq!(captured.task.as_deref(), Some("gate"));
21760        assert_eq!(captured.node, "gate");
21761        assert_eq!(captured.index, Some(1));
21762        assert_eq!(captured.total, Some(1));
21763        assert!(
21764            captured
21765                .command
21766                .as_deref()
21767                .is_some_and(|c| c.contains("started.marker")),
21768            "{captured:?}"
21769        );
21770
21771        assert!(
21772            runner.state.active.is_empty(),
21773            "the entry must be cleared once the command actually finished: {:?}",
21774            runner.state.active
21775        );
21776        assert!(runner.state.gate_ran);
21777        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
21778    }
21779
21780    /// The hand-off over a blocking finding a reviewer rejected on leaves a
21781    /// record for `land`; one with only a Minor, or no reject, leaves none.
21782    #[tokio::test]
21783    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
21784        use crate::verdict::{Finding, ReviewVote, Severity};
21785        crate::run::pin_test_home();
21786        let tmp = tempfile::tempdir().expect("tempdir");
21787        let repo = tmp.path().join("repo");
21788        std::fs::create_dir_all(&repo).unwrap();
21789        init_repo(&repo);
21790
21791        for (severity, vote, expect) in [
21792            (Severity::Major, ReviewVote::Reject, true),
21793            (Severity::Minor, ReviewVote::Reject, false),
21794            (Severity::Major, ReviewVote::Approve, false),
21795        ] {
21796            let mut round = review_round(false, 1, 1, 1, false, true);
21797            round.reviews = vec![ReviewRecord {
21798                reviewer: 1,
21799                agent: "alpha".to_owned(),
21800                summary: String::new(),
21801                findings: vec![Finding {
21802                    id: "R1-1-1".to_owned(),
21803                    severity,
21804                    file: None,
21805                    line: None,
21806                    title: "t".to_owned(),
21807                    detail: String::new(),
21808                }],
21809                vote: Some(vote),
21810                failed: None,
21811                duration_ms: 0,
21812                attempts: 0,
21813            }];
21814            let mut state = RunState::new(
21815                repo.clone(),
21816                "main".to_owned(),
21817                "deadbeef".to_owned(),
21818                "task".to_owned(),
21819                Config::default(),
21820            );
21821            state.reviews = vec![round];
21822            let mut runner = Runner {
21823                state,
21824                roles: ResolvedRoles {
21825                    implementers: Vec::new(),
21826                    judges: Vec::new(),
21827                    reviewers: Vec::new(),
21828                    fixer: None,
21829                    conductor: conductor(),
21830                    implementer_roster: Vec::new(),
21831                    judge_roster: Vec::new(),
21832                    reviewer_roster: Vec::new(),
21833                },
21834                sem: Arc::new(Semaphore::new(1)),
21835                pause: Pause::new(),
21836                interrupt: Pause::new(),
21837            };
21838            let shell = runner.state.config.shell();
21839            runner
21840                .stop_reviewing("round budget spent", &shell, &repo)
21841                .await
21842                .expect("stop_reviewing");
21843            assert_eq!(runner.state.status, RunStatus::Gating);
21844            assert_eq!(
21845                runner.state.contested_handoff.is_some(),
21846                expect,
21847                "{severity:?} + {vote:?}"
21848            );
21849        }
21850    }
21851
21852    /// The shape the incident this whole fix responds to actually had: the
21853    /// round budget spent, the last round's own e2e blocked on the shared
21854    /// build cache (held here by a live pid — this test process — exactly
21855    /// `cache`'s own unit tests' pattern for "another owner, still alive"
21856    /// without forking a process). `stop_reviewing` must retry it — not
21857    /// silently leave the round looking untouched (the catch-up-only half of
21858    /// the bug), and not read the contention as a red `e2e` and block the
21859    /// run on it (the other half). Called directly, the same way
21860    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
21861    /// above exercises `gate`, so this never needs a real cargo build to
21862    /// reach: the lease is never released, so `with_cache_lease` never gets
21863    /// past acquiring it into anything that would need a real workspace.
21864    #[tokio::test]
21865    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
21866        crate::run::pin_test_home();
21867        let home = crate::run::home();
21868
21869        let tmp = tempfile::tempdir().expect("tempdir");
21870        let repo = tmp.path().join("repo");
21871        std::fs::create_dir_all(&repo).unwrap();
21872        init_repo(&repo);
21873        let head = crate::git::rev_parse(&repo, "HEAD")
21874            .await
21875            .expect("rev-parse");
21876        // Unique to this test, so holding its lease cannot collide with
21877        // another test sharing the same process-wide `home`.
21878        let cache_dir = tmp.path().join("target");
21879
21880        let mut config = Config::default();
21881        config.verify.e2e = vec![format!(
21882            "CARGO_TARGET_DIR='{}' test -f README.md",
21883            cache_dir.display()
21884        )];
21885        config.graph.review_rounds = 1;
21886        // Bounded so a regression that does start waiting fails the test in
21887        // seconds, not hangs it.
21888        config.graph.timeout_verify = Some(2);
21889        config.graph.timeout_resource_wait = 2;
21890
21891        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21892        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21893            .expect("no io error acquiring directly")
21894        {
21895            crate::cache::AcquireOutcome::Acquired(g) => g,
21896            crate::cache::AcquireOutcome::Busy(b) => {
21897                panic!("expected the direct acquire to win the lease first: {b:?}")
21898            }
21899        };
21900
21901        let mut state = RunState::new(
21902            repo.clone(),
21903            "main".to_owned(),
21904            head.clone(),
21905            "task".to_owned(),
21906            config,
21907        );
21908        state.candidates = vec![Candidate {
21909            index: 0,
21910            label: 'A',
21911            agent: "alpha".to_owned(),
21912            branch: "does-not-exist".to_owned(),
21913            worktree: repo.clone(),
21914            summary: String::new(),
21915            stat: String::new(),
21916            files: 0,
21917            commits: 0,
21918            empty: false,
21919            failed: None,
21920            verified_noop: None,
21921            duration_ms: 0,
21922            folded: false,
21923        }];
21924        state.tally = Some(Tally {
21925            first_choice: BTreeMap::from([('A', 1)]),
21926            borda: BTreeMap::new(),
21927            winner: 'A',
21928            rankings: 1,
21929            unanimous_initial: true,
21930            deliberated: false,
21931            changed_votes: 0,
21932            unanimous_final: true,
21933            tie_break: None,
21934            judges: 0,
21935            present: 0,
21936            quorum: 0,
21937            met_quorum: true,
21938            uncontested: Some("only candidate A produced a change".to_owned()),
21939        });
21940        // The round budget's last round, deferred: `needs_catchup_run`'s
21941        // other trigger. `stop_reviewing`'s retry machinery must treat this
21942        // exactly like a resource-blocked attempt once it actually runs.
21943        state.reviews = vec![ReviewRound {
21944            round: 1,
21945            head: head.clone(),
21946            verified_head: None,
21947            verified_at: None,
21948            reviews: Vec::new(),
21949            e2e: Vec::new(),
21950            fix: None,
21951            blocking: 1,
21952            answered: 1,
21953            expected: 1,
21954            clean: false,
21955            verify_retried: false,
21956            e2e_deferred: true,
21957            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
21958            progressed: false,
21959            vote_split: false,
21960            reconsideration: Vec::new(),
21961            verdict: None,
21962        }];
21963
21964        let mut runner = Runner {
21965            state,
21966            roles: ResolvedRoles {
21967                implementers: Vec::new(),
21968                judges: Vec::new(),
21969                reviewers: Vec::new(),
21970                fixer: None,
21971                conductor: conductor(),
21972                implementer_roster: Vec::new(),
21973                judge_roster: Vec::new(),
21974                reviewer_roster: Vec::new(),
21975            },
21976            sem: Arc::new(Semaphore::new(1)),
21977            pause: Pause::new(),
21978            interrupt: Pause::new(),
21979        };
21980
21981        let shell = runner.state.config.shell();
21982        runner
21983            .stop_reviewing("round budget spent", &shell, &repo)
21984            .await
21985            .expect("stop_reviewing");
21986
21987        let last = runner.state.reviews.last().expect("round record");
21988        assert_eq!(
21989            last.e2e_status(),
21990            E2eStatus::ResourceBlocked,
21991            "the shared cache is still held; the attempt must read as blocked, not deferred or \
21992             failed: {last:?}"
21993        );
21994        assert_eq!(
21995            last.verified_head.as_deref(),
21996            Some(head.as_str()),
21997            "which commit this attempt targeted is known even though nothing finished checking \
21998             it"
21999        );
22000        let first_attempt_at = last
22001            .verified_at
22002            .expect("when this attempt ran is known too");
22003        assert_ne!(
22004            runner.state.status,
22005            RunStatus::Blocked,
22006            "contention is evidence about the machine, not the patch — it must not settle the \
22007             run as blocked: {:?}",
22008            runner.state.status
22009        );
22010        assert!(
22011            !runner
22012                .state
22013                .events
22014                .iter()
22015                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
22016            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
22017            runner.state.events
22018        );
22019
22020        // The cache is still held: a later reentry must retry the same
22021        // round's verification again — not leave it looking exactly as
22022        // untouched as the first blocked attempt, which is indistinguishable
22023        // from never having tried again at all.
22024        runner
22025            .stop_reviewing("round budget spent", &shell, &repo)
22026            .await
22027            .expect("stop_reviewing retry");
22028        assert_eq!(
22029            runner.state.reviews.len(),
22030            1,
22031            "no new round was started: {:?}",
22032            runner.state.reviews
22033        );
22034        let last = runner.state.reviews.last().expect("round record");
22035        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
22036        assert!(
22037            last.verified_at.expect("still known") > first_attempt_at,
22038            "a second reentry must be a fresh attempt, not a stale copy of the first"
22039        );
22040        assert_ne!(runner.state.status, RunStatus::Blocked);
22041
22042        held.release();
22043    }
22044
22045    #[cfg(unix)]
22046    #[tokio::test]
22047    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
22048        ask_test_home();
22049        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
22050            let tmp = tempfile::tempdir().unwrap();
22051            let repo = tmp.path().join("repo");
22052            std::fs::create_dir(&repo).unwrap();
22053            init_repo(&repo);
22054            let run_git = |args: &[&str]| {
22055                let out = std::process::Command::new("git")
22056                    .args(args)
22057                    .current_dir(&repo)
22058                    .output()
22059                    .unwrap();
22060                assert!(
22061                    out.status.success(),
22062                    "{args:?}: {}",
22063                    String::from_utf8_lossy(&out.stderr)
22064                );
22065            };
22066            let origin = tmp.path().join("origin.git");
22067            run_git(&["init", "--bare", origin.to_str().unwrap()]);
22068            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
22069            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
22070            run_git(&["add", "spec.rs"]);
22071            run_git(&["commit", "-m", "initial spec"]);
22072            run_git(&["push", "origin", "main"]);
22073            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
22074            run_git(&["checkout", "-b", "fix/review"]);
22075            std::fs::write(
22076                repo.join("check.rs"),
22077                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
22078            )
22079            .unwrap();
22080            run_git(&["add", "check.rs"]);
22081            run_git(&["commit", "-m", "use spec"]);
22082            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
22083            run_git(&["checkout", "main"]);
22084            std::fs::write(
22085                repo.join("spec.rs"),
22086                "struct AgentSpec { max_turn_secs: u64 }\n",
22087            )
22088            .unwrap();
22089            run_git(&["add", "spec.rs"]);
22090            run_git(&["commit", "-m", "extend spec"]);
22091            run_git(&["push", "origin", "main"]);
22092            run_git(&["checkout", "fix/review"]);
22093
22094            let mut runner = runner_at(RunStatus::Reviewing);
22095            runner.state.repo = repo.clone();
22096            runner.state.base_commit = base;
22097            runner.state.pr_head = Some("fix/review".into());
22098            runner.state.config.graph.review_rounds = max_rounds;
22099            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22100            runner.state.config.graph.sessions = false;
22101            runner.state.config.disk.min_free_bytes = 0;
22102            runner.state.config.verify.e2e =
22103                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22104            runner.state.candidates = vec![Candidate {
22105                index: 0,
22106                label: 'A',
22107                agent: "fixture".into(),
22108                branch: "fix/review".into(),
22109                worktree: repo.clone(),
22110                summary: String::new(),
22111                stat: String::new(),
22112                files: 1,
22113                commits: 1,
22114                empty: false,
22115                failed: None,
22116                verified_noop: None,
22117                duration_ms: 0,
22118                folded: false,
22119            }];
22120            runner.state.tally = Some(Tally {
22121                first_choice: BTreeMap::new(),
22122                borda: BTreeMap::new(),
22123                winner: 'A',
22124                rankings: 0,
22125                unanimous_initial: true,
22126                deliberated: false,
22127                changed_votes: 0,
22128                unanimous_final: true,
22129                tie_break: None,
22130                judges: 0,
22131                present: 0,
22132                quorum: 0,
22133                met_quorum: true,
22134                uncontested: Some("review-only".into()),
22135            });
22136            let mut last = review_round(false, 0, 1, 1, false, false);
22137            last.head = reviewed.clone();
22138            last.e2e_deferred = true;
22139            last.e2e[0].resource_blocked = true;
22140            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22141            if max_rounds == 1 {
22142                last.e2e.clear();
22143            }
22144            runner.state.reviews = vec![last];
22145            let calls = tmp.path().join("fix-calls");
22146            let mut fixer = spec("repair");
22147            fixer
22148                .env
22149                .insert("FIX_CALLS".into(), calls.display().to_string());
22150            fixer.command = vec!["sh".into(), "-c".into(), r#"
22151                echo fix >> "$FIX_CALLS"
22152                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22153                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22154                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22155                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22156            "#.into()];
22157            let mut reviewer = spec("reviewer");
22158            reviewer.command = vec![
22159                "sh".into(),
22160                "-c".into(),
22161                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22162                    .into(),
22163            ];
22164            runner.roles.fixer = Some(vec![fixer]);
22165            runner.roles.reviewers = vec![reviewer];
22166
22167            runner.sync_to_base().await.unwrap();
22168            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22169            assert_ne!(rebased, reviewed);
22170            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
22171            if reentry {
22172                // Simulate a crash after catch-up evidence was saved but before
22173                // dispatching the fixer. No dedicated pending-repair field exists.
22174                let shell = runner.state.config.shell();
22175                runner
22176                    .stop_unresolved_review("deferred verification", &shell, &repo)
22177                    .await
22178                    .unwrap();
22179                assert!(runner.catchup_repairable());
22180                assert!(!calls.exists());
22181                runner.state = RunState::load(&runner.state.id).unwrap();
22182                assert!(runner.catchup_repairable());
22183            }
22184            runner.review_loop().await.unwrap();
22185            let first = &runner.state.reviews[0];
22186            assert_eq!(first.head, reviewed);
22187            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
22188            assert!(
22189                first.verify_retried,
22190                "a reproduced build failure gets exactly one retry: {:?}",
22191                first.e2e
22192            );
22193            assert!(first.e2e[0].output_tail.contains("E0063"));
22194            assert!(!runner.catchup_repairable());
22195            if max_rounds == 2 {
22196                assert_eq!(
22197                    runner.state.status,
22198                    RunStatus::Gating,
22199                    "{}",
22200                    crate::report::run(&runner.state)
22201                );
22202                assert_eq!(runner.state.reviews.len(), 2);
22203                assert!(first.fix.as_ref().unwrap().committed);
22204                assert!(runner.state.reviews[1].clean);
22205                assert_eq!(
22206                    runner
22207                        .state
22208                        .reviews
22209                        .iter()
22210                        .filter(|r| r.fix.is_some())
22211                        .count(),
22212                    1
22213                );
22214                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
22215                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
22216            } else {
22217                assert_eq!(runner.state.status, RunStatus::Blocked);
22218                assert!(first.fix.is_none());
22219                assert!(!calls.exists());
22220                let recovery = crate::recovery::assess(
22221                    "prior",
22222                    Some(&runner.state),
22223                    &runner.landing_base(),
22224                    crate::recovery::Relation::Diverged,
22225                );
22226                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
22227                let reasons = recovery.reasons.join("\n");
22228                assert!(
22229                    reasons.contains(&reviewed) && reasons.contains(&rebased),
22230                    "{reasons}"
22231                );
22232                assert!(
22233                    reasons.contains("base sync to")
22234                        && reasons.contains("additional review is required"),
22235                    "{reasons}"
22236                );
22237            }
22238        }
22239    }
22240
22241    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
22242    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
22243    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
22244    /// own top-of-function fast path (`review_conclusion`) correctly reads
22245    /// this shape as `None` rather than guessing `Blocked`, and the loop's
22246    /// own `for` range is empty once the round budget is spent, so
22247    /// `review_loop` must retry the check itself rather than silently doing
22248    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
22249    /// above exercises directly, but through `review_loop`'s own entry point
22250    /// this time, proving the wiring between the two rather than just the
22251    /// retry logic in isolation.
22252    #[tokio::test]
22253    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
22254        crate::run::pin_test_home();
22255        let home = crate::run::home();
22256
22257        let tmp = tempfile::tempdir().expect("tempdir");
22258        let repo = tmp.path().join("repo");
22259        std::fs::create_dir_all(&repo).unwrap();
22260        init_repo(&repo);
22261        let head = crate::git::rev_parse(&repo, "HEAD")
22262            .await
22263            .expect("rev-parse");
22264        let cache_dir = tmp.path().join("target");
22265
22266        let mut config = Config::default();
22267        config.verify.e2e = vec![format!(
22268            "CARGO_TARGET_DIR='{}' test -f README.md",
22269            cache_dir.display()
22270        )];
22271        config.graph.review_rounds = 1;
22272        config.graph.timeout_verify = Some(2);
22273        config.graph.timeout_resource_wait = 2;
22274
22275        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22276        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22277            .expect("no io error acquiring directly")
22278        {
22279            crate::cache::AcquireOutcome::Acquired(g) => g,
22280            crate::cache::AcquireOutcome::Busy(b) => {
22281                panic!("expected the direct acquire to win the lease first: {b:?}")
22282            }
22283        };
22284
22285        let mut state = RunState::new(
22286            repo.clone(),
22287            "main".to_owned(),
22288            head.clone(),
22289            "task".to_owned(),
22290            config,
22291        );
22292        state.candidates = vec![Candidate {
22293            index: 0,
22294            label: 'A',
22295            agent: "alpha".to_owned(),
22296            branch: "does-not-exist".to_owned(),
22297            worktree: repo.clone(),
22298            summary: String::new(),
22299            stat: String::new(),
22300            files: 0,
22301            commits: 0,
22302            empty: false,
22303            failed: None,
22304            verified_noop: None,
22305            duration_ms: 0,
22306            folded: false,
22307        }];
22308        state.tally = Some(Tally {
22309            first_choice: BTreeMap::from([('A', 1)]),
22310            borda: BTreeMap::new(),
22311            winner: 'A',
22312            rankings: 1,
22313            unanimous_initial: true,
22314            deliberated: false,
22315            changed_votes: 0,
22316            unanimous_final: true,
22317            tie_break: None,
22318            judges: 0,
22319            present: 0,
22320            quorum: 0,
22321            met_quorum: true,
22322            uncontested: Some("only candidate A produced a change".to_owned()),
22323        });
22324        // The exact shape a prior process's `stop_reviewing` would have left
22325        // on disk: the round budget's last round, a real attempt already
22326        // made and already resource-blocked.
22327        state.reviews = vec![ReviewRound {
22328            round: 1,
22329            head: head.clone(),
22330            verified_head: Some(head.clone()),
22331            verified_at: Some(jiff::Timestamp::now()),
22332            reviews: Vec::new(),
22333            e2e: vec![CommandOutcome {
22334                command: format!(
22335                    "CARGO_TARGET_DIR='{}' test -f README.md",
22336                    cache_dir.display()
22337                ),
22338                code: None,
22339                output_tail: "waiting for the shared build cache".to_owned(),
22340                duration_ms: 0,
22341                resource_blocked: true,
22342                ..Default::default()
22343            }],
22344            fix: None,
22345            blocking: 1,
22346            answered: 1,
22347            expected: 1,
22348            clean: false,
22349            verify_retried: false,
22350            e2e_deferred: false,
22351            e2e_defer_reason: None,
22352            progressed: false,
22353            vote_split: false,
22354            reconsideration: Vec::new(),
22355            verdict: None,
22356        }];
22357
22358        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
22359        let mut runner = Runner {
22360            state,
22361            roles: ResolvedRoles {
22362                implementers: Vec::new(),
22363                judges: Vec::new(),
22364                reviewers: Vec::new(),
22365                fixer: None,
22366                conductor: conductor(),
22367                implementer_roster: Vec::new(),
22368                judge_roster: Vec::new(),
22369                reviewer_roster: Vec::new(),
22370            },
22371            sem: Arc::new(Semaphore::new(1)),
22372            pause: Pause::new(),
22373            interrupt: Pause::new(),
22374        };
22375
22376        // The lease is still held throughout, so this reentry's own retry is
22377        // also contended — proving `review_loop` actually tried again (not
22378        // that it happened to succeed) is what the timestamp comparison
22379        // below is for.
22380        runner.review_loop().await.expect("review_loop");
22381
22382        assert_eq!(
22383            runner.state.reviews.len(),
22384            1,
22385            "no new round was started on top of the unresolved one: {:?}",
22386            runner.state.reviews
22387        );
22388        let last = &runner.state.reviews[0];
22389        assert_eq!(
22390            last.e2e_status(),
22391            E2eStatus::ResourceBlocked,
22392            "still contended: {last:?}"
22393        );
22394        assert!(
22395            last.verified_at.expect("still known") > first_attempt_at,
22396            "review_loop must have actually retried the check, not left it exactly as found"
22397        );
22398        assert_ne!(
22399            runner.state.status,
22400            RunStatus::Blocked,
22401            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
22402            runner.state.status
22403        );
22404
22405        held.release();
22406    }
22407
22408    #[tokio::test]
22409    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
22410        crate::run::pin_test_home();
22411        for status in [RunStatus::Blocked, RunStatus::Gating] {
22412            let mut runner = runner_at(status);
22413            runner.state.config.graph.land = true;
22414            runner.state.gate_ran = true;
22415            runner.state.merge = Some(MergeOutcome {
22416                mode: MergeMode::Pr,
22417                ok: false,
22418                detail: "the fixer produced no commit".into(),
22419                empty: false,
22420            });
22421            let url = "https://example.invalid/o/r/pull/1";
22422            runner.state.pr = Some(crate::run::PrRecord {
22423                url: url.into(),
22424                number: 1,
22425                state: "open".into(),
22426                checks: "red".into(),
22427                round: 1,
22428                rounds: 1,
22429                red_at_merge: Vec::new(),
22430            });
22431            runner.state.save().unwrap();
22432            // The nonexistent repository makes observation fail before a forge
22433            // command can run. We still must reach land, rather than silently
22434            // return from the graph with its old gate and merge records.
22435            runner.execute_graph().await.unwrap();
22436            assert_eq!(runner.state.status, RunStatus::Blocked);
22437            assert!(runner.state.land_sync_pending);
22438            assert!(runner.state.events.iter().any(|event|
22439                event.node == "land" && event.message == format!("watching {url}")));
22440            assert_eq!(
22441                runner.state.merge.as_ref().unwrap().detail,
22442                "the fixer produced no commit"
22443            );
22444        }
22445    }
22446
22447    #[tokio::test]
22448    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
22449        crate::run::pin_test_home();
22450        let tmp = tempfile::tempdir().expect("tempdir");
22451        let repo = tmp.path().join("repo");
22452        std::fs::create_dir_all(&repo).unwrap();
22453        init_repo(&repo);
22454
22455        let mut config = Config::default();
22456        config.merge.mode = MergeMode::Pr;
22457        config.graph.land = true;
22458        config.graph.land_approval = false;
22459
22460        let mut state = RunState::new(
22461            repo.clone(),
22462            "main".to_owned(),
22463            "deadbeef".to_owned(),
22464            "task".to_owned(),
22465            config,
22466        );
22467        state.candidates = vec![Candidate {
22468            index: 0,
22469            label: 'A',
22470            agent: "alpha".to_owned(),
22471            branch: "does-not-exist".to_owned(),
22472            worktree: repo.clone(),
22473            summary: String::new(),
22474            stat: String::new(),
22475            files: 0,
22476            commits: 0,
22477            empty: false,
22478            failed: None,
22479            verified_noop: None,
22480            duration_ms: 0,
22481            folded: false,
22482        }];
22483        state.tally = Some(Tally {
22484            first_choice: BTreeMap::from([('A', 1)]),
22485            borda: BTreeMap::new(),
22486            winner: 'A',
22487            rankings: 1,
22488            unanimous_initial: true,
22489            deliberated: false,
22490            changed_votes: 0,
22491            unanimous_final: true,
22492            tie_break: None,
22493            judges: 0,
22494            present: 0,
22495            quorum: 0,
22496            met_quorum: true,
22497            uncontested: Some("only candidate A produced a change".to_owned()),
22498        });
22499        state.reviews = vec![ReviewRound {
22500            round: 1,
22501            head: "deadbeef".to_owned(),
22502            verified_head: None,
22503            verified_at: None,
22504            reviews: Vec::new(),
22505            e2e: Vec::new(),
22506            fix: None,
22507            blocking: 0,
22508            answered: 0,
22509            expected: 0,
22510            clean: true,
22511            verify_retried: false,
22512            e2e_deferred: false,
22513            e2e_defer_reason: None,
22514            progressed: false,
22515            vote_split: false,
22516            reconsideration: Vec::new(),
22517            verdict: None,
22518        }];
22519        state.gate = vec![CommandOutcome {
22520            command: "test".to_owned(),
22521            code: Some(0),
22522            output_tail: String::new(),
22523            duration_ms: 0,
22524            resource_blocked: false,
22525            ..Default::default()
22526        }];
22527        state.gate_ran = true;
22528        // A first pass through `merge` already pushed and opened this pull
22529        // request; `status` is `Landing` because a previous call into `land`
22530        // parked or was interrupted before it reached a terminal outcome.
22531        state.status = RunStatus::Landing;
22532        state.merge = Some(MergeOutcome {
22533            mode: MergeMode::Pr,
22534            ok: true,
22535            detail: "https://example.invalid/x/y/pull/1".to_owned(),
22536            empty: false,
22537        });
22538
22539        // The Landing-resume shortcut calls `run_land` directly rather than
22540        // through `merge`, which is exactly the call site that used to skip
22541        // `settle_questions` - see the fixture below.
22542        ask_test_home();
22543        // A real resume loads a persisted run; driver ownership is checked
22544        // against that record before the Landing shortcut is entered.
22545        state.save().expect("save landing run");
22546        let store = ask::Questions::open();
22547        let q = ask_open_question(&store, &state.id);
22548
22549        let mut runner = Runner {
22550            state,
22551            roles: ResolvedRoles {
22552                implementers: Vec::new(),
22553                judges: Vec::new(),
22554                reviewers: Vec::new(),
22555                fixer: None,
22556                conductor: conductor(),
22557                implementer_roster: Vec::new(),
22558                judge_roster: Vec::new(),
22559                reviewer_roster: Vec::new(),
22560            },
22561            sem: Arc::new(Semaphore::new(1)),
22562            pause: Pause::new(),
22563            interrupt: Pause::new(),
22564        };
22565
22566        // `execute`, not `merge` directly: the Landing-resume shortcut lives
22567        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
22568        // exactly because `review_loop` would otherwise clobber the marker
22569        // first.
22570        runner.execute().await.expect("execute");
22571
22572        assert_eq!(
22573            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22574            Some("https://example.invalid/x/y/pull/1"),
22575            "reentry must not push again or open a second pull request over the \
22576             one `land` is already watching"
22577        );
22578        assert_ne!(
22579            runner.state.status,
22580            RunStatus::Landing,
22581            "land could not actually reach the fake pull request, so it must \
22582             have given up rather than left the run silently parked forever"
22583        );
22584        // `land` could not reach the fake pull request, so it gave up into
22585        // `Blocked` - still resumable, so the question must not have been
22586        // swept just because this branch now also calls `settle_questions`.
22587        assert_eq!(runner.state.status, RunStatus::Blocked);
22588        assert!(
22589            store.get(&q.id).unwrap().status.open(),
22590            "Blocked is still alive; settle_questions must have been a no-op here"
22591        );
22592    }
22593
22594    fn state_with_round(round: ReviewRound) -> RunState {
22595        let mut s = RunState::new(
22596            PathBuf::from("/repo"),
22597            "main".to_owned(),
22598            "abc1234".to_owned(),
22599            "add retries".to_owned(),
22600            Config::default(),
22601        );
22602        s.reviews = vec![round];
22603        s
22604    }
22605
22606    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
22607        crate::verdict::Finding {
22608            id: id.to_owned(),
22609            severity,
22610            file: None,
22611            line: None,
22612            title: title.to_owned(),
22613            detail: String::new(),
22614        }
22615    }
22616
22617    #[test]
22618    fn pr_body_names_open_findings_and_declined_ones() {
22619        let round = ReviewRound {
22620            round: 2,
22621            head: "deadbee".to_owned(),
22622            verified_head: None,
22623            verified_at: None,
22624            reviews: vec![ReviewRecord {
22625                attempts: 0,
22626                reviewer: 1,
22627                agent: "alpha".to_owned(),
22628                summary: String::new(),
22629                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
22630                vote: None,
22631                failed: None,
22632                duration_ms: 0,
22633            }],
22634            e2e: vec![CommandOutcome {
22635                command: "cargo test".to_owned(),
22636                code: Some(0),
22637                output_tail: String::new(),
22638                duration_ms: 0,
22639                resource_blocked: false,
22640                ..Default::default()
22641            }],
22642            verify_retried: false,
22643            e2e_deferred: false,
22644            e2e_defer_reason: None,
22645            fix: Some(FixRecord {
22646                agent: "alpha".to_owned(),
22647                addressed: Vec::new(),
22648                rejected: vec![crate::verdict::Rejection {
22649                    id: "R1-1-1".to_owned(),
22650                    why: "not reachable from any caller".to_owned(),
22651                }],
22652                notes: String::new(),
22653                committed: true,
22654                failed: None,
22655                duration_ms: 0,
22656                continuation: None,
22657            }),
22658            blocking: 0,
22659            answered: 1,
22660            expected: 1,
22661            clean: false,
22662            progressed: true,
22663            vote_split: false,
22664            reconsideration: Vec::new(),
22665            verdict: None,
22666        };
22667        let state = state_with_round(round);
22668        let body = pr_message(&state, 'A').body;
22669
22670        assert!(body.contains("add retries"), "the task must still be there");
22671        assert!(body.contains("R2-1-1"), "{body}");
22672        assert!(!body.contains("unused import"), "{body}");
22673        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
22674        assert!(
22675            !body.contains("not reachable from any caller"),
22676            "the reason it was declined: {body}"
22677        );
22678    }
22679
22680    #[test]
22681    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
22682        let round = ReviewRound {
22683            round: 1,
22684            head: "deadbee".to_owned(),
22685            verified_head: None,
22686            verified_at: None,
22687            reviews: vec![ReviewRecord {
22688                attempts: 0,
22689                reviewer: 1,
22690                agent: "alpha".to_owned(),
22691                summary: String::new(),
22692                findings: Vec::new(),
22693                vote: None,
22694                failed: None,
22695                duration_ms: 0,
22696            }],
22697            e2e: Vec::new(),
22698            verify_retried: false,
22699            e2e_deferred: false,
22700            e2e_defer_reason: None,
22701            fix: None,
22702            blocking: 0,
22703            answered: 1,
22704            expected: 1,
22705            clean: true,
22706            progressed: false,
22707            vote_split: false,
22708            reconsideration: Vec::new(),
22709            verdict: None,
22710        };
22711        let state = state_with_round(round);
22712        let body = pr_message(&state, 'A').body;
22713        assert!(!body.contains("Open review findings"), "{body}");
22714        assert!(!body.contains("Declined"), "{body}");
22715    }
22716
22717    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
22718        let mut state = RunState::new(
22719            PathBuf::from("/repo"),
22720            "main".to_owned(),
22721            "abc1234".to_owned(),
22722            instruction.to_owned(),
22723            Config::default(),
22724        );
22725        // These fixtures test execution flow, independent of host disk capacity.
22726        state.config.disk.min_free_bytes = 0;
22727        state.candidates.push(Candidate {
22728            index: 0,
22729            label: 'A',
22730            agent: "alpha".to_owned(),
22731            branch: "magi/x/A".to_owned(),
22732            worktree: PathBuf::from("/wt"),
22733            summary: summary.to_owned(),
22734            stat: String::new(),
22735            files: 1,
22736            commits: 1,
22737            empty: false,
22738            failed: None,
22739            verified_noop: None,
22740            folded: false,
22741            duration_ms: 0,
22742        });
22743        state
22744    }
22745
22746    fn review_state(subjects: &[&str]) -> RunState {
22747        let mut state = state_with_summary(
22748            "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",
22749            "",
22750        );
22751        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
22752        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
22753        state
22754    }
22755
22756    /// A branch rebased onto a main that moved past the recorded
22757    /// `base_commit` is titled from its own first commit, never main's.
22758    #[tokio::test]
22759    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
22760        ask_test_home();
22761        let tmp = tempfile::tempdir().unwrap();
22762        let repo = tmp.path().join("repo");
22763        std::fs::create_dir_all(&repo).unwrap();
22764        init_repo(&repo);
22765        let origin = tmp.path().join("origin.git");
22766        let g = |dir: &Path, args: &[&str]| {
22767            let out = std::process::Command::new("git")
22768                .args(args)
22769                .current_dir(dir)
22770                .quiet()
22771                .output()
22772                .expect("spawn git");
22773            assert!(
22774                out.status.success(),
22775                "git {args:?}: {}",
22776                String::from_utf8_lossy(&out.stderr)
22777            );
22778        };
22779        g(
22780            tmp.path(),
22781            &[
22782                "clone",
22783                "--bare",
22784                "-q",
22785                repo.to_str().unwrap(),
22786                origin.to_str().unwrap(),
22787            ],
22788        );
22789        g(
22790            &repo,
22791            &["remote", "add", "origin", origin.to_str().unwrap()],
22792        );
22793        let c1 = git::rev_parse(&repo, "main").await.unwrap();
22794
22795        // Main moves on; the branch is built on top of the new main.
22796        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
22797        g(&repo, &["add", "-A"]);
22798        g(
22799            &repo,
22800            &["commit", "-q", "-m", "chore(deps): update a crate"],
22801        );
22802        g(&repo, &["push", "-q", "origin", "main"]);
22803        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
22804        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22805        g(&repo, &["add", "-A"]);
22806        g(
22807            &repo,
22808            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
22809        );
22810        g(&repo, &["checkout", "-q", "main"]);
22811
22812        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
22813        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
22814        // Without a readable tracking ref the recorded base's merge base is used.
22815        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
22816        assert_eq!(fallback, c1);
22817
22818        let mut state = review_state(&[
22819            "chore(deps): update a crate",
22820            "fix(daemon): apply a chosen action",
22821        ]);
22822        state.repo = repo.clone();
22823        state.base_branch = "main".to_owned();
22824        state.base_commit = c1;
22825        refresh_reviewed_commits(&mut state, "feat/own").await;
22826        assert_eq!(
22827            state.reviewed_commits,
22828            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
22829        );
22830        assert_eq!(
22831            review_title(&state).as_deref(),
22832            Some("fix(daemon): apply a chosen action")
22833        );
22834        assert_eq!(
22835            leaked_subjects(&state, "feat/own").await,
22836            Some(vec!["chore(deps): update a crate".to_owned()])
22837        );
22838        // A stale tracking ref is still used when the fetch fails, but the
22839        // leak list is withheld.
22840        state.config.merge.remote = "nowhere".to_owned();
22841        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
22842    }
22843
22844    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
22845    /// with `origin/main` one commit behind it, and a summarizing agent that
22846    /// prints whatever `reply` holds.
22847    struct SummaryFixture {
22848        _tmp: tempfile::TempDir,
22849        repo: PathBuf,
22850        reply: PathBuf,
22851        runner: Runner,
22852    }
22853
22854    fn summary_fixture() -> SummaryFixture {
22855        ask_test_home();
22856        let tmp = tempfile::tempdir().unwrap();
22857        let repo = tmp.path().join("repo");
22858        std::fs::create_dir_all(&repo).unwrap();
22859        init_repo(&repo);
22860        let origin = tmp.path().join("origin.git");
22861        let g = |args: &[&str]| {
22862            let out = std::process::Command::new("git")
22863                .args(args)
22864                .current_dir(&repo)
22865                .quiet()
22866                .output()
22867                .expect("spawn git");
22868            assert!(
22869                out.status.success(),
22870                "git {args:?}: {}",
22871                String::from_utf8_lossy(&out.stderr)
22872            );
22873        };
22874        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
22875        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
22876        g(&["push", "-q", "origin", "main"]);
22877        g(&["checkout", "-q", "-b", "feat/own"]);
22878        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22879        g(&["add", "-A"]);
22880        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
22881        let reply = tmp.path().join("reply.txt");
22882        std::fs::write(
22883            &reply,
22884            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
22885        )
22886        .unwrap();
22887        let mut runner = runner_at(RunStatus::Gating);
22888        let mut state = review_state(&["feat(own): add the own file"]);
22889        state.repo = repo.clone();
22890        state.base_branch = "main".to_owned();
22891        state.candidates[0].branch = "feat/own".to_owned();
22892        state.candidates[0].worktree = repo.clone();
22893        let mut author = spec("alpha");
22894        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
22895        author
22896            .env
22897            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
22898        state.config.agents = vec![author];
22899        runner.state = state;
22900        SummaryFixture {
22901            _tmp: tmp,
22902            repo,
22903            reply,
22904            runner,
22905        }
22906    }
22907
22908    async fn posted(f: &mut SummaryFixture) -> PrMessage {
22909        let winner = f.runner.state.candidates[0].clone();
22910        f.runner
22911            .guarded_pr_message(&winner, None, true)
22912            .await
22913            .unwrap()
22914            .expect("an English description never parks")
22915    }
22916
22917    fn clean_round_with_minor_findings() -> ReviewRound {
22918        let mut round = passing_round(2, None);
22919        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
22920        round.reviews = vec![ReviewRecord {
22921            attempts: 0,
22922            reviewer: 1,
22923            agent: "alpha".into(),
22924            summary: "内部レビュー".into(),
22925            findings: vec![
22926                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
22927                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
22928            ],
22929            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
22930            failed: None,
22931            duration_ms: 0,
22932        }];
22933        round
22934    }
22935
22936    #[tokio::test]
22937    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
22938        for review_only in [false, true] {
22939            let mut f = summary_fixture();
22940            if !review_only {
22941                f.runner.state.candidates[0].agent = "alpha".into();
22942            }
22943            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
22944            assert!(f.runner.state.reviews[0].clean);
22945            assert!(f.runner.state.reviews[0].fix.is_none());
22946            assert!(f.runner.state.open_findings().is_empty());
22947            assert_eq!(
22948                crate::pr_outcome::required_finding_ids(&f.runner.state),
22949                ["R2-1-1", "R2-1-2"]
22950            );
22951            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22952            let evidence = crate::pr_outcome::summary_evidence(
22953                &f.runner.state,
22954                crate::pr_outcome::FinalHead::At(&head),
22955            );
22956            assert!(
22957                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
22958            );
22959            // The ordinary reply omits both IDs: no cached description is adopted.
22960            let omitted = posted(&mut f).await;
22961            assert!(omitted.body.contains("No description"));
22962            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
22963            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
22964            assert!(f.runner.state.change_summary.is_none());
22965            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();
22966            let described = posted(&mut f).await;
22967            assert!(described.body.contains("improve documentation for callers"));
22968            assert!(described.body.contains("remaining edge case"));
22969            assert!(described.body.contains("## Open review findings"));
22970            assert!(!described.body.contains("未修正"));
22971        }
22972    }
22973
22974    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
22975        let mut f = summary_fixture();
22976        if !review_only {
22977            f.runner.state.candidates[0].agent = "alpha".into();
22978        }
22979        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22980        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
22981        fixed
22982            .fix
22983            .as_mut()
22984            .unwrap()
22985            .rejected
22986            .push(crate::verdict::Rejection {
22987                id: "R1-1-1".into(),
22988                why: "呼び出されないコードのため辞退".into(),
22989            });
22990        let mut clean = clean_round_with_minor_findings();
22991        clean.verified_head = Some(head.clone());
22992        f.runner.state.reviews = vec![fixed, clean];
22993        ok_gate(&mut f.runner.state, Some(&head));
22994        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
22995        f.runner.state.config.agents.push(scripted("beta", reply));
22996        f.runner.state.config.roles.language_judge =
22997            Some(crate::config::AgentChoice::One("beta".into()));
22998        f
22999    }
23000
23001    #[tokio::test]
23002    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
23003        for review_only in [false, true] {
23004            let mut f = rewrite_fixture_with_findings(review_only,
23005                "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;
23006            let m = posted(&mut f).await;
23007            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23008            let expected =
23009                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
23010            assert!(m.body.contains(&expected));
23011            assert!(m.body.contains("## Review rounds"));
23012            assert!(
23013                m.body
23014                    .contains("Gate (`verify.gate`): passed on the final commit")
23015            );
23016            assert!(
23017                m.body
23018                    .contains("Tests (`verify.e2e`): passed on the final commit")
23019            );
23020            let c = f.runner.state.change_summary.as_ref().unwrap();
23021            assert!(
23022                m.body
23023                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
23024            );
23025            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23026            assert!(crate::pr_outcome::covers_required_findings(
23027                &f.runner.state,
23028                &m.body
23029            ));
23030            assert!(m.body.contains("documentation remains incomplete"));
23031            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
23032            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
23033            assert!(f.runner.state.github_text.is_none());
23034        }
23035    }
23036
23037    #[tokio::test]
23038    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
23039        for review_only in [false, true] {
23040            for reply in [
23041                "TITLE: fix: public description\nA short English description.",
23042                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
23043            ] {
23044                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
23045                let winner = f.runner.state.candidates[0].clone();
23046                let posted = f
23047                    .runner
23048                    .guarded_pr_message(&winner, None, true)
23049                    .await
23050                    .unwrap();
23051                assert!(posted.is_none());
23052                assert!(f.runner.state.parked);
23053                let withheld = f.runner.state.github_text.as_ref().unwrap();
23054                assert!(
23055                    withheld.rewrite.is_none(),
23056                    "an incomplete rewrite must not be selectable"
23057                );
23058                let q = ask::Questions::open()
23059                    .get(withheld.question.as_ref().unwrap())
23060                    .unwrap();
23061                assert!(
23062                    !q.choices
23063                        .contains(&crate::github_text::USE_REWRITE.to_owned())
23064                );
23065                assert!(
23066                    q.detail.contains("R1-1-1")
23067                        && q.detail.contains("R2-1-1")
23068                        && q.detail.contains("R2-1-2")
23069                );
23070            }
23071        }
23072    }
23073
23074    #[tokio::test]
23075    async fn japanese_reports_stay_local_in_both_public_run_modes() {
23076        for review_only in [false, true] {
23077            let mut f = summary_fixture();
23078            if !review_only {
23079                f.runner.state.candidates[0].agent = "alpha".into();
23080            }
23081            f.runner.state.instruction = "内部タスクの説明".into();
23082            f.runner.state.candidates[0].summary = "内部の候補報告".into();
23083            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23084            f.runner.state.reviews = vec![
23085                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
23086                round_with_notes(2, Some("二回目の内部修正報告です。")),
23087                passing_round(3, Some(&head)),
23088            ];
23089            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
23090            ok_gate(&mut f.runner.state, Some(&head));
23091            let captured = f.repo.join("public-prompt.txt");
23092            let author = &mut f.runner.state.config.agents[0];
23093            author.command = vec![
23094                "sh".into(),
23095                "-c".into(),
23096                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23097            ];
23098            author.env.insert(
23099                "PROMPT_FILE".into(),
23100                captured.to_string_lossy().into_owned(),
23101            );
23102            let m = posted(&mut f).await;
23103            assert!(m.body.contains("Adds `own.txt`"));
23104            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23105            assert!(m.body.contains("R1-1-1"));
23106            assert!(
23107                m.body
23108                    .contains("Gate (`verify.gate`): passed on the final commit")
23109            );
23110            assert!(
23111                m.body
23112                    .contains("Tests (`verify.e2e`): passed on the final commit")
23113            );
23114            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23115            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23116            let prompt = std::fs::read_to_string(captured).unwrap();
23117            assert!(prompt.contains(&format!(
23118                "git diff {} {head}",
23119                f.runner.state.change_summary.as_ref().unwrap().base
23120            )));
23121            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23122            assert_eq!(
23123                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23124                "二回目の内部修正報告です。"
23125            );
23126        }
23127    }
23128
23129    #[tokio::test]
23130    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23131        for review_only in [false, true] {
23132            let mut f = summary_fixture();
23133            if !review_only {
23134                f.runner.state.candidates[0].agent = "alpha".into();
23135            }
23136            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23137            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23138            std::fs::write(&f.reply, "no usable description").unwrap();
23139            let failed = posted(&mut f).await;
23140            assert!(
23141                failed
23142                    .body
23143                    .contains("No description of what this change does could be generated")
23144            );
23145            assert!(failed.body.is_ascii());
23146            assert!(f.runner.state.github_text.is_none());
23147            assert!(f.runner.state.change_summary.is_none());
23148            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23149            let evidence = crate::pr_outcome::summary_evidence(
23150                &f.runner.state,
23151                crate::pr_outcome::FinalHead::At(&head),
23152            );
23153            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23154            assert!(
23155                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23156                    .exists()
23157            );
23158            f.runner.state =
23159                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23160            std::fs::write(
23161                &f.reply,
23162                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23163            )
23164            .unwrap();
23165            let retried = posted(&mut f).await;
23166            assert!(retried.body.contains("Adds the committed own file."));
23167            assert_eq!(
23168                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23169                "日本語の修正報告"
23170            );
23171        }
23172    }
23173
23174    #[tokio::test]
23175    async fn same_head_verification_and_findings_invalidate_public_prose() {
23176        let mut f = summary_fixture();
23177        posted(&mut f).await;
23178        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23179        let original = f
23180            .runner
23181            .state
23182            .change_summary
23183            .as_ref()
23184            .unwrap()
23185            .evidence
23186            .clone();
23187        ok_gate(&mut f.runner.state, Some(&head));
23188        std::fs::write(
23189            &f.reply,
23190            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
23191        )
23192        .unwrap();
23193        let verified = posted(&mut f).await;
23194        assert!(verified.body.contains("now verified"));
23195        assert_ne!(
23196            f.runner.state.change_summary.as_ref().unwrap().evidence,
23197            original
23198        );
23199        let mut round = round_with_notes(1, Some("内部報告"));
23200        round.reviews.push(ReviewRecord {
23201            attempts: 0,
23202            reviewer: 1,
23203            agent: "alpha".into(),
23204            summary: "内部レビュー".into(),
23205            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
23206            vote: None,
23207            failed: None,
23208            duration_ms: 0,
23209        });
23210        round
23211            .fix
23212            .as_mut()
23213            .unwrap()
23214            .rejected
23215            .push(crate::verdict::Rejection {
23216                id: "R1-1-1".into(),
23217                why: "呼び出し元から到達できない".into(),
23218            });
23219        f.runner.state.reviews = vec![round];
23220        // A description omitting the required ID is unusable, even with a title.
23221        let omitted = posted(&mut f).await;
23222        assert!(omitted.body.contains("No description"));
23223        assert!(omitted.body.contains("R1-1-1"));
23224        assert!(!omitted.body.contains("到達"));
23225        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();
23226        let described = posted(&mut f).await;
23227        assert!(described.body.contains("unreachable from callers"));
23228        assert!(described.body.contains("R1-1-1"));
23229        assert!(!described.body.contains("到達"));
23230        let evidence = f
23231            .runner
23232            .state
23233            .change_summary
23234            .as_ref()
23235            .unwrap()
23236            .evidence
23237            .clone();
23238        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
23239        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
23240        assert!(posted(&mut f).await.body.contains("rationale updated"));
23241        assert_ne!(
23242            f.runner.state.change_summary.as_ref().unwrap().evidence,
23243            evidence
23244        );
23245        // Old serialized summaries have no evidence fingerprint and must regenerate.
23246        f.runner
23247            .state
23248            .change_summary
23249            .as_mut()
23250            .unwrap()
23251            .evidence
23252            .clear();
23253        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
23254        assert!(posted(&mut f).await.body.contains("current specification"));
23255    }
23256
23257    #[tokio::test]
23258    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
23259        let mut f = summary_fixture();
23260        let m = posted(&mut f).await;
23261        assert_eq!(m.title, "feat(own): add the own file");
23262        assert!(
23263            m.body
23264                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
23265            "{}",
23266            m.body
23267        );
23268        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
23269        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
23270        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23271        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23272        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
23273        let kept = f.runner.state.change_summary.as_ref().unwrap();
23274        assert_eq!(
23275            (kept.head.as_str(), kept.base.as_str()),
23276            (head.as_str(), base.as_str())
23277        );
23278        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
23279    }
23280
23281    #[tokio::test]
23282    async fn review_only_summary_receives_the_configured_github_language() {
23283        let mut f = summary_fixture();
23284        f.runner.state.config.graph.github_language = "ja".into();
23285        let captured = f.repo.join("summary-prompt.txt");
23286        let author = &mut f.runner.state.config.agents[0];
23287        author.command = vec![
23288            "sh".into(),
23289            "-c".into(),
23290            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23291        ];
23292        author.env.insert(
23293            "PROMPT_FILE".into(),
23294            captured.to_string_lossy().into_owned(),
23295        );
23296        std::fs::write(
23297            &f.reply,
23298            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
23299        )
23300        .unwrap();
23301        let m = posted(&mut f).await;
23302        let prompt = std::fs::read_to_string(captured).unwrap();
23303        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
23304        assert!(!prompt.contains("in English"));
23305        assert_eq!(m.title, "feat(own): ファイルを追加");
23306        assert!(m.body.contains("own.txt を追加します。"));
23307    }
23308
23309    #[tokio::test]
23310    async fn review_fixes_come_after_the_whole_change_summary() {
23311        let mut f = summary_fixture();
23312        f.runner.state.reviews = vec![
23313            round_with_notes(1, Some("handled the PATH case")),
23314            round_with_notes(2, None),
23315        ];
23316        let m = posted(&mut f).await;
23317        let summary = m.body.find("## Summary").expect("summary");
23318        let fixes = m.body.find("## Review rounds").expect("review rounds");
23319        assert!(summary < fixes, "{}", m.body);
23320        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
23321        assert!(m.body.contains("## Final verification"), "{}", m.body);
23322    }
23323
23324    #[tokio::test]
23325    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
23326        let mut f = summary_fixture();
23327        let first = posted(&mut f).await;
23328        let first_head = f.runner.state.change_summary.clone().unwrap().head;
23329        // The same head reuses the record: a different reply is not read.
23330        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
23331        let again = posted(&mut f).await;
23332        assert_eq!((again.title, again.body), (first.title, first.body));
23333
23334        let g = |args: &[&str]| {
23335            let out = std::process::Command::new("git")
23336                .args(args)
23337                .current_dir(&f.repo)
23338                .quiet()
23339                .output()
23340                .expect("spawn git");
23341            assert!(out.status.success(), "git {args:?}");
23342        };
23343        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
23344        g(&["add", "-A"]);
23345        g(&["commit", "-q", "-m", "fix(own): handle more"]);
23346        let second = posted(&mut f).await;
23347        let kept = f.runner.state.change_summary.clone().unwrap();
23348        assert_ne!(kept.head, first_head);
23349        assert!(second.body.contains("Not read yet."), "{}", second.body);
23350        assert!(!second.body.contains("so the first summary is read"));
23351        assert_eq!(second.title, "feat(own): other");
23352    }
23353
23354    #[tokio::test]
23355    async fn an_unavailable_summary_is_stated_and_never_invented() {
23356        let mut f = summary_fixture();
23357        std::fs::write(&f.reply, "no title line here").unwrap();
23358        let m = posted(&mut f).await;
23359        assert!(
23360            m.body
23361                .contains("No description of what this change does could be generated"),
23362            "{}",
23363            m.body
23364        );
23365        assert!(m.body.contains("internal reports remain in local records"));
23366        assert!(f.runner.state.change_summary.is_none());
23367        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
23368        // A preview asks nobody and claims nothing.
23369        let winner = f.runner.state.candidates[0].clone();
23370        let preview = f
23371            .runner
23372            .guarded_pr_message(&winner, None, false)
23373            .await
23374            .unwrap()
23375            .unwrap();
23376        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
23377    }
23378
23379    #[test]
23380    fn pr_message_review_single_commit_uses_its_subject() {
23381        let state = review_state(&["feat(nats): per-role user"]);
23382        let m = pr_message(&state, 'A');
23383        assert_eq!(m.title, "feat(nats): per-role user");
23384        assert!(!m.body.contains("Review the work already"), "{}", m.body);
23385        assert!(m.body.contains("## Commits under review"), "{}", m.body);
23386    }
23387
23388    #[test]
23389    fn pr_message_review_multi_commit_takes_the_oldest() {
23390        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
23391        let m = pr_message(&state, 'A');
23392        assert_eq!(m.title, "feat: the change");
23393        for s in ["feat: the change", "fix: typo", "fix: again"] {
23394            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
23395        }
23396    }
23397
23398    #[test]
23399    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
23400        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
23401            let mut state = review_state(&[first, "fix: later fixup"]);
23402            state.candidates[0].branch = "機能/ログイン".to_owned();
23403            let m = pr_message(&state, 'A');
23404            assert!(
23405                m.title.starts_with("chore: land candidate A of run"),
23406                "{}",
23407                m.title
23408            );
23409        }
23410    }
23411
23412    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
23413        BranchFacts {
23414            commits: commits
23415                .iter()
23416                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
23417                .collect(),
23418            stat: stat.to_owned(),
23419        }
23420    }
23421
23422    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
23423        let mut r = review_round(true, 0, 1, 1, true, true);
23424        r.round = round;
23425        r.fix = notes.map(|n| FixRecord {
23426            agent: "fixer".to_owned(),
23427            addressed: Vec::new(),
23428            rejected: Vec::new(),
23429            notes: n.to_owned(),
23430            committed: true,
23431            failed: None,
23432            duration_ms: 0,
23433            continuation: None,
23434        });
23435        r
23436    }
23437
23438    #[test]
23439    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
23440        let state = review_state(&["ignored"]);
23441        let f = facts(
23442            &[
23443                (
23444                    "fix(login): resolve PATH on macOS",
23445                    "Login shells skip rc files.",
23446                ),
23447                ("fix: address review", ""),
23448            ],
23449            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
23450        );
23451        let m = pr_message_with(&state, 'A', Some(&f));
23452        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
23453        assert!(
23454            m.body
23455                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
23456            "{}",
23457            m.body
23458        );
23459        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
23460        assert!(m.body.contains("## Diff stat"), "{}", m.body);
23461        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
23462        for banned in [
23463            "Review the work already",
23464            "no task statement",
23465            "Original task",
23466        ] {
23467            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
23468        }
23469        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
23470    }
23471
23472    #[test]
23473    fn pr_message_review_truncates_a_huge_first_commit_body() {
23474        let state = review_state(&["ignored"]);
23475        let f = facts(
23476            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
23477            "s",
23478        );
23479        let m = pr_message_with(&state, 'A', Some(&f));
23480        assert!(m.body.len() < 30_000, "{}", m.body.len());
23481        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
23482        assert!(
23483            m.body.contains("- ... 1 more commit(s)"),
23484            "{}",
23485            m.body.len()
23486        );
23487        assert!(m.body.ends_with("magi:candidate-a\n"));
23488    }
23489
23490    #[test]
23491    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
23492        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
23493        assert_eq!(m.title, "feat: x");
23494        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
23495        assert!(!m.body.contains("Diff stat"), "{}", m.body);
23496        assert!(!m.body.contains("no task statement"), "{}", m.body);
23497    }
23498
23499    #[test]
23500    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
23501        let mut state = review_state(&["日本語の件名"]);
23502        state.candidates[0].branch = "fix/macos-login-path".to_owned();
23503        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
23504        state.candidates[0].branch = "機能/ログイン".to_owned();
23505        assert!(
23506            pr_message(&state, 'A')
23507                .title
23508                .starts_with("chore: land candidate A")
23509        );
23510    }
23511
23512    #[test]
23513    fn pr_message_review_fixes_survive_a_clean_final_round() {
23514        let mut state = review_state(&["feat: x"]);
23515        state.reviews = vec![
23516            round_with_notes(1, Some("handled the PATH case")),
23517            round_with_notes(2, None),
23518        ];
23519        let body = pr_message(&state, 'A').body;
23520        assert!(
23521            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
23522            "{body}"
23523        );
23524        assert!(body.contains("### Round 1"), "{body}");
23525
23526        state.reviews = vec![
23527            round_with_notes(1, Some("first fix")),
23528            round_with_notes(2, Some("")),
23529            round_with_notes(3, Some("second fix")),
23530            round_with_notes(4, None),
23531        ];
23532        let body = pr_message(&state, 'A').body;
23533        assert!(
23534            body.contains("### Round 1") && !body.contains("first fix"),
23535            "{body}"
23536        );
23537        assert!(
23538            body.contains("### Round 3") && !body.contains("second fix"),
23539            "{body}"
23540        );
23541        assert!(body.contains("### Round 2"), "{body}");
23542    }
23543
23544    const FINAL: &str = "abcdef1234567890";
23545
23546    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
23547        let mut r = round_with_notes(round, None);
23548        r.verified_head = verified.map(str::to_owned);
23549        r
23550    }
23551
23552    fn ok_gate(state: &mut RunState, head: Option<&str>) {
23553        state.gate = vec![CommandOutcome {
23554            command: "gate".to_owned(),
23555            code: Some(0),
23556            output_tail: String::new(),
23557            duration_ms: 0,
23558            resource_blocked: false,
23559            ..Default::default()
23560        }];
23561        state.gate_ran = true;
23562        state.gate_head = head.map(str::to_owned);
23563    }
23564
23565    fn body_at(state: &RunState) -> String {
23566        pr_message_raw(
23567            state,
23568            'A',
23569            None,
23570            crate::pr_outcome::FinalHead::At(FINAL),
23571            ChangeNote::NotAsked,
23572        )
23573        .body
23574    }
23575
23576    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
23577
23578    #[test]
23579    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
23580        let mut state = review_state(&["feat: x"]);
23581        state.reviews = vec![
23582            round_with_notes(1, Some(SANDBOXED)),
23583            passing_round(2, Some(FINAL)),
23584        ];
23585        ok_gate(&mut state, Some(FINAL));
23586        let body = body_at(&state);
23587        assert!(!body.contains("Handled the PATH case."), "{body}");
23588        assert!(!body.contains("could not commit"), "{body}");
23589        assert!(!body.contains("could not run"), "{body}");
23590        assert!(
23591            body.contains("The fix is committed on the branch"),
23592            "{body}"
23593        );
23594        assert!(!body.contains("sandbox"), "{body}");
23595        assert!(
23596            body.contains("Tests (`verify.e2e`): passed on the final commit"),
23597            "{body}"
23598        );
23599        assert!(
23600            body.contains("Gate (`verify.gate`): passed on the final commit"),
23601            "{body}"
23602        );
23603        // The raw report is untouched in the record.
23604        assert!(
23605            state.reviews[0]
23606                .fix
23607                .as_ref()
23608                .unwrap()
23609                .notes
23610                .contains("could not commit")
23611        );
23612    }
23613
23614    #[test]
23615    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
23616        let mut state = review_state(&["feat: x"]);
23617        let mut r1 = round_with_notes(1, Some(SANDBOXED));
23618        r1.fix.as_mut().unwrap().committed = false;
23619        let mut r2 = passing_round(2, Some(FINAL));
23620        r2.e2e[0].code = Some(1);
23621        state.reviews = vec![r1, r2];
23622        let body = body_at(&state);
23623        assert!(!body.contains("could not commit"), "{body}");
23624        assert!(!body.contains("could not run"), "{body}");
23625        assert!(body.contains("This round produced no commit"), "{body}");
23626        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
23627        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
23628        assert!(!body.contains("passed"), "{body}");
23629    }
23630
23631    #[test]
23632    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
23633        let mut state = review_state(&["feat: x"]);
23634        state.reviews = vec![
23635            round_with_notes(1, Some(SANDBOXED)),
23636            passing_round(2, Some("0123456789abcdef")),
23637        ];
23638        ok_gate(&mut state, Some("0123456789abcdef"));
23639        let body = body_at(&state);
23640        assert!(!body.contains("HTTP tests could not run"), "{body}");
23641        // The commit claim is still settled by the structured record.
23642        assert!(!body.contains("could not commit"), "{body}");
23643        assert!(
23644            body.contains("passed on an earlier commit (`0123456`)"),
23645            "{body}"
23646        );
23647        assert!(!body.contains("passed on the final commit"), "{body}");
23648
23649        // A gate recorded before `gate_head` existed is "not recorded".
23650        ok_gate(&mut state, None);
23651        let body = body_at(&state);
23652        assert!(
23653            body.contains("passed on a commit that was not recorded"),
23654            "{body}"
23655        );
23656    }
23657
23658    #[test]
23659    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
23660        let state = state_with_summary(
23661            "add retries to the client",
23662            "TITLE: feat: retries\n\nDid it.",
23663        );
23664        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
23665        assert_eq!(m.title, "feat: retries");
23666        assert!(
23667            m.body.contains("<summary>Original task</summary>"),
23668            "{}",
23669            m.body
23670        );
23671        assert!(!m.body.contains("Commits under review"), "{}", m.body);
23672        assert!(
23673            m.body
23674                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
23675            "{}",
23676            m.body
23677        );
23678    }
23679
23680    #[test]
23681    fn pr_message_review_bounds_a_long_english_subject() {
23682        let long = format!("feat: {}", "word ".repeat(100));
23683        let m = pr_message(&review_state(&[&long]), 'A');
23684        assert!(m.title.starts_with("feat: word"), "{}", m.title);
23685        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23686    }
23687
23688    #[test]
23689    fn pr_message_implementation_run_is_unchanged_by_review_support() {
23690        let state = state_with_summary("add retries\n\ndetails", "- did some things");
23691        let m = pr_message(&state, 'A');
23692        assert_eq!(m.title, "add retries");
23693        assert!(m.body.contains("<summary>Original task</summary>"));
23694        assert!(!m.body.contains("Commits under review"));
23695        assert_eq!(landing_subject_source(&state), state.instruction);
23696    }
23697
23698    #[test]
23699    fn review_run_squash_subject_is_the_change_not_the_prompt() {
23700        let state = review_state(&["feat: the change", "fix: typo"]);
23701        let source = landing_subject_source(&state);
23702        assert_eq!(land::merge_subject("", &source), "feat: the change");
23703        assert_eq!(
23704            land::merge_subject("magi: candidate A (uncommitted work)", &source),
23705            "feat: the change"
23706        );
23707        // An operator's rename still wins.
23708        assert_eq!(
23709            land::merge_subject("feat: renamed by hand", &source),
23710            "feat: renamed by hand"
23711        );
23712        let blank = review_state(&["日本語"]);
23713        assert!(
23714            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
23715        );
23716    }
23717
23718    #[test]
23719    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
23720        let state = review_state(&["feat: the change"]);
23721        let source = landing_subject_source(&state);
23722        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
23723        assert_eq!(
23724            land::merge_subject(landing_title(&state, old), &source),
23725            "feat: the change"
23726        );
23727        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
23728        let task = state_with_summary("add retries", "");
23729        assert_eq!(landing_title(&task, old), old);
23730    }
23731
23732    #[test]
23733    fn pr_message_describes_the_change_not_the_task() {
23734        let state = state_with_summary(
23735            "今回やってほしいこと: results projector を直す",
23736            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
23737        );
23738        let m = pr_message(&state, 'A');
23739        assert_eq!(m.title, "fix(web): batch the runs list reads");
23740        assert!(
23741            m.body.starts_with("## Summary\n\n- reads run.json once"),
23742            "{}",
23743            m.body
23744        );
23745        assert!(!m.body.contains("TITLE:"), "{}", m.body);
23746        let task_at = m.body.find("今回やってほしいこと").unwrap();
23747        let details_at = m.body.find("<details>").unwrap();
23748        assert!(
23749            details_at < task_at,
23750            "the task lives inside <details>: {}",
23751            m.body
23752        );
23753        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
23754        assert!(m.body.contains("magi:candidate-a"));
23755    }
23756
23757    #[test]
23758    fn pr_message_falls_back_to_the_task_without_a_title_line() {
23759        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
23760        let m = pr_message(&state, 'A');
23761        assert_eq!(m.title, "add retries");
23762        assert!(
23763            m.body.contains("## Summary\n\n- did some things"),
23764            "{}",
23765            m.body
23766        );
23767
23768        let none = RunState::new(
23769            PathBuf::from("/repo"),
23770            "main".to_owned(),
23771            "abc1234".to_owned(),
23772            "add retries".to_owned(),
23773            Config::default(),
23774        );
23775        let m = pr_message(&none, 'A');
23776        assert_eq!(m.title, "add retries");
23777        assert!(!m.body.contains("## Summary"), "{}", m.body);
23778    }
23779
23780    #[test]
23781    fn pr_message_refuses_the_candidate_commit_subject() {
23782        for bad in [
23783            "TITLE: magi: candidate A (uncommitted work)",
23784            "TITLE: chore: stuff (uncommitted work)",
23785            "TITLE:   ",
23786        ] {
23787            let state = state_with_summary("add retries", bad);
23788            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
23789        }
23790    }
23791
23792    #[test]
23793    fn pr_message_bounds_a_very_long_task_and_title() {
23794        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
23795        let state = state_with_summary(&long, "- nothing");
23796        let m = pr_message(&state, 'A');
23797        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23798        assert!(!m.title.contains('\n'));
23799
23800        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
23801        let m = pr_message(&state, 'A');
23802        assert!(m.title.starts_with("feat: "));
23803        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23804        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
23805    }
23806
23807    fn long_title_of(instruction: &str) -> String {
23808        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
23809    }
23810
23811    #[test]
23812    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
23813        let first = "Make the landing path keep a readable title for long tasks";
23814        let line = format!(
23815            "{first}. {}",
23816            "And then keep going with more words ".repeat(20)
23817        );
23818        let t = long_title_of(&line);
23819        assert_eq!(t, first);
23820        assert!(!t.starts_with("chore: land"));
23821    }
23822
23823    #[test]
23824    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
23825        let line = "word ".repeat(200);
23826        let t = long_title_of(&line);
23827        assert!(t.ends_with("word..."), "{t}");
23828        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
23829    }
23830
23831    #[test]
23832    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
23833        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
23834            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
23835        }
23836    }
23837
23838    #[test]
23839    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
23840        let mut state = state_with_summary("再試行を追加する", "- nothing");
23841        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
23842        state.config.graph.github_language = "ja".into();
23843        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
23844    }
23845
23846    #[test]
23847    fn pr_message_title_limit_is_exact() {
23848        let at = "a".repeat(PR_TITLE_MAX);
23849        assert_eq!(long_title_of(&at), at);
23850        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
23851        assert!(over.ends_with("..."), "{over}");
23852        assert_eq!(over.chars().count(), PR_TITLE_MAX);
23853    }
23854
23855    #[test]
23856    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
23857        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
23858        let t = long_title_of(&line);
23859        assert!(t.ends_with("..."), "{t}");
23860        assert!(t.is_ascii(), "{t}");
23861    }
23862
23863    #[test]
23864    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
23865        let line = format!(
23866            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
23867            "plus more filler words ".repeat(20)
23868        );
23869        let t = long_title_of(&line);
23870        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
23871    }
23872
23873    #[test]
23874    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
23875        let line = format!("\n\n# {}", "title words ".repeat(40));
23876        let state = state_with_summary(&line, "- nothing");
23877        let m = pr_message(&state, 'A');
23878        assert!(m.title.starts_with("title words"), "{}", m.title);
23879        assert_eq!(
23880            land::merge_subject(&m.title, &landing_subject_source(&state)),
23881            m.title
23882        );
23883        // An operator's rename wins untouched.
23884        assert_eq!(
23885            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
23886            "feat: renamed by hand"
23887        );
23888    }
23889
23890    #[tokio::test]
23891    async fn github_text_rewrite_is_bounded_and_falls_back() {
23892        crate::run::pin_test_home();
23893        for (reply, accepted) in [
23894            (
23895                "TITLE: fix: retries\nAdd retries for failed requests.",
23896                true,
23897            ),
23898            (
23899                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
23900                false,
23901            ),
23902            (
23903                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
23904                true,
23905            ),
23906            (
23907                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
23908                true,
23909            ),
23910            (
23911                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
23912                true,
23913            ),
23914            (
23915                "TITLE: fix: retries\n日本語の説明です。 token=secret",
23916                false,
23917            ),
23918            ("TITLE: fix: retries\n", false),
23919        ] {
23920            let dir = tempfile::tempdir().unwrap();
23921            let mut runner = runner_at(RunStatus::Gating);
23922            runner.state = state_with_summary(
23923                "add retries",
23924                "TITLE: fix: retries\n日本語の説明を書きます。",
23925            );
23926            runner.state.repo = dir.path().to_owned();
23927            runner.state.candidates[0].worktree = dir.path().to_owned();
23928            let mut author = spec("alpha");
23929            author.command = vec![
23930                "sh".into(),
23931                "-c".into(),
23932                "printf '%s' \"$REWRITE_REPLY\"".into(),
23933            ];
23934            author.env.insert("REWRITE_REPLY".into(), reply.into());
23935            runner.state.config.agents = vec![author];
23936            seed_public_summary(&mut runner);
23937            let winner = runner.state.candidates[0].clone();
23938            let first = runner
23939                .guarded_pr_message(&winner, None, true)
23940                .await
23941                .unwrap();
23942            let message = if accepted {
23943                first.expect("a passing rewrite never asks")
23944            } else {
23945                // Withheld: the run parks on a question and posts nothing yet.
23946                assert!(first.is_none());
23947                assert!(runner.state.parked);
23948                let store = ask::Questions::open();
23949                let asked: Vec<_> = store
23950                    .list()
23951                    .into_iter()
23952                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23953                    .collect();
23954                assert_eq!(asked.len(), 1);
23955                assert!(!asked[0].detail.contains("secret"));
23956                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
23957                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
23958                assert_eq!(
23959                    asked[0]
23960                        .choices
23961                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
23962                    rewrite.is_some()
23963                );
23964                // Silence: the question lapses and the neutral text is used,
23965                // without a second rewrite call or a second question.
23966                store
23967                    .update(&asked[0].id, |q| {
23968                        q.abandon("test");
23969                        Ok(())
23970                    })
23971                    .unwrap();
23972                let again = runner
23973                    .guarded_pr_message(&winner, None, true)
23974                    .await
23975                    .unwrap()
23976                    .expect("an abandoned question falls back");
23977                let n = store
23978                    .list()
23979                    .into_iter()
23980                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23981                    .count();
23982                assert_eq!(n, 1, "asked once per rejected text");
23983                again
23984            };
23985            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
23986            assert!(!message.body.contains("secret"));
23987            assert!(!message.body.contains("prefix"));
23988            assert!(!message.title.contains("secret"));
23989            assert_eq!(
23990                message.body.contains("Add retries for failed requests."),
23991                accepted
23992            );
23993            assert_eq!(
23994                runner.state.seats["github-text-rewrite"].turns, 1,
23995                "only one rewrite invocation"
23996            );
23997            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
23998            if accepted {
23999                assert!(runner.state.github_text.is_none());
24000                assert!(!runner.state.parked);
24001                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
24002                assert!(message.body.contains("## Final verification"));
24003                assert!(message.body.contains("Evidence: final diff"));
24004                assert!(
24005                    message
24006                        .body
24007                        .contains(&format!("magi:run/{}", runner.state.id))
24008                );
24009            }
24010            if !accepted {
24011                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24012                assert!(
24013                    message
24014                        .body
24015                        .contains(&format!("magi:run/{}", runner.state.id))
24016                );
24017            }
24018        }
24019    }
24020
24021    fn scripted(id: &str, reply: &str) -> AgentSpec {
24022        let mut a = spec(id);
24023        a.command = vec![
24024            "sh".into(),
24025            "-c".into(),
24026            "printf '%s' \"$REWRITE_REPLY\"".into(),
24027        ];
24028        a.env.insert("REWRITE_REPLY".into(), reply.into());
24029        a
24030    }
24031
24032    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
24033    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
24034
24035    /// Gate tests inject generated public output, not internal reports.
24036    fn seed_public_summary(runner: &mut Runner) {
24037        let repo = &runner.state.repo;
24038        let g = |args: &[&str]| {
24039            let out = std::process::Command::new("git")
24040                .args(args)
24041                .current_dir(repo)
24042                .quiet()
24043                .output()
24044                .unwrap();
24045            assert!(out.status.success(), "git {args:?}");
24046            String::from_utf8_lossy(&out.stdout).trim().to_owned()
24047        };
24048        g(&["init", "-q", "-b", "main"]);
24049        g(&[
24050            "-c",
24051            "user.name=Test",
24052            "-c",
24053            "user.email=test@example.invalid",
24054            "commit",
24055            "-q",
24056            "--allow-empty",
24057            "-m",
24058            "feat: fixture",
24059        ]);
24060        let head = g(&["rev-parse", "HEAD"]);
24061        g(&["update-ref", "refs/remotes/origin/main", &head]);
24062        let evidence = crate::pr_outcome::summary_evidence(
24063            &runner.state,
24064            crate::pr_outcome::FinalHead::At(&head),
24065        );
24066        let generated = &runner.state.candidates[0].summary;
24067        runner.state.change_summary = Some(crate::run::ChangeSummary {
24068            base: head.clone(),
24069            head,
24070            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
24071            title: summary_title(generated).unwrap(),
24072            body: summary_without_title(generated),
24073        });
24074    }
24075
24076    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
24077        let mut runner = runner_at(RunStatus::Gating);
24078        runner.state = state_with_summary("add retries", JA_SUMMARY);
24079        if review_only {
24080            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24081        }
24082        runner.state.repo = dir.to_owned();
24083        runner.state.candidates[0].worktree = dir.to_owned();
24084        runner.state.config.agents = agents;
24085        seed_public_summary(&mut runner);
24086        runner
24087    }
24088
24089    fn gate_questions(runner: &Runner) -> usize {
24090        ask::Questions::open()
24091            .list()
24092            .into_iter()
24093            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24094            .count()
24095    }
24096
24097    #[tokio::test]
24098    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24099        crate::run::pin_test_home();
24100        let dir = tempfile::tempdir().unwrap();
24101        let mut runner = rewrite_runner(
24102            dir.path(),
24103            true,
24104            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24105        );
24106        runner.state.config.roles.language_judge =
24107            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24108        let winner = runner.state.candidates[0].clone();
24109        let msg = runner
24110            .guarded_pr_message(&winner, None, true)
24111            .await
24112            .unwrap()
24113            .expect("an English rewrite posts without asking");
24114        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24115        assert!(msg.body.contains("<details>kept</details>"));
24116        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24117        assert_eq!(gate_questions(&runner), 0);
24118        assert!(runner.state.github_text.is_none());
24119        assert!(!runner.state.seats.contains_key("impl-A"));
24120        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24121    }
24122
24123    #[tokio::test]
24124    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24125        crate::run::pin_test_home();
24126        let dir = tempfile::tempdir().unwrap();
24127        let mut runner = rewrite_runner(
24128            dir.path(),
24129            false,
24130            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24131        );
24132        runner.state.config.roles.language_judge =
24133            Some(crate::config::AgentChoice::One("beta".into()));
24134        runner.state.seats.insert(
24135            "impl-A".into(),
24136            SeatState::new("impl-A", "alpha", runner.state.seed),
24137        );
24138        let winner = runner.state.candidates[0].clone();
24139        let msg = runner
24140            .guarded_pr_message(&winner, None, true)
24141            .await
24142            .unwrap()
24143            .expect("rewritten");
24144        assert!(msg.body.contains("<details>kept</details>"));
24145        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24146        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24147        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24148    }
24149
24150    #[tokio::test]
24151    async fn rewrite_reuses_a_resumable_implementer_session() {
24152        crate::run::pin_test_home();
24153        let dir = tempfile::tempdir().unwrap();
24154        let mut runner = rewrite_runner(
24155            dir.path(),
24156            false,
24157            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24158        );
24159        runner.state.config.roles.language_judge =
24160            Some(crate::config::AgentChoice::One("beta".into()));
24161        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24162        seat.turns = 1;
24163        runner.state.seats.insert("impl-A".into(), seat);
24164        let winner = runner.state.candidates[0].clone();
24165        runner
24166            .guarded_pr_message(&winner, None, true)
24167            .await
24168            .unwrap()
24169            .expect("rewritten");
24170        assert_eq!(runner.state.seats["impl-A"].turns, 2);
24171        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
24172    }
24173
24174    #[tokio::test]
24175    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
24176        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
24177        // session, was out of quota, and nothing else was asked.
24178        crate::run::pin_test_home();
24179        let dir = tempfile::tempdir().unwrap();
24180        let mut exhausted = spec("alpha");
24181        exhausted.command = vec!["false".into()];
24182        let mut runner = rewrite_runner(
24183            dir.path(),
24184            false,
24185            vec![exhausted, scripted("beta", EN_REWRITE)],
24186        );
24187        // The implementer's own agent is in the role too: it is not asked twice.
24188        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24189            "alpha".into(),
24190            "beta".into(),
24191        ]));
24192        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24193        seat.turns = 1;
24194        runner.state.seats.insert("impl-A".into(), seat);
24195        let winner = runner.state.candidates[0].clone();
24196        let msg = runner
24197            .guarded_pr_message(&winner, None, true)
24198            .await
24199            .unwrap()
24200            .expect("the role rewrites after the implementer fails");
24201        assert!(msg.body.contains("`src/net.rs`"));
24202        assert_eq!(
24203            runner.state.seats["impl-A"].turns, 2,
24204            "the implementer was tried once"
24205        );
24206        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24207        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24208    }
24209
24210    #[tokio::test]
24211    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
24212        crate::run::pin_test_home();
24213        let dir = tempfile::tempdir().unwrap();
24214        let mut broken = spec("bad");
24215        broken.command = vec!["false".into()];
24216        let mut runner = rewrite_runner(
24217            dir.path(),
24218            true,
24219            vec![
24220                broken,
24221                scripted("noformat", "Add retries."),
24222                scripted("good", EN_REWRITE),
24223            ],
24224        );
24225        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24226            "bad".into(),
24227            "noformat".into(),
24228            "good".into(),
24229        ]));
24230        let winner = runner.state.candidates[0].clone();
24231        let msg = runner
24232            .guarded_pr_message(&winner, None, true)
24233            .await
24234            .unwrap()
24235            .expect("the third agent rewrites");
24236        assert!(msg.body.contains("`src/net.rs`"));
24237        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
24238        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
24239    }
24240
24241    #[tokio::test]
24242    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
24243        crate::run::pin_test_home();
24244        // (agents, role): still Japanese; no TITLE; nothing resolvable.
24245        for (agents, role, saved) in [
24246            (
24247                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
24248                Some("beta"),
24249                true,
24250            ),
24251            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
24252            (Vec::new(), None, false),
24253        ] {
24254            let dir = tempfile::tempdir().unwrap();
24255            let mut runner = rewrite_runner(dir.path(), true, agents);
24256            runner.state.config.roles.language_judge =
24257                role.map(|r| crate::config::AgentChoice::One(r.into()));
24258            let winner = runner.state.candidates[0].clone();
24259            let first = runner
24260                .guarded_pr_message(&winner, None, true)
24261                .await
24262                .unwrap();
24263            assert!(first.is_none(), "withheld text parks the run");
24264            assert!(runner.state.parked);
24265            assert_eq!(gate_questions(&runner), 1);
24266            let g = runner.state.github_text.as_ref().unwrap();
24267            assert_eq!(g.rewrite.is_some(), saved);
24268            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
24269        }
24270    }
24271
24272    #[tokio::test]
24273    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
24274        crate::run::pin_test_home();
24275        let dir = tempfile::tempdir().unwrap();
24276        let mut runner = runner_at(RunStatus::Gating);
24277        runner.state =
24278            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
24279        runner.state.repo = dir.path().to_owned();
24280        runner.state.candidates[0].worktree = dir.path().to_owned();
24281        let mut author = spec("alpha");
24282        author.command = vec![
24283            "sh".into(),
24284            "-c".into(),
24285            "printf '%s' \"$REWRITE_REPLY\"".into(),
24286        ];
24287        author.env.insert(
24288            "REWRITE_REPLY".into(),
24289            format!(
24290                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
24291                "English sentence. ".repeat(600)
24292            ),
24293        );
24294        runner.state.config.agents = vec![author];
24295        seed_public_summary(&mut runner);
24296        let winner = runner.state.candidates[0].clone();
24297        assert!(
24298            runner
24299                .guarded_pr_message(&winner, None, true)
24300                .await
24301                .unwrap()
24302                .is_none()
24303        );
24304        let record = runner.state.github_text.clone().unwrap();
24305        let rewrite = record.rewrite.clone().unwrap();
24306        assert_eq!(rewrite.failed, ["body-language"]);
24307        assert!(
24308            rewrite
24309                .body
24310                .ends_with(&format!("magi:run/{}", runner.state.id))
24311        );
24312        let store = ask::Questions::open();
24313        let q = store.get(record.question.as_ref().unwrap()).unwrap();
24314        assert!(
24315            q.choices
24316                .contains(&crate::github_text::USE_REWRITE.to_owned())
24317        );
24318        for label in [
24319            "ORIGINAL",
24320            "FALLBACK",
24321            "REWRITE",
24322            "Rules still failed: body-language",
24323            "truncated",
24324        ] {
24325            assert!(q.detail.contains(label), "{label}");
24326        }
24327        let artifact = std::fs::read_to_string(crate::run::artifact_path(
24328            &runner.state,
24329            &crate::github_text::artifact_name(&record.fingerprint),
24330        ))
24331        .unwrap();
24332        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
24333        // Restart from serialized state, then retry after a bad owner title.
24334        runner.state =
24335            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
24336        store
24337            .update(&q.id, |q| {
24338                q.say("まだ日本語")?;
24339                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
24340            })
24341            .unwrap();
24342        assert!(
24343            runner
24344                .guarded_pr_message(&winner, None, true)
24345                .await
24346                .unwrap()
24347                .is_none()
24348        );
24349        let retry = runner.state.github_text.as_ref().unwrap();
24350        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
24351        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
24352        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
24353        assert!(
24354            q.posting_comparison
24355                .as_ref()
24356                .unwrap()
24357                .matches_detail(&q.detail)
24358        );
24359        store
24360            .update(&q.id, |q| {
24361                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24362            })
24363            .unwrap();
24364        let message = runner
24365            .guarded_pr_message(&winner, None, true)
24366            .await
24367            .unwrap()
24368            .unwrap();
24369        assert_eq!(message.title, rewrite.title);
24370        assert_eq!(message.body, rewrite.body);
24371        assert_eq!(
24372            runner.state.github_text.as_ref().unwrap().choice,
24373            Some(GithubTextChoice::Rewrite)
24374        );
24375        let again = runner
24376            .guarded_pr_message(&winner, None, true)
24377            .await
24378            .unwrap()
24379            .unwrap();
24380        assert_eq!(again.title, message.title);
24381        assert_eq!(again.body, message.body);
24382        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24383        assert!(
24384            !runner
24385                .state
24386                .events
24387                .iter()
24388                .any(|e| e.message.contains(&rewrite.title)
24389                    || e.message.contains("English sentence."))
24390        );
24391    }
24392
24393    #[tokio::test]
24394    async fn historical_posting_reply_never_expires_into_fallback() {
24395        crate::run::pin_test_home();
24396        let dir = tempfile::tempdir().unwrap();
24397        let mut runner = runner_at(RunStatus::Gating);
24398        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24399        runner.state.repo = dir.path().to_owned();
24400        runner.state.candidates[0].worktree = dir.path().to_owned();
24401        seed_public_summary(&mut runner);
24402        let winner = runner.state.candidates[0].clone();
24403        assert!(
24404            runner
24405                .guarded_pr_message(&winner, None, true)
24406                .await
24407                .unwrap()
24408                .is_none()
24409        );
24410        let id = runner
24411            .state
24412            .github_text
24413            .as_ref()
24414            .unwrap()
24415            .question
24416            .clone()
24417            .unwrap();
24418        let store = ask::Questions::open();
24419        let mut q = store.get(&id).unwrap();
24420        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
24421        q.answer(ask::Answer::Choice(
24422            crate::github_text::POST_ORIGINAL.into(),
24423        ))
24424        .unwrap();
24425        q.answer_delivered = true;
24426        store.put(&mut q).unwrap();
24427        let source = std::fs::read(store.path_of(&id)).unwrap();
24428        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
24429        std::fs::create_dir_all(&migration).unwrap();
24430        std::fs::write(
24431            migration.join("state.json"),
24432            serde_json::to_vec(&serde_json::json!({
24433                "schema": 1, "sources": [id], "pending": [id]
24434            }))
24435            .unwrap(),
24436        )
24437        .unwrap();
24438        for _ in 0..2 {
24439            assert!(
24440                runner
24441                    .guarded_pr_message(&winner, None, true)
24442                    .await
24443                    .unwrap()
24444                    .is_none()
24445            );
24446            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24447            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24448        }
24449        let home = crate::run::home();
24450        crate::task_chat::sweep(
24451            &crate::queue::Queue::at(home.join("queue")),
24452            &crate::talk::Talks::at(home.join("talks")),
24453            &store,
24454            &home,
24455        );
24456        let outbox = crate::task_inquiry::Outbox::at(&home);
24457        outbox
24458            .update_decision(&id, |d| {
24459                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
24460                d.source_answer_at = q.answered_at;
24461                Ok(true)
24462            })
24463            .unwrap();
24464        outbox
24465            .settle(
24466                &id,
24467                "owner-chat",
24468                "Owner confirms no publication remains necessary",
24469                None,
24470            )
24471            .unwrap();
24472        assert!(
24473            runner
24474                .guarded_pr_message(&winner, None, true)
24475                .await
24476                .unwrap()
24477                .is_none()
24478        );
24479        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24480        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24481    }
24482
24483    #[tokio::test]
24484    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
24485        crate::run::pin_test_home();
24486        let dir = tempfile::tempdir().unwrap();
24487        let mut runner = runner_at(RunStatus::Gating);
24488        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24489        runner.state.repo = dir.path().to_owned();
24490        runner.state.candidates[0].worktree = dir.path().to_owned();
24491        seed_public_summary(&mut runner);
24492        let winner = runner.state.candidates[0].clone();
24493        assert!(
24494            runner
24495                .guarded_pr_message(&winner, None, true)
24496                .await
24497                .unwrap()
24498                .is_none()
24499        );
24500        let record = runner.state.github_text.as_ref().unwrap();
24501        assert!(record.rewrite.is_none());
24502        // Records written before the additive field deserialize with no rewrite.
24503        let mut old = serde_json::to_value(record).unwrap();
24504        old.as_object_mut().unwrap().remove("rewrite");
24505        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
24506        assert!(old.rewrite.is_none());
24507        let id = record.question.clone().unwrap();
24508        ask::Questions::open()
24509            .update(&id, |q| {
24510                q.choices.push(crate::github_text::USE_REWRITE.into());
24511                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24512            })
24513            .unwrap();
24514        let message = runner
24515            .guarded_pr_message(&winner, None, true)
24516            .await
24517            .unwrap()
24518            .unwrap();
24519        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24520        assert_eq!(
24521            runner.state.github_text.as_ref().unwrap().choice,
24522            Some(GithubTextChoice::Fallback)
24523        );
24524    }
24525
24526    #[tokio::test]
24527    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
24528        crate::run::pin_test_home();
24529        let dir = tempfile::tempdir().unwrap();
24530        let mut runner = runner_at(RunStatus::Gating);
24531        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
24532        runner.state.repo = dir.path().to_owned();
24533        runner.state.candidates[0].worktree = dir.path().to_owned();
24534        seed_public_summary(&mut runner);
24535        let winner = runner.state.candidates[0].clone();
24536        assert!(
24537            runner
24538                .guarded_pr_message(&winner, None, true)
24539                .await
24540                .unwrap()
24541                .is_none()
24542        );
24543        let store = ask::Questions::open();
24544        let find = |run: &str| {
24545            store
24546                .list()
24547                .into_iter()
24548                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
24549                .unwrap()
24550        };
24551        let run = runner.state.id.clone();
24552        let q = find(&run);
24553        let fp = runner
24554            .state
24555            .github_text
24556            .as_ref()
24557            .unwrap()
24558            .fingerprint
24559            .clone();
24560        let name = crate::github_text::artifact_name(&fp);
24561        let path = crate::run::artifact_path(&runner.state, &name);
24562        assert!(q.detail.contains(&path.display().to_string()));
24563        assert!(q.detail.contains("title-language: title"));
24564        let saved = std::fs::read_to_string(&path).expect("artifact written");
24565        assert!(saved.contains("日本語のタイトル"));
24566        assert!(q.cwd.is_none());
24567        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
24568        // A bad replacement is refused and asked about once more.
24569        let say = |id: &str, text: &str, choice: &str| {
24570            store
24571                .update(id, |q| {
24572                    q.thread.push(ask::Turn {
24573                        who: ask::Who::Operator,
24574                        body: text.to_owned(),
24575                        at: jiff::Timestamp::now(),
24576                        note: None,
24577                    });
24578                    q.answer(ask::Answer::Choice(choice.to_owned()))
24579                })
24580                .unwrap();
24581        };
24582        say(&q.id, "まだ日本語", "use my text");
24583        assert!(
24584            runner
24585                .guarded_pr_message(&winner, None, true)
24586                .await
24587                .unwrap()
24588                .is_none()
24589        );
24590        let second = find(&run);
24591        assert_ne!(second.id, q.id);
24592        assert!(second.detail.contains("did not pass"));
24593        // The retry still compares the original text; the rejected
24594        // replacement is named by category only.
24595        assert!(second.detail.contains("日本語のタイトル"));
24596        assert!(!second.detail.contains("まだ日本語"));
24597        assert!(second.detail.contains(&path.display().to_string()));
24598        say(&second.id, "fix: retry failed requests", "use my text");
24599        let message = runner
24600            .guarded_pr_message(&winner, None, true)
24601            .await
24602            .unwrap()
24603            .expect("a vetted replacement is posted");
24604        assert_eq!(message.title, "fix: retry failed requests");
24605        assert_eq!(
24606            runner
24607                .state
24608                .github_text
24609                .as_ref()
24610                .unwrap()
24611                .chosen_title
24612                .as_deref(),
24613            Some("fix: retry failed requests")
24614        );
24615        assert!(runner.state.github_text.as_ref().unwrap().resolved);
24616        // Resumed again: the saved decision is applied, nothing is re-asked.
24617        let again = runner
24618            .guarded_pr_message(&winner, None, true)
24619            .await
24620            .unwrap()
24621            .unwrap();
24622        assert_eq!(again.title, message.title);
24623        assert_eq!(
24624            store
24625                .list()
24626                .into_iter()
24627                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
24628                .count(),
24629            2
24630        );
24631    }
24632
24633    #[test]
24634    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
24635        // What magi itself writes stays English under any configured language,
24636        // so a future localisation of these headings fails here. (The agents'
24637        // own text is also checked by the posting gate.)
24638        let mut state = state_with_summary(
24639            "add retries",
24640            "TITLE: fix(web): batch reads\n- reads run.json once",
24641        );
24642        state.config.graph.language = "ja".to_owned();
24643        let m = pr_message(&state, 'A');
24644        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
24645        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
24646
24647        // The task is the operator's own text: it goes in untouched, and the
24648        // fallback title (no summary) may be in its language too.
24649        let task = "今回やってほしいこと: results projector を直す";
24650        let mut state = state_with_summary(task, "- no title line");
24651        state.config.graph.language = "ja".to_owned();
24652        let m = pr_message(&state, 'A');
24653        assert_eq!(
24654            m.title,
24655            format!("chore: land candidate A of run {}", state.id)
24656        );
24657        assert!(
24658            m.body.contains(&format!(
24659                "<summary>Original task</summary>\n\n{task}\n\n</details>"
24660            )),
24661            "{}",
24662            m.body
24663        );
24664    }
24665
24666    #[test]
24667    fn pr_message_scrubs_home_paths_and_addresses() {
24668        let state = state_with_summary(
24669            "fix it in /Users/someone/src/x",
24670            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
24671        );
24672        let m = pr_message(&state, 'A');
24673        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
24674            assert!(!m.body.contains(leak), "{}", m.body);
24675        }
24676        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
24677    }
24678
24679    #[test]
24680    fn pr_message_survives_a_task_that_closes_details() {
24681        let state = state_with_summary("a </details> b", "TITLE: fix: x");
24682        let m = pr_message(&state, 'A');
24683        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
24684    }
24685
24686    #[test]
24687    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
24688        let cmd = manual_merge_command(
24689            MergeStyle::Squash,
24690            Path::new("/repo"),
24691            "b",
24692            "fix: \"quoted\" $(x) `y`\n\nbody",
24693        );
24694        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
24695    }
24696
24697    #[test]
24698    fn manual_merge_command_matches_the_configured_style() {
24699        let repo = Path::new("/repo");
24700        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
24701
24702        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
24703        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
24704
24705        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
24706        assert_eq!(
24707            squash,
24708            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
24709             \"Merge magi run 0832 (candidate A)\""
24710        );
24711
24712        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
24713        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
24714    }
24715
24716    #[test]
24717    fn a_nudge_gets_a_quarter_of_the_budget() {
24718        // The judge and implement budgets magi ships with.
24719        assert_eq!(retry_budget(secs(1200), true), secs(300));
24720        assert_eq!(retry_budget(secs(3600), true), secs(900));
24721    }
24722
24723    #[test]
24724    fn a_resent_prompt_keeps_the_whole_budget() {
24725        // The seat kept no context, so the retry is the original job again and
24726        // shortening it would only guarantee a second failure.
24727        assert_eq!(retry_budget(secs(1200), false), secs(1200));
24728        assert_eq!(retry_budget(secs(60), false), secs(60));
24729    }
24730
24731    #[test]
24732    fn the_floor_never_exceeds_the_original_budget() {
24733        // A short configured timeout must not be *raised* by the floor: the
24734        // operator asked for a bound, and a retry may not outlast the attempt
24735        // it is retrying.
24736        assert_eq!(retry_budget(secs(60), true), secs(60));
24737        assert_eq!(retry_budget(secs(480), true), secs(120));
24738        assert_eq!(retry_budget(secs(0), true), secs(0));
24739    }
24740
24741    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
24742        agent::CommandEvidence {
24743            id: "item1".to_owned(),
24744            description: "cargo test".to_owned(),
24745            exit_code,
24746            result_summary: String::new(),
24747            source: "codex".to_owned(),
24748        }
24749    }
24750
24751    #[test]
24752    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
24753        // No evidence is not the same fact as unconfirmed evidence: a
24754        // backend with no adapter, or a reply that ran no commands at all,
24755        // must not be misread as carrying a dangling job.
24756        assert!(!has_unconfirmed_command(&[]));
24757    }
24758
24759    #[test]
24760    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
24761        // Deliberately not a check on the exit code's *value*: a fixer
24762        // legitimately runs something that fails mid-iteration before it
24763        // succeeds, and that must never by itself reopen a valid report.
24764        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
24765        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
24766        assert!(!has_unconfirmed_command(&[
24767            evidence(Some(0)),
24768            evidence(Some(101))
24769        ]));
24770    }
24771
24772    #[test]
24773    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
24774        assert!(has_unconfirmed_command(&[
24775            evidence(Some(0)),
24776            evidence(None)
24777        ]));
24778    }
24779
24780    #[test]
24781    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
24782        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24783        assert_eq!(
24784            verified_noop_claim(true, &[], text).as_deref(),
24785            Some("already fixed by b32cfc4, on main.")
24786        );
24787    }
24788
24789    #[test]
24790    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
24791        // A timeout or a bad exit code reads as the ordinary loss it is,
24792        // whatever the reply's own prose claims.
24793        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24794        assert!(verified_noop_claim(false, &[], text).is_none());
24795    }
24796
24797    #[test]
24798    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
24799        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24800        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
24801        // A confirmed command alongside the marker is fine.
24802        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
24803    }
24804
24805    #[test]
24806    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
24807        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
24808    }
24809
24810    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
24811    /// pair, in order, labelled A, B, C, ...
24812    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
24813        runner.state.candidates = shape
24814            .iter()
24815            .enumerate()
24816            .map(|(i, &(empty, verified))| Candidate {
24817                index: i,
24818                label: (b'A' + i as u8) as char,
24819                agent: "sonnet".to_owned(),
24820                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
24821                worktree: PathBuf::from(format!("/wt/{i}")),
24822                summary: String::new(),
24823                stat: String::new(),
24824                files: 0,
24825                commits: 0,
24826                empty,
24827                failed: None,
24828                verified_noop: verified.map(str::to_owned),
24829                duration_ms: 0,
24830                folded: false,
24831            })
24832            .collect();
24833    }
24834
24835    #[test]
24836    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
24837        ask_test_home();
24838        let mut runner = runner_at(RunStatus::Implementing);
24839        set_candidates(
24840            &mut runner,
24841            &[
24842                (true, Some("already on main at b32cfc4")),
24843                (true, Some("same fix, see the existing test")),
24844            ],
24845        );
24846
24847        runner
24848            .after_implement()
24849            .expect("a verified no-op is not an error");
24850
24851        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
24852    }
24853
24854    #[test]
24855    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
24856        ask_test_home();
24857        let mut runner = runner_at(RunStatus::Implementing);
24858        // Candidate A declares a verified no-op; candidate B simply wrote
24859        // nothing and said nothing about why. One candidate's claim is not
24860        // the whole run's agreement.
24861        set_candidates(
24862            &mut runner,
24863            &[(true, Some("already on main at b32cfc4")), (true, None)],
24864        );
24865
24866        let err = runner
24867            .after_implement()
24868            .expect_err("an unverified empty candidate must still fail the run");
24869
24870        assert!(
24871            err.to_string().contains("no candidate produced a change"),
24872            "{err}"
24873        );
24874        assert_eq!(runner.state.status, RunStatus::Failed);
24875    }
24876
24877    #[test]
24878    fn after_implement_still_fails_an_ordinary_all_empty_run() {
24879        ask_test_home();
24880        let mut runner = runner_at(RunStatus::Implementing);
24881        set_candidates(&mut runner, &[(true, None), (true, None)]);
24882
24883        let err = runner
24884            .after_implement()
24885            .expect_err("no candidate declared anything; this is an ordinary failure");
24886
24887        assert!(
24888            err.to_string().contains("no candidate produced a change"),
24889            "{err}"
24890        );
24891        assert_eq!(runner.state.status, RunStatus::Failed);
24892    }
24893}
24894
24895/// A graft rollback whose restore could not be confirmed (see
24896/// [`Runner::graft`]).
24897#[derive(Debug)]
24898struct GraftRestoreFailed(String);
24899
24900impl std::fmt::Display for GraftRestoreFailed {
24901    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24902        write!(
24903            f,
24904            "could not restore the winner to its pre-graft commit: {}",
24905            self.0
24906        )
24907    }
24908}
24909
24910impl std::error::Error for GraftRestoreFailed {}
24911
24912/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
24913/// not the agent: they never draw on an agent's own timeout, and running out of
24914/// them never reads as an agent failure.
24915#[cfg(test)]
24916mod resource_wait_tests {
24917    use super::*;
24918    use std::collections::BTreeMap;
24919
24920    fn sh(id: &str, script: &str) -> AgentSpec {
24921        AgentSpec {
24922            id: id.to_owned(),
24923            kind: crate::config::AgentKind::Command,
24924            model: None,
24925            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
24926            extra_args: Vec::new(),
24927            env: BTreeMap::new(),
24928            prompt_delivery: None,
24929            max_turn_secs: None,
24930        }
24931    }
24932
24933    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
24934        SeatJob {
24935            seat: SeatState::new("impl-A", &spec.id, 1),
24936            spec,
24937            cwd: dir.to_path_buf(),
24938            prompt: "do it".to_owned(),
24939            timeout,
24940            allow_write: true,
24941            sessions: false,
24942            artifacts: dir.join("art"),
24943            stem: "impl-A".to_owned(),
24944            handover: None,
24945        }
24946    }
24947
24948    fn state(resource_wait_secs: u64) -> RunState {
24949        let mut config = Config::default();
24950        config.graph.timeout_resource_wait = resource_wait_secs;
24951        RunState::new(
24952            PathBuf::from("/repo"),
24953            "main".to_owned(),
24954            "abc1234".to_owned(),
24955            "task".to_owned(),
24956            config,
24957        )
24958    }
24959
24960    fn hold(cache: &Path) -> crate::cache::Guard {
24961        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
24962        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
24963            crate::cache::AcquireOutcome::Acquired(g) => g,
24964            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
24965        }
24966    }
24967
24968    async fn run(
24969        jobs: Vec<SeatJob>,
24970        sem: Arc<Semaphore>,
24971        cache: Option<&Path>,
24972        st: &mut RunState,
24973    ) -> Vec<(usize, SeatState, AgentOutcome)> {
24974        let prompts = Prompts::default();
24975        let ctx = WaveCtx {
24976            run: "r",
24977            node: "implement",
24978            prompts: &prompts,
24979            cache,
24980            round: None,
24981            carry_seats: false,
24982            pauses: None,
24983        };
24984        wave(jobs, sem, &ctx, st, 0).await
24985    }
24986
24987    #[tokio::test]
24988    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
24989        crate::run::pin_test_home();
24990        let home = crate::run::home();
24991        let tmp = tempfile::tempdir().unwrap();
24992        let repo = tmp.path().join("repo");
24993        let checkout = tmp.path().join("checkout");
24994        std::fs::create_dir(&repo).unwrap();
24995        git::git(&repo, &["init"]).await.unwrap();
24996        git::git(
24997            &repo,
24998            &[
24999                "-c",
25000                "user.name=Fixture",
25001                "-c",
25002                "user.email=fixture@example.invalid",
25003                "commit",
25004                "--allow-empty",
25005                "-m",
25006                "initial",
25007            ],
25008        )
25009        .await
25010        .unwrap();
25011        git::worktree_add_detached(&repo, &checkout, "HEAD")
25012            .await
25013            .unwrap();
25014        let target = crate::build_target::resolve(&home, &checkout).unwrap();
25015        let target_lease = hold(&target);
25016        let shared = tmp.path().join("unrelated");
25017        let _shared_lease = hold(&shared);
25018        let mut st = state(0);
25019        st.repo = repo.clone();
25020        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
25021        st.config.verify.e2e = vec![format!(
25022            "CARGO_TARGET_DIR='{}' cargo test",
25023            git::path_arg(&shared)
25024        )];
25025        let config = tmp.path().join("config.toml");
25026        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
25027        let prompts = Prompts::default();
25028        let run_id = st.id.clone();
25029        let ctx = WaveCtx {
25030            run: &run_id,
25031            node: "implement",
25032            prompts: &prompts,
25033            cache: None,
25034            round: None,
25035            carry_seats: false,
25036            pauses: None,
25037        };
25038        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
25039        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
25040        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25041        assert_eq!(results[0].1.turns, 0);
25042        let saved = RunState::load_under(&run_id, &home).unwrap();
25043        let block = saved.resource_block.unwrap();
25044        assert!(matches!(
25045            block.cause,
25046            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
25047                if actual == &target
25048        ));
25049        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
25050        let mut task = crate::queue::Task::new(
25051            "build".into(),
25052            "build".into(),
25053            repo,
25054            crate::queue::Source::Human,
25055        );
25056        task.runs.push(run_id);
25057        task.hold_machine(Some(format!(
25058            "{}{}",
25059            crate::cache::RESOURCE_HOLD,
25060            block.description()
25061        )));
25062        queue.put(&mut task).unwrap();
25063        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
25064        let triage =
25065            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
25066        let pending = triage();
25067        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
25068        assert_eq!(
25069            queue.get(&task.id).unwrap().status,
25070            crate::queue::TaskStatus::Held
25071        );
25072        drop(target_lease);
25073        assert_eq!(triage().resumed, vec![task.id.clone()]);
25074        assert_eq!(
25075            queue.get(&task.id).unwrap().status,
25076            crate::queue::TaskStatus::Queued
25077        );
25078        assert!(crate::cache::in_use(&home, &shared));
25079    }
25080
25081    #[tokio::test]
25082    async fn verification_cache_wait_preserves_the_command_budget() {
25083        crate::run::pin_test_home();
25084        let tmp = tempfile::tempdir().unwrap();
25085        let cache = tmp.path().join("target");
25086        let guard = hold(&cache);
25087        let release = tokio::spawn(async move {
25088            tokio::time::sleep(Duration::from_millis(100)).await;
25089            guard.release();
25090        });
25091        let mut st = state(10);
25092        let budget = Duration::from_millis(50);
25093        let wait = repository_wait(&st, None);
25094        let (outcomes, _) = with_cache_lease(
25095            &mut st,
25096            Some(&cache),
25097            "gate",
25098            "gate",
25099            tmp.path(),
25100            "abc1234",
25101            budget,
25102            "test gate",
25103            &wait,
25104            |_, available| async move {
25105                assert_eq!(
25106                    available, budget,
25107                    "contention must not shorten verification"
25108                );
25109                (Vec::new(), false, Vec::new())
25110            },
25111        )
25112        .await
25113        .unwrap();
25114        release.await.unwrap();
25115        assert!(outcomes.is_empty(), "{outcomes:?}");
25116        assert!(
25117            st.events
25118                .iter()
25119                .any(|event| event.message.contains("waiting for"))
25120        );
25121        assert!(st.resource_wait.is_none());
25122        // The verification body no longer owns the lease after returning.
25123        hold(&cache).release();
25124    }
25125
25126    #[tokio::test]
25127    async fn verification_cache_wait_expires_without_starting_commands() {
25128        crate::run::pin_test_home();
25129        let tmp = tempfile::tempdir().unwrap();
25130        let cache = tmp.path().join("target");
25131        let _held = hold(&cache);
25132        let mut st = state(0);
25133        let wait = repository_wait(&st, None);
25134        let (outcomes, _) = with_cache_lease(
25135            &mut st,
25136            Some(&cache),
25137            "gate",
25138            "gate",
25139            tmp.path(),
25140            "abc1234",
25141            Duration::from_secs(60),
25142            "test gate",
25143            &wait,
25144            |_, _| async { panic!("commands must not start without the cache lease") },
25145        )
25146        .await
25147        .unwrap();
25148        assert_eq!(outcomes.len(), 1);
25149        assert!(outcomes[0].resource_blocked);
25150        assert!(st.resource_wait.is_none());
25151        assert!(matches!(
25152            st.resource_block.unwrap().cause,
25153            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
25154        ));
25155    }
25156
25157    #[tokio::test]
25158    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
25159        crate::run::pin_test_home();
25160        let tmp = tempfile::tempdir().unwrap();
25161        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
25162        let cache = tmp.path().join("cache");
25163        let mut state = state(21600);
25164        let wait = repository_wait(&state, None);
25165        let (outcomes, _) = with_cache_lease(
25166            &mut state,
25167            Some(&cache),
25168            "gate",
25169            "gate",
25170            tmp.path(),
25171            "head",
25172            Duration::from_secs(60),
25173            "gate",
25174            &wait,
25175            |_, _| async { panic!("freshness failure must not start verification") },
25176        )
25177        .await
25178        .unwrap();
25179        assert_eq!(outcomes.len(), 1);
25180        assert!(outcomes[0].resource_blocked);
25181        let block = state.resource_block.unwrap();
25182        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
25183        assert!(!block.description().contains("timed out"));
25184    }
25185
25186    #[tokio::test]
25187    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
25188        crate::run::pin_test_home();
25189        let tmp = tempfile::tempdir().unwrap();
25190        let cache = tmp.path().join("cache");
25191        let _held = hold(&cache);
25192        let mut state = state(21600);
25193        let pause = Pause::new();
25194        let interrupt = Pause::new();
25195        let cause = ParkCause::Operator;
25196        pause.park_for(cause.clone());
25197        let prompts = Prompts::default();
25198        let ctx = WaveCtx {
25199            run: "test",
25200            node: "fix",
25201            prompts: &prompts,
25202            cache: Some(&cache),
25203            round: None,
25204            carry_seats: false,
25205            pauses: Some((&pause, &interrupt)),
25206        };
25207        let result = wave(
25208            vec![job(
25209                sh("writer", "exit 99"),
25210                tmp.path(),
25211                Duration::from_secs(1),
25212            )],
25213            Arc::new(Semaphore::new(1)),
25214            &ctx,
25215            &mut state,
25216            0,
25217        )
25218        .await;
25219        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
25220        assert_eq!(result[0].1.turns, 0);
25221        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25222        assert_eq!(
25223            state.resource_block.unwrap().cause,
25224            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
25225        );
25226        assert!(state.active.is_empty());
25227    }
25228
25229    #[tokio::test]
25230    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
25231        crate::run::pin_test_home();
25232        let tmp = tempfile::tempdir().unwrap();
25233        let cache = tmp.path().join("target-a");
25234        let guard = hold(&cache);
25235        // Held for longer than the agent's whole 1s budget.
25236        tokio::spawn(async move {
25237            tokio::time::sleep(Duration::from_millis(1500)).await;
25238            guard.release();
25239        });
25240        let mut st = state(60);
25241        let results = run(
25242            vec![job(
25243                sh("alpha", "echo ok"),
25244                tmp.path(),
25245                Duration::from_secs(1),
25246            )],
25247            Arc::new(Semaphore::new(1)),
25248            Some(&cache),
25249            &mut st,
25250        )
25251        .await;
25252        assert!(
25253            matches!(results[0].2, AgentOutcome::Ok(_)),
25254            "the wait must not be charged to the agent"
25255        );
25256        assert!(st.resource_block.is_none());
25257        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25258        assert!(st.resource_wait.is_none() && st.active.is_empty());
25259    }
25260
25261    #[tokio::test]
25262    #[cfg(unix)]
25263    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
25264        use std::os::fd::AsRawFd as _;
25265        crate::run::pin_test_home();
25266        let tmp = tempfile::tempdir().unwrap();
25267        crate::git::git(tmp.path(), &["init"]).await.unwrap();
25268        let common = tmp.path().join(".git");
25269        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
25270        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
25271        assert_eq!(
25272            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
25273            0
25274        );
25275        let mut st = state(1);
25276        st.config.coordination = crate::config::test_coordination();
25277        let mut reader = job(
25278            sh("reader", "echo must-not-run"),
25279            tmp.path(),
25280            Duration::from_secs(30),
25281        );
25282        reader.allow_write = false;
25283        let results = run(
25284            vec![reader.clone()],
25285            Arc::new(Semaphore::new(1)),
25286            None,
25287            &mut st,
25288        )
25289        .await;
25290        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25291        assert_eq!(results[0].1.turns, 0);
25292        assert!(FailClass::of(&results[0].2).is_none());
25293        assert_eq!(
25294            st.resource_block.as_ref().unwrap().kind,
25295            "repository coordination"
25296        );
25297        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25298        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25299        drop(external);
25300        let editor = crate::repo_lock::SeatLease::for_checkout(
25301            tmp.path(),
25302            true,
25303            crate::config::test_coordination().as_ref(),
25304        )
25305        .await
25306        .unwrap();
25307        let pause = Pause::new();
25308        let interrupt = Pause::new();
25309        let prompts = Prompts::default();
25310        let ctx = WaveCtx {
25311            run: "r",
25312            node: "review",
25313            prompts: &prompts,
25314            cache: None,
25315            round: None,
25316            carry_seats: false,
25317            pauses: Some((&pause, &interrupt)),
25318        };
25319        let (results, ()) = tokio::join!(
25320            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
25321            async {
25322                tokio::time::sleep(Duration::from_millis(50)).await;
25323                pause.park();
25324            }
25325        );
25326        assert!(
25327            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
25328        );
25329        assert_eq!(results[0].1.turns, 0);
25330        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25331        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25332        drop(editor);
25333    }
25334
25335    #[tokio::test]
25336    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
25337        crate::run::pin_test_home();
25338        let tmp = tempfile::tempdir().unwrap();
25339        let cache = tmp.path().join("target-b");
25340        let _held = hold(&cache);
25341        let mut st = state(1);
25342        let results = run(
25343            vec![job(
25344                sh("alpha", "echo ok"),
25345                tmp.path(),
25346                Duration::from_secs(1),
25347            )],
25348            Arc::new(Semaphore::new(1)),
25349            Some(&cache),
25350            &mut st,
25351        )
25352        .await;
25353        let (_, seat, out) = &results[0];
25354        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
25355        assert!(wave_blocked(&results));
25356        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
25357        assert_eq!(seat.turns, 0, "nothing was asked");
25358        assert!(
25359            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
25360            "no agent was spawned"
25361        );
25362        assert!(FailClass::of(out).is_none(), "not a failure class");
25363        let block = st.resource_block.as_ref().expect("recorded for the resume");
25364        assert_eq!(block.kind, "shared build cache");
25365        assert!(matches!(
25366            block.cause,
25367            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
25368        ));
25369        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25370        assert!(st.active.is_empty());
25371    }
25372
25373    #[tokio::test]
25374    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
25375        crate::run::pin_test_home();
25376        let tmp = tempfile::tempdir().unwrap();
25377        let mut st = state(1);
25378        let results = run(
25379            vec![job(
25380                sh("alpha", "echo ok"),
25381                tmp.path(),
25382                Duration::from_secs(1),
25383            )],
25384            Arc::new(Semaphore::new(0)),
25385            None,
25386            &mut st,
25387        )
25388        .await;
25389        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25390        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
25391        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
25392    }
25393
25394    #[tokio::test]
25395    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
25396        crate::run::pin_test_home();
25397        let tmp = tempfile::tempdir().unwrap();
25398        let mut st = state(60);
25399        let results = run(
25400            vec![job(
25401                sh("alpha", "sleep 30"),
25402                tmp.path(),
25403                Duration::from_secs(1),
25404            )],
25405            Arc::new(Semaphore::new(1)),
25406            None,
25407            &mut st,
25408        )
25409        .await;
25410        let out = &results[0].2;
25411        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
25412        let class = FailClass::of(out).expect("a failure");
25413        assert_eq!(class, FailClass::Timeout);
25414        assert!(should_hand_over(None, &class), "existing handover policy");
25415        assert!(st.resource_block.is_none());
25416    }
25417}