Skip to main content

magi/
graph.rs

1//! The competition graph.
2//!
3//! ```text
4//! prep ──► implement ×N ──► judge ×M (blind) ──► split? ──► deliberate ──► vote (private)
5//!                                                   │                          │
6//!                                                   └──── unanimous ───────────┤
7//!                                                                              ▼
8//!   merge ◄── gate ◄── review ×R + E2E, fix, repeat ◄── fold losers ◄──────── tally
9//! ```
10//!
11//! Every node persists before the next one starts, so a run can be resumed
12//! after a crash, a rate limit, or a reboot without re-spending the work that
13//! already landed.
14//!
15//! The design decision that matters most is *where the facilitator lives*.
16//! There is no moderator agent: magi assigns the labels, decides the
17//! presentation order, relays the transcript, and collects the final votes
18//! one-to-one. A moderator that never learns an author cannot leak one.
19use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use anyhow::{Context as _, Result, bail};
26use jiff::Timestamp;
27use tokio::sync::Semaphore;
28
29use crate::advise;
30use crate::agent::{self, AgentOutput, Invocation, SeatState};
31use crate::ask;
32use crate::blind;
33use crate::bump;
34use crate::config::{
35    AgentSpec, Config, IncompleteReviewPolicy, LeakPolicy, MergeMode, MergeStyle, Prompts,
36    ResolvedRoles,
37};
38use crate::fixer;
39use crate::git;
40use crate::graft;
41use crate::land;
42use crate::proc::Quiet as _;
43use crate::prompt::{
44    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
45};
46use crate::queue;
47#[cfg(test)]
48use crate::refs;
49use crate::run::{
50    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
51    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord,
52    GithubTextChoice, GraftOutcome, GraftRecord, Handover, JobRecord, JobStatus, Judgement,
53    MergeOutcome, OperatorFixFinding, OperatorFixOutcome, OperatorFixRequest, Origin, ParkCause,
54    QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState, RunStatus, SeatHistory,
55    Tally, VoteRecord, summarize_verify, write_artifact,
56};
57use crate::verdict::{
58    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
59    ReviewVote, Severity,
60};
61
62/// Fixed commit message for graph-owned mechanical `verify.pre_gate` commits.
63pub const PRE_GATE_COMMIT_MESSAGE: &str = "magi: pre_gate (mechanical fixes)";
64
65/// Event node recorded by [`Runner::run_pre_gate`].
66pub(crate) const PRE_GATE_EVENT_NODE: &str = "pre_gate";
67
68/// Durable event text logged when [`Runner::run_pre_gate`] commits mechanical changes.
69pub(crate) fn pre_gate_commit_event(head: &str) -> String {
70    format!("committed mechanical fixes ({head})")
71}
72use crate::worktree_setup;
73
74/// Bytes of a failing command's output kept in an event, so the reason a run
75/// stopped is readable from the report without opening `run.json`.
76const EVENT_OUTPUT_TAIL: usize = 2_000;
77
78/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
79/// command's pid before releasing the build cache's lease.
80const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
81
82/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
83/// command's pid to actually exit before giving up and releasing anyway.
84///
85/// A timeout means the process was asked to die (`kill_on_drop`,
86/// `start_kill`), not that it already has — on Windows in particular that can
87/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
88/// the instant the command returns would let the very next acquirer (this
89/// run's own next round, another run's verification, the janitor's prune)
90/// start touching the same directory while it might still be writing to it,
91/// so this polls the actual pid — real confirmation, not a fixed guess —
92/// until it is gone or this ceiling is reached. It is still not full
93/// process-tree reaping: a grandchild the timed-out process spawned and that
94/// outlives it independently is invisible to a pid check, and continuing to
95/// observe and collect *that* stays a different piece of work with its own
96/// owner. Set generously because the common case returns early the moment
97/// the pid is confirmed gone, not because every timeout pays this in full.
98const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
99
100/// Consecutive review rounds with no tree progress (see
101/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
102/// instead of spending the rest of the round budget.
103///
104/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
105/// legitimately finds nothing left to change (its previous round's fix already
106/// covered it, and this round's reviewers re-raised only nits) looks the same
107/// as one that is spinning, for exactly one round. Two in a row is where the
108/// two stop being distinguishable, and a review round on this workload has
109/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
110/// third attempt at a tree that has not moved twice running is pure cost.
111/// This does not touch `review_rounds` itself, which stays the operator's
112/// call.
113pub(crate) const STAGNANT_LIMIT: usize = 2;
114
115/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
116/// a base that moved before giving up and leaving the run `Blocked` for a
117/// person.
118///
119/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
120/// that keeps moving faster than a run can catch it is not something more
121/// rebasing fixes, it is a person's call. Not the same *number as*
122/// `land_rounds` - this budget is spent before a pull request exists, land's
123/// after - but bounded for the identical reason, so it uses the same
124/// default. Counted across both call sites in [`Runner::finish_after_tally`]
125/// (once before review, once before the gate), because either one finding
126/// the base still moving is the same signal.
127pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
128
129/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
130/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
131/// reply held no [`FixReport`].
132///
133/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
134/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
135/// "I'll pause here until the `cargo make check` background run reports
136/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
137/// No `FixReport` was ever collected from that seat, and the run moved on to
138/// the next review round regardless.
139///
140/// Bounded independently of `review_rounds` and `graph.retries`: this
141/// recovers one seat's missing report mid-round, not a new round of review or
142/// an ordinary parse retry, and must not itself become the unbounded wait the
143/// rest of this module exists to avoid.
144const MAX_FIX_CONTINUATIONS: usize = 2;
145
146/// One queued agent invocation.
147///
148/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
149/// CLI hung up on its own stream is asked again from the same job rather than
150/// rebuilt from scratch. See [`Runner::resume_undelivered`].
151#[derive(Clone)]
152struct SeatJob {
153    spec: AgentSpec,
154    seat: SeatState,
155    cwd: PathBuf,
156    prompt: String,
157    timeout: Duration,
158    allow_write: bool,
159    sessions: bool,
160    artifacts: PathBuf,
161    stem: String,
162    /// The prompt for a seat that has been handed to another roster agent
163    /// (a fresh session): everything the original seat would have
164    /// remembered. `None` when `prompt` already carries it, as the first
165    /// ranking and the implement prompt do. Never a resume-style prompt.
166    handover: Option<String>,
167}
168
169/// How the graph reads one agent invocation.
170///
171/// Quota is split out from an ordinary failure on purpose: a rate-limited call
172/// is known to fail again if retried now, so the retry loop must not spend an
173/// attempt on it. `Dropped` is split out for the opposite reason: unlike
174/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
175/// error JSON, never the agent's answer — a caller that matched only
176/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
177/// left to read that JSON as if it were usable output. `resume_undelivered`
178/// is the only caller that acts on it; everywhere else it is reported like an
179/// ordinary failure.
180enum AgentOutcome {
181    /// A usable output.
182    Ok(AgentOutput),
183    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
184    Quota(AgentOutput),
185    /// The CLI hung up on its own stream after billed work. See
186    /// [`agent::AgentOutput::work_undelivered`].
187    Dropped(AgentOutput),
188    /// Any other failure: a timeout, a bad exit code, an empty reply.
189    Failed(String),
190    /// A resource prevented admission or interrupted execution. Not an agent
191    /// failure: never advance a fallback chain or spend an attempt on it.
192    /// Post-spawn interruptions carry a typed error into wave, which records
193    /// implementation preservation before returning this outcome. This outcome
194    /// alone is not proof that no source changes were made.
195    /// [`RunState::resource_block`] says why.
196    ResourceBlocked(String),
197}
198
199/// A request to park the run at its next node boundary.
200///
201/// Cloning is how the request travels: the loop keeps one handle and hands a
202/// clone to each [`Runner`], and every clone points at the same flag. There
203/// is no channel because there is nothing to send - the only message is
204/// "park", it is idempotent, and a flag cannot be missed by a receiver that
205/// was not listening yet.
206///
207/// The boundary is what makes this cheap. Every node writes the run's state
208/// before the next one starts, and every node skips what is already recorded:
209/// `prep` returns early once candidates exist, `implement` asks only the seats
210/// with nothing on disk, `judge` returns early once judgements exist. So a
211/// parked run resumes into exactly the node it stopped before, and no agent
212/// work is thrown away. Killing the process mid-node, by contrast, loses
213/// whatever the seats in flight had not yet written - which for an implement
214/// wave is an hour of paid work.
215///
216/// A [`Runner`] watches two independent handles of this type - see
217/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
218/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
219/// clone covering the whole daemon's lifetime and is never asked to un-park,
220/// which is correct exactly because nothing is dispatched after it fires.
221/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
222/// that parks for an interrupted task must go on to run other tasks
223/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
224/// reusing the daemon-wide one.
225#[derive(Debug, Clone, Default)]
226pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
227
228impl Pause {
229    /// A pause nobody has asked for yet.
230    #[must_use]
231    pub fn new() -> Self {
232        Self::default()
233    }
234
235    /// Ask the run to park at its next node boundary. Idempotent.
236    pub fn park(&self) {
237        self.0.store(true, Ordering::SeqCst);
238    }
239
240    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
241    /// fold into the run's own `park` event - so an operator reading the run
242    /// later knows this was a deliberate interrupt rather than a shutdown or
243    /// a binary swap. The first reason recorded wins; a park already in
244    /// flight is not relabelled by a second, unrelated request.
245    pub fn park_because(&self, reason: impl Into<String>) {
246        self.park_for(ParkCause::Interrupt {
247            reason: reason.into(),
248        });
249    }
250
251    /// [`Pause::park`], recording the structured cause. The first cause
252    /// recorded wins, like [`Pause::park_because`].
253    pub fn park_for(&self, cause: ParkCause) {
254        let mut reason_guard = self
255            .1
256            .lock()
257            .unwrap_or_else(std::sync::PoisonError::into_inner);
258        if reason_guard.is_none() {
259            *reason_guard = Some(cause);
260        }
261        drop(reason_guard);
262        self.park();
263    }
264
265    /// Has a park been asked for?
266    #[must_use]
267    pub fn parked(&self) -> bool {
268        self.0.load(Ordering::SeqCst)
269    }
270
271    /// Why the park was asked for, when the caller used [`Pause::park_because`].
272    #[must_use]
273    pub fn reason(&self) -> Option<String> {
274        self.cause().map(|c| c.label())
275    }
276
277    /// The structured cause, when one was recorded.
278    #[must_use]
279    pub fn cause(&self) -> Option<ParkCause> {
280        self.1
281            .lock()
282            .unwrap_or_else(std::sync::PoisonError::into_inner)
283            .clone()
284    }
285}
286
287/// Drives one run.
288pub struct Runner {
289    /// Run state; public so the CLI can report on it.
290    pub state: RunState,
291    roles: ResolvedRoles,
292    sem: Arc<Semaphore>,
293    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
294    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
295    /// this is never the same handle as `interrupt`.
296    pause: Pause,
297    /// Set when `magi serve`'s interrupt scheduler wants this specific run
298    /// parked at its next node boundary, to let a task marked
299    /// [`crate::queue::Task::interrupt`] run alone before this one carries
300    /// on. Unlike `pause`, a fresh, unshared handle per run - see
301    /// [`Runner::watch_interrupt`].
302    interrupt: Pause,
303}
304
305/// Where the branch's own commits start: its merge base with the base branch
306/// as the remote has it now, else with the recorded `base_commit`. A branch
307/// rebased onto a base that moved past `base_commit` would otherwise count
308/// the base's commits as its own under `base_commit..branch`.
309async fn review_base(
310    repo: &Path,
311    remote: &str,
312    base_branch: &str,
313    base_commit: &str,
314    branch: &str,
315) -> String {
316    review_base_checked(repo, remote, base_branch, base_commit, branch)
317        .await
318        .0
319}
320
321/// [`review_base`] plus whether the base was read from a freshly fetched
322/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
323/// never older than `base_commit`'s view of the base), but the answer is then
324/// not trusted to rewrite a pull request's title.
325async fn review_base_checked(
326    repo: &Path,
327    remote: &str,
328    base_branch: &str,
329    base_commit: &str,
330    branch: &str,
331) -> (String, bool) {
332    let tracking = format!("{remote}/{base_branch}");
333    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
334    if git::rev_exists(repo, &tracking).await
335        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
336        && !mb.is_empty()
337    {
338        return (mb, fresh);
339    }
340    let mb = git::merge_base(repo, base_commit, branch)
341        .await
342        .ok()
343        .filter(|mb| !mb.is_empty())
344        .unwrap_or_else(|| base_commit.to_owned());
345    (mb, false)
346}
347
348/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
349/// when git cannot say or finds nothing: a stale list is better than a wrong
350/// or empty one.
351pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
352    if !is_review_run(state) {
353        return;
354    }
355    let base = review_base(
356        &state.repo,
357        &state.config.merge.remote,
358        &state.base_branch,
359        &state.base_commit,
360        branch,
361    )
362    .await;
363    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
364        && !subjects.is_empty()
365        && state.reviewed_commits.as_ref() != Some(&subjects)
366    {
367        state.reviewed_commits = Some(subjects);
368        state.save().ok();
369    }
370}
371
372/// Subjects of the base's commits between the recorded start and the branch's
373/// merge base: what a stale `base_commit..branch` would have mistaken for the
374/// branch's own work.
375async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
376    let (base, trusted) = review_base_checked(
377        &state.repo,
378        &state.config.merge.remote,
379        &state.base_branch,
380        &state.base_commit,
381        branch,
382    )
383    .await;
384    if !trusted {
385        return None;
386    }
387    git::subjects(&state.repo, &state.base_commit, &base)
388        .await
389        .ok()
390}
391
392/// May an adopted pull request's title be replaced with `computed`? Only when
393/// it is empty, magi's own shape, or a base commit's subject that leaked in;
394/// a title a person wrote stays. Never when `computed` is itself a leak.
395pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
396    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
397    if is_leak(computed) {
398        return false;
399    }
400    let cur = current.trim();
401    cur.is_empty()
402        || cur.starts_with(REVIEW_PROMPT_OPENING)
403        || cur.starts_with("chore: land candidate")
404        || cur.starts_with("magi: candidate")
405        || is_leak(cur)
406}
407
408/// The commit a run branches from: the base branch as the remote has it.
409///
410/// Two failures this replaces. A run used to branch off `HEAD` and so refused
411/// to start on a dirty tree, which made `magi serve` decline every task for as
412/// long as the operator had work in progress - most of the time. Branching off
413/// the *local* base branch fixed that and introduced a worse one: `land` merges
414/// the winner on GitHub, nothing updates the local ref, and the next run
415/// branches off a base missing everything the previous runs landed. Two tasks
416/// in a row from a phone would have had the second silently re-implementing
417/// against stale code and opening a pull request that reverted the first.
418///
419/// Only refs move here - no checkout, no local branch, no merge - so it is safe
420/// with uncommitted work in the tree. A machine with no network still starts:
421/// the fetch may fail and the local tip is used with a warning, because
422/// refusing to run offline is a worse failure than running against a base the
423/// operator can see for themselves.
424///
425/// One function, called by both entry points. Two answers to "where does a run
426/// branch from" is the kind of drift nobody notices until a diff is wrong.
427/// Bring the local `branch` in line with `<remote>/<branch>` before a review
428/// checks it out.
429///
430/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
431/// anything other than plain `git push` from this checkout (a jj colocated
432/// workspace, another clone) moves only the remote-tracking ref - so the local
433/// one can be a stale placeholder. It moves only when local is behind the remote or is an
434/// empty placeholder that diverged from it; unpushed local work is kept, and a real
435/// divergence is refused rather than guessed at.
436async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
437    let tracking = format!("{remote}/{branch}");
438    let fetched = git::fetch(repo, remote, branch).await;
439    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
440    let local_exists = git::branch_exists(repo, branch).await?;
441    if !fresh {
442        if !local_exists {
443            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
444        }
445        tracing::warn!(
446            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
447        );
448        return Ok(());
449    }
450    let remote_sha = git::rev_parse(repo, &tracking).await?;
451    if !local_exists {
452        git::git(repo, &["branch", branch, &tracking]).await?;
453        return Ok(());
454    }
455    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
456    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
457        return Ok(());
458    }
459    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
460        // Diverged. `reconcile` settles it only when it can prove nothing is
461        // lost: a local tip that is the remote's change rebased is pushed over
462        // it (lease pinned to the tip read here), a tip whose every extra
463        // commit is empty is a placeholder the remote's work replaced, and
464        // anything else is two different changes - a question for a person.
465        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
466            .await?
467        {
468            crate::reconcile::Reconciliation::Pushed => {
469                tracing::warn!(
470                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
471                    short(&local_sha),
472                    short(&remote_sha)
473                );
474                return Ok(());
475            }
476            crate::reconcile::Reconciliation::Placeholder => {}
477            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
478        }
479    }
480    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
481    if !out.ok() {
482        bail!(
483            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
484            short(&local_sha),
485            short(&remote_sha),
486            out.stderr
487        );
488    }
489    tracing::warn!(
490        "local `{branch}` was stale: fast-forwarded {} -> {}",
491        short(&local_sha),
492        short(&remote_sha)
493    );
494    Ok(())
495}
496
497async fn resolve_base(
498    repo: &Path,
499    base_branch: &str,
500    remote: &str,
501    coordination: Option<&crate::config::Coordination>,
502) -> Result<crate::run::FetchedBase> {
503    let _lease = crate::repo_lock::SeatLease::operation_with(
504        repo,
505        coordination,
506        &crate::repo_lock::WaitPolicy::current(),
507    )
508    .await?;
509    let tracking = format!("{remote}/{base_branch}");
510    let fetched = git::fetch(repo, remote, base_branch).await;
511    if let Ok(out) = &fetched
512        && out.ok()
513        && git::rev_exists(repo, &tracking).await
514    {
515        return Ok(crate::run::FetchedBase {
516            remote: remote.to_owned(),
517            branch: base_branch.to_owned(),
518            commit: git::rev_parse(repo, &tracking).await?,
519            fetched_at: jiff::Timestamp::now(),
520        });
521    }
522    let why = match &fetched {
523        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
524        Ok(_) => format!("{remote} has no {base_branch}"),
525        Err(e) => e.to_string(),
526    };
527    // No fallback to the local branch: it may be behind, and branching off an
528    // old commit is the stale-checkout bug this check exists to prevent.
529    bail!(
530        "cannot read {tracking} ({why}); refusing to branch off the local \
531         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
532         base / remote in magi.toml. This is launcher preparation: check the \
533         launcher's network, Git access and repository coordination before \
534         retrying"
535    )
536}
537
538/// Outcome of the shared fixer chain, before caller-owned stop policy.
539enum FixStep {
540    Resource,
541    Recorded { report_lost: bool },
542}
543
544/// Exclusive claim shared by targeted repairs and repository reassignment.
545/// Held before asynchronous fix preflight and released on every return or panic.
546///
547/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
548/// manual `magi fix` invocations against the same run are otherwise
549/// invisible to each other and would race to remove and recreate the same
550/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
551/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
552/// which is only ever reclaimed later, out of band, by
553/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
554/// `magi fix` invocation is not necessarily running under either of those, so
555/// nothing would ever sweep a lock a killed or crashed process left behind.
556/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
557/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
558/// lease use: an unreadable or unparsable pid, or a liveness query the
559/// platform cannot answer, reads as alive and the lock is left in place.
560pub(crate) struct FixClaim {
561    path: PathBuf,
562}
563
564impl FixClaim {
565    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
566        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
567        let path = dir.join("fix.lock");
568        let retry = crate::lock_file::Retry::new(None);
569        match Self::create(&path, retry) {
570            Ok(claim) => Ok(claim),
571            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
572                if Self::reclaim_if_dead(&path) {
573                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
574                } else {
575                    bail!(
576                        "another repair or `magi fix` is already running for this run ({} exists)",
577                        path.display()
578                    )
579                }
580            }
581            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
582        }
583    }
584
585    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
586        let mut f = retry.create(path)?;
587        use std::io::Write as _;
588        // Read back by `reclaim_if_dead` on a later, stuck invocation.
589        writeln!(f, "{}", std::process::id())?;
590        Ok(Self {
591            path: path.to_owned(),
592        })
593    }
594
595    /// True if the lock named a process confirmed dead, in which case it was
596    /// also removed. Never true on an unreadable file, an unparsable pid, or
597    /// a liveness query the platform cannot answer — see this type's own doc.
598    fn reclaim_if_dead(path: &Path) -> bool {
599        let dead = std::fs::read_to_string(path)
600            .ok()
601            .and_then(|body| body.trim().parse::<u32>().ok())
602            .is_some_and(|pid| !crate::proc::pid_alive(pid));
603        dead && std::fs::remove_file(path).is_ok()
604    }
605}
606
607impl Drop for FixClaim {
608    fn drop(&mut self) {
609        let _ = std::fs::remove_file(&self.path);
610    }
611}
612
613#[doc(hidden)]
614pub struct ExecutionLeaseGuard {
615    _lease: crate::driver::ExecutionLease,
616}
617
618#[doc(hidden)]
619pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
620    Ok(ExecutionLeaseGuard {
621        _lease: crate::driver::maintenance(home, run_id)?,
622    })
623}
624
625/// Holds the mutable runner as well as its durable lease: cancellation must
626/// clear both copies of ownership, including state a caller may save later.
627struct DriverExecution<'a> {
628    runner: &'a mut Runner,
629    driver: crate::driver::DriverGuard,
630}
631
632impl Drop for DriverExecution<'_> {
633    fn drop(&mut self) {
634        self.driver.release_local(&mut self.runner.state);
635    }
636}
637
638fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
639    if let Some(startup) = &mut state.startup {
640        startup.stage = stage.to_owned();
641    }
642    state.save()
643}
644
645/// Keep a reservation visible as blocked until startup finishes. A killed process
646/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
647struct StartupGuard {
648    id: String,
649    armed: bool,
650}
651
652impl StartupGuard {
653    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
654        state.startup = Some(crate::run::Startup {
655            kind: kind.to_owned(),
656            branch: branch.map(str::to_owned),
657            stage: "reserved".to_owned(),
658            complete: false,
659            failure: None,
660        });
661        state.status = RunStatus::Blocked;
662        state.reserve()?;
663        Ok(Self {
664            id: state.id.clone(),
665            armed: true,
666        })
667    }
668
669    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
670        startup_stage(state, stage)
671    }
672
673    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
674        let result = result.and_then(|()| {
675            state.startup.as_mut().expect("reserved startup").complete = true;
676            state.save()
677        });
678        self.armed = false;
679        match result {
680            Ok(()) => Ok(()),
681            Err(error) => {
682                let startup = state.startup.as_mut().expect("reserved startup");
683                startup.complete = false;
684                startup.failure = Some(format!("{error:#}"));
685                let context = crate::run::StartupFailure {
686                    run: state.id.clone(),
687                    stage: startup.stage.clone(),
688                };
689                // Repository assets may remain. Never infer that a failed startup
690                // is safe to resume or that an earlier owner has been restored.
691                state.status = RunStatus::Failed;
692                state.driver_exited = true;
693                state.event(
694                    "startup-failed",
695                    format!("{context}: {error:#}; retained assets require inspection"),
696                );
697                if let Err(save) = state.save() {
698                    tracing::warn!(
699                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
700                        state.id
701                    );
702                }
703                Err(error.context(context))
704            }
705        }
706    }
707}
708
709impl Drop for StartupGuard {
710    fn drop(&mut self) {
711        if self.armed
712            && let Ok(mut state) = RunState::load(&self.id)
713        {
714            state.status = RunStatus::Blocked;
715            state.driver_exited = true;
716            if let Some(startup) = &mut state.startup {
717                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
718            }
719            state.event(
720                "startup-interrupted",
721                "startup did not finish; inspect retained assets before recovery",
722            );
723            if let Err(error) = state.save() {
724                tracing::error!(
725                    "could not record interrupted startup {}: {error:#}",
726                    self.id
727                );
728            }
729        }
730    }
731}
732
733impl Runner {
734    /// A queue-side failure after construction must not strand an unexecuted run.
735    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
736        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
737            return error;
738        }
739        if let Some(startup) = &mut self.state.startup {
740            startup.stage = stage.to_owned();
741        } else {
742            // A resumed run already has execution history: do not rewrite it.
743            return error;
744        }
745        StartupGuard {
746            id: self.state.id.clone(),
747            armed: true,
748        }
749        .finish(&mut self.state, Err(error))
750        .expect_err("startup failed")
751    }
752
753    /// Start a fresh run against `repo`.
754    pub async fn start(
755        repo: &Path,
756        instruction: String,
757        config: Config,
758        origin: Origin,
759    ) -> Result<Self> {
760        Self::start_naming(repo, instruction, "", config, origin).await
761    }
762
763    /// [`Runner::start`] for a queued task. Titles and instructions never
764    /// select implementation sources. The title argument is retained for callers.
765    pub async fn start_naming(
766        repo: &Path,
767        instruction: String,
768        _also_scan: &str,
769        config: Config,
770        origin: Origin,
771    ) -> Result<Self> {
772        let repo = git::toplevel(repo).await?;
773        let missing = agent::missing_programs(&config.agents);
774        if !missing.is_empty() {
775            bail!(
776                "these agent programs are not on PATH: {}. Fix the roster in \
777                 magi.toml or install them.",
778                missing.join(", ")
779            );
780        }
781        let base_branch =
782            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
783                .await?;
784        let fetched_base = resolve_base(
785            &repo,
786            &base_branch,
787            &config.merge.remote,
788            config.coordination.as_ref(),
789        )
790        .await?;
791        let base_commit = fetched_base.commit.clone();
792        let roles = config.resolve_roles()?;
793        let max_parallel = config.graph.max_parallel.max(1);
794        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
795        // Capture task identity and repository assignment before the first
796        // save, so publication scope survives crashes and later task moves.
797        state.fetched_base = Some(fetched_base);
798        state.set_origin(origin)?;
799        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
800        state.status = RunStatus::Prep;
801        state.event("start", format!("run {} created", state.id));
802        startup.finish(&mut state, Ok(()))?;
803        Ok(Self {
804            state,
805            roles,
806            sem: Arc::new(Semaphore::new(max_parallel)),
807            pause: Pause::new(),
808            interrupt: Pause::new(),
809        })
810    }
811
812    /// Open a review-only run against work that already exists on `branch`.
813    ///
814    /// The expensive half of the graph is the implement wave — measured at
815    /// 111 and 134 internal tool-loop turns on this repository, against a
816    /// handful for a judge or a reviewer. The cheap half is worth running on
817    /// hand-written work too, and there was no way to reach it.
818    ///
819    /// No new state and no schema change are needed: a run with **one** viable
820    /// candidate and a tally already decided degrades `execute` to exactly
821    /// review → gate → merge, because `judge` skips a single-candidate field,
822    /// `deliberate` has fewer than two first choices to reconcile, `vote`
823    /// returns early, `tally` is already present and `fold_losers` has no
824    /// losers. Resuming such a run therefore does the right thing as well.
825    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
826        Self::review_taking_over(repo, branch, config, None, origin).await
827    }
828
829    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
830    /// at the same task still has `branch` checked out, its worktree is
831    /// released first if that is safe (see [`crate::handover`]), and the
832    /// review refuses with the reason if it is not. `None` is a hand-run
833    /// review: it has no earlier attempts, so only a worktree of a dead run
834    /// magi recorded itself can be released.
835    pub async fn review_taking_over(
836        repo: &Path,
837        branch: &str,
838        config: Config,
839        takeover: Option<crate::handover::Takeover>,
840        origin: Origin,
841    ) -> Result<Self> {
842        let repo = git::toplevel(repo).await?;
843        let missing = agent::missing_programs(&config.agents);
844        if !missing.is_empty() {
845            bail!(
846                "these agent programs are not on PATH: {}. Fix the roster in \
847                 magi.toml or install them.",
848                missing.join(", ")
849            );
850        }
851        let base_branch =
852            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
853                .await?;
854        if base_branch == branch {
855            bail!("`{branch}` is the base branch; there is nothing to review against");
856        }
857        let fetched_base = resolve_base(
858            &repo,
859            &base_branch,
860            &config.merge.remote,
861            config.coordination.as_ref(),
862        )
863        .await?;
864        let base_commit = fetched_base.commit.clone();
865
866        let roles = config.resolve_roles()?;
867        let max_parallel = config.graph.max_parallel.max(1);
868        let mut state = RunState::new(
869            repo.clone(),
870            base_branch,
871            base_commit.clone(),
872            format!("Review the work already on branch `{branch}`."),
873            config,
874        );
875        state.fetched_base = Some(fetched_base);
876        state.set_origin(origin)?;
877        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
878        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
879        let opened = async {
880            startup.stage(&mut state, "handover")?;
881
882            // Released before anything else touches the branch: a stale local
883            // branch is moved with `git branch -f`, which git refuses while an
884            // earlier attempt's worktree still has it checked out. Everything
885            // after this point that can fail puts the old run back.
886            // A hand-run review has no task, hence no earlier attempts, but a
887            // worktree of a dead run magi made may still be released.
888            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
889                earlier: Vec::new(),
890                home: crate::run::home(),
891                choice: None,
892                task_instruction: None,
893            });
894            let wait = repository_wait(&state, None);
895            let coordination_config = state.config.coordination.clone();
896            let coordination =
897                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
898                    .await?;
899            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
900            if let Some(released) = &released {
901                state.event(
902                    "release",
903                    format!(
904                        "took `{branch}` over from run {}: its worktree was released: {}",
905                        crate::run::short_of(&released.old_id),
906                        released.audit
907                    ),
908                );
909            }
910            let opened = async {
911                startup.stage(&mut state, "review-preflight")?;
912                // The owner's answer to an earlier divergence question is applied
913                // here: after the release (git will not move a checked-out branch)
914                // and before the sync that would otherwise ask again.
915                state.foreign_checkout = crate::handover::preflight_review(
916                    &repo,
917                    branch,
918                    &takeover.home,
919                    &state.config.merge.remote,
920                )
921                .await?;
922                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
923                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
924                }
925                if let Some(choice) = takeover.choice.as_ref()
926                    && let Err(e) =
927                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
928                            .await
929                {
930                    return Err(e.context("applying the owner's answer about the diverged branch"));
931                }
932                // An earlier attempt of this task that published the task head, and
933                // whose work is the branch under review, hands that head over: the
934                // review run updates the same pull request. Without one (a legacy
935                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
936                // own head and its own open pull request is adopted as before.
937                for id in takeover.earlier.iter().rev() {
938                    if let Ok(old) = RunState::load_under(id, &takeover.home)
939                        && let Some(head) = old.pr_head.clone()
940                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
941                    {
942                        state.pr_head = Some(head);
943                        break;
944                    }
945                }
946                drop(coordination);
947                startup.stage(&mut state, "open-review")?;
948                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
949            }
950            .await;
951            if opened.is_err()
952                && let Some(released) = &released
953            {
954                // Restoration is ownership checked and best effort. Keep the original
955                // startup cause even if reacquiring coordination is no longer possible.
956                match crate::repo_lock::SeatLease::operation_with(
957                    &repo,
958                    coordination_config.as_ref(),
959                    &wait,
960                )
961                .await
962                {
963                    Ok(_coordination) => {
964                        released.restore(&repo, branch).await;
965                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
966                            .map(|old| {
967                                format!(
968                                    "predecessor released_to={:?}; candidate path exists={}",
969                                    old.released_to,
970                                    old.candidates.iter().any(|c| {
971                                        c.branch == branch && c.worktree.exists()
972                                    }),
973                                )
974                            })
975                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
976                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
977                    }
978                    Err(error) => {
979                        tracing::warn!(
980                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
981                            state.id
982                        );
983                        state.event(
984                            "startup-restore",
985                            format!("restoration not attempted: {error:#}"),
986                        );
987                    }
988                }
989            }
990            opened
991        }
992        .await;
993        startup.finish(&mut state, opened)?;
994        Ok(Self {
995            state,
996            roles,
997            sem: Arc::new(Semaphore::new(max_parallel)),
998            pause: Pause::new(),
999            interrupt: Pause::new(),
1000        })
1001    }
1002
1003    /// Recover exactly the operator-selected public implementation, without touching old sources.
1004    pub async fn recover_pr(
1005        repo: &Path,
1006        task: &str,
1007        selection: crate::pr_recovery::Selection,
1008        mut config: Config,
1009    ) -> Result<Self> {
1010        selection.configure(&mut config)?;
1011        let assignment = crate::run::task_assignment_for(task)?;
1012        match crate::queue::Queue::open().get(task) {
1013            Ok(owner) => selection.check_retained_task(&owner, &crate::run::home())?,
1014            Err(_) => selection.check_task_assignment(task, &selection.instruction, assignment)?,
1015        }
1016        let base_branch =
1017            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1018                .await?;
1019        let fetched_base = resolve_base(
1020            repo,
1021            &base_branch,
1022            &config.merge.remote,
1023            config.coordination.as_ref(),
1024        )
1025        .await?;
1026        let base_commit = fetched_base.commit.clone();
1027        selection
1028            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1029            .await?;
1030        Box::pin(selection.verify_source(repo)).await?;
1031        if let Some(proof) = &selection.source_proof {
1032            anyhow::ensure!(
1033                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1034                "source rebase base is outside the fetched landing base"
1035            );
1036        }
1037        let roles = config.resolve_roles()?;
1038        let max_parallel = config.graph.max_parallel.max(1);
1039        let mut state = RunState::new(
1040            repo.to_path_buf(),
1041            base_branch,
1042            base_commit.clone(),
1043            selection.instruction.clone(),
1044            config,
1045        );
1046        state.fetched_base = Some(fetched_base);
1047        state.set_origin(crate::run::Origin::queue(task))?;
1048        state.pr_head = Some(selection.branch.clone());
1049        state.pr_recovery = Some(selection.clone());
1050        state.stale_pr_recovery = selection.disposition
1051            == Some(crate::pr_recovery::Disposition::Land)
1052            && !git::is_ancestor(repo, &base_commit, &selection.head).await
1053            && crate::queue::Queue::open().get(task).is_ok_and(|task| {
1054                task.execution_runs().iter().any(|id| {
1055                    RunState::load(id).is_ok_and(|old| {
1056                        old.status == RunStatus::Ready
1057                            && !old.released()
1058                            && old.retired_to.is_none()
1059                            && old.pr_taken_over_by.is_none()
1060                            && task.assignment_accepts(&old)
1061                            && old.pr_branch() == Some(selection.branch.as_str())
1062                            && old
1063                                .pr
1064                                .as_ref()
1065                                .is_some_and(|pr| pr.state == "open" && pr.url == selection.url)
1066                    })
1067                })
1068            });
1069        if state.stale_pr_recovery {
1070            state.event("recovery", "stale public PR: a content conflict requires an explicit base-conflict repair grant");
1071        }
1072        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1073    }
1074
1075    async fn open_selected(
1076        repo: &Path,
1077        mut state: RunState,
1078        roles: ResolvedRoles,
1079        max_parallel: usize,
1080        base_commit: String,
1081        selection: crate::pr_recovery::Selection,
1082    ) -> Result<Self> {
1083        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1084        let opened = async {
1085            startup.stage(&mut state, "predecessors")?;
1086            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1087            startup.stage(&mut state, "open-selected")?;
1088            let branch = state.branch_for('A');
1089            let wait = repository_wait(&state, None);
1090            let prepared = async {
1091                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1092                git::git(repo, &["branch", &branch, selection.source()]).await?;
1093                drop(coordination);
1094                anyhow::Ok(())
1095            }
1096            .await;
1097            prepared?;
1098            state.event(
1099                "recovery",
1100                format!(
1101                    "selected implementation {} for {} (public lease {})",
1102                    selection.source(),
1103                    selection.url,
1104                    selection.head
1105                ),
1106            );
1107            let takeover = crate::handover::Takeover {
1108                earlier: Vec::new(),
1109                home: crate::run::home(),
1110                choice: None,
1111                task_instruction: Some(selection.instruction.clone()),
1112            };
1113            state.save()?;
1114            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1115        }
1116        .await;
1117        startup.finish(&mut state, opened)?;
1118        Ok(Self {
1119            state,
1120            roles,
1121            sem: Arc::new(Semaphore::new(max_parallel)),
1122            pause: Pause::new(),
1123            interrupt: Pause::new(),
1124        })
1125    }
1126
1127    /// What the newest earlier attempt that reviewed `branch` leaves for this
1128    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1129    /// no earlier attempts. Reads the earlier record only: ownership of its
1130    /// worktree and branch is [`crate::handover`]'s business.
1131    async fn inherit(
1132        repo: &Path,
1133        branch: &str,
1134        base_commit: &str,
1135        takeover: &crate::handover::Takeover,
1136    ) -> Option<crate::recovery::RecoveryRecord> {
1137        use crate::recovery::{Relation, assess};
1138        let newest = takeover.earlier.last()?;
1139        let mut chosen = None;
1140        for id in takeover.earlier.iter().rev() {
1141            if let Ok(old) = RunState::load_under(id, &takeover.home)
1142                && !old.reviews.is_empty()
1143                && (old.winner().is_some_and(|w| w.branch == branch)
1144                    || old.pr_head.as_deref() == Some(branch))
1145            {
1146                chosen = Some(old);
1147                break;
1148            }
1149        }
1150        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1151            .await
1152            .unwrap_or_default();
1153        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1154            Some(last) if last.head == tip => Relation::Same,
1155            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1156            _ => Relation::Diverged,
1157        };
1158        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1159        Some(assess(from, chosen.as_ref(), base_commit, relation))
1160    }
1161
1162    /// The half of [`Runner::review_taking_over`] that can fail after an
1163    /// earlier attempt's worktree was released.
1164    async fn open_review(
1165        repo: &Path,
1166        branch: &str,
1167        state: &mut RunState,
1168        base_commit: String,
1169        takeover: &crate::handover::Takeover,
1170    ) -> Result<()> {
1171        startup_stage(state, "review-sync")?;
1172        let wait = repository_wait(state, None);
1173        let _coordination = coordinate_operation(state, repo, &wait).await?;
1174        if state.foreign_checkout.is_some() {
1175            // Never reconcile or force-move a ref checked out by the operator.
1176            if state.pr_head.is_none() {
1177                state.pr_head = Some(branch.to_owned());
1178            }
1179        } else if state.pr_recovery.is_none() {
1180            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1181        }
1182        // The commit subjects are the closest thing to a task statement that
1183        // existing work carries, and the reviewers are told as much.
1184        let start = review_base(
1185            repo,
1186            &state.config.merge.remote,
1187            &state.base_branch,
1188            &base_commit,
1189            branch,
1190        )
1191        .await;
1192        let log = git::log_oneline(repo, &start, branch)
1193            .await
1194            .unwrap_or_default();
1195        let log_text = if log.trim().is_empty() {
1196            "(no commit messages)"
1197        } else {
1198            log.trim()
1199        };
1200        let mut instruction = format!(
1201            "Review the work already on branch `{branch}`. There is no task \
1202             statement: what the change claims to do is whatever its commits \
1203             say.\n\n{log_text}"
1204        );
1205        // A retry of a task whose earlier attempt left reviews behind carries
1206        // that attempt's evidence, and the task's own statement with it: the
1207        // completion criteria are the task's, not whatever the commits claim.
1208        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1209            if let Some(task) = takeover
1210                .task_instruction
1211                .as_deref()
1212                .filter(|t| !t.trim().is_empty())
1213                && rec.reviewed_head.is_some()
1214            {
1215                instruction = format!(
1216                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1217                    task.trim()
1218                );
1219                rec.criteria_inherited = true;
1220            }
1221            state.event("recovery", rec.summary());
1222            state.recovery = Some(rec);
1223        }
1224        if let Some(selected) = &state.pr_recovery {
1225            instruction = selected.instruction.clone();
1226        }
1227        state.task_instruction = takeover.task_instruction.clone();
1228        state.instruction = instruction;
1229        state.reviewed_commits = Some(
1230            git::subjects(repo, &start, branch)
1231                .await
1232                .unwrap_or_default(),
1233        );
1234
1235        // A takeover must not forget a hold that a previous review observed,
1236        // even if repairs have since removed it from the branch.
1237        for id in &takeover.earlier {
1238            if let Ok(old) = RunState::load_under(id, &takeover.home)
1239                && old.repo == state.repo
1240                && (old.pr_head.as_deref() == Some(branch)
1241                    || old.winner().is_some_and(|w| w.branch == branch))
1242            {
1243                for hold in old.branch_owner_holds {
1244                    if !state.branch_owner_holds.contains(&hold) {
1245                        state.event(
1246                            "approval-policy",
1247                            format!(
1248                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1249                                hold.control.key(),
1250                                hold.file,
1251                                hold.head
1252                            ),
1253                        );
1254                        state.branch_owner_holds.push(hold);
1255                    }
1256                }
1257            }
1258        }
1259        // Select the actual review tip before observing owner policy. A foreign
1260        // checkout can lag its remote descendant, and repairs must not erase
1261        // holds introduced only on that selected commit.
1262        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1263            let tracking = format!("{}/{branch}", state.config.merge.remote);
1264            // A surviving tracking ref is not evidence that the remote still
1265            // offers this tip. Adopt it only after a successful fetch here.
1266            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1267            let mut head = checkout.synced_head.clone();
1268            if matches!(fetched, Ok(out) if out.ok()) {
1269                let remote = git::rev_parse(repo, &tracking).await?;
1270                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1271                    head = remote;
1272                }
1273            }
1274            head
1275        } else {
1276            git::rev_parse(repo, branch).await?
1277        };
1278        state.observe_branch_owner_holds(&reviewed_head).await;
1279
1280        // An attached worktree, so the fixer's commits land on the branch under
1281        // review rather than on a detached head nobody will look at again.
1282        let worktree = state.worktree_root().join("under-review");
1283        if let Some(parent) = worktree.parent() {
1284            tokio::fs::create_dir_all(parent).await.ok();
1285        }
1286        let path = worktree.to_string_lossy().to_string();
1287        let review_branch = if state.foreign_checkout.is_some() {
1288            let shadow = format!("magi/{}/review", state.short());
1289            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1290            shadow
1291        } else {
1292            branch.to_owned()
1293        };
1294        startup_stage(state, "review-checkout")?;
1295        git::git(repo, &["worktree", "add", &path, &review_branch])
1296            .await
1297            .with_context(|| {
1298                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1299            })?;
1300
1301        startup_stage(state, "worktree-setup")?;
1302        let setup = match ensure_setup_config(state, repo).await {
1303            Ok(()) => {
1304                worktree_setup::prepare_with(
1305                    &state.config,
1306                    repo,
1307                    &worktree,
1308                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1309                )
1310                .await
1311            }
1312            Err(e) => Err(e),
1313        };
1314        if let Err(e) = setup {
1315            git::worktree_remove_clean(repo, &worktree).await.ok();
1316            return Err(e);
1317        }
1318        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1319            .await
1320            .unwrap_or(0);
1321        if commits == 0 {
1322            git::worktree_remove_clean(repo, &worktree).await.ok();
1323            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1324        }
1325        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1326            .await
1327            .map(|f| f.len())
1328            .unwrap_or(0);
1329        if files == 0
1330            && let (Ok(head_tree), Ok(base_tree)) = (
1331                git::tree_of(&worktree, "HEAD").await,
1332                git::tree_of(&worktree, &base_commit).await,
1333            )
1334            && head_tree == base_tree
1335        {
1336            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1337            git::worktree_remove_clean(repo, &worktree).await.ok();
1338            bail!(
1339                "`{branch}` at {} has a tree identical to base {}; this usually means \
1340                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1341                 against `{}/{branch}`) rather than an empty change",
1342                short(&head),
1343                short(&base_commit),
1344                state.config.merge.remote
1345            );
1346        }
1347        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1348            .await
1349            .unwrap_or_default();
1350
1351        state.candidates.push(Candidate {
1352            index: 0,
1353            label: 'A',
1354            // Not an agent id on purpose: nothing in the roster wrote this, and
1355            // the stats tables must not credit anyone with a win for it.
1356            agent: EXISTING_BRANCH.to_owned(),
1357            branch: review_branch,
1358            worktree,
1359            summary: String::new(),
1360            stat,
1361            files,
1362            commits,
1363            empty: false,
1364            failed: None,
1365            verified_noop: None,
1366            duration_ms: 0,
1367            folded: false,
1368        });
1369        state.tally = Some(Tally {
1370            first_choice: BTreeMap::from([('A', 0)]),
1371            borda: BTreeMap::new(),
1372            winner: 'A',
1373            rankings: 0,
1374            unanimous_initial: false,
1375            deliberated: false,
1376            changed_votes: 0,
1377            unanimous_final: false,
1378            tie_break: None,
1379            // No panel sat, so no quorum applies. Zero judges is the correct
1380            // number for work that never competed, and must not be reported as
1381            // a collapsed panel.
1382            judges: 0,
1383            present: 0,
1384            quorum: 0,
1385            met_quorum: true,
1386            uncontested: Some("review-only run: nothing competed".to_owned()),
1387        });
1388        state.status = RunStatus::Reviewing;
1389        state.prep_complete = Some(true);
1390        state.event(
1391            "start",
1392            format!(
1393                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1394                state.id
1395            ),
1396        );
1397        Ok(())
1398    }
1399
1400    /// Authorize one bounded synchronization interval, under the caller's queue task
1401    /// claim and the same owner/execution locks used by run maintenance.
1402    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1403        Self::authorize_base_recovery_request(home, id, task, false, None, None).await
1404    }
1405
1406    /// Authorize a known preparation failure against the inspected evidence.
1407    pub async fn authorize_base_preparation_recovery(
1408        home: &Path,
1409        id: &str,
1410        task: &str,
1411        digest: &str,
1412    ) -> Result<()> {
1413        Self::authorize_base_recovery_request(home, id, task, false, None, Some(digest)).await
1414    }
1415
1416    /// Queue release uses its durable approval generation exactly once.
1417    pub(crate) async fn authorize_base_recovery_from_resumption(
1418        home: &Path,
1419        id: &str,
1420        task: &str,
1421    ) -> Result<()> {
1422        Self::authorize_base_recovery_request(home, id, task, true, None, None).await
1423    }
1424
1425    pub(crate) async fn authorize_base_recovery_control(
1426        home: &Path,
1427        task: &str,
1428        control: &mut crate::base_recovery_control::Transaction,
1429    ) -> Result<()> {
1430        let id = control.request.run.clone();
1431        Self::authorize_base_recovery_request(home, &id, task, false, Some(control), None).await
1432    }
1433
1434    async fn authorize_base_recovery_request(
1435        home: &Path,
1436        id: &str,
1437        task: &str,
1438        resumption: bool,
1439        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1440        terminal_digest: Option<&str>,
1441    ) -> Result<()> {
1442        let _owner = crate::pr_head::owner_lock(home, id)?;
1443        let mut state = RunState::load_under(id, home)?;
1444        crate::pr_head::ensure_owner(&state)?;
1445        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1446        anyhow::ensure!(
1447            queued.execution_runs().last().is_some_and(|run| run == id)
1448                && queued.assignment_accepts(&state)
1449                && queued.status != crate::queue::TaskStatus::Done
1450                && !queued.fresh_start
1451                && queued.review_branch.is_none(),
1452            "run task ownership changed"
1453        );
1454        anyhow::ensure!(
1455            state
1456                .origin
1457                .as_ref()
1458                .and_then(|o| o.task.as_deref())
1459                .is_none_or(|owner| owner == task),
1460            "run belongs to another task"
1461        );
1462        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1463        anyhow::ensure!(
1464            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1465            "run is live or its ownership is unknown"
1466        );
1467        // Judge the previous driver's lease before acquiring our maintenance
1468        // lease. The owner lock excludes new driver claims across both steps.
1469        let _execution = crate::driver::maintenance(home, id)?;
1470        anyhow::ensure!(
1471            state.status.resumable()
1472                && state.released_to.is_none()
1473                && state.retired_to.is_none()
1474                && state.pr_taken_over_by.is_none(),
1475            "run ownership is final"
1476        );
1477        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1478        anyhow::ensure!(
1479            !state.pr_publication_pending
1480                && !crate::handover::landing_checkpoint(&state)
1481                && state.merge_decision.is_none(),
1482            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1483        );
1484        let winner = state.winner().context("run has no retained winner")?;
1485        anyhow::ensure!(
1486            git::is_clean(&winner.worktree).await?,
1487            "retained worktree has uncommitted changes"
1488        );
1489        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1490        anyhow::ensure!(
1491            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1492            "retained worktree does not match the winner branch"
1493        );
1494        if let Some(control) = control.as_ref() {
1495            anyhow::ensure!(
1496                head.starts_with(&control.request.head),
1497                "retained HEAD changed since the owner request"
1498            );
1499            anyhow::ensure!(
1500                state
1501                    .base_sync_recovery
1502                    .stop
1503                    .as_ref()
1504                    .is_none_or(|stop| stop.head == head),
1505                "retained HEAD differs from the recorded stop head; inspect it first"
1506            );
1507        }
1508        anyhow::ensure!(
1509            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1510            "{}",
1511            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1512        );
1513        state.ensure_base_episode();
1514        state.record_base_sync_stop(&head);
1515        let preparation = state.unknown_preparation_stop(&head);
1516        anyhow::ensure!(
1517            state
1518                .base_sync_recovery
1519                .stop
1520                .as_ref()
1521                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted)
1522                || (preparation && !resumption),
1523            "base recovery refused: missing eligible movement-exhaustion or preparation-stop evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1524        );
1525        let fetched =
1526            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1527        anyhow::ensure!(
1528            fetched.ok(),
1529            "cannot authorize base recovery without a fetched base"
1530        );
1531        let approved_tip = git::rev_parse(
1532            &state.repo,
1533            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1534        )
1535        .await?;
1536        let preparation_digest = state.preparation_digest(&head);
1537        anyhow::ensure!(
1538            preparation
1539                || (terminal_digest.is_none()
1540                    && control
1541                        .as_ref()
1542                        .is_none_or(|c| c.request.evidence_digest.is_none())),
1543            "preparation evidence digest does not name an eligible preparation stop"
1544        );
1545        if preparation {
1546            anyhow::ensure!(
1547                crate::daemon::compatible_run_instruction(&state, &queued),
1548                "task instruction does not match the retained run"
1549            );
1550            if let Some(control) = control.as_ref() {
1551                anyhow::ensure!(
1552                    control.request.head == head
1553                        && control.request.evidence_digest.is_some()
1554                        && control.request.evidence_digest == preparation_digest
1555                        && control.request.decision.is_none(),
1556                    "preparation stop requires the full HEAD and current inspected evidence digest"
1557                );
1558            } else {
1559                anyhow::ensure!(
1560                    terminal_digest.is_some() && terminal_digest == preparation_digest.as_deref(),
1561                    "preparation stop requires the current inspected evidence digest"
1562                );
1563            }
1564            let stop = state.base_sync_recovery.stop.as_ref().unwrap();
1565            anyhow::ensure!(
1566                git::is_ancestor(&state.repo, &stop.tip, &approved_tip).await,
1567                "current base does not descend from the stopped base"
1568            );
1569            git::probe_rebase_preparation(
1570                &state,
1571                &head,
1572                &home.join("runs").join(id),
1573                &repository_wait(&state, None),
1574            )
1575            .await?;
1576        }
1577        if let Some(control) = control.as_deref_mut() {
1578            let queue = crate::queue::Queue::at(home.join("queue"));
1579            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1580            if let Some(prior) = state
1581                .base_sync_recovery
1582                .authorizations
1583                .iter()
1584                .find(|a| a.request.as_deref() == Some(&control.key()))
1585            {
1586                anyhow::ensure!(
1587                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1588                    "recovery request was consumed or invalidated; it cannot queue again"
1589                );
1590                return control.enqueue(&queue);
1591            }
1592        }
1593        if resumption {
1594            anyhow::ensure!(
1595                crate::daemon::compatible_run_instruction(&state, &queued),
1596                "resumption instruction does not match the retained run"
1597            );
1598            let approval = queued
1599                .resumption
1600                .as_ref()
1601                .context("no operator resumption")?;
1602            anyhow::ensure!(
1603                approval.instruction == queued.instruction,
1604                "resumption approval does not match the current task instruction"
1605            );
1606            state.authorize_base_sync_resumption(task, approval)?;
1607        } else {
1608            state.authorize_base_sync(task)?;
1609        }
1610        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1611        state
1612            .base_sync_recovery
1613            .authorizations
1614            .last_mut()
1615            .unwrap()
1616            .scope = Some(crate::base_sync_recovery::Scope {
1617            tip: approved_tip,
1618            instruction: queued.instruction.clone(),
1619            episode,
1620            preparation_digest,
1621        });
1622        if let Some(control) = control.as_deref_mut() {
1623            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1624            authorization.request = Some(control.key());
1625            authorization.generation = control.generation();
1626            authorization.decision = control.decision();
1627            authorization.question = control
1628                .request
1629                .decision
1630                .as_ref()
1631                .map(|_| control.request.request.clone());
1632        }
1633        state.event(
1634            "base-recovery",
1635            if preparation {
1636                "owner authorized the proven preparation-stop recovery; remaining budget retained; fresh verification required"
1637            } else {
1638                "owner authorized a bounded base synchronization interval; fresh verification required"
1639            },
1640        );
1641        state.save_under(home)?;
1642        if let Some(control) = control {
1643            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1644        }
1645        Ok(())
1646    }
1647
1648    /// Reopen an existing run.
1649    pub fn resume(id: &str) -> Result<Self> {
1650        let state = RunState::load(id)?;
1651        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1652        if state.startup.as_ref().is_some_and(|s| !s.complete)
1653            || (state.status == RunStatus::Prep
1654                && state.instruction.trim().is_empty()
1655                && state.candidates.is_empty()
1656                && state.prep_complete == Some(false))
1657        {
1658            bail!(
1659                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1660            );
1661        }
1662        crate::pr_head::ensure_owner(&state)?;
1663        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1664            bail!(
1665                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1666            );
1667        }
1668        if let Some(to) = &state.released_to {
1669            bail!(
1670                "run {} cannot be resumed: its worktree was released to run {}",
1671                state.short(),
1672                crate::run::short_of(to)
1673            );
1674        }
1675        let roles = state.config.resolve_roles()?;
1676        if let Some(id) = &state.config.graph.selected_implementer
1677            && state.candidates.iter().any(|c| c.agent != *id)
1678        {
1679            bail!(
1680                "replacement implementer pin does not match the saved candidates; task must stay held"
1681            );
1682        }
1683        let max_parallel = state.config.graph.max_parallel.max(1);
1684        Ok(Self {
1685            state,
1686            roles,
1687            sem: Arc::new(Semaphore::new(max_parallel)),
1688            pause: Pause::new(),
1689            interrupt: Pause::new(),
1690        })
1691    }
1692
1693    /// Walk the graph to a terminal state, skipping nodes already recorded.
1694    ///
1695    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1696    /// the phone - ends here, so this is the one place a run that ended
1697    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1698    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1699    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1700        // Allocate before polling: boxing inside an async wrapper would still
1701        // retain its construction frame while the nested graph is polled.
1702        Box::pin(self.execute_inner(None))
1703    }
1704
1705    pub(crate) async fn execute_sync_only(
1706        &mut self,
1707        request: crate::base_sync_only::Request,
1708    ) -> Result<()> {
1709        Box::pin(self.execute_inner(Some(request))).await
1710    }
1711
1712    async fn execute_inner(
1713        &mut self,
1714        sync_only: Option<crate::base_sync_only::Request>,
1715    ) -> Result<()> {
1716        anyhow::ensure!(
1717            self.state.startup.as_ref().is_none_or(|s| s.complete),
1718            "startup incomplete; inspect retained evidence before explicit recovery"
1719        );
1720        if let Some(selection) = &self.state.pr_recovery
1721            && (selection.source_proof.is_some() || selection.source_run.is_some())
1722        {
1723            Box::pin(selection.verify_source(&self.state.repo)).await?;
1724        }
1725        // Queue claims cover daemon work; this also serializes manual drivers
1726        // consuming a repair answer, including the new review and decision.
1727        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1728            || self.state.land_approval.is_some()
1729            || self.state.merge_decision.is_some()
1730            || !self.state.merge_repairs.is_empty()
1731            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1732        {
1733            let claim = FixClaim::acquire(&self.state.dir())?;
1734            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1735            let disk = RunState::load(&self.state.id)?;
1736            let checkpoint = |s: &RunState| {
1737                (
1738                    s.merge_repairs.len(),
1739                    s.merge_repairs
1740                        .last()
1741                        .map(|r| (r.question.clone(), r.phase)),
1742                    s.land_approval
1743                        .as_ref()
1744                        .map(|a| (a.question.clone(), a.head.clone())),
1745                )
1746            };
1747            if checkpoint(&disk) != checkpoint(&self.state) {
1748                bail!(
1749                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1750                );
1751            }
1752            Some(claim)
1753        } else {
1754            None
1755        };
1756        let base_only = sync_only.is_some();
1757        let mut execution = self.claim_driver(sync_only).await?;
1758        let runner = &mut *execution.runner;
1759        let wait = runner.repository_wait();
1760        // Keep the graph's large future off the callers' stack, including
1761        // standalone task attempts running on a default-sized test thread.
1762        let result = if base_only {
1763            wait.scope(Box::pin(async {
1764                let repo = runner.state.repo.clone();
1765                let result = async {
1766                    let _coordination = runner.coordinate(&repo).await?;
1767                    anyhow::ensure!(
1768                        !runner.pause.parked() && !runner.interrupt.parked(),
1769                        "paused before base synchronization"
1770                    );
1771                    crate::base_sync_only::sync(&mut runner.state).await
1772                }
1773                .await;
1774                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1775                pass.result = match result {
1776                    Ok(outcome) => outcome,
1777                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1778                };
1779                let summary = pass.summary();
1780                runner.state.event("base-sync-only", summary);
1781                runner.state.save()
1782            }))
1783            .await
1784        } else {
1785            wait.scope(Box::pin(runner.execute_graph())).await
1786        };
1787        let result = match result {
1788            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1789                record_repository_block(&mut runner.state, &e);
1790                runner.park_here()?;
1791                Ok(())
1792            }
1793            other => other,
1794        };
1795        execution.driver.finish(&mut runner.state).await?;
1796        let ended = if result.is_err() {
1797            Some({
1798                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1799                if let Err(error) = &result {
1800                    notice.message = format!(
1801                        "Run {} stopped with an error: {}",
1802                        runner.state.id,
1803                        error.to_string().lines().next().unwrap_or("unknown error")
1804                    );
1805                }
1806                notice
1807            })
1808        } else {
1809            crate::notices::run_ended(&runner.state)
1810        };
1811        if let Some(notice) = ended {
1812            crate::notices::raise(notice);
1813        }
1814        result
1815    }
1816
1817    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1818        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1819    }
1820
1821    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1822        let wait = self.repository_wait();
1823        coordinate_operation(&mut self.state, cwd, &wait).await
1824    }
1825
1826    /// Validate ownership and persist the driver claim in one critical section.
1827    async fn claim_driver(
1828        &mut self,
1829        sync_only: Option<crate::base_sync_only::Request>,
1830    ) -> Result<DriverExecution<'_>> {
1831        let owner = match crate::pr_head::owner_lock_wait(
1832            &crate::run::home(),
1833            &self.state.id,
1834            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1835        )
1836        .await
1837        {
1838            Ok(owner) => owner,
1839            Err(error) => {
1840                let detail = format!("worktree maintenance or ownership update: {error:#}");
1841                // Admission did not own run.json: retain this resource outcome
1842                // in memory for queue settlement without overwriting a concurrent
1843                // retirement or publication transaction.
1844                self.state.resource_block = Some(crate::run::ResourceBlock {
1845                    cause: crate::run::ResourceBlockCause::Other,
1846                    node: "start".into(),
1847                    kind: "worktree maintenance".into(),
1848                    detail: detail.clone(),
1849                    at: Timestamp::now(),
1850                });
1851                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1852            }
1853        };
1854        let disk = RunState::load(&self.state.id)?;
1855        crate::pr_head::ensure_owner(&disk)?;
1856        let now = Timestamp::now();
1857        let home = crate::run::home();
1858        let claim = crate::daemon::other_claim_for_run(&home, &disk.id, now)?;
1859        let assessment = disk.assess_liveness_under(&home, claim, now);
1860        // Only proven-live ownership refuses here. Unknown records (legacy runs
1861        // with no claim marker or process identity) fall through to the
1862        // exclusive execution lease taken just below, which is what actually
1863        // keeps a second driver out.
1864        anyhow::ensure!(
1865            assessment.verdict != crate::run::Liveness::Live,
1866            "{}",
1867            assessment.live_driver_refusal()
1868        );
1869        if let Some(to) = &disk.released_to {
1870            bail!(
1871                "run {} cannot continue: its worktree was released to run {}",
1872                self.state.short(),
1873                crate::run::short_of(to)
1874            );
1875        }
1876        anyhow::ensure!(
1877            serde_json::to_value(&disk.base_sync_recovery)?
1878                == serde_json::to_value(&self.state.base_sync_recovery)?,
1879            "base recovery changed since this run was loaded; reload the saved run"
1880        );
1881        anyhow::ensure!(
1882            disk.sync_only_passes == self.state.sync_only_passes,
1883            "base-only synchronization changed since this run was loaded; reload the saved run"
1884        );
1885        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1886        let mut execution = DriverExecution {
1887            runner: self,
1888            driver,
1889        };
1890        // Declare after the execution guard: on any claim error this short
1891        // lock must drop before that guard reloads and releases ownership.
1892        let _owner = owner;
1893        if let Some(request) = sync_only {
1894            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1895            anyhow::ensure!(
1896                request.run == disk.id,
1897                "sync-base-only request targets a different run"
1898            );
1899            let state = &mut execution.runner.state;
1900            let task_entry = state.next_pass_task_entry;
1901            *state = disk;
1902            state.next_pass_task_entry = task_entry;
1903            if state.pending_sync_only().is_some() {
1904                let pass_index = state.passes.len();
1905                let pass = state.sync_only_passes.last_mut().unwrap();
1906                anyhow::ensure!(
1907                    pass.request == request,
1908                    "interrupted base-only synchronization belongs to a different request"
1909                );
1910                pass.pass_index = pass_index;
1911            } else {
1912                let pass = crate::base_sync_only::Pass::new(request, state);
1913                state.sync_only_passes.push(pass);
1914            }
1915            if state.status == RunStatus::Failed {
1916                state.status = RunStatus::Blocked;
1917            }
1918        } else {
1919            anyhow::ensure!(
1920                disk.pending_sync_only().is_none(),
1921                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1922            );
1923            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1924                .await?;
1925        }
1926        let state = &mut execution.runner.state;
1927        // Moving again, so it is no longer parked. Set before the walk rather
1928        // than in `resume`, so every way of re-entering the graph clears it
1929        // and a card cannot claim a run is waiting to be resumed while the
1930        // agents are already working.
1931        state.parked = false;
1932        state.resource_wait = None;
1933        state.resource_block = None;
1934        // Any seat this state still lists as answering belongs to whatever
1935        // process last drove this run — this one included, if it crashed
1936        // mid-wave. Cleared and flushed immediately, before anything else
1937        // runs, so a resume can never show a seat as live when nothing is
1938        // asking it anything yet; the node that actually dispatches the next
1939        // wave repopulates it.
1940        state.clear_active();
1941        // Recorded in the same spot, and flushed together with the clear
1942        // above: this is the pid a reader checks (`RunState::liveness`) when
1943        // no daemon claim exists to answer "is a process still driving this
1944        // run" — a plain `magi run` / `magi review` typed into a terminal
1945        // claims nothing there. Always overwritten, never only-if-absent, so
1946        // a resumed run's stale pid from a previous, possibly-dead process
1947        // can never survive into this one's own report. Unlike
1948        // `clear_active`, this changes on every single `execute()` call, so
1949        // the save below is now unconditional rather than only-if-cleared.
1950        //
1951        // `driver_started_at` is recorded in the same breath, from this same
1952        // pid, so `liveness` can tell a live pid that is genuinely still us
1953        // apart from one the OS has since handed to an unrelated process —
1954        // see that field's own doc for why the pid alone is not enough.
1955        let pid = std::process::id();
1956        state.driver_pid = Some(pid);
1957        state.driver_started_at = crate::proc::process_started_at(pid);
1958        state.driver_exited = false;
1959        state.driver_claimed = Some(true);
1960        state.begin_pass();
1961        execution.driver.bind(state);
1962        state.save()?;
1963        execution.driver.record(state)?;
1964        Ok(execution)
1965    }
1966
1967    /// No conflict checkpoint proves dispatch was never reached. End that
1968    /// consumed generation so an owner can explicitly authorize a fresh one.
1969    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1970        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1971        if let Err(error) = &result
1972            && !error.is::<crate::repo_lock::ResourceBlocked>()
1973            && self
1974                .state
1975                .repair_grants
1976                .last()
1977                .is_some_and(|g| g.conflict.is_none())
1978        {
1979            self.state.repair_grants.last_mut().unwrap().phase =
1980                crate::repair_budget::Phase::Complete;
1981            self.state.status = RunStatus::Blocked;
1982            self.state.save()?;
1983            bail!(
1984                "{error:#}. The consumed reservation ended before editing-seat dispatch. Inspect its scratch tree, then authorize a new base-conflict grant with a new request ID and current --expect-pass {}; the old request will not dispatch again",
1985                self.state.passes.last().map_or(0, |p| p.index)
1986            );
1987        }
1988        result
1989    }
1990
1991    /// A grant owns only these repair attempts. Confirmation reviews cannot
1992    /// create another fixer allowance, and every operation is restart-checkpointed.
1993    async fn execute_granted_repair(&mut self) -> Result<()> {
1994        use crate::repair_budget::{Kind, Phase};
1995        let index = self.state.repair_grants.len() - 1;
1996        let winner = self
1997            .state
1998            .winner()
1999            .cloned()
2000            .context("repair winner missing")?;
2001        loop {
2002            let grant = self.state.repair_grants[index].clone();
2003            match grant.phase {
2004                Phase::Pending => {
2005                    if grant.spent >= grant.receipt.request.rounds {
2006                        self.state.repair_grants[index].phase = Phase::Complete;
2007                        self.state.status = RunStatus::Blocked;
2008                        self.state.save()?;
2009                        return Ok(());
2010                    }
2011                    if grant.spent == 0 && grant.receipt.request.kind == Kind::Review {
2012                        crate::repair_budget::verify_initial_review_grant(&self.state, &grant)
2013                            .await?;
2014                    }
2015                    // Reserve before dispatch. A crash can consume an attempt,
2016                    // but can never duplicate it or reset saved fixer history.
2017                    self.state.repair_grants[index].spent += 1;
2018                    self.state.repair_grants[index].phase = Phase::Fixing;
2019                    self.state.save()?;
2020                    match grant.receipt.request.kind {
2021                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
2022                        Kind::Gate => {
2023                            let failed = self.state.gate.clone();
2024                            let _ = self.gate_fix_round(&winner, &failed).await?;
2025                        }
2026                        Kind::Review => {
2027                            let mut record = self
2028                                .state
2029                                .reviews
2030                                .last()
2031                                .cloned()
2032                                .context("review failure missing")?;
2033                            let round = record.round;
2034                            let step = self.run_fix_round(&winner, &mut record).await?;
2035                            self.state.reviews[round - 1] = record;
2036                            if matches!(step, FixStep::Recorded { report_lost: true }) {
2037                                self.state.repair_grants[index].phase = Phase::Complete;
2038                                self.state.status = RunStatus::Blocked;
2039                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
2040                                self.state.save()?;
2041                                return Ok(());
2042                            }
2043                            if matches!(step, FixStep::Resource) {
2044                                self.stop_for_resource()?;
2045                                return Ok(());
2046                            }
2047                            self.state.save()?;
2048                        }
2049                    }
2050                    if self.resource_halt()? {
2051                        return Ok(());
2052                    }
2053                }
2054                Phase::Fixing => {
2055                    if grant.receipt.request.kind == Kind::BaseConflict {
2056                        self.repair_base_conflict(false).await?;
2057                    }
2058                    // Interrupted fixers may have left source changes or an
2059                    // unpushed commit. Preserve them before fresh assessment.
2060                    let _coordination = self.coordinate(&winner.worktree).await?;
2061                    let rescued = git::rescue_commit(
2062                        &winner.worktree,
2063                        "magi: preserve interrupted granted repair",
2064                    )
2065                    .await?;
2066                    self.state.note_withheld("repair-grant", &rescued.withheld);
2067                    // Fresh checks must supersede even a same-head failure.
2068                    // Archive rather than erase failure evidence or counters.
2069                    self.state
2070                        .verification_history
2071                        .push(crate::run::VerificationEvidence {
2072                            superseded_by: None,
2073                            archived_at: Some(Timestamp::now()),
2074                            fixes_spent: Some(self.state.gate_fixes.len()),
2075                            gate_head: self.state.gate_head.take(),
2076                            gate_ran: std::mem::take(&mut self.state.gate_ran),
2077                            gate: std::mem::take(&mut self.state.gate),
2078                            e2e: self.state.head_e2e.take(),
2079                        });
2080                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
2081                        self.state
2082                            .verification_history
2083                            .push(crate::run::VerificationEvidence {
2084                                superseded_by: None,
2085                                archived_at: Some(Timestamp::now()),
2086                                fixes_spent: Some(self.state.gate_fixes.len()),
2087                                gate_head: None,
2088                                gate_ran: false,
2089                                gate: Vec::new(),
2090                                e2e: Some(e2e),
2091                            });
2092                    }
2093                    self.state.repair_grants[index].review_start = self.state.reviews.len();
2094                    self.state.repair_grants[index].head =
2095                        git::rev_parse(&winner.worktree, "HEAD").await?;
2096                    self.state.repair_grants[index].phase = Phase::Reviewing;
2097                    if grant.receipt.request.kind == Kind::BaseConflict {
2098                        self.state.base_sync_recovery.stop = None;
2099                        if let Some(sync) = &mut self.state.base_sync {
2100                            sync.tip = grant
2101                                .receipt
2102                                .request
2103                                .tip
2104                                .clone()
2105                                .context("repair base tip missing")?;
2106                            sync.conflict = None;
2107                            sync.behind = 0;
2108                        }
2109                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2110                    }
2111                    self.state.save()?;
2112                }
2113                Phase::Reviewing => {
2114                    self.review_loop_pass().await?;
2115                    if self.resource_halt()? {
2116                        return Ok(());
2117                    }
2118                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2119                    let reviewed = (self.state.reviews.len() > grant.review_start)
2120                        .then(|| self.state.reviews.last())
2121                        .flatten();
2122                    let review_passed = reviewed.is_some_and(|r| {
2123                        r.clean
2124                            && r.expected > 0
2125                            && r.answered == r.expected
2126                            && matches!(
2127                                r.e2e_status(),
2128                                E2eStatus::Passed | E2eStatus::NotConfigured
2129                            )
2130                            && ((r.e2e_status() == E2eStatus::NotConfigured
2131                                && self.state.config.verify.e2e.is_empty())
2132                                || r.verified_head.as_deref() == Some(head.as_str()))
2133                    });
2134                    let clean = review_passed && reviewed.is_some_and(|r| r.head == head);
2135                    if !clean {
2136                        let next = if review_passed
2137                            && let Some(r) = reviewed
2138                            && r.head != head
2139                        {
2140                            crate::repair_budget::prove_mechanical_pre_gate_commit(
2141                                &self.state,
2142                                r,
2143                                &head,
2144                            )
2145                            .await
2146                            .map(|_| Some(Phase::Reviewing))
2147                        } else if grant.receipt.request.kind == Kind::Review
2148                            && grant.spent < grant.receipt.request.rounds
2149                        {
2150                            crate::repair_budget::prove_review_target(&self.state, &head)
2151                                .await
2152                                .map(|_| Some(Phase::Pending))
2153                        } else {
2154                            Ok(None)
2155                        };
2156                        let next = match next {
2157                            Ok(next) => next,
2158                            Err(error) => {
2159                                if self.state.repair_grants[index]
2160                                    .checkpoint_provenance_retry(&head, &error)
2161                                {
2162                                    self.state.status = RunStatus::Blocked;
2163                                    self.state.event("repair-grant", format!(
2164                                        "pre-gate provenance unavailable; resume confirmation without spending repair budget: {error:#}"
2165                                    ));
2166                                    self.state.save()?;
2167                                    return Ok(());
2168                                }
2169                                None
2170                            }
2171                        };
2172                        if next == Some(Phase::Reviewing) {
2173                            self.state.repair_grants[index].review_start = self.state.reviews.len();
2174                            self.state.repair_grants[index].head = head;
2175                            self.state.repair_grants[index].phase = Phase::Reviewing;
2176                            self.state.status = RunStatus::Blocked;
2177                            self.state.event(
2178                                "repair-grant",
2179                                "pre-gate changed the reviewed head; resume for fresh review before publication",
2180                            );
2181                            self.state.save()?;
2182                            return Ok(());
2183                        }
2184                        // A confirmation review carries no additional fix budget.
2185                        self.state.repair_grants[index].phase = if next == Some(Phase::Pending) {
2186                            self.state.repair_grants[index].head = head;
2187                            Phase::Pending
2188                        } else {
2189                            Phase::Complete
2190                        };
2191                        self.state.status = RunStatus::Blocked;
2192                        self.state.event(
2193                            "repair-grant",
2194                            "fresh review did not clear the repaired head; no publication",
2195                        );
2196                        self.state.save()?;
2197                        if self.state.repair_grants[index].phase == Phase::Pending {
2198                            continue;
2199                        }
2200                        return Ok(());
2201                    }
2202                    self.state.repair_grants[index].phase = Phase::Gating;
2203                    self.state.save()?;
2204                }
2205                Phase::Gating => {
2206                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2207                    self.state.reconcile_verification_head(&head);
2208                    let wait = self.repository_wait();
2209                    if self
2210                        .state
2211                        .reviews
2212                        .last()
2213                        .is_none_or(|r| r.head != head || !r.clean)
2214                    {
2215                        self.state.status = RunStatus::Blocked;
2216                        self.state.repair_grants[index].phase = Phase::Complete;
2217                        self.state.event(
2218                            "repair-grant",
2219                            "head changed since fresh review; repair held",
2220                        );
2221                        self.state.save()?;
2222                        return Ok(());
2223                    }
2224                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2225                        return Ok(());
2226                    }
2227                    let outcomes = self.run_gate(&winner).await?;
2228                    if verify_inconclusive(&outcomes) {
2229                        return Ok(());
2230                    }
2231                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2232                    if after != head {
2233                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2234                        self.state.repair_grants[index].head = after;
2235                        self.state.repair_grants[index].phase = Phase::Reviewing;
2236                        self.state.status = RunStatus::Blocked;
2237                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2238                        self.state.save()?;
2239                        return Ok(());
2240                    }
2241                    let passed = outcomes.iter().all(CommandOutcome::ok);
2242                    // Follow-up grants owe the same guarded checkout delivery
2243                    // as the conflict repair that introduced the new head.
2244                    if passed
2245                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2246                    {
2247                        return Ok(());
2248                    }
2249                    self.state.repair_grants[index].succeeded = passed;
2250                    self.state.gate = outcomes;
2251                    self.state.gate_ran = true;
2252                    self.state.status = if passed {
2253                        RunStatus::Gating
2254                    } else {
2255                        RunStatus::Blocked
2256                    };
2257                    self.state.repair_grants[index].phase = if !passed
2258                        && grant.receipt.request.kind == Kind::Gate
2259                        && grant.spent < grant.receipt.request.rounds
2260                    {
2261                        Phase::Pending
2262                    } else {
2263                        Phase::Complete
2264                    };
2265                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2266                        // Persist publication debt with the successful checkpoint.
2267                        self.state.pr_publication_pending = true;
2268                    } else if passed {
2269                        self.state.status = RunStatus::Ready;
2270                    }
2271                    self.state.save()?;
2272                    if !passed {
2273                        continue;
2274                    }
2275                    // Existing PR ownership and push lease stay in place. The
2276                    // normal publisher owes the new reviewed/gated SHA, and
2277                    // land's fresh owner approval remains mandatory.
2278                    if self.state.config.merge.mode != MergeMode::Pr {
2279                        self.state.status = RunStatus::Ready;
2280                        self.state.event(
2281                            "repair-grant",
2282                            "repair verified locally; grant carries no merge authorization",
2283                        );
2284                        self.state.save()?;
2285                        return Ok(());
2286                    }
2287                    return self.merge().await;
2288                }
2289                Phase::Complete => return Ok(()),
2290            }
2291        }
2292    }
2293
2294    async fn execute_graph(&mut self) -> Result<()> {
2295        // Even a terminal run may reenter through an explicit recovery action.
2296        // Restore before prep shortcuts, saved conversations or graph nodes use
2297        // a disposable path; GC may already have removed its original objects.
2298        let archive_home = crate::run::home().canonicalize()?;
2299        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2300            let repo = self.state.repo.clone();
2301            let _coordination = self.coordinate(&repo).await?;
2302            ensure_setup_config(&mut self.state, &repo).await?;
2303            crate::retention::restore_execution_seats(
2304                &archive_home,
2305                &self.state,
2306                _coordination.as_ref(),
2307            )
2308            .await?;
2309        }
2310        self.state.configure_recovery_resume()?;
2311        if self
2312            .state
2313            .repair_grants
2314            .last()
2315            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2316        {
2317            return self.execute_granted_repair().await;
2318        }
2319        if self
2320            .state
2321            .repair_grants
2322            .last()
2323            .is_some_and(|g| !g.succeeded)
2324        {
2325            self.state.status = RunStatus::Blocked;
2326            self.state.save()?;
2327            return Ok(());
2328        }
2329        // Preservation may invalidate an old empty classification. Resolve it
2330        // before any resume shortcut can reuse a verdict or publish a branch.
2331        self.persist_candidates().await?;
2332        // A saved base stop outranks stage markers, including legacy Voting.
2333        // Recovery never reenters implementation, deliberation or voting.
2334        if self.state.base_sync_blocked() {
2335            self.sync_to_base().await?;
2336            if !self.state.base_sync_blocked()
2337                && self.state.status != RunStatus::AlreadyInBase
2338                && !self.resource_halt()?
2339            {
2340                self.finish_after_tally().await?;
2341            }
2342            return Ok(());
2343        }
2344        if self
2345            .state
2346            .merge_decision
2347            .as_ref()
2348            .is_some_and(|decision| !decision.closed)
2349            && self.state.status != RunStatus::Landing
2350        {
2351            if crate::merge_decision::resumable_hold(&self.state) {
2352                self.state.merge = Some(MergeOutcome {
2353                    mode: MergeMode::Pr,
2354                    ok: false,
2355                    detail: self
2356                        .state
2357                        .merge_decision
2358                        .as_ref()
2359                        .unwrap()
2360                        .target
2361                        .pr
2362                        .clone(),
2363                    empty: false,
2364                });
2365                self.run_land().await?;
2366                self.settle_questions();
2367                return Ok(());
2368            }
2369            bail!(
2370                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2371            );
2372        }
2373        if self.state.config.graph.selected_implementer.is_some()
2374            && self.state.status == RunStatus::Blocked
2375            && self.state.tally.is_none()
2376            && self.state.candidate_preservation.is_empty()
2377            && self.state.interrupted_implementations.is_empty()
2378        {
2379            bail!(
2380                "selected implementation is held; explicitly release the owning task to retry it"
2381            );
2382        }
2383
2384        if self.state.merge_repairs.last().is_some_and(|r| {
2385            matches!(
2386                r.phase,
2387                crate::run::MergeRepairPhase::Requested
2388                    | crate::run::MergeRepairPhase::Fixing
2389                    | crate::run::MergeRepairPhase::Reviewing
2390            )
2391        }) {
2392            if self.repair_merge_review().await? {
2393                self.run_land().await?;
2394            }
2395            self.settle_questions();
2396            return Ok(());
2397        }
2398        // Publication already passed review and gate. Resume only that node:
2399        // syncing to a newer base here could change the verified commit.
2400        if self.state.pr_publication_pending {
2401            self.merge().await?;
2402            if self.resource_halt()? {
2403                return Ok(());
2404            }
2405            self.state.save()?;
2406            self.settle_questions();
2407            return Ok(());
2408        }
2409        // A run that already lost its quorum never resumes into the verdict
2410        // machinery: `deliberate` and `vote` would otherwise clobber the
2411        // stalled marker back to Voting and the run would keep going past a
2412        // verdict that is no longer trustworthy. Everything already recorded is
2413        // kept, so the run stays resumable (or foldable) for a human to pick up.
2414        //
2415        // On --resume the run gets one chance to repair itself: the seats a
2416        // rate limit took out are re-asked. If their quota has since reset and
2417        // the quorum is restored, the run picks up and finishes; otherwise it
2418        // stays stale and still-resumable for a later retry. If it does not
2419        // recover, the returned status stays `Stalled` and nothing was
2420        // clobbered (the recovery only mutates entries for the lost seats).
2421        if self.state.status == RunStatus::Stalled {
2422            if self.recover_stall().await? {
2423                self.finish_after_tally().await?;
2424            } else {
2425                // Still below quorum: persist the marker and stay resumable.
2426                self.state.save()?;
2427            }
2428            return Ok(());
2429        }
2430        // A run parked inside `land` - watching CI, mid fix-round, or
2431        // waiting on the owner's merge approval - resumes directly into it,
2432        // never back through `prep`. Everything before `merge` already
2433        // concluded; that is the only way `status` reaches `Landing` in the
2434        // first place. Re-walking `review_loop` first would also be actively
2435        // wrong: its own status recomputation (see its doc) treats any
2436        // clean round as reason to set `status` to `Gating`, which would
2437        // clobber this marker before `merge` ever ran, and this run would
2438        // never find its way back into `land` at all.
2439        if self.state.status == RunStatus::Landing
2440            || crate::handover::landing_checkpoint(&self.state)
2441        {
2442            self.state.land_sync_pending = true;
2443            self.state.save()?;
2444            self.run_land().await?;
2445            // `run_land` may have settled the run right here - CI came back
2446            // green and the PR merged, say - without ever passing back
2447            // through `merge`'s own trailing call. Whatever it left `status`
2448            // as is what this has to read.
2449            self.settle_questions();
2450            return Ok(());
2451        }
2452        // A run parked at `merge` on the owner's word about a withheld PR text
2453        // resumes straight into `merge`. Re-walking the tail would sync to the
2454        // base again (possibly rebasing, possibly spending the fixer) after the
2455        // gate had passed, and then push a tree nobody reviewed or gated.
2456        if self.state.github_text.is_some()
2457            && self.state.merge.is_none()
2458            && self.state.status == RunStatus::Gating
2459        {
2460            self.merge().await?;
2461            if self.resource_halt()? {
2462                return Ok(());
2463            }
2464            self.state.save()?;
2465            return Ok(());
2466        }
2467        // A resource stop left the reserved synchronization unfinished. Reconcile
2468        // its exact HEAD and base before starting any earlier graph stage.
2469        if self.state.pending_base_operation().is_some() {
2470            return self.finish_after_tally().await;
2471        }
2472        if let Err(e) = self.prep().await {
2473            if e.is::<crate::repo_lock::ResourceBlocked>() {
2474                return Err(e);
2475            }
2476            self.state.status = RunStatus::Blocked;
2477            self.state
2478                .prep_failure
2479                .get_or_insert_with(|| format!("{e:#}"));
2480            self.state
2481                .event("prep", format!("preparation stopped: {e:#}"));
2482            self.state.save()?;
2483            return Err(e);
2484        }
2485        if self.park_here()? {
2486            return Ok(());
2487        }
2488        self.advise().await?;
2489        if self.park_here()? {
2490            return Ok(());
2491        }
2492        self.implement().await?;
2493        if self.park_here()? {
2494            return Ok(());
2495        }
2496        // `after_implement` already saved the state and settled any open
2497        // questions when it set this; nothing later in the graph has
2498        // anything to judge.
2499        if self.state.status == RunStatus::VerifiedNoop {
2500            return Ok(());
2501        }
2502        self.judge().await?;
2503        if self.park_here()? {
2504            return Ok(());
2505        }
2506        self.deliberate().await?;
2507        if self.park_here()? {
2508            return Ok(());
2509        }
2510        self.vote().await?;
2511        if self.park_here()? {
2512            return Ok(());
2513        }
2514        self.tally()?;
2515        // A verdict that lost its quorum is not trustworthy: do not review,
2516        // gate, or merge on it. Everything already done is kept, so the run
2517        // stays resumable (or foldable); the human can replace the agent that
2518        // ran out of quota and pick it up.
2519        if self.state.status == RunStatus::Stalled {
2520            // Persist the stalled marker now — the normal end-of-execute save
2521            // below is below this early return, and without it a resumed run
2522            // would reload a pre-tally status and keep going.
2523            self.state.save()?;
2524            return Ok(());
2525        }
2526        self.finish_after_tally().await?;
2527        Ok(())
2528    }
2529
2530    /// A wave could not start its agents because a shared resource stayed busy
2531    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2532    /// resumable. Unstarted seats have no result; completed peers retain
2533    /// their saved candidate state.
2534    fn stop_for_resource(&mut self) -> Result<()> {
2535        // Resource acquisition observes cancellation inside a node. Complete
2536        // the same durable park as every other node boundary before returning.
2537        if self.pause.parked() || self.interrupt.parked() {
2538            self.park_here()?;
2539            return Ok(());
2540        }
2541        if self.state.resource_block.is_some() {
2542            self.state.status = RunStatus::Blocked;
2543        }
2544        self.state.save()
2545    }
2546
2547    /// Stop walking the graph if a node ended on a resource block.
2548    fn resource_halt(&mut self) -> Result<bool> {
2549        if self.state.resource_block.is_none() {
2550            return Ok(false);
2551        }
2552        self.stop_for_resource()?;
2553        Ok(true)
2554    }
2555
2556    /// Park here if asked to, recording it in the run's own timeline.
2557    ///
2558    /// Returns whether the caller should stop walking the graph. The state is
2559    /// saved either way by the node that just finished; this adds the event so
2560    /// the operator's card says why a run that is neither finished nor moving
2561    /// is sitting where it is.
2562    fn park_here(&mut self) -> Result<bool> {
2563        let parking = self.pause.parked() || self.interrupt.parked();
2564        if !parking && self.state.resource_block.is_some() {
2565            self.stop_for_resource()?;
2566            return Ok(true);
2567        }
2568        // Either handle asking is enough - see `Pause`'s own doc for why
2569        // they are never the same one. `interrupt` is checked second so a
2570        // reason it carries is preferred in the message below over a plain
2571        // shutdown park racing it at the same boundary.
2572        if !self.pause.parked() && !self.interrupt.parked() {
2573            return Ok(false);
2574        }
2575        if self.state.parked {
2576            return Ok(true);
2577        }
2578        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2579        if let Some(block) = &mut self.state.resource_block
2580            && matches!(
2581                block.cause,
2582                crate::run::ResourceBlockCause::Cancelled { .. }
2583            )
2584        {
2585            block.cause = crate::run::ResourceBlockCause::Cancelled {
2586                park: cause.clone(),
2587            };
2588        }
2589        let why = match cause.as_ref().map(ParkCause::label) {
2590            Some(reason) => format!(
2591                "parked after `{}` ({reason}) — resume to carry on from here",
2592                self.state.status.as_str()
2593            ),
2594            None => format!(
2595                "parked after `{}` — resume to carry on from here",
2596                self.state.status.as_str()
2597            ),
2598        };
2599        self.state.event("park", why);
2600        self.state
2601            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2602        self.state.parked = true;
2603        self.state.save()?;
2604        Ok(true)
2605    }
2606
2607    /// Only a new explicit operator approval may retry failed preparation.
2608    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2609        if self.state.prep_failure.is_none() {
2610            return Ok(());
2611        }
2612        let failed_at = self
2613            .state
2614            .events
2615            .iter()
2616            .rev()
2617            .find(|event| event.node == "prep")
2618            .map_or(self.state.updated_at, |event| event.at);
2619        anyhow::ensure!(
2620            approval_at > failed_at,
2621            "preparation retry requires a new explicit release after the failure"
2622        );
2623        self.state.prep_failure = None;
2624        self.state.prep_complete = Some(false);
2625        self.state
2626            .event("prep-retry", "operator approved retry of preparation");
2627        Ok(())
2628    }
2629
2630    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2631    pub fn on_pause(&mut self, pause: Pause) {
2632        self.pause = pause;
2633    }
2634
2635    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2636    /// scheduler asking this one run - and no other - to park so a task
2637    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2638    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2639    /// handle.
2640    pub fn watch_interrupt(&mut self, pause: Pause) {
2641        self.interrupt = pause;
2642    }
2643
2644    /// Abandon this run's own open questions, once `status` has actually
2645    /// settled rather than merely paused.
2646    ///
2647    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2648    /// either back up with the candidates, the review round and the seat
2649    /// sessions already on disk, so a question an implementer asked mid-round
2650    /// may still get a real answer read by a real resume. Only the statuses
2651    /// `resumable` excludes are actually final: the run merged, it reached
2652    /// `Ready` with nothing left to do, it failed outright with no
2653    /// established point to continue from, or every candidate agreed, with
2654    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2655    /// every one of those the seat that asked is gone for good, exactly like
2656    /// the run being deleted under `magi run rm` - so the same cleanup
2657    /// applies, worded for what actually happened instead of "the run was
2658    /// deleted".
2659    ///
2660    /// Best-effort and silent on success: called from every place `status`
2661    /// can land on one of those three, including ones a resumed run revisits,
2662    /// so it must cost nothing when there was nothing open to begin with.
2663    fn settle_questions(&mut self) {
2664        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2665            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2666        }
2667    }
2668
2669    /// The tail of the graph after a trustworthy tally: fold losers, review,
2670    /// gate, merge, and persist.
2671    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2672        Box::pin(self.finish_after_tally_inner())
2673    }
2674
2675    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2676        // Before the losers are folded: their branches are what the graft
2677        // reads from.
2678        self.graft().await?;
2679        if self.resource_halt()? {
2680            return Ok(());
2681        }
2682        self.fold_losers().await?;
2683        // Before review starts, and again right before the gate: a run's
2684        // review rounds can themselves take long enough for the base to move
2685        // a second time, and the gate is the one node whose "green" gets
2686        // acted on.
2687        self.sync_to_base().await?;
2688        if self.hold_base_sync().await? || self.resource_halt()? {
2689            return Ok(());
2690        }
2691        if self.state.status == RunStatus::AlreadyInBase {
2692            return Ok(());
2693        }
2694        self.review_loop().await?;
2695        if self.resource_halt()? {
2696            return Ok(());
2697        }
2698        self.sync_to_base().await?;
2699        if self.hold_base_sync().await? || self.resource_halt()? {
2700            return Ok(());
2701        }
2702        if self.state.status == RunStatus::AlreadyInBase {
2703            return Ok(());
2704        }
2705        self.gate().await?;
2706        self.merge().await?;
2707        if self.resource_halt()? {
2708            return Ok(());
2709        }
2710        self.state.save()?;
2711        Ok(())
2712    }
2713
2714    // ---------------------------------------------------------------- prep
2715
2716    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2717    /// run with the step and its output in the event; it is never swallowed.
2718    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2719    /// resume starts over instead of finding candidates and missing seats.
2720    async fn setup_seat_worktree(
2721        &mut self,
2722        repo: &Path,
2723        wt: &Path,
2724        in_prep: bool,
2725        coordination: Option<&crate::repo_lock::SeatLease>,
2726    ) -> Result<()> {
2727        let result = match ensure_setup_config(&mut self.state, repo).await {
2728            Ok(()) => {
2729                worktree_setup::prepare_with(
2730                    &self.state.config,
2731                    repo,
2732                    wt,
2733                    crate::build_target::Coordination::Held(coordination),
2734                )
2735                .await
2736            }
2737            Err(e) => Err(e),
2738        };
2739        if let Err(e) = result {
2740            git::worktree_remove_clean(repo, wt).await.ok();
2741            if in_prep {
2742                self.rollback_prep(repo).await;
2743            }
2744            self.state.status = RunStatus::Blocked;
2745            self.state.event(
2746                "setup",
2747                format!("worktree setup failed in {}: {e:#}", wt.display()),
2748            );
2749            self.state.save()?;
2750            return Err(e);
2751        }
2752        Ok(())
2753    }
2754
2755    /// Undo everything `prep` created, so a resume re-runs it whole.
2756    async fn rollback_prep(&mut self, repo: &Path) {
2757        let root = self.state.worktree_root();
2758        for c in std::mem::take(&mut self.state.candidates) {
2759            if matches!(
2760                git::worktree_remove_clean(repo, &c.worktree).await,
2761                Ok(true)
2762            ) {
2763                git::branch_delete(repo, &c.branch).await.ok();
2764            } else {
2765                self.state.candidates.push(c);
2766            }
2767        }
2768        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2769        for j in 1..=seats {
2770            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2771                .await
2772                .ok();
2773        }
2774        for k in 1..=self.state.config.graph.advisors {
2775            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2776                .await
2777                .ok();
2778        }
2779    }
2780
2781    async fn prep(&mut self) -> Result<()> {
2782        if let Some(reason) = &self.state.prep_failure {
2783            bail!(
2784                "candidate preparation previously failed: {reason}; correct the source before retrying"
2785            );
2786        }
2787        if self
2788            .state
2789            .prep_complete
2790            .unwrap_or(!self.state.candidates.is_empty())
2791        {
2792            return Ok(());
2793        }
2794        let repo = self.state.repo.clone();
2795        // Includes rollback, config, refs, checkout creation and setup. No
2796        // repository mutation may precede the real shared lock acquisition.
2797        let _coordination = self.coordinate(&repo).await?;
2798        let base = self.state.base_commit.clone();
2799        let plan = self.state.sources.plan(&repo, &base).await?;
2800        self.rollback_prep(&repo).await;
2801        if !self.state.candidates.is_empty() {
2802            bail!(
2803                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2804            );
2805        }
2806        self.state.prep_complete = Some(false);
2807        self.state.status = RunStatus::Prep;
2808        self.state.save()?;
2809        let repo = self.state.repo.clone();
2810        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2811        let root = self.state.worktree_root();
2812        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2813
2814        // The hook is the write-time half of the blindness contract; the
2815        // presentation filter in `blind` is the half that cannot be bypassed.
2816        let hooks_dir = self.state.dir().join("hooks");
2817        if self.state.config.blind.commit_msg_hook {
2818            std::fs::create_dir_all(&hooks_dir)
2819                .with_context(|| format!("create {}", hooks_dir.display()))?;
2820            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2821            let path = hooks_dir.join("commit-msg");
2822            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2823            make_executable(&path)?;
2824            // Ref-counted rather than a plain idempotent set: with more than
2825            // one run able to be in flight in the same repository at once
2826            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2827            // true?" check cannot tell "another run of mine still needs
2828            // this" from "nobody does", and the run that happens to finish
2829            // first would disable the hook out from under a sibling still
2830            // relying on it.
2831            git::acquire_worktree_config(&repo).await?;
2832            self.state.enabled_worktree_config = true;
2833        }
2834
2835        // `[worktree] setup` hides its products per worktree, which needs the
2836        // same per-worktree config the hook does. Held until fold, like it.
2837        ensure_setup_config(&mut self.state, &repo).await?;
2838
2839        for (index, (spec, label)) in self
2840            .roles
2841            .implementers
2842            .clone()
2843            .into_iter()
2844            .zip(labels)
2845            .enumerate()
2846        {
2847            let branch = self.state.branch_for(label);
2848            let worktree = root.join(format!("cand-{label}"));
2849            // Persist intent before Git can leave a partially created tree.
2850            // Candidate registration follows setup, so it cannot inventory
2851            // crashes or refusals during creation itself.
2852            self.state.event(
2853                "prep-intent",
2854                serde_json::json!({
2855                    "branch": branch,
2856                    "worktree": worktree,
2857                    "start": start,
2858                    "picks": plan.picks,
2859                })
2860                .to_string(),
2861            );
2862            self.state.save()?;
2863            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2864            if self.state.config.blind.commit_msg_hook {
2865                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2866            }
2867            git::local_exclude(&worktree, "/.magi/").await?;
2868            if let Err(e) = worktree_setup::prepare_with(
2869                &self.state.config,
2870                &repo,
2871                &worktree,
2872                crate::build_target::Coordination::Held(_coordination.as_ref()),
2873            )
2874            .await
2875            {
2876                // Nothing of this prep may survive: a resume must start over,
2877                // not find half the candidates and skip the rest.
2878                git::worktree_remove_clean(&repo, &worktree).await.ok();
2879                git::branch_delete(&repo, &branch).await.ok();
2880                self.rollback_prep(&repo).await;
2881                self.state.status = RunStatus::Blocked;
2882                self.state
2883                    .event("prep", format!("worktree setup failed: {e:#}"));
2884                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2885                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2886                }
2887                self.state.save()?;
2888                return Err(e);
2889            }
2890            self.state.candidates.push(Candidate {
2891                index,
2892                label,
2893                agent: spec.id.clone(),
2894                branch,
2895                worktree,
2896                summary: String::new(),
2897                stat: String::new(),
2898                files: 0,
2899                commits: 0,
2900                empty: false,
2901                failed: None,
2902                verified_noop: None,
2903                duration_ms: 0,
2904                folded: false,
2905            });
2906            self.state.save()?;
2907            for pick in &plan.picks {
2908                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2909                {
2910                    self.state.status = RunStatus::Blocked;
2911                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2912                    self.state
2913                        .event("prep", format!("cannot apply referenced commit: {e}"));
2914                    self.state.save()?;
2915                    return Err(e);
2916                }
2917            }
2918        }
2919
2920        for j in 1..=self.roles.judges.len() {
2921            let wt = root.join(format!("judge-{j}"));
2922            if !wt.exists() {
2923                git::worktree_add_detached(&repo, &wt, &base).await?;
2924                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2925                    .await?;
2926            }
2927        }
2928
2929        // Disposable, detached checkouts for the design-deliberation stage's
2930        // advisor seats — the same shape as the judges' above, at the same
2931        // base commit, since advisors also only ever read. Sized off the
2932        // configured count directly rather than a resolved roster: unlike
2933        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2934        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2935        // `prep` has no `ResolvedRoles` field to read a count from here.
2936        if self.state.config.graph.advise {
2937            for k in 1..=self.state.config.graph.advisors {
2938                let wt = root.join(format!("advisor-{k}"));
2939                if !wt.exists() {
2940                    git::worktree_add_detached(&repo, &wt, &base).await?;
2941                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2942                        .await?;
2943                }
2944            }
2945        }
2946
2947        // A judge cannot tell it is looking at its own patch — the seats keep
2948        // separate conversations — but a panel that shares agents with the
2949        // field is less independent than it looks, and that is worth saying out
2950        // loud once per run rather than leaving it in the config.
2951        let authors: Vec<&str> = self
2952            .roles
2953            .implementers
2954            .iter()
2955            .map(|a| a.id.as_str())
2956            .collect();
2957        let overlap: Vec<String> = self
2958            .roles
2959            .judges
2960            .iter()
2961            .enumerate()
2962            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2963            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2964            .collect();
2965        if !overlap.is_empty() {
2966            let note = format!(
2967                "{} also authored a candidate; blind, but the panel is less \
2968                 independent than {} distinct agents would be",
2969                overlap.join(", "),
2970                self.roles.judges.len()
2971            );
2972            self.state.event("prep", note);
2973        }
2974
2975        self.state.event(
2976            "prep",
2977            format!(
2978                "{} candidates, {} judges, base {} ({})",
2979                self.state.candidates.len(),
2980                self.roles.judges.len(),
2981                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2982                self.state.base_branch
2983            ),
2984        );
2985        self.state.prep_complete = Some(true);
2986        self.state.status = RunStatus::Implementing;
2987        self.state.save()?;
2988        Ok(())
2989    }
2990
2991    // -------------------------------------------------------------- advise
2992
2993    /// The design-deliberation stage: independent, read-only advisor seats
2994    /// each sketch a design before any implementer touches the repository,
2995    /// and (when at least one produced a usable proposal) a synthesis seat
2996    /// blends them into a brief `implement` carries in every candidate's
2997    /// prompt.
2998    ///
2999    /// `[graph] advise` is the on/off switch, on by default; `[graph]
3000    /// advisors` is the proposal count. Everything here is best-effort and
3001    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
3002    /// that cannot reach quota, or a synthesis seat that produced nothing
3003    /// usable all leave `implement` exactly as it was before this stage
3004    /// existed — the task instruction alone — rather than failing the whole
3005    /// competition over an enrichment stage. Every outcome is still recorded
3006    /// as an event, so a run that got nothing from this stage says why.
3007    ///
3008    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
3009    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
3010    /// resumed run whose stage failed would re-run it, and re-spend the
3011    /// agent calls, on every reentry before `implement`.
3012    ///
3013    /// Also skipped once any candidate shows implementation progress — the
3014    /// exact predicate `implement` itself uses to decide a candidate is no
3015    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
3016    /// is not enough: a run created by an older binary that predates this
3017    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
3018    /// an already-`Implementing`-or-later run under this build would
3019    /// otherwise walk straight back through `prep` (a no-op once candidates
3020    /// exist) into this node and spawn every advisor seat against worktrees
3021    /// `prep` never recreated — after implementation has already started,
3022    /// which is exactly the invariant this stage exists to guarantee.
3023    async fn advise(&mut self) -> Result<()> {
3024        let implement_untouched = self
3025            .state
3026            .candidates
3027            .iter()
3028            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
3029        if !self.state.config.graph.advise || self.state.advise_attempted {
3030            return Ok(());
3031        }
3032        if !implement_untouched {
3033            self.state.event(
3034                "advise",
3035                "skipping the design-deliberation stage: at least one \
3036                 candidate already shows implementation progress, so this \
3037                 run is past the point the stage exists to run before"
3038                    .to_owned(),
3039            );
3040            self.state.advise_attempted = true;
3041            self.state.save()?;
3042            return Ok(());
3043        }
3044        let run_id = self.state.id.clone();
3045        let prompts = self.state.config.prompts.clone();
3046        let instruction = self.state.instruction.clone();
3047        let language = self.state.config.graph.language.clone();
3048        let root = self.state.worktree_root();
3049        let n = self.state.config.graph.advisors;
3050        let where_recorded = self.state.dir().join("run.json");
3051
3052        let seats = match self.state.config.advisors() {
3053            Ok(seats) if !seats.is_empty() => seats,
3054            Ok(_) => {
3055                self.state.event(
3056                    "advise",
3057                    format!(
3058                        "[graph] advisors is 0; skipping the design-deliberation \
3059                         stage and continuing without a synthesis brief (see {})",
3060                        where_recorded.display()
3061                    ),
3062                );
3063                self.state.advise_attempted = true;
3064                self.state.save()?;
3065                return Ok(());
3066            }
3067            Err(e) => {
3068                self.state.event(
3069                    "advise",
3070                    format!(
3071                        "could not resolve advisor seats ({e:#}); continuing \
3072                         without a design-deliberation brief (see {})",
3073                        where_recorded.display()
3074                    ),
3075                );
3076                self.state.advise_attempted = true;
3077                self.state.save()?;
3078                return Ok(());
3079            }
3080        };
3081
3082        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3083        let artifacts = agent::artifacts_dir(&self.state.dir());
3084        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
3085
3086        let mut jobs = Vec::new();
3087        for (i, spec) in seats.iter().cloned().enumerate() {
3088            let seat_key = format!("advisor-{}", i + 1);
3089            let seat = self.seat(&seat_key, &spec.id);
3090            jobs.push(SeatJob {
3091                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
3092                spec,
3093                seat,
3094                cwd: worktrees[i % worktrees.len()].clone(),
3095                timeout,
3096                allow_write: false,
3097                sessions: false,
3098                artifacts: artifacts.clone(),
3099                stem: seat_key,
3100                handover: None,
3101            });
3102        }
3103
3104        self.state.event(
3105            "advise",
3106            format!(
3107                "{} advisor seat(s) sketching a design in parallel",
3108                jobs.len()
3109            ),
3110        );
3111        let mut quota_losses = Vec::new();
3112        let cache = self.state.config.cache_dir();
3113        let ctx = WaveCtx {
3114            carry_seats: false,
3115            pauses: Some((&self.pause, &self.interrupt)),
3116            run: &run_id,
3117            node: "advise",
3118            prompts: &prompts,
3119            cache: cache.as_deref(),
3120            round: None,
3121        };
3122        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
3123        let results = ask_json_wave::<Proposal>(
3124            jobs,
3125            Arc::clone(&self.sem),
3126            self.state.config.graph.retries,
3127            &advisor_roster,
3128            &ctx,
3129            &mut quota_losses,
3130            &mut self.state,
3131            &|p: &Proposal| p.validate(),
3132        )
3133        .await;
3134        if self.state.resource_block.is_some() {
3135            return self.stop_for_resource();
3136        }
3137        self.state.quota.extend(quota_losses);
3138
3139        let mut records = Vec::with_capacity(results.len());
3140        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
3141            let agent_id = seat.agent.clone();
3142            self.state.seats.insert(seat.key.clone(), seat);
3143            match res {
3144                Ok((proposal, out)) => {
3145                    self.state
3146                        .event("advise", format!("advisor-{} proposed a design", i + 1));
3147                    records.push(advise::AdvisorRecord::proposed(
3148                        i + 1,
3149                        agent_id,
3150                        proposal,
3151                        out.duration_ms,
3152                    ));
3153                }
3154                Err(e) => {
3155                    self.state.event(
3156                        "advise",
3157                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3158                    );
3159                    records.push(advise::AdvisorRecord::failed(
3160                        i + 1,
3161                        agent_id,
3162                        e.to_string(),
3163                    ));
3164                }
3165            }
3166        }
3167
3168        let mut advice = advise::Advice {
3169            records,
3170            synthesis: None,
3171        };
3172        if advice.proposals().is_empty() {
3173            self.state.event(
3174                "advise",
3175                "no advisor produced a usable proposal; continuing without a \
3176                 synthesis brief"
3177                    .to_owned(),
3178            );
3179        } else {
3180            match self
3181                .synthesize_brief(
3182                    &advice,
3183                    &instruction,
3184                    &language,
3185                    &worktrees[0],
3186                    &artifacts,
3187                    &run_id,
3188                    &prompts,
3189                    cache.as_deref(),
3190                )
3191                .await
3192            {
3193                Ok(Some(text)) => {
3194                    self.state.event(
3195                        "advise",
3196                        "synthesized a design brief for the implementer".to_owned(),
3197                    );
3198                    advice.synthesis = Some(text);
3199                }
3200                Ok(None) => {
3201                    self.state.event(
3202                        "advise",
3203                        "the synthesis seat produced nothing usable; continuing \
3204                         without a design brief"
3205                            .to_owned(),
3206                    );
3207                }
3208                Err(e) => {
3209                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3210                        return Err(e);
3211                    }
3212                    self.state.event(
3213                        "advise",
3214                        format!("could not synthesize a design brief: {e:#}"),
3215                    );
3216                }
3217            }
3218        }
3219        advise::apply_reflection(&mut advice);
3220
3221        self.state.advice = Some(advice);
3222        self.state.advise_attempted = true;
3223        self.state.save()?;
3224        Ok(())
3225    }
3226
3227    /// The synthesis seat: reads every advisor's proposal and blends them
3228    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3229    /// out of [`Runner::advise`] only for readability — it is not called
3230    /// anywhere else.
3231    ///
3232    /// Picked the same way [`crate::talk`]'s standing conversation and
3233    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3234    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3235    /// order (a claude seat, else the first runnable agent in roster order)
3236    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3237    /// in [`crate::config`] for why a dedicated field exists here at all.
3238    #[allow(clippy::too_many_arguments)]
3239    async fn synthesize_brief(
3240        &mut self,
3241        advice: &advise::Advice,
3242        instruction: &str,
3243        language: &str,
3244        cwd: &Path,
3245        artifacts: &Path,
3246        run_id: &str,
3247        prompts: &Prompts,
3248        cache: Option<&Path>,
3249    ) -> Result<Option<String>> {
3250        let chain = agent::pick_chain(
3251            &self.state.config.agents,
3252            self.state.config.roles.synthesizer.as_ref(),
3253            &agent::installed,
3254            "synthesizer",
3255        )?;
3256        let proposals = advice.proposals();
3257        let mut prompt = prompt::with_overlay(
3258            prompt::synthesize_brief(instruction, &proposals, language),
3259            prompts.overlay("advise"),
3260        );
3261        if cache.is_some() {
3262            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3263            // below — see `prompt::build_cache_note`'s doc for why telling a
3264            // read-only seat to build through the shared cache is exactly how
3265            // a sandbox's write refusal gets misread as a defect.
3266            prompt.push('\n');
3267            prompt.push_str(&prompt::build_cache_note("advise", false));
3268        }
3269        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3270        // Each id is tried once, in order; a quota hit, error or unusable
3271        // answer moves to the next. The seat is single-turn (`sessions:
3272        // false`) and the prompt is the whole context, so a fallback agent
3273        // needs nothing carried over.
3274        let mut last = None;
3275        for (n, spec) in chain.iter().enumerate() {
3276            if n > 0 {
3277                self.state
3278                    .event("advise", format!("synthesis falling back to {}", spec.id));
3279            }
3280            let mut seat = self.seat("advise-synthesis", &spec.id);
3281            let wait = self.repository_wait();
3282            let outcome = wait
3283                .scope(agent::invoke(
3284                    spec,
3285                    &mut seat,
3286                    &Invocation {
3287                        coordination: self.state.config.coordination.as_ref(),
3288                        fetched_base: None,
3289                        cwd,
3290                        prompt: &prompt,
3291                        timeout,
3292                        allow_write: false,
3293                        sessions: false,
3294                        artifacts,
3295                        stem: &if n == 0 {
3296                            "advise-synthesis".to_owned()
3297                        } else {
3298                            format!("advise-synthesis-{}", spec.id)
3299                        },
3300                        run: run_id,
3301                        node: "advise",
3302                        cache_dir: None,
3303                        attachments: &[],
3304                        writable: &[],
3305                    },
3306                ))
3307                .await;
3308            if outcome.is_ok() {
3309                self.state.seats.insert(seat.key.clone(), seat);
3310            }
3311            let advance = agent::chain_advances(&outcome);
3312            last = Some(outcome);
3313            if !advance {
3314                break;
3315            }
3316        }
3317        // Exhausted: the last attempt's result is what a single failed seat
3318        // would have produced.
3319        let out = last.expect("a chain holds at least one agent")?;
3320        if !out.usable() {
3321            return Ok(None);
3322        }
3323        let text =
3324            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3325        Ok((!text.trim().is_empty()).then_some(text))
3326    }
3327
3328    // ----------------------------------------------------------- implement
3329
3330    async fn implement(&mut self) -> Result<()> {
3331        self.persist_candidates().await?;
3332        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3333        // agent files with `magi task add` name the run that paid for it. The
3334        // prompt overlay is cloned alongside it because the waves borrow it
3335        // while `self` is mutably borrowed by the node's own bookkeeping.
3336        let run_id = self.state.id.clone();
3337        let prompts = self.state.config.prompts.clone();
3338        let todo: Vec<usize> = self
3339            .state
3340            .candidates
3341            .iter()
3342            .enumerate()
3343            .filter(|(_, c)| {
3344                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3345                    && c.failed.is_none()
3346                    && !c.empty
3347            })
3348            .map(|(i, _)| i)
3349            .collect();
3350        if todo.is_empty() {
3351            return self.after_implement();
3352        }
3353        self.state.status = RunStatus::Implementing;
3354
3355        let language = self.state.config.graph.language.clone();
3356        let github_language = self.state.config.graph.github_language.clone();
3357        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3358        let sessions = self.state.config.graph.sessions;
3359        let artifacts = agent::artifacts_dir(&self.state.dir());
3360        // The design-deliberation stage's blended brief, when `advise` found
3361        // one — carried into every implementer's prompt the same way
3362        // regardless of which candidate it is.
3363        let brief = self
3364            .state
3365            .advice
3366            .as_ref()
3367            .and_then(|a| a.synthesis.as_deref())
3368            .map(str::to_owned);
3369        let attachments = self.state.attachments.clone();
3370
3371        let mut jobs = Vec::new();
3372        for &i in &todo {
3373            let (index, label, worktree) = {
3374                let c = &self.state.candidates[i];
3375                (c.index, c.label, c.worktree.clone())
3376            };
3377            let spec = self.roles.implementers[index].clone();
3378            let seat_key = format!("impl-{label}");
3379            let seat = self.seat(&seat_key, &spec.id);
3380            let instruction = seeded_instruction(&self.state);
3381            jobs.push(SeatJob {
3382                spec,
3383                seat,
3384                prompt: prompt::implement_in(
3385                    &instruction,
3386                    &worktree.to_string_lossy(),
3387                    &language,
3388                    &github_language,
3389                    brief.as_deref(),
3390                    &attachments,
3391                ),
3392                cwd: worktree,
3393                timeout,
3394                allow_write: true,
3395                sessions,
3396                artifacts: artifacts.clone(),
3397                stem: format!("impl-{label}"),
3398                handover: None,
3399            });
3400        }
3401
3402        self.state.event(
3403            "implement",
3404            format!("{} candidates in parallel", jobs.len()),
3405        );
3406        // Kept so a seat whose CLI hung up can be asked again from the same
3407        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3408        // can update a seat's own entry once a fallback agent takes it over —
3409        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3410        // whichever agent actually answered, not the one that quota'd out.
3411        let mut sent = jobs.clone();
3412        // Where each seat's checkout stood before its turn. A reply is judged
3413        // against this, never against the run's base: a tree that carries an
3414        // inherited patch is ahead of the base before the seat does anything.
3415        let mut baselines = Vec::with_capacity(sent.len());
3416        for (job, &i) in sent.iter().zip(&todo) {
3417            baselines.push((
3418                self.state.candidates[i].label,
3419                git::rev_parse(&job.cwd, "HEAD").await.ok(),
3420            ));
3421        }
3422        let cache = self.state.config.cache_dir();
3423        let ctx = WaveCtx {
3424            carry_seats: false,
3425            pauses: Some((&self.pause, &self.interrupt)),
3426            run: &run_id,
3427            node: "implement",
3428            prompts: &prompts,
3429            cache: cache.as_deref(),
3430            round: None,
3431        };
3432        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3433        if !wave_blocked(&results) {
3434            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3435                .await;
3436            self.retry_unstarted(&mut results, &sent, &baselines, &prompts, &run_id)
3437                .await?;
3438            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3439                .await?;
3440            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3441                .await;
3442        }
3443        // Do not finalize failed candidates when the entire wave needs machine
3444        // recovery: leaving them pending resumes this node with its work intact.
3445        if !results.is_empty()
3446            && results
3447                .iter()
3448                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3449        {
3450            let losses: Vec<_> = results
3451                .iter()
3452                .map(|(_, seat, out)| {
3453                    let AgentOutcome::Quota(o) = out else {
3454                        unreachable!()
3455                    };
3456                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3457                })
3458                .collect();
3459            self.state.quota.extend(losses.clone());
3460            for (_, seat, _) in results {
3461                self.state.seats.insert(seat.key.clone(), seat);
3462            }
3463            for &i in &todo {
3464                let label = self.state.candidates[i].label;
3465                self.state.interrupted_implementations.insert(label);
3466                self.state
3467                    .candidate_preservation
3468                    .insert(label, "machine outage awaiting persistence".into());
3469            }
3470            // Preserve partial edits too, while keeping every interrupted seat
3471            // pending even when its tree already contains an inherited patch.
3472            block_machine_outage(&mut self.state, "implement", &losses);
3473            self.state.save()?;
3474            self.persist_candidates().await?;
3475            for &i in &todo {
3476                self.state
3477                    .interrupted_implementations
3478                    .insert(self.state.candidates[i].label);
3479            }
3480            return self.stop_for_resource();
3481        }
3482        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3483
3484        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3485            && results
3486                .iter()
3487                .any(|(_, _, out)| FailClass::of(out).is_some());
3488        let base_commit = self.state.base_commit.clone();
3489        let blind_cfg = self.state.config.blind.clone();
3490        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3491        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3492            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3493                // Executed turns interrupted by disk pressure already carry
3494                // a preservation barrier from wave. Admission-only waits do
3495                // not. Keep the interrupted seat's session for recovery too.
3496                if self
3497                    .state
3498                    .candidate_preservation
3499                    .contains_key(&self.state.candidates[i].label)
3500                {
3501                    self.state.seats.insert(seat.key.clone(), seat);
3502                }
3503                continue;
3504            }
3505            let seat_key = seat.key.clone();
3506            // A quota fallback (`resume_seat_handovers`) may have handed this
3507            // seat to a different agent than the one `prep` recorded on the
3508            // candidate; the stats tables and any later fixer-defaults-to-
3509            // winner's-author lookup must credit whoever actually answered —
3510            // unless every fallback also quota'd out, in which case nobody
3511            // actually answered and crediting the last agent tried would
3512            // erase every earlier agent's own quota loss from the stats
3513            // tables instead of just this one seat's.
3514            let agent = seat.agent.clone();
3515            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3516            self.state.seats.insert(seat.key.clone(), seat);
3517            let label = self.state.candidates[i].label;
3518            let worktree = self.state.candidates[i].worktree.clone();
3519            self.state.interrupted_implementations.remove(&label);
3520
3521            let (sanitized_summary, duration, failed, verified_claim) = match out {
3522                AgentOutcome::Ok(o) => {
3523                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3524                    let failed = (!o.usable()).then(|| {
3525                        if o.timed_out {
3526                            "agent timed out".to_owned()
3527                        } else {
3528                            format!(
3529                                "agent exited with {}",
3530                                crate::notices::exit_status(o.exit_code)
3531                            )
3532                        }
3533                    });
3534                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3535                    let verified_claim = match verified_noop_claim_in_worktree(
3536                        failed.is_none(),
3537                        &o.commands,
3538                        &text,
3539                        &worktree,
3540                        &base_commit,
3541                    )
3542                    .await
3543                    {
3544                        NoopClaimVerdict::Accepted => {
3545                            if matches!(
3546                                verdict::parse_verified_noop(&sanitized_summary),
3547                                Some(Ok(_))
3548                            ) {
3549                                Some(sanitized_summary.clone())
3550                            } else {
3551                                rejected_noops.push((
3552                                    label,
3553                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3554                                ));
3555                                None
3556                            }
3557                        }
3558                        NoopClaimVerdict::Rejected(reason) => {
3559                            rejected_noops.push((label, reason));
3560                            None
3561                        }
3562                        NoopClaimVerdict::Absent => None,
3563                    };
3564                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3565                }
3566                // Left un-resumed by `resume_undelivered` (a dirty tree
3567                // already rescues the work, or there was no session left to
3568                // resume into) — reported like the ordinary failure it is,
3569                // never as if `o.text` (the CLI's raw error JSON) were an
3570                // answer.
3571                AgentOutcome::Dropped(o) => {
3572                    let why = o
3573                        .dropped
3574                        .as_ref()
3575                        .map(|d| d.why.as_str())
3576                        .unwrap_or("the CLI ended the stream without delivering its answer");
3577                    (
3578                        String::new(),
3579                        o.duration_ms,
3580                        Some(format!("the CLI dropped the stream ({why})")),
3581                        None,
3582                    )
3583                }
3584                AgentOutcome::Quota(o) => {
3585                    self.state.quota.push(QuotaLoss::from_report(
3586                        seat_key,
3587                        "implement",
3588                        o.quota.as_ref(),
3589                    ));
3590                    (
3591                        String::new(),
3592                        o.duration_ms,
3593                        Some("rate limited (quota); produced no change".to_owned()),
3594                        None,
3595                    )
3596                }
3597                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3598                    (String::new(), 0, Some(e), None)
3599                }
3600            };
3601
3602            // Save every completed turn before any fallible Git operation. A failed
3603            // rescue must not erase the reply or prevent collection of other seats.
3604            let c = &mut self.state.candidates[i];
3605            if !exhausted_the_fallback_chain {
3606                c.agent = agent;
3607            }
3608            c.summary = sanitized_summary;
3609            c.duration_ms = duration;
3610            c.failed = failed;
3611            c.verified_noop = verified_claim;
3612            self.state
3613                .candidate_preservation
3614                .insert(label, "awaiting persistence".to_owned());
3615        }
3616        self.state.save()?;
3617        self.persist_candidates().await?;
3618
3619        let mut recorded_rejection = false;
3620        for (label, reason) in rejected_noops {
3621            if self.state.interrupted_implementations.contains(&label) {
3622                continue;
3623            }
3624            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3625                && c.empty
3626            {
3627                c.verified_noop = None;
3628                c.failed
3629                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3630                self.state.event(
3631                    "implement",
3632                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3633                );
3634                recorded_rejection = true;
3635            }
3636        }
3637        if recorded_rejection {
3638            self.state.save()?;
3639        }
3640
3641        if resource_blocked {
3642            return self.stop_for_resource();
3643        }
3644        if selected_failed {
3645            self.state.status = RunStatus::Blocked;
3646            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3647            self.state.save()?;
3648            bail!(
3649                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3650            );
3651        }
3652        self.after_implement()
3653    }
3654
3655    /// Retry only persistence after a completed implementation turn.
3656    async fn persist_candidates(&mut self) -> Result<()> {
3657        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3658        for label in labels {
3659            let i = self
3660                .state
3661                .candidates
3662                .iter()
3663                .position(|c| c.label == label)
3664                .context("pending candidate is missing")?;
3665            let c = self.state.candidates[i].clone();
3666            let interrupted = self.state.interrupted_implementations.contains(&label);
3667            let result = async {
3668                let wait = crate::repo_lock::WaitPolicy::new(
3669                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3670                    || false,
3671                );
3672                let _coordination =
3673                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3674                // Best effort evidence requires no index writes. A successful snapshot
3675                // never authorizes removal of a tree whose rescue failed.
3676                if let Err(e) = git::snapshot_uncommitted(
3677                    &c.worktree,
3678                    &self
3679                        .state
3680                        .dir()
3681                        .join("artifacts")
3682                        .join(format!("candidate-{label}-recovery")),
3683                )
3684                .await
3685                {
3686                    self.state.event(
3687                        "preserve",
3688                        format!("candidate {label} snapshot incomplete: {e:#}"),
3689                    );
3690                }
3691                let rescued = git::rescue_commit(
3692                    &c.worktree,
3693                    &format!("magi: candidate {label} (uncommitted work)"),
3694                )
3695                .await?;
3696                self.state.note_withheld("implement", &rescued.withheld);
3697                let base = &self.state.base_commit;
3698                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3699                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3700                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3701                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3702                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3703                if c.empty && commits > 0 && !patch.trim().is_empty()
3704                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3705                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3706                        || self.state.tally.is_some())
3707                {
3708                    // Keep the old classification and pending marker so every
3709                    // retry stops too. Retain decisions as recovery evidence;
3710                    // only a supported recovery operation may replace them.
3711                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3712                }
3713                let c = &mut self.state.candidates[i];
3714                c.commits = commits;
3715                c.stat = stat;
3716                c.files = files;
3717                let no_changes = commits == 0 || patch.trim().is_empty();
3718                c.empty = no_changes && !interrupted;
3719                if interrupted && no_changes {
3720                    c.failed = None;
3721                    c.verified_noop = None;
3722                }
3723                if !c.empty {
3724                    c.failed = None;
3725                    c.verified_noop = None;
3726                }
3727                self.state.event(
3728                    "preserve",
3729                    format!("candidate {label}: {files} files, {commits} commits"),
3730                );
3731                Ok::<_, anyhow::Error>(())
3732            }
3733            .await;
3734            match result {
3735                Ok(()) => {
3736                    self.state.candidate_preservation.remove(&label);
3737                    if !interrupted || self.state.candidates[i].files > 0 {
3738                        self.state.interrupted_implementations.remove(&label);
3739                    }
3740                }
3741                Err(e) => {
3742                    let reason = format!("candidate {label} preservation failed: {e:#}");
3743                    self.state.event("preserve", &reason);
3744                    self.state.candidate_preservation.insert(label, reason);
3745                }
3746            }
3747            if self.state.candidate_preservation.is_empty()
3748                && self.state.status == RunStatus::Blocked
3749                && self.state.candidates.iter().all(|c| c.failed.is_none())
3750            {
3751                // Persist the recovered phase with the cleared pending marker;
3752                // a crash between saves must not turn this into a selected-seat
3753                // failure hold on the next resume.
3754                self.state.status = RunStatus::Implementing;
3755                self.state.event(
3756                    "preserve",
3757                    "candidate persistence recovered; implementation can continue",
3758                );
3759            }
3760            self.state.save()?;
3761        }
3762        if !self.state.candidate_preservation.is_empty() {
3763            self.state.status = RunStatus::Blocked;
3764            self.state.save()?;
3765            bail!(
3766                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3767            );
3768        }
3769        Ok(())
3770    }
3771
3772    /// Ask again, once, for work a CLI did and then failed to hand over.
3773    ///
3774    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3775    /// status with an empty response and a usage report showing output tokens,
3776    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3777    /// seven minutes and 14,267 output tokens that arrived as an empty
3778    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3779    ///
3780    /// Two conditions, and both matter:
3781    ///
3782    /// - **Only when the tree is untouched.** Often the agent has already
3783    ///   written its files and only the closing message was lost; the rescue
3784    ///   commit below picks that up and there is nothing to ask for. Re-asking
3785    ///   then would pay for a second implementation of work already on disk.
3786    /// - **Once.** A CLI that drops one stream can drop the next, and this
3787    ///   node is the most expensive in the graph.
3788    ///
3789    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3790    /// dropped reply still carried its `conversation_id`, so the seat is asked
3791    /// to finish what it was doing rather than sent the whole task again. It
3792    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3793    /// node's - for the same reason a re-ranked judge does: restating finished
3794    /// work is not the work.
3795    ///
3796    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3797    /// same way until it resets, while an abandoned conversation is still
3798    /// there to be picked up.
3799    async fn resume_undelivered(
3800        &mut self,
3801        results: &mut [(usize, SeatState, AgentOutcome)],
3802        sent: &[SeatJob],
3803        prompts: &Prompts,
3804        run_id: &str,
3805    ) {
3806        for (wi, seat, out) in results.iter_mut() {
3807            let Some(dropped) = (match &*out {
3808                AgentOutcome::Dropped(o) => o.dropped.clone(),
3809                _ => None,
3810            }) else {
3811                continue;
3812            };
3813            let Some(job) = sent.get(*wi) else { continue };
3814            // Already on disk? Then only the closing message was lost.
3815            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3816                self.state.event(
3817                    "implement",
3818                    format!(
3819                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3820                         work is in the tree",
3821                        seat.key, dropped.output_tokens, dropped.why
3822                    ),
3823                );
3824                continue;
3825            }
3826            // The re-ask only makes sense as a resume: `resume_after_drop`
3827            // says nothing about the task, trusting the seat to still hold it.
3828            // Without a session to resume — sessions disabled, or this CLI's
3829            // drop shape happened not to carry a session id — that prompt
3830            // would open a brand-new conversation with no context at all,
3831            // which is worse than leaving this as the ordinary failure it
3832            // already is.
3833            if !has_context(&job.spec, seat, job.sessions) {
3834                self.state.event(
3835                    "implement",
3836                    format!(
3837                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3838                         is no session left to resume",
3839                        seat.key, dropped.output_tokens, dropped.why
3840                    ),
3841                );
3842                continue;
3843            }
3844            self.state.event(
3845                "implement",
3846                format!(
3847                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3848                     conversation",
3849                    seat.key, dropped.output_tokens, dropped.why
3850                ),
3851            );
3852            let mut retry = job.clone();
3853            retry.seat = seat.clone();
3854            retry.prompt = prompt::resume_after_drop(&dropped.why);
3855            retry.timeout = retry_budget(job.timeout, true);
3856            retry.stem = format!("{}-resume", job.stem);
3857            let cache = self.state.config.cache_dir();
3858            let ctx = WaveCtx {
3859                carry_seats: false,
3860                pauses: Some((&self.pause, &self.interrupt)),
3861                run: run_id,
3862                node: "implement",
3863                prompts,
3864                cache: cache.as_deref(),
3865                round: None,
3866            };
3867            let (resumed_seat, resumed) =
3868                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3869            *seat = resumed_seat;
3870            *out = resumed;
3871        }
3872    }
3873
3874    /// Fall an implement seat through to the next untried agent in the
3875    /// implementer roster when it lost to quota — or, since the handover was
3876    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3877    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3878    /// quota path itself being unchanged — instead of leaving the
3879    /// seat's loss final the moment one agent's account runs dry.
3880    ///
3881    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3882    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3883    /// truncates to the single slot rotation picked, so a solo task whose one
3884    /// implementer hits quota mid-run used to have nothing else to try. This
3885    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3886    /// unrotated roster — which is the only place the *other* candidates in
3887    /// the machine's roster still exist once `implementers` has been cut down
3888    /// to size.
3889    ///
3890    /// Walks forward from just past the seat's own original position in the
3891    /// roster, never wrapping back to the front: a later candidate slot (say
3892    /// `beta`, the roster's second entry) must fall through to the *next*
3893    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3894    /// almost certainly a different candidate's own agent already — and once
3895    /// the roster's tail is exhausted there is nothing left to fall through
3896    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3897    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3898    /// let this retry that id forever. The loop keeps falling through until
3899    /// an attempt lands something other than `Quota` or the roster's tail
3900    /// runs out of untried ids, at which point the seat is left exactly as
3901    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3902    /// `QuotaLoss` recorded, the candidate failed/empty.
3903    ///
3904    /// `sent` is taken mutably and updated with the fallback agent's spec:
3905    /// `resume_unconfirmed_commands`, which runs after this and also reads
3906    /// `sent`, must see whichever agent actually ended up answering the seat
3907    /// — reading the stale, original spec there would check session
3908    /// eligibility against the wrong CLI and could hand a fallback agent's
3909    /// session id to the agent that just lost the seat to quota.
3910    ///
3911    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3912    /// — `self.seat` only reuses state when the agent id is unchanged, so
3913    /// handing it a different id already gets this for free. Reusing the old
3914    /// seat would resume a different CLI's session as if it were a
3915    /// continuation of this one.
3916    ///
3917    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3918    /// a quota loss cuts an agent off mid-turn, so anything already in the
3919    /// tree is unfinished work, not a completed candidate a re-ask would pay
3920    /// for twice. A dirty tree is rescued into a commit first (the same
3921    /// neutral-identity rescue `implement`'s own outcome loop gives every
3922    /// candidate) so the next agent starts clean.
3923    ///
3924    /// The new agent gets the implementer's full prompt and full
3925    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3926    /// it has no session and no context, and is implementing the task from
3927    /// nothing, unlike a resumed drop which is only restating work already
3928    /// done.
3929    ///
3930    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3931    /// `implement` event, never into `self.state.quota` — that is what
3932    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3933    /// go unspent, and a seat that ultimately recovered on its second or
3934    /// third agent is not the stalled panel that check exists to catch. Only
3935    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3936    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3937    /// outcome loop already has — this helper never pushes to it itself.
3938    async fn resume_seat_handovers(
3939        &mut self,
3940        results: &mut [(usize, SeatState, AgentOutcome)],
3941        sent: &mut [SeatJob],
3942        prompts: &Prompts,
3943        run_id: &str,
3944    ) -> Result<()> {
3945        let instruction = seeded_instruction(&self.state);
3946        let language = self.state.config.graph.language.clone();
3947        let github_language = self.state.config.graph.github_language.clone();
3948        let brief = self
3949            .state
3950            .advice
3951            .as_ref()
3952            .and_then(|a| a.synthesis.as_deref())
3953            .map(str::to_owned);
3954        let attachments = self.state.attachments.clone();
3955        for (wi, seat, out) in results.iter_mut() {
3956            // Who holds the other candidate seats of this wave right now
3957            // (earlier handovers already written back to `sent`).
3958            let others: BTreeSet<String> = sent
3959                .iter()
3960                .enumerate()
3961                .filter(|(j, _)| j != wi)
3962                .map(|(_, j)| j.spec.id.clone())
3963                .collect();
3964            let Some(job) = sent.get_mut(*wi) else {
3965                continue;
3966            };
3967            // Where the seat's own original agent sits in the roster — the
3968            // fallback walk starts just past here, never at the front, so a
3969            // later candidate slot's quota loss does not fall back onto an
3970            // earlier slot's own agent.
3971            let start = self
3972                .roles
3973                .implementer_roster
3974                .iter()
3975                .position(|s| s.id == job.spec.id)
3976                .unwrap_or(0);
3977            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3978            let mut fallback_attempt = 0usize;
3979            let mut prev: Option<FailClass> = None;
3980            while let Some(cur) = FailClass::of(&*out) {
3981                if !should_hand_over(prev.as_ref(), &cur) {
3982                    break;
3983                }
3984                let Some(next) =
3985                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3986                        .cloned()
3987                else {
3988                    break;
3989                };
3990                tried.insert(next.id.clone());
3991                fallback_attempt += 1;
3992
3993                let coordination = self.coordinate(&job.cwd).await?;
3994                if let Ok(r) = git::rescue_commit(
3995                    &job.cwd,
3996                    &format!(
3997                        "magi: candidate {} (uncommitted work before {} fallback)",
3998                        seat.key,
3999                        if cur == FailClass::Quota {
4000                            "quota"
4001                        } else {
4002                            "handover"
4003                        }
4004                    ),
4005                )
4006                .await
4007                {
4008                    self.state.note_withheld("implement", &r.withheld);
4009                }
4010                drop(coordination);
4011
4012                record_handover(
4013                    &mut self.state,
4014                    "implement",
4015                    &seat.key,
4016                    &seat.agent,
4017                    &next.id,
4018                    &cur,
4019                    &fail_reason(&*out),
4020                );
4021                prev = Some(cur.clone());
4022
4023                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
4024                self.state.seats.insert(seat.key.clone(), new_seat.clone());
4025                // Kept in sync on `sent` itself, not just the local retry: a
4026                // later helper (`resume_unconfirmed_commands`) reads `sent`
4027                // after this one returns and must see whichever agent is now
4028                // occupying the seat, not the one that just quota'd out —
4029                // otherwise it would judge session/continuation eligibility
4030                // by the wrong CLI and could resend a fallback's session id
4031                // to the agent that lost it the seat in the first place.
4032                job.spec = next.clone();
4033                let mut retry = job.clone();
4034                retry.seat = new_seat;
4035                retry.prompt = prompt::implement_in(
4036                    &instruction,
4037                    &job.cwd.to_string_lossy(),
4038                    &language,
4039                    &github_language,
4040                    brief.as_deref(),
4041                    &attachments,
4042                );
4043                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
4044                let cache = self.state.config.cache_dir();
4045                let ctx = WaveCtx {
4046                    carry_seats: false,
4047                    pauses: Some((&self.pause, &self.interrupt)),
4048                    run: run_id,
4049                    node: "implement",
4050                    prompts,
4051                    cache: cache.as_deref(),
4052                    round: None,
4053                };
4054                let (fallback_seat, fallback_out) = run_one(
4055                    retry,
4056                    Arc::clone(&self.sem),
4057                    &ctx,
4058                    &mut self.state,
4059                    fallback_attempt,
4060                )
4061                .await;
4062                *seat = fallback_seat;
4063                *out = fallback_out;
4064            }
4065        }
4066        Ok(())
4067    }
4068
4069    /// Ask an implement seat's own CLI to confirm what it started, once, when
4070    /// its reply reported a command whose completion status it never
4071    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
4072    /// that does and does not mean.
4073    ///
4074    /// The completion contract this task asks for, extended to `implement`
4075    /// with the same signal `continue_fix_report` reads for the fixer,
4076    /// rather than a keyword search over the reply or a hard requirement on
4077    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
4078    /// a candidate's CLI turn ended cleanly while a test run it had started
4079    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
4080    /// named in it at all is untouched by this: `commands` is empty, so
4081    /// there is nothing to be unconfirmed.
4082    ///
4083    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
4084    /// this is not about recovering edits that might already be on disk, it
4085    /// is about a result the seat itself never vouched for, which resuming
4086    /// asks for regardless of what the tree already holds. Bounded to one
4087    /// attempt for the same reason `resume_undelivered` is — this is the
4088    /// most expensive node in the graph — and a seat that still cannot
4089    /// confirm on that attempt is left as whatever its (possibly still
4090    /// unconfirmed) reply says; this does not invent a new "failed" reason
4091    /// for a candidate that otherwise produced a real, committed change.
4092    async fn resume_unconfirmed_commands(
4093        &mut self,
4094        results: &mut [(usize, SeatState, AgentOutcome)],
4095        sent: &[SeatJob],
4096        prompts: &Prompts,
4097        run_id: &str,
4098    ) {
4099        for (wi, seat, out) in results.iter_mut() {
4100            let AgentOutcome::Ok(o) = &*out else {
4101                continue;
4102            };
4103            if !has_unconfirmed_command(&o.commands) {
4104                continue;
4105            }
4106            let Some(job) = sent.get(*wi) else { continue };
4107            if !has_context(&job.spec, seat, job.sessions) {
4108                self.state.event(
4109                    "implement",
4110                    format!(
4111                        "{}: the reply named a command whose own CLI never confirmed the exit \
4112                         status of, but there is no session left to resume",
4113                        seat.key
4114                    ),
4115                );
4116                continue;
4117            }
4118            self.state.event(
4119                "implement",
4120                format!(
4121                    "{}: the reply named a command whose own CLI never confirmed the exit \
4122                     status of; resuming the conversation",
4123                    seat.key
4124                ),
4125            );
4126            let mut retry = job.clone();
4127            retry.seat = seat.clone();
4128            retry.prompt = prompt::resume_incomplete(
4129                "a command in your last reply had no confirmed exit status",
4130            );
4131            retry.timeout = retry_budget(job.timeout, true);
4132            retry.stem = format!("{}-confirm", job.stem);
4133            let cache = self.state.config.cache_dir();
4134            let ctx = WaveCtx {
4135                carry_seats: false,
4136                pauses: Some((&self.pause, &self.interrupt)),
4137                run: run_id,
4138                node: "implement",
4139                prompts,
4140                cache: cache.as_deref(),
4141                round: None,
4142            };
4143            let (resumed_seat, resumed) =
4144                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4145            *seat = resumed_seat;
4146            *out = resumed;
4147        }
4148    }
4149
4150    /// Ask an implement seat again, once per candidate and run, when its
4151    /// turn ended cleanly without starting the work.
4152    ///
4153    /// The shape behind 86f0, 3ce0 and eca7: the model's first response was a
4154    /// final answer ("Implementation incomplete. No files were changed...")
4155    /// after six to twelve seconds, with no tool call and no change. That is
4156    /// a usable exit-0 reply, so none of the other recoveries sees it — it is
4157    /// not a dropped stream, not a failure and names no unconfirmed command —
4158    /// and the candidate was recorded as an ordinary empty one.
4159    ///
4160    /// Decided on evidence, never on the reply's wording (see
4161    /// [`ended_unstarted`]), and never for a reply whose `NO CHANGE NEEDED`
4162    /// claim verifies: that one did answer the task.
4163    ///
4164    /// The seat's own conversation is resumed with [`prompt::resume_unstarted`]
4165    /// when it has one; without a session the whole prompt goes out again.
4166    /// Either way the budget is the full `timeout_implement`, not a nudge's
4167    /// quarter: nothing was done yet, so this is the job itself.
4168    ///
4169    /// Bounded by [`RunState::unstarted_retries`], saved before the agent is
4170    /// asked so a restart cannot grant a second retry. A seat that ends the
4171    /// same way again becomes an ordinary failure with [`UNSTARTED_TWICE`] as
4172    /// its reason, which `resume_seat_handovers` (run next) may hand to the
4173    /// next roster agent like any other failure.
4174    async fn retry_unstarted(
4175        &mut self,
4176        results: &mut [(usize, SeatState, AgentOutcome)],
4177        sent: &[SeatJob],
4178        baselines: &[(char, Option<String>)],
4179        prompts: &Prompts,
4180        run_id: &str,
4181    ) -> Result<()> {
4182        for (wi, seat, out) in results.iter_mut() {
4183            let (Some(job), Some((label, before))) = (sent.get(*wi), baselines.get(*wi)) else {
4184                continue;
4185            };
4186            if !self.unstarted(out, before.as_deref(), &job.cwd).await {
4187                continue;
4188            }
4189            if !self.state.unstarted_retries.insert(*label) {
4190                self.state
4191                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4192                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4193                continue;
4194            }
4195            let resumed = has_context(&job.spec, seat, job.sessions);
4196            self.state.event(
4197                "implement",
4198                format!(
4199                    "{}: the turn ended without starting the work (no tool call, worktree \
4200                     unchanged); {}",
4201                    seat.key,
4202                    if resumed {
4203                        "resuming the conversation once"
4204                    } else {
4205                        "sending the task once more"
4206                    }
4207                ),
4208            );
4209            self.state.save()?;
4210            let mut retry = job.clone();
4211            retry.seat = seat.clone();
4212            if resumed {
4213                retry.prompt = prompt::resume_unstarted();
4214            }
4215            retry.stem = format!("{}-unstarted", job.stem);
4216            let cache = self.state.config.cache_dir();
4217            let ctx = WaveCtx {
4218                carry_seats: false,
4219                pauses: Some((&self.pause, &self.interrupt)),
4220                run: run_id,
4221                node: "implement",
4222                prompts,
4223                cache: cache.as_deref(),
4224                round: None,
4225            };
4226            let (answered_seat, answer) =
4227                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4228            *seat = answered_seat;
4229            *out = answer;
4230            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
4231                // No agent was spawned, so the retry was not spent.
4232                self.state.unstarted_retries.remove(label);
4233                continue;
4234            }
4235            if self.unstarted(out, before.as_deref(), &job.cwd).await {
4236                self.state
4237                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4238                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4239            }
4240        }
4241        Ok(())
4242    }
4243
4244    /// Whether `out` is a clean reply from a seat that never started the
4245    /// work in `cwd`, and whose reply does not verify as a no-op either.
4246    async fn unstarted(&self, out: &AgentOutcome, before: Option<&str>, cwd: &Path) -> bool {
4247        let AgentOutcome::Ok(o) = out else {
4248            return false;
4249        };
4250        // The CLI's own record first: most replies stop here without git.
4251        if o.tool_calls != Some(0) {
4252            return false;
4253        }
4254        let after = git::rev_parse(cwd, "HEAD").await.ok();
4255        let clean = git::is_clean(cwd).await.ok();
4256        if !ended_unstarted(o, before, after.as_deref(), clean) {
4257            return false;
4258        }
4259        let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
4260        verified_noop_claim_in_worktree(true, &o.commands, &text, cwd, &self.state.base_commit)
4261            .await
4262            != NoopClaimVerdict::Accepted
4263    }
4264
4265    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
4266    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
4267    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
4268    /// that motivated this.
4269    ///
4270    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
4271    /// own nudge loop already covers for judge/review/vote seats, and not a
4272    /// dropped stream, which [`Runner::resume_undelivered`] covers for
4273    /// implement seats: here the CLI turn genuinely finished while the node's
4274    /// own work — the fixer's account of what it did — had not. Gated purely
4275    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
4276    /// reply, never on any wording in it, so a fixer whose valid, first-try
4277    /// `FixReport` happens to mention having waited on a background test is
4278    /// never resumed — the `Ok(report)` branch at the call site returns
4279    /// before this is ever invoked.
4280    ///
4281    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4282    /// attempt ([`retry_budget`]), nothing attempted once the session is
4283    /// gone, and a quota hit ends the loop immediately rather than retrying a
4284    /// rate limit that fails the same way again.
4285    async fn continue_fix_report(
4286        &mut self,
4287        mut seat: SeatState,
4288        parse_err: String,
4289        job: &SeatJob,
4290        prompts: &Prompts,
4291        run_id: &str,
4292        round: usize,
4293    ) -> (
4294        SeatState,
4295        Option<FixReport>,
4296        Option<String>,
4297        ContinuationRecord,
4298    ) {
4299        let mut last_err = parse_err;
4300        let mut cumulative_wait_ms = 0u64;
4301        let mut attempts = 0usize;
4302        loop {
4303            if !has_context(&job.spec, &seat, job.sessions) {
4304                self.state.event(
4305                    "fix",
4306                    format!(
4307                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4308                         session left to resume into"
4309                    ),
4310                );
4311                let outcome = if attempts == 0 {
4312                    ContinuationOutcome::NoSession
4313                } else {
4314                    ContinuationOutcome::Exhausted
4315                };
4316                return (
4317                    seat,
4318                    None,
4319                    Some(format!("unparsable fix report: {last_err}")),
4320                    ContinuationRecord {
4321                        attempts,
4322                        cumulative_wait_ms,
4323                        outcome,
4324                    },
4325                );
4326            }
4327            if attempts >= MAX_FIX_CONTINUATIONS {
4328                self.state.event(
4329                    "fix",
4330                    format!(
4331                        "round {round}: fixer's reply still had no adoption report after \
4332                         {attempts} continuation(s) ({last_err}); giving up"
4333                    ),
4334                );
4335                return (
4336                    seat,
4337                    None,
4338                    Some(format!(
4339                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4340                    )),
4341                    ContinuationRecord {
4342                        attempts,
4343                        cumulative_wait_ms,
4344                        outcome: ContinuationOutcome::Exhausted,
4345                    },
4346                );
4347            }
4348            attempts += 1;
4349            self.state.event(
4350                "fix",
4351                format!(
4352                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4353                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4354                ),
4355            );
4356            let mut retry = job.clone();
4357            retry.seat = seat.clone();
4358            retry.prompt = prompt::resume_incomplete(&last_err);
4359            retry.timeout = retry_budget(job.timeout, true);
4360            retry.stem = format!("{}-continue{attempts}", job.stem);
4361            let cache = self.state.config.cache_dir();
4362            let ctx = WaveCtx {
4363                carry_seats: false,
4364                pauses: Some((&self.pause, &self.interrupt)),
4365                run: run_id,
4366                node: "fix",
4367                prompts,
4368                cache: cache.as_deref(),
4369                round: Some(round),
4370            };
4371            let (resumed_seat, resumed_out) = run_one(
4372                retry,
4373                Arc::clone(&self.sem),
4374                &ctx,
4375                &mut self.state,
4376                attempts,
4377            )
4378            .await;
4379            seat = resumed_seat;
4380            match resumed_out {
4381                AgentOutcome::Ok(o) => {
4382                    cumulative_wait_ms += o.duration_ms;
4383                    match verdict::extract_json::<FixReport>(&o.text) {
4384                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4385                            self.state.event(
4386                                "fix",
4387                                format!(
4388                                    "round {round}: fixer's adoption report recovered after \
4389                                     {attempts} continuation(s)"
4390                                ),
4391                            );
4392                            return (
4393                                seat,
4394                                Some(report),
4395                                None,
4396                                ContinuationRecord {
4397                                    attempts,
4398                                    cumulative_wait_ms,
4399                                    outcome: ContinuationOutcome::Resumed,
4400                                },
4401                            );
4402                        }
4403                        // The report parsed, but this same reply's own
4404                        // CommandEvidence — the identical record `state.jobs`
4405                        // renders — names a command whose CLI never
4406                        // confirmed an exit status. Read together, that is
4407                        // not a resolved answer: keep nudging rather than
4408                        // accept a report standing next to a command the
4409                        // seat's own CLI cannot vouch for.
4410                        Ok(_) => {
4411                            last_err = "the reply parsed, but it reported a command whose own CLI \
4412                                 never confirmed an exit status"
4413                                .to_owned();
4414                        }
4415                        Err(e) => last_err = e.to_string(),
4416                    }
4417                }
4418                AgentOutcome::Quota(o) => {
4419                    cumulative_wait_ms += o.duration_ms;
4420                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4421                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4422                    self.state.quota.push(loss);
4423                    self.state.event(
4424                        "fix",
4425                        format!(
4426                            "round {round}: continuation rate limited (quota); not retrying now"
4427                        ),
4428                    );
4429                    return (
4430                        seat,
4431                        None,
4432                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4433                        ContinuationRecord {
4434                            attempts,
4435                            cumulative_wait_ms,
4436                            outcome: ContinuationOutcome::QuotaLost,
4437                        },
4438                    );
4439                }
4440                AgentOutcome::Dropped(o) => {
4441                    cumulative_wait_ms += o.duration_ms;
4442                    let why = o
4443                        .dropped
4444                        .as_ref()
4445                        .map(|d| d.why.as_str())
4446                        .unwrap_or("the CLI ended the stream without delivering its answer");
4447                    last_err = format!("the CLI dropped the stream ({why})");
4448                }
4449                AgentOutcome::Failed(e) => last_err = e,
4450                // The continuation was never started; the report stays lost
4451                // and the caller records that, without any handover.
4452                AgentOutcome::ResourceBlocked(e) => {
4453                    return (
4454                        seat,
4455                        None,
4456                        Some(format!("the continuation was not started: {e}")),
4457                        ContinuationRecord {
4458                            attempts: attempts.saturating_sub(1),
4459                            cumulative_wait_ms,
4460                            outcome: ContinuationOutcome::NoSession,
4461                        },
4462                    );
4463                }
4464            }
4465        }
4466    }
4467
4468    fn after_implement(&mut self) -> Result<()> {
4469        if !self.state.candidate_preservation.is_empty() {
4470            bail!("candidate preservation incomplete; judging is unsafe");
4471        }
4472        // Scan every candidate patch once the set is complete.
4473        if self.state.leaks.is_empty() {
4474            let cfg = self.state.config.blind.clone();
4475            let mut leaks = Vec::new();
4476            for c in &self.state.candidates {
4477                let Some(patch) =
4478                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4479                else {
4480                    continue;
4481                };
4482                leaks.extend(blind::scan(
4483                    &format!("candidate {} patch", c.label),
4484                    &patch,
4485                    &cfg.vendor_tokens,
4486                ));
4487            }
4488            if !leaks.is_empty() {
4489                let summary = leaks
4490                    .iter()
4491                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4492                    .collect::<Vec<_>>()
4493                    .join(", ");
4494                match cfg.on_leak {
4495                    LeakPolicy::Fail => {
4496                        self.state.status = RunStatus::Failed;
4497                        self.state
4498                            .event("blind", format!("vendor text in a patch: {summary}"));
4499                        self.state.leaks = leaks;
4500                        self.state.save()?;
4501                        self.settle_questions();
4502                        bail!(
4503                            "blind.on_leak = \"fail\" and vendor text reached a \
4504                             judged patch: {summary}"
4505                        );
4506                    }
4507                    LeakPolicy::Redact => self.state.event(
4508                        "blind",
4509                        format!("redacting vendor text for judging: {summary}"),
4510                    ),
4511                    LeakPolicy::Warn => self.state.event(
4512                        "blind",
4513                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4514                    ),
4515                }
4516                self.state.leaks = leaks;
4517            }
4518        }
4519
4520        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4521        // incomplete or inconsistent saved state cannot bypass the strict contract.
4522        let mut invalidated = Vec::new();
4523        for c in &mut self.state.candidates {
4524            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4525                c.verified_noop = None;
4526                if c.empty && c.failed.is_none() {
4527                    c.failed = Some(
4528                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4529                            .to_owned(),
4530                    );
4531                }
4532                invalidated.push(c.label);
4533            }
4534        }
4535        for label in invalidated {
4536            self.state.event(
4537                "implement",
4538                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4539            );
4540        }
4541
4542        if self.state.viable().is_empty() {
4543            if self.state.all_candidates_verified_noop() {
4544                // Every candidate agreed, with evidence the adoption guard
4545                // accepted, that nothing belongs in this worktree. That is
4546                // not the same fact as a candidate that simply failed to
4547                // write anything, and settling it as an ordinary `Failed`
4548                // (see `SCHEMA`'s doc for schema 10) is what let two of
4549                // task 391f's attempts burn a retry each re-discovering the
4550                // same already-landed fix. Terminal either way, so `judge`
4551                // must never run over an empty candidate set — unlike the
4552                // `Failed` branch below this returns `Ok`, not an error:
4553                // nothing here failed.
4554                self.state.status = RunStatus::VerifiedNoop;
4555                self.state.save()?;
4556                self.settle_questions();
4557                return Ok(());
4558            }
4559            self.state.status = RunStatus::Failed;
4560            self.state.save()?;
4561            self.settle_questions();
4562            bail!("no candidate produced a change; nothing to judge");
4563        }
4564        self.state.status = RunStatus::Judging;
4565        self.state.save()?;
4566        Ok(())
4567    }
4568
4569    // --------------------------------------------------------------- judge
4570
4571    async fn judge(&mut self) -> Result<()> {
4572        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4573        // agent files with `magi task add` name the run that paid for it. The
4574        // prompt overlay is cloned alongside it because the waves borrow it
4575        // while `self` is mutably borrowed by the node's own bookkeeping.
4576        let run_id = self.state.id.clone();
4577        let prompts = self.state.config.prompts.clone();
4578        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4579            return Ok(());
4580        }
4581        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4582        if viable.len() == 1 {
4583            // Recorded so this is a one-time event: `judgements` stays empty
4584            // either way, which without this flag is indistinguishable from
4585            // "not yet judged" on the next reentry — and status is left
4586            // untouched, so a later node's conclusion (e.g. `Blocked` after
4587            // the review budget ran out) survives a resume instead of being
4588            // clobbered back to `Judging` by this node running again.
4589            self.state.judge_skipped = true;
4590            self.state.event(
4591                "judge",
4592                format!(
4593                    "only candidate {} produced a change; judging skipped",
4594                    viable[0].label
4595                ),
4596            );
4597            self.state.save()?;
4598            return Ok(());
4599        }
4600        self.state.status = RunStatus::Judging;
4601
4602        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4603        let language = self.state.config.graph.language.clone();
4604        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4605        let sessions = self.state.config.graph.sessions;
4606        let artifacts = agent::artifacts_dir(&self.state.dir());
4607        let root = self.state.worktree_root();
4608        let base_short = short(&self.state.base_commit);
4609
4610        let mut jobs = Vec::new();
4611        let mut orders = Vec::new();
4612        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4613            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4614            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4615            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4616            let seat_key = format!("judge-{}", j + 1);
4617            let seat = self.seat(&seat_key, &spec.id);
4618            jobs.push(SeatJob {
4619                prompt: prompt::judge(
4620                    &self.state.instruction,
4621                    &views,
4622                    self.roles.judges.len(),
4623                    &base_short,
4624                    &language,
4625                ),
4626                spec,
4627                seat,
4628                cwd: root.join(format!("judge-{}", j + 1)),
4629                timeout,
4630                allow_write: false,
4631                sessions,
4632                artifacts: artifacts.clone(),
4633                stem: format!("judge-{}", j + 1),
4634                handover: None,
4635            });
4636        }
4637
4638        self.state.event(
4639            "judge",
4640            format!(
4641                "{} judges ranking {} candidates blind",
4642                jobs.len(),
4643                viable.len()
4644            ),
4645        );
4646        let labels_for_check = labels.clone();
4647        let mut quota_losses = Vec::new();
4648        let cache = self.state.config.cache_dir();
4649        let ctx = WaveCtx {
4650            carry_seats: false,
4651            pauses: Some((&self.pause, &self.interrupt)),
4652            run: &run_id,
4653            node: "judge",
4654            prompts: &prompts,
4655            cache: cache.as_deref(),
4656            round: None,
4657        };
4658        let results = ask_json_wave::<Ranking>(
4659            jobs,
4660            Arc::clone(&self.sem),
4661            self.state.config.graph.retries,
4662            &self.roles.judge_roster,
4663            &ctx,
4664            &mut quota_losses,
4665            &mut self.state,
4666            &move |r: &Ranking| r.validate(&labels_for_check),
4667        )
4668        .await;
4669        if self.state.resource_block.is_some() {
4670            return self.stop_for_resource();
4671        }
4672        self.state.quota.extend(quota_losses);
4673
4674        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4675            let agent_id = seat.agent.clone();
4676            self.state.seats.insert(seat.key.clone(), seat);
4677            let mut record = Judgement {
4678                judge: j + 1,
4679                seat: format!("judge-{}", j + 1),
4680                agent: agent_id,
4681                ranking: Vec::new(),
4682                reasons: BTreeMap::new(),
4683                confidence: None,
4684                strengths: BTreeMap::new(),
4685                order: orders[j].clone(),
4686                failed: None,
4687                duration_ms: 0,
4688            };
4689            match res {
4690                Ok((ranking, out)) => {
4691                    record.ranking = ranking.normalized();
4692                    record.reasons = ranking.reasons;
4693                    record.strengths = ranking.strengths;
4694                    record.confidence = ranking.confidence;
4695                    record.duration_ms = out.duration_ms;
4696                    self.state.event(
4697                        "judge",
4698                        format!(
4699                            "judge {} ranked {}",
4700                            j + 1,
4701                            record.ranking.iter().collect::<String>()
4702                        ),
4703                    );
4704                }
4705                Err(e) => {
4706                    record.failed = Some(e.to_string());
4707                    self.state
4708                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4709                }
4710            }
4711            self.state.judgements.push(record);
4712            self.state.save()?;
4713        }
4714        Ok(())
4715    }
4716
4717    // ---------------------------------------------------------- deliberate
4718
4719    async fn deliberate(&mut self) -> Result<()> {
4720        if self.hold_base_sync().await? {
4721            return Ok(());
4722        }
4723        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4724        // agent files with `magi task add` name the run that paid for it. The
4725        // prompt overlay is cloned alongside it because the waves borrow it
4726        // while `self` is mutably borrowed by the node's own bookkeeping.
4727        let run_id = self.state.id.clone();
4728        let prompts = self.state.config.prompts.clone();
4729        let rounds = self.state.config.graph.deliberate_rounds;
4730        // Resume unfinished rounds after an outage, but never reopen a tally.
4731        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4732            return Ok(());
4733        }
4734        let tops: Vec<char> = self
4735            .state
4736            .judgements
4737            .iter()
4738            .filter_map(|j| j.ranking.first().copied())
4739            .collect();
4740        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4741            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4742                self.state.event(
4743                    "deliberate",
4744                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4745                );
4746            }
4747            self.state.status = RunStatus::Voting;
4748            self.state.save()?;
4749            return Ok(());
4750        }
4751
4752        self.state.status = RunStatus::Deliberating;
4753        self.state.event(
4754            "deliberate",
4755            format!(
4756                "split: first choices were {} — opening {rounds} round(s)",
4757                tops.iter().collect::<String>()
4758            ),
4759        );
4760
4761        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4762        let language = self.state.config.graph.language.clone();
4763        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4764        let sessions = self.state.config.graph.sessions;
4765        let artifacts = agent::artifacts_dir(&self.state.dir());
4766        let root = self.state.worktree_root();
4767        let base_short = short(&self.state.base_commit);
4768
4769        // Judges argue in sequence so that a turn can answer the one before it;
4770        // that is the difference between deliberation and three parallel
4771        // monologues.
4772        for round in self.state.deliberation.len() + 1..=rounds {
4773            let mut turns: Vec<DeliberationTurn> = Vec::new();
4774            let mut round_losses = Vec::new();
4775            let mut asked = 0;
4776            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4777                if self.state.judgements[j].failed.is_some() {
4778                    continue;
4779                }
4780                let seat_key = format!("judge-{}", j + 1);
4781                let spec = self.occupant(&seat_key, spec);
4782                let mut seat = self.seat(&seat_key, &spec.id);
4783                let transcript = self.transcript(&turns, j);
4784                let build = |context: Option<&str>| {
4785                    prompt::deliberate(
4786                        &self.state.instruction,
4787                        context,
4788                        &transcript,
4789                        round,
4790                        rounds,
4791                        &language,
4792                    )
4793                };
4794                let block = self.candidate_block(&viable, &base_short);
4795                let full = build(Some(&block));
4796                let text = if has_context(&spec, &seat, sessions) {
4797                    build(None)
4798                } else {
4799                    full.clone()
4800                };
4801                let job = SeatJob {
4802                    spec,
4803                    seat: seat.clone(),
4804                    prompt: text,
4805                    cwd: root.join(format!("judge-{}", j + 1)),
4806                    timeout,
4807                    allow_write: false,
4808                    sessions,
4809                    artifacts: artifacts.clone(),
4810                    stem: format!("delib-{round}-judge-{}", j + 1),
4811                    handover: Some(full),
4812                };
4813                let cache = self.state.config.cache_dir();
4814                let ctx = WaveCtx {
4815                    carry_seats: false,
4816                    pauses: Some((&self.pause, &self.interrupt)),
4817                    run: &run_id,
4818                    node: "deliberate",
4819                    prompts: &prompts,
4820                    cache: cache.as_deref(),
4821                    round: None,
4822                };
4823                // A turn is never nudged (`retries` 0): a failed seat is
4824                // handed to the next roster agent, which gets the full
4825                // context. An empty answer is a turn, not a failure.
4826                let mut losses = Vec::new();
4827                asked += 1;
4828                let mut results = ask_wave_with::<String>(
4829                    vec![job],
4830                    Arc::clone(&self.sem),
4831                    0,
4832                    &self.roles.judge_roster,
4833                    &ctx,
4834                    &mut losses,
4835                    &mut self.state,
4836                    &|text: &str| {
4837                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4838                    },
4839                )
4840                .await;
4841                if self.state.resource_block.is_some() {
4842                    return self.stop_for_resource();
4843                }
4844                round_losses.extend(losses.iter().cloned());
4845                self.state.quota.extend(losses);
4846                let (updated, res, _) = results.pop().expect("one job in, one result out");
4847                seat = updated;
4848                let agent_id = seat.agent.clone();
4849                self.state.seats.insert(seat.key.clone(), seat);
4850                let body = match res {
4851                    Ok((body, _)) => body,
4852                    // Skip the seat; a CLI's raw error JSON is never read as
4853                    // this judge's position.
4854                    Err(e) => {
4855                        self.state
4856                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4857                        continue;
4858                    }
4859                };
4860                let tentative = verdict::extract_json::<Position>(&body)
4861                    .ok()
4862                    .and_then(|p| p.tentative)
4863                    .and_then(|s| s.trim().chars().next())
4864                    .map(|c| c.to_ascii_uppercase());
4865                self.state.event(
4866                    "deliberate",
4867                    format!(
4868                        "round {round}: judge {} now favours {}",
4869                        j + 1,
4870                        tentative.map_or("—".to_owned(), |c| c.to_string())
4871                    ),
4872                );
4873                turns.push(DeliberationTurn {
4874                    judge: j + 1,
4875                    agent: agent_id,
4876                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4877                    tentative,
4878                });
4879            }
4880            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4881                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4882                return self.stop_for_resource();
4883            }
4884            self.state
4885                .deliberation
4886                .push(DeliberationRound { round, turns });
4887            self.state.save()?;
4888        }
4889
4890        self.state.status = RunStatus::Voting;
4891        self.state.save()?;
4892        Ok(())
4893    }
4894
4895    // ---------------------------------------------------------------- vote
4896
4897    async fn vote(&mut self) -> Result<()> {
4898        if self.hold_base_sync().await? {
4899            return Ok(());
4900        }
4901        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4902        // agent files with `magi task add` name the run that paid for it. The
4903        // prompt overlay is cloned alongside it because the waves borrow it
4904        // while `self` is mutably borrowed by the node's own bookkeeping.
4905        let run_id = self.state.id.clone();
4906        let prompts = self.state.config.prompts.clone();
4907        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4908            return Ok(());
4909        }
4910        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4911        if viable.len() == 1 {
4912            return Ok(());
4913        }
4914        self.state.status = RunStatus::Voting;
4915
4916        let language = self.state.config.graph.language.clone();
4917        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4918        let sessions = self.state.config.graph.sessions;
4919        let artifacts = agent::artifacts_dir(&self.state.dir());
4920        let root = self.state.worktree_root();
4921        let base_short = short(&self.state.base_commit);
4922        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4923
4924        let mut jobs = Vec::new();
4925        let mut seats_at = Vec::new();
4926        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4927            if self
4928                .state
4929                .judgements
4930                .get(j)
4931                .is_some_and(|r| r.failed.is_some())
4932            {
4933                continue;
4934            }
4935            let seat_key = format!("judge-{}", j + 1);
4936            let spec = self.occupant(&seat_key, spec);
4937            let seat = self.seat(&seat_key, &spec.id);
4938            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4939            let text = if has_context(&spec, &seat, sessions) {
4940                prompt::final_vote(&viable, &language)
4941            } else {
4942                full.clone()
4943            };
4944            jobs.push(SeatJob {
4945                spec,
4946                seat,
4947                prompt: text,
4948                cwd: root.join(format!("judge-{}", j + 1)),
4949                timeout,
4950                allow_write: false,
4951                sessions,
4952                artifacts: artifacts.clone(),
4953                stem: format!("vote-judge-{}", j + 1),
4954                handover: Some(full),
4955            });
4956            seats_at.push(j);
4957        }
4958
4959        self.state.event(
4960            "vote",
4961            format!(
4962                "collecting {} final votes one by one, privately",
4963                jobs.len()
4964            ),
4965        );
4966        let allowed = viable.clone();
4967        let mut quota_losses = Vec::new();
4968        let cache = self.state.config.cache_dir();
4969        let ctx = WaveCtx {
4970            carry_seats: false,
4971            pauses: Some((&self.pause, &self.interrupt)),
4972            run: &run_id,
4973            node: "vote",
4974            prompts: &prompts,
4975            cache: cache.as_deref(),
4976            round: None,
4977        };
4978        let results = ask_json_wave::<FinalVote>(
4979            jobs,
4980            Arc::clone(&self.sem),
4981            self.state.config.graph.retries,
4982            &self.roles.judge_roster,
4983            &ctx,
4984            &mut quota_losses,
4985            &mut self.state,
4986            &move |v: &FinalVote| match v.label() {
4987                Some(c) if allowed.contains(&c) => Ok(()),
4988                other => bail!("vote {other:?} is not one of {allowed:?}"),
4989            },
4990        )
4991        .await;
4992        if self.state.resource_block.is_some() {
4993            return self.stop_for_resource();
4994        }
4995        self.state.quota.extend(quota_losses);
4996
4997        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4998            let agent_id = seat.agent.clone();
4999            self.state.seats.insert(seat.key.clone(), seat);
5000            let initial = self
5001                .state
5002                .judgements
5003                .get(j)
5004                .and_then(|r| r.ranking.first().copied());
5005            let mut record = VoteRecord {
5006                judge: j + 1,
5007                agent: agent_id,
5008                vote: None,
5009                reason: String::new(),
5010                changed: false,
5011            };
5012            match res {
5013                Ok((v, _)) => {
5014                    record.vote = v.label();
5015                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5016                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
5017                    self.state.event(
5018                        "vote",
5019                        format!(
5020                            "judge {} voted {}{}",
5021                            j + 1,
5022                            record.vote.unwrap_or('?'),
5023                            if record.changed { " (changed)" } else { "" }
5024                        ),
5025                    );
5026                }
5027                Err(e) => {
5028                    self.state
5029                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
5030                }
5031            }
5032            self.state.votes.push(record);
5033            self.state.save()?;
5034        }
5035        Ok(())
5036    }
5037
5038    // --------------------------------------------------------------- tally
5039
5040    fn tally(&mut self) -> Result<()> {
5041        if self.state.tally.is_some() {
5042            return Ok(());
5043        }
5044        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
5045        let tops: Vec<char> = self
5046            .state
5047            .judgements
5048            .iter()
5049            .filter_map(|j| j.ranking.first().copied())
5050            .collect();
5051        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
5052
5053        // A judge whose private vote failed still counted once, in the initial
5054        // ranking; using it beats discarding a whole seat.
5055        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5056        let mut cast: Vec<char> = Vec::new();
5057        for (i, j) in self.state.judgements.iter().enumerate() {
5058            let vote = self
5059                .state
5060                .votes
5061                .iter()
5062                .find(|v| v.judge == i + 1)
5063                .and_then(|v| v.vote)
5064                .or_else(|| j.ranking.first().copied());
5065            if let Some(v) = vote {
5066                *first_choice.entry(v).or_insert(0) += 1;
5067                cast.push(v);
5068            }
5069        }
5070
5071        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5072        for j in &self.state.judgements {
5073            let n = j.ranking.len();
5074            for (pos, label) in j.ranking.iter().enumerate() {
5075                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
5076            }
5077        }
5078
5079        let best = first_choice.values().copied().max().unwrap_or(0);
5080        let mut leaders: Vec<char> = first_choice
5081            .iter()
5082            .filter(|(_, v)| **v == best)
5083            .map(|(k, _)| *k)
5084            .collect();
5085        let mut tie_break = None;
5086        if leaders.len() > 1 {
5087            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
5088            let borda_leaders: Vec<char> = leaders
5089                .iter()
5090                .copied()
5091                .filter(|l| borda[l] == top_borda)
5092                .collect();
5093            tie_break = Some(if borda_leaders.len() == 1 {
5094                format!(
5095                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
5096                    leaders.len()
5097                )
5098            } else {
5099                format!(
5100                    "{} way tie on both first-choice votes and Borda points, broken by label order",
5101                    leaders.len()
5102                )
5103            });
5104            leaders = borda_leaders;
5105            leaders.sort_unstable();
5106        }
5107        let winner = *leaders
5108            .first()
5109            .or(viable.first())
5110            .context("no candidate to declare a winner from")?;
5111
5112        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
5113        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
5114        let deliberated = !self.state.deliberation.is_empty();
5115
5116        // Whose verdict is this? A rate-limited seat is absent even if it
5117        // ranked before the limit hit, so presence is measured against the
5118        // recorded losses, not just "did a ranking ever appear".
5119        let quota_seats: std::collections::BTreeSet<&str> =
5120            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5121        let mut present = 0usize;
5122        for (i, j) in self.state.judgements.iter().enumerate() {
5123            if quota_seats.contains(j.seat.as_str()) {
5124                continue;
5125            }
5126            let ranked = !j.ranking.is_empty() && j.failed.is_none();
5127            let voted = self
5128                .state
5129                .votes
5130                .iter()
5131                .any(|v| v.judge == i + 1 && v.vote.is_some());
5132            if ranked || voted {
5133                present += 1;
5134            }
5135        }
5136        // Strict majority of the configured panel. A bare majority is real
5137        // signal we can act on, while a minority verdict must never stand in
5138        // for a healthy one. A one-candidate run needs no panel at all, and
5139        // `judges` stays `0` rather than the roster size a panel that never
5140        // sat would otherwise be credited with.
5141        let needs_quorum = viable.len() > 1;
5142        let judges_total = if needs_quorum {
5143            self.roles.judges.len()
5144        } else {
5145            0
5146        };
5147        let quorum = if needs_quorum {
5148            judges_total / 2 + 1
5149        } else {
5150            0
5151        };
5152        let met_quorum = !needs_quorum || present >= quorum;
5153        let uncontested = (!needs_quorum).then(|| {
5154            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
5155        });
5156
5157        self.state.event(
5158            "tally",
5159            match &uncontested {
5160                Some(reason) => format!("winner {winner} — {reason}"),
5161                None => format!(
5162                    "winner {winner} — votes {} | initial {} | {} changed | \
5163                     {present}/{judges_total} judges{}",
5164                    first_choice
5165                        .iter()
5166                        .map(|(k, v)| format!("{k}:{v}"))
5167                        .collect::<Vec<_>>()
5168                        .join(" "),
5169                    if unanimous_initial {
5170                        "unanimous"
5171                    } else {
5172                        "split"
5173                    },
5174                    changed_votes,
5175                    if met_quorum {
5176                        String::new()
5177                    } else {
5178                        format!(" — below quorum ({quorum} required)")
5179                    },
5180                ),
5181            },
5182        );
5183        if !met_quorum {
5184            self.state.event(
5185                "stall",
5186                format!(
5187                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
5188                     the run stops here, resumable"
5189                ),
5190            );
5191        }
5192        self.state.tally = Some(Tally {
5193            first_choice,
5194            borda,
5195            winner,
5196            rankings: tops.len(),
5197            unanimous_initial,
5198            deliberated,
5199            changed_votes,
5200            unanimous_final,
5201            tie_break,
5202            judges: judges_total,
5203            present,
5204            quorum,
5205            met_quorum,
5206            uncontested,
5207        });
5208        self.state.status = if met_quorum {
5209            RunStatus::Reviewing
5210        } else {
5211            RunStatus::Stalled
5212        };
5213        self.state.save()?;
5214        Ok(())
5215    }
5216
5217    // ------------------------------------------------------------- recover
5218
5219    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
5220    /// resumed toward completion once the transient cause clears.
5221    ///
5222    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
5223    /// it toward the quorum, which is exactly the set of seats whose absence
5224    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
5225    /// not depend on which node happened to hit the limit), or an ordinary
5226    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
5227    /// seat is never disturbed.
5228    ///
5229    /// A seat that now answers with a usable ranking is "recovered": its
5230    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
5231    /// `tally` counts it present again), and its vote re-collected. A seat that
5232    /// still fails keeps its loss and stays absent.
5233    ///
5234    /// Returns `true` when the re-tally restores the quorum (the run may proceed
5235    /// to review/gate/merge), `false` when it is still below quorum (the run
5236    /// stays `Stalled`, still resumable for a later retry).
5237    #[allow(clippy::too_many_lines)]
5238    async fn recover_stall(&mut self) -> Result<bool> {
5239        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
5240        // agent files with `magi task add` name the run that paid for it. The
5241        // prompt overlay is cloned alongside it because the waves borrow it
5242        // while `self` is mutably borrowed by the node's own bookkeeping.
5243        let run_id = self.state.id.clone();
5244        let prompts = self.state.config.prompts.clone();
5245        // Absent seats = quota-lost at any node, or failed outright. Mirroring
5246        // `tally`'s presence test (rather than the old quota-judge/vote filter)
5247        // is what keeps a non-quota collapse — or a quota loss recorded at the
5248        // deliberate node — from being a permanent dead-end on `--resume`.
5249        let quota_seats: BTreeSet<&str> =
5250            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5251        let absent: Vec<String> = self
5252            .state
5253            .judgements
5254            .iter()
5255            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
5256            .map(|j| j.seat.clone())
5257            .collect();
5258        if absent.is_empty() {
5259            return Ok(false);
5260        }
5261        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
5262        if viable.len() <= 1 {
5263            return Ok(false);
5264        }
5265        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
5266        let language = self.state.config.graph.language.clone();
5267        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
5268        let sessions = self.state.config.graph.sessions;
5269        let artifacts = agent::artifacts_dir(&self.state.dir());
5270        let root = self.state.worktree_root();
5271        let base_short = short(&self.state.base_commit);
5272        let candidates: Vec<Candidate> = viable.clone();
5273
5274        // Map each absent seat key to its 0-based position in `roles.judges`.
5275        let mut positions: Vec<usize> = absent
5276            .iter()
5277            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5278            .collect();
5279        if positions.is_empty() {
5280            return Ok(false);
5281        }
5282        positions.sort_unstable();
5283        positions.dedup();
5284
5285        // Re-rank the lost seats, one blind prompt each.
5286        let mut judge_jobs = Vec::new();
5287        for &j in &positions {
5288            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5289            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5290            let seat_key = format!("judge-{}", j + 1);
5291            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5292            let seat = self.seat(&seat_key, &spec.id);
5293            judge_jobs.push(SeatJob {
5294                spec,
5295                seat,
5296                prompt: prompt::judge(
5297                    &self.state.instruction,
5298                    &views,
5299                    self.roles.judges.len(),
5300                    &base_short,
5301                    &language,
5302                ),
5303                cwd: root.join(seat_key),
5304                timeout,
5305                allow_write: false,
5306                sessions,
5307                artifacts: artifacts.clone(),
5308                stem: format!("judge-{}-recover", j + 1),
5309                handover: None,
5310            });
5311        }
5312
5313        let labels_for_check = labels.clone();
5314        let mut judge_losses = Vec::new();
5315        let retries = self.state.config.graph.retries;
5316        let cache = self.state.config.cache_dir();
5317        let ctx = WaveCtx {
5318            carry_seats: false,
5319            pauses: Some((&self.pause, &self.interrupt)),
5320            run: &run_id,
5321            node: "judge",
5322            prompts: &prompts,
5323            cache: cache.as_deref(),
5324            round: None,
5325        };
5326        let results = ask_json_wave::<Ranking>(
5327            judge_jobs,
5328            Arc::clone(&self.sem),
5329            retries,
5330            &self.roles.judge_roster,
5331            &ctx,
5332            &mut judge_losses,
5333            &mut self.state,
5334            &move |r: &Ranking| r.validate(&labels_for_check),
5335        )
5336        .await;
5337        if self.state.resource_block.is_some() {
5338            self.stop_for_resource()?;
5339            return Ok(false);
5340        }
5341
5342        // Refresh the judgement of every seat that ranked again.
5343        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5344        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5345            let agent_id = seat.agent.clone();
5346            self.state.seats.insert(seat.key.clone(), seat);
5347            let record = &mut self.state.judgements[j];
5348            match res {
5349                Ok((ranking, out)) => {
5350                    record.agent = agent_id;
5351                    record.ranking = ranking.normalized();
5352                    record.reasons = ranking.reasons;
5353                    record.strengths = ranking.strengths;
5354                    record.confidence = ranking.confidence;
5355                    record.failed = None;
5356                    record.duration_ms = out.duration_ms;
5357                    recovered.insert(j);
5358                    self.state.event(
5359                        "recover",
5360                        format!("judge {} ranked again after the limit", j + 1),
5361                    );
5362                }
5363                Err(e) => {
5364                    self.state
5365                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5366                }
5367            }
5368        }
5369
5370        // Re-ask the votes of the seats that recovered a ranking.
5371        let mut vote_jobs = Vec::new();
5372        let mut vote_pos: Vec<usize> = Vec::new();
5373        for &j in &recovered {
5374            let seat_key = format!("judge-{}", j + 1);
5375            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5376            let seat = self.seat(&seat_key, &spec.id);
5377            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5378            let text = if has_context(&spec, &seat, sessions) {
5379                prompt::final_vote(&labels, &language)
5380            } else {
5381                full.clone()
5382            };
5383            vote_jobs.push(SeatJob {
5384                spec,
5385                seat,
5386                prompt: text,
5387                cwd: root.join(seat_key),
5388                timeout,
5389                allow_write: false,
5390                sessions,
5391                artifacts: artifacts.clone(),
5392                stem: format!("vote-judge-{}-recover", j + 1),
5393                handover: Some(full),
5394            });
5395            vote_pos.push(j);
5396        }
5397        let allowed = labels.clone();
5398        let mut vote_losses = Vec::new();
5399        let vote_retries = self.state.config.graph.retries;
5400        let vote_cache = self.state.config.cache_dir();
5401        let ctx = WaveCtx {
5402            carry_seats: false,
5403            pauses: Some((&self.pause, &self.interrupt)),
5404            run: &run_id,
5405            node: "vote",
5406            prompts: &prompts,
5407            cache: vote_cache.as_deref(),
5408            round: None,
5409        };
5410        let votes = ask_json_wave::<FinalVote>(
5411            vote_jobs,
5412            Arc::clone(&self.sem),
5413            vote_retries,
5414            &self.roles.judge_roster,
5415            &ctx,
5416            &mut vote_losses,
5417            &mut self.state,
5418            &move |v: &FinalVote| match v.label() {
5419                Some(c) if allowed.contains(&c) => Ok(()),
5420                other => bail!("vote {other:?} is not one of {allowed:?}"),
5421            },
5422        )
5423        .await;
5424        if self.state.resource_block.is_some() {
5425            self.stop_for_resource()?;
5426            return Ok(false);
5427        }
5428        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5429            let agent_id = seat.agent.clone();
5430            self.state.seats.insert(seat.key.clone(), seat);
5431            match res {
5432                Ok((v, _)) => {
5433                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5434                        rec.vote = v.label();
5435                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5436                    } else {
5437                        self.state.votes.push(VoteRecord {
5438                            judge: j + 1,
5439                            agent: agent_id,
5440                            vote: v.label(),
5441                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5442                            changed: false,
5443                        });
5444                    }
5445                    self.state.event(
5446                        "recover",
5447                        format!("judge {} voted again after the limit", j + 1),
5448                    );
5449                }
5450                Err(e) => {
5451                    self.state
5452                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5453                }
5454            }
5455        }
5456
5457        // A seat that ranked again is present even if its re-vote failed —
5458        // `tally` falls back to the initial ranking's first choice — so clear
5459        // its quota loss. Seats that still fail keep theirs and stay absent.
5460        let recovered_keys: BTreeSet<String> = recovered
5461            .iter()
5462            .map(|&j| format!("judge-{}", j + 1))
5463            .collect();
5464        self.state
5465            .quota
5466            .retain(|q| !recovered_keys.contains(&q.seat));
5467        // A seat that hit the limit again is a fresh loss, not the old one:
5468        // replace the stale entry so the history stays one-per-seat and the
5469        // daemon can tell this attempt's loss from a previous session's.
5470        for loss in judge_losses.into_iter().chain(vote_losses) {
5471            if recovered_keys.contains(&loss.seat) {
5472                continue;
5473            }
5474            self.state.quota.retain(|q| q.seat != loss.seat);
5475            self.state.quota.push(loss);
5476        }
5477
5478        // Recompute the verdict from the refreshed panel.
5479        self.state.tally = None;
5480        self.tally()?;
5481        Ok(self
5482            .state
5483            .tally
5484            .as_ref()
5485            .map(|t| t.met_quorum)
5486            .unwrap_or(false))
5487    }
5488
5489    // ---------------------------------------------------------------- graft
5490
5491    /// Port the strengths the judges attributed to the losing candidates onto
5492    /// the winner, once, between the tally and the review loop.
5493    ///
5494    /// Best-effort by construction: it returns nothing and fails nothing. A
5495    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5496    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5497    /// the run carries on as if the phase were off. See [`graft`] for the
5498    /// decisions and `AGENTS.md` for the invariants.
5499    ///
5500    /// The one exception is a rollback that could not be confirmed: the
5501    /// rejected commit may still be the winner's tip, so the run is blocked
5502    /// (resumable; the record stays `Running`, which makes a resume retry the
5503    /// restore) instead of reviewing, gating and merging it.
5504    async fn graft(&mut self) -> Result<()> {
5505        let Err(e) = self.graft_inner().await else {
5506            return Ok(());
5507        };
5508        if e.is::<crate::repo_lock::ResourceBlocked>() {
5509            return Err(e);
5510        }
5511        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5512            self.state.status = RunStatus::Blocked;
5513            self.state.event("graft", format!("blocked: {e:#}"));
5514            self.state.save()?;
5515            return Err(e);
5516        }
5517        // An error after the `Running` record was saved may have left the
5518        // fixer's work in the tree: the record must not stay unsettled
5519        // (a later resume would reset past the review fixes), so confirm the
5520        // restore now, or block.
5521        if let Some(rec) = self.state.graft.clone()
5522            && !rec.outcome.settled()
5523        {
5524            if let Some(winner) = self.state.winner().cloned() {
5525                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5526                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5527                        return Err(re);
5528                    }
5529                    self.state.status = RunStatus::Blocked;
5530                    self.state.event("graft", format!("blocked: {re:#}"));
5531                    self.state.save()?;
5532                    return Err(re);
5533                }
5534            }
5535            if let Some(g) = self.state.graft.as_mut() {
5536                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5537            }
5538        }
5539        self.state.event("graft", format!("skipped: {e:#}"));
5540        if let Err(e) = self.state.save() {
5541            tracing::warn!("save after graft: {e:#}");
5542        }
5543        Ok(())
5544    }
5545
5546    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5547    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5548    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5549        let _coordination = self.coordinate(wt).await?;
5550        crate::recovery::restore_repair(wt, pre)
5551            .await
5552            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5553    }
5554
5555    /// A skip is a run event, recorded once however often the node is re-entered.
5556    fn graft_skipped(&mut self, why: &str) {
5557        let message = format!("skipped: {why}");
5558        if !self
5559            .state
5560            .events
5561            .iter()
5562            .any(|e| e.node == "graft" && e.message == message)
5563        {
5564            self.state.event("graft", message);
5565        }
5566    }
5567
5568    async fn graft_inner(&mut self) -> Result<()> {
5569        // A round that was started and never finished (crash, kill): the
5570        // fixer may have left anything in the tree, so put the winner back.
5571        if let Some(rec) = self.state.graft.clone()
5572            && !rec.outcome.settled()
5573        {
5574            // Reviews exist only if the graft ended without its record being
5575            // settled (a swallowed error): the tree has moved on since, and
5576            // a reset to `pre` would discard the review fixes.
5577            if self.state.reviews.is_empty()
5578                && let Some(winner) = self.state.winner().cloned()
5579            {
5580                self.graft_restore(&winner.worktree, &rec.pre).await?;
5581            }
5582            if rec.outcome == GraftOutcome::WaitingForRestore {
5583                self.state.graft = None;
5584                self.state.save()?;
5585            } else {
5586                if let Some(g) = self.state.graft.as_mut() {
5587                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5588                }
5589                self.state.event(
5590                    "graft",
5591                    "rolled back: the previous round was interrupted; the winner is untouched",
5592                );
5593                self.state.save()?;
5594                return Ok(());
5595            }
5596        }
5597        let plan = match graft::plan(&self.state) {
5598            Ok(plan) => plan,
5599            Err(skip) => {
5600                if skip != graft::Skip::AlreadyDone {
5601                    self.graft_skipped(skip.reason());
5602                    self.state.save()?;
5603                }
5604                return Ok(());
5605            }
5606        };
5607        let Some(winner) = self.state.winner().cloned() else {
5608            return Ok(());
5609        };
5610        let wt = winner.worktree.clone();
5611        if !git::is_clean(&wt).await? {
5612            self.graft_skipped("the winner's worktree has uncommitted changes");
5613            self.state.save()?;
5614            return Ok(());
5615        }
5616        let pre = git::rev_parse(&wt, "HEAD").await?;
5617        // Saved before the fixer is called: a stop from here on is repaired
5618        // by the branch above on the next entry.
5619        self.state.graft = Some(GraftRecord {
5620            pre: pre.clone(),
5621            post: None,
5622            lines: None,
5623            limit: None,
5624            agent: None,
5625            outcome: GraftOutcome::Running,
5626            requested: graft::requested(&plan),
5627            adoption: None,
5628            adoption_error: None,
5629        });
5630        self.state.event(
5631            "graft",
5632            format!(
5633                "porting strengths of candidate(s) {} onto {}",
5634                plan.strengths
5635                    .iter()
5636                    .map(|(l, _, _)| l.to_string())
5637                    .collect::<Vec<_>>()
5638                    .join(", "),
5639                plan.winner
5640            ),
5641        );
5642        self.state.save()?;
5643
5644        let fix_prompt = prompt::graft(
5645            &self.state.instruction,
5646            plan.winner,
5647            &plan.strengths,
5648            &self.state.config.graph.language,
5649        );
5650        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5651        let sessions = self.state.config.graph.sessions;
5652        let artifacts = agent::artifacts_dir(&self.state.dir());
5653        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5654        let (_, seat, out) = self
5655            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5656                SeatJob {
5657                    prompt: fix_prompt.clone(),
5658                    spec,
5659                    seat,
5660                    cwd: wt.clone(),
5661                    timeout,
5662                    allow_write: true,
5663                    sessions,
5664                    artifacts: artifacts.clone(),
5665                    stem: "graft".to_owned(),
5666                    handover: None,
5667                }
5668            })
5669            .await;
5670        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5671            // Preserve the need to restore earlier fallback edits without
5672            // confusing an unstarted seat with an interrupted invocation.
5673            self.state.graft.as_mut().expect("graft record").outcome =
5674                GraftOutcome::WaitingForRestore;
5675            return self.stop_for_resource();
5676        }
5677        let mut why: Option<String> = None;
5678        match &out {
5679            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5680                why = Some("the fixer produced nothing usable".to_owned());
5681            }
5682            AgentOutcome::Ok(_) => {}
5683            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5684            AgentOutcome::Quota(o) => {
5685                self.state.quota.push(QuotaLoss::from_report(
5686                    seat.key.clone(),
5687                    "graft",
5688                    o.quota.as_ref(),
5689                ));
5690                why = Some("rate limited (quota)".to_owned());
5691            }
5692            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5693                why = Some(format!(
5694                    "the fixer failed: {}",
5695                    e.lines()
5696                        .next()
5697                        .unwrap_or("")
5698                        .chars()
5699                        .take(160)
5700                        .collect::<String>()
5701                ));
5702            }
5703        }
5704        let agent_id = seat.agent.clone();
5705        self.state.seats.insert(seat.key.clone(), seat);
5706
5707        let mut post = None;
5708        let mut lines = None;
5709        let _coordination = self.coordinate(&wt).await?;
5710        if why.is_none() {
5711            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5712            if let Ok(r) = &rescued {
5713                self.state.note_withheld("graft", &r.withheld);
5714            }
5715            let head = git::rev_parse(&wt, "HEAD").await?;
5716            // What is measured must be what gets reviewed and gated: a failed
5717            // rescue, or anything still uncommitted (withheld lockfiles
5718            // aside, which are never part of the tree), rejects the graft.
5719            let dirty = match &rescued {
5720                Ok(r) => git::status_porcelain(&wt)
5721                    .await
5722                    .map(|st| {
5723                        st.lines().any(|l| {
5724                            !r.withheld
5725                                .iter()
5726                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5727                        })
5728                    })
5729                    .unwrap_or(true),
5730                Err(_) => true,
5731            };
5732            if dirty {
5733                why = Some("the fixer left changes that could not be committed".to_owned());
5734            } else if head == pre {
5735                why = Some("the fixer changed nothing".to_owned());
5736            } else {
5737                lines = git::changed_lines(&wt, &pre, &head).await;
5738                post = Some(head);
5739            }
5740        }
5741        let (adoption, adoption_error) = match &out {
5742            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5743            _ => (None, None),
5744        };
5745        let requested = graft::requested(&plan);
5746        let outcome = match why {
5747            None => {
5748                self.state.event(
5749                    "graft",
5750                    format!(
5751                        "applied: {}",
5752                        lines.map_or_else(
5753                            || "changed lines unavailable".to_owned(),
5754                            |n| format!("{n} changed lines")
5755                        )
5756                    ),
5757                );
5758                GraftOutcome::Applied
5759            }
5760            Some(why) => {
5761                // Not settled until the restore is confirmed: the record
5762                // stays `Running`, so a resume retries it.
5763                crate::recovery::restore_repair(&wt, &pre)
5764                    .await
5765                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5766                self.state.event(
5767                    "graft",
5768                    format!("rolled back: {why}; the winner is untouched"),
5769                );
5770                GraftOutcome::RolledBack(why)
5771            }
5772        };
5773        self.state.graft = Some(GraftRecord {
5774            pre,
5775            post,
5776            lines,
5777            limit: None,
5778            agent: Some(agent_id),
5779            outcome,
5780            requested,
5781            adoption,
5782            adoption_error,
5783        });
5784        self.state.save()?;
5785        Ok(())
5786    }
5787
5788    // ----------------------------------------------------------------- fold
5789
5790    async fn fold_losers(&mut self) -> Result<()> {
5791        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5792            return Ok(());
5793        };
5794        if !self.state.candidate_preservation.is_empty() {
5795            bail!("candidate preservation incomplete; refusing cleanup");
5796        }
5797        let repo = self.state.repo.clone();
5798        let _coordination = self.coordinate(&repo).await?;
5799        let home = crate::run::home();
5800        let root = self.state.worktree_root();
5801        let isolated = crate::build_target::isolated(&self.state.config);
5802        let mut folded = Vec::new();
5803        for i in 0..self.state.candidates.len() {
5804            let c = &self.state.candidates[i];
5805            if c.label == winner || c.folded {
5806                continue;
5807            }
5808            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5809            let target = fold_target(&home, &root, &wt, isolated);
5810            remove_preserved_worktree(&repo, &wt).await?;
5811            reclaim_fold_target(&home, target);
5812            if git::branch_exists(&repo, &branch).await?
5813                && !git::branch_delete(&repo, &branch).await?
5814            {
5815                bail!("candidate branch removal refused");
5816            }
5817            self.state.candidates[i].folded = true;
5818            self.state.save()?;
5819            folded.push(label.to_string());
5820        }
5821        // The judges are finished; their checkouts are pure cost from here.
5822        for j in 1..=self.roles.judges.len() {
5823            let wt = root.join(format!("judge-{j}"));
5824            if wt.exists() {
5825                let target = fold_target(&home, &root, &wt, isolated);
5826                remove_read_seat_worktree(&mut self.state, &wt).await?;
5827                reclaim_fold_target(&home, target);
5828                self.state.save()?;
5829            }
5830        }
5831        // The design-deliberation stage is finished by the time a tally
5832        // exists — same reasoning as the judges above.
5833        if self.state.config.graph.advise {
5834            for k in 1..=self.state.config.graph.advisors {
5835                let wt = root.join(format!("advisor-{k}"));
5836                if wt.exists() {
5837                    let target = fold_target(&home, &root, &wt, isolated);
5838                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5839                    reclaim_fold_target(&home, target);
5840                    self.state.save()?;
5841                }
5842            }
5843        }
5844        if !folded.is_empty() {
5845            self.state
5846                .event("fold", format!("folded candidates {}", folded.join(", ")));
5847            self.state.save()?;
5848        }
5849        Ok(())
5850    }
5851
5852    // ------------------------------------------------------------ base sync
5853
5854    async fn hold_base_sync(&mut self) -> Result<bool> {
5855        self.hold_base_sync_as(None).await
5856    }
5857
5858    async fn hold_base_sync_kind(
5859        &mut self,
5860        kind: crate::base_sync_recovery::StopKind,
5861    ) -> Result<()> {
5862        self.hold_base_sync_as(Some(kind)).await?;
5863        Ok(())
5864    }
5865
5866    async fn hold_base_sync_as(
5867        &mut self,
5868        kind: Option<crate::base_sync_recovery::StopKind>,
5869    ) -> Result<bool> {
5870        if !self.state.base_sync_blocked() {
5871            self.state.base_sync_recovery.stop = None;
5872            return Ok(false);
5873        }
5874        let head = match self.state.winner() {
5875            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5876                .await
5877                .unwrap_or_default(),
5878            None => String::new(),
5879        };
5880        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5881            && !authorization.consumed
5882            && authorization.stop.head != head
5883        {
5884            authorization.refuse(format!(
5885                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5886                authorization.stop.head
5887            ));
5888        }
5889        self.state.record_base_sync_stop(&head);
5890        if let Some(kind) = kind {
5891            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5892            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5893                stop.kind = kind;
5894            }
5895        }
5896        self.state.save()?;
5897        Ok(true)
5898    }
5899
5900    async fn resume_legacy_sequencer_stop(
5901        &mut self,
5902        winner: &Candidate,
5903        scratch: &Path,
5904        head: &str,
5905    ) -> Result<()> {
5906        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5907
5908        if !resumable_sequencer_stop(&self.state)
5909            || legacy_sequencer_head(&self.state) != Some(head)
5910            || self.state.base_recovery_pending()
5911            || self
5912                .state
5913                .repair_grants
5914                .iter()
5915                .any(|grant| !grant.succeeded)
5916        {
5917            return Ok(());
5918        }
5919        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5920            return Ok(());
5921        };
5922        let owner = crate::queue::Queue::open().get(task)?;
5923        if owner.execution_runs().last() != Some(&self.state.id)
5924            || owner.status == crate::queue::TaskStatus::Done
5925            || owner.fresh_start
5926            || owner.review_branch.is_some()
5927            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5928        {
5929            return Ok(());
5930        }
5931
5932        let repo = self.state.repo.clone();
5933        let wait = repository_wait(&self.state, None);
5934        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5935        let common = crate::repo_lock::common_dir(&repo).await?;
5936        let op = self.state.base_sync_recovery.operations.last().unwrap();
5937        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5938            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5939            || git::current_branch(&winner.worktree).await?.as_deref()
5940                != Some(winner.branch.as_str())
5941            || common.is_none()
5942            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5943            || crate::repo_lock::common_dir(&owner.repo).await? != common
5944            || !git::is_clean(&winner.worktree).await?
5945        {
5946            return Ok(());
5947        }
5948        if scratch.try_exists()? {
5949            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5950            if admin.join("locked").try_exists()?
5951                || !git::git(
5952                    scratch,
5953                    &[
5954                        "status",
5955                        "--porcelain",
5956                        "--untracked-files=all",
5957                        "--ignored",
5958                    ],
5959                )
5960                .await?
5961                .is_empty()
5962            {
5963                return Ok(());
5964            }
5965            if git::checked_rebase_in_progress(scratch).await? {
5966                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5967                    || crate::rebase::rebase_target(scratch).await? != op.tip
5968                    || !git::unmerged_paths(scratch).await?.is_empty()
5969                {
5970                    return Ok(());
5971                }
5972            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5973                || git::rev_parse(scratch, "HEAD").await? != head
5974            {
5975                return Ok(());
5976            }
5977        }
5978
5979        self.state
5980            .base_sync_recovery
5981            .operations
5982            .last_mut()
5983            .unwrap()
5984            .finished = false;
5985        let diagnostic = self
5986            .state
5987            .base_sync
5988            .as_mut()
5989            .unwrap()
5990            .conflict
5991            .take()
5992            .unwrap();
5993        self.state.base_sync_recovery.stop = None;
5994        self.state.event(
5995            "rebase",
5996            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
5997        );
5998        self.state.save()
5999    }
6000
6001    /// Land the winner's tree on the current tip of `<remote>/<base>` before
6002    /// anything verifies it.
6003    ///
6004    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
6005    /// read whatever is checked out in the winner's worktree. Left alone that
6006    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
6007    /// it when the run *branched* - and a run takes long enough that the base
6008    /// has usually moved by the time it gets here. A gate that ran there
6009    /// answers "green on the commit this run started from", not "green on
6010    /// what is about to land", and the difference showed up three times in
6011    /// one day as a green run whose merge would have reverted a file another
6012    /// pull request had already landed.
6013    ///
6014    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
6015    /// `land::Step::Rebase` calls, rather than a second implementation of the
6016    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
6017    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
6018    /// doc warns about ("two answers to a question nobody notices until a
6019    /// diff is wrong").
6020    ///
6021    /// Foreign-checkout reviews instead merge the base into the owned shadow
6022    /// worktree, preserving the ancestry required for fast-forward delivery.
6023    /// A conflicting merge is aborted and held for operator resolution.
6024    ///
6025    /// A conflict is not the end of the road: the standing rebase is handed
6026    /// to the fixer seat, at most `graph.review_rounds` times, counted in
6027    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
6028    /// land). Once it finishes, review and the gate run as usual on the
6029    /// rebased tree, which is where a breakage the new base caused is caught
6030    /// by the ordinary gate-fix round. magi resolves nothing itself.
6031    ///
6032    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
6033    /// the current durable recovery interval, bounds how often the base is
6034    /// synchronized during active recovery (lifetime attempts remain evidence).
6035    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
6036    /// rebase the branch is restored, `state.base_sync.conflict` is set with
6037    /// what was tried (rounds spent, paths still conflicted) and the branch
6038    /// and worktree stay exactly as they were - untouched, for a person to
6039    /// look at - which is also what makes re-entering this function
6040    /// afterwards a no-op instead of a second attempt at the same wall. A
6041    /// push failure ends the same way.
6042    async fn sync_to_base(&mut self) -> Result<()> {
6043        if self.state.status == RunStatus::AlreadyInBase {
6044            return Ok(());
6045        }
6046        self.hold_base_sync().await?;
6047        let Some(winner) = self.state.winner().cloned() else {
6048            return Ok(());
6049        };
6050
6051        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
6052
6053        let repo = self.state.repo.clone();
6054        let remote = self.state.config.merge.remote.clone();
6055        let base_branch = self.state.base_branch.clone();
6056        let tracking = format!("{remote}/{base_branch}");
6057
6058        let fetched_base =
6059            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
6060        if !fetched_base
6061            && self
6062                .state
6063                .base_sync_recovery
6064                .stop
6065                .as_ref()
6066                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
6067        {
6068            self.state.event(
6069                "land",
6070                "cannot recheck recorded public branch divergence without a fresh base",
6071            );
6072            self.state.save()?;
6073            return Ok(());
6074        }
6075        // No network, or the remote never had this branch: the run already
6076        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
6077        // otherwise), and one that got this far is not blocked by a fetch
6078        // that fails now. It just has no newer tip to compare against.
6079        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
6080            return Ok(());
6081        };
6082
6083        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
6084        self.state.ensure_base_episode();
6085        let scratch = self.state.dir().join("base-sync");
6086        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
6087            .await?;
6088        let conflicted = self
6089            .state
6090            .base_sync
6091            .as_ref()
6092            .is_some_and(|s| s.conflict.is_some());
6093        let mut pending = self.state.pending_base_operation().cloned();
6094        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
6095        {
6096            Ok(active) => active,
6097            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
6098            Err(error) => return Err(error),
6099        };
6100        if in_progress {
6101            // Older resource stops predate operation reservations. Import the
6102            // standing Git operation, never retarget it to today's main.
6103            if pending.is_none()
6104                && self.state.base_sync_recovery.operations.is_empty()
6105                && !conflicted
6106                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
6107                    .await
6108                    .ok()
6109                    .as_deref()
6110                    == Some(head.as_str())
6111                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6112                && git::is_clean(&winner.worktree).await?
6113            {
6114                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
6115                if self.state.base_sync.is_none() {
6116                    self.state.base_sync = Some(BaseSync {
6117                        tip: saved_tip.clone(),
6118                        behind: 0,
6119                        attempts: 0,
6120                        conflict: None,
6121                        already_in: None,
6122                    });
6123                }
6124                self.state.reserve_base_operation(&head, &saved_tip);
6125                self.state.event(
6126                    "base-recovery",
6127                    "imported standing legacy rebase as a spent synchronization reservation",
6128                );
6129                self.state.save()?;
6130                pending = self.state.base_sync_recovery.operations.last().cloned();
6131            }
6132            let expected = pending.as_ref().map(|op| op.tip.as_str());
6133            if expected.is_none()
6134                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
6135            {
6136                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
6137                if self.state.base_sync.is_none() {
6138                    self.state.base_sync = Some(BaseSync {
6139                        tip: tip.clone(),
6140                        behind: 0,
6141                        attempts: 0,
6142                        conflict: None,
6143                        already_in: None,
6144                    });
6145                }
6146                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
6147                self.state.event("land", why);
6148                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6149                    .await?;
6150                return Ok(());
6151            }
6152        }
6153        if let Some(op) = &pending {
6154            // A replay may add the pinned base's commits, never foreign work.
6155            let mut replay_proven =
6156                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
6157            if !replay_proven && !in_progress && scratch.try_exists()? {
6158                let wait = repository_wait(&self.state, None);
6159                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6160                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
6161                    Ok(true) => {
6162                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
6163                        self.state.save()?;
6164                        git::worktree_remove(&repo, &scratch).await.ok();
6165                        replay_proven = true;
6166                    }
6167                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
6168                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
6169                }
6170            }
6171            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
6172                if self.state.foreign_checkout.is_some() {
6173                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
6174                        .await
6175                        .ok()
6176                        .as_deref()
6177                        == Some(op.head.as_str())
6178                        && git::rev_parse(&repo, &format!("{head}^2"))
6179                            .await
6180                            .ok()
6181                            .as_deref()
6182                            == Some(op.tip.as_str());
6183                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
6184                    .await
6185                    .is_ok_and(|m| m.is_empty())
6186                    && let Ok(added) =
6187                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
6188                {
6189                    replay_proven = true;
6190                    for commit in added {
6191                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
6192                            replay_proven = false;
6193                            break;
6194                        }
6195                    }
6196                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
6197                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
6198                }
6199            }
6200            // Never retarget an operation across a crash, even if main moved.
6201            // sync_to_head resets and cleans with -x, so even ignored untracked
6202            // files must stop recovery independently of the old tracked tree.
6203            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6204                || (head != op.head
6205                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
6206                        .await?
6207                        .is_empty())
6208                || (!git::is_clean(&winner.worktree).await?
6209                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
6210                        .await
6211                        .is_ok_and(|o| o.ok()))
6212                || !replay_proven
6213            {
6214                let why = format!(
6215                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
6216                    op.id
6217                );
6218                let sync = self
6219                    .state
6220                    .base_sync
6221                    .as_mut()
6222                    .context("reserved synchronization has no lifetime accounting")?;
6223                sync.conflict = Some(why.clone());
6224                self.state.event("land", why);
6225                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6226                    .await?;
6227                return Ok(());
6228            }
6229            if head != op.head {
6230                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6231            }
6232            tip = op.tip.clone();
6233        }
6234        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
6235        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
6236        if pending.is_none()
6237            && !conflicted
6238            && fetched_base
6239            && self
6240                .state
6241                .base_sync_recovery
6242                .episodes
6243                .last()
6244                .is_some_and(|e| e.boundary.is_some())
6245            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
6246            && let Ok(owner) = crate::queue::Queue::open().get(&task)
6247            && owner.execution_runs().last() == Some(&self.state.id)
6248            && owner.status != crate::queue::TaskStatus::Done
6249            && !owner.fresh_start
6250            && owner.review_branch.is_none()
6251            && crate::daemon::compatible_run_instruction(&self.state, &owner)
6252            && let Some(approval) = owner.resumption.as_ref()
6253            && approval.instruction == owner.instruction
6254            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6255            && git::is_clean(&winner.worktree).await?
6256            && self.state.renew_base_episode(&task, approval, &head, &tip)
6257        {
6258            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
6259            self.state.save()?;
6260        }
6261
6262        // Before any rebase, and before a recorded conflict is honoured: a
6263        // branch whose change reached the base under other commit ids has
6264        // nothing to rebase and nothing to conflict with, and a run that
6265        // already stopped on that phantom conflict recovers here on resume.
6266        // `behind == 0` with head == tip is a branch the base has since taken
6267        // in whole, whether or not a conflict was ever recorded: the ancestry
6268        // proof must still run (`classify` ignores a head still on the start
6269        // commit).
6270        if (behind > 0 || conflicted || head == tip)
6271            && self
6272                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
6273                .await?
6274        {
6275            return Ok(());
6276        }
6277        if conflicted && self.state.base_recovery_pending() {
6278            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6279            let owner =
6280                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6281            let owner_valid = owner.as_ref().is_ok_and(|t| {
6282                t.execution_runs().last() == Some(&self.state.id)
6283                    && t.assignment_accepts(&self.state)
6284                    && t.status != crate::queue::TaskStatus::Done
6285                    && !t.fresh_start
6286                    && t.review_branch.is_none()
6287            });
6288            let invalidation = if !owner_valid {
6289                Some("latest task ownership changed")
6290            } else if !owner.as_ref().is_ok_and(|t| {
6291                authorization
6292                    .generation
6293                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6294            }) {
6295                Some("owner approval generation changed")
6296            } else if authorization.question.as_ref().is_some_and(|question| {
6297                !crate::base_recovery_control::decision_current(
6298                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6299                    &self.state,
6300                    &authorization.task,
6301                    question,
6302                )
6303            }) {
6304                Some("recovery decision ownership, routing or stop evidence changed")
6305            } else if authorization.request.is_some()
6306                && !owner
6307                    .as_ref()
6308                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6309            {
6310                Some("owner decision changed")
6311            } else if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown
6312                && !authorization.scope.as_ref().is_some_and(|scope| {
6313                    scope.preparation_digest.is_some()
6314                        && scope.preparation_digest == self.state.preparation_digest(&head)
6315                })
6316            {
6317                Some("scratch preparation stop evidence changed")
6318            } else if let Some(scope) = &authorization.scope {
6319                if scope.tip != tip {
6320                    Some("fetched base changed")
6321                } else if !self
6322                    .state
6323                    .base_sync_recovery
6324                    .episodes
6325                    .last()
6326                    .is_some_and(|e| e.id == scope.episode)
6327                {
6328                    Some("active synchronization interval changed")
6329                } else if !owner
6330                    .as_ref()
6331                    .is_ok_and(|t| t.instruction == scope.instruction)
6332                {
6333                    Some("task instruction changed")
6334                } else {
6335                    None
6336                }
6337            } else {
6338                None
6339            };
6340            if let Some(reason) = invalidation {
6341                let authorization = self
6342                    .state
6343                    .base_sync_recovery
6344                    .authorizations
6345                    .last_mut()
6346                    .unwrap();
6347                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6348                self.state.save()?;
6349                return Ok(());
6350            }
6351            if !fetched_base
6352                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6353                || !git::is_clean(&winner.worktree).await?
6354                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6355            {
6356                return Ok(());
6357            }
6358            if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown {
6359                git::check_rebase_preparation(&self.state, &head, &self.state.dir()).await?;
6360            }
6361        }
6362        let recovery = conflicted && self.state.consume_base_recovery(&head);
6363        if conflicted {
6364            // Consumption (including a refused changed HEAD) is durable before Git.
6365            self.state.save()?;
6366            if !recovery {
6367                return Ok(());
6368            }
6369        }
6370
6371        if behind == 0 {
6372            // A fixer-finished rebase moves the branch ref before the
6373            // winner's worktree is told (`sync_to_head` below). A run that
6374            // died in between resumes here with `behind == 0` and a tree still
6375            // holding the pre-rebase files, which review and the gate would
6376            // then read. That state is exactly: HEAD moved off the tip the
6377            // rebase started from, yet the tree is still identical to that
6378            // tip. A tree with edits of its own differs from it, so nothing
6379            // is thrown away.
6380            if let Some(from) = self
6381                .state
6382                .rebase_fixes
6383                .iter()
6384                .rev()
6385                .find_map(|r| r.from.clone())
6386                && from != head
6387                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6388                    .await
6389                    .is_ok_and(|o| o.ok())
6390            {
6391                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6392            }
6393            // An earlier attempt may have rebased the branch locally and died
6394            // before pushing it (only the fresh-rebase arm below pushes).
6395            // Publish it now, so the plain push at PR time is not refused as
6396            // a non-fast-forward. A run already holding a recorded conflict
6397            // never reaches here; that case is out of scope.
6398            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6399            if let Some(why) = &conflict {
6400                self.state.status = RunStatus::Blocked;
6401                self.state.event("land", why.clone());
6402            }
6403            self.state.base_sync = Some(BaseSync {
6404                tip,
6405                behind: 0,
6406                attempts,
6407                conflict,
6408                already_in: None,
6409            });
6410            if pending.is_some() {
6411                self.state.finish_base_operation(Some(&head));
6412            }
6413            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6414                .await?;
6415            self.state.save()?;
6416            return Ok(());
6417        }
6418
6419        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6420            let why = format!(
6421                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6422                 synchronization(s); synchronizing again would only race it",
6423                winner.branch
6424            );
6425            self.state.status = RunStatus::Blocked;
6426            self.state.base_sync = Some(BaseSync {
6427                tip,
6428                behind,
6429                attempts,
6430                conflict: Some(why.clone()),
6431                already_in: None,
6432            });
6433            self.state.event("land", why);
6434            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6435                .await?;
6436            self.state.save()?;
6437            return Ok(());
6438        }
6439
6440        if self.state.foreign_checkout.is_some() {
6441            // Delivery to the operator's checkout is fast-forward only. A
6442            // rebase here would discard its saved head from our ancestry.
6443            let wait = repository_wait(&self.state, None);
6444            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6445            if self.state.base_sync.is_none() {
6446                self.state.base_sync = Some(BaseSync {
6447                    tip: tip.clone(),
6448                    behind,
6449                    attempts: 0,
6450                    conflict: None,
6451                    already_in: None,
6452                });
6453            }
6454            self.state.reserve_base_operation(&head, &tip);
6455            self.state.save()?;
6456            let merged = git::git_raw(
6457                &winner.worktree,
6458                &[
6459                    "-c",
6460                    "core.hooksPath=/dev/null",
6461                    "merge",
6462                    "--no-ff",
6463                    "--no-autostash",
6464                    "--no-edit",
6465                    "-m",
6466                    &format!("Merge {tracking} before verifying"),
6467                    &tip,
6468                ],
6469            )
6470            .await?;
6471            let conflict = if merged.ok() {
6472                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6473                self.state.event(
6474                    "land",
6475                    format!("merged {tracking} into {} before verifying", winner.branch),
6476                );
6477                None
6478            } else {
6479                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6480                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6481                }
6482                let why = format!(
6483                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6484                    winner.branch,
6485                    merged.stderr.chars().take(600).collect::<String>()
6486                );
6487                self.state.status = RunStatus::Blocked;
6488                self.state.event("land", &why);
6489                Some(why)
6490            };
6491            let synced = conflict.is_none();
6492            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6493            self.state
6494                .finish_base_operation(synced.then_some(fresh.as_str()));
6495            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6496            self.state.base_sync = Some(BaseSync {
6497                tip,
6498                behind: if synced { 0 } else { behind },
6499                attempts,
6500                conflict,
6501                already_in: None,
6502            });
6503            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6504                .await?;
6505            self.state.save()?;
6506            return Ok(());
6507        }
6508
6509        self.state.event(
6510            "land",
6511            format!(
6512                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6513                winner.branch
6514            ),
6515        );
6516        self.state.save()?;
6517
6518        // The remote's copy of the branch, read now and only if the fetch
6519        // really succeeded (a stale tracking ref must never pin a lease). It is
6520        // pushed over after a rebase only when it is a commit this branch
6521        // already contains, by ancestry or by patch (an earlier rebase of ours
6522        // that never reached the remote): anything else is somebody else's work.
6523        let branch_tracking = format!("{remote}/{}", winner.branch);
6524        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6525        let remote_tip = if self.state.task_pr_branch().is_none()
6526            && matches!(&fetched_branch, Ok(o) if o.ok())
6527        {
6528            git::rev_parse(&repo, &branch_tracking).await.ok()
6529        } else {
6530            None
6531        };
6532        // A remote tip this branch does not contain is somebody else's work:
6533        // rebasing would leave a local tip that can never be pushed. Stop
6534        // before touching anything and say so.
6535        if let Some(theirs) = &remote_tip
6536            && !git::is_ancestor(&repo, theirs, &head).await
6537            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6538                .await
6539                .is_ok_and(|missing| missing.is_empty())
6540        {
6541            let why = format!(
6542                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6543                 them",
6544                short(theirs),
6545                winner.branch
6546            );
6547            self.state.status = RunStatus::Blocked;
6548            self.state.base_sync = Some(BaseSync {
6549                tip,
6550                behind,
6551                attempts,
6552                conflict: Some(why.clone()),
6553                already_in: None,
6554            });
6555            self.state.event("land", why);
6556            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6557                .await?;
6558            self.state.save()?;
6559            return Ok(());
6560        }
6561
6562        if self.state.base_sync.is_none() {
6563            self.state.base_sync = Some(BaseSync {
6564                tip: tip.clone(),
6565                behind,
6566                attempts: 0,
6567                conflict: None,
6568                already_in: None,
6569            });
6570        }
6571        let scratch = self.state.dir().join("base-sync");
6572        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6573        {
6574            if error.is::<crate::repo_lock::ResourceBlocked>() {
6575                return Ok(());
6576            }
6577            return Err(error);
6578        }
6579        self.state.reserve_base_operation(&head, &tip);
6580        self.state.save()?;
6581        let rebased =
6582            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6583                .await
6584            {
6585                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6586                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6587                Err(e) => Err(e),
6588            };
6589        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6590        let stop_kind = match &rebased {
6591            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6592            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6593            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6594        };
6595        match rebased {
6596            Ok(None) => {
6597                // The branch ref moved, but a worktree that already had it
6598                // checked out (the winner's) was not told; sync its index and
6599                // files before anything reads them.
6600                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6601                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6602                self.state.finish_base_operation(Some(&fresh));
6603                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6604                let mut conflict = None;
6605                if let Some(pinned) = &remote_tip {
6606                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6607                    match pushed {
6608                        Ok(o) if o.ok() => self.state.event(
6609                            "land",
6610                            format!("pushed rebased {} to {remote}", winner.branch),
6611                        ),
6612                        Ok(o) => {
6613                            conflict = Some(format!(
6614                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6615                                winner.branch,
6616                                short(pinned),
6617                                o.stderr.chars().take(600).collect::<String>()
6618                            ));
6619                        }
6620                        Err(e) => {
6621                            conflict = Some(format!(
6622                                "rebased {} locally but could not push it: {e:#}",
6623                                winner.branch
6624                            ));
6625                        }
6626                    }
6627                }
6628                if let Some(why) = &conflict {
6629                    self.state.status = RunStatus::Blocked;
6630                    self.state.event("land", why.clone());
6631                }
6632                self.state.base_sync = Some(BaseSync {
6633                    tip: tip.clone(),
6634                    behind: 0,
6635                    attempts,
6636                    conflict,
6637                    already_in: None,
6638                });
6639                self.state
6640                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6641            }
6642            Ok(Some(conflict)) => {
6643                self.state.finish_base_operation(None);
6644                let why = format!(
6645                    "{} conflicts with {tracking} and did not rebase: {}",
6646                    winner.branch,
6647                    conflict.chars().take(600).collect::<String>()
6648                );
6649                self.state.status = RunStatus::Blocked;
6650                self.state.base_sync = Some(BaseSync {
6651                    tip,
6652                    behind,
6653                    attempts,
6654                    conflict: Some(why.clone()),
6655                    already_in: None,
6656                });
6657                self.state.event("land", why);
6658            }
6659            // A refused Git write or a busy repository: nothing is wrong with
6660            // the branch. The scratch rebase stays standing and the run
6661            // resumes into it (`base_sync` must not claim a conflict).
6662            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6663                self.state.save()?;
6664                return Ok(());
6665            }
6666            Err(e) => {
6667                self.state.finish_base_operation(None);
6668                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6669                self.state.status = RunStatus::Blocked;
6670                self.state.base_sync = Some(BaseSync {
6671                    tip,
6672                    behind,
6673                    attempts,
6674                    conflict: Some(why.clone()),
6675                    already_in: None,
6676                });
6677                self.state.event("land", why);
6678            }
6679        }
6680        if !self.state.base_sync_blocked() {
6681            self.state.base_sync_recovery.stop = None;
6682        }
6683        self.hold_base_sync_kind(stop_kind).await?;
6684        self.state.save()?;
6685        Ok(())
6686    }
6687
6688    /// Push a branch an earlier attempt rebased locally but never published,
6689    /// pinned to the remote tip read right after a successful fetch. Returns
6690    /// the reason when the run must stop; `None` when there was nothing to do
6691    /// (no remote copy, the same tip, or a remote copy this branch already
6692    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6693    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6694        // Task competitions publish only after the PR text gate, to their
6695        // public head; never resurrect a candidate branch on the remote.
6696        if self.state.task_pr_branch().is_some() {
6697            return None;
6698        }
6699        let repo = self.state.repo.clone();
6700        let remote = self.state.config.merge.remote.clone();
6701        let fetched = git::fetch(&repo, &remote, branch).await;
6702        if !matches!(&fetched, Ok(o) if o.ok()) {
6703            return None;
6704        }
6705        let branch_tracking = format!("{remote}/{branch}");
6706        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6707        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6708            return None;
6709        }
6710        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6711            .await
6712            .is_ok_and(|missing| missing.is_empty())
6713        {
6714            return Some(format!(
6715                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6716                 them",
6717                short(&theirs)
6718            ));
6719        }
6720        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6721            Ok(o) if o.ok() => {
6722                self.state
6723                    .event("land", format!("pushed rebased {branch} to {remote}"));
6724                None
6725            }
6726            Ok(o) => Some(format!(
6727                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6728                 someone may have pushed): {}",
6729                short(&theirs),
6730                o.stderr.chars().take(600).collect::<String>()
6731            )),
6732            Err(e) => Some(format!(
6733                "{branch} is rebased locally but could not be pushed: {e:#}"
6734            )),
6735        }
6736    }
6737
6738    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6739    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6740    /// whether it did.
6741    ///
6742    /// Checked only when the base is ahead of the branch. A failing check is
6743    /// "not proven" - the ordinary rebase path then decides - never a reason to
6744    /// stop the run.
6745    ///
6746    /// The remote copy of the branch is held to the same standard as the local
6747    /// one: if it carries a tip this worktree does not, that tip must itself be
6748    /// proven in the base, or nothing is settled (a pull request would
6749    /// otherwise be closed over commits nobody checked). The pull request is
6750    /// closed *before* the terminal status is saved; if that fails for a
6751    /// reason other than a refusal (no network, a `gh` error) the run is left
6752    /// `Blocked` with the reason as its conflict, which a resume retries -
6753    /// the same recovery a phantom conflict gets.
6754    async fn settle_already_in(
6755        &mut self,
6756        branch: &str,
6757        tip: &str,
6758        head: &str,
6759        attempts: usize,
6760        behind: usize,
6761    ) -> Result<bool> {
6762        let repo = self.state.repo.clone();
6763        let remote = self.state.config.merge.remote.clone();
6764        let start = self.state.base_commit.clone();
6765        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6766            Ok(Some(e)) => e,
6767            Ok(None) => return Ok(false),
6768            Err(e) => {
6769                tracing::warn!("already-in-base check for {branch}: {e:#}");
6770                return Ok(false);
6771            }
6772        };
6773        let mut verified = vec![head.to_owned()];
6774        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6775        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6776        let divergence = self
6777            .state
6778            .base_sync_recovery
6779            .stop
6780            .as_ref()
6781            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6782        if matches!(&fetched, Ok(o) if o.ok()) {
6783            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6784                Ok(theirs) if theirs != head => {
6785                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6786                        Ok(Some(_)) => verified.push(theirs),
6787                        _ => return Ok(false),
6788                    }
6789                }
6790                Err(_) if divergence => return Ok(false),
6791                _ => {}
6792            }
6793        } else if divergence
6794            && !matches!(
6795                git::remote_has_branch(&repo, &remote, &public_branch).await,
6796                Ok(false)
6797            )
6798        {
6799            // A failed fetch cannot discharge a recorded divergence.
6800            return Ok(false);
6801        }
6802        let base_branch = self.state.base_branch.clone();
6803        let message = format!(
6804            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6805             land",
6806            evidence.names(),
6807            evidence.proof.as_str()
6808        );
6809        let closed =
6810            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6811                .await;
6812        match closed {
6813            Ok(Ok(url)) => self
6814                .state
6815                .event("land", format!("closed {url}: superseded on {base_branch}")),
6816            Ok(Err(why)) => self
6817                .state
6818                .event("land", format!("did not close a pull request: {why}")),
6819            Err(e) => {
6820                let why = format!(
6821                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6822                     not be closed ({e:#}); resume to retry"
6823                );
6824                self.state.status = RunStatus::Blocked;
6825                self.state.base_sync = Some(BaseSync {
6826                    tip: tip.to_owned(),
6827                    behind,
6828                    attempts,
6829                    conflict: Some(why.clone()),
6830                    already_in: None,
6831                });
6832                self.state.event("land", why);
6833                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6834                    .await?;
6835                self.state.save()?;
6836                return Ok(true);
6837            }
6838        }
6839        self.state.status = RunStatus::AlreadyInBase;
6840        self.state.base_sync_recovery.stop = None;
6841        self.state.base_sync = Some(BaseSync {
6842            tip: tip.to_owned(),
6843            behind,
6844            attempts,
6845            conflict: None,
6846            already_in: Some(evidence),
6847        });
6848        self.state.event("land", message);
6849        self.state.save()?;
6850        self.settle_questions();
6851        Ok(true)
6852    }
6853
6854    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6855    /// last landed the winner on, once it has run, else the commit the run
6856    /// branched from.
6857    ///
6858    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6859    /// and `vote` all happen before there is a winner to rebase, so they
6860    /// compare every candidate against the branch point on purpose, and a
6861    /// base that moves after they are already done cannot change an answer
6862    /// they already gave.
6863    fn landing_base(&self) -> String {
6864        self.state
6865            .base_sync
6866            .as_ref()
6867            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6868    }
6869
6870    // ------------------------------------------------------- operator fix
6871
6872    /// Route specific, already-recorded review findings to a fixer for a
6873    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6874    /// entry point.
6875    ///
6876    /// Distinct from `review_loop`'s own fix step in three ways: it never
6877    /// runs a reviewer wave, it never spends review-round budget, and what
6878    /// happened is recorded as an [`OperatorFixRequest`] appended to
6879    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6880    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6881    /// and vote must never be rewritten to look like a manufactured blocking
6882    /// verdict.
6883    ///
6884    /// Only meaningful once review has actually concluded: `Ready` (handed
6885    /// off with findings still open, or simply concluded clean while minor
6886    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6887    /// gate failed). Everything else is refused: a run still in progress
6888    /// should simply be resumed, and a `Merged` run's branch has already
6889    /// landed — reopening *this* run's own record cannot change that, so the
6890    /// answer there is a fresh `magi review <branch>`.
6891    ///
6892    /// A real commit here re-verifies through a fresh, ordinary review-only
6893    /// run on the same branch ([`Self::review`]) rather than reopening this
6894    /// run's own `review_loop`: once any round in this run's history went
6895    /// clean, `review_conclusion` treats that as permanent by design (the
6896    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6897    /// way to force one more genuine reviewer wave out of *this* run without
6898    /// either rewriting history or weakening that guarantee for every other
6899    /// caller. A review-only run costs nothing extra — no implementation, no
6900    /// judging, no vote — and exercises the exact same review → verify →
6901    /// gate → (human) merge path, unmodified.
6902    pub async fn fix_selected(
6903        &mut self,
6904        ids: &[String],
6905        reason: &str,
6906        allow_stale: bool,
6907    ) -> Result<()> {
6908        let reason = reason.trim();
6909        if reason.is_empty() {
6910            bail!("a fix request needs a reason — that is the operator's own record of why");
6911        }
6912        if ids.is_empty() {
6913            bail!("no finding id given");
6914        }
6915        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6916            bail!(
6917                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6918                 has already concluded — can be given a targeted fix. A run still \
6919                 in progress should simply be resumed; a `merged` run's branch has \
6920                 already landed, so its answer is a fresh `magi review <branch>`, \
6921                 not reopening this run's own record",
6922                self.state.id,
6923                self.state.status.as_str()
6924            );
6925        }
6926        // Reassignment shares this claim through its atomic task save. Check
6927        // the canonical run identity inside it, before preflight or any await.
6928        let _claim = FixClaim::acquire(&self.state.dir())?;
6929        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6930        let home = crate::run::home();
6931        // The ordinary driver takes these same locks at admission. Keep the
6932        // execution lease through the fix, but never the owner lock across Git
6933        // or agent awaits.
6934        let execution = {
6935            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6936            let disk = RunState::load(&self.state.id)?;
6937            crate::pr_head::ensure_owner(&disk)?;
6938            anyhow::ensure!(
6939                disk.status == self.state.status && disk.released_to.is_none(),
6940                "run changed since it was loaded; reload before fixing"
6941            );
6942            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6943            anyhow::ensure!(
6944                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6945                "run {} is currently being worked on or its ownership is unknown",
6946                disk.id
6947            );
6948            let lease = crate::driver::maintenance(&home, &disk.id).context(
6949                "run is currently being worked on or its execution lease is unavailable",
6950            )?;
6951            self.state = disk;
6952            lease
6953        };
6954        let Some(winner) = self.state.winner().cloned() else {
6955            bail!("run {} has no winning candidate to fix", self.state.id);
6956        };
6957        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6958            bail!(
6959                "branch `{}` no longer exists; this run cannot be extended",
6960                winner.branch
6961            );
6962        }
6963        // Resolve every id before spending anything — an unknown id refuses
6964        // the whole request rather than silently dropping it — and dedup
6965        // while keeping the operator's own order.
6966        let mut seen = BTreeSet::new();
6967        let mut findings = Vec::new();
6968        let mut missing = Vec::new();
6969        for id in ids {
6970            if !seen.insert(id.clone()) {
6971                continue;
6972            }
6973            match self.state.finding(id) {
6974                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6975                    id: f.id.clone(),
6976                    severity: f.severity,
6977                    reviewer_vote: rec.vote,
6978                    round: round.round,
6979                    round_head: round.head.clone(),
6980                    reviewer: rec.reviewer,
6981                    agent: rec.agent.clone(),
6982                    file: f.file.clone(),
6983                    line: f.line,
6984                    title: f.title.clone(),
6985                    detail: f.detail.clone(),
6986                    outcome: OperatorFixOutcome::Pending,
6987                }),
6988                None => missing.push(id.clone()),
6989            }
6990        }
6991        if !missing.is_empty() {
6992            bail!(
6993                "unknown finding id(s): {}; nothing was changed",
6994                missing.join(", ")
6995            );
6996        }
6997
6998        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6999        let stale_details: Vec<(String, String)> = findings
7000            .iter()
7001            .filter(|f| f.round_head != head_at_request)
7002            .map(|f| (f.id.clone(), f.round_head.clone()))
7003            .collect();
7004        let stale = !stale_details.is_empty();
7005        if stale && !allow_stale {
7006            bail!(
7007                "the branch has moved since some finding(s) were raised — {} — now \
7008                 at {}; pass --allow-stale to fix anyway, or re-run review first",
7009                stale_details
7010                    .iter()
7011                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
7012                    .collect::<Vec<_>>()
7013                    .join(", "),
7014                short(&head_at_request)
7015            );
7016        }
7017
7018        let request = OperatorFixRequest {
7019            requested_at: Timestamp::now(),
7020            reason: reason.to_owned(),
7021            findings,
7022            head_at_request: head_at_request.clone(),
7023            allow_stale,
7024            stale,
7025            fix: None,
7026            result_head: None,
7027            follow_up_review_run: None,
7028        };
7029        self.state.event(
7030            "fix",
7031            format!(
7032                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
7033                request.findings.len(),
7034                request
7035                    .findings
7036                    .iter()
7037                    .map(|f| f.id.as_str())
7038                    .collect::<Vec<_>>()
7039                    .join(", "),
7040            ),
7041        );
7042        // Recorded now, before any worktree work or the fixer call itself —
7043        // and re-saved at each checkpoint below: a crash at any point after
7044        // this (mid fixer call, mid follow-up review) must not lose the fact
7045        // that this was requested, for which findings, and why. Everything
7046        // past this point reads and writes through `request_index` rather
7047        // than a local variable, since `request` itself is moved here.
7048        self.state.operator_fixes.push(request);
7049        self.state.save()?;
7050        let request_index = self.state.operator_fixes.len() - 1;
7051
7052        // A fresh, dedicated worktree for this one call, never the winner's
7053        // own worktree in place: that one may already be gone (folded away),
7054        // and reusing it in place would leave the branch checked out there
7055        // when the follow-up review below tries to check it out again. Freed
7056        // immediately after, either way — but only once confirmed clean:
7057        // `worktree_remove` is a `git worktree remove --force`, which would
7058        // otherwise discard uncommitted work left there by the operator or
7059        // another process before this had a chance to even look at it.
7060        let repo = self.state.repo.clone();
7061        let coordination = self.coordinate(&repo).await?;
7062        if winner.worktree.exists() {
7063            // Lockfiles a rescue commit withheld stay untracked on purpose and
7064            // are already recorded; they are not the operator's work to protect.
7065            let dirty = git::git(
7066                &winner.worktree,
7067                &["status", "--porcelain", "--untracked-files=all"],
7068            )
7069            .await?;
7070            let only_withheld = dirty.lines().all(|l| {
7071                l.strip_prefix("?? ")
7072                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
7073            });
7074            if !only_withheld {
7075                bail!(
7076                    "`{}` has uncommitted changes; refusing to touch it — commit or \
7077                     discard them first",
7078                    winner.worktree.display()
7079                );
7080            }
7081            git::worktree_remove(&self.state.repo, &winner.worktree)
7082                .await
7083                .ok();
7084        }
7085        let fix_worktree = self.state.worktree_root().join("operator-fix");
7086        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
7087        git::git(
7088            &self.state.repo,
7089            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
7090        )
7091        .await
7092        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
7093        if !git::is_clean(&fix_worktree).await? {
7094            git::worktree_remove(&self.state.repo, &fix_worktree)
7095                .await
7096                .ok();
7097            bail!(
7098                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
7099                winner.branch
7100            );
7101        }
7102        let repo_for_setup = self.state.repo.clone();
7103        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
7104            Ok(()) => {
7105                worktree_setup::prepare_with(
7106                    &self.state.config,
7107                    &repo_for_setup,
7108                    &fix_worktree,
7109                    crate::build_target::Coordination::Held(coordination.as_ref()),
7110                )
7111                .await
7112            }
7113            Err(e) => Err(e),
7114        };
7115        if let Err(e) = setup {
7116            git::worktree_remove(&self.state.repo, &fix_worktree)
7117                .await
7118                .ok();
7119            return Err(e);
7120        }
7121
7122        // This explicit operator request retries availability independently
7123        // of execute(); the previous call has already saved and cleaned up.
7124        self.state.resource_block = None;
7125
7126        let run_id = self.state.id.clone();
7127        let prompts = self.state.config.prompts.clone();
7128        let language = self.state.config.graph.language.clone();
7129        let sessions = self.state.config.graph.sessions;
7130        let artifacts = agent::artifacts_dir(&self.state.dir());
7131        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
7132            .findings
7133            .iter()
7134            .map(|f| Finding {
7135                id: f.id.clone(),
7136                severity: f.severity,
7137                file: f.file.clone(),
7138                line: f.line,
7139                title: f.title.clone(),
7140                detail: f.detail.clone(),
7141            })
7142            .collect();
7143        let fix_prompt = prompt::operator_fix_in(
7144            &self.state.instruction,
7145            &finding_list,
7146            reason,
7147            &stale_details,
7148            &head_at_request,
7149            &language,
7150            &self.state.config.graph.github_language,
7151        );
7152        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7153        drop(coordination);
7154        let (job, seat, out) = self
7155            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
7156                prompt: fix_prompt.clone(),
7157                spec,
7158                seat,
7159                cwd: fix_worktree.clone(),
7160                timeout,
7161                allow_write: true,
7162                sessions,
7163                artifacts: artifacts.clone(),
7164                stem: "operator-fix".to_owned(),
7165                handover: None,
7166            })
7167            .await;
7168        let agent_id = seat.agent.clone();
7169
7170        let mut fix = FixRecord {
7171            agent: agent_id,
7172            addressed: Vec::new(),
7173            rejected: Vec::new(),
7174            notes: String::new(),
7175            committed: false,
7176            failed: None,
7177            duration_ms: 0,
7178            continuation: None,
7179        };
7180        let mut final_seat = seat.clone();
7181        match out {
7182            AgentOutcome::Ok(o) => {
7183                fix.duration_ms = o.duration_ms;
7184                let parsed = verdict::extract_json::<FixReport>(&o.text);
7185                let incomplete_reason = match &parsed {
7186                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
7187                        "the reply parsed, but it reported a command whose own CLI \
7188                         never confirmed an exit status"
7189                            .to_owned(),
7190                    ),
7191                    Ok(_) => None,
7192                    Err(e) => Some(e.to_string()),
7193                };
7194                match incomplete_reason {
7195                    None => {
7196                        let report = parsed.expect("checked Ok above");
7197                        fix.addressed = report.addressed;
7198                        fix.rejected = report.rejected;
7199                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
7200                    }
7201                    Some(reason) => {
7202                        let (resumed_seat, resolved, failure, cont) = self
7203                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
7204                            .await;
7205                        fix.duration_ms += cont.cumulative_wait_ms;
7206                        fix.continuation = Some(cont);
7207                        final_seat = resumed_seat;
7208                        match resolved {
7209                            Some(report) => {
7210                                fix.addressed = report.addressed;
7211                                fix.rejected = report.rejected;
7212                                fix.notes =
7213                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
7214                            }
7215                            None => fix.failed = failure,
7216                        }
7217                    }
7218                }
7219            }
7220            AgentOutcome::Dropped(o) => {
7221                fix.duration_ms = o.duration_ms;
7222                let why = o
7223                    .dropped
7224                    .as_ref()
7225                    .map(|d| d.why.as_str())
7226                    .unwrap_or("the CLI ended the stream without delivering its answer");
7227                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
7228            }
7229            AgentOutcome::Quota(o) => {
7230                self.state.quota.push(QuotaLoss::from_report(
7231                    final_seat.key.clone(),
7232                    "fix",
7233                    o.quota.as_ref(),
7234                ));
7235                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
7236            }
7237            AgentOutcome::Failed(e) => fix.failed = Some(e),
7238            AgentOutcome::ResourceBlocked(e) => {
7239                fix.failed = Some(format!("the fixer was not started: {e}"));
7240            }
7241        }
7242        // Even a deferred call must rescue edits, release the worktree and
7243        // finalize its record below so an explicit `magi fix` can retry.
7244        if fix.continuation.is_none() {
7245            fix.continuation = Some(ContinuationRecord::not_needed());
7246        }
7247        self.state.seats.insert(final_seat.key.clone(), final_seat);
7248
7249        let rescue_message = format!(
7250            "magi: operator-selected fix ({}) (uncommitted work)",
7251            self.state.operator_fixes[request_index]
7252                .findings
7253                .iter()
7254                .map(|f| f.id.as_str())
7255                .collect::<Vec<_>>()
7256                .join(", ")
7257        );
7258        let repo = self.state.repo.clone();
7259        let coordination = self.coordinate(&repo).await?;
7260        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
7261            self.state.note_withheld("fix", &r.withheld);
7262        }
7263        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
7264        fix.committed = after != head_at_request;
7265        git::worktree_remove(&self.state.repo, &fix_worktree)
7266            .await
7267            .ok();
7268        drop(coordination);
7269
7270        self.state.event(
7271            "fix",
7272            match &fix.failed {
7273                Some(reason) => format!(
7274                    "operator fix: adoption report was lost ({reason}); {}",
7275                    if fix.committed {
7276                        "committed"
7277                    } else {
7278                        "NO new commit"
7279                    }
7280                ),
7281                None => format!(
7282                    "operator fix: {} addressed, {} rejected, {}",
7283                    fix.addressed.len(),
7284                    fix.rejected.len(),
7285                    if fix.committed {
7286                        "committed"
7287                    } else {
7288                        "NO new commit"
7289                    }
7290                ),
7291            },
7292        );
7293
7294        // Every selected finding gets an outcome — never left `Pending` once
7295        // the fixer's own turn is over. A report that never came back at all
7296        // marks every one of them `Unreported`, not silently "not addressed":
7297        // quota, a dropped stream, or an exhausted continuation are gaps in
7298        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7299        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7300        for f in &mut self.state.operator_fixes[request_index].findings {
7301            f.outcome = if fix.failed.is_some() {
7302                OperatorFixOutcome::Unreported
7303            } else if fix.addressed.contains(&f.id) {
7304                OperatorFixOutcome::Addressed
7305            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7306                OperatorFixOutcome::Rejected { why: r.why.clone() }
7307            } else {
7308                OperatorFixOutcome::Unreported
7309            };
7310        }
7311
7312        let committed = fix.committed;
7313        if committed {
7314            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7315        }
7316        self.state.operator_fixes[request_index].fix = Some(fix);
7317        // Saved again now that the fixer's own outcome is final, on top of
7318        // the save right after the request was first pushed above.
7319        self.state.save()?;
7320        if self.state.resource_block.is_some() {
7321            return self.stop_for_resource();
7322        }
7323
7324        if committed {
7325            self.state.event(
7326                "fix",
7327                format!(
7328                    "operator fix committed {}; opening a follow-up review-only run",
7329                    short(&after)
7330                ),
7331            );
7332            self.state.save()?;
7333            drop(execution);
7334            // The new review owns its own execution. Update only its audit link
7335            // afterwards, since publication may have changed the old record.
7336            let event_count = self.state.events.len();
7337            let save_follow_up = |state: &mut RunState| -> Result<()> {
7338                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7339                let _execution = crate::driver::maintenance(&home, &state.id)?;
7340                let mut disk = RunState::load(&state.id)?;
7341                disk.events.extend(state.events.drain(event_count..));
7342                let follow_up = state.operator_fixes[request_index]
7343                    .follow_up_review_run
7344                    .clone();
7345                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7346                disk.save()?;
7347                *state = disk;
7348                Ok(())
7349            };
7350            // The operator asked for the fix, and the follow-up serves whatever
7351            // task the run it follows served.
7352            let origin =
7353                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7354            match Self::review(
7355                &self.state.repo,
7356                &winner.branch,
7357                self.state.config.clone(),
7358                origin,
7359            )
7360            .await
7361            {
7362                Ok(mut follow_up) => {
7363                    follow_up.state.event(
7364                        "start",
7365                        format!(
7366                            "requested by an operator fix on run {} for finding(s) {}",
7367                            self.state.id,
7368                            self.state.operator_fixes[request_index]
7369                                .findings
7370                                .iter()
7371                                .map(|f| f.id.as_str())
7372                                .collect::<Vec<_>>()
7373                                .join(", "),
7374                        ),
7375                    );
7376                    follow_up.state.save()?;
7377                    let follow_up_id = follow_up.state.id.clone();
7378                    // The follow-up is a run like any other: it belongs to the
7379                    // task of the run it follows, or to one filed for it.
7380                    let adopted = match crate::direct::adopt(
7381                        &follow_up.state,
7382                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7383                    ) {
7384                        Ok(a) => a,
7385                        Err(e) => {
7386                            // An ownerless run must not spend agent calls; it
7387                            // stays saved, and `magi run --resume` adopts it.
7388                            self.state.event(
7389                                "fix",
7390                                format!(
7391                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7392                                ),
7393                            );
7394                            save_follow_up(&mut self.state)?;
7395                            return Ok(());
7396                        }
7397                    };
7398                    let executed = follow_up.execute().await;
7399                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7400                    if let Some(a) = adopted {
7401                        a.finish(&follow_up.state, executed);
7402                    }
7403                    if let Some(e) = failure {
7404                        self.state.event(
7405                            "fix",
7406                            format!(
7407                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7408                            ),
7409                        );
7410                    }
7411                    self.state.operator_fixes[request_index].follow_up_review_run =
7412                        Some(follow_up_id);
7413                }
7414                Err(e) => {
7415                    self.state.event(
7416                        "fix",
7417                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7418                    );
7419                }
7420            }
7421            save_follow_up(&mut self.state)?;
7422        }
7423
7424        Ok(())
7425    }
7426
7427    // --------------------------------------------------------------- review
7428
7429    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7430    /// names, in order, each at most once, moving on only when the call
7431    /// advances (an error, a quota hit or nothing usable - the same decision
7432    /// point `agent::chain_advances` is for the other chained roles).
7433    ///
7434    /// Each agent gets its own seat from `Runner::seat`: the same agent
7435    /// continues its conversation (the winner's own implementer seat when it
7436    /// is the winner's author, now that the competition is over), another
7437    /// takes a fresh one so the full prompt is sent again. A handover is
7438    /// recorded under `node`, which is what makes the fallback stick for the
7439    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7440    /// is returned, so an exhausted chain reads exactly like a single failed
7441    /// fixer: one quota loss, the same wording, the same refund. An earlier
7442    /// attempt's edits are left in the tree and judged, with the final
7443    /// attempt's, by what git says afterwards.
7444    ///
7445    /// Returns the job that produced the outcome, for `continue_fix_report`.
7446    async fn ask_fixer(
7447        &mut self,
7448        winner: &Candidate,
7449        node: &'static str,
7450        round: Option<usize>,
7451        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7452    ) -> (SeatJob, SeatState, AgentOutcome) {
7453        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7454        self.ask_fixer_among(attempts, node, round, None, build)
7455            .await
7456    }
7457
7458    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7459    /// worktree and a commit: before the next agent is asked after one that
7460    /// did not satisfy the call, the worktree is put back on that commit, so
7461    /// a failed agent's partial edits are not carried into the next one.
7462    async fn ask_fixer_among(
7463        &mut self,
7464        attempts: Vec<(AgentSpec, String)>,
7465        node: &'static str,
7466        round: Option<usize>,
7467        restore: Option<(&Path, &str)>,
7468        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7469    ) -> (SeatJob, SeatState, AgentOutcome) {
7470        let run_id = self.state.id.clone();
7471        let prompts = self.state.config.prompts.clone();
7472        let cache = self.state.config.cache_dir();
7473        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7474        let mut last = None;
7475        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7476            let seat = self.seat(&key, &spec.id);
7477            let mut job = build(spec.clone(), seat);
7478            if i > 0 {
7479                job.stem = format!("{}-{}", job.stem, spec.id);
7480            }
7481            let ctx = WaveCtx {
7482                carry_seats: false,
7483                pauses: Some((&self.pause, &self.interrupt)),
7484                run: &run_id,
7485                node,
7486                prompts: &prompts,
7487                cache: cache.as_deref(),
7488                round,
7489            };
7490            let (seat, out) =
7491                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7492            // A resource block never advances the chain: the chosen agent
7493            // was not asked, so it must be the one asked again on resume.
7494            let advances = match &out {
7495                AgentOutcome::Ok(o) => agent::output_advances(o),
7496                AgentOutcome::ResourceBlocked(_) => false,
7497                _ => true,
7498            };
7499            if let Some(next) = ids.get(i + 1)
7500                && advances
7501            {
7502                self.state.seats.insert(seat.key.clone(), seat.clone());
7503                let class =
7504                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7505                let reason = match &out {
7506                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7507                    other => fail_reason(other),
7508                };
7509                // A failed agent's edits must not reach the next one, and a
7510                // restore that did not work ends the chain: the call fails
7511                // and the caller's own (confirmed) restore decides.
7512                if let Some((wt, rev)) = restore
7513                    && let Err(e) = self.graft_restore(wt, rev).await
7514                {
7515                    let why =
7516                        format!("could not restore the worktree before the next fixer: {e:#}");
7517                    tracing::warn!("{why}");
7518                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7519                        AgentOutcome::ResourceBlocked(why)
7520                    } else {
7521                        AgentOutcome::Failed(why)
7522                    };
7523                    last = Some((job, seat, out));
7524                    break;
7525                }
7526                record_handover(
7527                    &mut self.state,
7528                    node,
7529                    &seat.key,
7530                    &spec.id,
7531                    next,
7532                    &class,
7533                    &reason,
7534                );
7535                continue;
7536            }
7537            last = Some((job, seat, out));
7538            break;
7539        }
7540        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7541        if let AgentOutcome::Quota(output) = &out
7542            && node != "graft"
7543        {
7544            // Graft is best effort: its caller records the loss and restores
7545            // the pre-graft tree, then proceeds to review and gate.
7546            // Every fallback was tried. Machine outages cannot be repaired by
7547            // spending a fix round; use each caller's resumable resource path.
7548            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7549            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7550            self.state.quota.push(loss);
7551            self.state.seats.insert(seat.key.clone(), seat.clone());
7552            self.state.status = RunStatus::Blocked;
7553            return (
7554                job,
7555                seat,
7556                AgentOutcome::ResourceBlocked(
7557                    "fixer unavailable; restore agent availability and resume".into(),
7558                ),
7559            );
7560        }
7561        (job, seat, out)
7562    }
7563
7564    /// The one repair a verification-only failure earns (see
7565    /// [`crate::recovery`]), before the first review round of a run that took
7566    /// a branch over.
7567    ///
7568    /// Saved as started *before* the fixer is called, so a resume never
7569    /// repairs twice; a start found on re-entry is rolled back to the commit
7570    /// it began from. A failed or unusable fixer leaves the tree as it was and
7571    /// the review goes on over it, so the first round's own verification
7572    /// reports the failure again. The failure is never carried into a round as
7573    /// a result: verification is re-run on whatever commit this leaves.
7574    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7575        use crate::recovery::{Mode, Repair};
7576        if !self.state.reviews.is_empty() {
7577            return Ok(());
7578        }
7579        let Some(mut rec) = self.state.recovery.clone() else {
7580            return Ok(());
7581        };
7582        if rec.mode != Mode::VerifyRepair {
7583            return Ok(());
7584        }
7585        let wt = winner.worktree.clone();
7586        let mut head = git::rev_parse(&wt, "HEAD").await?;
7587        match rec.repair.clone() {
7588            Repair::Done { .. } => return Ok(()),
7589            Repair::WaitingForRestore { before } => {
7590                self.graft_restore(&wt, &before).await?;
7591                head = before;
7592                rec.repair = Repair::NotStarted;
7593                self.state.recovery = Some(rec.clone());
7594                self.state.save()?;
7595            }
7596            Repair::Started { before } => {
7597                // Interrupted: the unfinished edits are not trusted.
7598                // An unconfirmed rollback blocks the run with `Started` kept,
7599                // so a resume retries it; the tree is never reviewed as is.
7600                if let Err(e) = self.graft_restore(&wt, &before).await {
7601                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7602                        return Err(e);
7603                    }
7604                    return self
7605                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7606                        .await;
7607                }
7608                rec.repair = Repair::Done {
7609                    before: before.clone(),
7610                    after: before,
7611                    committed: false,
7612                    failed: Some("interrupted; rolled back".to_owned()),
7613                };
7614                self.state
7615                    .event("recovery", "the repair was interrupted and rolled back");
7616                self.state.recovery = Some(rec);
7617                self.state.save()?;
7618                return Ok(());
7619            }
7620            Repair::NotStarted => {}
7621        }
7622        if crate::recovery::recheck(&mut rec, &head) {
7623            self.state.event("recovery", rec.summary());
7624            self.state.recovery = Some(rec);
7625            self.state.save()?;
7626            return Ok(());
7627        }
7628        rec.repair = Repair::Started {
7629            before: head.clone(),
7630        };
7631        self.state.recovery = Some(rec.clone());
7632        self.state.save()?;
7633
7634        let language = self.state.config.graph.language.clone();
7635        let sessions = self.state.config.graph.sessions;
7636        let artifacts = agent::artifacts_dir(&self.state.dir());
7637        let fix_prompt = prompt::recovery_fix(
7638            &self.state.instruction,
7639            &rec,
7640            self.state.config.graph.review_rounds,
7641            &language,
7642        );
7643        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7644        self.state.event(
7645            "recovery",
7646            format!(
7647                "repair: the fixer starts from the failed verification on {}",
7648                short(&head)
7649            ),
7650        );
7651        let (_job, seat, out) = self
7652            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7653                prompt: fix_prompt.clone(),
7654                spec,
7655                seat,
7656                cwd: wt.clone(),
7657                timeout,
7658                allow_write: true,
7659                sessions,
7660                artifacts: artifacts.clone(),
7661                stem: "fix-recovery".to_owned(),
7662                handover: None,
7663            })
7664            .await;
7665        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7666            rec.repair = Repair::WaitingForRestore { before: head };
7667            self.state.recovery = Some(rec);
7668            return self.stop_for_resource();
7669        }
7670        let failed = match &out {
7671            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7672            AgentOutcome::Quota(o) => {
7673                self.state.quota.push(QuotaLoss::from_report(
7674                    seat.key.clone(),
7675                    "fix",
7676                    o.quota.as_ref(),
7677                ));
7678                Some("rate limited (quota); the fixer could not run".to_owned())
7679            }
7680            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7681            AgentOutcome::Failed(e) => Some(e.clone()),
7682        };
7683        self.state.seats.insert(seat.key.clone(), seat);
7684        let coordination = self.coordinate(&wt).await?;
7685        let failed = match failed {
7686            // The agent's partial edits are not kept.
7687            Some(why) => {
7688                if let Err(e) = git::restore_to(&wt, &head).await {
7689                    return self
7690                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7691                        .await;
7692                }
7693                Some(why)
7694            }
7695            None => {
7696                if let Ok(r) = git::rescue_commit(
7697                    &wt,
7698                    "magi: recovery repair of the failed verification (uncommitted work)",
7699                )
7700                .await
7701                {
7702                    self.state.note_withheld("fix", &r.withheld);
7703                }
7704                None
7705            }
7706        };
7707        let after = git::rev_parse(&wt, "HEAD").await?;
7708        drop(coordination);
7709        self.state.event(
7710            "recovery",
7711            match &failed {
7712                Some(why) => format!("repair: nothing kept ({why})"),
7713                None if after != head => {
7714                    format!("repair: committed {}", short(&after))
7715                }
7716                None => "repair: the fixer made no commit".to_owned(),
7717            },
7718        );
7719        rec.repair = Repair::Done {
7720            before: head.clone(),
7721            committed: after != head,
7722            after,
7723            failed,
7724        };
7725        self.state.recovery = Some(rec);
7726        self.state.save()?;
7727        Ok(())
7728    }
7729
7730    /// A repair whose rollback could not be confirmed: the run is blocked and
7731    /// resumable, and the unconfirmed state is never reviewed.
7732    async fn stop_recovery(
7733        &mut self,
7734        mut rec: crate::recovery::RecoveryRecord,
7735        head: &str,
7736        why: String,
7737    ) -> Result<()> {
7738        // `Started` stays recorded: a resume retries the restore.
7739        rec.repair = crate::recovery::Repair::Started {
7740            before: head.to_owned(),
7741        };
7742        self.state.recovery = Some(rec);
7743        self.state
7744            .event("recovery", format!("repair could not be undone: {why}"));
7745        self.state.status = RunStatus::Blocked;
7746        self.state.save()?;
7747        bail!("recovery repair could not be rolled back: {why}")
7748    }
7749
7750    async fn review_loop(&mut self) -> Result<()> {
7751        if self.hold_base_sync().await? {
7752            return Ok(());
7753        }
7754        loop {
7755            if self
7756                .state
7757                .base_sync
7758                .as_ref()
7759                .is_some_and(|s| s.conflict.is_some())
7760            {
7761                return Ok(());
7762            }
7763            if self.catchup_repairable() {
7764                let record = self.state.reviews.last().expect("repairable round").clone();
7765                let winner = self
7766                    .state
7767                    .winner()
7768                    .cloned()
7769                    .context("catch-up repair has no winner")?;
7770                if !self.fix_review_round(&winner, record).await? {
7771                    return Ok(());
7772                }
7773            }
7774            self.review_loop_pass().await?;
7775            if !self.catchup_repairable() {
7776                return Ok(());
7777            }
7778        }
7779    }
7780
7781    /// Derive an owed catch-up repair from durable round evidence, including
7782    /// reentry after a crash before the fixer was dispatched.
7783    fn catchup_repairable(&self) -> bool {
7784        self.state.reviews.len() < self.state.config.graph.review_rounds
7785            && self.state.reviews.last().is_some_and(|r| {
7786                !r.clean
7787                    && r.blocking == 0
7788                    && r.fix.is_none()
7789                    && r.e2e_status() == E2eStatus::Failed
7790            })
7791    }
7792
7793    async fn review_loop_pass(&mut self) -> Result<()> {
7794        // A base that would not rebase is a person's decision, not a review
7795        // round: nothing here would change the answer, and reviewers and a
7796        // fixer would be spending real budget on a tree that cannot land
7797        // regardless of what they find.
7798        if self
7799            .state
7800            .base_sync
7801            .as_ref()
7802            .is_some_and(|s| s.conflict.is_some())
7803        {
7804            return Ok(());
7805        }
7806        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7807        // agent files with `magi task add` name the run that paid for it. The
7808        // prompt overlay is cloned alongside it because the waves borrow it
7809        // while `self` is mutably borrowed by the node's own bookkeeping.
7810        let run_id = self.state.id.clone();
7811        let prompts = self.state.config.prompts.clone();
7812        let Some(winner) = self.state.winner().cloned() else {
7813            return Ok(());
7814        };
7815        let granted_review = self
7816            .state
7817            .repair_grants
7818            .last()
7819            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7820            .cloned();
7821        let fresh_review = granted_review
7822            .as_ref()
7823            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7824        let max_rounds = granted_review
7825            .as_ref()
7826            .map_or(self.state.config.graph.review_rounds, |g| {
7827                g.review_start.saturating_add(1)
7828            });
7829        // A clean round, an exhausted round budget, or a stalled tree (see
7830        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7831        // they are recorded — recomputed here, not read off `status`, so a
7832        // reentry into a run that already stopped restates the identical
7833        // verdict instead of silently handing back whatever an earlier node
7834        // in this same walk clobbered `status` to (a solo-candidate
7835        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7836        // below runs an empty range once the budget is spent, and would
7837        // otherwise fall through without touching `status` at all.
7838        if let Some(status) =
7839            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7840        {
7841            // A reentry after a crash between the last round's save and
7842            // `stop_reviewing` reaches the hand-off here, not there.
7843            if status == RunStatus::Gating {
7844                self.record_contested_handoff();
7845            }
7846            self.state.status = status;
7847            self.state.save()?;
7848            return Ok(());
7849        }
7850        self.state.status = RunStatus::Reviewing;
7851        // A last recorded round whose own verification never resolved
7852        // (`ResourceBlocked` — the shared build cache, not the patch) is
7853        // never a concluded round, whatever the round budget says: starting
7854        // a fresh round on top of it would spend a whole new reviewer wave
7855        // re-reading an unchanged patch instead of just retrying the one
7856        // check that actually needs it, and once the budget is spent the
7857        // loop below has nothing left to do at all (its range is empty).
7858        // Retry that check directly instead, exactly the same retry
7859        // `stop_reviewing` already does for its own catch-up case.
7860        if !fresh_review
7861            && self.state.reviews.last().is_some_and(|r| {
7862                r.e2e_status() == E2eStatus::ResourceBlocked
7863                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7864            })
7865        {
7866            let shell = self.state.config.shell();
7867            return self
7868                .stop_unresolved_review(
7869                    "the last round's own verification never resolved",
7870                    &shell,
7871                    &winner.worktree,
7872                )
7873                .await;
7874        }
7875
7876        if granted_review.is_none() {
7877            self.recovery_repair(&winner).await?;
7878        }
7879        if self.resource_halt()? {
7880            return Ok(());
7881        }
7882
7883        let repo = self.state.repo.clone();
7884        let root = self.state.worktree_root();
7885        let language = self.state.config.graph.language.clone();
7886        let sessions = self.state.config.graph.sessions;
7887        let artifacts = self.merge_repair_artifacts();
7888        let base = self.landing_base();
7889        let base_short = short(&base);
7890        let reviewers = self.roles.reviewers.clone();
7891        let shell = self.state.config.shell();
7892
7893        for round in (self.state.reviews.len() + 1)..=max_rounds {
7894            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7895            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7896            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7897            // The prior round's own record, already persisted — never a
7898            // hand-carried variable of just its failing output: that is
7899            // exactly what let a round's e2e result drift out of sync with
7900            // which commit it was actually about (see `SCHEMA`'s doc for
7901            // schema 8). Judged against `head`, the commit reviewers are
7902            // about to look at now, so the summary always reads as "an
7903            // earlier head" here — this round's own patch has not been
7904            // checked yet.
7905            let prev_verification = self
7906                .state
7907                .reviews
7908                .last()
7909                .and_then(|r| r.verification_summary(&head));
7910            // Only the first round of a run that took a branch over: later
7911            // rounds have this run's own history.
7912            let prior_section = match (&self.state.recovery, round) {
7913                (Some(rec), 1) if self.state.reviews.is_empty() => {
7914                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7915                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7916                            Some(crate::recovery::head_of(
7917                                &git::diff(&winner.worktree, reviewed, "HEAD")
7918                                    .await
7919                                    .unwrap_or_default(),
7920                                crate::recovery::SINCE_DIFF_MAX,
7921                            ))
7922                        }
7923                        _ => None,
7924                    };
7925                    Some(prompt::recovery_review(rec, since.as_deref()))
7926                }
7927                _ => None,
7928            };
7929
7930            // Each reviewer gets its own detached checkout of exactly this
7931            // commit: nobody can perturb the winner's tree, and the fixer can
7932            // keep working without racing a reviewer.
7933            let mut jobs = Vec::new();
7934            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7935                self.coordinate(&repo).await?
7936            } else {
7937                None
7938            };
7939            for (r, spec) in reviewers.iter().cloned().enumerate() {
7940                let wt = root.join(format!("review-{}", r + 1));
7941                // `clean -fdx` in a reset wipes setup's products, so every
7942                // round sets the seat up again.
7943                if wt.exists() {
7944                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7945                } else {
7946                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7947                        None
7948                    } else {
7949                        self.coordinate(&repo).await?
7950                    };
7951                    git::worktree_add_detached(&repo, &wt, &head).await?;
7952                }
7953                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7954                    None
7955                } else {
7956                    self.coordinate(&repo).await?
7957                };
7958                self.setup_seat_worktree(
7959                    &repo,
7960                    &wt,
7961                    false,
7962                    coordination.as_ref().or(_setup_lease.as_ref()),
7963                )
7964                .await?;
7965                let seat_key = format!("review-{}", r + 1);
7966                // The seat starts the round on whoever answered it last, not
7967                // on the agent the spec names, so a failure is not re-paid.
7968                let spec = pick_start_spec(
7969                    &self.roles.reviewer_roster,
7970                    spec,
7971                    self.state.seat_history.get(&seat_key),
7972                );
7973                let seat = self.seat(&seat_key, &spec.id);
7974                jobs.push(SeatJob {
7975                    prompt: prompt::review(&prompt::ReviewCtx {
7976                        instruction: &self.state.instruction,
7977                        branch: &winner.branch,
7978                        base_short: &base_short,
7979                        stat: &stat,
7980                        patch: &patch,
7981                        verification: prev_verification.as_ref(),
7982                        prior: prior_section.as_deref(),
7983                        reviewers: reviewers.len(),
7984                        round,
7985                        rounds: max_rounds,
7986                        // A review-only run has no rankings, so nothing
7987                        // competed for this patch and the reviewer is told so.
7988                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7989                        lens: Lens::for_seat(r),
7990                        language: &language,
7991                        github_language: &self.state.config.graph.github_language,
7992                    }),
7993                    spec,
7994                    seat,
7995                    cwd: wt,
7996                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7997                    allow_write: false,
7998                    sessions,
7999                    artifacts: artifacts.clone(),
8000                    stem: format!("review-{round}-{}", r + 1),
8001                    handover: None,
8002                });
8003            }
8004
8005            drop(coordination);
8006            self.state.event(
8007                "review",
8008                format!(
8009                    "round {round}: {} reviewers on {}",
8010                    jobs.len(),
8011                    short(&head)
8012                ),
8013            );
8014            let mut quota_losses = Vec::new();
8015            let review_retries = self.state.config.graph.retries;
8016            let review_cache = self.state.config.cache_dir();
8017            let ctx = WaveCtx {
8018                carry_seats: true,
8019                pauses: Some((&self.pause, &self.interrupt)),
8020                run: &run_id,
8021                node: "review",
8022                prompts: &prompts,
8023                cache: review_cache.as_deref(),
8024                round: Some(round),
8025            };
8026            let results = ask_json_wave::<Review>(
8027                jobs,
8028                Arc::clone(&self.sem),
8029                review_retries,
8030                &self.roles.reviewer_roster,
8031                &ctx,
8032                &mut quota_losses,
8033                &mut self.state,
8034                &|_: &Review| Ok(()),
8035            )
8036            .await;
8037            if self.state.resource_block.is_some() {
8038                return self.stop_for_resource();
8039            }
8040            // Counted before the move below: how many of *this* round's
8041            // reviewer seats were lost to their own rate limit, as opposed to
8042            // a crash, a timeout, or unparsable output — see `round_is_clean`.
8043            let round_quota_missing = quota_losses.len();
8044            self.state.quota.extend(quota_losses);
8045
8046            let mut records = Vec::new();
8047            let mut all_findings = Vec::new();
8048            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
8049                let agent_id = seat.agent.clone();
8050                self.state.seats.insert(seat.key.clone(), seat);
8051                let mut record = ReviewRecord {
8052                    reviewer: r + 1,
8053                    agent: agent_id,
8054                    summary: String::new(),
8055                    findings: Vec::new(),
8056                    vote: None,
8057                    failed: None,
8058                    duration_ms: 0,
8059                    // Set for both outcomes: `failed: Some(_)` with
8060                    // `attempts > 0` is a seat every retry still lost, not a
8061                    // recovered one — only `failed: None` with `attempts > 0`
8062                    // reads as "answered after a nudge" (see this field's own
8063                    // doc).
8064                    attempts,
8065                };
8066                match res {
8067                    Ok((review, out)) => {
8068                        // Sanitized here, at the point every other piece of
8069                        // agent prose in this file is (candidate summaries,
8070                        // deliberation turns, vote reasons): a reviewer's own
8071                        // words are the one thing about it that could name
8072                        // it, and reconsideration below broadcasts this same
8073                        // summary and these same findings to every other
8074                        // seat on the panel.
8075                        record.summary =
8076                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
8077                        record.vote = Some(review.vote);
8078                        record.duration_ms = out.duration_ms;
8079                        for (n, mut f) in review.findings.into_iter().enumerate() {
8080                            // ids are magi's, never the agent's: the fixer's
8081                            // adoption report is keyed by them.
8082                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
8083                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
8084                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
8085                            // `file` is agent-supplied prose too, never
8086                            // checked against the real tree — the same
8087                            // exposure `title`/`detail` above have, just in
8088                            // a field easy to forget because it looks like a
8089                            // path rather than free text.
8090                            f.file = f
8091                                .file
8092                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
8093                            all_findings.push(f.clone());
8094                            record.findings.push(f);
8095                        }
8096                        self.state.event(
8097                            "review",
8098                            format!(
8099                                "round {round}: reviewer {} voted {} with {} finding(s)",
8100                                r + 1,
8101                                review.vote.label(),
8102                                record.findings.len()
8103                            ),
8104                        );
8105                    }
8106                    Err(e) => {
8107                        record.failed = Some(e.to_string());
8108                        self.state.event(
8109                            "review",
8110                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
8111                        );
8112                    }
8113                }
8114                records.push(record);
8115            }
8116
8117            // Tally the round's votes and, if they split, spend the one
8118            // round of reconsideration the split -> deliberate -> revote
8119            // shape `judge`/`vote` use for the panel, sized down to what a
8120            // read-only review round can afford: one round, and a revote
8121            // rather than an argument, because the panel already wrote its
8122            // reasoning down as findings the first time around.
8123            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
8124            let vote_split =
8125                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
8126            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
8127            if vote_split {
8128                self.state.event(
8129                    "review",
8130                    format!(
8131                        "round {round}: votes split ({}) — one round of reconsideration",
8132                        initial_votes
8133                            .iter()
8134                            .map(|v| v.label())
8135                            .collect::<Vec<_>>()
8136                            .join(", ")
8137                    ),
8138                );
8139                // Seats read every seat's findings and votes, still numbered
8140                // and never named — the same anonymity `review` itself keeps.
8141                let panel: Vec<ReviewSeatReport<'_>> = records
8142                    .iter()
8143                    .filter_map(|r| {
8144                        r.vote.map(|vote| ReviewSeatReport {
8145                            reviewer: r.reviewer,
8146                            vote,
8147                            summary: &r.summary,
8148                            findings: &r.findings,
8149                        })
8150                    })
8151                    .collect();
8152
8153                let mut jobs = Vec::new();
8154                let mut seats_at = Vec::new();
8155                for (r, spec) in reviewers.iter().cloned().enumerate() {
8156                    // A seat with no initial vote has nothing to reconsider
8157                    // from and stays absent, the same as it stayed absent
8158                    // from `panel` above.
8159                    if records[r].vote.is_none() {
8160                        continue;
8161                    }
8162                    let wt = root.join(format!("review-{}", r + 1));
8163                    let seat_key = format!("review-{}", r + 1);
8164                    let spec = self.occupant(&seat_key, spec);
8165                    let seat = self.seat(&seat_key, &spec.id);
8166                    // A seat with no live session has already forgotten the
8167                    // initial review's prompt — restate the patch it is
8168                    // voting on, the same as `deliberate`/`vote` do for a
8169                    // judge in the same position.
8170                    // The panel already carries this seat's own review and
8171                    // vote, so restating the patch makes the prompt whole for
8172                    // a seat handed to another agent.
8173                    let build = |with_patch: bool| {
8174                        prompt::review_reconsider(&ReviewReconsiderCtx {
8175                            instruction: &self.state.instruction,
8176                            reviewer: r + 1,
8177                            lens: Lens::for_seat(r),
8178                            panel: &panel,
8179                            patch: with_patch.then_some(ReviewPatch {
8180                                branch: &winner.branch,
8181                                base_short: &base_short,
8182                                stat: &stat,
8183                                patch: &patch,
8184                            }),
8185                            round,
8186                            rounds: max_rounds,
8187                            language: &language,
8188                        })
8189                    };
8190                    let full = build(true);
8191                    let prompt = if has_context(&spec, &seat, sessions) {
8192                        build(false)
8193                    } else {
8194                        full.clone()
8195                    };
8196                    jobs.push(SeatJob {
8197                        prompt,
8198                        spec,
8199                        seat,
8200                        cwd: wt,
8201                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8202                        allow_write: false,
8203                        sessions,
8204                        artifacts: artifacts.clone(),
8205                        stem: format!("review-{round}-reconsider-{}", r + 1),
8206                        handover: Some(full),
8207                    });
8208                    seats_at.push(r);
8209                }
8210
8211                let mut recon_quota_losses = Vec::new();
8212                let recon_cache = self.state.config.cache_dir();
8213                let recon_ctx = WaveCtx {
8214                    carry_seats: true,
8215                    pauses: Some((&self.pause, &self.interrupt)),
8216                    run: &run_id,
8217                    node: "review",
8218                    prompts: &prompts,
8219                    cache: recon_cache.as_deref(),
8220                    round: Some(round),
8221                };
8222                let recon_results = ask_json_wave::<ReviewRevote>(
8223                    jobs,
8224                    Arc::clone(&self.sem),
8225                    review_retries,
8226                    &self.roles.reviewer_roster,
8227                    &recon_ctx,
8228                    &mut recon_quota_losses,
8229                    &mut self.state,
8230                    &|_: &ReviewRevote| Ok(()),
8231                )
8232                .await;
8233                if self.state.resource_block.is_some() {
8234                    return self.stop_for_resource();
8235                }
8236                self.state.quota.extend(recon_quota_losses);
8237
8238                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
8239                    let agent_id = seat.agent.clone();
8240                    self.state.seats.insert(seat.key.clone(), seat);
8241                    let mut rec = ReviewRevoteRecord {
8242                        reviewer: r + 1,
8243                        agent: agent_id,
8244                        vote: None,
8245                        reason: String::new(),
8246                        failed: None,
8247                    };
8248                    match res {
8249                        Ok((rv, _)) => {
8250                            rec.vote = Some(rv.vote);
8251                            rec.reason =
8252                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
8253                            self.state.event(
8254                                "review",
8255                                format!(
8256                                    "round {round}: reviewer {} revoted {}",
8257                                    r + 1,
8258                                    rv.vote.label()
8259                                ),
8260                            );
8261                        }
8262                        Err(e) => {
8263                            rec.failed = Some(e.to_string());
8264                            self.state.event(
8265                                "review",
8266                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
8267                            );
8268                        }
8269                    }
8270                    reconsideration.push(rec);
8271                }
8272            } else if initial_votes.len() > 1 {
8273                self.state.event(
8274                    "review",
8275                    format!(
8276                        "round {round}: votes agreed ({}) — no reconsideration",
8277                        initial_votes[0].label()
8278                    ),
8279                );
8280            }
8281
8282            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
8283            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8284            // A round that already has a blocking finding and a round left to
8285            // try is going back to the fixer no matter what `verify.e2e`
8286            // says, so running it first only spends the loop's slowest step
8287            // (minutes, for a Rust repo's full test suite) on a head about
8288            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8289            // runs once a round has no blocking findings left (see
8290            // `round_is_clean`, which a deferred — empty — `e2e` can never
8291            // satisfy since `blocking` is nonzero whenever this branch is
8292            // taken), and `stop_reviewing` forces a real run before it will
8293            // ever read a deferred round as green.
8294            let defer_e2e =
8295                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8296            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8297                let reason =
8298                    format!("{blocking} blocking finding(s) already required a fix this round");
8299                self.state.event(
8300                    "verify",
8301                    format!(
8302                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8303                         {}); it will run once a round has none left",
8304                        short(&head)
8305                    ),
8306                );
8307                (Vec::new(), false, true, Some(reason))
8308            } else {
8309                let e2e_commands = self.state.config.verify.e2e.clone();
8310                let cache_dir = self.state.config.cache_dir();
8311                let context = format!("round {round}");
8312                let wait = self.repository_wait();
8313                let (e2e, verify_retried) = with_cache_lease(
8314                    &mut self.state,
8315                    cache_dir.as_deref(),
8316                    "e2e",
8317                    "e2e",
8318                    &winner.worktree,
8319                    &head,
8320                    verify_timeout,
8321                    &context,
8322                    &wait,
8323                    |state, budget| {
8324                        let shell = shell.clone();
8325                        let e2e_commands = e2e_commands.clone();
8326                        let worktree = winner.worktree.clone();
8327                        let context = context.clone();
8328                        let winner = winner.clone();
8329                        async move {
8330                            if !e2e_commands.is_empty() {
8331                                // The suite certifies one SHA. Format before it
8332                                // runs, or the commit `pre_gate` makes at the
8333                                // gate owes the whole suite again.
8334                                Self::run_pre_gate(state, &winner).await;
8335                            }
8336                            run_e2e_with_retry(
8337                                state,
8338                                &shell,
8339                                &e2e_commands,
8340                                &worktree,
8341                                budget,
8342                                &context,
8343                                Some(round),
8344                            )
8345                            .await
8346                        }
8347                    },
8348                )
8349                .await?;
8350                (e2e, verify_retried, false, None)
8351            };
8352
8353            let expected = records.len();
8354            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8355            let incomplete = answered < expected;
8356            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8357            let policy = self.state.config.graph.incomplete_review;
8358            let clean = round_is_clean(
8359                blocking,
8360                e2e_ok,
8361                answered,
8362                expected,
8363                round_quota_missing,
8364                policy,
8365            );
8366
8367            let mut round_record = ReviewRound {
8368                round,
8369                head: head.clone(),
8370                verified_head: None,
8371                verified_at: None,
8372                reviews: records,
8373                e2e,
8374                verify_retried,
8375                e2e_deferred,
8376                e2e_defer_reason,
8377                fix: None,
8378                blocking,
8379                answered,
8380                expected,
8381                clean,
8382                progressed: false,
8383                vote_split,
8384                reconsideration,
8385                verdict: None,
8386            };
8387            // The final vote per seat is its revote where reconsideration
8388            // ran and answered, its initial vote otherwise — the same
8389            // fallback `tally` uses for a judge whose private vote failed.
8390            round_record.verdict = ReviewVote::worst(
8391                round_record
8392                    .final_votes()
8393                    .into_iter()
8394                    .map(|(_, _, vote)| vote),
8395            );
8396            // Which commit and when magi actually attempted to check —
8397            // known the moment a command was dispatched against `head`,
8398            // whether or not it finished: a resource-blocked attempt still
8399            // targeted a specific commit at a specific time, and leaving
8400            // that unrecorded is exactly what made `verification_summary`
8401            // report a fresh attempt as "commit unknown ... recorded before
8402            // this was tracked", indistinguishable from a genuinely old,
8403            // untracked record. Only a deferred or unconfigured round never
8404            // ran at all and has nothing to record — see
8405            // `ReviewRound::verified_head`'s own doc.
8406            if !matches!(
8407                round_record.e2e_status(),
8408                E2eStatus::Deferred | E2eStatus::NotConfigured
8409            ) {
8410                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8411                // mechanical fixes before the commands ran.
8412                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8413                round_record.verified_at = Some(Timestamp::now());
8414            }
8415
8416            if incomplete {
8417                let missing: Vec<String> = round_record
8418                    .reviews
8419                    .iter()
8420                    .filter(|r| r.failed.is_some())
8421                    .map(|r| format!("review-{}", r.reviewer))
8422                    .collect();
8423                self.state.event(
8424                    "review",
8425                    format!(
8426                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8427                        missing.join(", ")
8428                    ),
8429                );
8430            }
8431
8432            if clean {
8433                self.state.event(
8434                    "review",
8435                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8436                        format!(
8437                            "round {round}: clean (warn policy, incomplete panel) — no \
8438                             blocking findings from the seats that answered, verification green"
8439                        )
8440                    } else if incomplete {
8441                        format!(
8442                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8443                             quorum) — no blocking findings from the seats that answered, \
8444                             verification green",
8445                            expected - answered
8446                        )
8447                    } else {
8448                        format!("round {round}: clean — no blocking findings, verification green")
8449                    },
8450                );
8451                self.state.reviews.push(round_record);
8452                self.state.status = RunStatus::Gating;
8453                self.state.save()?;
8454                return Ok(());
8455            }
8456
8457            // Nothing was raised and verification passed, but not every seat
8458            // answered and `round_is_clean` still refused to call it clean —
8459            // either a seat is missing for a reason other than its own quota
8460            // (a crash, a timeout, unparsable output — worth another try), or
8461            // every seat that could have answered lost its quota and nobody
8462            // is left to decide on: re-review rather than send the fixer
8463            // after a round with nothing to fix.
8464            if incomplete && blocking == 0 && e2e_ok {
8465                self.state.reviews.push(round_record);
8466                self.state.save()?;
8467                if round == max_rounds {
8468                    self.state.status = RunStatus::Blocked;
8469                    self.state.event(
8470                        "review",
8471                        format!(
8472                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8473                             refusing to call it clean",
8474                            expected - answered
8475                        ),
8476                    );
8477                    return Ok(());
8478                }
8479                continue;
8480            }
8481
8482            // Nothing for the fixer to act on (`blocking == 0`) and the only
8483            // reason this round is not clean is that magi itself never got
8484            // a command to run — the shared build cache, not the patch (see
8485            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8486            // the fixer would invite a change to appease contention that has
8487            // nothing to do with the diff, and would leave this attempt
8488            // sitting in the next round's prompt as if it were about an
8489            // earlier, superseded commit rather than what it actually is:
8490            // the same head, still waiting to be checked. Wait for it the
8491            // same way the final round's own contention is already handled,
8492            // whatever round this happens to be.
8493            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8494                self.state.reviews.push(round_record);
8495                return self
8496                    .stop_unresolved_review(
8497                        "the round's own verification could not run",
8498                        &shell,
8499                        &winner.worktree,
8500                    )
8501                    .await;
8502            }
8503
8504            if round == max_rounds {
8505                self.state.reviews.push(round_record);
8506                return self
8507                    .stop_reviewing(
8508                        &format!(
8509                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8510                        ),
8511                        &shell,
8512                        &winner.worktree,
8513                    )
8514                    .await;
8515            }
8516
8517            if !self.fix_review_round(&winner, round_record).await? {
8518                return Ok(());
8519            }
8520        }
8521        Ok(())
8522    }
8523
8524    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8525    /// False means admission or continuation policy stopped the review loop.
8526    async fn fix_review_round(
8527        &mut self,
8528        winner: &Candidate,
8529        mut round_record: ReviewRound,
8530    ) -> Result<bool> {
8531        let round = round_record.round;
8532        let shell = self.state.config.shell();
8533        let step = self.run_fix_round(winner, &mut round_record).await?;
8534        if matches!(step, FixStep::Resource) {
8535            self.stop_for_resource()?;
8536            return Ok(false);
8537        }
8538        if self.state.reviews.len() < round {
8539            self.state.reviews.push(round_record);
8540        } else {
8541            self.state.reviews[round - 1] = round_record;
8542        }
8543        self.state.save()?;
8544
8545        // The fixer's own report never came back this round, even after
8546        // `continue_fix_report`'s own budget was spent on it — not an
8547        // ordinary "no report" (dropped stream, quota, plain failure),
8548        // which already reads that way and is left to the existing round
8549        // budget. Stopping here, rather than opening another round, is
8550        // what keeps a next reviewer/fixer wave from ever being
8551        // dispatched onto `winner.worktree` while whatever the seat's
8552        // last call may still have running there is unaccounted for: no
8553        // process liveness check exists (and none is being added — see
8554        // AGENTS.md/this task's own scope), so the only way to honour
8555        // "nothing starts before a valid report returns" is to not start
8556        // anything further on this worktree from this run at all.
8557        if matches!(step, FixStep::Recorded { report_lost: true }) {
8558            self.stop_reviewing(
8559                "the fixer's adoption report never came back, even after resuming its \
8560                         own seat; refusing to start another round against the same worktree \
8561                         while that is unresolved",
8562                &shell,
8563                &winner.worktree,
8564            )
8565            .await?;
8566            return Ok(false);
8567        }
8568
8569        let streak = self
8570            .state
8571            .reviews
8572            .iter()
8573            .rev()
8574            .take_while(|r| !r.progressed)
8575            .count();
8576        if streak >= STAGNANT_LIMIT {
8577            self.stop_reviewing(
8578                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8579                &shell,
8580                &winner.worktree,
8581            )
8582            .await?;
8583            return Ok(false);
8584        }
8585        Ok(true)
8586    }
8587
8588    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8589    async fn run_fix_round(
8590        &mut self,
8591        winner: &Candidate,
8592        round_record: &mut ReviewRound,
8593    ) -> Result<FixStep> {
8594        let round = round_record.round;
8595        let max_rounds = self.state.config.graph.review_rounds;
8596        let run_id = self.state.id.clone();
8597        let prompts = self.state.config.prompts.clone();
8598        let language = self.state.config.graph.language.clone();
8599        let sessions = self.state.config.graph.sessions;
8600        let artifacts = self.merge_repair_artifacts();
8601        let base = self.landing_base();
8602        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8603        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8604        let this_round_verification = round_record.verification_summary(&head);
8605        let all_findings: Vec<_> = round_record
8606            .reviews
8607            .iter()
8608            .flat_map(|r| r.findings.iter().cloned())
8609            .collect();
8610        // Fix. The winner's own implementer seat continues its conversation:
8611        // the competition is over, so context is pure benefit now.
8612        let blocking_findings: Vec<_> = all_findings
8613            .iter()
8614            .filter(|f| f.severity.blocks())
8615            .cloned()
8616            .collect();
8617        let fix_prompt = prompt::fix_in(
8618            &self.state.instruction,
8619            &blocking_findings,
8620            this_round_verification.as_ref(),
8621            round,
8622            max_rounds,
8623            &language,
8624            &self.state.config.graph.github_language,
8625        );
8626        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8627        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8628        let (job, seat, out) = self
8629            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8630                prompt: fix_prompt.clone(),
8631                spec,
8632                seat,
8633                cwd: winner.worktree.clone(),
8634                timeout,
8635                allow_write: true,
8636                sessions,
8637                artifacts: artifacts.clone(),
8638                stem: format!("fix-{round}"),
8639                handover: None,
8640            })
8641            .await;
8642        // Not asked: the round is not recorded (so a resume repeats it),
8643        // no fixer was handed over to, and the seat is left as it was.
8644        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8645            return Ok(FixStep::Resource);
8646        }
8647        let agent_id = seat.agent.clone();
8648
8649        let mut fix = FixRecord {
8650            agent: agent_id,
8651            addressed: Vec::new(),
8652            rejected: Vec::new(),
8653            notes: String::new(),
8654            committed: false,
8655            failed: None,
8656            duration_ms: 0,
8657            continuation: None,
8658        };
8659        let mut continuation = ContinuationRecord::not_needed();
8660        let mut final_seat = seat.clone();
8661        match out {
8662            AgentOutcome::Ok(o) => {
8663                fix.duration_ms = o.duration_ms;
8664                let parsed = verdict::extract_json::<FixReport>(&o.text);
8665                // A parsed report standing next to a command this same
8666                // reply's own CLI never confirmed the exit status of is
8667                // not a resolved answer — the identical `CommandEvidence`
8668                // `state.jobs` renders, read here instead of only on
8669                // display, per the completion judgment and the shown
8670                // record needing to agree.
8671                let incomplete_reason = match &parsed {
8672                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8673                        "the reply parsed, but it reported a command whose own CLI never \
8674                             confirmed an exit status"
8675                            .to_owned(),
8676                    ),
8677                    Ok(_) => None,
8678                    Err(e) => Some(e.to_string()),
8679                };
8680                match incomplete_reason {
8681                    None => {
8682                        let report = parsed.expect("checked Ok above");
8683                        fix.addressed = report.addressed;
8684                        fix.rejected = report.rejected;
8685                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8686                    }
8687                    Some(reason) => {
8688                        let (resumed_seat, resolved, failure, cont) = self
8689                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8690                            .await;
8691                        fix.duration_ms += cont.cumulative_wait_ms;
8692                        continuation = cont;
8693                        final_seat = resumed_seat;
8694                        match resolved {
8695                            Some(report) => {
8696                                fix.addressed = report.addressed;
8697                                fix.rejected = report.rejected;
8698                                fix.notes =
8699                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8700                            }
8701                            None => fix.failed = failure,
8702                        }
8703                    }
8704                }
8705            }
8706            // The CLI's raw error JSON is not a fix report to parse.
8707            AgentOutcome::Dropped(o) => {
8708                fix.duration_ms = o.duration_ms;
8709                let why = o
8710                    .dropped
8711                    .as_ref()
8712                    .map(|d| d.why.as_str())
8713                    .unwrap_or("the CLI ended the stream without delivering its answer");
8714                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8715            }
8716            AgentOutcome::Quota(o) => {
8717                self.state.quota.push(QuotaLoss::from_report(
8718                    final_seat.key.clone(),
8719                    "fix",
8720                    o.quota.as_ref(),
8721                ));
8722                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8723            }
8724            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8725        }
8726        if self.state.resource_block.is_some() {
8727            self.state.seats.insert(final_seat.key.clone(), final_seat);
8728            return Ok(FixStep::Resource);
8729        }
8730        fix.continuation = Some(continuation);
8731        self.state.seats.insert(final_seat.key.clone(), final_seat);
8732        let coordination = self.coordinate(&winner.worktree).await?;
8733        if let Ok(r) = git::rescue_commit(
8734            &winner.worktree,
8735            &format!("magi: review round {round} fixes (uncommitted work)"),
8736        )
8737        .await
8738        {
8739            self.state.note_withheld("fix", &r.withheld);
8740        }
8741        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8742        fix.committed = after != before;
8743        // Judged by what `git` says moved against base, never by the
8744        // fixer's own `addressed`/`rejected` count — see
8745        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8746        // `patch` snapshot above: swallowing this error would default
8747        // `diff_after` to empty, which almost always differs from a
8748        // non-empty `patch` and reads as "progressed" — exactly backwards
8749        // for a `git` failure the stagnation check cannot see through.
8750        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8751        drop(coordination);
8752        let progressed = diff_after != patch;
8753        let commit_note = if fix.committed {
8754            "committed"
8755        } else {
8756            "NO new commit"
8757        };
8758        let tree_note = if progressed {
8759            "changed vs base"
8760        } else {
8761            "unchanged vs base"
8762        };
8763        self.state.event(
8764            "fix",
8765            match &fix.failed {
8766                // Distinct on purpose from "0 addressed, 0 rejected": the
8767                // fixer's own diff still landed (blocking counts do keep
8768                // falling round over round), only its adoption report did
8769                // not come back, so this must never read like every
8770                // finding was reviewed and declined.
8771                Some(reason) => {
8772                    format!(
8773                        "round {round}: fixer's adoption report was lost ({reason}); \
8774                             {commit_note}, tree {tree_note}"
8775                    )
8776                }
8777                None => format!(
8778                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8779                         {tree_note}{}",
8780                    fix.addressed.len(),
8781                    fix.rejected.len(),
8782                    if continuation.outcome == ContinuationOutcome::Resumed {
8783                        format!(
8784                            " (adoption report recovered after {} continuation(s))",
8785                            continuation.attempts
8786                        )
8787                    } else {
8788                        String::new()
8789                    },
8790                ),
8791            },
8792        );
8793        round_record.fix = Some(fix);
8794        round_record.progressed = progressed;
8795        Ok(FixStep::Recorded {
8796            report_lost: matches!(
8797                continuation.outcome,
8798                ContinuationOutcome::Exhausted
8799                    | ContinuationOutcome::QuotaLost
8800                    | ContinuationOutcome::NoSession
8801            ),
8802        })
8803    }
8804
8805    /// Decide, from the last recorded round's own verification, whether
8806    /// stopping the review loop is a hand-off or a genuine block.
8807    ///
8808    /// Called once the loop has given up trying — the round budget is spent,
8809    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8810    /// findings still open, never while a round is still clean or the
8811    /// incomplete-panel case handled inline above. Gate and e2e are facts
8812    /// about the tree; a lingering review finding is an opinion, and this
8813    /// workload's own `magi stats` puts reviewer precision low enough
8814    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8815    /// must not by itself stand between a green, verified change and the
8816    /// human who decides what to do with it. A red e2e is not an opinion, so
8817    /// that case still blocks, with the failing command and a tail of its
8818    /// output recorded here rather than left in `run.json` for someone to go
8819    /// find.
8820    ///
8821    /// A round that deferred its own e2e (see [`Config::graph`]'s
8822    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8823    /// only because nothing ran, and treating an empty list as a passing one
8824    /// here is exactly the "deferred painted green" bug this function exists
8825    /// to not have. When the last round's own verification never resolved —
8826    /// deferred on purpose, or a real attempt the shared build cache blocked
8827    /// — this makes (or retries) the real run, on the actual worktree this
8828    /// loop is about to stop touching, before deciding anything. A
8829    /// resource-blocked attempt is likewise never read as either green or
8830    /// red: it is evidence about the machine, not the patch (see
8831    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8832    /// blocked cache leaves this call without deciding rather than guessing
8833    /// — the caller retries on a later reentry.
8834    /// Record, once, that the review loop handed off over a blocking finding
8835    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8836    /// `land` asks the owner even with `land_approval` off. Called from every
8837    /// path that concludes `Gating`; a reentry keeps the first record.
8838    fn record_contested_handoff(&mut self) {
8839        if self.state.contested_handoff.is_some() {
8840            return;
8841        }
8842        let Some(contested) = self
8843            .state
8844            .reviews
8845            .last()
8846            .and_then(ReviewRound::contested_handoff)
8847        else {
8848            return;
8849        };
8850        self.state.event(
8851            "review",
8852            format!(
8853                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8854                 wait for the owner's approval",
8855                contested.findings.len(),
8856                contested.rejecters.len()
8857            ),
8858        );
8859        self.state.contested_handoff = Some(contested);
8860    }
8861
8862    async fn stop_unresolved_review(
8863        &mut self,
8864        why: &str,
8865        shell: &[String],
8866        worktree: &Path,
8867    ) -> Result<()> {
8868        self.stop_reviewing_inner(why, shell, worktree, true).await
8869    }
8870
8871    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8872        self.stop_reviewing_inner(why, shell, worktree, false).await
8873    }
8874
8875    async fn stop_reviewing_inner(
8876        &mut self,
8877        why: &str,
8878        shell: &[String],
8879        worktree: &Path,
8880        repairable: bool,
8881    ) -> Result<()> {
8882        let round_idx = self.state.reviews.len() - 1;
8883        // A deferred round and a resource-blocked one are the same shape
8884        // here: neither has a real result yet, and both get one more
8885        // attempt. Read off `e2e_status` — the single source for this —
8886        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8887        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8888        // still retries instead of being read as a settled result the
8889        // instant it stops being empty.
8890        let needs_catchup_run = matches!(
8891            self.state.reviews[round_idx].e2e_status(),
8892            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8893        );
8894        if needs_catchup_run {
8895            let round = self.state.reviews[round_idx].round;
8896            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8897            let commands = self.state.config.verify.e2e.clone();
8898            let before_head = git::rev_parse(worktree, "HEAD").await?;
8899            let winner = self.state.winner().cloned();
8900            let cache_dir = self.state.config.cache_dir();
8901            let context = format!(
8902                "round {round}: verification unresolved, catching up before the final decision"
8903            );
8904            let wait = self.repository_wait();
8905            let (outcomes, verify_retried) = with_cache_lease(
8906                &mut self.state,
8907                cache_dir.as_deref(),
8908                "e2e",
8909                "e2e",
8910                worktree,
8911                &before_head,
8912                timeout,
8913                &context,
8914                &wait,
8915                |state, budget| {
8916                    let shell = shell.to_vec();
8917                    let commands = commands.clone();
8918                    let context = context.clone();
8919                    async move {
8920                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8921                            // Same reason as in the round itself: format before
8922                            // the suite, not after it.
8923                            Self::run_pre_gate(state, &winner).await;
8924                        }
8925                        run_e2e_with_retry(
8926                            state,
8927                            &shell,
8928                            &commands,
8929                            worktree,
8930                            budget,
8931                            &context,
8932                            Some(round),
8933                        )
8934                        .await
8935                    }
8936                },
8937            )
8938            .await?;
8939            // After `pre_gate`: the commit the commands actually ran against.
8940            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8941            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8942                self.state.record_base_progress(&attempted_head);
8943            }
8944            let last = &mut self.state.reviews[round_idx];
8945            last.e2e = outcomes;
8946            last.verify_retried = verify_retried;
8947            // Always the commit and time this attempt actually targeted,
8948            // whether or not it happens to equal the reviewed `head` and
8949            // whether or not a command finished — see
8950            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8951            // attempt is recorded too, so a later reader sees "attempted
8952            // again at T2" rather than silence.
8953            last.verified_head = Some(attempted_head);
8954            last.verified_at = Some(Timestamp::now());
8955            if verify_inconclusive(&last.e2e) {
8956                // Still not a real result: `e2e_deferred` is left exactly
8957                // as it was, so `needs_catchup_run` above reads
8958                // `ResourceBlocked` (via `e2e_status`, which checks
8959                // `resource_blocked` before `e2e_deferred`) and retries
8960                // again on the next reentry, rather than recording
8961                // contention as a red e2e and blocking the run on it.
8962                self.state.save()?;
8963                return Ok(());
8964            }
8965            last.e2e_deferred = false;
8966            // A complete panel may have been saved as unclean solely because
8967            // verification could not run. Refresh that verdict with the new
8968            // outcomes before a granted repair consumes the round's result.
8969            // Incomplete panels retain their original policy/quota decision.
8970            if last.answered == last.expected {
8971                last.clean = round_is_clean(
8972                    last.blocking,
8973                    last.e2e.iter().all(CommandOutcome::ok),
8974                    last.answered,
8975                    last.expected,
8976                    0,
8977                    self.state.config.graph.incomplete_review,
8978                );
8979            }
8980        }
8981        let last = &self.state.reviews[round_idx];
8982        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8983
8984        match last.e2e_status() {
8985            E2eStatus::Failed => {
8986                let red: Vec<String> = last
8987                    .e2e
8988                    .iter()
8989                    .filter(|o| !o.ok())
8990                    .map(|o| {
8991                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8992                            .map(|c| format!(" ({c})"))
8993                            .unwrap_or_default();
8994                        format!(
8995                            "`{}` -> {:?}{comparison}\n{}",
8996                            o.command,
8997                            o.code,
8998                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8999                        )
9000                    })
9001                    .collect();
9002                let can_repair = last.blocking == 0 && last.fix.is_none();
9003                self.state.reviews[round_idx].clean = false;
9004                self.state
9005                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
9006                self.state.status = RunStatus::Blocked;
9007                if repairable
9008                    && can_repair
9009                    && self.state.reviews.len() < self.state.config.graph.review_rounds
9010                {
9011                    self.state.status = RunStatus::Reviewing;
9012                }
9013            }
9014            // `needs_catchup_run` above already retried once this call; if
9015            // it is still blocked, this is magi's own admission it could
9016            // not get a command to run, never a verdict on the patch — the
9017            // run is left exactly where a later reentry can retry again.
9018            E2eStatus::ResourceBlocked => {
9019                self.state.event(
9020                    "review",
9021                    format!(
9022                        "{why}; e2e could not run (resource unavailable); not \
9023                         deciding yet"
9024                    ),
9025                );
9026            }
9027            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
9028                self.state.event(
9029                    "review",
9030                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
9031                );
9032                self.record_contested_handoff();
9033                self.state.status = RunStatus::Gating;
9034            }
9035        }
9036        self.state.save()?;
9037        Ok(())
9038    }
9039
9040    // ----------------------------------------------------------------- gate
9041
9042    async fn gate(&mut self) -> Result<()> {
9043        if self.hold_base_sync().await? {
9044            return Ok(());
9045        }
9046        // Judged by the review record itself, not by `status`: a solo
9047        // candidate's `judge`/`deliberate` skip rewrites `status` on every
9048        // reentry (see `judge`), and trusting it here is exactly how a run
9049        // that exhausted its review budget got gated and merged a second
9050        // time around. `review_conclusion` recomputes the review loop's own
9051        // verdict from the round records themselves — `Gating` for a clean
9052        // round or a hand-off (see `stop_reviewing`), anything else means the
9053        // loop is still going or genuinely blocked.
9054        // A base the winner could not be replayed onto is a decision, not a
9055        // round: there is no landing tree to gate. Read as its own record for
9056        // the same reason the review verdict is.
9057        if self.state.status == RunStatus::Failed
9058            || self
9059                .state
9060                .base_sync
9061                .as_ref()
9062                .is_some_and(|s| s.conflict.is_some())
9063            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9064                != Some(RunStatus::Gating)
9065        {
9066            return Ok(());
9067        }
9068        let Some(winner) = self.state.winner().cloned() else {
9069            return Ok(());
9070        };
9071        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9072        self.state.reconcile_verification_head(&head);
9073        self.state.save()?;
9074        let wait = self.repository_wait();
9075        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9076            return Ok(());
9077        }
9078        if self.state.gate_ran {
9079            // `review_loop` derives its conclusion from the clean review
9080            // record on every reentry and therefore puts a completed run back
9081            // in `Gating`. A recorded gate is a stronger, terminal fact:
9082            // retain its original command output (or lack of any, for a repo
9083            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
9084            // doc) and restore `Blocked` on a real failure rather than
9085            // pretending the command is still running or running it a second
9086            // time. `gate_ran == false` remains the only shape — unattempted,
9087            // or a resource-blocked retry — that may still need to execute a
9088            // command.
9089            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
9090                self.state.status = RunStatus::Blocked;
9091                self.state.save()?;
9092            }
9093            return Ok(());
9094        }
9095        self.state.status = RunStatus::Gating;
9096        let mut outcomes = self.run_gate(&winner).await?;
9097        let mut attempted_head = self.state.gate_head.clone();
9098        loop {
9099            // A resource-blocked outcome means the gate command never actually
9100            // ran - the shared build cache could not be acquired or confirmed
9101            // fresh in time - which is evidence about the machine, not about
9102            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
9103            // Recording it as a red gate would mark a run `Blocked` on nothing
9104            // but contention magi has already logged; leaving `self.state.gate`
9105            // empty and `self.state.gate_ran` false instead keeps the shape
9106            // this function already treats as "still needs to run" (see the
9107            // early-return above), so the next call retries the command
9108            // rather than concluding anything.
9109            if verify_inconclusive(&outcomes) {
9110                self.state.save()?;
9111                return Ok(());
9112            }
9113            if outcomes.iter().all(CommandOutcome::ok) {
9114                break;
9115            }
9116            let fixes_before = self.state.gate_fixes.len();
9117            match self.gate_fix_round(&winner, &outcomes).await? {
9118                GateFix::Retry => {
9119                    outcomes = self.run_gate(&winner).await?;
9120                    attempted_head = self.state.gate_head.clone();
9121                }
9122                GateFix::Stop => {
9123                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
9124                    if self.state.gate_fixes.len() > fixes_before
9125                        && attempted_head.as_deref() != Some(current.as_str())
9126                        && verify_current_head(&mut self.state, &winner, &wait).await?
9127                    {
9128                        // A new SHA owes a gate even when a spent fixer changed only
9129                        // commit metadata. This does not grant another repair round.
9130                        outcomes = self.run_gate(&winner).await?;
9131                        attempted_head = self.state.gate_head.clone();
9132                    } else {
9133                        break;
9134                    }
9135                }
9136                GateFix::Defer => {
9137                    self.state.save()?;
9138                    return Ok(());
9139                }
9140            }
9141        }
9142        let passed = outcomes.iter().all(CommandOutcome::ok);
9143        self.state.gate = outcomes;
9144        self.state.gate_ran = true;
9145        self.state.gate_head = attempted_head;
9146        if !self.state.gate.is_empty()
9147            && !verify_inconclusive(&self.state.gate)
9148            && let Some(head) = self.state.gate_head.clone()
9149        {
9150            self.state.record_base_progress(&head);
9151        }
9152        self.state.save()?;
9153        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9154            return Ok(());
9155        }
9156        if !passed {
9157            self.state.status = RunStatus::Blocked;
9158            let spent = self.state.gate_fixes.len();
9159            self.state.event(
9160                "gate",
9161                if spent == 0 {
9162                    "gate failed; not merging".to_owned()
9163                } else {
9164                    format!("gate failed after {spent} gate-fix round(s); not merging")
9165                },
9166            );
9167        }
9168        self.state.save()?;
9169        Ok(())
9170    }
9171
9172    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
9173    /// changed into one commit. Runs before `verify.e2e` in the review loop
9174    /// and again before the gate commands, always on the winner and never on
9175    /// a candidate awaiting judging.
9176    ///
9177    /// Before e2e as well as before the gate because command evidence belongs
9178    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
9179    /// commit e2e never saw, and the suite ran again for a formatter's diff -
9180    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
9181    /// own call then finds nothing left to change. The commands must be
9182    /// idempotent; one that is not makes a commit per call.
9183    ///
9184    /// Never fails the run: a non-zero exit or timeout is a warning and a
9185    /// recorded outcome, and the gate remains the single arbiter. Nothing
9186    /// configured means nothing happens - no event, no commit. `commit_all`
9187    /// commits any leftover change under the neutral identity and returns
9188    /// `false` when the tree is clean, so no empty commit is ever made.
9189    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
9190        let commands = state.config.verify.pre_gate.clone();
9191        if commands.is_empty() {
9192            return;
9193        }
9194        let shell = state.config.shell();
9195        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
9196        let (outcomes, _) = run_commands(
9197            state,
9198            "pre_gate",
9199            "pre_gate",
9200            0,
9201            &shell,
9202            &commands,
9203            &winner.worktree,
9204            timeout,
9205        )
9206        .await;
9207        for o in &outcomes {
9208            if !o.ok() {
9209                tracing::warn!(
9210                    "pre_gate `{}` failed ({:?}); the gate decides",
9211                    o.command,
9212                    o.code
9213                );
9214            }
9215            state.event(
9216                "pre_gate",
9217                format!(
9218                    "`{}` -> {}",
9219                    o.command,
9220                    if o.ok() {
9221                        "pass".to_owned()
9222                    } else {
9223                        format!(
9224                            "FAIL ({:?})\n{}",
9225                            o.code,
9226                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9227                        )
9228                    }
9229                ),
9230            );
9231        }
9232        state.pre_gate = outcomes;
9233        match git::commit_all(&winner.worktree, PRE_GATE_COMMIT_MESSAGE).await {
9234            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
9235                Ok(head) => {
9236                    state.event(PRE_GATE_EVENT_NODE, pre_gate_commit_event(&head));
9237                    state.pre_gate_commit = Some(head);
9238                }
9239                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
9240            },
9241            Ok(false) => {}
9242            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
9243        }
9244        if let Err(e) = state.save() {
9245            tracing::warn!("could not persist the pre_gate record: {e:#}");
9246        }
9247    }
9248
9249    /// Run `verify.gate` once against the winner's current tree, logging one
9250    /// event per command. Empty when nothing is configured.
9251    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
9252        let wait = self.repository_wait();
9253        run_landing_gate(&mut self.state, winner, &wait).await
9254    }
9255
9256    /// One bounded fix round for a failing gate.
9257    ///
9258    /// The fixer is told the failure came from the gate itself, not from a
9259    /// reviewer, and is shown the failed commands, their exit codes and a tail
9260    /// of their output - whatever `[verify].gate` holds, nothing here knows
9261    /// what those commands run. Only a normal non-zero exit that printed
9262    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
9263    /// command or a full disk says nothing about the code, and a fixer sent
9264    /// after it can only appease the machine. The round is judged by what git
9265    /// says moved, never by the fixer's own report, and `verify.e2e` runs
9266    /// again before the gate does, so a fix cannot trade a green gate for a
9267    /// red e2e unnoticed.
9268    async fn gate_fix_round(
9269        &mut self,
9270        winner: &Candidate,
9271        outcomes: &[CommandOutcome],
9272    ) -> Result<GateFix> {
9273        let cap = if self.state.repair_grants.last().is_some_and(|g| {
9274            g.phase == crate::repair_budget::Phase::Fixing
9275                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
9276        }) {
9277            self.state.gate_fixes.len().saturating_add(1)
9278        } else {
9279            self.state.config.graph.gate_fix_rounds
9280        };
9281        let spent = self.state.gate_fixes.len();
9282        if spent >= cap {
9283            if cap > 0 {
9284                self.state.event(
9285                    "gate",
9286                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
9287                );
9288            }
9289            return Ok(GateFix::Stop);
9290        }
9291        if !gate_fixable(outcomes) {
9292            self.state.event(
9293                "gate",
9294                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9295                 command or similar); not spending a fix round on it",
9296            );
9297            return Ok(GateFix::Stop);
9298        }
9299        let min_free = self.state.config.disk.min_free_bytes;
9300        if min_free > 0 {
9301            match crate::disk::free_bytes(&winner.worktree) {
9302                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9303                Ok(free) => {
9304                    self.state.event(
9305                        "gate",
9306                        format!(
9307                            "only {free} bytes free ({min_free} required by `[disk] \
9308                             min_free_bytes`); not spending a fix round on a failure the disk \
9309                             may explain"
9310                        ),
9311                    );
9312                    return Ok(GateFix::Stop);
9313                }
9314                Err(e) => {
9315                    self.state.event(
9316                        "gate",
9317                        format!("free disk space could not be measured ({e:#}); no fix round"),
9318                    );
9319                    return Ok(GateFix::Stop);
9320                }
9321            }
9322        }
9323
9324        let attempt = spent + 1;
9325        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9326        let base = self.landing_base();
9327        let fix_prompt = prompt::gate_fix_in(
9328            &self.state.instruction,
9329            &failed,
9330            attempt,
9331            cap,
9332            &self.state.config.graph.language,
9333            &self.state.config.graph.github_language,
9334        );
9335        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9336        let sessions = self.state.config.graph.sessions;
9337        let artifacts = self.merge_repair_artifacts();
9338        self.state.event(
9339            "gate",
9340            format!("gate failed; gate-fix round {attempt} of {cap}"),
9341        );
9342        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9343        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9344        // Persist before invoking the fixer: it may commit and then be
9345        // interrupted before its result (or the following e2e) is saved.
9346        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9347            before.clone(),
9348            false,
9349            Vec::new(),
9350        ));
9351        self.state.save()?;
9352        let (_, seat, out) = self
9353            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9354                prompt: fix_prompt.clone(),
9355                spec,
9356                seat,
9357                cwd: winner.worktree.clone(),
9358                timeout,
9359                allow_write: true,
9360                sessions,
9361                artifacts: artifacts.clone(),
9362                stem: format!("gate-fix-{attempt}"),
9363                handover: None,
9364            })
9365            .await;
9366        // The fixer was never asked: no round is spent (nothing is recorded)
9367        // and a later reentry asks the same agent again.
9368        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9369            return Ok(GateFix::Defer);
9370        }
9371        let mut record = GateFixRecord {
9372            agent: seat.agent.clone(),
9373            failed,
9374            notes: String::new(),
9375            committed: false,
9376            error: None,
9377        };
9378        match out {
9379            AgentOutcome::Ok(o) => {
9380                // A missing report is not a failed fix: the round is judged
9381                // by the tree below, and the report only carries prose.
9382                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9383                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9384                }
9385            }
9386            AgentOutcome::Dropped(_) => {
9387                record.error = Some("the CLI dropped the stream".to_owned());
9388            }
9389            AgentOutcome::Quota(o) => {
9390                self.state.quota.push(QuotaLoss::from_report(
9391                    seat.key.clone(),
9392                    "gate-fix",
9393                    o.quota.as_ref(),
9394                ));
9395                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9396            }
9397            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9398        }
9399        self.state.seats.insert(seat.key.clone(), seat);
9400        let coordination = self.coordinate(&winner.worktree).await?;
9401        if let Ok(r) = git::rescue_commit(
9402            &winner.worktree,
9403            &format!("magi: gate fix {attempt} (uncommitted work)"),
9404        )
9405        .await
9406        {
9407            self.state.note_withheld("gate-fix", &r.withheld);
9408        }
9409        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9410        record.committed = after != before;
9411        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9412        let note = record.error.clone();
9413        self.state.gate_fixes.push(record);
9414        self.state.save()?;
9415        if !changed {
9416            self.state.event(
9417                "gate",
9418                match note {
9419                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9420                    None => format!("gate-fix round {attempt}: the tree did not change"),
9421                },
9422            );
9423            return Ok(GateFix::Stop);
9424        }
9425        self.state.event(
9426            "gate",
9427            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9428        );
9429
9430        drop(coordination);
9431        let wait = self.repository_wait();
9432        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9433    }
9434
9435    // ---------------------------------------------------------------- merge
9436
9437    /// One read-only rewrite by the summary's author; a text the gate still
9438    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9439    /// applies on their word or on silence. `None` means the run is parked on
9440    /// that question and nothing may be pushed or opened yet.
9441    async fn guarded_pr_message(
9442        &mut self,
9443        winner: &Candidate,
9444        facts: Option<&BranchFacts>,
9445        posting: bool,
9446    ) -> Result<Option<PrMessage>> {
9447        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9448        let head = match final_head.as_deref() {
9449            Some(h) => crate::pr_outcome::FinalHead::At(h),
9450            None => crate::pr_outcome::FinalHead::Unknown,
9451        };
9452        // Only a pull request that is about to be posted pays for a summary.
9453        let summarized = if posting {
9454            Some(self.summarize_change(winner, final_head.as_deref()).await)
9455        } else {
9456            None
9457        };
9458        // A busy shared resource is not a permanent cause: publishing an
9459        // "unavailable" description would stick (a later head move never
9460        // edits the body). Stop before anything is pushed or opened; the
9461        // run is `Blocked` and a resume asks the summary again.
9462        if self.state.resource_block.is_some() {
9463            self.state.event(
9464                "pr-summary",
9465                "a shared resource was busy; nothing was published, resume to summarize again",
9466            );
9467            return Ok(None);
9468        }
9469        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9470            anyhow::bail!(
9471                "the final commit moved during public description generation; retry before publishing"
9472            );
9473        }
9474        let note = match (&summarized, &self.state.change_summary) {
9475            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9476            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9477            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9478            (None, _) => ChangeNote::NotAsked,
9479        };
9480        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9481        if !posting {
9482            let identity = crate::scrub::Identity::current();
9483            return Ok(Some(PrMessage {
9484                title: crate::scrub::scrub(&pr.title, &identity),
9485                body: crate::scrub::scrub(&pr.body, &identity),
9486            }));
9487        }
9488        // This very text was already rejected and asked about: no second
9489        // judge call, rewrite or question, just carry the record on.
9490        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9491        if let Some(known) = self
9492            .state
9493            .github_text
9494            .clone()
9495            .filter(|g| g.fingerprint == raw_fp)
9496        {
9497            return self.settle_withheld(winner, &pr, known).await;
9498        }
9499        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9500        let mut violations =
9501            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9502        let identity = crate::scrub::Identity::current();
9503        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9504            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9505            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9506        {
9507            violations.push(crate::github_text::Violation::SensitiveData);
9508        }
9509        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9510        // only a language violation starts one; sensitive data alone goes
9511        // straight to the owner, with the redacted text as the fallback.
9512        let has_language = violations
9513            .iter()
9514            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9515        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9516            self.state.event(
9517                "github-text",
9518                if has_language {
9519                    format!("description rejected: {violations:?}; requesting one rewrite")
9520                } else {
9521                    format!("description rejected: {violations:?}; asking the owner")
9522                },
9523            );
9524            let mut rewritten = false;
9525            let mut rejected_rewrite = None;
9526            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9527            {
9528                let output = text;
9529                if let Some(title) = summary_title(&output) {
9530                    // Judge the redacted candidate that will actually be posted.
9531                    // Sensitive data alone must not discard a useful rewrite.
9532                    let raw_body = summary_without_title(&output);
9533                    let clean_title = crate::scrub::scrub(&title, &identity);
9534                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9535                    let redacted = clean_title != title || body != raw_body;
9536                    let title = clean_title;
9537                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9538                    if !complete {
9539                        self.state.event(
9540                            "github-text",
9541                            "description rewrite omitted required findings",
9542                        );
9543                    }
9544                    if !body.trim().is_empty() {
9545                        body.push_str("\n\n");
9546                        body.push_str(&public_pr_evidence(&self.state, head));
9547                    }
9548                    let marker = format!("magi:run/{}", self.state.id);
9549                    if !body.trim().is_empty() && !body.contains(&marker) {
9550                        body.push_str(&format!("\n\n{marker}"));
9551                    }
9552                    let rewrite = PrMessage {
9553                        title: title.clone(),
9554                        body: body.clone(),
9555                    };
9556                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9557                    let mut failed = crate::github_text::check_for(
9558                        &self.state.config.graph,
9559                        &title,
9560                        &body,
9561                        redecision,
9562                    );
9563                    if (!crate::github_text::shareable(&title)
9564                        || !crate::github_text::shareable(&body))
9565                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9566                    {
9567                        failed.push(crate::github_text::Violation::SensitiveData);
9568                    }
9569                    if complete
9570                        && !title.trim().is_empty()
9571                        && !body.trim().is_empty()
9572                        && !failed.is_empty()
9573                    {
9574                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9575                            title: title.clone(),
9576                            body: body.clone(),
9577                            failed: failed
9578                                .iter()
9579                                .map(|v| crate::github_text::category(*v).to_owned())
9580                                .collect(),
9581                        });
9582                    }
9583                    if complete
9584                        && !title.trim().is_empty()
9585                        && !raw_body.trim().is_empty()
9586                        && failed.is_empty()
9587                    {
9588                        decision = redecision;
9589                        pr = PrMessage { title, body };
9590                        rewritten = true;
9591                        self.state
9592                            .event("github-text", "description rewrite passed");
9593                        if redacted {
9594                            self.state.event(
9595                                "github-text",
9596                                "sensitive data removed from description rewrite",
9597                            );
9598                        }
9599                    }
9600                }
9601            }
9602            if !rewritten {
9603                self.state.event(
9604                    "github-text",
9605                    "description rewrite unavailable or rejected; asking the owner",
9606                );
9607                if let Some(w) =
9608                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9609                {
9610                    // A different text than the one asked about before: that
9611                    // question no longer describes anything.
9612                    self.retire_github_text_question("the withheld text changed");
9613                    let record = crate::run::GithubTextAsk {
9614                        rewrite: rejected_rewrite,
9615                        fingerprint: raw_fp,
9616                        title: w.title,
9617                        body: w.body,
9618                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9619                        question: None,
9620                        asks: 0,
9621                        resolved: false,
9622                        chosen_title: None,
9623                        choice: None,
9624                        publication: None,
9625                    };
9626                    return self.settle_withheld(winner, &pr, record).await;
9627                }
9628            }
9629        }
9630        let (title, body) =
9631            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9632        Ok(Some(PrMessage { title, body }))
9633    }
9634
9635    /// Describe the whole change from its final diff in either run mode.
9636    ///
9637    /// The summary is tied to the final commit and to the merge base of the
9638    /// resolved remote base; a record for any other pair is dropped and the
9639    /// agent asked again, so a description never outlives the diff it was
9640    /// written from. The seat is read-only and the prompt tells it to read the
9641    /// diff and the code around it. `[roles] synthesizer` selects the agents
9642    /// (unset: the default pick), each asked at most once, advancing on an
9643    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9644    /// carries the reason it is unavailable; nothing is invented then.
9645    async fn summarize_change(
9646        &mut self,
9647        winner: &Candidate,
9648        head: Option<&str>,
9649    ) -> std::result::Result<(), String> {
9650        let Some(head) = head else {
9651            return Err("the final commit could not be read".to_owned());
9652        };
9653        let remote = self.state.config.merge.remote.clone();
9654        let tracking = format!("{remote}/{}", self.state.base_branch);
9655        if !git::rev_exists(&winner.worktree, &tracking).await {
9656            return Err(format!("the remote base `{tracking}` could not be read"));
9657        }
9658        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9659            Ok(b) if !b.is_empty() => b,
9660            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9661        };
9662        let evidence = crate::pr_outcome::summary_evidence(
9663            &self.state,
9664            crate::pr_outcome::FinalHead::At(head),
9665        );
9666        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9667        if self
9668            .state
9669            .change_summary
9670            .as_ref()
9671            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9672        {
9673            return Ok(());
9674        }
9675        if self.state.change_summary.take().is_some() {
9676            self.state.event(
9677                "pr-summary",
9678                "the final diff or evidence changed; the earlier change summary was discarded",
9679            );
9680        }
9681        // Save the source snapshot even if no generation agent is available.
9682        if let Err(e) = write_artifact(
9683            &self.state,
9684            &format!("public-description-{fingerprint}.md"),
9685            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9686        ) {
9687            tracing::warn!("could not save public description evidence: {e:#}");
9688        }
9689        let chain = match agent::pick_chain(
9690            &self.state.config.agents,
9691            self.state.config.roles.synthesizer.as_ref(),
9692            &agent::installed,
9693            "synthesizer",
9694        ) {
9695            Ok(chain) => chain,
9696            Err(e) => {
9697                tracing::warn!("no agent for the change summary: {e:#}");
9698                self.state.event("pr-summary", "no summary agent available");
9699                return Err("no agent was available to summarize it".to_owned());
9700            }
9701        };
9702        let subjects = git::subjects(&winner.worktree, &base, head)
9703            .await
9704            .unwrap_or_default();
9705        let stat = git::diff_stat(&winner.worktree, &base, head)
9706            .await
9707            .unwrap_or_default();
9708        let stat: String = stat.chars().take(6_000).collect();
9709        let mut prompt = crate::prompt::change_summary_in(
9710            &base,
9711            head,
9712            &subjects,
9713            stat.trim(),
9714            &self.state.config.graph.github_language,
9715        );
9716        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."));
9717        let sessions = self.state.config.graph.sessions;
9718        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9719        let prompts = self.state.config.prompts.clone();
9720        let cache = self.state.config.cache_dir();
9721        let run = self.state.id.clone();
9722        for (i, spec) in chain.into_iter().enumerate() {
9723            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9724            let github_spec = match agent::for_github_text(
9725                &spec,
9726                &self.state.config.graph.github_language,
9727                &winner.worktree,
9728            ) {
9729                Ok(spec) => spec,
9730                Err(e) => {
9731                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9732                    continue;
9733                }
9734            };
9735            let job = SeatJob {
9736                spec: github_spec,
9737                seat,
9738                cwd: winner.worktree.clone(),
9739                prompt: prompt.clone(),
9740                timeout,
9741                allow_write: false,
9742                sessions,
9743                artifacts: agent::artifacts_dir(&self.state.dir()),
9744                stem: if i == 0 {
9745                    "change-summary".to_owned()
9746                } else {
9747                    format!("change-summary-{}", spec.id)
9748                },
9749                handover: None,
9750            };
9751            let ctx = WaveCtx {
9752                run: &run,
9753                node: "pr-summary",
9754                prompts: &prompts,
9755                cache: cache.as_deref(),
9756                round: None,
9757                carry_seats: false,
9758                pauses: Some((&self.pause, &self.interrupt)),
9759            };
9760            let (seat, outcome) =
9761                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9762            self.state.seats.insert(seat.key.clone(), seat);
9763            let text = match outcome {
9764                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9765                AgentOutcome::ResourceBlocked(why) => {
9766                    // No agent was asked: the run stops resumably before
9767                    // anything is published (see `guarded_pr_message`).
9768                    if self.state.resource_block.is_none() {
9769                        self.state.resource_block = Some(crate::run::ResourceBlock {
9770                            cause: crate::run::ResourceBlockCause::Other,
9771                            node: "pr-summary".to_owned(),
9772                            kind: "shared resource".to_owned(),
9773                            detail: why,
9774                            at: Timestamp::now(),
9775                        });
9776                    }
9777                    return Err("a shared resource was busy".to_owned());
9778                }
9779                _ => continue,
9780            };
9781            let blind = &self.state.config.blind;
9782            let Some(title) = summary_title(&text) else {
9783                continue;
9784            };
9785            let body: String = summary_without_title(&text)
9786                .lines()
9787                .filter(|l| !l.contains("magi:run/"))
9788                .collect::<Vec<_>>()
9789                .join("\n");
9790            let body = blind::sanitize_prose(body.trim(), blind);
9791            let title = blind::sanitize_prose(&title, blind);
9792            if body.trim().is_empty() || title.trim().is_empty() {
9793                continue;
9794            }
9795            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9796                continue;
9797            }
9798            // The branch must still be the one the agent was shown.
9799            if git::rev_parse(&winner.worktree, "HEAD")
9800                .await
9801                .ok()
9802                .as_deref()
9803                != Some(head)
9804            {
9805                return Err("the branch moved while the summary was written".to_owned());
9806            }
9807            if git::merge_base(&winner.worktree, &tracking, head)
9808                .await
9809                .ok()
9810                .as_deref()
9811                != Some(base.as_str())
9812                || crate::pr_outcome::summary_evidence(
9813                    &self.state,
9814                    crate::pr_outcome::FinalHead::At(head),
9815                ) != evidence
9816            {
9817                return Err("the summary evidence changed while it was written".to_owned());
9818            }
9819            self.state.change_summary = Some(crate::run::ChangeSummary {
9820                head: head.to_owned(),
9821                base,
9822                evidence: fingerprint,
9823                title,
9824                body,
9825            });
9826            self.state.event(
9827                "pr-summary",
9828                format!("change summary written by {} for the final diff", spec.id),
9829            );
9830            if let Err(e) = self.state.save() {
9831                tracing::warn!("could not save the change summary: {e:#}");
9832            }
9833            return Ok(());
9834        }
9835        self.state
9836            .event("pr-summary", "no agent produced a change summary");
9837        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9838    }
9839
9840    /// One read-only rewrite request for a withheld description. The
9841    /// implementer's own conversation is tried first when it exists and can be
9842    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9843    /// writes it in a separate conversation, skipping the implementer's agent.
9844    /// The prompt carries the whole text, so no agent needs any memory. Each
9845    /// agent is asked at most once and the chain advances on an error, quota,
9846    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9847    /// that has run out of quota must not end the rewrite. Nothing is recorded
9848    /// as a handover.
9849    async fn rewrite_pr_text(
9850        &mut self,
9851        winner: &Candidate,
9852        pr: &PrMessage,
9853        violations: &[crate::github_text::Violation],
9854    ) -> Option<String> {
9855        let prompt = format!(
9856            "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{}",
9857            pr.title, pr.body
9858        );
9859        let sessions = self.state.config.graph.sessions;
9860        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9861        // (spec, the resumed implementer's seat). A fallback seat is created
9862        // only when its turn comes, so an unused fallback leaves no record.
9863        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9864        let key = format!("impl-{}", winner.label);
9865        if let Some(spec) = self
9866            .state
9867            .config
9868            .agents
9869            .iter()
9870            .find(|a| a.id == winner.agent)
9871            .cloned()
9872            && let Some(existing) = self.state.seats.get(&key)
9873            && existing.agent == spec.id
9874            && agent::has_session(spec.kind, existing, sessions)
9875        {
9876            attempts.push((spec, Some(existing.clone())));
9877        }
9878        match agent::pick_chain(
9879            &self.state.config.agents,
9880            self.state.config.roles.language_judge.as_ref(),
9881            &agent::installed,
9882            "language_judge",
9883        ) {
9884            Ok(chain) => {
9885                for spec in chain {
9886                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9887                        continue;
9888                    }
9889                    attempts.push((spec, None));
9890                }
9891            }
9892            Err(e) if attempts.is_empty() => {
9893                tracing::warn!("no agent for the description rewrite: {e:#}");
9894                self.state
9895                    .event("github-text", "no rewrite agent available");
9896                return None;
9897            }
9898            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9899        }
9900        let prompts = self.state.config.prompts.clone();
9901        let cache = self.state.config.cache_dir();
9902        let run = self.state.id.clone();
9903        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9904            let resumed = resumed_seat.is_some();
9905            let seat = resumed_seat.unwrap_or_else(|| {
9906                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9907            });
9908            let github_spec = match agent::for_github_text(
9909                &spec,
9910                &self.state.config.graph.github_language,
9911                &winner.worktree,
9912            ) {
9913                Ok(spec) => spec,
9914                Err(e) => {
9915                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9916                    continue;
9917                }
9918            };
9919            let job = SeatJob {
9920                spec: github_spec,
9921                seat,
9922                cwd: winner.worktree.clone(),
9923                prompt: prompt.clone(),
9924                timeout: retry_budget(timeout_full, resumed),
9925                allow_write: false,
9926                sessions,
9927                artifacts: agent::artifacts_dir(&self.state.dir()),
9928                stem: if i == 0 {
9929                    "github-text-rewrite".to_owned()
9930                } else {
9931                    format!("github-text-rewrite-{}", spec.id)
9932                },
9933                handover: None,
9934            };
9935            let ctx = WaveCtx {
9936                run: &run,
9937                node: "github-text",
9938                prompts: &prompts,
9939                cache: cache.as_deref(),
9940                round: None,
9941                carry_seats: false,
9942                pauses: Some((&self.pause, &self.interrupt)),
9943            };
9944            let (seat, outcome) =
9945                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9946            self.state.seats.insert(seat.key.clone(), seat);
9947            match outcome {
9948                AgentOutcome::Ok(o)
9949                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9950                {
9951                    return Some(o.text);
9952                }
9953                AgentOutcome::ResourceBlocked(_) => return None,
9954                _ => {}
9955            }
9956        }
9957        None
9958    }
9959
9960    /// Abandon the standing posting-gate question, if any.
9961    fn retire_github_text_question(&mut self, why: &str) {
9962        let Some(id) = self
9963            .state
9964            .github_text
9965            .as_ref()
9966            .and_then(|g| g.question.clone())
9967        else {
9968            return;
9969        };
9970        let _ = ask::Questions::open().update(&id, |q| {
9971            q.abandon(why);
9972            Ok(())
9973        });
9974    }
9975
9976    /// Carry a withheld text to its end: file the question, park while it is
9977    /// open, and on an answer, silence or timeout pick the text to post. The
9978    /// decision is saved before it is used, so it applies once.
9979    async fn settle_withheld(
9980        &mut self,
9981        winner: &Candidate,
9982        pr: &PrMessage,
9983        mut g: crate::run::GithubTextAsk,
9984    ) -> Result<Option<PrMessage>> {
9985        use crate::github_text as gt;
9986        let store = ask::Questions::open();
9987        let timeout = self.state.config.graph.answer_timeout;
9988        if !g.resolved {
9989            let mut standing = g
9990                .question
9991                .as_ref()
9992                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9993            if let Some(q) = standing.as_ref()
9994                && q.status.open()
9995                && !store.held_reply(&q.id)
9996                && gt::expired(q, timeout)
9997            {
9998                let why = format!("no answer within {}s of asking", timeout.max(1));
9999                standing = store
10000                    .update(&q.id, |q| {
10001                        q.abandon(&why);
10002                        Ok(())
10003                    })
10004                    .ok()
10005                    .map(|(q, ())| q);
10006            }
10007            let mut ask_again: Option<Option<Vec<String>>> = None;
10008            match standing {
10009                // Recorded but never written (a stop between the two saves),
10010                // or removed: ask again without spending the retry.
10011                None if g.asks <= 1 => {
10012                    g.asks = 0;
10013                    ask_again = Some(None);
10014                }
10015                None => {
10016                    g.resolved = true;
10017                    g.chosen_title = None;
10018                    g.choice = Some(GithubTextChoice::Fallback);
10019                }
10020                Some(q) if q.status.open() => {
10021                    self.park_on_github_text(&g)?;
10022                    return Ok(None);
10023                }
10024                Some(q) => match gt::read_reply(&q) {
10025                    gt::Reply::Fallback => {
10026                        g.resolved = true;
10027                        g.chosen_title = None;
10028                        g.choice = Some(GithubTextChoice::Fallback);
10029                    }
10030                    gt::Reply::Original => {
10031                        g.resolved = true;
10032                        g.chosen_title = None;
10033                        g.choice = Some(GithubTextChoice::Original);
10034                    }
10035                    gt::Reply::Rewrite => {
10036                        g.resolved = true;
10037                        g.chosen_title = None;
10038                        g.choice = Some(if g.rewrite.is_some() {
10039                            GithubTextChoice::Rewrite
10040                        } else {
10041                            GithubTextChoice::Fallback
10042                        });
10043                    }
10044                    gt::Reply::Title(text) => {
10045                        let first = text
10046                            .lines()
10047                            .map(str::trim)
10048                            .find(|l| !l.is_empty())
10049                            .unwrap_or("");
10050                        let decision = if first.is_empty() {
10051                            None
10052                        } else {
10053                            let candidate = PrMessage {
10054                                title: first.to_owned(),
10055                                body: String::new(),
10056                            };
10057                            self.judge_pr_language(&winner.worktree, &candidate).await
10058                        };
10059                        match gt::vet_title(
10060                            &text,
10061                            decision,
10062                            self.state.config.graph.github_english(),
10063                        ) {
10064                            Ok(title) => {
10065                                g.resolved = true;
10066                                g.chosen_title = Some(title);
10067                                g.choice = Some(GithubTextChoice::MyTitle);
10068                            }
10069                            Err(cats) if g.asks < 2 => {
10070                                ask_again = Some(Some(
10071                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
10072                                ))
10073                            }
10074                            Err(_) => {
10075                                g.resolved = true;
10076                                g.chosen_title = None;
10077                                g.choice = Some(GithubTextChoice::Fallback);
10078                            }
10079                        }
10080                    }
10081                },
10082            }
10083            if let Some(rejected) = ask_again {
10084                // A retry (after a rejected replacement title) is still about
10085                // the original text: the same ORIGINAL / FALLBACK comparison.
10086                let w = gt::Withheld {
10087                    title: g.title,
10088                    body: g.body,
10089                    categories: g.categories.clone(),
10090                };
10091                // Named by the original text's fingerprint alone, so a resume
10092                // rewrites the same file and the detail stays identical.
10093                let artifact = match crate::run::write_artifact(
10094                    &self.state,
10095                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
10096                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
10097                ) {
10098                    Ok(p) => Some(p),
10099                    Err(e) => {
10100                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
10101                        None
10102                    }
10103                };
10104                let (detail, comparison) = gt::question_content(
10105                    &w,
10106                    &pr.title,
10107                    &pr.body,
10108                    &self.state.id,
10109                    rejected.as_deref(),
10110                    artifact.as_deref(),
10111                    g.rewrite.as_ref(),
10112                );
10113                let mut q = ask::Question::new(
10114                    self.state.id.clone(),
10115                    gt::ASK_NODE.to_owned(),
10116                    gt::ASK_SEAT.to_owned(),
10117                    gt::question_summary(&self.state.config.graph.language, &w),
10118                    detail,
10119                    gt::question_choices(&w, g.rewrite.as_ref()),
10120                );
10121                q.posting_comparison = Some(comparison);
10122                q.answer_timeout = timeout;
10123                // Recorded before it is written: a stop in between leaves a
10124                // record naming a question the resume then files again.
10125                g.question = Some(q.id.clone());
10126                g.asks += 1;
10127                self.state.github_text = Some(g.clone());
10128                self.state.event(
10129                    "github-text",
10130                    format!("asking the owner about the withheld text ({})", q.short()),
10131                );
10132                self.state.save()?;
10133                store
10134                    .put_executable(&mut q)
10135                    .context("file the posting-gate question")?;
10136                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
10137                    tracing::warn!(
10138                        "could not notify about posting-gate question {}: {e:#}",
10139                        q.short()
10140                    );
10141                }
10142                self.park_on_github_text(&g)?;
10143                return Ok(None);
10144            }
10145        }
10146        let resolved = g.chosen_title.clone();
10147        let original = g.choice == Some(GithubTextChoice::Original);
10148        // Field names only: the event log never records the text.
10149        self.state.event(
10150            "github-text",
10151            if original {
10152                format!(
10153                    "posting the original text for: {}",
10154                    match (g.title, g.body) {
10155                        (true, true) => "title, description",
10156                        (true, false) => "title",
10157                        _ => "description",
10158                    }
10159                )
10160            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
10161                "posting the saved rewrite title and description".to_owned()
10162            } else if resolved.is_some() {
10163                "posting the owner's replacement title".to_owned()
10164            } else {
10165                "posting the neutral text for the withheld fields".to_owned()
10166            },
10167        );
10168        self.state.github_text = Some(g.clone());
10169        self.state.save()?;
10170        if g.choice == Some(GithubTextChoice::Rewrite)
10171            && let Some(r) = g.rewrite.as_ref()
10172        {
10173            return Ok(Some(PrMessage {
10174                title: r.title.clone(),
10175                body: r.body.clone(),
10176            }));
10177        }
10178        let w = gt::Withheld {
10179            title: g.title,
10180            body: g.body,
10181            categories: g.categories.clone(),
10182        };
10183        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
10184        if let Some(t) = resolved {
10185            title = t;
10186        }
10187        // Every withheld field is now neutral or vetted English.
10188        let english = gt::LanguageDecision {
10189            title_english: true,
10190            body_english: true,
10191            body_complete: true,
10192        };
10193        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
10194        if original {
10195            // The owner's explicit choice overrides the gate for the fields it
10196            // was made for; the others keep what the gate produced.
10197            if g.title {
10198                title = pr.title.clone();
10199            }
10200            if g.body {
10201                body = pr.body.clone();
10202            }
10203        }
10204        Ok(Some(PrMessage { title, body }))
10205    }
10206
10207    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
10208        self.state.github_text = Some(g.clone());
10209        self.state.end_pass_parked(ParkCause::Question);
10210        self.state.parked = true;
10211        self.state.event(
10212            "github-text",
10213            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
10214        );
10215        self.state.save()
10216    }
10217
10218    /// Ask `[roles] language_judge` about this text and record which source
10219    /// decided; the text itself is never recorded.
10220    async fn judge_pr_language(
10221        &mut self,
10222        cwd: &Path,
10223        pr: &PrMessage,
10224    ) -> Option<crate::github_text::LanguageDecision> {
10225        self.state.config.roles.language_judge.as_ref()?;
10226        if !self.state.config.graph.language_gate() {
10227            return None;
10228        }
10229        let decision =
10230            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
10231        self.state.event(
10232            "github-text",
10233            if decision.is_some() {
10234                "language decided by the language judge"
10235            } else {
10236                "language judge unavailable; using built-in heuristics"
10237            },
10238        );
10239        decision
10240    }
10241
10242    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10243        Box::pin(self.merge_inner())
10244    }
10245
10246    async fn merge_inner(&mut self) -> Result<()> {
10247        if self.resource_halt()? || self.hold_base_sync().await? {
10248            return Ok(());
10249        }
10250        // Same reasoning as `gate`: ask the review and gate records directly
10251        // rather than `status`, which a solo-candidate `judge`/`deliberate`
10252        // skip can rewrite on reentry to something that no longer says
10253        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
10254        // so a hand-off (open findings, green verification) reaches merge
10255        // exactly like a genuinely clean round does.
10256        //
10257        // A run resumed mid-`land` never reaches here at all: `execute`
10258        // recognises `RunStatus::Landing` before it even calls `prep`, and
10259        // routes straight to `run_land` instead. That has to happen a level
10260        // up from this function, not with a check in here, because
10261        // `review_loop`'s own status recomputation (see its doc) runs
10262        // *before* `merge` on every reentry and would otherwise overwrite
10263        // the `Landing` marker with `Gating` before this node ever saw it.
10264        if self
10265            .state
10266            .base_sync
10267            .as_ref()
10268            .is_some_and(|s| s.conflict.is_some())
10269            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10270                != Some(RunStatus::Gating)
10271            // `gate_ran == false` is not "passed" - `gate` leaves it false
10272            // both before it has ever run and when its last attempt was
10273            // resource-blocked (see `Runner::gate`'s own doc), and neither is
10274            // permission to merge on nothing but the review record. Only a
10275            // gate that actually ran may proceed; an intentional local
10276            // review can also finish with verification explicitly not configured.
10277            // `RunState::gate_status` computes that distinction.
10278            || !self.state.gate_allows_progress()
10279        {
10280            return Ok(());
10281        }
10282        // This node's own record, not `status`: `status == Ready` is not
10283        // unique to the harmless `MergeMode::None` path this line was
10284        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
10285        // run's PR was closed without merging — and on that run `mode` is
10286        // still `Pr`, so a reentry that fell through here would push and
10287        // open a second pull request. `self.state.merge` is set exactly once
10288        // this node (or `land`) has already produced a verdict, under every
10289        // mode, which is what "already done" actually means here.
10290        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10291            return Ok(());
10292        }
10293        let Some(winner) = self.state.winner().cloned() else {
10294            return Ok(());
10295        };
10296        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10297        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10298            self.state.status = RunStatus::Blocked;
10299            self.state.event(
10300                "gate",
10301                "winner changed after gate; fresh verification required",
10302            );
10303            self.state.save()?;
10304            return Ok(());
10305        }
10306        let wait = self.repository_wait();
10307        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10308            return Ok(());
10309        }
10310        let repo = self.state.repo.clone();
10311        let base = self.state.base_branch.clone();
10312        let mode = self.state.config.merge.mode;
10313        let style = self.state.config.merge.style;
10314        let facts = if is_review_run(&self.state) {
10315            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10316            let start = review_base(
10317                &repo,
10318                &self.state.config.merge.remote,
10319                &base,
10320                &self.state.base_commit,
10321                &winner.branch,
10322            )
10323            .await;
10324            branch_facts(&repo, &start, &winner.branch).await
10325        } else {
10326            None
10327        };
10328        // `None` when the base could not be freshly read: then an adopted
10329        // pull request's title is left alone.
10330        let leaked = if is_review_run(&self.state) {
10331            leaked_subjects(&self.state, &winner.branch).await
10332        } else {
10333            Some(Vec::new())
10334        };
10335        // `None`: parked on the owner's word about a withheld title or body.
10336        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10337        // the resume arrives here again.
10338        let Some(pr) = self
10339            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10340            .await?
10341        else {
10342            return Ok(());
10343        };
10344        let message = pr.commit_message();
10345
10346        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10347        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10348            return Ok(());
10349        }
10350        let outcome = match mode {
10351            MergeMode::None => MergeOutcome {
10352                mode,
10353                ok: true,
10354                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10355                empty: false,
10356            },
10357            MergeMode::Pr | MergeMode::Local
10358                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10359            {
10360                MergeOutcome {
10361                    mode,
10362                    ok: false,
10363                    detail: empty_candidate_detail(&self.state, &base),
10364                    empty: true,
10365                }
10366            }
10367            MergeMode::Local => {
10368                let on = git::current_branch(&repo).await?;
10369                if on.as_deref() != Some(base.as_str()) {
10370                    MergeOutcome {
10371                        mode,
10372                        ok: false,
10373                        detail: format!(
10374                            "{} has {} checked out, not the base branch {base}",
10375                            repo.display(),
10376                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10377                        ),
10378                        empty: false,
10379                    }
10380                } else if !git::is_clean(&repo).await? {
10381                    MergeOutcome {
10382                        mode,
10383                        ok: false,
10384                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10385                        empty: false,
10386                    }
10387                } else {
10388                    let out = match style {
10389                        MergeStyle::Merge => {
10390                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10391                        }
10392                        MergeStyle::Squash => {
10393                            git::merge_squash(&repo, &winner.branch, &message).await?
10394                        }
10395                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10396                    };
10397                    MergeOutcome {
10398                        mode,
10399                        ok: out.ok(),
10400                        detail: if out.ok() { out.stdout } else { out.stderr },
10401                        empty: false,
10402                    }
10403                }
10404            }
10405            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10406                self.state.pr_publication_pending = true;
10407                self.state.save()?;
10408                let out =
10409                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10410                self.state.pr_publication_pending = out.is_err();
10411                MergeOutcome {
10412                    mode,
10413                    ok: out.is_ok(),
10414                    detail: match out {
10415                        Ok(url) => url,
10416                        Err(e) => format!("{e:#}"),
10417                    },
10418                    empty: false,
10419                }
10420            }
10421            MergeMode::Pr => {
10422                let remote = self.state.config.merge.remote.clone();
10423                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10424                let pushed = if self.state.foreign_checkout.is_some() {
10425                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10426                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10427                } else {
10428                    git::push(&winner.worktree, &remote, &winner.branch).await?
10429                };
10430                if !pushed.ok() {
10431                    MergeOutcome {
10432                        mode,
10433                        ok: false,
10434                        detail: pushed.stderr,
10435                        empty: false,
10436                    }
10437                } else {
10438                    if self.state.foreign_checkout.is_some() {
10439                        self.state.pr_pushed_head = Some(delivery_head.clone());
10440                    }
10441                    // A retry or resume of a run whose branch already has an
10442                    // open pull request adopts it rather than failing on a
10443                    // duplicate. Only this winner branch into this base:
10444                    // `branch_for` derives the name from the run id, so a
10445                    // different run's pull request never matches.
10446                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10447                    let out = match pr_merge_plan(found) {
10448                        PrPlan::Create => {
10449                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10450                                .await
10451                        }
10452                        PrPlan::Adopt { url, title } => {
10453                            self.state
10454                                .event("merge", format!("Pr: adopted open pull request {url}"));
10455                            if self.state.explicit_github_text_selection() {
10456                                // An explicit publication selection applies the prepared
10457                                // payload; acceptance alone is not publication proof.
10458                                land::set_pr_text_verbatim(
10459                                    &winner.worktree,
10460                                    &url,
10461                                    &pr.title,
10462                                    &pr.body,
10463                                )
10464                                .await
10465                                .map(|()| url)
10466                            } else {
10467                                if title != pr.title
10468                                    && (!is_review_run(&self.state)
10469                                        || leaked
10470                                            .as_deref()
10471                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10472                                    && let Err(e) =
10473                                        if self.state.github_text.as_ref().is_some_and(|g| {
10474                                            g.resolved
10475                                                && g.title
10476                                                && g.choice == Some(GithubTextChoice::Original)
10477                                        }) {
10478                                            // The owner chose to post this title unmodified.
10479                                            land::set_pr_title_verbatim(
10480                                                &winner.worktree,
10481                                                &url,
10482                                                &pr.title,
10483                                            )
10484                                            .await
10485                                        } else {
10486                                            land::set_pr_title(
10487                                                &mut self.state,
10488                                                &winner.worktree,
10489                                                &url,
10490                                                &pr.title,
10491                                            )
10492                                            .await
10493                                        }
10494                                {
10495                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10496                                    self.state
10497                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10498                                }
10499                                Ok(url)
10500                            }
10501                        }
10502                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10503                    };
10504                    match out {
10505                        Ok(url) => MergeOutcome {
10506                            mode,
10507                            ok: true,
10508                            detail: url,
10509                            empty: false,
10510                        },
10511                        Err(e) => MergeOutcome {
10512                            mode,
10513                            ok: false,
10514                            detail: e.to_string(),
10515                            empty: false,
10516                        },
10517                    }
10518                }
10519            }
10520        };
10521
10522        self.state.status = match (mode, outcome.ok) {
10523            (MergeMode::None, _) => RunStatus::Ready,
10524            (_, true) if outcome.empty => RunStatus::Ready,
10525            (MergeMode::Pr, true) => RunStatus::Ready,
10526            (_, true) => RunStatus::Merged,
10527            (_, false) => RunStatus::Blocked,
10528        };
10529        self.state.event(
10530            "merge",
10531            format!(
10532                "{:?}: {}",
10533                mode,
10534                outcome.detail.lines().next().unwrap_or("")
10535            ),
10536        );
10537        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10538            self.state.record_github_text_publication(&outcome.detail);
10539        }
10540        self.state.merge = Some(outcome);
10541        self.state.save()?;
10542
10543        // The PR is open and the run would historically stop here, leaving the
10544        // operator to watch checks, feed review comments back to a fixer, and
10545        // merge. That was done by hand six times in one session before this
10546        // existed. Opt-in, because merging is the one irreversible thing magi
10547        // can do to a repository.
10548        if self.state.config.graph.land
10549            && mode == MergeMode::Pr
10550            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10551        {
10552            self.run_land().await?;
10553        }
10554        // `run_land` may have left `status` at `Landing` - still waiting on
10555        // CI or the owner's approval, not actually settled - so this has to
10556        // read whatever `status` ended up as here, not the `Merged` this
10557        // function set a few lines up.
10558        self.settle_questions();
10559        Ok(())
10560    }
10561
10562    /// Enter `land`.
10563    ///
10564    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10565    /// a resumed run's re-entry. `land::land` itself is what serialises the
10566    /// two git-mutating moments inside the loop — the rebase push and
10567    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10568    /// to hold a lock across the whole call, and doing so would serialise
10569    /// this run's CI wait against a *different* run's land-approval resume
10570    /// in the same repository, which is exactly the "must not wait on
10571    /// another task" property the daemon's slot-freeing exists to give.
10572    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10573        Box::pin(self.run_land_inner())
10574    }
10575
10576    async fn run_land_inner(&mut self) -> Result<()> {
10577        crate::pr_head::ensure_owner(&self.state)?;
10578        let url = self
10579            .state
10580            .pr
10581            .as_ref()
10582            .map(|pr| pr.url.clone())
10583            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10584            .unwrap_or_default();
10585        let url = url.lines().next().unwrap_or("").trim().to_owned();
10586        if !url.starts_with("http") {
10587            return Ok(());
10588        }
10589        // A land failure is not a lost run: the work is on a branch and the
10590        // pull request is open, which is exactly where a human takes over.
10591        loop {
10592            match land::land(&mut self.state, &url).await {
10593                Ok(_)
10594                    if self
10595                        .state
10596                        .merge_repairs
10597                        .last()
10598                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10599                {
10600                    if self.repair_merge_review().await? {
10601                        continue;
10602                    }
10603                }
10604                Ok(_) if self.state.resource_block.is_some() => {
10605                    return self.stop_for_resource();
10606                }
10607                Ok(pr) if self.state.parked => {
10608                    // `land` already saved the parked marker; nothing here
10609                    // overrides `status` back to a terminal value while an
10610                    // approval is still outstanding.
10611                    let _ = pr;
10612                }
10613                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10614                    self.state.status = RunStatus::Superseded;
10615                    self.state.save()?;
10616                }
10617                Ok(pr) => {
10618                    self.state.status = match pr.state {
10619                        land::PrLifecycle::Merged => RunStatus::Merged,
10620                        _ => RunStatus::Blocked,
10621                    };
10622                    // Downstream of a confirmed merge only - see
10623                    // `bump::should_release_bump`'s own doc for why this one
10624                    // check covers all three of `land`'s success paths.
10625                    // Best-effort: the run already landed, so a failure here
10626                    // (the decision call, `gh`, `cargo`) is recorded and never
10627                    // turns a landed run into a failed one.
10628                    if bump::should_release_bump(self.state.status)
10629                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10630                    {
10631                        // The event is the run's own record. Not-eligible cases
10632                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10633                        // `Err` is a bump that was tried and failed:
10634                        // `after_merge` itself raises the operator notice for
10635                        // that, whether or not a release PR exists yet.
10636                        self.state
10637                            .event("bump", format!("release bump skipped: {e:#}"));
10638                    }
10639                    // Independent of the bump, and best-effort in the same way:
10640                    // findings the merge left open become follow-up tasks.
10641                    if self.state.status == RunStatus::Merged {
10642                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10643                    }
10644                    self.state.save()?;
10645                }
10646                Err(e) => {
10647                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10648                        return Err(e);
10649                    }
10650                    self.state.status = RunStatus::Blocked;
10651                    self.state.event("land", format!("gave up: {e}"));
10652                    self.state.save()?;
10653                }
10654            }
10655            break;
10656        }
10657        Ok(())
10658    }
10659
10660    /// One repair cycle stays under the existing driver/task claim. An
10661    /// interrupted fixer is rolled back and held rather than run twice.
10662    async fn repair_merge_review(&mut self) -> Result<bool> {
10663        use crate::run::MergeRepairPhase as Phase;
10664        crate::pr_head::ensure_owner(&self.state)?;
10665        let i = self.state.merge_repairs.len() - 1;
10666        let request = self.state.merge_repairs[i].clone();
10667        if request.phase == Phase::Fixing {
10668            let restored = match self.state.winner().cloned() {
10669                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10670                None => Err(anyhow::anyhow!("repair has no winning branch")),
10671            };
10672            let why = match restored {
10673                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10674                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10675                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10676            };
10677            self.hold_merge_repair(i, why)?;
10678            return Ok(false);
10679        }
10680        // A completed repair gate is a publication checkpoint. On reentry,
10681        // reject external changes before the ordinary gate path can replace
10682        // that evidence by verifying a new head. Requested repairs still
10683        // start their own review generation below.
10684        if request.phase == Phase::Reviewing && self.state.gate_ran {
10685            let winner = self
10686                .state
10687                .winner()
10688                .context("repair has no winning branch")?;
10689            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10690            if self.state.gate_head.as_deref() != Some(head.as_str())
10691                || !git::is_clean(&winner.worktree).await?
10692            {
10693                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())?;
10694                return Ok(false);
10695            }
10696        }
10697        let failure = if i >= self.state.config.graph.land_rounds
10698            || self.state.config.graph.review_rounds == 0
10699        {
10700            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10701        } else {
10702            None
10703        };
10704        if let Some(why) = failure {
10705            self.hold_merge_repair(i, why)?;
10706            return Ok(false);
10707        }
10708        if request.phase == Phase::Requested {
10709            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10710                Ok(pr) => pr,
10711                Err(e) => {
10712                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10713                    return Ok(false);
10714                }
10715            };
10716            self.state.merge_repairs[i].phase = Phase::Fixing;
10717            self.state.land_approval = None;
10718            self.state.land_armed_head = None;
10719            self.state.save()?;
10720            // Serialize the exact records, including finding ids/details,
10721            // reconsideration reasons, final votes and verification output.
10722            let evidence = serde_json::to_string_pretty(&request)?;
10723            let reason = format!(
10724                "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}"
10725            );
10726            let budget = self.state.config.graph.land_rounds;
10727            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10728            match result {
10729                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10730                Ok(land::Fixed::Deferred) => {
10731                    // An unavailable fixer did not spend this repair request.
10732                    // Restore partial fallback work before retrying it, as for
10733                    // an interrupted repair, without closing the request.
10734                    let worktree = self
10735                        .state
10736                        .winner()
10737                        .context("repair has no winning branch")?
10738                        .worktree
10739                        .clone();
10740                    self.graft_restore(&worktree, &request.head).await?;
10741                    self.state.merge_repairs[i].phase = Phase::Requested;
10742                    self.stop_for_resource()?;
10743                    return Ok(false);
10744                }
10745                Ok(land::Fixed::Failed(why)) => {
10746                    self.hold_merge_repair(
10747                        i,
10748                        format!(
10749                            "repair failed: {why}; inspect the branch and run an explicit review"
10750                        ),
10751                    )?;
10752                    return Ok(false);
10753                }
10754                Err(e) => {
10755                    self.hold_merge_repair(
10756                        i,
10757                        format!(
10758                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10759                        ),
10760                    )?;
10761                    return Ok(false);
10762                }
10763            }
10764            // Even no change gets a real new reviewer wave. The previous
10765            // evidence remains in the request; a former clean/concluded round
10766            // cannot short-circuit the new review or gate.
10767            self.begin_merge_repair_review(i)?;
10768        }
10769        self.review_loop().await?;
10770        self.gate().await?;
10771        if self.resource_halt()? || self.state.parked {
10772            return Ok(false);
10773        }
10774        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10775            != Some(RunStatus::Gating)
10776            || !self.state.gate_allows_progress()
10777        {
10778            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10779            return Ok(false);
10780        }
10781        // Review and gate may have added commits after the initial repair.
10782        // Publish exactly their final head to the existing PR, with a lease.
10783        let winner = self
10784            .state
10785            .winner()
10786            .cloned()
10787            .context("repair has no winning branch")?;
10788        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10789        if self.state.gate_head.as_deref() != Some(after.as_str())
10790            || !git::is_clean(&winner.worktree).await?
10791        {
10792            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())?;
10793            return Ok(false);
10794        }
10795        let expected = self
10796            .state
10797            .pr_pushed_head
10798            .as_deref()
10799            .unwrap_or(&request.head)
10800            .to_owned();
10801        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10802        // Push the checked commit itself: a local ref moving after the check
10803        // must not change which commit the forge receives.
10804        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10805            return Ok(false);
10806        }
10807        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10808        let refspec = format!("{after}:refs/heads/{public}");
10809        let push = git::git_raw(
10810            &winner.worktree,
10811            &["push", &lease, &self.state.config.merge.remote, &refspec],
10812        )
10813        .await;
10814        match push {
10815            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10816            Ok(out) => {
10817                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10818                return Ok(false);
10819            }
10820            Err(e) => {
10821                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10822                return Ok(false);
10823            }
10824        }
10825        self.state.merge_repairs[i].phase = Phase::Complete;
10826        self.state.status = RunStatus::Landing;
10827        self.state.event(
10828            "repair",
10829            "new review and gate completed; fresh owner merge decision required",
10830        );
10831        self.state.save()?;
10832        Ok(true)
10833    }
10834
10835    fn merge_repair_artifacts(&self) -> PathBuf {
10836        let artifacts = agent::artifacts_dir(&self.state.dir());
10837        match self
10838            .state
10839            .merge_repairs
10840            .last()
10841            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10842        {
10843            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10844            None => artifacts,
10845        }
10846    }
10847
10848    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10849        if let Some(e2e) = self.state.head_e2e.take() {
10850            self.state
10851                .verification_history
10852                .push(crate::run::VerificationEvidence {
10853                    superseded_by: None,
10854                    archived_at: Some(Timestamp::now()),
10855                    fixes_spent: Some(self.state.gate_fixes.len()),
10856                    gate_head: None,
10857                    gate_ran: false,
10858                    gate: Vec::new(),
10859                    e2e: Some(e2e),
10860                });
10861        }
10862        self.state.reviews.clear();
10863        self.state.gate.clear();
10864        self.state.gate_ran = false;
10865        self.state.gate_head = None;
10866        self.state.gate_fixes.clear();
10867        self.state.gate_repair_e2e = None;
10868        self.state.pre_gate.clear();
10869        self.state.pre_gate_commit = None;
10870        self.state.contested_handoff = None;
10871        self.state.land_reruns = None;
10872        self.state.land_approval = None;
10873        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10874        self.state.status = RunStatus::Reviewing;
10875        self.state.save()
10876    }
10877
10878    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10879        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10880        self.state.merge_repairs[index].failure = Some(why.clone());
10881        self.state.status = RunStatus::Blocked;
10882        self.state.event("repair", why);
10883        self.state.save()
10884    }
10885
10886    // -------------------------------------------------------------- helpers
10887
10888    /// Fetch or create a seat, keeping its conversation across nodes.
10889    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10890        if let Some(existing) = self.state.seats.get(key)
10891            && existing.agent == agent
10892        {
10893            return existing.clone();
10894        }
10895        // A seat that changes agent mints its session id from the agent too,
10896        // like a handover: the old agent's uuid is already taken by the CLI.
10897        let fresh = if self.state.seats.contains_key(key) {
10898            handover_seat(key, agent, self.state.next_seat_seed())
10899        } else {
10900            SeatState::new(key, agent, self.state.seed)
10901        };
10902        self.state.seats.insert(key.to_owned(), fresh.clone());
10903        fresh
10904    }
10905
10906    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10907    /// seat to another roster agent, in which case that agent. Nodes that
10908    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10909    /// reconsideration) must keep talking to whoever answered it, not slip
10910    /// back to the agent that failed it.
10911    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10912        match self.state.seats.get(key) {
10913            Some(s) if s.agent != spec.id => {
10914                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10915            }
10916            _ => spec,
10917        }
10918    }
10919
10920    /// A candidate rendered for judging, with the leak policy applied.
10921    fn view(&self, c: &Candidate) -> CandidateView {
10922        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10923            .unwrap_or_default();
10924        let (patch, _) = blind::sanitize_patch(
10925            &format!("candidate {} patch", c.label),
10926            &raw,
10927            &self.state.config.blind,
10928        );
10929        CandidateView {
10930            label: c.label,
10931            branch: c.branch.clone(),
10932            summary: c.summary.clone(),
10933            stat: c.stat.clone(),
10934            patch,
10935        }
10936    }
10937
10938    /// The full candidate set as prompt text, for seats with no live session.
10939    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10940        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10941        prompt::judge(
10942            "(see above)",
10943            &views,
10944            self.roles.judges.len(),
10945            base_short,
10946            "en",
10947        )
10948    }
10949
10950    /// The final-vote prompt with everything a seat that has no session of its
10951    /// own needs: the candidates, the seat's own ranking and reasons, and the
10952    /// anonymised deliberation it took part in (only when there was one, so a
10953    /// handed-over seat never sees more than the seat it replaces did). The
10954    /// `Final vote` heading stays first.
10955    fn vote_prompt_full(
10956        &self,
10957        j: usize,
10958        labels: &[char],
10959        language: &str,
10960        candidates: &[Candidate],
10961        base_short: &str,
10962    ) -> String {
10963        let mut text = format!(
10964            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10965            prompt::final_vote(labels, language),
10966            self.state.instruction,
10967            self.candidate_block(candidates, base_short)
10968        );
10969        if let Some(own) = self
10970            .state
10971            .judgements
10972            .get(j)
10973            .filter(|r| !r.ranking.is_empty())
10974        {
10975            let reasons = own
10976                .reasons
10977                .iter()
10978                .map(|(k, v)| format!("- {k}: {v}"))
10979                .collect::<Vec<_>>()
10980                .join("\n");
10981            text.push_str(&format!(
10982                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10983                own.ranking.iter().collect::<String>(),
10984                if reasons.is_empty() {
10985                    ""
10986                } else {
10987                    ", because:\n"
10988                }
10989            ));
10990        }
10991        if !self.state.deliberation.is_empty() {
10992            text.push_str("\n# What was argued before this vote\n");
10993            for t in self.transcript(&[], j) {
10994                text.push_str(&format!(
10995                    "\n## {}{}\n\n{}\n",
10996                    t.who,
10997                    if t.is_self { " (you)" } else { "" },
10998                    t.body.trim()
10999                ));
11000            }
11001        }
11002        text
11003    }
11004
11005    /// Anonymised transcript for judge `self_idx`.
11006    ///
11007    /// The initial rankings are always the opening statements. Seeding them
11008    /// only when no turn had been taken yet meant every judge after the first
11009    /// argued against a single voice instead of against the actual split — the
11010    /// disagreement is the information, so it is always on the table.
11011    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
11012        let mut turns = Vec::new();
11013        for j in &self.state.judgements {
11014            if j.ranking.is_empty() {
11015                continue;
11016            }
11017            let reasons = j
11018                .reasons
11019                .iter()
11020                .map(|(k, v)| format!("- {k}: {v}"))
11021                .collect::<Vec<_>>()
11022                .join("\n");
11023            turns.push(Turn {
11024                who: format!("Judge {} (opening ranking)", j.judge),
11025                is_self: j.judge == self_idx + 1,
11026                body: format!(
11027                    "Ranked {}{}{reasons}",
11028                    j.ranking.iter().collect::<String>(),
11029                    if reasons.is_empty() {
11030                        ""
11031                    } else {
11032                        ", because:\n"
11033                    }
11034                ),
11035            });
11036        }
11037        for t in self
11038            .state
11039            .deliberation
11040            .iter()
11041            .flat_map(|r| r.turns.iter())
11042            .chain(current)
11043        {
11044            turns.push(Turn {
11045                who: format!("Judge {}", t.judge),
11046                is_self: t.judge == self_idx + 1,
11047                body: t.body.clone(),
11048            });
11049        }
11050        turns
11051    }
11052}
11053
11054/// Does this seat still hold the context a follow-up prompt would rely on?
11055fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
11056    agent::has_session(spec.kind, seat, sessions)
11057}
11058
11059/// The next entry in `roster` after `start`, never wrapping back to the
11060/// front, whose id is not in `tried` yet.
11061///
11062/// Starts one past `start` rather than at the front of `roster`: `start` is
11063/// the seat's own original position, and a seat whose candidate slot already
11064/// sits on the roster's second entry must fall through to the third next, not
11065/// restart at the first — which is very likely a different candidate's own
11066/// agent already. Never wraps back past `start`, for the same reason: an
11067/// entry earlier in the roster than the seat's own position is almost
11068/// certainly some *other* candidate slot's own agent, and once the tail of
11069/// the roster is exhausted there are no more untried agents for *this* seat
11070/// to fall through to — the caller's fallback chain ends there, exactly as
11071/// "no further untried agents remain in the list for that seat" asks for.
11072///
11073/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
11074/// the same id twice (an operator's `roles.implementers` typo, or a
11075/// `[[agents]]` list reused across roles) must not let
11076/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
11077/// over `roster` either finds an untried id or runs out, so this always
11078/// terminates regardless of duplicates.
11079fn next_untried_in_roster<'a>(
11080    roster: &'a [AgentSpec],
11081    start: usize,
11082    tried: &BTreeSet<String>,
11083) -> Option<&'a AgentSpec> {
11084    roster
11085        .get(start + 1..)?
11086        .iter()
11087        .find(|s| !tried.contains(&s.id))
11088}
11089
11090/// The successor for a seat, shared by all four seat kinds (implement, judge,
11091/// review, advise). `others` holds the ids that *currently* occupy the other
11092/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
11093/// sees them), so roster entries beyond the seat count act as spares: a failed
11094/// seat goes to an agent no other seat holds whenever the roster permits.
11095///
11096/// `carried` is `Some` only for the review loop's carried failure history.
11097/// Order: (1) forward from `start`, never wrapping, untried, not a carried
11098/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
11099/// whole roster: untried and not another seat's occupant; (3) the plain walk
11100/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
11101/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
11102/// a better outcome than an empty seat, and it keeps the answer to "is there
11103/// a successor at all" exactly what it was before occupants were considered,
11104/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
11105/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
11106/// carried failure is a cheaper bet than doubling an agent on the panel, and
11107/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
11108/// the same round are handled one at a time, so a seat later in the batch
11109/// sees an earlier one's new occupant but not yet its own freed agent.
11110fn pick_successor<'a>(
11111    roster: &'a [AgentSpec],
11112    start: usize,
11113    tried: &BTreeSet<String>,
11114    carried: Option<&BTreeSet<String>>,
11115    others: &BTreeSet<String>,
11116) -> Option<&'a AgentSpec> {
11117    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
11118    roster
11119        .get(start + 1..)
11120        .and_then(|tail| {
11121            tail.iter()
11122                .filter(free)
11123                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
11124        })
11125        .or_else(|| {
11126            carried
11127                .is_some()
11128                .then(|| roster.iter().find(free))
11129                .flatten()
11130        })
11131        .or_else(|| match carried {
11132            Some(c) => next_for_seat(roster, start, tried, c),
11133            None => next_untried_in_roster(roster, start, tried),
11134        })
11135}
11136
11137/// The next agent for a seat that carries its failure history across rounds
11138/// (the review loop). `round_tried` is this round's own bound and starts
11139/// empty every round; `carried_failed` only decides priority.
11140///
11141/// First: an id walking forward from `start`, never wrapping, that is neither
11142/// tried this round nor failed in an earlier one. Only when that is exhausted
11143/// does it rescue: the first roster id (in roster order, so this one *does*
11144/// look before `start`) not yet tried this round, which is by then a carried
11145/// failure. Each id is rescued at most once per round, so it cannot loop.
11146fn next_for_seat<'a>(
11147    roster: &'a [AgentSpec],
11148    start: usize,
11149    round_tried: &BTreeSet<String>,
11150    carried_failed: &BTreeSet<String>,
11151) -> Option<&'a AgentSpec> {
11152    roster
11153        .get(start + 1..)?
11154        .iter()
11155        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
11156        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
11157}
11158
11159/// Where a reviewer seat starts a round: the agent that last answered it when
11160/// it is still on the roster and not marked failed, else the spec's own agent
11161/// unless it failed, else the next roster agent that has not failed, else the
11162/// spec's own agent again (the whole roster failed). Ids no longer on the
11163/// roster are ignored. An empty roster has no handover, so the spec stands.
11164fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
11165    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
11166        return spec;
11167    };
11168    let ok = |id: &str| !h.failed.contains(id);
11169    if let Some(last) = h.last_ok.as_deref()
11170        && ok(last)
11171        && let Some(s) = roster.iter().find(|s| s.id == last)
11172    {
11173        return s.clone();
11174    }
11175    if ok(&spec.id) {
11176        return spec;
11177    }
11178    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
11179    roster
11180        .get(from + 1..)
11181        .into_iter()
11182        .flatten()
11183        .chain(roster.iter())
11184        .find(|s| ok(&s.id))
11185        .cloned()
11186        .unwrap_or(spec)
11187}
11188
11189/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
11190/// seed so a CLI that mints its session id up front (`--session-id`) never
11191/// reuses the uuid the previous agent already opened under the same seat key.
11192pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
11193    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
11194}
11195
11196/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
11197/// so the classifier below and the code that builds the message cannot drift.
11198const TIMED_OUT: &str = "timed out";
11199
11200impl FailClass {
11201    /// `None` for an answer; otherwise how the turn failed.
11202    fn of(out: &AgentOutcome) -> Option<Self> {
11203        match out {
11204            AgentOutcome::Ok(_) => None,
11205            AgentOutcome::Quota(_) => Some(Self::Quota),
11206            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
11207            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
11208            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
11209            // Not a failure of the agent. Callers check for it first; `None`
11210            // here means "no class to hand over on".
11211            AgentOutcome::ResourceBlocked(_) => None,
11212        }
11213    }
11214
11215    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11216    fn stem_word(&self) -> &'static str {
11217        match self {
11218            Self::Quota => "quota",
11219            _ => "handover",
11220        }
11221    }
11222}
11223
11224/// The message's first line with its variable parts removed — digit runs and
11225/// path-like tokens — so "exit code 2" and "exit code 7" read
11226/// as one kind of failure.
11227fn failure_signature(msg: &str) -> String {
11228    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11229    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11230    // the historical machine key while the process diagnosis uses readable prose.
11231    if let Some(code) = line
11232        .strip_prefix("process exited with no usable output (exit code ")
11233        .and_then(|s| s.strip_suffix(')'))
11234        .and_then(|s| s.parse::<i32>().ok())
11235    {
11236        line = format!("exited with some({code}) and no usable output");
11237    } else if matches!(
11238        line.as_str(),
11239        "process exited with no usable output (no exit code reported)"
11240            | "process exited with no usable output (exit code unavailable)"
11241    ) {
11242        line = "exited with none and no usable output".to_owned();
11243    }
11244    let mut out = Vec::new();
11245    for word in line.split_whitespace() {
11246        if word.contains('/') || word.contains('\\') {
11247            out.push("<path>".to_owned());
11248            continue;
11249        }
11250        let mut w = String::new();
11251        let mut in_digits = false;
11252        for c in word.chars() {
11253            if c.is_ascii_digit() {
11254                if !in_digits {
11255                    w.push('#');
11256                }
11257                in_digits = true;
11258            } else {
11259                in_digits = false;
11260                w.push(c);
11261            }
11262        }
11263        out.push(w);
11264    }
11265    out.join(" ").chars().take(120).collect()
11266}
11267
11268/// Whether a seat that just failed with `cur` may go to the next roster agent.
11269/// A quota or a timeout always may. Any other failure may not when the agent
11270/// before it failed the same way: an error the prompt causes would otherwise
11271/// walk the whole roster. `prev` is the class of the immediately preceding
11272/// agent's failure, so a quota or timeout in between breaks the run of
11273/// identical failures by itself.
11274fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11275    match cur {
11276        FailClass::Quota | FailClass::Timeout => true,
11277        FailClass::Other(_) => prev != Some(cur),
11278    }
11279}
11280
11281/// A short human reason for a failed outcome, for the handover record.
11282fn fail_reason(out: &AgentOutcome) -> String {
11283    match out {
11284        AgentOutcome::Ok(_) => String::new(),
11285        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11286        AgentOutcome::Dropped(o) => format!(
11287            "the CLI dropped the stream ({})",
11288            o.dropped
11289                .as_ref()
11290                .map(|d| d.why.as_str())
11291                .unwrap_or("it ended without delivering its answer")
11292        ),
11293        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11294            e.lines().next().unwrap_or("").chars().take(160).collect()
11295        }
11296    }
11297}
11298
11299/// Note one handover in the run: the structured record and, in the timeline,
11300/// the sentence a person reads. A quota keeps the wording it always had.
11301pub(crate) fn record_handover(
11302    state: &mut RunState,
11303    node: &str,
11304    seat: &str,
11305    from: &str,
11306    to: &str,
11307    class: &FailClass,
11308    reason: &str,
11309) {
11310    let message = if *class == FailClass::Quota {
11311        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11312    } else {
11313        format!("{seat}: handed over {from} -> {to} ({reason})")
11314    };
11315    state.event(node, message);
11316    state.handovers.push(Handover {
11317        at: Timestamp::now(),
11318        node: node.to_owned(),
11319        seat: seat.to_owned(),
11320        from: from.to_owned(),
11321        to: to.to_owned(),
11322        reason: reason.to_owned(),
11323    });
11324}
11325
11326/// Did this reply report running a command whose own CLI never confirmed an
11327/// exit status?
11328///
11329/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11330/// command *finished* (see that type's own doc), so this can only be `true`
11331/// for a command whose completion event carried no readable exit code — not
11332/// for one that simply is not mentioned at all. That is the one signal this
11333/// crate can read, from the same record `state.jobs` renders, about a reply
11334/// standing next to work its own CLI cannot vouch for finishing; it is
11335/// deliberately not a check on the exit code's *value* (a fixer legitimately
11336/// runs a command that fails mid-iteration before it succeeds) and not a
11337/// guess at a command still running in the background (which emits no event
11338/// at all, and so leaves no evidence here to find).
11339fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11340    commands.iter().any(|c| c.exit_code.is_none())
11341}
11342
11343/// The reason recorded for a candidate, and named in a handover, when an
11344/// implement seat ended its turn without starting the work and did so again
11345/// on its one retry. See [`Runner::retry_unstarted`].
11346const UNSTARTED_TWICE: &str = "the agent ended its turn without starting the work (no tool call, \
11347                               worktree unchanged), and again when asked once more";
11348
11349/// Did this turn end cleanly without the seat having started the work?
11350///
11351/// Every part is positive evidence, and a missing one means "no": a usable
11352/// reply; a CLI whose stream reports tool calls and reported none
11353/// (`tool_calls` is `None` for a backend that does not report them, which is
11354/// unknown, never zero); no command evidence; and a checkout whose `HEAD` is
11355/// the one recorded before the turn (`before`) with nothing uncommitted. A
11356/// dirty tree, a moved `HEAD` or an unreadable repository never authorizes a
11357/// retry: partial work is the other recoveries' business.
11358///
11359/// The comparison is with the seat's own starting point, not the run's base,
11360/// so a seat that left an inherited patch untouched is unstarted too.
11361fn ended_unstarted(
11362    out: &AgentOutput,
11363    before: Option<&str>,
11364    after: Option<&str>,
11365    clean: Option<bool>,
11366) -> bool {
11367    out.usable()
11368        && out.tool_calls == Some(0)
11369        && out.commands.is_empty()
11370        && before.is_some()
11371        && before == after
11372        && clean == Some(true)
11373}
11374
11375/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11376/// adoption guard.
11377#[derive(Debug, Clone, PartialEq, Eq)]
11378enum NoopClaimVerdict {
11379    /// Reply did not open with `NO CHANGE NEEDED:`.
11380    Absent,
11381    /// Structured evidence passed schema, CLI command, and repository checks.
11382    Accepted,
11383    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11384    /// concrete reason.
11385    Rejected(String),
11386}
11387
11388fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11389    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11390    cmd.description.trim() == check.method.trim()
11391}
11392
11393/// Checks cited by `requirements` plus the final check, deduplicated in order.
11394fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11395    let mut out = report.cited_checks();
11396    if let Some(last) = report.checks.last()
11397        && !out
11398            .iter()
11399            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11400    {
11401        out.push(last);
11402    }
11403    out
11404}
11405
11406/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11407/// when the backend reported commands. Empty `commands` is allowed because not
11408/// every backend emits structured command events.
11409fn check_command_evidence(
11410    report: &verdict::VerifiedNoopReport,
11411    commands: &[agent::CommandEvidence],
11412) -> std::result::Result<(), String> {
11413    if commands.is_empty() {
11414        return Ok(());
11415    }
11416    for check in checks_to_cross_verify(report) {
11417        let matching: Vec<&agent::CommandEvidence> = commands
11418            .iter()
11419            .filter(|cmd| command_matches_check(cmd, check))
11420            .collect();
11421        match check.kind {
11422            verdict::NoopEvidenceKind::Command
11423            | verdict::NoopEvidenceKind::Test
11424            | verdict::NoopEvidenceKind::Path => {
11425                let Some(last_cmd) = matching.last() else {
11426                    return Err(format!(
11427                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11428                         but no matching command was recorded by the CLI",
11429                        check.id.trim(),
11430                        check.kind,
11431                        check.target.trim()
11432                    ));
11433                };
11434                if last_cmd.exit_code != Some(0) {
11435                    return Err(format!(
11436                        "contradictory command evidence: check `{}` claims `{}` passed, \
11437                         but its last recorded CLI command (`{}`) exited with {}",
11438                        check.id.trim(),
11439                        check.target.trim(),
11440                        last_cmd.description.trim(),
11441                        crate::notices::exit_status(last_cmd.exit_code)
11442                    ));
11443                }
11444                if check.kind == verdict::NoopEvidenceKind::Test
11445                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11446                {
11447                    return Err(format!(
11448                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11449                         but its last recorded CLI output reports failure or no passing tests",
11450                        check.id.trim(),
11451                        check.target.trim()
11452                    ));
11453                }
11454            }
11455            verdict::NoopEvidenceKind::Commit => {
11456                if let Some(last_cmd) = matching.last()
11457                    && last_cmd.exit_code != Some(0)
11458                {
11459                    return Err(format!(
11460                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11461                         but its last recorded CLI command (`{}`) exited with {}",
11462                        check.id.trim(),
11463                        check.target.trim(),
11464                        last_cmd.description.trim(),
11465                        crate::notices::exit_status(last_cmd.exit_code)
11466                    ));
11467                }
11468            }
11469        }
11470    }
11471    Ok(())
11472}
11473
11474/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11475/// exit, confirmed commands, strict structured JSON validation, and
11476/// `CommandEvidence` consistency.
11477fn evaluate_noop_claim(
11478    usable: bool,
11479    commands: &[agent::CommandEvidence],
11480    text: &str,
11481) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11482    if !text
11483        .trim_start()
11484        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11485    {
11486        return Ok(None);
11487    }
11488    if !usable {
11489        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11490    }
11491    if has_unconfirmed_command(commands) {
11492        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11493    }
11494    let Some(parsed) = verdict::parse_verified_noop(text) else {
11495        return Ok(None);
11496    };
11497    let report = parsed?;
11498    check_command_evidence(&report, commands)?;
11499    Ok(Some(report))
11500}
11501
11502/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11503/// structured no-op report against the candidate's real Git history and
11504/// worktree. Existence alone never satisfies a requirement (the report still
11505/// had to carry concrete passing checks), while a missing commit/path or a
11506/// commit not on `base_commit` disqualifies the claim.
11507async fn verify_noop_repo_evidence(
11508    report: &verdict::VerifiedNoopReport,
11509    worktree: &Path,
11510    base_commit: &str,
11511) -> std::result::Result<(), String> {
11512    let wt_canon = std::fs::canonicalize(worktree).ok();
11513    for check in checks_to_cross_verify(report) {
11514        match check.kind {
11515            verdict::NoopEvidenceKind::Commit => {
11516                let target = check.target.trim();
11517                let Some(sha) = git::commit_of(worktree, target).await else {
11518                    return Err(format!(
11519                        "check `{}` cites commit `{target}`, which does not exist in git history",
11520                        check.id.trim()
11521                    ));
11522                };
11523                if !git::is_ancestor(worktree, &sha, base_commit).await {
11524                    return Err(format!(
11525                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11526                        check.id.trim(),
11527                        short(base_commit)
11528                    ));
11529                }
11530            }
11531            verdict::NoopEvidenceKind::Path => {
11532                let target = check.target.trim();
11533                let rel = verdict::strip_path_locator(target);
11534                let full = worktree.join(rel);
11535                if !full.exists() {
11536                    return Err(format!(
11537                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11538                        check.id.trim()
11539                    ));
11540                }
11541                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11542                    && !path_canon.starts_with(wt_canon)
11543                {
11544                    return Err(format!(
11545                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11546                        check.id.trim()
11547                    ));
11548                }
11549            }
11550            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11551        }
11552    }
11553    Ok(())
11554}
11555
11556/// Full adoption guard for an implementer reply, including real Git history and
11557/// worktree path verification.
11558async fn verified_noop_claim_in_worktree(
11559    usable: bool,
11560    commands: &[agent::CommandEvidence],
11561    text: &str,
11562    worktree: &Path,
11563    base_commit: &str,
11564) -> NoopClaimVerdict {
11565    let report = match evaluate_noop_claim(usable, commands, text) {
11566        Ok(Some(r)) => r,
11567        Ok(None) => return NoopClaimVerdict::Absent,
11568        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11569    };
11570    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11571        return NoopClaimVerdict::Rejected(reason);
11572    }
11573    NoopClaimVerdict::Accepted
11574}
11575
11576/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11577/// trusted as a verified no-op — the adoption guard's pure text-and-command
11578/// half (repository history/path verification runs in
11579/// [`verified_noop_claim_in_worktree`]).
11580///
11581/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11582/// timed out): a marker only earns the benefit of the doubt from a turn the
11583/// CLI itself vouches for finishing properly, the same house style
11584/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11585/// *fix* report to for `commands`. A candidate that timed out, exited
11586/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11587/// or failed structured validation returns `None`.
11588#[cfg(test)]
11589fn verified_noop_claim(
11590    usable: bool,
11591    commands: &[agent::CommandEvidence],
11592    text: &str,
11593) -> Option<String> {
11594    evaluate_noop_claim(usable, commands, text)
11595        .ok()
11596        .flatten()
11597        .map(|report| report.summary_text())
11598}
11599
11600fn short(commit: &str) -> String {
11601    commit.chars().take(7).collect()
11602}
11603
11604fn make_executable(path: &Path) -> Result<()> {
11605    #[cfg(unix)]
11606    {
11607        use std::os::unix::fs::PermissionsExt as _;
11608        let mut perms = std::fs::metadata(path)?.permissions();
11609        perms.set_mode(0o755);
11610        std::fs::set_permissions(path, perms)?;
11611    }
11612    #[cfg(not(unix))]
11613    {
11614        let _ = path;
11615    }
11616    Ok(())
11617}
11618
11619/// What every seat in one batch shares: where the answers are attributed, the
11620/// prompt overlay they inherit, and the build cache they are told to use.
11621///
11622/// A struct rather than four more parameters: `wave` also needs the run's
11623/// state (to record who is answering right now) and the attempt number, and
11624/// eight positional arguments is both unreadable and a clippy error.
11625struct WaveCtx<'a> {
11626    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11627    /// paid for it.
11628    run: &'a str,
11629    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11630    node: &'a str,
11631    prompts: &'a Prompts,
11632    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11633    cache: Option<&'a Path>,
11634    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11635    /// `JobRecord::round`. `None` for every other node.
11636    round: Option<usize>,
11637    /// Carry each seat's failed-agent history across waves (the review loop
11638    /// only): start-of-round priority and handover choice read
11639    /// [`RunState::seat_history`], and every answer or failure writes it.
11640    carry_seats: bool,
11641    /// The run's park / interrupt requests, so a wait for a shared resource
11642    /// can be abandoned the moment the operator asks to park.
11643    pauses: Option<(&'a Pause, &'a Pause)>,
11644}
11645
11646/// Shared scheduling policy for operations and spawned seat invocations.
11647fn repository_wait(
11648    state: &RunState,
11649    pauses: Option<(&Pause, &Pause)>,
11650) -> crate::repo_lock::WaitPolicy {
11651    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11652    let inherited = crate::repo_lock::WaitPolicy::current();
11653    crate::repo_lock::WaitPolicy::new(
11654        Duration::from_secs(state.config.graph.timeout_resource_wait),
11655        move || {
11656            inherited.cancelled()
11657                || pauses
11658                    .as_ref()
11659                    .is_some_and(|(a, b)| a.parked() || b.parked())
11660        },
11661    )
11662}
11663
11664fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11665    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11666        state.event("resource", timeout.0.description());
11667        state.resource_block = Some(timeout.0.clone());
11668        return;
11669    }
11670    if error.is::<crate::repo_lock::ResourceBlocked>() {
11671        state.resource_block = Some(crate::run::ResourceBlock {
11672            cause: crate::run::ResourceBlockCause::Other,
11673            node: "repository".into(),
11674            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11675                "disk admission"
11676            } else if error.to_string().contains("disk pressure") {
11677                "disk pressure"
11678            } else if error.to_string().contains("disk admission") {
11679                "disk admission"
11680            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11681                "incremental cache admission"
11682            } else {
11683                "repository coordination"
11684            }
11685            .into(),
11686            detail: format!("{error:#}"),
11687            at: Timestamp::now(),
11688        });
11689        state.event("resource", error.to_string());
11690    }
11691}
11692
11693async fn coordinate_operation(
11694    state: &mut RunState,
11695    cwd: &Path,
11696    wait: &crate::repo_lock::WaitPolicy,
11697) -> Result<Option<crate::repo_lock::SeatLease>> {
11698    let result =
11699        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11700            .await;
11701    if let Err(e) = &result {
11702        record_repository_block(state, e);
11703    }
11704    result
11705}
11706
11707/// Run one job, honouring the parallelism budget.
11708async fn run_one(
11709    job: SeatJob,
11710    sem: Arc<Semaphore>,
11711    ctx: &WaveCtx<'_>,
11712    state: &mut RunState,
11713    attempt: usize,
11714) -> (SeatState, AgentOutcome) {
11715    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11716        .await
11717        .pop()
11718        .expect("one job in, one result out");
11719    (seat, out)
11720}
11721
11722/// Run every job concurrently, capped by the semaphore, preserving order.
11723///
11724/// Every seat in the batch is recorded into [`RunState::active`] before the
11725/// wave starts and cleared as each answer lands, so the run's own record says
11726/// who is still being waited on rather than only who finished.
11727async fn wave(
11728    jobs: Vec<SeatJob>,
11729    sem: Arc<Semaphore>,
11730    ctx: &WaveCtx<'_>,
11731    state: &mut RunState,
11732    attempt: usize,
11733) -> Vec<(usize, SeatState, AgentOutcome)> {
11734    let WaveCtx {
11735        run,
11736        node,
11737        prompts,
11738        cache,
11739        round,
11740        carry_seats: _,
11741        pauses,
11742    } = *ctx;
11743    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11744    for job in &jobs {
11745        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11746    }
11747    if let Err(e) = state.save() {
11748        // A failed persist of "who is answering right now" must not abort the
11749        // wave: the seats are already being asked, and the alternative is
11750        // losing the answers to save a status line nobody may even be
11751        // watching.
11752        tracing::warn!("could not persist in-progress seats: {e:#}");
11753    }
11754    // Shared-mode waves keep their existing single lease. Isolated writers
11755    // acquire their own checkout's target at seat admission.
11756    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11757    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11758    // never borrowed from a job's agent budget (and never charged to it either,
11759    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11760    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11761    let cache_guard = if let Some(cache_dir) = cache {
11762        if jobs_had_a_writer {
11763            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11764            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11765            match acquire_cache_lease(
11766                state,
11767                cache_dir,
11768                &owner,
11769                resource_limit,
11770                node,
11771                node,
11772                &cancel,
11773            )
11774            .await
11775            {
11776                Ok(Some(g)) => Some(g),
11777                // Parking: leave without spawning anything. The run parks at
11778                // the next boundary and the seats are asked afresh on resume.
11779                Ok(None) => {
11780                    if let Some(block) = &mut state.resource_block {
11781                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11782                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11783                        };
11784                    }
11785                    return block_wave(
11786                        jobs,
11787                        state,
11788                        node,
11789                        attempt,
11790                        "parked while waiting for the shared build cache",
11791                    );
11792                }
11793                // An unreadable lease is not contention: keep the old
11794                // fallback (no shared cache for this wave's seats).
11795                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11796                Err(e) => {
11797                    // Writing seats may not build into a cache this run does
11798                    // not hold, and an agent that cannot be given one is not
11799                    // asked at all: the run stops resumably instead.
11800                    let why = format!("{e:#}");
11801                    state.event(
11802                        "resource",
11803                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11804                    );
11805                    return block_wave(jobs, state, node, attempt, &why);
11806                }
11807            }
11808        } else {
11809            None
11810        }
11811    } else {
11812        None
11813    };
11814    // Every job keeps its whole budget: the wait above was not the agent's.
11815    // Restart the seats' clocks so "started" means "being spawned now".
11816    state.seats_spawning(node, attempt);
11817    if let Err(e) = state.save() {
11818        tracing::warn!("could not persist the start of a wave: {e:#}");
11819    }
11820    // Queueing behind this wave's own seats for a parallelism slot is normal
11821    // (each of them is bounded by its own agent timeout); only a wait beyond
11822    // all of them plus the resource limit means the slots never came back.
11823    let slot_limit = resource_limit
11824        + jobs
11825            .iter()
11826            .map(|j| j.timeout)
11827            .max()
11828            .unwrap_or_default()
11829            .saturating_mul(jobs.len() as u32);
11830    let mut set = tokio::task::JoinSet::new();
11831    // Seats announce themselves here the moment they hold a parallelism
11832    // permit, i.e. just before their CLI is spawned.
11833    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11834    let overlay = prompts.overlay(node);
11835    let repository_wait = repository_wait(state, pauses);
11836    for (i, mut job) in jobs.into_iter().enumerate() {
11837        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11838        if cache.is_some() {
11839            job.prompt.push('\n');
11840            job.prompt
11841                .push_str(&prompt::build_cache_note(node, job.allow_write));
11842        }
11843        let sem = Arc::clone(&sem);
11844        let run = run.to_owned();
11845        let node = node.to_owned();
11846        // Only implementers were told about the task's attachments, so only
11847        // their seats get the directory widened for reading.
11848        let attachments = if node == "implement" {
11849            state.attachments.clone()
11850        } else {
11851            Vec::new()
11852        };
11853        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11854        // `prompt::build_cache_note`'s doc for why setting it anyway is
11855        // exactly how a sandboxed reviewer's write refusal got reported as a
11856        // defect in the patch, not a property of its own seat. And a
11857        // write-allowed one is handed it only when the lease above was
11858        // actually acquired: a wave that could not get it (`cache_guard` is
11859        // `None`, see its own comment) must not send seats to build into a
11860        // directory this run does not hold - that is the exact concurrent,
11861        // unmanaged-write race this module exists to prevent, not something
11862        // "proceeding anyway" is allowed to reintroduce.
11863        let cache = cache
11864            .filter(|_| job.allow_write && cache_guard.is_some())
11865            .map(Path::to_path_buf);
11866        let spawned_tx = spawned_tx.clone();
11867        let repository_wait = repository_wait.clone();
11868        let coordination = state.config.coordination.clone();
11869        let fetched_base = state.fetched_base.clone();
11870        set.spawn(async move {
11871            // A wait for a parallelism slot is scheduling, not the agent: it
11872            // is bounded by its own limit and ends as a resource block, never
11873            // as a timeout of the agent that was not started.
11874            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11875                Ok(p) => p,
11876                Err(_) => {
11877                    return (
11878                        i,
11879                        job.seat,
11880                        AgentOutcome::ResourceBlocked(format!(
11881                            "no parallel slot became free within {}s",
11882                            slot_limit.as_secs()
11883                        )),
11884                        None,
11885                        false,
11886                    );
11887                }
11888            };
11889            spawned_tx.send(job.seat.key.clone()).ok();
11890            let mut seat = job.seat;
11891            let out = repository_wait
11892                .scope(agent::invoke(
11893                    &job.spec,
11894                    &mut seat,
11895                    &Invocation {
11896                        coordination: coordination.as_ref(),
11897                        fetched_base: fetched_base.as_ref(),
11898                        cwd: &job.cwd,
11899                        prompt: &job.prompt,
11900                        timeout: job.timeout,
11901                        allow_write: job.allow_write,
11902                        sessions: job.sessions,
11903                        artifacts: &job.artifacts,
11904                        stem: &job.stem,
11905                        run: &run,
11906                        node: &node,
11907                        cache_dir: cache.as_deref(),
11908                        attachments: &attachments,
11909                        writable: &[],
11910                    },
11911                ))
11912                .await;
11913            let cache_block = out
11914                .as_ref()
11915                .err()
11916                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11917                .map(|timeout| timeout.0.clone());
11918            let interrupted = out
11919                .as_ref()
11920                .err()
11921                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11922            let out = match out {
11923                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11924                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11925                // Billed work the CLI failed to hand over is not an ordinary
11926                // failure, but its text is the CLI's raw error JSON, not an
11927                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11928                // read it as one by forgetting to check. `usable()` is always
11929                // false here (dropped implies an empty response), so this has
11930                // to be checked before the catch-all `Failed` below or the
11931                // one shape this exists for is lost with the rest.
11932                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11933                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11934                Ok(o) => AgentOutcome::Failed(format!(
11935                    "process exited with no usable output ({})",
11936                    crate::notices::exit_status(o.exit_code)
11937                )),
11938                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11939                    AgentOutcome::ResourceBlocked(e.to_string())
11940                }
11941                Err(e) => AgentOutcome::Failed(e.to_string()),
11942            };
11943            (i, seat, out, cache_block, interrupted)
11944        });
11945    }
11946    drop(spawned_tx);
11947    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11948    loop {
11949        let joined = tokio::select! {
11950            Some(key) = spawned_rx.recv() => {
11951                // The clock of this seat starts now, not when it queued.
11952                state.seat_spawned(&key);
11953                if let Err(e) = state.save() {
11954                    tracing::warn!("could not persist a seat's start: {e:#}");
11955                }
11956                continue;
11957            }
11958            joined = set.join_next() => joined,
11959        };
11960        let Some(joined) = joined else {
11961            break;
11962        };
11963        let (i, seat, out, cache_block, interrupted) = match joined {
11964            Ok(v) => v,
11965            // No seat to clear: a panicked task never reported which one it
11966            // was. The defensive sweep below this loop is what stops that
11967            // seat's `active` entry from surviving forever.
11968            Err(e) => {
11969                tracing::error!("agent task panicked: {e}");
11970                continue;
11971            }
11972        };
11973        state.seat_finished(&seat.key);
11974        if interrupted
11975            && node == "implement"
11976            && let Some(label) = state
11977                .candidates
11978                .iter()
11979                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11980                .map(|candidate| candidate.label)
11981        {
11982            state.candidate_preservation.insert(
11983                label,
11984                "interrupted implementation awaiting persistence".into(),
11985            );
11986            state.interrupted_implementations.insert(label);
11987        }
11988        if let Some(block) = cache_block
11989            && state.resource_block.is_none()
11990        {
11991            state.event("resource", block.description());
11992            state.resource_block = Some(block);
11993        }
11994        if let AgentOutcome::ResourceBlocked(why) = &out
11995            && state.resource_block.is_none()
11996        {
11997            state.resource_block = Some(crate::run::ResourceBlock {
11998                cause: crate::run::ResourceBlockCause::Other,
11999                node: node.to_owned(),
12000                kind: if why.contains("disk pressure") {
12001                    "disk pressure"
12002                } else if why.contains("disk admission") {
12003                    "disk admission"
12004                } else if why.contains(crate::incremental::BLOCKED) {
12005                    "incremental cache admission"
12006                } else if why.contains(crate::build_target::KIND) {
12007                    crate::build_target::KIND
12008                } else if why.contains("repository coordination") {
12009                    "repository coordination"
12010                } else {
12011                    "parallel slot"
12012                }
12013                .to_owned(),
12014                detail: why.clone(),
12015                at: Timestamp::now(),
12016            });
12017            let activity = if interrupted {
12018                "agent execution interrupted"
12019            } else {
12020                "no agent was started"
12021            };
12022            state.event("resource", format!("{node}: {activity} - {why}"));
12023        }
12024        record_jobs(state, node, round, &seat.key, &out);
12025        if let Err(e) = state.save() {
12026            tracing::warn!("could not persist a seat's completion: {e:#}");
12027        }
12028        if collected.len() <= i {
12029            collected.resize_with(i + 1, || None);
12030        }
12031        collected[i] = Some((i, seat, out));
12032    }
12033    // Belt-and-braces for the panic branch above: every seat this exact batch
12034    // started shares this `(node, attempt)` pair, and every seat that finished
12035    // normally already cleared itself, so anything left tagged with it here
12036    // can only be a panicked task's leftover. Cleared unconditionally rather
12037    // than left to read as still answering forever.
12038    if state
12039        .active
12040        .values()
12041        .any(|a| a.node == node && a.attempt == attempt)
12042    {
12043        state
12044            .active
12045            .retain(|_, a| !(a.node == node && a.attempt == attempt));
12046        if let Err(e) = state.save() {
12047            tracing::warn!("could not persist the end of a wave: {e:#}");
12048        }
12049    }
12050    // Whether or not the lease above was actually held, several worktrees
12051    // may just have built into the cache with nothing here able to name one
12052    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
12053    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
12054    // clean it might not have strictly needed; trusting a stale match would
12055    // cost it a wrong answer.
12056    if let Some(cache_dir) = cache
12057        && jobs_had_a_writer
12058    {
12059        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
12060    }
12061    if let Some(guard) = cache_guard {
12062        guard.release();
12063    }
12064    collected.into_iter().flatten().collect()
12065}
12066
12067/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
12068/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
12069/// this is data collection, not the fix-specific completion contract in
12070/// [`Runner::continue_fix_report`], and applies regardless of which node
12071/// asked.
12072///
12073/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
12074/// evidence from; `Failed` does not, and correctly contributes nothing — a
12075/// timeout or crash is not itself evidence about a command the seat may have
12076/// started.
12077fn record_jobs(
12078    state: &mut RunState,
12079    node: &str,
12080    round: Option<usize>,
12081    seat: &str,
12082    out: &AgentOutcome,
12083) {
12084    let commands: &[agent::CommandEvidence] = match out {
12085        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
12086        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
12087    };
12088    let checked_at = Timestamp::now();
12089    for c in commands {
12090        state.jobs.push(JobRecord {
12091            node: node.to_owned(),
12092            round,
12093            seat: seat.to_owned(),
12094            id: c.id.clone(),
12095            description: c.description.clone(),
12096            checked_at,
12097            status: match c.exit_code {
12098                Some(0) => JobStatus::Completed,
12099                Some(_) => JobStatus::Failed,
12100                None => JobStatus::Unknown,
12101            },
12102            exit_code: c.exit_code,
12103            result_summary: c.result_summary.clone(),
12104            source: c.source.clone(),
12105        });
12106    }
12107}
12108
12109/// Is a review round clean, given how many reviewer seats answered against
12110/// how many the round expected?
12111///
12112/// A seat that never answered (timeout, crash, unparsable output) is not a
12113/// seat that read the patch and found nothing — treating it as such is
12114/// exactly the bug this function exists to close. Under the default `block`
12115/// policy a missing seat can never be clean; `warn` still requires the seats
12116/// that *did* answer to have found nothing blocking and verification to be
12117/// green.
12118///
12119/// `quota_missing` narrows that `block` default for exactly one cause of
12120/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
12121/// a session limit lifts by the very next round buys nothing — the seat is
12122/// asked again with the same quota — so once every missing seat is accounted
12123/// for by a quota loss (and at least one seat *did* answer, so a decision has
12124/// something to rest on) the round is decided on the panel that could answer,
12125/// same as `warn` would. A panel that lost every seat to quota is not
12126/// decided here: `answered == 0` falls through to the existing `block`
12127/// fallback so a fully collapsed panel still waits rather than landing on no
12128/// review at all.
12129fn round_is_clean(
12130    blocking: usize,
12131    e2e_ok: bool,
12132    answered: usize,
12133    expected: usize,
12134    quota_missing: usize,
12135    policy: IncompleteReviewPolicy,
12136) -> bool {
12137    if blocking != 0 || !e2e_ok {
12138        return false;
12139    }
12140    if answered == expected || policy == IncompleteReviewPolicy::Warn {
12141        return true;
12142    }
12143    answered > 0 && expected - answered <= quota_missing
12144}
12145
12146/// The review loop's own conclusion, derived entirely from its persisted
12147/// round records and the round budget that produced them — never from
12148/// `status`, so a reentry (or `gate`/`merge` reading it independently)
12149/// recomputes the identical answer regardless of what an earlier node in the
12150/// same walk, or a previous walk, did to `status`.
12151///
12152/// `None` while more rounds remain to try, including when review never ran
12153/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
12154/// gone clean, or the budget is spent, or the tree has stopped moving (see
12155/// [`STAGNANT_LIMIT`]), the answer is one of two things:
12156///
12157/// - An incomplete panel that raised nothing is missing input, not a
12158///   verified tree — never a hand-off candidate, whatever verification said
12159///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
12160/// - Otherwise, green e2e on the last round hands off (see
12161///   [`Runner::stop_reviewing`]); red e2e blocks.
12162///
12163/// A last round whose own verification is still `ResourceBlocked` — magi
12164/// itself never got a command to run, not evidence the patch is broken —
12165/// is neither: this returns `None` for it too, the same as "more rounds
12166/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
12167/// handling of that shape) instead of this cheap recomputation guessing a
12168/// verdict a real attempt never produced.
12169pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
12170    if max_rounds == 0
12171        || reviews.last().is_some_and(|r| {
12172            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
12173        })
12174    {
12175        return Some(RunStatus::Gating);
12176    }
12177    let last = reviews.last()?;
12178    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
12179    if reviews.len() < max_rounds && !stagnant {
12180        return None;
12181    }
12182    if last.incomplete() && last.blocking == 0 {
12183        return Some(RunStatus::Blocked);
12184    }
12185    if last.e2e_status() == E2eStatus::ResourceBlocked
12186        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
12187    {
12188        return None;
12189    }
12190    Some(if last.e2e.iter().all(CommandOutcome::ok) {
12191        RunStatus::Gating
12192    } else {
12193        RunStatus::Blocked
12194    })
12195}
12196
12197/// How long a re-ask may take, given the budget the first attempt had.
12198///
12199/// A `nudged` retry is a request to restate an answer the seat has already
12200/// worked out: it carries no new work, so it does not deserve the original
12201/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
12202/// 133 seconds while a third sat for over ten minutes on a resumed session
12203/// holding 410 KB of prior output - and because the retry had inherited the
12204/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
12205/// judging round whose other seats were long finished.
12206///
12207/// A quarter of the budget, with a floor so that a deliberately short timeout
12208/// does not collapse to nothing. A retry that re-sends the whole prompt
12209/// (because the seat kept no context) is the original job again, and keeps the
12210/// original budget.
12211pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
12212    if nudged {
12213        (full / 4).max(Duration::from_secs(120)).min(full)
12214    } else {
12215        full
12216    }
12217}
12218
12219/// Run a wave and parse each reply, re-asking the seats whose reply was
12220/// unusable.
12221///
12222/// The re-ask is a nudge rather than the whole prompt again when the seat still
12223/// holds its conversation, which is the difference between a cheap retry and
12224/// paying for the entire candidate set twice.
12225///
12226/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
12227/// successor in `roster` is handed to it instead of being re-asked: the
12228/// handover is the retry. A seat with no successor left (a single-agent
12229/// roster, the roster's tail) is nudged as before, up to `retries` times. So
12230/// the asks to one seat in one node number at most
12231/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
12232/// is asked once (a dropped stream is nudged first), and only the last agent
12233/// of the chain gets the `retries` same-agent nudges. Each roster agent is
12234/// tried at most once per seat, walking forward from the seat's own position and never wrapping
12235/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
12236/// other failure stops the chain when the previous agent failed the same way
12237/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
12238/// [`has_context`] is false and the job's own full prompt and full budget are
12239/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
12240/// intermediate ones are not losses) and is returned as a failure like any
12241/// other absent seat — the caller decides whether the panel still has a
12242/// quorum. An empty `roster` disables handover: failures are nudged as they
12243/// always were, and a quota is simply lost. A reply that fails to parse or
12244/// validate is the prompt's doing and is only ever nudged, never handed over.
12245///
12246/// The returned [`SeatState`] names the agent that answered (or tried last).
12247#[allow(clippy::too_many_arguments)]
12248async fn ask_json_wave<T>(
12249    jobs: Vec<SeatJob>,
12250    sem: Arc<Semaphore>,
12251    retries: usize,
12252    roster: &[AgentSpec],
12253    ctx: &WaveCtx<'_>,
12254    losses: &mut Vec<QuotaLoss>,
12255    state: &mut RunState,
12256    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12257) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12258where
12259    T: serde::de::DeserializeOwned + Send + 'static,
12260{
12261    ask_wave_with(
12262        jobs,
12263        sem,
12264        retries,
12265        roster,
12266        ctx,
12267        losses,
12268        state,
12269        &|text: &str| {
12270            let v = verdict::extract_json::<T>(text)?;
12271            validate(&v)?;
12272            Ok(v)
12273        },
12274    )
12275    .await
12276}
12277
12278/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12279/// a node whose answer is prose (deliberation) shares the same handover,
12280/// failure classification, quota bookkeeping and bounds instead of a copy.
12281///
12282/// A seat handed to another roster agent is sent the job's `handover` prompt
12283/// (when it has one) rather than `prompt`: the new agent has no session, so a
12284/// resume-style prompt would be incomplete. That holds for the handover ask
12285/// and for every nudge to that agent whose `has_context` is false.
12286#[allow(clippy::too_many_arguments)]
12287async fn ask_wave_with<T>(
12288    jobs: Vec<SeatJob>,
12289    sem: Arc<Semaphore>,
12290    retries: usize,
12291    roster: &[AgentSpec],
12292    ctx: &WaveCtx<'_>,
12293    losses: &mut Vec<QuotaLoss>,
12294    state: &mut RunState,
12295    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12296) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12297where
12298    T: Send + 'static,
12299{
12300    let n = jobs.len();
12301    let originals: Vec<SeatJob> = jobs;
12302    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12303    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12304    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12305    // answer, N once it has gone through N nudges. Read back once this
12306    // returns, so a caller building a history record (`ReviewRecord`) can
12307    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12308    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12309    // field's own doc.
12310    let mut nudges: Vec<usize> = vec![0; n];
12311    // The agent now occupying each seat, the ids it has already been through,
12312    // where in the roster the walk began, the class of the last failure, and
12313    // the stem word of a handover not yet asked (full prompt, full budget).
12314    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12315    let mut tried: Vec<BTreeSet<String>> = specs
12316        .iter()
12317        .map(|s| BTreeSet::from([s.id.clone()]))
12318        .collect();
12319    let starts: Vec<usize> = specs
12320        .iter()
12321        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12322        .collect();
12323    let carry = ctx.carry_seats && !roster.is_empty();
12324    // Carried across rounds: ids that failed the seat earlier, and how the
12325    // last failure went (so a repeat of it is not handed over again).
12326    let carried: Vec<BTreeSet<String>> = originals
12327        .iter()
12328        .map(|j| {
12329            state
12330                .seat_history
12331                .get(&j.seat.key)
12332                .filter(|_| carry)
12333                .map(|h| h.failed.clone())
12334                .unwrap_or_default()
12335        })
12336        .collect();
12337    let mut prev: Vec<Option<FailClass>> = originals
12338        .iter()
12339        .map(|j| {
12340            state
12341                .seat_history
12342                .get(&j.seat.key)
12343                .filter(|_| carry)
12344                .and_then(|h| h.last_fail.clone())
12345        })
12346        .collect();
12347    let next_agent =
12348        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12349            let others: BTreeSet<String> = specs
12350                .iter()
12351                .enumerate()
12352                .filter(|(j, _)| *j != i)
12353                .map(|(_, s)| s.id.clone())
12354                .collect();
12355            pick_successor(
12356                roster,
12357                starts[i],
12358                tried,
12359                carry.then(|| &carried[i]),
12360                &others,
12361            )
12362            .cloned()
12363        };
12364    let mut fresh: Vec<Option<String>> = vec![None; n];
12365    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12366    let mut pending: Vec<usize> = (0..n).collect();
12367
12368    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12369    // asks: an agent with a successor is asked once and handed over, and only
12370    // a seat with no successor spends `retries` nudges on the same agent. This
12371    // only guarantees the loop's own termination whatever those say.
12372    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12373    for round in 0..max_rounds {
12374        if pending.is_empty() {
12375            break;
12376        }
12377        let mut batch = Vec::with_capacity(pending.len());
12378        let mut renudged: Vec<&str> = Vec::new();
12379        for &i in &pending {
12380            let src = &originals[i];
12381            // A seat now held by another agent than the job named has no
12382            // session of its own: it gets the full-context prompt whenever
12383            // it is asked in full (the handover ask, a nudge it cannot
12384            // resume).
12385            let full: &str = match &src.handover {
12386                Some(h) if specs[i].id != src.spec.id => h,
12387                _ => &src.prompt,
12388            };
12389            // The prompt and the budget are one decision: a nudge restates
12390            // finished work, a re-sent prompt redoes it.
12391            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12392                (
12393                    full.to_owned(),
12394                    src.timeout,
12395                    format!("{}-{word}-{}", src.stem, specs[i].id),
12396                )
12397            } else if nudges[i] == 0 {
12398                (full.to_owned(), src.timeout, src.stem.clone())
12399            } else {
12400                renudged.push(src.seat.key.as_str());
12401                let why = done[i]
12402                    .as_ref()
12403                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12404                    .unwrap_or_else(|| "no parsable answer".to_owned());
12405                let nudge = prompt::nudge(&why);
12406                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12407                let prompt = if nudged {
12408                    nudge
12409                } else {
12410                    format!("{full}\n\n---\n\n{nudge}")
12411                };
12412                (
12413                    prompt,
12414                    retry_budget(src.timeout, nudged),
12415                    format!("{}-retry{}", src.stem, nudges[i]),
12416                )
12417            };
12418            batch.push(SeatJob {
12419                spec: specs[i].clone(),
12420                seat: seats[i].clone(),
12421                cwd: src.cwd.clone(),
12422                prompt,
12423                timeout,
12424                allow_write: src.allow_write,
12425                sessions: src.sessions,
12426                artifacts: src.artifacts.clone(),
12427                stem,
12428                handover: None,
12429            });
12430        }
12431
12432        if !renudged.is_empty() {
12433            state.event(
12434                ctx.node,
12435                format!("retry {round}: re-asking {}", renudged.join(", ")),
12436            );
12437        }
12438        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12439        let mut still = Vec::new();
12440        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12441            seats[i] = seat;
12442            // No agent was asked: nothing to hand over, nudge, remember or
12443            // charge. The caller sees `resource_block` and stops the node.
12444            if let AgentOutcome::ResourceBlocked(why) = &out {
12445                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12446                continue;
12447            }
12448            let class = FailClass::of(&out);
12449            // A dropped stream is nudged first (the conversation is still
12450            // there to pick up); only a seat whose nudges are spent hands over.
12451            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12452                && nudges[i] < retries
12453                && !roster.is_empty();
12454            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12455                let next = should_hand_over(prev[i].as_ref(), &cur)
12456                    .then(|| next_agent(i, &tried[i], &specs))
12457                    .flatten();
12458                if carry {
12459                    let h = state
12460                        .seat_history
12461                        .entry(originals[i].seat.key.clone())
12462                        .or_default();
12463                    h.failed.insert(specs[i].id.clone());
12464                    h.last_fail = Some(cur.clone());
12465                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12466                        h.last_ok = None;
12467                    }
12468                    // Saved before the next agent is asked, so a restart in
12469                    // between does not forget who failed.
12470                    if let Err(e) = state.save() {
12471                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12472                    }
12473                }
12474                if let Some(next) = next {
12475                    record_handover(
12476                        state,
12477                        ctx.node,
12478                        &originals[i].seat.key,
12479                        &specs[i].id,
12480                        &next.id,
12481                        &cur,
12482                        &fail_reason(&out),
12483                    );
12484                    tried[i].insert(next.id.clone());
12485                    prev[i] = Some(cur.clone());
12486                    seats[i] =
12487                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12488                    specs[i] = next;
12489                    fresh[i] = Some(cur.stem_word().to_owned());
12490                    nudges[i] = 0;
12491                    done[i] = Some(Err(anyhow::anyhow!(
12492                        "handed over after: {}",
12493                        fail_reason(&out)
12494                    )));
12495                    still.push(i);
12496                    continue;
12497                }
12498            }
12499            if carry
12500                && !nudge_first
12501                && let Some(cur) = class.clone()
12502            {
12503                // The chain ended here (no successor, or a repeated failure).
12504                let h = state
12505                    .seat_history
12506                    .entry(originals[i].seat.key.clone())
12507                    .or_default();
12508                h.failed.insert(specs[i].id.clone());
12509                h.last_fail = Some(cur);
12510            }
12511            let parsed = match out {
12512                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12513                AgentOutcome::Quota(o) => {
12514                    last_quota[i] = o.quota.clone();
12515                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12516                }
12517                // Not a parseable answer: the nudge loop re-asks it, which is
12518                // exactly what a dropped stream needs. Just don't hand its raw
12519                // error JSON to `extract_json`.
12520                AgentOutcome::Dropped(o) => {
12521                    let why = o
12522                        .dropped
12523                        .as_ref()
12524                        .map(|d| d.why.as_str())
12525                        .unwrap_or("the CLI ended the stream without delivering its answer");
12526                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12527                }
12528                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12529                    Err(anyhow::anyhow!(e))
12530                }
12531            };
12532            let quota = class == Some(FailClass::Quota);
12533            let failed = parsed.is_err();
12534            if !failed && matches!(ctx.node, "judge" | "vote") {
12535                // A validated answer restores this seat's quorum presence,
12536                // including on the normal path after an all-seat block.
12537                state
12538                    .quota
12539                    .retain(|loss| loss.seat != originals[i].seat.key);
12540            }
12541            done[i] = Some(parsed);
12542            if carry && !failed {
12543                let h = state
12544                    .seat_history
12545                    .entry(originals[i].seat.key.clone())
12546                    .or_default();
12547                h.failed.remove(&specs[i].id);
12548                h.last_ok = Some(specs[i].id.clone());
12549                h.last_fail = None;
12550            }
12551            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12552            // fail the same way; and never re-ask a seat that already parsed.
12553            // A failed agent that still has a successor is not re-asked
12554            // either: the handover was its remedy and has just been refused
12555            // (the chain stops on a repeated failure class). A seat with no
12556            // successor left (a single-agent roster, the roster's tail, or an
12557            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12558            let agent_failure = class.is_some()
12559                && !nudge_first
12560                && !roster.is_empty()
12561                && next_agent(i, &tried[i], &specs).is_some();
12562            if failed && !quota && !agent_failure && nudges[i] < retries {
12563                nudges[i] += 1;
12564                still.push(i);
12565            }
12566        }
12567        pending = still;
12568    }
12569
12570    // One loss per seat whose chain ended on a quota: the intermediate ones
12571    // were absorbed by a handover and are not losses.
12572    for (i, q) in last_quota.into_iter().enumerate() {
12573        if let Some(quota) = q {
12574            losses.push(QuotaLoss::from_report(
12575                originals[i].seat.key.clone(),
12576                ctx.node,
12577                Some(&quota),
12578            ));
12579        }
12580    }
12581
12582    // A stalled quorum already has its own recovery checkpoint. Refresh
12583    // its missing seats before deciding whether it can resume.
12584    if state.status != RunStatus::Stalled
12585        && ctx.node != "deliberate"
12586        && n > 0
12587        && losses.len() == n
12588        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12589    {
12590        block_machine_outage(state, ctx.node, losses);
12591        state.quota.append(losses);
12592    }
12593
12594    seats
12595        .into_iter()
12596        .zip(done)
12597        .zip(nudges)
12598        .map(|((seat, res), attempts)| {
12599            (
12600                seat,
12601                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12602                attempts,
12603            )
12604        })
12605        .collect()
12606}
12607
12608/// A node with no available agent has no task verdict. Preserve the node
12609/// checkpoint and record why a subsequent explicit resume is needed.
12610pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12611    let mut auth: Vec<_> = losses
12612        .iter()
12613        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12614        .map(|loss| loss.agent.clone())
12615        .collect();
12616    auth.sort();
12617    auth.dedup();
12618    let (kind, detail) = if auth.is_empty() {
12619        (
12620            "agent usage limit",
12621            "All seats reached their agent usage limits; resume after usage is available"
12622                .to_owned(),
12623        )
12624    } else {
12625        (
12626            "agent authentication",
12627            format!(
12628                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12629                auth.join(", ")
12630            ),
12631        )
12632    };
12633    state.resource_block = Some(crate::run::ResourceBlock {
12634        node: node.to_owned(),
12635        kind: kind.to_owned(),
12636        cause: crate::run::ResourceBlockCause::Other,
12637        detail: detail.clone(),
12638        at: Timestamp::now(),
12639    });
12640    state.event(node, detail);
12641}
12642
12643/// Did the wave end without asking any agent (see [`block_wave`])?
12644fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12645    results
12646        .iter()
12647        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12648}
12649
12650/// Settle a wave that never spawned anything: every job answers
12651/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12652/// else about the seat (session, history, quota) is touched.
12653fn block_wave(
12654    jobs: Vec<SeatJob>,
12655    state: &mut RunState,
12656    node: &str,
12657    attempt: usize,
12658    why: &str,
12659) -> Vec<(usize, SeatState, AgentOutcome)> {
12660    state.resource_wait = None;
12661    state
12662        .active
12663        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12664    if let Err(e) = state.save() {
12665        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12666    }
12667    jobs.into_iter()
12668        .enumerate()
12669        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12670        .collect()
12671}
12672
12673/// Acquire the shared build cache's lease, waiting out contention within
12674/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12675/// unbounded wait is never acceptable).
12676///
12677/// A first, non-blocking check happens before ever waiting; if it finds the
12678/// lease busy, that fact is logged as a `verify` event *and* flushed with
12679/// [`RunState::save`] immediately — not only once the wait finally succeeds
12680/// or gives up — so a `magi show` run by a different process while this one
12681/// is still waiting reads a `run.json` that says so, rather than whatever it
12682/// looked like before the wait started. The same applies to the terminal
12683/// failure: logged and saved before this returns `Err`, so a caller that
12684/// could not get the lease at all still leaves a legible record of why.
12685async fn acquire_cache_lease(
12686    state: &mut RunState,
12687    cache_dir: &Path,
12688    owner: &crate::cache::Owner,
12689    budget: Duration,
12690    node: &str,
12691    context: &str,
12692    cancel: &(dyn Fn() -> bool + Sync),
12693) -> Result<Option<crate::cache::Guard>> {
12694    let home = crate::run::home();
12695    let kind = if crate::build_target::isolated(&state.config) {
12696        crate::build_target::KIND
12697    } else {
12698        "shared build cache"
12699    };
12700    let started = Instant::now();
12701    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12702        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12703        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12704        Err(e) => {
12705            state.event(
12706                "verify",
12707                format!(
12708                    "{context}: could not check the {kind} at {}: {e:#}",
12709                    cache_dir.display()
12710                ),
12711            );
12712            if let Err(e2) = state.save() {
12713                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12714            }
12715            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12716        }
12717    };
12718    state.event(
12719        "verify",
12720        format!(
12721            "{context}: waiting for the {kind} at {} ({})",
12722            cache_dir.display(),
12723            busy.describe()
12724        ),
12725    );
12726    // Seats of this node are waiting, not running: say so, so the countdown a
12727    // reader sees only ever measures an agent that has been spawned.
12728    state.resource_wait = Some(crate::run::ResourceWait {
12729        node: context.to_owned(),
12730        kind: kind.to_owned(),
12731        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12732        since: Timestamp::now(),
12733        limit_secs: budget.as_secs(),
12734    });
12735    if let Err(e) = state.save() {
12736        tracing::warn!("could not persist a cache wait: {e:#}");
12737    }
12738    let remaining = budget.saturating_sub(started.elapsed());
12739    let waited = crate::cache::wait_for_unless(
12740        &home,
12741        cache_dir,
12742        owner,
12743        remaining,
12744        Duration::from_secs(5),
12745        cancel,
12746    )
12747    .await;
12748    state.resource_wait = None;
12749    let cause = match &waited {
12750        Ok(Some(_)) => None,
12751        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12752        Err(error)
12753            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12754        {
12755            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12756                target: cache_dir.to_owned(),
12757                waited_secs: started.elapsed().as_secs(),
12758                limit_secs: budget.as_secs(),
12759            })
12760        }
12761        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12762            Some(crate::run::ResourceBlockCause::Timeout {
12763                waited_secs: started.elapsed().as_secs(),
12764                limit_secs: budget.as_secs(),
12765            })
12766        }
12767        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12768    };
12769    if let Some(cause) = cause {
12770        let detail = match &waited {
12771            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12772            Err(error) => format!("{error:#}"),
12773        };
12774        state.resource_block = Some(crate::run::ResourceBlock {
12775            cause,
12776            node: node.to_owned(),
12777            kind: kind.into(),
12778            detail: format!("{}: {detail}", cache_dir.display()),
12779            at: Timestamp::now(),
12780        });
12781        state.event(
12782            "resource",
12783            state.resource_block.as_ref().unwrap().description(),
12784        );
12785    }
12786    if let Err(error) = state.save() {
12787        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12788    }
12789    waited
12790}
12791
12792/// The lease state could not be read at all (unreadable lease file, a
12793/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12794/// known to be contended, so a wave degrades to running without a shared cache
12795/// instead of stopping on a hold that [`crate::triage`] could never release.
12796#[derive(Debug)]
12797struct CacheCheckError(String);
12798
12799impl std::fmt::Display for CacheCheckError {
12800    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12801        f.write_str(&self.0)
12802    }
12803}
12804
12805impl std::error::Error for CacheCheckError {}
12806
12807/// Keep a specific acquisition outcome when the caller adds command evidence.
12808fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12809    let kind = if crate::build_target::isolated(&state.config) {
12810        crate::build_target::KIND
12811    } else {
12812        "shared build cache"
12813    };
12814    state
12815        .resource_block
12816        .get_or_insert_with(|| crate::run::ResourceBlock {
12817            cause: crate::run::ResourceBlockCause::Other,
12818            node: node.to_owned(),
12819            kind: kind.into(),
12820            detail: format!("{error:#}"),
12821            at: Timestamp::now(),
12822        });
12823    if let Err(error) = state.save() {
12824        tracing::warn!("could not persist cache resource block: {error:#}");
12825    }
12826}
12827
12828tokio::task_local! {
12829    static VERIFY_TARGET: PathBuf;
12830}
12831
12832/// Run `body` — a verify command batch — while holding the shared build
12833/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12834/// never interleave with another borrower's build against the same
12835/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12836/// timeout, or a human's own `magi review`. See the `cache` module doc for
12837/// why this matters more than Cargo's own per-target locking covers — two
12838/// *different* worktrees building the same package name/version into one
12839/// cache directory is a staleness bug, not a lock contention one.
12840///
12841/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12842/// agent waves do. Repository scheduling also has its own bounded,
12843/// cancellable resource-wait policy. Contention must not consume the
12844/// verification budget: `body` receives the full `budget` after both leases
12845/// are acquired and the cache is fresh. Without a shared cache, only
12846/// repository coordination is acquired before handing over the full budget.
12847///
12848/// A lease that cannot be acquired within the resource wait is reported as a single
12849/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12850/// verification — the same shape a spawn failure already takes in
12851/// [`run_commands`], so a caller need not special-case it.
12852#[allow(clippy::too_many_arguments)]
12853async fn with_cache_lease<'s, F, Fut>(
12854    state: &'s mut RunState,
12855    cache_dir: Option<&Path>,
12856    node: &str,
12857    seat: &str,
12858    worktree: &Path,
12859    head: &str,
12860    budget: Duration,
12861    context: &str,
12862    wait: &crate::repo_lock::WaitPolicy,
12863    body: F,
12864) -> Result<(Vec<CommandOutcome>, bool)>
12865where
12866    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12867    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12868{
12869    // Match editing waves: cache first, repository second. In particular,
12870    // pre_gate must never hold the repository while waiting for a wave's cache.
12871    let started = Instant::now();
12872    let home = crate::run::home();
12873    let isolated = crate::build_target::isolated(&state.config);
12874    let planned_target = if isolated {
12875        let plan = (|| -> Result<PathBuf> {
12876            crate::build_target::supports(&state.config)?;
12877            crate::build_target::resolve(&home, worktree)
12878        })();
12879        match plan {
12880            Ok(path) => Some(path),
12881            Err(error) => {
12882                record_cache_error(state, node, &error);
12883                return Ok((
12884                    vec![CommandOutcome {
12885                        command: "(planning isolated build cache)".into(),
12886                        code: None,
12887                        output_tail: format!("{error:#}"),
12888                        duration_ms: 0,
12889                        resource_blocked: true,
12890                        ..Default::default()
12891                    }],
12892                    false,
12893                ));
12894            }
12895        }
12896    } else {
12897        None
12898    };
12899    let cache_dir = planned_target.as_deref().or(cache_dir);
12900    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12901    let guard = if let Some(cache_dir) = cache_dir {
12902        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12903        match acquire_cache_lease(
12904            state,
12905            cache_dir,
12906            &owner,
12907            resource_limit,
12908            node,
12909            context,
12910            &|| wait.cancelled(),
12911        )
12912        .await
12913        .and_then(|g| {
12914            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12915        }) {
12916            Ok(g) => Some(g),
12917            Err(e) => {
12918                record_cache_error(state, node, &e);
12919                return Ok((
12920                    vec![CommandOutcome {
12921                        command: if isolated {
12922                            "(waiting for the isolated build cache)"
12923                        } else {
12924                            "(waiting for the shared build cache)"
12925                        }
12926                        .into(),
12927                        code: None,
12928                        output_tail: e.to_string(),
12929                        duration_ms: started.elapsed().as_millis() as u64,
12930                        resource_blocked: true,
12931                        ..Default::default()
12932                    }],
12933                    false,
12934                ));
12935            }
12936        }
12937    } else {
12938        None
12939    };
12940    let _coordination = coordinate_operation(state, worktree, wait).await?;
12941    if let Some(path) = &planned_target {
12942        state.event(node, format!("isolated build target: {}", path.display()));
12943    }
12944    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12945        let identity = crate::cache::Identity::new(worktree, head);
12946        let fresh = crate::cache::ensure_fresh(
12947            &home,
12948            cache_dir,
12949            &identity,
12950            &state.config.verify.cargo_manifests(),
12951        );
12952        if let Err(e) = fresh {
12953            record_cache_error(state, node, &e);
12954            state.event(
12955                "verify",
12956                format!(
12957                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12958                    worktree.display(),
12959                    short(head)
12960                ),
12961            );
12962            if let Some(guard) = guard {
12963                guard.release();
12964            }
12965            return Ok((
12966                vec![CommandOutcome {
12967                    command: "(confirming the build cache is fresh)".into(),
12968                    code: None,
12969                    output_tail: e.to_string(),
12970                    duration_ms: started.elapsed().as_millis() as u64,
12971                    resource_blocked: true,
12972                    ..Default::default()
12973                }],
12974                false,
12975            ));
12976        }
12977    }
12978    let future = body(state, budget);
12979    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12980        VERIFY_TARGET.scope(target, future).await
12981    } else {
12982        future.await
12983    };
12984    if !timed_out_pids.is_empty() {
12985        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12986    }
12987    // Drop repository coordination before releasing the cache, reversing the
12988    // acquisition order. A cancelled/error future also drops both guards.
12989    drop(_coordination);
12990    if let Some(guard) = guard {
12991        guard.release();
12992    }
12993    Ok((outcomes, retried))
12994}
12995
12996/// Poll `pids` — commands [`run_commands`] reports as still running when its
12997/// own timeout elapsed — until every one is confirmed gone, or
12998/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12999///
13000/// Real confirmation where confirmation is possible, not a substitute for
13001/// full process-tree observation: a grandchild the timed-out process spawned
13002/// and that survives independently of it is invisible to a pid check the
13003/// same way it always was, and continuing to observe and collect *that*
13004/// stays a different piece of work with its own owner. This only narrows a
13005/// fixed blind wait into an actual check of the pids this process does know
13006/// about.
13007async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
13008    wait_for_pids_with(
13009        pids,
13010        crate::proc::pid_alive,
13011        LEASE_RELEASE_POLL,
13012        LEASE_RELEASE_MAX_WAIT,
13013    )
13014    .await;
13015}
13016
13017/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
13018/// interval and ceiling supplied by the caller, so the polling *logic* -
13019/// returns as soon as every pid reports dead, gives up at the ceiling
13020/// otherwise - is testable on millisecond durations without asking the real
13021/// OS about a pid at all.
13022async fn wait_for_pids_with<F: Fn(u32) -> bool>(
13023    pids: &[u32],
13024    alive: F,
13025    poll: Duration,
13026    max_wait: Duration,
13027) {
13028    let deadline = Instant::now() + max_wait;
13029    loop {
13030        if pids.iter().all(|&pid| !alive(pid)) {
13031            return;
13032        }
13033        if Instant::now() >= deadline {
13034            return;
13035        }
13036        tokio::time::sleep(poll).await;
13037    }
13038}
13039
13040/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
13041/// admission that it could not even get a verify command to run, as opposed
13042/// to evidence the command actually produced? A caller that would otherwise
13043/// read a resource-blocked outcome as a red command must check this first:
13044/// see [`Runner::gate`], which retries rather than records `Blocked` when
13045/// this is true.
13046fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
13047    outcomes.iter().any(|o| o.resource_blocked)
13048}
13049
13050/// What [`Runner::gate_fix_round`] decided.
13051pub(crate) enum GateFix {
13052    /// The tree changed and `verify.e2e` is still green: run the gate again.
13053    Retry,
13054    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
13055    /// last failure stands and the run ends blocked.
13056    Stop,
13057    /// `verify.e2e` could not run after the fix (magi's own contention):
13058    /// decide nothing now, a later reentry retries.
13059    Defer,
13060}
13061
13062/// Is every red command in `outcomes` an ordinary failure the code could
13063/// explain: it ran, exited non-zero, and said something?
13064///
13065/// A timeout, a spawn failure and a killed process all leave `code` `None`;
13066/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
13067/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
13068/// what the command is stays the gate's business.
13069pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
13070    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13071    red.peek().is_some()
13072        && red.all(|o| {
13073            !o.resource_blocked
13074                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13075                && !o.output_tail.trim().is_empty()
13076        })
13077}
13078
13079/// Describe one verify command's outcome for the event log, distinguishing a
13080/// build/link failure — the toolchain never produced a binary to run — from
13081/// an actual test failure, since only the latter is a verdict on the patch.
13082fn e2e_outcome_label(o: &CommandOutcome) -> String {
13083    if o.ok() {
13084        return "pass".to_owned();
13085    }
13086    let reason = if o.build_failed() {
13087        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
13088    } else {
13089        format!("FAIL ({:?})", o.code)
13090    };
13091    format!(
13092        "{reason}\n{}",
13093        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13094    )
13095}
13096
13097/// Does `outcomes` hold a failure worth one more run on the same commit?
13098///
13099/// Only an ordinary test result qualifies: every red command ran, exited
13100/// non-zero and said which way (not a build/link failure, a timeout or kill,
13101/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
13102/// evidence about the machine or the toolchain, never about a flaky test.
13103fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
13104    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13105    red.peek().is_some()
13106        && !verify_inconclusive(outcomes)
13107        && red.all(|o| {
13108            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13109        })
13110}
13111
13112/// Run `verify.e2e`, retrying once if the first attempt could not build or
13113/// link — a build/link failure is frequently a race against a shared
13114/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
13115/// `verify` event per command, tagged with `context` (normally `"round N"`)
13116/// so the call sites that need this — the ordinary per-round leg in
13117/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
13118/// will ever call a round green, `verify_current_head` and the gate-repair
13119/// check — read identically in the event log.
13120///
13121/// A failure that is a test result (see [`rerunnable_failure`]) is believed
13122/// only after the failed commands have run once more on the same commit, in
13123/// the same worktree and — because the caller holds it around this whole
13124/// function — under the same cache lease, with a full `timeout` of their own
13125/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
13126/// flake: the head is verified, the first failure is recorded and filed
13127/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
13128/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
13129/// preserving bounded evidence and artifact references for both attempts;
13130/// it claims a matching reproduction only when both attempts yield identical
13131/// confirmed terminal test failures. One verification is therefore run at most
13132/// three times: the build/link retry, then this one rerun. `round` is the
13133/// review round the verification belongs to, if any.
13134async fn run_e2e_with_retry(
13135    state: &mut RunState,
13136    shell: &[String],
13137    commands: &[String],
13138    worktree: &Path,
13139    timeout: Duration,
13140    context: &str,
13141    round: Option<usize>,
13142) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
13143    let (mut e2e, mut timed_out_pids) = run_commands(
13144        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
13145    )
13146    .await;
13147    for o in &e2e {
13148        state.event(
13149            "verify",
13150            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
13151        );
13152    }
13153    // A build/link failure is not a verdict on the patch — it is frequently a
13154    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
13155    // one retry before letting a red like that decide the round.
13156    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
13157    if verify_retried {
13158        state.event(
13159            "verify",
13160            format!(
13161                "{context}: verify could not build/link, not a test result — retrying once \
13162                 before concluding"
13163            ),
13164        );
13165        let retried = run_commands(
13166            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
13167        )
13168        .await;
13169        e2e = retried.0;
13170        // Both attempts' timeouts matter, not just the last one: the first
13171        // attempt's descendants may still be alive alongside the retry's.
13172        timed_out_pids.extend(retried.1);
13173        for o in &e2e {
13174            state.event(
13175                "verify",
13176                format!(
13177                    "{context}: retry `{}` -> {}",
13178                    o.command,
13179                    e2e_outcome_label(o)
13180                ),
13181            );
13182        }
13183    }
13184    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
13185        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
13186        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
13187        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
13188        state.event(
13189            "verify",
13190            format!(
13191                "{context}: {} failed with a test result — running it once more on the same \
13192                 commit {} before deciding",
13193                rerun_commands
13194                    .iter()
13195                    .map(|c| format!("`{c}`"))
13196                    .collect::<Vec<_>>()
13197                    .join(", "),
13198                short(&head)
13199            ),
13200        );
13201        let (second, pids) = run_commands(
13202            state,
13203            "verify",
13204            "e2e",
13205            1 + usize::from(verify_retried),
13206            shell,
13207            &rerun_commands,
13208            worktree,
13209            timeout,
13210        )
13211        .await;
13212        timed_out_pids.extend(pids);
13213        for o in &second {
13214            state.event(
13215                "verify",
13216                format!(
13217                    "{context}: rerun `{}` -> {}",
13218                    o.command,
13219                    e2e_outcome_label(o)
13220                ),
13221            );
13222        }
13223        for (slot, &i) in failed.iter().enumerate() {
13224            let Some(again) = second.get(slot) else {
13225                break;
13226            };
13227            let first = std::mem::replace(&mut e2e[i], again.clone());
13228            if again.ok() {
13229                let signature = crate::flake::signature(&first.output_tail, first.code);
13230                let flake = crate::run::VerifyFlake {
13231                    round,
13232                    context: context.to_owned(),
13233                    head: head.clone(),
13234                    command: first.command.clone(),
13235                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
13236                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
13237                    at: Timestamp::now(),
13238                    task: None,
13239                    filed: false,
13240                    filing_error: None,
13241                };
13242                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
13243            } else if !again.resource_blocked {
13244                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
13245                let message = crate::verify_evidence::rerun_event_message(
13246                    context,
13247                    &e2e[i].command,
13248                    &comparison,
13249                );
13250                e2e[i].rerun_comparison = Some(comparison);
13251                state.event("verify", message);
13252            }
13253        }
13254    }
13255    (e2e, verify_retried, timed_out_pids)
13256}
13257
13258/// Run configured shell commands in `cwd`, in order. The second element is
13259/// the pid of every command that hit `timeout` and was still running when
13260/// this stopped waiting on it (best-effort: `None` when the platform did not
13261/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13262/// that releases a shared resource afterward needs to know.
13263///
13264/// Records `task` into [`RunState::active`] at every command boundary
13265/// (`RunState::task_command`) and clears it once the whole list has run
13266/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13267/// for minutes with no seat and no output of its own to show for it (see
13268/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13269/// apart from "not yet run" without this), and this is the only place that
13270/// knows which command is running right now and how many are left. Three
13271/// saves per command — start, not per second — matching the same "only at a
13272/// boundary" rule [`wave`] already follows for seats.
13273#[allow(clippy::too_many_arguments)]
13274async fn run_commands(
13275    state: &mut RunState,
13276    node: &str,
13277    task: &str,
13278    attempt: usize,
13279    shell: &[String],
13280    commands: &[String],
13281    cwd: &Path,
13282    timeout: Duration,
13283) -> (Vec<CommandOutcome>, Vec<u32>) {
13284    let isolated = crate::build_target::isolated(&state.config);
13285    if isolated && let Some(block) = &state.resource_block {
13286        return (
13287            vec![CommandOutcome {
13288                command: "(isolated build admission)".into(),
13289                code: None,
13290                output_tail: block.description(),
13291                duration_ms: 0,
13292                resource_blocked: true,
13293                ..Default::default()
13294            }],
13295            Vec::new(),
13296        );
13297    }
13298    if commands.is_empty() {
13299        // Nothing to mark as running and nothing to clear — an empty list
13300        // means "not configured", and touching `active` (or the disk) over
13301        // that would be a write for every round of a repo with no
13302        // `verify.e2e` / `verify.gate` commands at all.
13303        return (Vec::new(), Vec::new());
13304    }
13305    let mut out = Vec::new();
13306    let mut timed_out_pids = Vec::new();
13307    let total = commands.len();
13308    for (idx, command) in commands.iter().enumerate() {
13309        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13310        if let Err(e) = state.save() {
13311            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13312        }
13313        let started = Instant::now();
13314        let mut cmd = tokio::process::Command::new(&shell[0]);
13315        cmd.quiet();
13316        // Verify the checkout as a standalone caller. Worker ownership and
13317        // pinned executable selection belong to this driver, not to tests or
13318        // tools it runs. Preserve home/seat context and Running's containment.
13319        for key in crate::worker::INVOCATION_ENV {
13320            cmd.env_remove(key);
13321        }
13322        cmd.env_remove(crate::build_id::EXPECT_ENV);
13323        cmd.args(&shell[1..])
13324            .current_dir(cwd)
13325            .stdin(std::process::Stdio::null())
13326            .stdout(std::process::Stdio::piped())
13327            .stderr(std::process::Stdio::piped())
13328            .kill_on_drop(true);
13329        let mut outputs = Vec::new();
13330        let mut cache = None;
13331        let home = crate::run::home();
13332        let head = if isolated {
13333            Some(git::rev_parse(cwd, "HEAD").await)
13334        } else {
13335            None
13336        };
13337        let protected = (|| -> Result<()> {
13338            crate::incremental::configure(&mut cmd, cwd)?;
13339            cache = if isolated {
13340                let target = VERIFY_TARGET
13341                    .try_with(Clone::clone)
13342                    .context("isolated verification has no target lease")?;
13343                cmd.arg(crate::build_target::command::normalize(command)?);
13344                crate::build_target::command::configure(&mut cmd, &target)?;
13345                Some(target)
13346            } else {
13347                crate::build_target::command::clear(&mut cmd)?;
13348                cmd.arg(command);
13349                state.config.cache_dir()
13350            };
13351            let mut paths = vec![cwd.to_owned()];
13352            if let Some(cache) = &cache {
13353                paths.push(cache.clone());
13354            }
13355            let admit = if isolated {
13356                crate::retention::OutputLease::admit_isolated
13357            } else {
13358                crate::retention::OutputLease::admit
13359            };
13360            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13361            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13362                outputs.push(guard);
13363            }
13364            if let Some(cache) = &cache {
13365                outputs.push(crate::retention::OutputLease::cache(
13366                    &crate::run::home(),
13367                    cache,
13368                    false,
13369                )?);
13370                if let Some(head) = head {
13371                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13372                    if task == "pre_gate" {
13373                        crate::cache::invalidate_identity(&home, cache);
13374                    }
13375                }
13376            }
13377            Ok(())
13378        })();
13379        if let Err(e) = protected {
13380            let detail = format!("execution admission unavailable: {e:#}");
13381            state.resource_block = Some(crate::run::ResourceBlock {
13382                cause: crate::run::ResourceBlockCause::Other,
13383                node: node.to_owned(),
13384                kind: if detail.contains("disk admission") {
13385                    "disk admission"
13386                } else {
13387                    "output ownership"
13388                }
13389                .to_owned(),
13390                detail: detail.clone(),
13391                at: Timestamp::now(),
13392            });
13393            out.push(CommandOutcome {
13394                command: command.clone(),
13395                code: None,
13396                output_tail: detail,
13397                duration_ms: 0,
13398                resource_blocked: true,
13399                ..Default::default()
13400            });
13401            break;
13402        }
13403        let spawned = if isolated {
13404            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13405        } else {
13406            crate::seat_process::Running::spawn(cmd, None, outputs)
13407        };
13408        let (code, out_text, err_text, body) = match spawned {
13409            Ok(mut running) => {
13410                let pid = running.child().id();
13411                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13412                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13413                let mut paths = vec![cwd.to_owned()];
13414                if let Some(cache) = cache {
13415                    paths.push(cache);
13416                }
13417                let mut pressure = None;
13418                let status = tokio::select! {
13419                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13420                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13421                        pressure = Some(reason); None
13422                    }
13423                };
13424                let (code, failure) = match status {
13425                    Some(Ok(Ok(status))) => (
13426                        status.code(),
13427                        status
13428                            .code()
13429                            .is_none()
13430                            .then(|| format!("command terminated: {status}")),
13431                    ),
13432                    Some(Ok(Err(error))) => {
13433                        (None, Some(format!("failed waiting for command: {error}")))
13434                    }
13435                    Some(Err(_)) => {
13436                        // Leased cleanup confirms process-tree death itself.
13437                        // Unleased commands still need the caller's PID check
13438                        // after kill-on-drop, before releasing cache ownership.
13439                        if !running.coordinated()
13440                            && let Some(pid) = pid
13441                        {
13442                            timed_out_pids.push(pid);
13443                        }
13444                        (
13445                            None,
13446                            Some(format!("timed out after {}s", timeout.as_secs())),
13447                        )
13448                    }
13449                    None => (None, None),
13450                };
13451                running.finish().await;
13452                if let Some(reason) = pressure {
13453                    state.resource_block = Some(crate::run::ResourceBlock {
13454                        cause: crate::run::ResourceBlockCause::Other,
13455                        node: node.to_owned(),
13456                        kind: "disk pressure".to_owned(),
13457                        detail: reason.clone(),
13458                        at: Timestamp::now(),
13459                    });
13460                    out.push(CommandOutcome {
13461                        command: command.clone(),
13462                        code: None,
13463                        output_tail: reason,
13464                        duration_ms: started.elapsed().as_millis() as u64,
13465                        resource_blocked: true,
13466                        ..Default::default()
13467                    });
13468                    break;
13469                }
13470                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13471                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13472                let mut body = out_text.clone();
13473                body.push_str(&err_text);
13474                if let Some(failure) = failure {
13475                    body.push('\n');
13476                    body.push_str(&failure);
13477                }
13478                (code, out_text, err_text, body)
13479            }
13480            Err(e) if isolated => {
13481                let e = anyhow::Error::new(e)
13482                    .context(format!("could not start managed build `{}`", shell[0]));
13483                record_cache_error(state, node, &e);
13484                out.push(CommandOutcome {
13485                    command: command.clone(),
13486                    code: None,
13487                    output_tail: format!("{e:#}"),
13488                    duration_ms: 0,
13489                    resource_blocked: true,
13490                    ..Default::default()
13491                });
13492                break;
13493            }
13494            Err(e) => (
13495                None,
13496                String::new(),
13497                String::new(),
13498                format!("failed to spawn `{}`: {e}", shell[0]),
13499            ),
13500        };
13501        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13502        let mut artifact = None;
13503        if !body.is_empty() {
13504            // The full text is kept whatever the summary dropped. A fresh
13505            // name per command so a resume or retry never overwrites an
13506            // earlier run's output. A failed write changes no verdict.
13507            match crate::run::write_verification_artifact(state, task, &body) {
13508                Ok(name) => {
13509                    let rel = format!("artifacts/{name}");
13510                    if summary != body {
13511                        summary = format!("[full output: {rel}]\n{summary}");
13512                    }
13513                    artifact = Some(rel);
13514                }
13515                Err(e) => {
13516                    let warning = format!("could not save the full {task} output: {e:#}");
13517                    tracing::warn!("{warning}");
13518                    state.event(node, warning);
13519                    if summary != body {
13520                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13521                    }
13522                }
13523            }
13524        }
13525        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13526        let mut outcome = CommandOutcome {
13527            command: command.clone(),
13528            code,
13529            output_tail: summary,
13530            duration_ms: started.elapsed().as_millis() as u64,
13531            resource_blocked,
13532            artifact,
13533            failure_evidence: None,
13534            rerun_comparison: None,
13535        };
13536        if !outcome.ok() && !outcome.resource_blocked {
13537            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13538                code,
13539                outcome.build_failed(),
13540                &out_text,
13541                &err_text,
13542            ));
13543        }
13544        out.push(outcome);
13545        if resource_blocked {
13546            state.resource_block = Some(crate::run::ResourceBlock {
13547                cause: crate::run::ResourceBlockCause::Other,
13548                node: node.to_owned(),
13549                kind: "incremental cache admission".into(),
13550                detail: body,
13551                at: Timestamp::now(),
13552            });
13553            break;
13554        }
13555    }
13556    state.task_finished(task);
13557    if let Err(e) = state.save() {
13558        tracing::warn!("could not persist the end of {task}: {e:#}");
13559    }
13560    (out, timed_out_pids)
13561}
13562
13563/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13564/// section (`report::run`) and in the `merge` event this node records — for
13565/// the operator to run by hand.
13566///
13567/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13568/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13569/// merge commits", or "require linear history") rejects the push a `--no-ff`
13570/// merge would produce, which is exactly the guidance this function replaces.
13571/// `message`'s first line becomes the squash commit's subject, matching the
13572/// note `report::run` prints alongside this command — see that function for
13573/// why an explicit subject is not optional there.
13574fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13575    let repo = repo.display();
13576    match style {
13577        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13578        MergeStyle::Squash => {
13579            // The subject sits inside double quotes, and a title an agent
13580            // wrote may carry the characters that break out of them.
13581            let subject = message
13582                .lines()
13583                .next()
13584                .unwrap_or(branch)
13585                .replace(['\\', '"', '$', '`'], "");
13586            format!(
13587                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13588            )
13589        }
13590        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13591    }
13592}
13593
13594/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13595/// under the hood, rejects a `title` over 256 characters and the whole
13596/// command fails — no PR at all, for a run whose body was otherwise fine
13597/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13598/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13599/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13600/// this bound. It is a margin, not a guarantee — a title packed
13601/// with multi-unit characters could still in principle land close to the
13602/// edge, but a real task title's occasional emoji or accented letter fits
13603/// comfortably inside it.
13604const PR_TITLE_MAX: usize = 240;
13605
13606/// A pull request title from the opening line of `text`, or `None` when that
13607/// line is not English (GitHub text is) or has no letters.
13608///
13609/// A line within `max` is kept as is. A longer one is cut at the end of its
13610/// first sentence when that falls inside `max`, else at a word boundary with a
13611/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13612/// make every merely-truncated title look non-English). The language check
13613/// runs on the kept text before any mark is added, so only what GitHub will
13614/// show is judged: an English opening followed by non-ASCII far past the cut
13615/// still passes.
13616fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13617    let line = queue::first_line(text)?;
13618    let chars: Vec<char> = line.chars().collect();
13619    let (kept, mark) = if chars.len() <= max {
13620        (line.to_owned(), "")
13621    } else if let Some(end) = sentence_end(&chars, max) {
13622        (chars[..end].iter().collect::<String>(), "")
13623    } else {
13624        let room = max.saturating_sub(3);
13625        // Cut at the last space inside the room; when the char just past the
13626        // room is a space the room already ends on a word.
13627        let cut = if chars[room].is_whitespace() {
13628            room
13629        } else {
13630            chars[..room]
13631                .iter()
13632                .rposition(|c| c.is_whitespace())
13633                .unwrap_or(room)
13634        };
13635        let head: String = chars[..cut].iter().collect();
13636        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13637        (head.to_owned(), "...")
13638    };
13639    if kept.is_empty() {
13640        return None;
13641    }
13642    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13643        return None;
13644    }
13645    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13646        return None;
13647    }
13648    Some(format!("{kept}{mark}"))
13649}
13650
13651/// The char length of the first sentence of `chars` when it ends within `max`
13652/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13653/// abbreviations so `e.g. foo` does not end a title early.
13654fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13655    const MIN: usize = 20;
13656    for i in MIN..max.min(chars.len()) {
13657        if !matches!(chars[i], '.' | '!' | '?') {
13658            continue;
13659        }
13660        let Some(&next) = chars.get(i + 1) else {
13661            continue;
13662        };
13663        if !next.is_whitespace() {
13664            continue;
13665        }
13666        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13667        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13668            continue;
13669        }
13670        let word: String = chars[..i]
13671            .iter()
13672            .rev()
13673            .take_while(|c| !c.is_whitespace())
13674            .collect::<Vec<_>>()
13675            .into_iter()
13676            .rev()
13677            .collect();
13678        let word = word.to_ascii_lowercase();
13679        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13680            continue;
13681        }
13682        let end = chars[..i]
13683            .iter()
13684            .rposition(|c| !c.is_whitespace())
13685            .map_or(i, |p| p + 1);
13686        return Some(end);
13687    }
13688    None
13689}
13690
13691/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13692/// change: a title and a body describing what was *implemented*, not the task
13693/// that asked for it. A task reads as a request; a reader of the merged
13694/// history wants the change.
13695struct PrMessage {
13696    title: String,
13697    body: String,
13698}
13699
13700impl PrMessage {
13701    /// Title, blank line, body. The first line is the squash/merge commit
13702    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13703    /// has to stay one sensible line.
13704    fn commit_message(&self) -> String {
13705        format!("{}\n\n{}", self.title, self.body)
13706    }
13707}
13708
13709/// The text after a leading `TITLE:` (any case) on `line`.
13710fn title_marker(line: &str) -> Option<&str> {
13711    let line = line.trim();
13712    let head = line.get(..6)?;
13713    head.eq_ignore_ascii_case("title:")
13714        .then(|| line[6..].trim())
13715}
13716
13717/// The implementer's own one-line title: the `TITLE:` line the implement
13718/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13719/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13720/// source, and a title that says as much is refused here too.
13721fn summary_title(summary: &str) -> Option<String> {
13722    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13723    let raw = title_marker(first)?;
13724    if raw.is_empty() {
13725        return None;
13726    }
13727    let title = queue::title_from(raw, PR_TITLE_MAX);
13728    let lower = title.to_ascii_lowercase();
13729    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13730        return None;
13731    }
13732    Some(title)
13733}
13734
13735/// How `open_review`'s instruction begins; see [`landing_title`].
13736const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13737
13738/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13739pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13740
13741/// Does this run review work that already existed, rather than implement a
13742/// task? Runs recorded before `reviewed_commits` existed carry only the
13743/// candidate marker.
13744pub(crate) fn is_review_run(state: &RunState) -> bool {
13745    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13746}
13747
13748/// The title of a review-only run: the subject of the oldest commit under
13749/// review. Later commits are usually fixups, and `instruction` is the review
13750/// prompt, which says nothing about the change. GitHub text is English, so a
13751/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13752fn review_title(state: &RunState) -> Option<String> {
13753    english_subject(
13754        state.reviewed_commits.as_ref()?.first()?,
13755        state.config.graph.github_english(),
13756    )
13757}
13758
13759/// `raw` as a pull request title, or `None` when it is blank, not English
13760/// (GitHub text is), or one of magi's own candidate commit subjects.
13761fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13762    let raw = raw.trim();
13763    if raw.is_empty() {
13764        return None;
13765    }
13766    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13767        return None;
13768    }
13769    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13770        return None;
13771    }
13772    let title = queue::title_from(raw, PR_TITLE_MAX);
13773    let lower = title.to_ascii_lowercase();
13774    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13775        return None;
13776    }
13777    Some(title)
13778}
13779
13780/// What a review-only run's branch says about itself, read at the moment the
13781/// pull request is opened.
13782#[derive(Debug, Clone, PartialEq, Eq)]
13783struct BranchFacts {
13784    /// `(subject, body)` of each commit, oldest first.
13785    commits: Vec<(String, String)>,
13786    /// Trimmed `git diff --stat`.
13787    stat: String,
13788}
13789
13790/// Longest diff stat shown: this many file lines plus the summary line.
13791const STAT_FILE_LINES: usize = 25;
13792/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13793const COMMITS_MAX_CHARS: usize = 20_000;
13794
13795/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13796/// say or finds nothing, so the caller falls back to what the run recorded.
13797async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13798    let commits = git::commit_log(repo, base, branch).await.ok()?;
13799    if commits.is_empty() {
13800        return None;
13801    }
13802    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13803    let lines: Vec<&str> = stat.lines().collect();
13804    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13805        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13806        let more = format!(" ... {omitted} more file(s)");
13807        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13808        kept.push(&more);
13809        kept.push(lines[lines.len() - 1]);
13810        kept.join("\n")
13811    } else {
13812        lines.join("\n")
13813    };
13814    Some(BranchFacts { commits, stat })
13815}
13816
13817/// Defang what would break the surrounding markdown: a closing `</details>`
13818/// and a code fence.
13819fn markdown_safe(text: &str) -> String {
13820    text.replace("</details>", "&lt;/details&gt;")
13821        .replace("\x60\x60\x60", "~~~")
13822}
13823
13824fn neutral_title(state: &RunState, winner: char) -> String {
13825    format!(
13826        "chore: land candidate {} of run {}",
13827        winner.to_ascii_uppercase(),
13828        state.id
13829    )
13830}
13831
13832/// Reuse the graph's bounded fixer without starting another graph or driver.
13833/// Copy the working state back even on errors so spent rounds remain visible.
13834pub(crate) async fn repair_landing_gate(
13835    state: &mut RunState,
13836    winner: &Candidate,
13837    outcomes: &[CommandOutcome],
13838) -> Result<GateFix> {
13839    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13840        return Ok(GateFix::Stop);
13841    }
13842    let mut runner = Runner {
13843        roles: state.config.resolve_roles()?,
13844        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13845        state: state.clone(),
13846        pause: Pause::new(),
13847        interrupt: Pause::new(),
13848    };
13849    let result = runner.gate_fix_round(winner, outcomes).await;
13850    *state = runner.state;
13851    result
13852}
13853
13854/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13855/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13856pub(crate) async fn verify_current_head(
13857    state: &mut RunState,
13858    winner: &Candidate,
13859    wait: &crate::repo_lock::WaitPolicy,
13860) -> Result<bool> {
13861    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13862    // Preserve the previous record before replacing it, including on crash recovery.
13863    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13864        state
13865            .verification_history
13866            .push(crate::run::VerificationEvidence {
13867                superseded_by: Some(head.clone()),
13868                archived_at: Some(Timestamp::now()),
13869                fixes_spent: Some(state.gate_fixes.len()),
13870                gate_head: None,
13871                gate_ran: false,
13872                gate: Vec::new(),
13873                e2e: state.head_e2e.take(),
13874            });
13875    }
13876    if let Some(e) = &state.head_e2e
13877        && e.head == head
13878    {
13879        if e.passed {
13880            return Ok(true);
13881        }
13882        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13883            state.status = RunStatus::Blocked;
13884            state.save()?;
13885            return Ok(false);
13886        }
13887    } else if state.reviews.last().is_some_and(|r| {
13888        r.verified_head.as_deref() == Some(head.as_str())
13889            && (r.e2e_status() == E2eStatus::Passed
13890                || (r.e2e_status() == E2eStatus::NotConfigured
13891                    && state.config.verify.e2e.is_empty()))
13892    }) || state
13893        .gate_repair_e2e
13894        .as_ref()
13895        .is_some_and(|e| e.head == head && e.passed)
13896    {
13897        return Ok(true);
13898    }
13899    if let Some(e) = &state.gate_repair_e2e
13900        && e.head == head
13901        && !e.passed
13902        && !e.outcomes.is_empty()
13903        && !verify_inconclusive(&e.outcomes)
13904    {
13905        state.status = RunStatus::Blocked;
13906        state.save()?;
13907        return Ok(false);
13908    }
13909    // Bind the result to the base used by the candidate, not a tracking ref
13910    // that the background fetch can advance independently of verification.
13911    let base_commit = state
13912        .base_sync
13913        .as_ref()
13914        .map(|s| s.tip.clone())
13915        .filter(|tip| !tip.is_empty())
13916        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13917    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13918        head.clone(),
13919        false,
13920        Vec::new(),
13921    ));
13922    state.save()?;
13923    let commands = state.config.verify.e2e.clone();
13924    let shell = state.config.shell();
13925    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13926    let cache_dir = state.config.cache_dir();
13927    let outcomes = if commands.is_empty() {
13928        Vec::new()
13929    } else {
13930        let (outcomes, _) = with_cache_lease(
13931            state,
13932            cache_dir.as_deref(),
13933            "e2e",
13934            "e2e",
13935            &winner.worktree,
13936            &head,
13937            timeout,
13938            "current head e2e",
13939            wait,
13940            |state, budget| async move {
13941                run_e2e_with_retry(
13942                    state,
13943                    &shell,
13944                    &commands,
13945                    &winner.worktree,
13946                    budget,
13947                    "current head e2e",
13948                    None,
13949                )
13950                .await
13951            },
13952        )
13953        .await?;
13954        outcomes
13955    };
13956    let unresolved = verify_inconclusive(&outcomes);
13957    let passed = !unresolved
13958        && outcomes.iter().all(CommandOutcome::ok)
13959        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13960    if !outcomes.is_empty() && !unresolved {
13961        state.record_base_progress(&head);
13962    }
13963    let generation = Some(state.verification_history.len());
13964    let pass = state.passes.last().map(|p| p.index);
13965    let recorded_at = Some(Timestamp::now());
13966    let resumption_generation = state.entry_resumption_generation;
13967    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
13968    record.base_commit = base_commit;
13969    record.generation = generation;
13970    record.pass = pass;
13971    record.recorded_at = recorded_at;
13972    record.resumption_generation = resumption_generation;
13973    if !passed && !unresolved {
13974        let detail = state
13975            .head_e2e
13976            .as_ref()
13977            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13978            .map(|d| format!(" ({d})"))
13979            .unwrap_or_default();
13980        state.status = RunStatus::Blocked;
13981        state.event(
13982            "e2e",
13983            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13984        );
13985        record.recorded_events = Some(state.events.len());
13986    }
13987    state.head_e2e = Some(record);
13988    state.save()?;
13989    Ok(passed)
13990}
13991
13992/// Recheck a repair's e2e requirement across failures, resource deferrals and
13993/// process interruptions. A successful result only applies to its exact SHA.
13994pub(crate) async fn check_gate_repair_e2e(
13995    state: &mut RunState,
13996    winner: &Candidate,
13997    wait: &crate::repo_lock::WaitPolicy,
13998) -> Result<GateFix> {
13999    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
14000        return Ok(GateFix::Retry);
14001    }
14002    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14003    if let Some(record) = &state.gate_repair_e2e
14004        && record.head == head
14005    {
14006        if record.passed {
14007            return Ok(GateFix::Retry);
14008        }
14009        if !record.outcomes.is_empty()
14010            && record.outcomes.iter().all(|o| {
14011                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
14012            })
14013        {
14014            return Ok(GateFix::Stop);
14015        }
14016    }
14017    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
14018        head.clone(),
14019        false,
14020        Vec::new(),
14021    ));
14022    state.save()?;
14023    let commands = state.config.verify.e2e.clone();
14024    let outcomes = if commands.is_empty() {
14025        Vec::new()
14026    } else {
14027        let shell = state.config.shell();
14028        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14029        let cache_dir = state.config.cache_dir();
14030        let (outcomes, _) = with_cache_lease(
14031            state,
14032            cache_dir.as_deref(),
14033            "e2e",
14034            "e2e",
14035            &winner.worktree,
14036            &head,
14037            timeout,
14038            "gate repair e2e",
14039            wait,
14040            |state, budget| async move {
14041                run_e2e_with_retry(
14042                    state,
14043                    &shell,
14044                    &commands,
14045                    &winner.worktree,
14046                    budget,
14047                    "gate repair e2e",
14048                    None,
14049                )
14050                .await
14051            },
14052        )
14053        .await?;
14054        outcomes
14055    };
14056    let deferred = verify_inconclusive(&outcomes);
14057    let passed = outcomes.iter().all(CommandOutcome::ok)
14058        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14059    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
14060    state.save()?;
14061    if deferred {
14062        Ok(GateFix::Defer)
14063    } else if !passed {
14064        let detail = state
14065            .gate_repair_e2e
14066            .as_ref()
14067            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14068            .map(|d| format!(" ({d})"))
14069            .unwrap_or_default();
14070        state.event(
14071            "gate",
14072            format!("verify.e2e failed after gate repair{detail}; nothing published"),
14073        );
14074        Ok(GateFix::Stop)
14075    } else {
14076        Ok(GateFix::Retry)
14077    }
14078}
14079
14080/// Run the same configured gate for a landing head and a fresh graph.
14081pub(crate) async fn run_landing_gate(
14082    state: &mut RunState,
14083    winner: &Candidate,
14084    wait: &crate::repo_lock::WaitPolicy,
14085) -> Result<Vec<CommandOutcome>> {
14086    let shell = state.config.shell();
14087    let gate_commands = state.config.verify.gate.clone();
14088    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
14089    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
14090        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
14091        Vec::new()
14092    } else {
14093        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14094        let cache_dir = state.config.cache_dir();
14095        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14096        let (outcomes, _) = with_cache_lease(
14097            state,
14098            cache_dir.as_deref(),
14099            "gate",
14100            "gate",
14101            &winner.worktree,
14102            &head,
14103            timeout,
14104            "final gate",
14105            wait,
14106            |state, budget| {
14107                let shell = shell.clone();
14108                let gate_commands = gate_commands.clone();
14109                let winner = winner.clone();
14110                async move {
14111                    Runner::run_pre_gate(state, &winner).await;
14112                    // Bind command evidence after mechanical fixes, before commands start.
14113                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
14114                    let (outcomes, timed_out_pids) = run_commands(
14115                        state,
14116                        "gate",
14117                        "gate",
14118                        0,
14119                        &shell,
14120                        &gate_commands,
14121                        &winner.worktree,
14122                        budget,
14123                    )
14124                    .await;
14125                    (outcomes, false, timed_out_pids)
14126                }
14127            },
14128        )
14129        .await?;
14130        outcomes
14131    };
14132    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
14133    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
14134        let mut outcomes = outcomes;
14135        outcomes.push(CommandOutcome {
14136            command: "gate head stability".into(), code: None,
14137            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
14138            duration_ms: 0, resource_blocked: false,
14139            ..Default::default()
14140        });
14141        return Ok(outcomes);
14142    }
14143    if outcomes.is_empty() {
14144        // Nothing configured to check — distinct from every other
14145        // silence in this run's event log, since an empty `gate` alone
14146        // no longer says whether the gate ran at all (see
14147        // `RunState::gate_ran`'s own doc).
14148        state.event("gate", "no gate commands configured; not tested");
14149    }
14150    for o in &outcomes {
14151        state.event(
14152            "gate",
14153            format!(
14154                "`{}` -> {}",
14155                o.command,
14156                if o.ok() {
14157                    "pass".to_owned()
14158                } else {
14159                    format!(
14160                        "FAIL ({:?})\n{}",
14161                        o.code,
14162                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
14163                    )
14164                }
14165            ),
14166        );
14167    }
14168    Ok(outcomes)
14169}
14170
14171/// The pull request title to hand to `land::merge_subject`. A review-only run
14172/// opened by an earlier build titled its pull request with the review prompt;
14173/// that title is dropped (empty, so the fallback applies) rather than landed.
14174/// Any other title, including an operator's rename, passes through untouched,
14175/// and so does every title of a run that implements a task.
14176pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
14177    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
14178        ""
14179    } else {
14180        pr_title
14181    }
14182}
14183
14184/// What the squash subject falls back to when the pull request title is empty
14185/// or candidate-shaped: for a review-only run the derived title, never the
14186/// review prompt held in `instruction`.
14187pub fn landing_subject_source(state: &RunState) -> String {
14188    if is_review_run(state) {
14189        let winner = state.candidates.first().map_or('A', |c| c.label);
14190        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
14191    }
14192    state.instruction.clone()
14193}
14194
14195/// `summary` without its `TITLE:` line, which the pull request title already
14196/// carries.
14197fn summary_without_title(summary: &str) -> String {
14198    let mut lines = summary.trim().lines().peekable();
14199    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
14200        lines.next();
14201    }
14202    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
14203}
14204
14205/// The pull request title and body for the winning candidate.
14206///
14207/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
14208/// the task's own opening line via [`queue::title_from`] when there is none.
14209/// `state.instruction` can open with blank lines (`task_text` only rejects a
14210/// body that is blank *entirely*), which `title_from` skips.
14211///
14212/// Publishing uses an independent description generated from the final diff
14213/// and structured evidence. Internal summaries and reports remain local.
14214/// Non-publishing previews may display the original task and candidate summary.
14215/// The footer retains the run and candidate provenance.
14216#[cfg(test)]
14217fn pr_message(state: &RunState, winner: char) -> PrMessage {
14218    pr_message_with(state, winner, None)
14219}
14220
14221/// [`pr_message`] with what the branch of a review-only run says about itself.
14222/// `facts` is ignored for a run that implements a task.
14223#[cfg(test)]
14224fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
14225    let raw = pr_message_raw(
14226        state,
14227        winner,
14228        facts,
14229        crate::pr_outcome::FinalHead::Unreported,
14230        ChangeNote::NotAsked,
14231    );
14232    let id = crate::scrub::Identity::current();
14233    PrMessage {
14234        title: crate::scrub::scrub(&raw.title, &id),
14235        body: crate::scrub::scrub(&raw.body, &id),
14236    }
14237}
14238
14239/// What the public description may say about the change itself.
14240#[derive(Debug, Clone, Copy)]
14241enum ChangeNote<'a> {
14242    /// A local preview or non-publishing merge mode: no public generation needed.
14243    NotAsked,
14244    /// A summary written from the final diff.
14245    Summary(&'a crate::run::ChangeSummary),
14246    /// A summary was asked for and could not be produced; the text says why.
14247    Unavailable(&'a str),
14248}
14249
14250fn pr_message_raw(
14251    state: &RunState,
14252    winner: char,
14253    facts: Option<&BranchFacts>,
14254    head: crate::pr_outcome::FinalHead<'_>,
14255    change: ChangeNote<'_>,
14256) -> PrMessage {
14257    if !matches!(change, ChangeNote::NotAsked) {
14258        let (title, mut body) = match change {
14259            ChangeNote::Summary(c) => (
14260                c.title.clone(),
14261                format!("## Summary\n\n{}\n\n", c.body.trim()),
14262            ),
14263            ChangeNote::Unavailable(why) => (
14264                neutral_title(state, winner),
14265                format!(
14266                    "## 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"
14267                ),
14268            ),
14269            ChangeNote::NotAsked => unreachable!(),
14270        };
14271        body.push_str(&public_pr_evidence(state, head));
14272        body.push_str(&format!(
14273            "\n---\nmagi:run/{} magi:candidate-{}\n",
14274            state.id,
14275            winner.to_ascii_lowercase()
14276        ));
14277        return PrMessage { title, body };
14278    }
14279    pr_preview(state, winner, facts, head)
14280}
14281
14282/// Append public facts from the run records after every prose generation,
14283/// including posting-gate rewrites. The agent cannot drop this provenance.
14284fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14285    let mut body = crate::pr_outcome::review_rounds(state);
14286    body.push_str(&crate::pr_outcome::final_verification(state, head));
14287    let open = state.last_round_findings();
14288    if !open.is_empty() {
14289        body.push_str("## Open review findings\n\n");
14290        for f in open {
14291            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14292        }
14293        body.push('\n');
14294    }
14295    if let Some(c) = state.change_summary.as_ref()
14296        && head == crate::pr_outcome::FinalHead::At(&c.head)
14297    {
14298        body.push_str(&format!(
14299            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14300            c.base, c.head
14301        ));
14302    }
14303    body
14304}
14305
14306/// Local-only preview of the operator's task and candidate summary.
14307fn pr_preview(
14308    state: &RunState,
14309    winner: char,
14310    facts: Option<&BranchFacts>,
14311    head: crate::pr_outcome::FinalHead<'_>,
14312) -> PrMessage {
14313    let summary = state
14314        .candidates
14315        .iter()
14316        .find(|c| c.label == winner)
14317        .map(|c| c.summary.as_str())
14318        .unwrap_or_default();
14319    // The fallback is the operator's own words and may not be English; GitHub
14320    // text always is, so a non-English task gets a neutral title instead.
14321    let review = is_review_run(state);
14322    let title = if review {
14323        facts
14324            .and_then(|f| {
14325                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14326            })
14327            .or_else(|| review_title(state))
14328            .or_else(|| {
14329                state
14330                    .candidates
14331                    .iter()
14332                    .find(|c| c.label == winner)
14333                    .filter(|c| !c.branch.starts_with("magi/"))
14334                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14335            })
14336            .unwrap_or_else(|| neutral_title(state, winner))
14337    } else {
14338        summary_title(summary).unwrap_or_else(|| {
14339            english_title(
14340                &state.instruction,
14341                PR_TITLE_MAX,
14342                state.config.graph.github_english(),
14343            )
14344            .unwrap_or_else(|| neutral_title(state, winner))
14345        })
14346    };
14347
14348    let mut body = String::new();
14349    let what = summary_without_title(summary);
14350    if !what.is_empty() {
14351        body.push_str("## Summary\n\n");
14352        body.push_str(&what);
14353        body.push_str("\n\n");
14354    }
14355
14356    // Review history uses structured facts across all rounds, never reports.
14357    body.push_str(&crate::pr_outcome::review_rounds(state));
14358    body.push_str(&crate::pr_outcome::final_verification(state, head));
14359    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14360
14361    let open = state.open_findings();
14362    if !open.is_empty() {
14363        body.push_str("## Open review findings\n\n");
14364        for f in &open {
14365            body.push_str(&format!(
14366                "- `{}` [{:?}] {}\n",
14367                f.id, f.severity, "Context retained in local review records."
14368            ));
14369        }
14370        body.push('\n');
14371    }
14372
14373    if let Some(fix) = fix
14374        && !fix.rejected.is_empty()
14375    {
14376        body.push_str("## Declined by the fixer\n\n");
14377        for r in &fix.rejected {
14378            body.push_str(&format!(
14379                "- `{}`: {}\n",
14380                r.id, "Reason retained in local review records."
14381            ));
14382        }
14383        body.push('\n');
14384    }
14385
14386    if review {
14387        // The review prompt is not the task; list what the branch carries.
14388        body.push_str("## Commits under review\n\n");
14389        if let Some(facts) = facts {
14390            let mut left = COMMITS_MAX_CHARS;
14391            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14392                let mut entry = format!("- {}\n", markdown_safe(subject));
14393                for l in markdown_safe(text).lines() {
14394                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14395                }
14396                if left == 0 {
14397                    body.push_str(&format!(
14398                        "- ... {} more commit(s)\n",
14399                        facts.commits.len() - i
14400                    ));
14401                    break;
14402                }
14403                if entry.len() > left {
14404                    // Even the first commit is cut: one huge body must not
14405                    // push the whole description past GitHub's limit.
14406                    let mut end = left;
14407                    while !entry.is_char_boundary(end) {
14408                        end -= 1;
14409                    }
14410                    entry.truncate(end);
14411                    entry.push_str("\n  ... (truncated)\n");
14412                    left = 0;
14413                } else {
14414                    left -= entry.len();
14415                }
14416                body.push_str(&entry);
14417            }
14418            if !facts.stat.trim().is_empty() {
14419                body.push_str(&format!(
14420                    "\n## Diff stat\n\n```\n{}\n```\n",
14421                    markdown_safe(facts.stat.trim())
14422                ));
14423            }
14424        } else {
14425            match &state.reviewed_commits {
14426                Some(subjects) => {
14427                    for s in subjects {
14428                        body.push_str(&format!("- {}\n", s.trim()));
14429                    }
14430                }
14431                None => {
14432                    // An older run kept only the prompt, with the commit list
14433                    // after its first paragraph.
14434                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14435                    body.push_str(rest.trim());
14436                    body.push('\n');
14437                }
14438            }
14439        }
14440    } else {
14441        let task = state.instruction.trim();
14442        let task = if task.is_empty() {
14443            "(empty task)"
14444        } else {
14445            task
14446        };
14447        body.push_str(&format!(
14448            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14449            task.replace("</details>", "&lt;/details&gt;")
14450        ));
14451    }
14452
14453    body.push_str(&format!(
14454        "\n---\nmagi:run/{} magi:candidate-{}\n",
14455        state.id,
14456        winner.to_ascii_lowercase()
14457    ));
14458
14459    PrMessage { title, body }
14460}
14461
14462/// Source imports have already been prepared from structured inputs. Legacy
14463/// inferred references must never instruct a seat to reconstruct those imports.
14464fn seeded_instruction(state: &RunState) -> String {
14465    let mut inputs = Vec::new();
14466    if let Some(start) = &state.sources.start_from {
14467        inputs.push(format!(
14468            "Start from `{}` at `{}` (including ancestry).",
14469            start.token, start.sha
14470        ));
14471    }
14472    for pick in &state.sources.pick_commits {
14473        inputs.push(format!(
14474            "Pick `{}` at `{}` (single commit).",
14475            pick.token, pick.sha
14476        ));
14477    }
14478    if inputs.is_empty() {
14479        state.instruction.clone()
14480    } else {
14481        format!(
14482            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14483            state.instruction,
14484            inputs.join("\n")
14485        )
14486    }
14487}
14488
14489/// Does the winner have no commits ahead of the base it would land on?
14490/// Any failure to find out reads as "not empty": the merge then behaves as it
14491/// always did rather than refusing on a guess.
14492async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14493    let base = &state.base_branch;
14494    let mut against = base.clone();
14495    if mode == MergeMode::Pr {
14496        // A pull request lands on the remote's base, never the local branch
14497        // of the same name: if that cannot be read, "not empty" is the safe
14498        // answer.
14499        let remote = &state.config.merge.remote;
14500        let tracking = format!("{remote}/{base}");
14501        let fetched = git::fetch(repo, remote, base).await;
14502        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14503            against = tracking;
14504        } else {
14505            return false;
14506        }
14507    }
14508    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14509}
14510
14511/// Why nothing was opened for an empty winner, with what the task's own
14512/// references resolved to.
14513fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14514    let mut detail = format!(
14515        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14516         nothing to open a pull request for"
14517    );
14518    detail.push_str(
14519        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14520    );
14521    detail
14522}
14523
14524/// What the `Pr` merge does once it knows whether the branch already has an
14525/// open pull request.
14526#[derive(Debug, PartialEq, Eq)]
14527enum PrPlan {
14528    Create,
14529    Adopt { url: String, title: String },
14530    Stop(String),
14531}
14532
14533/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14534/// a failed lookup -> stop with the real reason. Never guesses.
14535fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14536    match found {
14537        Ok(land::OpenPr::None) => PrPlan::Create,
14538        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14539        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14540            "several open pull requests exist for this branch, not picking one: {}",
14541            urls.join(" ")
14542        )),
14543        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14544    }
14545}
14546
14547/// `gh pr create`, returning the PR url.
14548pub(crate) async fn gh_pr_create(
14549    cwd: &Path,
14550    base: &str,
14551    head: &str,
14552    title: &str,
14553    body: &str,
14554) -> Result<String> {
14555    let out = tokio::process::Command::new("gh")
14556        .args([
14557            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14558        ])
14559        .current_dir(cwd)
14560        .quiet()
14561        .stdin(std::process::Stdio::null())
14562        .output()
14563        .await
14564        .context("spawn gh")?;
14565    if out.status.success() {
14566        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14567    } else {
14568        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14569    }
14570}
14571
14572/// Never force deletion of uncommitted work, including unknown legacy trees.
14573async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14574    match std::fs::symlink_metadata(path) {
14575        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14576            // A previous cleanup may have removed the tree before a branch
14577            // deletion or state save failed. Unregister it if still present.
14578            git::worktree_remove_clean(repo, path).await?;
14579            return Ok(());
14580        }
14581        Err(e) => return Err(e.into()),
14582        Ok(_) => {}
14583    }
14584    if !git::is_clean(path).await? {
14585        bail!(
14586            "worktree has uncommitted work; refusing removal: {}",
14587            path.display()
14588        );
14589    }
14590    if !git::worktree_remove_clean(repo, path).await? {
14591        bail!("worktree removal refused: {}", path.display());
14592    }
14593    Ok(())
14594}
14595
14596/// Read seats return replies, not working-tree changes. Only registered,
14597/// detached seats directly inside this run's root may discard those changes.
14598async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14599    if !crate::retention::read_seat(path) || !path.exists() {
14600        return remove_preserved_worktree(&state.repo, path).await;
14601    }
14602    let owned = std::fs::symlink_metadata(path)?.is_dir()
14603        && path.parent().map(Path::canonicalize).transpose()?
14604            == Some(state.worktree_root().canonicalize()?)
14605        && crate::retention::worktrees(state)
14606            .await?
14607            .contains(&path.canonicalize()?);
14608    let common = crate::repo_lock::common_dir(&state.repo).await?;
14609    if !owned
14610        || common.is_none()
14611        || crate::repo_lock::common_dir(path).await? != common
14612        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14613            .await?
14614            .ok()
14615        || state.candidates.iter().any(|c| c.worktree == path)
14616    {
14617        return remove_preserved_worktree(&state.repo, path).await;
14618    }
14619    let changes = git::status_porcelain(path).await?;
14620    if !git::worktree_remove(&state.repo, path).await? {
14621        bail!(
14622            "read-only seat worktree removal refused: {}",
14623            path.display()
14624        );
14625    }
14626    if !changes.is_empty() {
14627        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14628        let paths: String = paths.chars().take(1024).collect();
14629        state.event(
14630            "fold",
14631            format!(
14632                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14633                path.file_name().unwrap_or_default().to_string_lossy(),
14634                changes.lines().count()
14635            ),
14636        );
14637    }
14638    Ok(())
14639}
14640
14641fn fold_target(
14642    home: &Path,
14643    root: &Path,
14644    path: &Path,
14645    isolated: bool,
14646) -> Option<crate::build_target::FoldTarget> {
14647    if !isolated {
14648        return None;
14649    }
14650    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14651        Ok(target) => target,
14652        Err(error) => {
14653            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14654            None
14655        }
14656    }
14657}
14658
14659fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14660    if let Some(target) = target
14661        && let Err(error) = target.reclaim_orphaned_target(home)
14662    {
14663        tracing::warn!(%error, "isolated target retained after fold");
14664    }
14665}
14666
14667/// Why a fold left a run alone. A typed refusal lets the automatic callers
14668/// (`clean::fold_one`, and through it the idle janitor and the busy-time fold
14669/// turn) say *why* in their receipts; it never changes what is deleted.
14670#[derive(Debug, Clone, PartialEq, Eq)]
14671pub enum FoldRefusal {
14672    /// A lease or lock a live owner holds - the run's execution lease or
14673    /// ownership lock, a source's output lease, a Cargo build, the repository's
14674    /// coordination lease - or a live daemon claim on the run.
14675    Live(String),
14676    /// A resumable status: someone may still continue this run.
14677    Resumable,
14678    /// Finished less than the fold grace period ago.
14679    WithinGrace,
14680    /// An explicitly retained recovery source (`pr_recovery`).
14681    Retained(String),
14682    /// The proof that nothing is lost is not complete: startup or candidate
14683    /// preservation unfinished, or the confirmed-merge source proof (Cargo
14684    /// residue, Git checkpoints, the fetched base) could not be established.
14685    ProofIncomplete(String),
14686    /// The run's record is gone, or is not the record that was locked: it was
14687    /// deleted while the fold waited for its locks. Nothing is touched and
14688    /// nothing is recreated.
14689    RecordGone,
14690    /// The record was readable when the caller first looked and cannot be read
14691    /// once the run's locks are held.
14692    Unreadable(String),
14693}
14694
14695impl std::fmt::Display for FoldRefusal {
14696    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14697        match self {
14698            Self::Live(detail) | Self::ProofIncomplete(detail) => f.write_str(detail),
14699            Self::Resumable => f.write_str("refusing fold: the run is resumable"),
14700            Self::WithinGrace => f.write_str("refusing fold: the run finished within its grace"),
14701            Self::Retained(reason) => write!(f, "refusing fold: {reason}"),
14702            Self::RecordGone => f.write_str("refusing fold: record gone"),
14703            Self::Unreadable(detail) => {
14704                write!(
14705                    f,
14706                    "refusing fold: the run record became unreadable: {detail}"
14707                )
14708            }
14709        }
14710    }
14711}
14712
14713impl std::error::Error for FoldRefusal {}
14714
14715/// Is `error` somebody else holding a lock or lease right now? Only
14716/// contention is: any other failure of a lock call is a real failure.
14717pub(crate) fn held_by_live_owner(error: &anyhow::Error) -> bool {
14718    error.chain().any(|cause| {
14719        cause.is::<crate::retention::OutputsInUse>()
14720            || cause.is::<crate::repo_lock::ResourceBlocked>()
14721            || cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
14722                io.kind() == std::io::ErrorKind::WouldBlock
14723                    || cfg!(windows) && io.raw_os_error() == Some(33)
14724            })
14725    })
14726}
14727
14728/// `error`, marked as [`FoldRefusal::Live`] when it is a held lock.
14729///
14730/// The refusal is *added to* the error as context, never substituted for it:
14731/// callers match the error underneath (`repo_lock::ResourceBlocked` for a
14732/// coordination wait, which several of them treat as a resource stop), and the
14733/// receipt's classification reads the refusal. Both downcasts succeed.
14734fn live_or(error: anyhow::Error) -> anyhow::Error {
14735    if held_by_live_owner(&error) {
14736        error.context(FoldRefusal::Live(
14737            "a lock or lease is held by another owner".into(),
14738        ))
14739    } else {
14740        error
14741    }
14742}
14743
14744/// A failure to take a run's owner lock or execution lease. A run directory
14745/// that is not there (deleted, or never was) is `record gone` and is *not*
14746/// created for the lock's sake; contention is `live`; anything else stays a
14747/// failure with its own text.
14748fn lock_refusal(error: anyhow::Error) -> anyhow::Error {
14749    if is_missing(&error) {
14750        FoldRefusal::RecordGone.into()
14751    } else {
14752        live_or(error)
14753    }
14754}
14755
14756fn is_missing(error: &anyhow::Error) -> bool {
14757    error.chain().any(|cause| {
14758        cause
14759            .downcast_ref::<std::io::Error>()
14760            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
14761    })
14762}
14763
14764fn preservation_refusal() -> anyhow::Error {
14765    FoldRefusal::ProofIncomplete("candidate preservation incomplete; refusing cleanup".into())
14766        .into()
14767}
14768
14769/// The record's own preconditions for the explicit recovery-retention override.
14770fn ensure_overridable(state: &RunState) -> Result<()> {
14771    anyhow::ensure!(
14772        state.status.done() && !state.status.resumable(),
14773        "recovery retention override requires a finished, non-resumable run"
14774    );
14775    Ok(())
14776}
14777
14778/// How a failure of the confirmed-merge source verification reaches the fold's
14779/// caller: somebody else holding a lock is `live`; a lock call that failed for
14780/// another reason is a failure of its own (`failed` in the receipt), not
14781/// evidence that the sources are unproven; anything else - missing or changed
14782/// evidence - is an incomplete proof.
14783fn source_proof_failure(error: anyhow::Error) -> anyhow::Error {
14784    if held_by_live_owner(&error) {
14785        live_or(error)
14786    } else if error
14787        .chain()
14788        .any(|cause| cause.is::<crate::retention::LockCallFailed>())
14789    {
14790        error
14791    } else {
14792        FoldRefusal::ProofIncomplete(format!("{error:#}")).into()
14793    }
14794}
14795
14796/// Which loader a fold uses on the record it reads again under its locks.
14797#[derive(Clone, Copy, PartialEq, Eq)]
14798enum Reload {
14799    /// Housekeeping: the record as saved, whatever schema wrote it
14800    /// ([`RunState::load_tolerant_under`]), exactly as `clean::fold_due` has
14801    /// always read it.
14802    Tolerant,
14803    /// An explicit fold (`magi fold`, the phone's route): the migrating loader
14804    /// the caller itself used ([`RunState::load_under`]), whose derived fields
14805    /// the preservation checks and the saved record then rest on.
14806    Strict,
14807}
14808
14809/// Why a record read under the locks is no longer the one that was locked.
14810fn reload_refusal(error: &anyhow::Error) -> FoldRefusal {
14811    if is_missing(error) {
14812        FoldRefusal::RecordGone
14813    } else {
14814        FoldRefusal::Unreadable(format!("{error:#}"))
14815    }
14816}
14817
14818/// What a test does after a fold's first look at the record and before it
14819/// takes the run's locks: where a deletion or a handover falls.
14820#[cfg(test)]
14821type BeforeLocks = Box<dyn FnOnce(&Path, &str)>;
14822
14823#[cfg(test)]
14824thread_local! {
14825    static BEFORE_LOCKS: std::cell::RefCell<Option<BeforeLocks>> =
14826        const { std::cell::RefCell::new(None) };
14827}
14828
14829/// Tear a run's worktrees and branches down.
14830///
14831/// `home` is where the updated `run.json` is saved (via
14832/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14833/// a housekeeping pass already has its own honest `home` handed to it, and
14834/// falling through to the global here would write back through whichever
14835/// directory some other process or test pinned into that `OnceLock` first,
14836/// not the one the caller actually resolved its `runs` and `state` from.
14837///
14838/// Every deletion decision is made on the record as it is on disk once the
14839/// owner lock and execution lease are held, not on the `state` the caller read
14840/// earlier: see [`fold_run_when`].
14841pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14842    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, false).await
14843}
14844
14845/// [`fold_run`] for the automatic callers, which decide whether the run may be
14846/// folded at all, and whether its winner goes too, from the run record.
14847///
14848/// `decide` is called on the caller's earlier read by the caller itself, and
14849/// again here on the record reloaded after taking the run's owner lock and
14850/// execution lease. A handover (`handover::release`) records `released_to` /
14851/// `released_branches` under that owner lock and removes the old worktree while
14852/// keeping the branch; a fold that acted on a record read before the handover
14853/// would delete the branch already given to the successor and save the stale
14854/// record over the handover. A run no longer eligible under the fresh record
14855/// is left alone and the refusal says why. The reload is tolerant of older
14856/// schemas, as `clean::fold_due` always was; the explicit entry points
14857/// ([`fold_run`], [`fold_run_overriding_recovery_retention`]) use the
14858/// migrating loader.
14859pub async fn fold_run_when(
14860    state: &mut RunState,
14861    home: &Path,
14862    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14863) -> Result<Vec<String>> {
14864    fold_run_with_policy(state, home, decide, Reload::Tolerant, false).await
14865}
14866
14867/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14868pub async fn fold_run_overriding_recovery_retention(
14869    state: &mut RunState,
14870    drop_winner: bool,
14871    home: &Path,
14872) -> Result<Vec<String>> {
14873    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, true).await
14874}
14875
14876async fn fold_run_with_policy(
14877    state: &mut RunState,
14878    home: &Path,
14879    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14880    reload: Reload,
14881    override_recovery_retention: bool,
14882) -> Result<Vec<String>> {
14883    // Cheap refusals on the caller's snapshot, before any lock is taken.
14884    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14885        && !override_recovery_retention
14886    {
14887        return Err(FoldRefusal::Retained(reason).into());
14888    }
14889    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14890        return Err(preservation_refusal());
14891    }
14892    // A fold needs the saved record of the run it locks. Nothing below may
14893    // bring a deleted run's directory back, and a fold is never entitled to
14894    // write a record of its own making: the caller's `state` is only a first
14895    // look, and every decision is made on what is read under the locks.
14896    let id = state.id.clone();
14897    let record = home.join("runs").join(&id).join("run.json");
14898    if !record.try_exists()? {
14899        return Err(FoldRefusal::RecordGone.into());
14900    }
14901    #[cfg(test)]
14902    if let Some(hook) = BEFORE_LOCKS.with(|hook| hook.borrow_mut().take()) {
14903        hook(home, &id);
14904    }
14905    // Serialize ordinary folding with the same starts/resumes as target-only
14906    // eviction. Otherwise a second janitor could remove the whole worktree
14907    // around a live output borrower even though target eviction was fenced.
14908    // Deleting a run record takes these same two locks (`clean::delete_run`).
14909    // The lock files are opened where they are and never created in a
14910    // directory that is not there: a refusal changes nothing, and the lock
14911    // files are never unlinked (`pr_head::owner_lock`).
14912    let _owner = crate::pr_head::owner_lock(home, &id).map_err(lock_refusal)?;
14913    // An override must use current durable ownership, not a pre-lock snapshot.
14914    // Its liveness assessment has to be made before this fold holds the
14915    // execution lease itself (a held lease reads as a live driver); the record
14916    // it is made on is checked for identity like every other, and the final
14917    // record, read once both locks are held, is checked again below.
14918    if override_recovery_retention {
14919        let current =
14920            RunState::load_under(&id, home).map_err(|e| anyhow::Error::from(reload_refusal(&e)))?;
14921        if current.id != id {
14922            return Err(FoldRefusal::RecordGone.into());
14923        }
14924        ensure_overridable(&current)?;
14925        let claimed = crate::daemon::is_working_on_other(home, &id, Timestamp::now())?;
14926        anyhow::ensure!(
14927            current.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14928            "run is live or its ownership is unknown"
14929        );
14930    }
14931    let _driver = crate::driver::maintenance(home, &id).map_err(lock_refusal)?;
14932    // Both locks are held, so no handover, driver claim, deletion or other
14933    // fold can change the record from here on: act on it, not on the earlier
14934    // read. There is no fallback to that read - a record that cannot be read
14935    // again, or is not this run's, ends the fold and touches nothing.
14936    let loaded = match reload {
14937        Reload::Tolerant => RunState::load_tolerant_under(&id, home),
14938        Reload::Strict => RunState::load_under(&id, home),
14939    };
14940    match loaded {
14941        Ok(fresh) if fresh.id == id => *state = fresh,
14942        Ok(_) => return Err(FoldRefusal::RecordGone.into()),
14943        Err(e) => return Err(reload_refusal(&e).into()),
14944    }
14945    if override_recovery_retention {
14946        ensure_overridable(state)?;
14947    }
14948    let drop_winner = decide(state)?;
14949    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14950        return Err(preservation_refusal());
14951    }
14952    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14953    if let Some(reason) = &retention_reason
14954        && !override_recovery_retention
14955    {
14956        return Err(FoldRefusal::Retained(reason.clone()).into());
14957    }
14958    let mut output_guards = Vec::new();
14959    for entry in std::fs::read_dir(state.worktree_root())
14960        .into_iter()
14961        .flatten()
14962        .flatten()
14963    {
14964        if entry.path().join(".git").is_file() {
14965            output_guards
14966                .push(crate::retention::OutputLease::take(&entry.path(), true).map_err(live_or)?);
14967        }
14968    }
14969    let repo = state.repo.clone();
14970    // CLI, Web and automatic cleanup all enter here, independently of
14971    // Runner::fold_losers. Protect deletion and shared config release too.
14972    //
14973    // Lock order. A handover (`handover::release`, a review taking a branch
14974    // over) holds repository coordination and then asks for this run's owner
14975    // lock; this fold already holds the owner lock. An automatic fold must not
14976    // *wait* for coordination here: the handover would wait for the owner lock
14977    // while the fold waited for coordination, and neither bound (the handover's
14978    // short retry, the fold's `timeout_resource_wait`) resolves that inversion
14979    // - the handover fails its startup, which costs the task an attempt. So it
14980    // asks once; when the lease is busy it gives way: everything it holds is
14981    // released on return, nothing was changed or saved, and the run is `live`
14982    // for this pass and judged again on a later one. The explicit callers
14983    // (`magi fold`, the phone's route) were asked for by a person and still
14984    // wait, bounded as before.
14985    let _coordination = if reload == Reload::Tolerant {
14986        match crate::repo_lock::SeatLease::operation_with(
14987            &repo,
14988            state.config.coordination.as_ref(),
14989            &crate::repo_lock::WaitPolicy::immediate(),
14990        )
14991        .await
14992        {
14993            Ok(lease) => lease,
14994            Err(e) => return Err(live_or(e)),
14995        }
14996    } else {
14997        let wait = repository_wait(state, None);
14998        match coordinate_operation(state, &repo, &wait).await {
14999            Ok(lease) => lease,
15000            Err(e) => {
15001                state.save_under(home)?;
15002                return Err(live_or(e));
15003            }
15004        }
15005    };
15006    // Confirmed merges dispose of their owned sources after durable evidence
15007    // capture. Preflight every source before removing anything. A failure of
15008    // this stage is, by what the stage is for, an incomplete proof - unless
15009    // it is only a lock somebody else holds.
15010    let _source_outputs = if retention_reason.is_some()
15011        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
15012    {
15013        match verify_merged_fold_sources(state, drop_winner, home).await {
15014            Ok(held) => held,
15015            Err(e) => return Err(source_proof_failure(e)),
15016        }
15017    } else {
15018        Vec::new()
15019    };
15020    if let Some(reason) = retention_reason {
15021        state.event(
15022            "fold",
15023            format!(
15024                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
15025                state.id
15026            ),
15027        );
15028        state.save_under(home)?;
15029    }
15030    let root = state.worktree_root();
15031    let winner = state.tally.as_ref().map(|t| t.winner);
15032    let mut removed = Vec::new();
15033    let isolated = crate::build_target::isolated(&state.config);
15034
15035    for i in 0..state.candidates.len() {
15036        let c = state.candidates[i].clone();
15037        let is_winner = Some(c.label) == winner;
15038        if is_winner && !drop_winner {
15039            continue;
15040        }
15041        let existed = c.worktree.exists();
15042        let target = fold_target(home, &root, &c.worktree, isolated);
15043        // A vanished directory can still have a Git registration that keeps
15044        // its branch checked out. Remove that registration before the branch.
15045        remove_preserved_worktree(&repo, &c.worktree).await?;
15046        reclaim_fold_target(home, target);
15047        if existed {
15048            removed.push(c.worktree.to_string_lossy().into_owned());
15049        }
15050        // A branch handed to a later run (and its pull request) is not this
15051        // run's to delete.
15052        let handed_over = state.released_branches.contains(&c.branch);
15053        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
15054            if !git::branch_delete(&repo, &c.branch).await? {
15055                bail!("candidate branch removal refused");
15056            }
15057            removed.push(c.branch.clone());
15058        }
15059        state.candidates[i].folded = true;
15060    }
15061
15062    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
15063        let path = name.path();
15064        let keep = !drop_winner
15065            && winner.is_some_and(|w| {
15066                path.file_name()
15067                    .is_some_and(|n| n == format!("cand-{w}").as_str())
15068            });
15069        if keep {
15070            continue;
15071        }
15072        let target = fold_target(home, &root, &path, isolated);
15073        remove_read_seat_worktree(state, &path).await?;
15074        reclaim_fold_target(home, target);
15075        removed.push(path.to_string_lossy().into_owned());
15076    }
15077
15078    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
15079    // judge worktrees, so once the loop above has cleared all of them out,
15080    // the parent is a bare directory nobody else was ever going to remove -
15081    // git only ever managed what was inside it. Left alone, one of these
15082    // accumulates per fully-folded run; the operator's own machine had 74.
15083    // `remove_if_empty` re-checks rather than assuming: a run whose winner
15084    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
15085    // so does anything a run never claimed that happens to share the bay.
15086    remove_if_empty(&root);
15087
15088    if state.enabled_worktree_config && drop_winner {
15089        // A release, not a raw disable: some sibling run in this repository
15090        // may still hold its own reference (see `git::acquire_worktree_config`),
15091        // and only the last release actually turns the setting back off.
15092        git::release_worktree_config(&repo).await.ok();
15093        state.enabled_worktree_config = false;
15094    }
15095    // What this fold itself found, written in the same locked save: nothing
15096    // left to remove and no bay on disk (a failed or erroring check is not
15097    // "gone"). The busy-time fold turn skips such a run only while the bay is
15098    // still confirmed absent; any fold that found work clears the mark.
15099    state.fold_settled_at =
15100        (removed.is_empty() && matches!(root.try_exists(), Ok(false))).then(Timestamp::now);
15101    state.save_under(home)?;
15102    Ok(removed)
15103}
15104
15105async fn verify_merged_fold_sources(
15106    state: &RunState,
15107    drop_winner: bool,
15108    home: &Path,
15109) -> Result<Vec<std::fs::File>> {
15110    let winner = state.tally.as_ref().map(|t| t.winner);
15111    let mut heads = BTreeSet::new();
15112    for candidate in &state.candidates {
15113        if Some(candidate.label) == winner && !drop_winner {
15114            continue;
15115        }
15116        anyhow::ensure!(
15117            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
15118            "candidate recovery source is outside the inventoried run root: {}",
15119            candidate.worktree.display()
15120        );
15121        match std::fs::symlink_metadata(&candidate.worktree) {
15122            Ok(_) => {}
15123            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15124            Err(error) => return Err(error.into()),
15125        }
15126        if !state.released_branches.contains(&candidate.branch)
15127            && git::branch_exists(&state.repo, &candidate.branch).await?
15128        {
15129            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
15130        }
15131    }
15132    let mut cargo_guards = Vec::new();
15133    let entries = match std::fs::read_dir(state.worktree_root()) {
15134        Ok(entries) => Some(entries),
15135        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
15136        Err(error) => return Err(error.into()),
15137    };
15138    for entry in entries.into_iter().flatten() {
15139        let path = entry?.path();
15140        let metadata = std::fs::symlink_metadata(&path)?;
15141        anyhow::ensure!(
15142            metadata.is_dir() && !metadata.file_type().is_symlink(),
15143            "non-directory or symlink recovery source retained: {}",
15144            path.display()
15145        );
15146        if !drop_winner
15147            && winner.is_some_and(|w| {
15148                path.file_name()
15149                    .is_some_and(|name| name == format!("cand-{w}").as_str())
15150            })
15151        {
15152            continue;
15153        }
15154        anyhow::ensure!(
15155            path.join(".git").is_file(),
15156            "unregistered recovery source retained: {}",
15157            path.display()
15158        );
15159        anyhow::ensure!(
15160            git::git(
15161                &path,
15162                &[
15163                    "status",
15164                    "--porcelain",
15165                    "--untracked-files=all",
15166                    "--ignored",
15167                    "--",
15168                    ".",
15169                    ":(exclude)target"
15170                ]
15171            )
15172            .await?
15173            .is_empty(),
15174            "source changes or ignored recovery files retained: {}",
15175            path.display()
15176        );
15177        match std::fs::symlink_metadata(path.join("target")) {
15178            Ok(_) => {
15179                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
15180            }
15181            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15182            Err(error) => return Err(error.into()),
15183        }
15184        for checkpoint in [
15185            "rebase-merge",
15186            "rebase-apply",
15187            "sequencer",
15188            "CHERRY_PICK_HEAD",
15189            "MERGE_HEAD",
15190            "REBASE_HEAD",
15191            "REVERT_HEAD",
15192            "BISECT_LOG",
15193            "AUTO_MERGE",
15194            "MERGE_MSG",
15195        ] {
15196            let location = git::git(
15197                &path,
15198                &[
15199                    "rev-parse",
15200                    "--path-format=absolute",
15201                    "--git-path",
15202                    checkpoint,
15203                ],
15204            )
15205            .await?;
15206            anyhow::ensure!(
15207                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
15208                if e.kind() == std::io::ErrorKind::NotFound),
15209                "Git recovery checkpoint retained: {checkpoint}"
15210            );
15211        }
15212        heads.insert(git::rev_parse(&path, "HEAD").await?);
15213    }
15214    crate::fold_evidence::preserve(state, home, &heads).await?;
15215
15216    Ok(cargo_guards)
15217}
15218
15219/// Remove `dir` if it exists and has nothing in it.
15220///
15221/// Best-effort and silent by design: a directory that is not empty (a run
15222/// whose winner is still parked there, a stray file some other process left)
15223/// is exactly the case this must refuse, and a directory that is already gone
15224/// is not a failure worth reporting either. `std::fs::remove_dir` itself
15225/// already refuses a non-empty directory, so the emptiness check below is
15226/// belt, not suspenders - it is what keeps this from ever attempting the
15227/// removal in the case that matters, rather than trusting `remove_dir`'s
15228/// error path to have no side effects if it ever changed.
15229fn remove_if_empty(dir: &Path) {
15230    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
15231        std::fs::remove_dir(dir).ok();
15232    }
15233}
15234
15235/// Severity of the worst open finding in the last review round, for reporting.
15236pub fn worst_open(state: &RunState) -> Option<Severity> {
15237    state
15238        .reviews
15239        .last()?
15240        .reviews
15241        .iter()
15242        .flat_map(|r| r.findings.iter())
15243        .map(|f| f.severity)
15244        .max()
15245}
15246
15247/// `[worktree] setup` hides its products per worktree, which needs
15248/// `extensions.worktreeConfig`. Taken once per run and released with the run's
15249/// worktrees, like the hook's; every place that runs setup calls this first.
15250async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
15251    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
15252        git::acquire_worktree_config(repo).await?;
15253        state.enabled_worktree_config = true;
15254    }
15255    Ok(())
15256}
15257
15258#[cfg(test)]
15259mod tests {
15260    #[tokio::test]
15261    async fn launcher_base_fetch_requires_remote_success() {
15262        let tmp = tempfile::tempdir().unwrap();
15263        let repo = tmp.path().join("repo");
15264        let remote = tmp.path().join("remote");
15265        std::fs::create_dir(&repo).unwrap();
15266        std::fs::create_dir(&remote).unwrap();
15267        git::git(&remote, &["init", "--bare", "-b", "main"])
15268            .await
15269            .unwrap();
15270        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
15271        git::git(
15272            &repo,
15273            &[
15274                "-c",
15275                "user.name=Fixture",
15276                "-c",
15277                "user.email=fixture@example.invalid",
15278                "commit",
15279                "--allow-empty",
15280                "-m",
15281                "fixture",
15282            ],
15283        )
15284        .await
15285        .unwrap();
15286        git::git(
15287            &repo,
15288            &["remote", "add", "origin", remote.to_str().unwrap()],
15289        )
15290        .await
15291        .unwrap();
15292        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
15293        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15294        assert_eq!(
15295            resolve_base(&repo, "main", "origin", None)
15296                .await
15297                .unwrap()
15298                .commit,
15299            head
15300        );
15301        #[cfg(unix)]
15302        {
15303            let policy: crate::config::Coordination = toml::from_str(
15304                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
15305            ).unwrap();
15306            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
15307            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
15308            let held = crate::repo_lock::SeatLease::operation_with(
15309                &repo,
15310                Some(&policy),
15311                &crate::repo_lock::WaitPolicy::default(),
15312            )
15313            .await
15314            .unwrap();
15315            assert!(held.is_some());
15316            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
15317            tokio::pin!(fetch);
15318            assert!(
15319                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
15320                    .await
15321                    .is_err()
15322            );
15323            assert!(
15324                !repo.join(".git/FETCH_HEAD").exists(),
15325                "no fetch before admission"
15326            );
15327            drop(held);
15328            let fetched = fetch.await.unwrap();
15329            assert_eq!(fetched.commit, head);
15330            assert_eq!(fetched.remote, "origin");
15331            assert_eq!(fetched.branch, "main");
15332        }
15333        // A surviving tracking ref is not successful fetch evidence.
15334        git::git(
15335            &repo,
15336            &[
15337                "remote",
15338                "set-url",
15339                "origin",
15340                tmp.path().join("missing").to_str().unwrap(),
15341            ],
15342        )
15343        .await
15344        .unwrap();
15345        let error = resolve_base(&repo, "main", "origin", None)
15346            .await
15347            .unwrap_err()
15348            .to_string();
15349        assert!(error.contains("cannot read origin/main"));
15350        assert!(error.contains("refusing to branch off"));
15351    }
15352
15353    #[test]
15354    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
15355        let leaked = vec!["chore(deps): update a crate".to_owned()];
15356        let own = "fix(daemon): apply a chosen action";
15357        assert!(should_retitle("", own, &leaked));
15358        assert!(should_retitle(
15359            &format!("{REVIEW_PROMPT_OPENING} `x`"),
15360            own,
15361            &leaked
15362        ));
15363        assert!(should_retitle(
15364            "chore: land candidate A of run 1",
15365            own,
15366            &leaked
15367        ));
15368        assert!(should_retitle(
15369            "magi: candidate A (uncommitted work)",
15370            own,
15371            &leaked
15372        ));
15373        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
15374        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
15375        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
15376    }
15377
15378    #[test]
15379    fn pr_merge_plan_creates_adopts_or_stops() {
15380        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
15381        assert_eq!(
15382            pr_merge_plan(Ok(land::OpenPr::One {
15383                url: "u".into(),
15384                title: "t".into()
15385            })),
15386            PrPlan::Adopt {
15387                url: "u".into(),
15388                title: "t".into()
15389            }
15390        );
15391        let PrPlan::Stop(many) =
15392            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
15393        else {
15394            panic!("many must stop");
15395        };
15396        assert!(many.contains('a') && many.contains('b'));
15397        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
15398            panic!("a failed lookup must stop");
15399        };
15400        assert!(err.contains("bad token"));
15401    }
15402
15403    use super::*;
15404    use crate::run::GateStatus;
15405    use std::collections::BTreeMap;
15406    use std::time::Duration;
15407
15408    fn conductor() -> AgentSpec {
15409        AgentSpec {
15410            id: "conductor".to_owned(),
15411            kind: crate::config::AgentKind::Command,
15412            model: None,
15413            command: vec!["true".to_owned()],
15414            extra_args: Vec::new(),
15415            env: BTreeMap::new(),
15416            prompt_delivery: None,
15417            max_turn_secs: None,
15418        }
15419    }
15420
15421    fn spec(id: &str) -> AgentSpec {
15422        AgentSpec {
15423            id: id.to_owned(),
15424            kind: crate::config::AgentKind::Command,
15425            model: None,
15426            command: vec!["true".to_owned()],
15427            extra_args: Vec::new(),
15428            env: BTreeMap::new(),
15429            prompt_delivery: None,
15430            max_turn_secs: None,
15431        }
15432    }
15433
15434    fn ids(xs: &[&str]) -> BTreeSet<String> {
15435        xs.iter().map(|s| (*s).to_owned()).collect()
15436    }
15437
15438    #[test]
15439    fn pick_successor_skips_an_agent_another_seat_holds() {
15440        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
15441        let roster = [spec("a"), spec("b"), spec("c")];
15442        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15443        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15444    }
15445
15446    #[test]
15447    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
15448        // The other seat started on c but was handed to d; c is free again.
15449        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
15450        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15451        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15452        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
15453        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
15454    }
15455
15456    #[test]
15457    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
15458        let roster = [spec("a"), spec("b")];
15459        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15460        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15461        let carried = ids(&["b"]);
15462        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
15463        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15464    }
15465
15466    #[test]
15467    fn pick_successor_returns_none_without_any_untried_successor() {
15468        let roster = [spec("a"), spec("b")];
15469        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
15470        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
15471        let carried = ids(&["a"]);
15472        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
15473    }
15474
15475    #[test]
15476    fn pick_successor_rescue_avoids_another_seats_occupant() {
15477        // b is a carried failure and free; a is held by the other seat.
15478        let roster = [spec("a"), spec("b"), spec("c")];
15479        let carried = ids(&["b", "c"]);
15480        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
15481        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15482    }
15483
15484    #[test]
15485    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
15486        let roster = [spec("a"), spec("b"), spec("c")];
15487        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
15488        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15489    }
15490
15491    #[test]
15492    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
15493        let roster = [spec("a"), spec("b"), spec("c")];
15494        let failed = ids(&["a", "b", "c"]);
15495        // Rescue looks at the whole roster, once per id, then runs out.
15496        let mut tried = ids(&["b"]);
15497        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15498        assert_eq!(first.id, "a");
15499        tried.insert(first.id.clone());
15500        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15501        assert_eq!(second.id, "c");
15502        tried.insert(second.id.clone());
15503        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
15504    }
15505
15506    #[test]
15507    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
15508        let roster = [spec("a"), spec("b")];
15509        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
15510        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15511    }
15512
15513    #[test]
15514    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15515        let roster = [spec("a"), spec("b"), spec("c")];
15516        let h = SeatHistory {
15517            failed: ids(&["a"]),
15518            last_ok: Some("b".to_owned()),
15519            last_fail: None,
15520        };
15521        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15522        // A last answerer that left the roster, or later failed, is ignored.
15523        let gone = SeatHistory {
15524            last_ok: Some("zzz".to_owned()),
15525            ..h.clone()
15526        };
15527        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15528        let failed = SeatHistory {
15529            failed: ids(&["a", "b"]),
15530            last_ok: Some("b".to_owned()),
15531            last_fail: None,
15532        };
15533        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15534    }
15535
15536    #[test]
15537    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15538        let first = SeatState::new("review-1", "alpha", 7);
15539        let next = handover_seat("review-1", "gamma", 7);
15540        assert_ne!(first.claude_session, next.claude_session);
15541    }
15542
15543    #[test]
15544    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15545        let mut state = state_with_summary("x", "y");
15546        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15547        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15548        assert_ne!(a.claude_session, b.claude_session);
15549    }
15550
15551    #[test]
15552    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15553        let roster = [spec("a"), spec("b")];
15554        let h = SeatHistory {
15555            failed: ids(&["a", "b"]),
15556            ..SeatHistory::default()
15557        };
15558        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15559        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15560        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15561    }
15562
15563    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15564    // fallback loop depends on to terminate: it must walk forward from the
15565    // seat's own position, never restart at the front of the roster, and it
15566    // must never hand back an id already tried, however many times that id
15567    // happens to appear.
15568
15569    #[test]
15570    fn failure_signature_ignores_numbers_and_paths() {
15571        assert_eq!(
15572            failure_signature("exited with Some(2) and no usable output"),
15573            failure_signature("exited with Some(137) and no usable output")
15574        );
15575        assert_eq!(
15576            failure_signature("process exited with no usable output (exit code 2)"),
15577            failure_signature("process exited with no usable output (exit code 137)")
15578        );
15579        for (old, new) in [
15580            (
15581                "exited with Some(2) and no usable output",
15582                "process exited with no usable output (exit code 2)",
15583            ),
15584            (
15585                "exited with None and no usable output",
15586                "process exited with no usable output (exit code unavailable)",
15587            ),
15588        ] {
15589            let previous = FailClass::Other(failure_signature(old));
15590            let current = FailClass::Other(failure_signature(new));
15591            assert_eq!(previous, current, "resumption retains the failure class");
15592            assert!(!should_hand_over(Some(&previous), &current));
15593        }
15594        assert_eq!(
15595            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15596            failure_signature("cannot open /var/x.txt: denied")
15597        );
15598        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15599    }
15600
15601    #[test]
15602    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15603        let other = FailClass::Other("x".into());
15604        assert!(should_hand_over(None, &FailClass::Quota));
15605        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15606        assert!(should_hand_over(
15607            Some(&FailClass::Timeout),
15608            &FailClass::Timeout
15609        ));
15610        assert!(should_hand_over(None, &other));
15611        assert!(!should_hand_over(Some(&other), &other));
15612        assert!(should_hand_over(
15613            Some(&other),
15614            &FailClass::Other("y".into())
15615        ));
15616        // A quota or timeout in between ends the run of identical failures.
15617        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15618        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15619    }
15620
15621    #[test]
15622    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15623        let a = SeatState::new("judge-1", "alpha", 7);
15624        let b = handover_seat("judge-1", "beta", 7);
15625        assert_ne!(a.claude_session, b.claude_session);
15626        assert_eq!(b.turns, 0);
15627    }
15628
15629    #[test]
15630    fn a_timeout_is_classified_apart_from_other_failures() {
15631        assert_eq!(
15632            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15633            Some(FailClass::Timeout)
15634        );
15635        assert!(matches!(
15636            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15637            Some(FailClass::Other(_))
15638        ));
15639    }
15640
15641    #[test]
15642    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15643        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15644        let tried = BTreeSet::from(["beta".to_owned()]);
15645        // beta sits at index 1; the next candidate is gamma, never alpha —
15646        // which is very likely a different candidate slot's own agent.
15647        let next = next_untried_in_roster(&roster, 1, &tried);
15648        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15649    }
15650
15651    #[test]
15652    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15653        let roster = vec![spec("alpha"), spec("beta")];
15654        let tried = BTreeSet::from(["beta".to_owned()]);
15655        // beta is the roster's last entry: nothing follows it, and alpha —
15656        // earlier in the roster, almost certainly a different candidate
15657        // slot's own agent — must not be reached by wrapping back to it.
15658        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15659    }
15660
15661    #[test]
15662    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15663        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15664        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15665        // beta (index 1) and gamma (index 2, the only entry after it) have
15666        // both been tried; alpha (index 0) never has, but it comes before
15667        // beta's own position, so there is nothing further for this seat.
15668        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15669    }
15670
15671    #[test]
15672    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15673        let roster = vec![spec("a"), spec("a"), spec("b")];
15674        let tried = BTreeSet::from(["a".to_owned()]);
15675        let next = next_untried_in_roster(&roster, 0, &tried);
15676        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15677    }
15678
15679    #[test]
15680    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15681        let roster = vec![spec("a"), spec("b")];
15682        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15683        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15684    }
15685
15686    #[test]
15687    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15688        let dir = tempfile::tempdir().unwrap();
15689        let bay = dir.path().join("ffff");
15690
15691        // Not there yet: nothing to do, nothing to panic on.
15692        remove_if_empty(&bay);
15693        assert!(!bay.exists());
15694
15695        // Something still inside - the winner's worktree, or a stray file -
15696        // keeps the directory standing.
15697        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15698        remove_if_empty(&bay);
15699        assert!(bay.exists(), "non-empty directory must survive");
15700
15701        // Once the last entry is gone, so is the directory itself.
15702        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15703        remove_if_empty(&bay);
15704        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15705    }
15706
15707    // `round_is_clean` is the exact decision this task fixed: a round with a
15708    // seat that never answered must not read the same as a round every seat
15709    // actually reviewed. These are deterministic and process-free by design —
15710    // the equivalent end-to-end check (a real reviewer timing out under a
15711    // live graph run) is a genuine race against wall-clock contention, and a
15712    // spawn slow enough to blow even a generous budget under a loaded test
15713    // run must not turn this specific regression check flaky.
15714
15715    #[test]
15716    fn a_full_panel_that_found_nothing_is_clean() {
15717        assert!(round_is_clean(
15718            0,
15719            true,
15720            2,
15721            2,
15722            0,
15723            IncompleteReviewPolicy::Block
15724        ));
15725    }
15726
15727    #[test]
15728    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15729        assert!(!round_is_clean(
15730            0,
15731            true,
15732            1,
15733            2,
15734            0,
15735            IncompleteReviewPolicy::Block
15736        ));
15737    }
15738
15739    #[test]
15740    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15741        assert!(!round_is_clean(
15742            1,
15743            true,
15744            1,
15745            2,
15746            0,
15747            IncompleteReviewPolicy::Warn
15748        ));
15749    }
15750
15751    #[test]
15752    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15753        assert!(round_is_clean(
15754            0,
15755            true,
15756            1,
15757            2,
15758            0,
15759            IncompleteReviewPolicy::Warn
15760        ));
15761    }
15762
15763    #[test]
15764    fn a_full_panel_with_an_open_finding_is_not_clean() {
15765        assert!(!round_is_clean(
15766            1,
15767            true,
15768            2,
15769            2,
15770            0,
15771            IncompleteReviewPolicy::Block
15772        ));
15773    }
15774
15775    #[test]
15776    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15777        assert!(!round_is_clean(
15778            0,
15779            false,
15780            2,
15781            2,
15782            0,
15783            IncompleteReviewPolicy::Block
15784        ));
15785    }
15786
15787    // The stall this task closes: under the default `block` policy, a seat
15788    // missing only because it was rate limited must not force a wait for a
15789    // session limit that will not lift by the next round. `round_is_clean`
15790    // is where that quorum carve-out lives; the review loop around it never
15791    // changes what a reviewer's vote or a finding's severity means.
15792
15793    #[test]
15794    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15795        // 1 of 2 answered, and the one missing was quota'd — the exact
15796        // "review-2 rate limited (quota)" shape from the field report.
15797        assert!(round_is_clean(
15798            0,
15799            true,
15800            1,
15801            2,
15802            1,
15803            IncompleteReviewPolicy::Block
15804        ));
15805    }
15806
15807    #[test]
15808    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15809        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15810        // not a quota loss (`quota_missing` stays 0) — worth another try.
15811        assert!(!round_is_clean(
15812            0,
15813            true,
15814            1,
15815            2,
15816            0,
15817            IncompleteReviewPolicy::Block
15818        ));
15819    }
15820
15821    #[test]
15822    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15823        assert!(!round_is_clean(
15824            1,
15825            true,
15826            1,
15827            2,
15828            1,
15829            IncompleteReviewPolicy::Block
15830        ));
15831        assert!(!round_is_clean(
15832            0,
15833            false,
15834            1,
15835            2,
15836            1,
15837            IncompleteReviewPolicy::Block
15838        ));
15839    }
15840
15841    #[test]
15842    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15843        // Every seat quota'd, nobody answered: there is no panel to decide
15844        // on, so this must fall through to the existing block-and-retry
15845        // fallback rather than call an unreviewed patch clean.
15846        assert!(!round_is_clean(
15847            0,
15848            true,
15849            0,
15850            2,
15851            2,
15852            IncompleteReviewPolicy::Block
15853        ));
15854    }
15855
15856    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15857        CommandOutcome {
15858            command: "test".to_owned(),
15859            code,
15860            output_tail: String::new(),
15861            duration_ms: 0,
15862            resource_blocked,
15863            ..Default::default()
15864        }
15865    }
15866
15867    #[cfg(unix)]
15868    #[tokio::test]
15869    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15870        ask_test_home();
15871        let temp = tempfile::tempdir().unwrap();
15872        let mut runner = runner_at(RunStatus::Gating);
15873        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15874        let commands = vec![
15875            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15876            "touch must-not-run".to_owned(),
15877        ];
15878        let (outcomes, retried, pids) = run_e2e_with_retry(
15879            &mut runner.state,
15880            &shell,
15881            &commands,
15882            temp.path(),
15883            Duration::from_secs(5),
15884            "fixture",
15885            None,
15886        )
15887        .await;
15888        assert_eq!(outcomes.len(), 1);
15889        assert!(outcomes[0].resource_blocked);
15890        assert!(!outcomes[0].build_failed());
15891        assert!(!retried);
15892        assert!(pids.is_empty());
15893        assert!(!temp.path().join("must-not-run").exists());
15894        assert_eq!(
15895            runner.state.resource_block.as_ref().unwrap().kind,
15896            "incremental cache admission"
15897        );
15898    }
15899
15900    #[test]
15901    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15902        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15903        assert!(
15904            !verify_inconclusive(&[outcome(Some(1), false)]),
15905            "an ordinary failure is still evidence about the patch"
15906        );
15907        assert!(verify_inconclusive(&[outcome(None, true)]));
15908        assert!(
15909            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15910            "one inconclusive outcome taints the whole batch"
15911        );
15912        assert!(!verify_inconclusive(&[]));
15913    }
15914
15915    #[tokio::test]
15916    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15917        // Alive for the first two checks, then dead - confirms the loop
15918        // actually re-polls rather than deciding once and sleeping out the
15919        // ceiling regardless.
15920        let calls = std::sync::atomic::AtomicUsize::new(0);
15921        let started = Instant::now();
15922        wait_for_pids_with(
15923            &[123],
15924            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15925            Duration::from_millis(5),
15926            Duration::from_secs(5),
15927        )
15928        .await;
15929        assert!(
15930            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15931            "must keep checking rather than deciding on the first answer"
15932        );
15933        assert!(
15934            started.elapsed() < Duration::from_secs(1),
15935            "must return the moment it is confirmed dead, not wait out the ceiling"
15936        );
15937    }
15938
15939    #[tokio::test]
15940    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15941        let started = Instant::now();
15942        wait_for_pids_with(
15943            &[123],
15944            |_| true, // never reports dead
15945            Duration::from_millis(5),
15946            Duration::from_millis(30),
15947        )
15948        .await;
15949        let elapsed = started.elapsed();
15950        assert!(
15951            elapsed >= Duration::from_millis(30),
15952            "must not give up before its own ceiling: {elapsed:?}"
15953        );
15954        assert!(
15955            elapsed < Duration::from_secs(1),
15956            "must not wait past its own ceiling either: {elapsed:?}"
15957        );
15958    }
15959
15960    #[tokio::test]
15961    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
15962        let started = Instant::now();
15963        wait_for_pids_with(
15964            &[],
15965            |_| true,
15966            Duration::from_secs(5),
15967            Duration::from_secs(5),
15968        )
15969        .await;
15970        assert!(
15971            started.elapsed() < Duration::from_millis(200),
15972            "an empty pid list has nothing to confirm"
15973        );
15974    }
15975
15976    // `review_conclusion` is the exact decision the review hand-off task
15977    // fixed: a round budget spent (or a tree that stopped moving) must not
15978    // collapse into `Blocked` regardless of what verification actually
15979    // said. Deterministic and process-free for the same reason the
15980    // `round_is_clean` family above is.
15981    fn review_round(
15982        clean: bool,
15983        blocking: usize,
15984        answered: usize,
15985        expected: usize,
15986        progressed: bool,
15987        e2e_ok: bool,
15988    ) -> ReviewRound {
15989        ReviewRound {
15990            round: 1,
15991            head: "h".to_owned(),
15992            verified_head: None,
15993            verified_at: None,
15994            reviews: Vec::new(),
15995            e2e: vec![CommandOutcome {
15996                command: "test".to_owned(),
15997                code: Some(if e2e_ok { 0 } else { 1 }),
15998                output_tail: String::new(),
15999                duration_ms: 0,
16000                resource_blocked: false,
16001                ..Default::default()
16002            }],
16003            verify_retried: false,
16004            e2e_deferred: false,
16005            e2e_defer_reason: None,
16006            fix: None,
16007            blocking,
16008            answered,
16009            expected,
16010            clean,
16011            progressed,
16012            vote_split: false,
16013            reconsideration: Vec::new(),
16014            verdict: None,
16015        }
16016    }
16017
16018    #[test]
16019    fn review_conclusion_is_none_when_nothing_has_run() {
16020        assert_eq!(review_conclusion(&[], 3), None);
16021    }
16022
16023    #[test]
16024    fn review_conclusion_is_none_while_rounds_remain() {
16025        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
16026        assert_eq!(review_conclusion(&rounds, 3), None);
16027    }
16028
16029    #[test]
16030    fn review_conclusion_is_gating_once_a_round_is_clean() {
16031        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
16032        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
16033    }
16034
16035    #[test]
16036    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
16037        let rounds = vec![
16038            review_round(false, 1, 2, 2, true, true),
16039            review_round(false, 1, 2, 2, true, true),
16040        ];
16041        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
16042    }
16043
16044    #[test]
16045    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
16046        let rounds = vec![
16047            review_round(false, 1, 2, 2, true, true),
16048            review_round(false, 1, 2, 2, true, false),
16049        ];
16050        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
16051    }
16052
16053    #[test]
16054    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
16055        // Magi never got a command to run against this round's own head — a
16056        // resource-blocked attempt, not a red one — so this must never
16057        // settle on `Blocked` the way a genuine e2e failure would. `None`
16058        // here is what tells `Runner::review_loop` to retry the check
16059        // itself rather than trust this cheap recomputation with a verdict
16060        // it cannot actually produce.
16061        let mut blocked = review_round(false, 1, 2, 2, true, false);
16062        blocked.e2e[0].resource_blocked = true;
16063        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
16064        assert_eq!(review_conclusion(&rounds, 2), None);
16065    }
16066
16067    #[test]
16068    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
16069        // Missing input, not a verified tree — never a hand-off candidate.
16070        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
16071        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
16072    }
16073
16074    #[test]
16075    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
16076        let rounds = vec![
16077            review_round(false, 1, 2, 2, false, true),
16078            review_round(false, 1, 2, 2, false, true),
16079        ];
16080        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
16081    }
16082
16083    fn secs(n: u64) -> Duration {
16084        Duration::from_secs(n)
16085    }
16086
16087    /// A throwaway repo with one commit on `main`, for tests that need `merge`
16088    /// to make real (and, if it runs at all, real*ly fail*) git calls.
16089    #[tokio::test]
16090    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
16091        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
16092        if std::env::var_os(CHILD).is_none() {
16093            // Other tests reconcile every run in the process-global home,
16094            // briefly taking owner locks. This ancestry test expects an idle
16095            // predecessor, so give it its own process and pinned test home.
16096            let output = std::process::Command::new(std::env::current_exe().unwrap())
16097                .args([
16098                    "--exact",
16099                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
16100                    "--nocapture",
16101                ])
16102                .env(CHILD, "1")
16103                .env_remove("MAGI_WORKER_HOME")
16104                .env_remove("MAGI_WORKER_ID")
16105                .output()
16106                .unwrap();
16107            assert!(
16108                output.status.success()
16109                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
16110                "{}\n{}",
16111                String::from_utf8_lossy(&output.stdout),
16112                String::from_utf8_lossy(&output.stderr)
16113            );
16114            return;
16115        }
16116        ask_test_home();
16117        let tmp = tempfile::tempdir().unwrap();
16118        let repo = tmp.path().join("repo");
16119        std::fs::create_dir_all(&repo).unwrap();
16120        init_repo(&repo);
16121        let g = |args: &[&str]| {
16122            let out = std::process::Command::new("git")
16123                .args(args)
16124                .current_dir(&repo)
16125                .quiet()
16126                .output()
16127                .unwrap();
16128            assert!(
16129                out.status.success(),
16130                "{}",
16131                String::from_utf8_lossy(&out.stderr)
16132            );
16133        };
16134        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16135        g(&["checkout", "-b", "historical"]);
16136        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
16137        g(&["add", "."]);
16138        g(&["commit", "-m", "old alternative"]);
16139        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
16140        g(&["checkout", "-b", "magi/task-selected", &base]);
16141        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
16142        g(&["add", "."]);
16143        g(&["commit", "-m", "measurement infrastructure"]);
16144        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
16145        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
16146        g(&["add", "."]);
16147        g(&["commit", "-m", "dependent implementation"]);
16148        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
16149        g(&["checkout", "main"]);
16150        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
16151        g(&["add", "."]);
16152        g(&["commit", "-m", "unrelated base change"]);
16153        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
16154        let origin = tmp.path().join("origin.git");
16155        g(&[
16156            "clone",
16157            "--bare",
16158            repo.to_str().unwrap(),
16159            origin.to_str().unwrap(),
16160        ]);
16161        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
16162        g(&["fetch", "origin"]);
16163        let selection = crate::pr_recovery::Selection {
16164            url: "https://example.test/project/pull/1".into(),
16165            branch: "magi/task-selected".into(),
16166            head: head.clone(),
16167            source_head: None,
16168            source_run: None,
16169            source_proof: None,
16170            disposition: Some(crate::pr_recovery::Disposition::Review),
16171            instruction: "preserve measured behavior".into(),
16172            approved_at: jiff::Timestamp::now(),
16173        };
16174        let mut template = runner_at(RunStatus::Reviewing);
16175        template.state.repo = repo.clone();
16176        template.state.base_commit = current.clone();
16177        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16178        template.state.origin = Some(crate::run::Origin::queue("selected"));
16179        template.state.pr_head = Some(selection.branch.clone());
16180        template.state.pr_recovery = Some(selection.clone());
16181        let mut runner =
16182            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
16183                .await
16184                .unwrap();
16185        let wt = runner.state.winner().unwrap().worktree.clone();
16186        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
16187        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
16188        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
16189        assert!(runner.state.seeds.is_empty());
16190        assert_eq!(runner.state.instruction, "preserve measured behavior");
16191        runner.sync_to_base().await.unwrap();
16192        assert_eq!(
16193            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
16194            "prerequisite"
16195        );
16196        assert_eq!(
16197            std::fs::read_to_string(wt.join("implementation")).unwrap(),
16198            "measured implementation"
16199        );
16200        assert_eq!(
16201            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
16202            "current main change"
16203        );
16204        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16205        assert_eq!(
16206            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16207            head
16208        );
16209
16210        // A failed selected-source setup stays inspectable, never resumable as a new competition.
16211        let mut partial = runner_at(RunStatus::Reviewing);
16212        partial.state.repo = repo.clone();
16213        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
16214        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
16215            run: Some("exit 1".into()),
16216            ..Default::default()
16217        }];
16218        let selection = runner.state.pr_recovery.clone().unwrap();
16219        partial.state.pr_recovery = Some(selection.clone());
16220        partial.state.pr_head = Some(selection.branch.clone());
16221        partial.state.origin = Some(crate::run::Origin::queue("selected"));
16222        let id = partial.state.id.clone();
16223        let error = match Runner::open_selected(
16224            &repo,
16225            partial.state,
16226            partial.roles,
16227            1,
16228            runner.state.base_commit.clone(),
16229            selection,
16230        )
16231        .await
16232        {
16233            Ok(_) => panic!("setup must fail"),
16234            Err(e) => e,
16235        };
16236        assert_eq!(
16237            error
16238                .downcast_ref::<crate::run::StartupFailure>()
16239                .unwrap()
16240                .run,
16241            id
16242        );
16243        let failed = RunState::load(&id).unwrap();
16244        assert_eq!(failed.status, RunStatus::Failed);
16245        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
16246        assert!(Runner::resume(&id).is_err());
16247        runner.state.status = RunStatus::Ready;
16248        runner.state.driver_exited = true;
16249        runner.state.save().unwrap();
16250        let mut retry = runner_at(RunStatus::Reviewing);
16251        retry.state.repo = repo.clone();
16252        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
16253        let mut reselected = runner.state.pr_recovery.clone().unwrap();
16254        reselected.approved_at = jiff::Timestamp::now();
16255        retry.state.origin = Some(crate::run::Origin::queue("selected"));
16256        retry.state.pr_head = Some(reselected.branch.clone());
16257        retry.state.pr_recovery = Some(reselected.clone());
16258        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
16259            .await
16260            .unwrap();
16261        let restarted = Runner::open_selected(
16262            &repo,
16263            retry.state,
16264            retry.roles,
16265            1,
16266            runner.state.base_commit.clone(),
16267            reselected,
16268        )
16269        .await
16270        .unwrap();
16271        assert_eq!(
16272            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
16273                .await
16274                .unwrap(),
16275            head
16276        );
16277        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16278        assert_eq!(
16279            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16280            head
16281        );
16282    }
16283
16284    #[tokio::test]
16285    #[cfg(unix)]
16286    async fn fallback_and_interrupted_restoration_require_coordination() {
16287        use std::os::fd::AsRawFd as _;
16288        ask_test_home();
16289        let tmp = tempfile::tempdir().unwrap();
16290        let mut runner = registered_runner(tmp.path()).await;
16291        runner.state.config.graph.timeout_resource_wait = 1;
16292        let winner = runner.state.candidates[0].clone();
16293        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16294        let leftover = winner.worktree.join("leftover");
16295        std::fs::write(&leftover, "untrusted edits").unwrap();
16296        let next = tmp.path().join("next-fixer");
16297        let mut failed = spec("first");
16298        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
16299        let mut successor = spec("second");
16300        successor.command = vec![
16301            "sh".into(),
16302            "-c".into(),
16303            format!("touch '{}'; echo done", next.display()),
16304        ];
16305        let attempts = vec![
16306            (failed.clone(), "first".into()),
16307            (successor.clone(), "second".into()),
16308        ];
16309        let lock_path = runner.state.repo.join(".git/updater.lock");
16310        let external = std::fs::File::create(&lock_path).unwrap();
16311        assert_eq!(
16312            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16313            0
16314        );
16315        let artifacts = tmp.path().join("artifacts");
16316        let build = |spec, seat| SeatJob {
16317            spec,
16318            seat,
16319            cwd: winner.worktree.clone(),
16320            prompt: "fixture".into(),
16321            timeout: Duration::from_secs(10),
16322            allow_write: true,
16323            sessions: false,
16324            artifacts: artifacts.clone(),
16325            stem: "fix".into(),
16326            handover: None,
16327        };
16328        let (_, _, out) = runner
16329            .ask_fixer_among(
16330                attempts.clone(),
16331                "graft",
16332                None,
16333                Some((&winner.worktree, &head)),
16334                build,
16335            )
16336            .await;
16337        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
16338        assert!(leftover.exists(), "contention must prevent clean");
16339        assert!(!next.exists());
16340        assert!(runner.state.handovers.is_empty());
16341        // Early interrupted-repair rollback uses the same protected route.
16342        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16343            from_run: "earlier".into(),
16344            generation: 1,
16345            mode: crate::recovery::Mode::VerifyRepair,
16346            reasons: Vec::new(),
16347            reviewed_head: None,
16348            rounds: Vec::new(),
16349            open_findings: Vec::new(),
16350            evidence: None,
16351            criteria_inherited: true,
16352            repair: crate::recovery::Repair::Started {
16353                before: head.clone(),
16354            },
16355        });
16356        assert!(
16357            runner
16358                .recovery_repair(&winner)
16359                .await
16360                .unwrap_err()
16361                .is::<crate::repo_lock::ResourceBlocked>()
16362        );
16363        assert!(matches!(
16364            runner.state.recovery.as_ref().unwrap().repair,
16365            crate::recovery::Repair::Started { .. }
16366        ));
16367        assert!(leftover.exists());
16368        drop(external);
16369        runner.recovery_repair(&winner).await.unwrap();
16370        assert!(!leftover.exists());
16371        assert!(matches!(
16372            runner.state.recovery.as_ref().unwrap().repair,
16373            crate::recovery::Repair::Done { .. }
16374        ));
16375        // A hard lock-open failure also leaves HEAD and untracked work intact.
16376        std::fs::remove_file(&lock_path).unwrap();
16377        std::fs::create_dir(&lock_path).unwrap();
16378        std::fs::write(&leftover, "untrusted edits").unwrap();
16379        let (_, _, out) = runner
16380            .ask_fixer_among(
16381                attempts,
16382                "graft",
16383                None,
16384                Some((&winner.worktree, &head)),
16385                build,
16386            )
16387            .await;
16388        assert!(matches!(out, AgentOutcome::Failed(_)));
16389        assert!(leftover.exists());
16390        assert!(!next.exists());
16391        assert_eq!(
16392            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16393            head
16394        );
16395    }
16396
16397    #[cfg(unix)]
16398    async fn registered_runner(root: &Path) -> Runner {
16399        repository_runner(root, crate::config::test_coordination()).await
16400    }
16401
16402    async fn repository_runner(
16403        root: &Path,
16404        coordination: Option<crate::config::Coordination>,
16405    ) -> Runner {
16406        ask_test_home();
16407        let repo = root.join("repo");
16408        std::fs::create_dir_all(&repo).unwrap();
16409        init_repo(&repo);
16410        if coordination.is_some() {
16411            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16412        }
16413        let mut runner = runner_at(RunStatus::Prep);
16414        runner.state.repo = repo.clone();
16415        runner.state.config.coordination = coordination;
16416        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16417        runner.state.config.graph.worktree_root = Some(root.join("wt"));
16418        runner.state.config.graph.advise = false;
16419        runner.roles.implementers = vec![spec("implement")];
16420        runner.roles.judges = vec![spec("judge")];
16421        runner.prep().await.unwrap();
16422        runner
16423    }
16424
16425    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
16426
16427    #[tokio::test]
16428    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
16429        let tmp = tempfile::tempdir().unwrap();
16430        let mut runner = repository_runner(tmp.path(), None).await;
16431        let prompts = runner.state.config.prompts.clone();
16432        let run = runner.state.id.clone();
16433        let ctx = WaveCtx {
16434            carry_seats: false,
16435            pauses: None,
16436            run: &run,
16437            node: "advise",
16438            prompts: &prompts,
16439            cache: None,
16440            round: None,
16441        };
16442        let jobs: Vec<_> = ["alpha", "beta"]
16443            .into_iter()
16444            .map(|id| SeatJob {
16445                spec: scripted(id, AUTH_OUTAGE),
16446                seat: SeatState::new(id, id, 7),
16447                prompt: "propose".into(),
16448                cwd: runner.state.candidates[0].worktree.clone(),
16449                timeout: Duration::from_secs(10),
16450                allow_write: false,
16451                sessions: false,
16452                artifacts: agent::artifacts_dir(&runner.state.dir()),
16453                stem: id.into(),
16454                handover: None,
16455            })
16456            .collect();
16457        let mut losses = Vec::new();
16458        let results = ask_wave_with(
16459            jobs.clone(),
16460            runner.sem.clone(),
16461            2,
16462            &[],
16463            &ctx,
16464            &mut losses,
16465            &mut runner.state,
16466            &|_: &str| Ok(()),
16467        )
16468        .await;
16469        assert!(
16470            results
16471                .iter()
16472                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
16473        );
16474        assert_eq!(runner.state.quota.len(), 2);
16475        assert!(
16476            runner
16477                .state
16478                .quota
16479                .iter()
16480                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
16481        );
16482        assert!(!runner.state.advise_attempted);
16483        runner.stop_for_resource().unwrap();
16484        assert_eq!(runner.state.status, RunStatus::Blocked);
16485        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
16486        assert_eq!(
16487            runner.state.resource_block.as_ref().unwrap().kind,
16488            "agent authentication"
16489        );
16490        // A machine loss followed by an ordinary failure is not evidence
16491        // that the whole node was unavailable, and must not earn a refund.
16492        runner.state.resource_block = None;
16493        runner.state.quota.clear();
16494        let mut mixed = jobs;
16495        mixed[1].spec.command = vec!["false".into()];
16496        let results = ask_wave_with(
16497            mixed,
16498            runner.sem.clone(),
16499            0,
16500            &[],
16501            &ctx,
16502            &mut losses,
16503            &mut runner.state,
16504            &|_: &str| Ok(()),
16505        )
16506        .await;
16507        assert!(results.iter().all(|(_, res, _)| res.is_err()));
16508        assert!(runner.state.resource_block.is_none());
16509        assert_eq!(losses.len(), 1);
16510    }
16511
16512    #[tokio::test]
16513    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16514        let tmp = tempfile::tempdir().unwrap();
16515        let mut runner = repository_runner(tmp.path(), None).await;
16516        let implementer = scripted("implement", AUTH_OUTAGE);
16517        runner.roles.implementers = vec![implementer.clone()];
16518        runner.state.config.agents = vec![implementer];
16519        runner.implement().await.unwrap();
16520        assert_eq!(runner.state.status, RunStatus::Blocked);
16521        assert_eq!(runner.state.quota.len(), 1);
16522        assert_eq!(
16523            runner.state.quota[0].cause,
16524            agent::QuotaCause::Authentication
16525        );
16526        let candidate = &runner.state.candidates[0];
16527        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16528        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16529    }
16530
16531    #[tokio::test]
16532    #[cfg(unix)]
16533    async fn parked_implementer_persists_completed_work() {
16534        for registered in [false, true] {
16535            let tmp = tempfile::tempdir().unwrap();
16536            let mut runner = registered_runner(tmp.path()).await;
16537            if !registered {
16538                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16539            }
16540            let marker = tmp.path().join("started");
16541            let release = tmp.path().join("release");
16542            let mut implementer = spec("implement");
16543            implementer.command = vec![
16544                "sh".into(),
16545                "-c".into(),
16546                format!(
16547                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16548                    marker.display(),
16549                    release.display()
16550                ),
16551            ];
16552            runner.roles.implementers = vec![implementer.clone()];
16553            runner.state.config.agents = vec![implementer];
16554            let pause = runner.pause.clone();
16555            let (result, ()) = tokio::join!(runner.implement(), async {
16556                tokio::time::timeout(Duration::from_secs(10), async {
16557                    while !marker.exists() {
16558                        tokio::time::sleep(Duration::from_millis(10)).await;
16559                    }
16560                })
16561                .await
16562                .unwrap();
16563                pause.park();
16564                std::fs::write(&release, "go").unwrap();
16565            });
16566            result.unwrap();
16567            let candidate = &runner.state.candidates[0];
16568            assert!(candidate.commits > 0, "{candidate:?}");
16569            assert!(candidate.summary.contains("saved-result"));
16570            assert_eq!(candidate.files, 1);
16571            let before = candidate.commits;
16572            runner.implement().await.unwrap();
16573            assert_eq!(runner.state.candidates[0].commits, before);
16574        }
16575    }
16576
16577    #[tokio::test]
16578    #[cfg(unix)]
16579    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16580        let tmp = tempfile::tempdir().unwrap();
16581        let mut runner = registered_runner(tmp.path()).await;
16582        let winner = runner.state.candidates[0].clone();
16583        let cache = tmp.path().join("cache");
16584        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16585        runner.state.config.graph.timeout_resource_wait = 0;
16586        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16587        let crate::cache::AcquireOutcome::Acquired(held) =
16588            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16589        else {
16590            panic!("cache must be free")
16591        };
16592        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16593            from_run: "earlier".into(),
16594            generation: 1,
16595            mode: crate::recovery::Mode::VerifyRepair,
16596            reasons: Vec::new(),
16597            reviewed_head: None,
16598            rounds: Vec::new(),
16599            open_findings: Vec::new(),
16600            evidence: None,
16601            criteria_inherited: true,
16602            repair: crate::recovery::Repair::NotStarted,
16603        });
16604        runner.recovery_repair(&winner).await.unwrap();
16605        assert!(matches!(
16606            runner.state.recovery.as_ref().unwrap().repair,
16607            crate::recovery::Repair::WaitingForRestore { .. }
16608        ));
16609        drop(held);
16610        runner.state.resource_block = None;
16611        runner.state.config.graph.timeout_resource_wait = 1;
16612        runner.recovery_repair(&winner).await.unwrap();
16613        assert!(matches!(
16614            runner.state.recovery.as_ref().unwrap().repair,
16615            crate::recovery::Repair::Done { .. }
16616        ));
16617        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16618    }
16619
16620    #[tokio::test]
16621    #[cfg(unix)]
16622    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16623        use std::os::fd::AsRawFd as _;
16624        for graft in [false, true] {
16625            let tmp = tempfile::tempdir().unwrap();
16626            let mut runner = registered_runner(tmp.path()).await;
16627            runner.state.config.graph.timeout_resource_wait = 1;
16628            let winner = runner.state.candidates[0].clone();
16629            let marker = tmp.path().join("fixer-started");
16630            let mut fixer = spec("fixer");
16631            fixer.command = vec![
16632                "sh".into(),
16633                "-c".into(),
16634                format!("echo started >> '{}'; echo done", marker.display()),
16635            ];
16636            runner.roles.fixer = Some(vec![fixer]);
16637            if graft {
16638                let mut loser = winner.clone();
16639                loser.label = 'B';
16640                loser.index = 1;
16641                runner.state.candidates.push(loser);
16642                runner.state.config.graph.graft_runner_up = true;
16643                runner.state.tally = Some(Tally {
16644                    first_choice: BTreeMap::new(),
16645                    borda: BTreeMap::new(),
16646                    winner: winner.label,
16647                    rankings: 1,
16648                    unanimous_initial: true,
16649                    deliberated: false,
16650                    changed_votes: 0,
16651                    unanimous_final: true,
16652                    tie_break: None,
16653                    judges: 1,
16654                    present: 1,
16655                    quorum: 1,
16656                    met_quorum: true,
16657                    uncontested: None,
16658                });
16659                runner.state.judgements.push(crate::run::Judgement {
16660                    judge: 1,
16661                    seat: "judge-1".into(),
16662                    agent: "judge".into(),
16663                    ranking: vec![winner.label, 'B'],
16664                    reasons: BTreeMap::new(),
16665                    confidence: None,
16666                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16667                    order: vec![0, 1],
16668                    failed: None,
16669                    duration_ms: 0,
16670                });
16671            } else {
16672                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16673                    from_run: "earlier".into(),
16674                    generation: 1,
16675                    mode: crate::recovery::Mode::VerifyRepair,
16676                    reasons: Vec::new(),
16677                    reviewed_head: None,
16678                    rounds: Vec::new(),
16679                    open_findings: Vec::new(),
16680                    evidence: None,
16681                    criteria_inherited: true,
16682                    repair: crate::recovery::Repair::NotStarted,
16683                });
16684            }
16685            let reader = crate::repo_lock::SeatLease::for_checkout(
16686                &winner.worktree,
16687                false,
16688                crate::config::test_coordination().as_ref(),
16689            )
16690            .await
16691            .unwrap();
16692            let pause = runner.pause.clone();
16693            let (result, ()) = tokio::join!(
16694                async {
16695                    if graft {
16696                        runner.graft().await
16697                    } else {
16698                        runner.recovery_repair(&winner).await
16699                    }
16700                },
16701                async {
16702                    tokio::time::sleep(Duration::from_millis(100)).await;
16703                    pause.park();
16704                }
16705            );
16706            result.unwrap();
16707            assert!(!marker.exists(), "a blocked seat must not spawn");
16708            // Exercise the persisted state, as a binary replacement/resume does.
16709            runner.state = RunState::load(&runner.state.id).unwrap();
16710            if graft {
16711                assert_eq!(
16712                    runner.state.graft.as_ref().unwrap().outcome,
16713                    GraftOutcome::WaitingForRestore
16714                );
16715            } else {
16716                assert!(matches!(
16717                    runner.state.recovery.as_ref().unwrap().repair,
16718                    crate::recovery::Repair::WaitingForRestore { .. }
16719                ));
16720            }
16721            drop(reader);
16722            runner.pause = Pause::new();
16723            runner.state.resource_block = None;
16724            // Deferred restoration must still respect an external lock owner.
16725            let external =
16726                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16727            assert_eq!(
16728                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16729                0
16730            );
16731            let leftover = winner.worktree.join("leftover");
16732            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16733            let result = if graft {
16734                runner.graft().await
16735            } else {
16736                runner.recovery_repair(&winner).await
16737            };
16738            assert!(
16739                result
16740                    .unwrap_err()
16741                    .is::<crate::repo_lock::ResourceBlocked>()
16742            );
16743            assert!(leftover.exists());
16744            assert!(!marker.exists());
16745            drop(external);
16746            runner.state.resource_block = None;
16747            let result = if graft {
16748                runner.graft().await
16749            } else {
16750                runner.recovery_repair(&winner).await
16751            };
16752            result.unwrap();
16753            assert!(!leftover.exists(), "restore must precede retry");
16754            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16755            if graft {
16756                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16757            } else {
16758                assert!(matches!(
16759                    runner.state.recovery.as_ref().unwrap().repair,
16760                    crate::recovery::Repair::Done { .. }
16761                ));
16762            }
16763        }
16764    }
16765
16766    #[tokio::test]
16767    #[cfg(unix)]
16768    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16769        use std::os::fd::AsRawFd as _;
16770        let tmp = tempfile::tempdir().unwrap();
16771        let mut runner = registered_runner(tmp.path()).await;
16772        runner.state.config.graph.timeout_resource_wait = 1;
16773        let winner = runner.state.candidates[0].clone();
16774        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16775        runner.state.tally = Some(Tally {
16776            first_choice: BTreeMap::new(),
16777            borda: BTreeMap::new(),
16778            winner: winner.label,
16779            rankings: 0,
16780            unanimous_initial: false,
16781            deliberated: false,
16782            changed_votes: 0,
16783            unanimous_final: false,
16784            tie_break: None,
16785            judges: 0,
16786            present: 0,
16787            quorum: 0,
16788            met_quorum: true,
16789            uncontested: Some("fixture".into()),
16790        });
16791        runner.state.graft = Some(GraftRecord {
16792            pre: pre.clone(),
16793            post: None,
16794            lines: None,
16795            limit: None,
16796            agent: None,
16797            outcome: GraftOutcome::Running,
16798            requested: Vec::new(),
16799            adoption: None,
16800            adoption_error: None,
16801        });
16802        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16803        git::commit_all(&winner.worktree, "unfinished graft")
16804            .await
16805            .unwrap();
16806        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16807        let leftover = winner.worktree.join("leftover");
16808        std::fs::write(&leftover, "untrusted edits").unwrap();
16809        let path = runner.state.repo.join(".git/updater.lock");
16810        let external = std::fs::File::create(&path).unwrap();
16811        assert_eq!(
16812            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16813            0
16814        );
16815        assert!(
16816            runner
16817                .graft()
16818                .await
16819                .unwrap_err()
16820                .is::<crate::repo_lock::ResourceBlocked>()
16821        );
16822        assert!(matches!(
16823            runner.state.graft.as_ref().unwrap().outcome,
16824            GraftOutcome::Running
16825        ));
16826        assert_eq!(
16827            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16828            unfinished
16829        );
16830        assert!(leftover.exists());
16831        drop(external);
16832        std::fs::remove_file(&path).unwrap();
16833        std::fs::create_dir(&path).unwrap();
16834        assert!(runner.graft().await.is_err());
16835        assert!(matches!(
16836            runner.state.graft.as_ref().unwrap().outcome,
16837            GraftOutcome::Running
16838        ));
16839        assert_eq!(
16840            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16841            unfinished
16842        );
16843        assert!(leftover.exists());
16844        std::fs::remove_dir(&path).unwrap();
16845        runner.graft().await.unwrap();
16846        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16847        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16848        assert!(!leftover.exists());
16849    }
16850
16851    #[tokio::test]
16852    #[cfg(unix)]
16853    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16854        use std::os::fd::AsRawFd as _;
16855        let tmp = tempfile::tempdir().unwrap();
16856        let mut runner = registered_runner(tmp.path()).await;
16857        runner.state.prep_complete = Some(false);
16858        runner.state.config.graph.timeout_resource_wait = 1;
16859        runner.state.save().unwrap();
16860        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16861        assert_eq!(
16862            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16863            0
16864        );
16865        runner.execute().await.unwrap();
16866        let disk = RunState::load(&runner.state.id).unwrap();
16867        assert!(disk.driver_exited);
16868        assert_eq!(disk.driver_pid, None);
16869        assert_eq!(runner.state.status, RunStatus::Blocked);
16870        assert_eq!(
16871            runner.state.resource_block.as_ref().unwrap().kind,
16872            "repository coordination"
16873        );
16874        assert!(runner.state.prep_failure.is_none());
16875        assert!(runner.state.seats.is_empty());
16876        runner.pause.park();
16877        // Include headroom for Git subprocesses under parallel test load;
16878        // the repository contention deadline itself remains one second.
16879        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16880            .await
16881            .unwrap()
16882            .unwrap();
16883        assert!(runner.state.parked);
16884        assert!(runner.state.prep_failure.is_none());
16885        let disk = RunState::load(&runner.state.id).unwrap();
16886        assert!(disk.driver_exited);
16887        assert_eq!(disk.driver_pid, None);
16888    }
16889
16890    #[tokio::test]
16891    #[cfg(unix)]
16892    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16893        use std::os::fd::AsRawFd as _;
16894        let tmp = tempfile::tempdir().unwrap();
16895        let mut runner = registered_runner(tmp.path()).await;
16896        runner.state.prep_complete = Some(false);
16897        runner.state.config.graph.timeout_resource_wait = 30;
16898        runner.state.save().unwrap();
16899        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16900        assert_eq!(
16901            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16902            0
16903        );
16904        assert!(
16905            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16906                .await
16907                .is_err()
16908        );
16909        let disk = RunState::load(&runner.state.id).unwrap();
16910        assert!(disk.driver_exited);
16911        assert_eq!(disk.driver_pid, None);
16912        assert!(disk.status.resumable());
16913        assert!(runner.state.driver_exited);
16914        assert_eq!(runner.state.driver_pid, None);
16915        runner.state.save().unwrap();
16916        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16917    }
16918
16919    #[tokio::test]
16920    #[cfg(unix)]
16921    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16922        let tmp = tempfile::tempdir().unwrap();
16923        let mut runner = registered_runner(tmp.path()).await;
16924        let winner = runner.state.candidates[0].clone();
16925        let cache = tmp.path().join("cache");
16926        let started = tmp.path().join("pre-gate-started");
16927        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16928        runner.state.config.verify.gate =
16929            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16930        let home = crate::run::home();
16931        let owner =
16932            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16933        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16934            crate::cache::AcquireOutcome::Acquired(g) => g,
16935            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16936        };
16937        let mut gate = Box::pin(runner.run_gate(&winner));
16938        assert!(
16939            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16940                .await
16941                .is_err()
16942        );
16943        assert!(!started.exists(), "pre-gate must wait for the cache too");
16944        // Simulate the wave that already owns the cache entering invoke.
16945        // It must obtain the editor reservation and finish without waiting
16946        // for the gate that is queued behind its cache.
16947        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16948        let editor = crate::repo_lock::SeatLease::checkout_with(
16949            &winner.worktree,
16950            true,
16951            crate::config::test_coordination().as_ref(),
16952            &wait,
16953        )
16954        .await
16955        .unwrap();
16956        drop(editor);
16957        guard.release();
16958        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16959            .await
16960            .unwrap()
16961            .unwrap();
16962        drop(gate);
16963        assert!(outcomes.iter().all(CommandOutcome::ok));
16964        assert!(started.exists());
16965    }
16966
16967    #[tokio::test]
16968    #[cfg(unix)]
16969    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
16970        use std::os::fd::AsRawFd as _;
16971
16972        ask_test_home();
16973        let tmp = tempfile::tempdir().unwrap();
16974        let repo = tmp.path().join("repo");
16975        std::fs::create_dir_all(&repo).unwrap();
16976        init_repo(&repo);
16977        let common = repo.join(".git");
16978        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16979        let mut runner = runner_at(RunStatus::Prep);
16980        runner.state.repo = repo.clone();
16981        runner.state.config.coordination = crate::config::test_coordination();
16982        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16983        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16984        runner.state.config.graph.advise = false;
16985        runner.roles.implementers = vec![spec("implement")];
16986        runner.roles.judges = vec![spec("judge")];
16987        runner.prep().await.unwrap();
16988        let winner = runner.state.candidates[0].clone();
16989        // Emulate edits already left by a completed seat. The fixture CLI
16990        // only reports completion; it performs no repository operations.
16991        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16992        let completed = tmp.path().join("seat-completed");
16993        runner.roles.implementers[0].command = vec![
16994            "sh".into(),
16995            "-c".into(),
16996            format!("touch '{}'; echo completed", completed.display()),
16997        ];
16998        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16999        assert_eq!(
17000            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17001            0
17002        );
17003        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17004        let mut implement = Box::pin(runner.implement());
17005        tokio::select! {
17006            result = &mut implement => panic!("rescue must wait: {result:?}"),
17007            result = tokio::time::timeout(Duration::from_secs(10), async {
17008                while !completed.exists() {
17009                    tokio::time::sleep(Duration::from_millis(20)).await;
17010                }
17011            }) => result.unwrap(),
17012        }
17013        assert!(
17014            tokio::time::timeout(Duration::from_millis(200), &mut implement)
17015                .await
17016                .is_err()
17017        );
17018        assert_eq!(
17019            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17020            before
17021        );
17022        assert_eq!(
17023            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17024            0
17025        );
17026        tokio::time::timeout(Duration::from_secs(10), &mut implement)
17027            .await
17028            .unwrap()
17029            .unwrap();
17030        drop(implement);
17031        assert_ne!(
17032            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17033            before
17034        );
17035        assert!(git::is_clean(&winner.worktree).await.unwrap());
17036
17037        let started = tmp.path().join("pre-gate-started");
17038        let proceed = tmp.path().join("pre-gate-proceed");
17039        let checked = tmp.path().join("gate-ran");
17040        runner.state.config.verify.pre_gate = vec![format!(
17041            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17042            started.display(),
17043            proceed.display()
17044        )];
17045        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
17046        assert_eq!(
17047            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17048            0
17049        );
17050        let mut gate = Box::pin(runner.run_gate(&winner));
17051        assert!(
17052            tokio::time::timeout(Duration::from_millis(200), &mut gate)
17053                .await
17054                .is_err()
17055        );
17056        assert!(!started.exists());
17057        assert!(!checked.exists());
17058        assert!(git::is_clean(&winner.worktree).await.unwrap());
17059        assert_eq!(
17060            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17061            0
17062        );
17063        tokio::select! {
17064            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
17065            result = tokio::time::timeout(Duration::from_secs(10), async {
17066                while !started.exists() {
17067                    tokio::time::sleep(Duration::from_millis(20)).await;
17068                }
17069            }) => result.unwrap(),
17070        }
17071        assert_eq!(
17072            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17073            -1,
17074            "mechanical edits must hold the real lock"
17075        );
17076        std::fs::write(proceed, "ready").unwrap();
17077        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17078            .await
17079            .unwrap()
17080            .unwrap();
17081        drop(gate);
17082        assert!(outcomes.iter().all(CommandOutcome::ok));
17083        assert!(checked.exists());
17084        assert!(runner.state.pre_gate_commit.is_some());
17085        assert!(git::is_clean(&winner.worktree).await.unwrap());
17086        assert_eq!(
17087            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17088            0,
17089            "gate completion must release coordination"
17090        );
17091        drop(outsider);
17092        std::fs::remove_file(common.join("updater.lock")).unwrap();
17093        std::fs::create_dir(common.join("updater.lock")).unwrap();
17094        std::fs::remove_file(&started).unwrap();
17095        std::fs::remove_file(&checked).unwrap();
17096        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17097        let error = runner.run_gate(&winner).await.unwrap_err();
17098        assert!(
17099            error
17100                .to_string()
17101                .contains("acquire mandatory repository lock")
17102        );
17103        assert!(
17104            !started.exists(),
17105            "failed acquisition must prevent pre-gate"
17106        );
17107        assert!(!checked.exists(), "failed acquisition must prevent gate");
17108        assert!(git::is_clean(&winner.worktree).await.unwrap());
17109        assert_eq!(
17110            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17111            head
17112        );
17113    }
17114
17115    #[tokio::test]
17116    #[cfg(unix)]
17117    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
17118        use std::os::fd::AsRawFd as _;
17119        use std::time::Duration;
17120
17121        ask_test_home();
17122        let tmp = tempfile::tempdir().unwrap();
17123        let repo = tmp.path().join("repo");
17124        std::fs::create_dir_all(&repo).unwrap();
17125        init_repo(&repo);
17126        let common = repo.join(".git");
17127        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17128        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
17129        assert_eq!(
17130            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17131            0
17132        );
17133        let mut runner = runner_at(RunStatus::Prep);
17134        runner.state.repo = repo.clone();
17135        runner.state.config.coordination = crate::config::test_coordination();
17136        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17137        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17138        runner.state.config.graph.advise = true;
17139        runner.state.config.graph.advisors = 1;
17140        runner.roles.implementers = vec![spec("implement")];
17141        runner.roles.judges = vec![spec("judge")];
17142        let root = runner.state.worktree_root();
17143        let started = tmp.path().join("setup-started");
17144        let proceed = tmp.path().join("setup-proceed");
17145        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17146            run: Some(format!(
17147                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17148                started.display(),
17149                proceed.display()
17150            )),
17151            ..Default::default()
17152        }];
17153        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
17154        let config = git::git(&repo, &["config", "--local", "--list"])
17155            .await
17156            .unwrap();
17157        let mut prep = Box::pin(runner.prep());
17158        assert!(
17159            tokio::time::timeout(Duration::from_millis(200), &mut prep)
17160                .await
17161                .is_err()
17162        );
17163        assert!(
17164            !root.exists(),
17165            "contention must prevent even checkout creation"
17166        );
17167        assert!(!started.exists(), "contention must prevent setup");
17168        assert_eq!(
17169            git::git(&repo, &["branch", "--list"]).await.unwrap(),
17170            branches
17171        );
17172        assert_eq!(
17173            git::git(&repo, &["config", "--local", "--list"])
17174                .await
17175                .unwrap(),
17176            config
17177        );
17178        drop(lock);
17179        tokio::select! {
17180            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
17181            result = tokio::time::timeout(Duration::from_secs(10), async {
17182                while !started.exists() {
17183                    tokio::time::sleep(Duration::from_millis(20)).await;
17184                }
17185            }) => result.unwrap(),
17186        }
17187        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
17188        assert_eq!(
17189            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17190            -1
17191        );
17192        assert!(
17193            tokio::time::timeout(
17194                Duration::from_millis(100),
17195                crate::repo_lock::SeatLease::for_checkout(
17196                    &repo,
17197                    true,
17198                    crate::config::test_coordination().as_ref()
17199                )
17200            )
17201            .await
17202            .is_err(),
17203            "preparation must also exclude local editors"
17204        );
17205        std::fs::write(proceed, "ready").unwrap();
17206        tokio::time::timeout(Duration::from_secs(10), &mut prep)
17207            .await
17208            .unwrap()
17209            .unwrap();
17210        drop(prep);
17211        assert_eq!(runner.state.prep_complete, Some(true));
17212        assert!(root.join("judge-1").exists());
17213        assert!(root.join("advisor-1").exists());
17214        assert_eq!(
17215            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17216            0
17217        );
17218    }
17219
17220    #[tokio::test]
17221    #[cfg(unix)]
17222    async fn preparation_lock_failure_prevents_repository_changes() {
17223        ask_test_home();
17224        let tmp = tempfile::tempdir().unwrap();
17225        let repo = tmp.path().join("repo");
17226        std::fs::create_dir_all(&repo).unwrap();
17227        init_repo(&repo);
17228        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
17229        // A directory at the required lock path makes opening the real lock
17230        // fail, rather than merely exercising an invalid registration.
17231        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
17232        let mut runner = runner_at(RunStatus::Prep);
17233        runner.state.repo = repo.clone();
17234        runner.state.config.coordination = crate::config::test_coordination();
17235        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17236        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17237        runner.roles.implementers = vec![spec("implement")];
17238        let error = runner.prep().await.unwrap_err();
17239        assert!(
17240            error
17241                .to_string()
17242                .contains("acquire mandatory repository lock")
17243        );
17244        assert!(!runner.state.worktree_root().exists());
17245        assert!(runner.state.candidates.is_empty());
17246        assert!(!repo.join(".git/config.worktree").exists());
17247        assert_eq!(
17248            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
17249            "* main"
17250        );
17251    }
17252
17253    #[tokio::test]
17254    async fn preparation_records_creation_intent_before_git_can_fail() {
17255        ask_test_home();
17256        let tmp = tempfile::tempdir().unwrap();
17257        let repo = tmp.path().join("repo");
17258        std::fs::create_dir_all(&repo).unwrap();
17259        init_repo(&repo);
17260        let mut runner = runner_at(RunStatus::Prep);
17261        runner.state.repo = repo.clone();
17262        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17263        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17264        runner.state.config.blind.commit_msg_hook = false;
17265        runner.roles.implementers = vec![spec("one")];
17266        let label = blind::assign_labels(1, runner.state.seed)[0];
17267        let branch = runner.state.branch_for(label);
17268        // A conflicting branch makes Git refuse creation before a candidate
17269        // can be registered. The durable intent must still identify it.
17270        git::git(&repo, &["branch", &branch]).await.unwrap();
17271        assert!(runner.prep().await.is_err());
17272        let saved = RunState::load(&runner.state.id).unwrap();
17273        assert!(saved.candidates.is_empty());
17274        let event = saved
17275            .events
17276            .iter()
17277            .find(|e| e.node == "prep-intent")
17278            .unwrap();
17279        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
17280        assert_eq!(intent["branch"], branch);
17281        assert_eq!(intent["start"], runner.state.base_commit);
17282        assert_eq!(
17283            intent["worktree"],
17284            runner
17285                .state
17286                .worktree_root()
17287                .join(format!("cand-{label}"))
17288                .to_string_lossy()
17289                .as_ref()
17290        );
17291        assert_eq!(intent["picks"], serde_json::json!([]));
17292    }
17293
17294    #[tokio::test]
17295    async fn invalid_pinned_sources_create_no_partial_worktrees() {
17296        ask_test_home();
17297        let tmp = tempfile::tempdir().unwrap();
17298        let repo = tmp.path().join("repo");
17299        std::fs::create_dir_all(&repo).unwrap();
17300        init_repo(&repo);
17301        let mut runner = runner_at(RunStatus::Prep);
17302        runner.state.repo = repo.clone();
17303        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17304        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17305        runner.state.sources.pick_commits.push(refs::Input {
17306            token: "missing".into(),
17307            sha: "0".repeat(40),
17308            provenance: refs::Provenance::ExplicitCli,
17309        });
17310        assert!(runner.prep().await.is_err());
17311        assert!(runner.state.candidates.is_empty());
17312        assert!(!runner.state.worktree_root().exists());
17313    }
17314
17315    #[tokio::test]
17316    async fn prose_and_legacy_inference_never_import_into_candidates() {
17317        ask_test_home();
17318        let tmp = tempfile::tempdir().unwrap();
17319        let repo = tmp.path().join("repo");
17320        std::fs::create_dir_all(&repo).unwrap();
17321        init_repo(&repo);
17322        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17323        git::git(&repo, &["checkout", "-b", "magi/history/A"])
17324            .await
17325            .unwrap();
17326        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
17327        git::git(&repo, &["add", "."]).await.unwrap();
17328        git::git(&repo, &["commit", "-m", "historical implementation"])
17329            .await
17330            .unwrap();
17331        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
17332        git::git(&repo, &["checkout", "main"]).await.unwrap();
17333        for instruction in [
17334            format!("Example: magi/history/A at {source}"),
17335            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
17336            format!("Never import magi/history/A or {source}"),
17337            format!("Conversation answer: I mentioned {source} only as background"),
17338        ] {
17339            let mut runner = runner_at(RunStatus::Prep);
17340            runner.state.repo = repo.clone();
17341            runner.state.base_commit = base.clone();
17342            runner.state.instruction = instruction.clone();
17343            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
17344            runner.state.config.blind.commit_msg_hook = false;
17345            runner.state.seeds = vec![refs::Seed {
17346                token: "magi/history/A".into(),
17347                sha: source.clone(),
17348                kind: refs::SeedKind::Unmerged,
17349                branch: true,
17350                detail: String::new(),
17351            }];
17352            runner.roles.implementers = vec![spec("one")];
17353            assert_eq!(seeded_instruction(&runner.state), instruction);
17354            // Model an old record with inferred seeds but no structured input field.
17355            let mut legacy = serde_json::to_value(&runner.state).unwrap();
17356            legacy.as_object_mut().unwrap().remove("sources");
17357            runner.state = serde_json::from_value(legacy).unwrap();
17358            assert_eq!(runner.state.sources, refs::Sources::default());
17359            runner.state.save().unwrap();
17360            runner.state = RunState::load(&runner.state.id).unwrap();
17361            runner.prep().await.unwrap();
17362            for candidate in &runner.state.candidates {
17363                assert_eq!(
17364                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
17365                    base
17366                );
17367                assert!(!candidate.worktree.join("unwanted").exists());
17368            }
17369        }
17370    }
17371
17372    #[tokio::test]
17373    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
17374        ask_test_home();
17375        let tmp = tempfile::tempdir().unwrap();
17376        let repo = tmp.path().join("repo");
17377        std::fs::create_dir_all(&repo).unwrap();
17378        init_repo(&repo);
17379        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17380        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
17381        std::fs::write(repo.join("referenced"), "required commit").unwrap();
17382        git::git(&repo, &["add", "."]).await.unwrap();
17383        git::git(&repo, &["commit", "-m", "required seed"])
17384            .await
17385            .unwrap();
17386        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
17387        git::git(&repo, &["checkout", "main"]).await.unwrap();
17388        let mut runner = runner_at(RunStatus::Prep);
17389        runner.state.repo = repo.clone();
17390        runner.state.base_commit = base.clone();
17391        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17392        runner.state.config.graph.advise = false;
17393        runner.state.config.blind.commit_msg_hook = false;
17394        runner.state.sources =
17395            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
17396                .await
17397                .unwrap();
17398        runner.roles.implementers = vec![spec("one"), spec("two")];
17399        runner.roles.judges = vec![spec("judge")];
17400        let label = blind::assign_labels(2, runner.state.seed)[0];
17401        let branch = runner.state.branch_for(label);
17402        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17403        git::worktree_add_branch(&repo, &worktree, &branch, &base)
17404            .await
17405            .unwrap();
17406        runner.state.candidates.push(Candidate {
17407            index: 0,
17408            label,
17409            agent: "one".into(),
17410            branch,
17411            worktree,
17412            summary: String::new(),
17413            stat: String::new(),
17414            files: 0,
17415            commits: 0,
17416            empty: false,
17417            failed: None,
17418            verified_noop: None,
17419            duration_ms: 0,
17420            folded: false,
17421        });
17422        runner.state.save().unwrap();
17423        // Reload the checkpoint immediately before its first cherry-pick.
17424        runner.state = RunState::load(&runner.state.id).unwrap();
17425        assert_eq!(runner.state.prep_complete, Some(false));
17426        runner.prep().await.unwrap();
17427        assert_eq!(runner.state.prep_complete, Some(true));
17428        assert_eq!(runner.state.candidates.len(), 2);
17429        for candidate in &runner.state.candidates {
17430            assert_eq!(
17431                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17432                git::tree_of(&repo, &seed).await.unwrap()
17433            );
17434            assert_eq!(
17435                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
17436                "required commit"
17437            );
17438        }
17439        assert!(runner.state.worktree_root().join("judge-1").exists());
17440        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
17441        runner.prep().await.unwrap();
17442        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
17443
17444        runner.state.prep_complete = Some(false);
17445        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17446            run: Some(format!(
17447                "test -f '{}'",
17448                tmp.path().join("dependency-ready").display()
17449            )),
17450            ..Default::default()
17451        }];
17452        assert!(runner.prep().await.is_err());
17453        assert!(runner.state.prep_failure.is_some());
17454        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
17455        runner.state = RunState::load(&runner.state.id).unwrap();
17456        assert!(
17457            runner.prep().await.is_err(),
17458            "correcting the cause alone must not auto-retry"
17459        );
17460        let failed_at = runner.state.events.last().unwrap().at;
17461        assert!(
17462            runner.retry_preparation(failed_at).is_err(),
17463            "old approvals cannot unlock the hold"
17464        );
17465        let mut task = crate::queue::Task::new(
17466            "retry".into(),
17467            "retry setup".into(),
17468            repo.clone(),
17469            crate::queue::Source::Human,
17470        );
17471        task.start(runner.state.id.clone());
17472        task.hold_machine(Some("setup failed".into()));
17473        task.release_operator("cli", None);
17474        runner
17475            .retry_preparation(task.resumption.as_ref().unwrap().at)
17476            .unwrap();
17477        runner.prep().await.unwrap();
17478        assert!(runner.state.prep_failure.is_none());
17479        assert_eq!(runner.state.prep_complete, Some(true));
17480        assert_eq!(runner.state.candidates.len(), 2);
17481        assert!(runner.state.worktree_root().join("judge-1").exists());
17482        for candidate in &runner.state.candidates {
17483            assert_eq!(
17484                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17485                git::tree_of(&repo, &seed).await.unwrap()
17486            );
17487        }
17488    }
17489
17490    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
17491        let mut heads = Vec::new();
17492        for candidate in candidates {
17493            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
17494        }
17495        heads
17496    }
17497
17498    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
17499        ask_test_home();
17500        let tmp = tempfile::tempdir().unwrap();
17501        let repo = tmp.path().join("repo");
17502        std::fs::create_dir(&repo).unwrap();
17503        init_repo(&repo);
17504        let mut runner = runner_at(RunStatus::Reviewing);
17505        runner.state.repo = repo.clone();
17506        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17507        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17508        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17509            let branch = format!("candidate-{label}");
17510            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17511            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17512                .await
17513                .unwrap();
17514            if label == 'B' {
17515                std::fs::write(worktree.join("change"), "winner").unwrap();
17516                git::rescue_commit(&worktree, "candidate change")
17517                    .await
17518                    .unwrap();
17519            }
17520            runner.state.candidates.push(Candidate {
17521                index,
17522                label,
17523                agent: "alpha".into(),
17524                branch,
17525                worktree,
17526                summary: "completed reply".into(),
17527                stat: String::new(),
17528                files: usize::from(label == 'B'),
17529                commits: usize::from(label == 'B'),
17530                empty: label == 'A',
17531                failed: None,
17532                verified_noop: None,
17533                duration_ms: 1,
17534                folded: false,
17535            });
17536        }
17537        runner.state.judge_skipped = true;
17538        runner.state.tally = Some(Tally {
17539            first_choice: BTreeMap::new(),
17540            borda: BTreeMap::new(),
17541            winner: 'B',
17542            rankings: 0,
17543            unanimous_initial: false,
17544            deliberated: false,
17545            changed_votes: 0,
17546            unanimous_final: false,
17547            tie_break: None,
17548            judges: 0,
17549            present: 0,
17550            quorum: 0,
17551            met_quorum: true,
17552            uncontested: Some("only B produced a change".into()),
17553        });
17554        runner.state.save().unwrap();
17555        (tmp, runner)
17556    }
17557
17558    #[tokio::test]
17559    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17560        let (_tmp, mut runner) = preservation_resume_fixture().await;
17561        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17562        runner.state.config.disk.cache_limit_bytes = 0;
17563        runner.state.config.graph.advise = true;
17564        runner.state.config.graph.advisors = 1;
17565        let advisor = runner.state.worktree_root().join("advisor-1");
17566        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17567            .await
17568            .unwrap();
17569        let home = crate::run::home();
17570        let loser =
17571            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17572        let winner =
17573            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17574        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17575        for target in [&loser, &winner, &advisor] {
17576            std::fs::write(target.join("build-output"), "compiled").unwrap();
17577        }
17578
17579        runner.fold_losers().await.unwrap();
17580
17581        assert!(!loser.join("build-output").exists());
17582        assert!(!advisor.join("build-output").exists());
17583        assert!(winner.join("build-output").is_file());
17584    }
17585
17586    #[tokio::test]
17587    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17588        let (_tmp, mut runner) = preservation_resume_fixture().await;
17589        runner.state.candidates[0].folded = true;
17590        runner.state.config.graph.advise = true;
17591        runner.state.config.graph.advisors = 2;
17592        let repo = runner.state.repo.clone();
17593        let root = runner.state.worktree_root();
17594        let discarded = root.join("advisor-1");
17595        git::worktree_add_detached(&repo, &discarded, "main")
17596            .await
17597            .unwrap();
17598        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17599        let protected = root.join("advisor-2");
17600        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17601            .await
17602            .unwrap();
17603        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17604        runner.state.save().unwrap();
17605
17606        assert!(runner.fold_losers().await.is_err());
17607        assert!(!discarded.exists());
17608        assert!(protected.join("keep").exists());
17609        let saved = RunState::load(&runner.state.id).unwrap();
17610        assert!(saved.events.iter().any(|event| {
17611            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17612        }));
17613    }
17614
17615    #[tokio::test]
17616    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17617        let (tmp, mut runner) = preservation_resume_fixture().await;
17618        let repo = runner.state.repo.clone();
17619        let root = runner.state.worktree_root();
17620        for name in ["advisor-3", "judge-1", "review-2"] {
17621            let path = root.join(name);
17622            git::worktree_add_detached(&repo, &path, "main")
17623                .await
17624                .unwrap();
17625            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17626            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17627            remove_read_seat_worktree(&mut runner.state, &path)
17628                .await
17629                .unwrap();
17630            assert!(!path.exists());
17631        }
17632        let outside = tmp.path().join("advisor-1");
17633        let unknown = root.join("unknown");
17634        let attached = root.join("advisor-4");
17635        git::worktree_add_detached(&repo, &outside, "main")
17636            .await
17637            .unwrap();
17638        git::worktree_add_detached(&repo, &unknown, "main")
17639            .await
17640            .unwrap();
17641        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17642            .await
17643            .unwrap();
17644        let foreign = tmp.path().join("foreign");
17645        std::fs::create_dir(&foreign).unwrap();
17646        init_repo(&foreign);
17647        let wrong_repo = root.join("judge-2");
17648        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17649            .await
17650            .unwrap();
17651        let candidate = runner.state.candidates[0].worktree.clone();
17652        for path in [outside, unknown, attached, wrong_repo, candidate] {
17653            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17654            assert!(
17655                remove_read_seat_worktree(&mut runner.state, &path)
17656                    .await
17657                    .is_err()
17658            );
17659            assert_eq!(
17660                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17661                "keep"
17662            );
17663        }
17664    }
17665
17666    #[tokio::test]
17667    #[cfg(unix)]
17668    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17669        for (solo, failed_checkpoint) in
17670            [(true, false), (false, false), (true, true), (false, true)]
17671        {
17672            let (_tmp, mut runner) = preservation_resume_fixture().await;
17673            if solo {
17674                runner.state.candidates.retain(|c| c.label == 'A');
17675            }
17676            runner.state.candidates[0].empty = false;
17677            runner.state.candidates[0].summary.clear();
17678            runner.state.tally = None;
17679            runner.state.judge_skipped = false;
17680            runner.state.status = RunStatus::Implementing;
17681            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17682            let mut implementer = spec("alpha");
17683            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17684            runner.roles.implementers = vec![implementer];
17685            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17686            if failed_checkpoint {
17687                std::fs::create_dir_all(&patch).unwrap();
17688            }
17689            runner.state.save().unwrap();
17690            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17691            drop(pressure);
17692            runner.state = RunState::load(&runner.state.id).unwrap();
17693            assert_eq!(runner.state.status, RunStatus::Blocked);
17694            assert!(runner.state.interrupted_implementations.contains(&'A'));
17695            assert_eq!(runner.state.candidates[0].commits, 0);
17696            assert!(!runner.state.candidates[0].empty);
17697            assert!(runner.state.candidates[0].failed.is_none());
17698            if failed_checkpoint {
17699                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17700                std::fs::remove_dir(patch).unwrap();
17701            }
17702            runner.state.resource_block = None;
17703            runner.state.config.disk.min_free_bytes = 0;
17704            runner.roles.implementers[0].command = vec![
17705                "sh".into(),
17706                "-c".into(),
17707                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17708            ];
17709            runner.implement().await.unwrap();
17710            assert!(runner.state.interrupted_implementations.is_empty());
17711            assert!(runner.state.candidate_preservation.is_empty());
17712            assert_eq!(runner.state.candidates[0].commits, 1);
17713            assert!(!runner.state.candidates[0].empty);
17714            assert!(
17715                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17716                    .unwrap()
17717                    .contains("retried empty interrupted seat")
17718            );
17719            if !solo {
17720                assert_eq!(runner.state.candidates[1].commits, 1);
17721            }
17722        }
17723    }
17724
17725    #[tokio::test]
17726    #[cfg(unix)]
17727    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17728        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17729            let (_tmp, mut runner) = preservation_resume_fixture().await;
17730            runner.state.candidates.retain(|c| c.label == 'A');
17731            runner.state.candidates[0].empty = false;
17732            runner.state.candidates[0].summary.clear();
17733            runner.state.tally = None;
17734            runner.state.judge_skipped = false;
17735            runner.state.status = RunStatus::Implementing;
17736            // Force only the real post-spawn watchdog, without failing the
17737            // separate admission check. Existing edits predate its measurement.
17738            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17739            let wt = runner.state.candidates[0].worktree.clone();
17740            std::fs::write(
17741                wt.join("interrupted-source"),
17742                "retain implementation work\n",
17743            )
17744            .unwrap();
17745            if committed {
17746                git::rescue_commit(&wt, "implementation checkpoint")
17747                    .await
17748                    .unwrap();
17749            }
17750            let lock = git::git(
17751                &wt,
17752                &[
17753                    "rev-parse",
17754                    "--path-format=absolute",
17755                    "--git-path",
17756                    "index.lock",
17757                ],
17758            )
17759            .await
17760            .unwrap();
17761            if block_rescue {
17762                std::fs::write(&lock, "fixture-owned lock").unwrap();
17763            }
17764            let mut implementer = spec("alpha");
17765            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17766            runner.roles.implementers = vec![implementer];
17767            runner.state.save().unwrap();
17768            let result = runner.implement().await;
17769            drop(pressure);
17770            assert_eq!(result.is_err(), block_rescue);
17771            assert_eq!(
17772                runner.state.resource_block.as_ref().unwrap().kind,
17773                "disk pressure"
17774            );
17775            assert!(
17776                runner
17777                    .state
17778                    .events
17779                    .iter()
17780                    .any(|e| e.message.contains("agent execution interrupted"))
17781            );
17782            assert!(
17783                runner
17784                    .state
17785                    .dir()
17786                    .join("artifacts/candidate-A-recovery/staged.patch")
17787                    .exists()
17788            );
17789            if block_rescue {
17790                let saved = RunState::load(&runner.state.id).unwrap();
17791                assert!(saved.candidate_preservation.contains_key(&'A'));
17792                assert!(!saved.candidates[0].empty);
17793                assert_eq!(
17794                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17795                    "retain implementation work\n"
17796                );
17797                std::fs::remove_file(lock).unwrap();
17798                runner.state = saved;
17799            } else {
17800                assert_eq!(runner.state.status, RunStatus::Blocked);
17801                assert_eq!(runner.state.candidates[0].commits, 1);
17802            }
17803            // Recovery must save the candidate before deciding whether another
17804            // implementation is needed. No implementer is available on retry.
17805            runner.roles.implementers.clear();
17806            runner.state.config.disk.min_free_bytes = 0;
17807            runner.state.resource_block = None;
17808            runner.implement().await.unwrap();
17809            assert!(runner.state.candidate_preservation.is_empty());
17810            assert_eq!(runner.state.candidates[0].commits, 1);
17811            assert!(!runner.state.candidates[0].empty);
17812            assert!(git::is_clean(&wt).await.unwrap());
17813            assert!(
17814                crate::run::read_artifact(&runner.state, "cand-A.patch")
17815                    .unwrap()
17816                    .contains("retain implementation work")
17817            );
17818        }
17819    }
17820
17821    #[tokio::test]
17822    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17823        let (_tmp, mut runner) = preservation_resume_fixture().await;
17824        // Schema 15 already confirmed the unfolded no-change result.
17825        runner.implement().await.unwrap();
17826        assert!(runner.state.candidate_preservation.is_empty());
17827        assert!(
17828            !runner
17829                .state
17830                .dir()
17831                .join("artifacts/candidate-A-recovery")
17832                .exists()
17833        );
17834        runner.fold_losers().await.unwrap();
17835        assert!(!runner.state.candidates[0].worktree.exists());
17836        for schema in [14, crate::run::SCHEMA] {
17837            runner.state.schema = schema;
17838            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17839            runner.state.save().unwrap();
17840            runner.state = RunState::load(&runner.state.id).unwrap();
17841            runner.implement().await.unwrap();
17842            assert!(runner.state.candidate_preservation.is_empty());
17843            assert!(runner.state.candidates[0].folded);
17844            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17845        }
17846    }
17847
17848    #[tokio::test]
17849    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17850        let (_tmp, mut runner) = preservation_resume_fixture().await;
17851        runner.state.candidates.retain(|c| c.label == 'A');
17852        runner.state.tally = None;
17853        runner.state.judge_skipped = false;
17854        let candidate = &mut runner.state.candidates[0];
17855        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17856        candidate.failed = Some("deployment validation unavailable".into());
17857        std::fs::write(
17858            candidate.worktree.join("repair"),
17859            "future launcher policy\n",
17860        )
17861        .unwrap();
17862        runner
17863            .state
17864            .candidate_preservation
17865            .insert('A', "awaiting persistence".into());
17866        runner.persist_candidates().await.unwrap();
17867        let candidate = &runner.state.candidates[0];
17868        assert!(!candidate.empty);
17869        assert_eq!(candidate.commits, 1);
17870        assert_eq!(candidate.files, 1);
17871        assert!(candidate.failed.is_none());
17872        assert!(candidate.summary.contains("EPERM"));
17873        assert!(
17874            crate::run::read_artifact(&runner.state, "cand-A.patch")
17875                .unwrap()
17876                .contains("future launcher policy")
17877        );
17878        assert!(runner.state.candidate_preservation.is_empty());
17879    }
17880
17881    #[tokio::test]
17882    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17883        let (_tmp, mut runner) = preservation_resume_fixture().await;
17884        let wt = runner.state.candidates[0].worktree.clone();
17885        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17886        runner.state.schema = 14;
17887        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17888        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17889        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17890        for _ in 0..2 {
17891            assert!(runner.implement().await.is_err());
17892            assert_eq!(runner.state.status, RunStatus::Blocked);
17893            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17894            assert!(
17895                runner.state.candidates[0].empty,
17896                "old verdict must remain unusable"
17897            );
17898            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17899            assert!(runner.state.judge_skipped);
17900            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17901            assert!(
17902                crate::run::read_artifact(&runner.state, "cand-A.patch")
17903                    .unwrap()
17904                    .contains("owned edits")
17905            );
17906            assert!(wt.exists());
17907            assert_eq!(
17908                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17909                    .await
17910                    .unwrap(),
17911                1
17912            );
17913            runner.state = RunState::load(&runner.state.id).unwrap();
17914        }
17915    }
17916
17917    #[tokio::test]
17918    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17919        let (_tmp, mut runner) = preservation_resume_fixture().await;
17920        let wt = runner.state.candidates[0].worktree.clone();
17921        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17922        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17923        let index_lock = PathBuf::from(
17924            git::git(
17925                &wt,
17926                &[
17927                    "rev-parse",
17928                    "--path-format=absolute",
17929                    "--git-path",
17930                    "index.lock",
17931                ],
17932            )
17933            .await
17934            .unwrap(),
17935        );
17936        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17937        runner.state.schema = 14;
17938        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17939        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17940        assert!(runner.implement().await.is_err());
17941        assert!(runner.after_implement().is_err());
17942        assert!(runner.fold_losers().await.is_err());
17943        assert_eq!(
17944            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17945            "failed seat edits"
17946        );
17947        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17948        runner.state = RunState::load(&runner.state.id).unwrap();
17949        std::fs::remove_file(index_lock).unwrap();
17950        // Recovery finds changes that the old uncontested result never judged.
17951        assert!(runner.implement().await.is_err());
17952        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17953        assert!(runner.state.candidates[0].empty);
17954        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17955        assert!(
17956            crate::run::read_artifact(&runner.state, "cand-A.patch")
17957                .unwrap()
17958                .contains("failed seat edits")
17959        );
17960        assert!(wt.exists());
17961    }
17962
17963    #[tokio::test]
17964    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
17965        let (_tmp, mut runner) = preservation_resume_fixture().await;
17966        let repo = runner.state.repo.clone();
17967        let common = git::git(
17968            &repo,
17969            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
17970        )
17971        .await
17972        .unwrap();
17973        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
17974        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
17975        assert!(runner.fold_losers().await.is_err());
17976        assert!(!runner.state.candidates[0].worktree.exists());
17977        assert!(!runner.state.candidates[0].folded);
17978        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
17979        runner.state = RunState::load(&runner.state.id).unwrap();
17980        std::fs::remove_file(branch_lock).unwrap();
17981        let judge = runner.state.worktree_root().join("judge-1");
17982        git::worktree_add_detached(&repo, &judge, "main")
17983            .await
17984            .unwrap();
17985        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
17986        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
17987            .await
17988            .unwrap();
17989        runner.roles.judges = vec![spec("judge")];
17990        assert!(runner.fold_losers().await.is_err());
17991        runner.state = RunState::load(&runner.state.id).unwrap();
17992        assert!(
17993            runner.state.candidates[0].folded,
17994            "candidate progress saved before judge failure"
17995        );
17996        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17997        assert!(judge.join("uncommitted").exists());
17998        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17999            .await
18000            .unwrap();
18001        runner.fold_losers().await.unwrap();
18002        assert!(!judge.exists());
18003        runner.fold_losers().await.unwrap();
18004    }
18005
18006    #[tokio::test]
18007    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
18008        let (_tmp, mut runner) = preservation_resume_fixture().await;
18009        runner.state.candidates.retain(|c| c.label == 'B');
18010        runner.state.tally = None;
18011        runner.state.judge_skipped = false;
18012        runner.state.prep_complete = Some(true);
18013        runner.state.config.graph.advise = false;
18014        runner.state.config.graph.selected_implementer = Some("alpha".into());
18015        let wt = runner.state.candidates[0].worktree.clone();
18016        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
18017        runner
18018            .state
18019            .candidate_preservation
18020            .insert('B', "awaiting persistence".into());
18021        let index_lock = git::git(
18022            &wt,
18023            &[
18024                "rev-parse",
18025                "--path-format=absolute",
18026                "--git-path",
18027                "index.lock",
18028            ],
18029        )
18030        .await
18031        .unwrap();
18032        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18033        runner.state.save().unwrap();
18034        assert!(runner.execute_graph().await.is_err());
18035        assert_eq!(runner.state.status, RunStatus::Blocked);
18036        assert!(runner.state.candidate_preservation.contains_key(&'B'));
18037        std::fs::remove_file(index_lock).unwrap();
18038        // Park at the next graph boundary: this tests the real selected-seat
18039        // hold guard without dispatching reviewers or publishing anything.
18040        for _ in 0..2 {
18041            runner.state = RunState::load(&runner.state.id).unwrap();
18042            runner.pause.park();
18043            runner.execute_graph().await.unwrap();
18044            assert_eq!(runner.state.status, RunStatus::Implementing);
18045            assert!(runner.state.candidate_preservation.is_empty());
18046            assert_eq!(runner.state.candidates[0].commits, 2);
18047            assert!(runner.state.tally.is_none());
18048        }
18049        runner.implement().await.unwrap();
18050        assert_eq!(runner.state.status, RunStatus::Judging);
18051        // A genuine selected-implementer hold must still require release.
18052        runner.state.status = RunStatus::Blocked;
18053        runner.state.candidates[0].failed = Some("implementation failed".into());
18054        runner.state.save().unwrap();
18055        let error = runner.execute_graph().await.unwrap_err();
18056        assert!(
18057            error
18058                .to_string()
18059                .contains("selected implementation is held")
18060        );
18061    }
18062
18063    #[tokio::test]
18064    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
18065        let (_tmp, mut runner) = preservation_resume_fixture().await;
18066        let repo = runner.state.repo.clone();
18067        let candidate = runner.state.candidates[0].clone();
18068        // Remove only the disposable fixture directory, leaving Git's linked
18069        // worktree registration and branch intact, as in a vanished checkout.
18070        let registered = git::worktree_holding(&repo, &candidate.branch)
18071            .await
18072            .unwrap()
18073            .unwrap();
18074        assert_eq!(
18075            registered.canonicalize().unwrap(),
18076            candidate.worktree.canonicalize().unwrap()
18077        );
18078        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18079        assert_eq!(
18080            git::worktree_holding(&repo, &candidate.branch)
18081                .await
18082                .unwrap(),
18083            Some(registered)
18084        );
18085        assert!(
18086            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
18087            "the stale registration initially keeps the branch checked out"
18088        );
18089        runner.fold_losers().await.unwrap();
18090        assert!(runner.state.candidates[0].folded);
18091        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18092        assert_eq!(
18093            git::worktree_holding(&repo, &candidate.branch)
18094                .await
18095                .unwrap(),
18096            None
18097        );
18098        runner.state = RunState::load(&runner.state.id).unwrap();
18099        runner.fold_losers().await.unwrap();
18100    }
18101
18102    #[tokio::test]
18103    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
18104        let (_tmp, mut runner) = preservation_resume_fixture().await;
18105        let repo = runner.state.repo.clone();
18106        let candidate = runner.state.candidates[0].clone();
18107        let winner = runner.state.candidates[1].clone();
18108        let registered = git::worktree_holding(&repo, &candidate.branch)
18109            .await
18110            .unwrap()
18111            .unwrap();
18112        assert_eq!(
18113            registered.canonicalize().unwrap(),
18114            candidate.worktree.canonicalize().unwrap()
18115        );
18116        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18117        assert_eq!(
18118            git::worktree_holding(&repo, &candidate.branch)
18119                .await
18120                .unwrap(),
18121            Some(registered)
18122        );
18123        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
18124
18125        for _ in 0..2 {
18126            fold_run(&mut runner.state, false, &crate::run::home())
18127                .await
18128                .unwrap();
18129            runner.state = RunState::load(&runner.state.id).unwrap();
18130            assert!(runner.state.candidates[0].folded);
18131            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18132            assert_eq!(
18133                git::worktree_holding(&repo, &candidate.branch)
18134                    .await
18135                    .unwrap(),
18136                None
18137            );
18138            assert!(!runner.state.candidates[1].folded);
18139            assert!(winner.worktree.exists());
18140            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
18141        }
18142    }
18143
18144    /// The recovery-retention override, refused for the rule under test. The
18145    /// arrangement is saved in `home` before each call, so `record gone` or
18146    /// `unreadable` would be the fixture's mistake and fails here.
18147    async fn override_refusal(state: &mut RunState, home: &Path) -> anyhow::Error {
18148        let error = fold_run_overriding_recovery_retention(state, true, home)
18149            .await
18150            .expect_err("the override is refused");
18151        assert!(
18152            !matches!(
18153                error.downcast_ref::<FoldRefusal>(),
18154                Some(FoldRefusal::RecordGone | FoldRefusal::Unreadable(_))
18155            ),
18156            "refused for the wrong reason: {error:#}"
18157        );
18158        error
18159    }
18160
18161    #[tokio::test]
18162    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
18163        for sidecar in [false, true] {
18164            let tmp = tempfile::tempdir().unwrap();
18165            let home = tmp.path().join("home");
18166            let repo = tmp.path().join("repo");
18167            std::fs::create_dir(&repo).unwrap();
18168            init_repo(&repo);
18169            let mut state = runner_at(RunStatus::Superseded).state;
18170            state.repo = repo.clone();
18171            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18172            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18173            state.driver_exited = true;
18174            state.reserve_under(&home).unwrap();
18175            git::git(
18176                &repo,
18177                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
18178            )
18179            .await
18180            .unwrap();
18181            let wt = state.worktree_root().join("cand-A");
18182            git::worktree_add_branch(&repo, &wt, "candidate", "main")
18183                .await
18184                .unwrap();
18185            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
18186            git::commit_all(&wt, "fixture: independent source")
18187                .await
18188                .unwrap();
18189            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
18190            state.candidates.push(Candidate {
18191                index: 0,
18192                label: 'A',
18193                agent: "fixture".into(),
18194                branch: "candidate".into(),
18195                worktree: wt.clone(),
18196                summary: String::new(),
18197                stat: String::new(),
18198                files: 0,
18199                commits: 0,
18200                empty: false,
18201                failed: None,
18202                verified_noop: None,
18203                duration_ms: 0,
18204                folded: false,
18205            });
18206            let mut task = crate::queue::Task::new(
18207                "task".into(),
18208                "task".into(),
18209                repo.clone(),
18210                crate::queue::Source::Human,
18211            );
18212            task.runs.push(state.id.clone());
18213            crate::queue::Queue::at(home.join("queue"))
18214                .put(&mut task)
18215                .unwrap();
18216            if sidecar {
18217                crate::pr_recovery::retain_sources(&task, &home).unwrap();
18218            }
18219            state.save_under(&home).unwrap();
18220            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
18221            let refusal = fold_run(&mut state, true, &home).await.unwrap_err();
18222            assert!(
18223                matches!(
18224                    refusal.downcast_ref::<FoldRefusal>(),
18225                    Some(FoldRefusal::Retained(retained)) if retained == &reason
18226                ),
18227                "{refusal:#}"
18228            );
18229            let mut disk = state.config.disk.clone();
18230            disk.fold_grace_secs = 0;
18231            assert_eq!(
18232                crate::clean::fold_due(
18233                    &home.join("runs"),
18234                    &home,
18235                    &state.worktree_root(),
18236                    &disk,
18237                    Timestamp::now() + std::time::Duration::from_secs(10),
18238                )
18239                .await
18240                .unwrap(),
18241                (0, 0)
18242            );
18243            assert!(wt.exists());
18244            state.status = RunStatus::Blocked;
18245            state.save_under(&home).unwrap();
18246            let error = override_refusal(&mut state, &home).await;
18247            assert!(
18248                error
18249                    .to_string()
18250                    .contains("requires a finished, non-resumable run"),
18251                "{error:#}"
18252            );
18253            state.status = RunStatus::Superseded;
18254            state.driver_exited = false;
18255            state.driver_claimed = None;
18256            state.save_under(&home).unwrap();
18257            let error = override_refusal(&mut state, &home).await;
18258            assert!(
18259                error
18260                    .to_string()
18261                    .contains("run is live or its ownership is unknown"),
18262                "{error:#}"
18263            );
18264            state.driver_pid = Some(std::process::id());
18265            state.driver_started_at = crate::proc::process_started_at(std::process::id());
18266            state.save_under(&home).unwrap();
18267            let error = override_refusal(&mut state, &home).await;
18268            assert!(
18269                error
18270                    .to_string()
18271                    .contains("run is live or its ownership is unknown"),
18272                "{error:#}"
18273            );
18274            state.driver_exited = true;
18275            state.driver_pid = None;
18276            state.driver_started_at = None;
18277            state.save_under(&home).unwrap();
18278            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
18279            let error = override_refusal(&mut state, &home).await;
18280            assert!(
18281                matches!(
18282                    error.downcast_ref::<FoldRefusal>(),
18283                    Some(FoldRefusal::Live(_))
18284                ),
18285                "{error:#}"
18286            );
18287            drop(lease);
18288            #[cfg(unix)]
18289            {
18290                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
18291                let error = override_refusal(&mut state, &home).await;
18292                assert!(
18293                    matches!(
18294                        error.downcast_ref::<FoldRefusal>(),
18295                        Some(FoldRefusal::Live(_))
18296                    ),
18297                    "{error:#}"
18298                );
18299                drop(output);
18300            }
18301            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
18302            let error = override_refusal(&mut state, &home).await;
18303            assert!(
18304                matches!(
18305                    error.downcast_ref::<FoldRefusal>(),
18306                    Some(FoldRefusal::Live(_))
18307                ),
18308                "{error:#}"
18309            );
18310            drop(owner);
18311            let checkpoint = git::git(
18312                &wt,
18313                &[
18314                    "rev-parse",
18315                    "--path-format=absolute",
18316                    "--git-path",
18317                    "CHERRY_PICK_HEAD",
18318                ],
18319            )
18320            .await
18321            .unwrap();
18322            std::fs::write(&checkpoint, &head).unwrap();
18323            let error = override_refusal(&mut state, &home).await;
18324            assert!(
18325                matches!(
18326                    error.downcast_ref::<FoldRefusal>(),
18327                    Some(FoldRefusal::ProofIncomplete(detail))
18328                        if detail.contains("Git recovery checkpoint retained")
18329                ),
18330                "{error:#}"
18331            );
18332            std::fs::remove_file(checkpoint).unwrap();
18333            std::fs::write(wt.join("dirty"), "keep").unwrap();
18334            let error = override_refusal(&mut state, &home).await;
18335            assert!(
18336                matches!(
18337                    error.downcast_ref::<FoldRefusal>(),
18338                    Some(FoldRefusal::ProofIncomplete(_))
18339                ),
18340                "{error:#}"
18341            );
18342            assert!(wt.join("dirty").exists());
18343            std::fs::remove_file(wt.join("dirty")).unwrap();
18344            let evidence = home
18345                .join("runs")
18346                .join(&state.id)
18347                .join("artifacts/fold-evidence");
18348            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
18349            std::fs::write(&evidence, "blocked archive").unwrap();
18350            let error = override_refusal(&mut state, &home).await;
18351            assert!(
18352                matches!(
18353                    error.downcast_ref::<FoldRefusal>(),
18354                    Some(FoldRefusal::ProofIncomplete(_))
18355                ),
18356                "{error:#}"
18357            );
18358            assert!(wt.exists());
18359            assert!(
18360                !RunState::load_under(&state.id, &home)
18361                    .unwrap()
18362                    .events
18363                    .iter()
18364                    .any(|event| event.message.contains("--override-recovery-retention"))
18365            );
18366            std::fs::remove_file(&evidence).unwrap();
18367            fold_run_overriding_recovery_retention(&mut state, true, &home)
18368                .await
18369                .unwrap();
18370            assert!(!wt.exists());
18371            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
18372            assert!(
18373                git::worktree_holding(&repo, "candidate")
18374                    .await
18375                    .unwrap()
18376                    .is_none()
18377            );
18378            assert!(
18379                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
18380                    .unwrap()
18381                    .contains("retained implementation")
18382            );
18383            assert!(evidence.join(format!("{head}.index")).is_file());
18384            let saved = RunState::load_under(&state.id, &home).unwrap();
18385            assert_eq!(saved.status, RunStatus::Superseded);
18386            assert!(saved.candidates[0].folded);
18387            assert!(saved.events.iter().any(|event| {
18388                event.message.contains("--override-recovery-retention")
18389                    && event.message.contains(&state.id)
18390                    && event.message.contains(&reason)
18391            }));
18392            assert_eq!(
18393                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
18394                sidecar
18395            );
18396        }
18397    }
18398
18399    #[tokio::test]
18400    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
18401        ask_test_home();
18402        let tmp = tempfile::tempdir().unwrap();
18403        let repo = tmp.path().join("repo");
18404        std::fs::create_dir(&repo).unwrap();
18405        init_repo(&repo);
18406        let mut runner = runner_at(RunStatus::Implementing);
18407        runner.state.repo = repo.clone();
18408        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18409        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18410        for (index, label) in ['A', 'B'].into_iter().enumerate() {
18411            let branch = format!("candidate-{label}");
18412            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
18413            git::worktree_add_branch(&repo, &wt, &branch, "main")
18414                .await
18415                .unwrap();
18416            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
18417            git::git(&wt, &["add", "README.md"]).await.unwrap();
18418            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
18419            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
18420            runner.state.candidates.push(Candidate {
18421                index,
18422                label,
18423                agent: "alpha".to_owned(),
18424                branch,
18425                worktree: wt,
18426                summary: "completed implementation".to_owned(),
18427                stat: String::new(),
18428                files: 0,
18429                commits: 0,
18430                empty: false,
18431                failed: None,
18432                verified_noop: None,
18433                duration_ms: 42,
18434                folded: false,
18435            });
18436            runner
18437                .state
18438                .candidate_preservation
18439                .insert(label, "awaiting persistence".to_owned());
18440        }
18441        let wt = runner.state.candidates[0].worktree.clone();
18442        let index_lock = git::git(
18443            &wt,
18444            &[
18445                "rev-parse",
18446                "--path-format=absolute",
18447                "--git-path",
18448                "index.lock",
18449            ],
18450        )
18451        .await
18452        .unwrap();
18453        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18454        runner.state.save().unwrap();
18455        assert!(runner.persist_candidates().await.is_err());
18456        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18457        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
18458        assert_eq!(
18459            runner.state.candidates[1].commits, 1,
18460            "other results are still collected"
18461        );
18462        assert!(
18463            !runner.state.candidates[0].empty,
18464            "failed rescue is not no change"
18465        );
18466        assert_eq!(
18467            runner.state.candidates[0].summary,
18468            "completed implementation"
18469        );
18470        assert!(runner.after_implement().is_err());
18471        // The record the fold locks is the one on disk, so the arrangement is
18472        // saved first; the refusal asserted is the preservation rule's own,
18473        // never `record gone`.
18474        runner.state.save().unwrap();
18475        let refusal = fold_run(&mut runner.state, true, &crate::run::home())
18476            .await
18477            .unwrap_err();
18478        assert!(
18479            matches!(
18480                refusal.downcast_ref::<FoldRefusal>(),
18481                Some(FoldRefusal::ProofIncomplete(detail))
18482                    if detail.contains("candidate preservation incomplete")
18483            ),
18484            "{refusal:#}"
18485        );
18486        assert!(wt.join("new-file").exists());
18487        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
18488        assert!(recovery.join("staged.patch").exists());
18489        assert!(recovery.join("unstaged.patch").exists());
18490        assert_eq!(
18491            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
18492            "untracked edits\n"
18493        );
18494        runner.state.begin_pass();
18495        runner.state.end_pass_parked(ParkCause::Upgrade {
18496            from: "1.0".into(),
18497            to: Some("1.1".into()),
18498        });
18499        runner.state.save().unwrap();
18500        runner.state = RunState::load(&runner.state.id).unwrap();
18501        assert!(matches!(
18502            runner.state.passes.last().unwrap().end,
18503            Some(crate::run::PassEnd::Parked {
18504                cause: ParkCause::Upgrade { .. }
18505            })
18506        ));
18507        std::fs::remove_file(index_lock).unwrap();
18508        // No implementer is configured: a persistence retry cannot dispatch a seat.
18509        runner.implement().await.unwrap();
18510        assert!(runner.state.candidate_preservation.is_empty());
18511        assert!(
18512            runner
18513                .state
18514                .candidates
18515                .iter()
18516                .all(|c| c.commits == 1 && !c.empty)
18517        );
18518        assert!(git::is_clean(&wt).await.unwrap());
18519        assert!(
18520            crate::run::read_artifact(&runner.state, "cand-A.patch")
18521                .unwrap()
18522                .contains("later tracked edits")
18523        );
18524    }
18525
18526    #[tokio::test]
18527    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
18528        ask_test_home();
18529        let tmp = tempfile::tempdir().unwrap();
18530        let repo = tmp.path().join("repo");
18531        std::fs::create_dir(&repo).unwrap();
18532        init_repo(&repo);
18533        let wt = tmp.path().join("candidate");
18534        git::worktree_add_branch(&repo, &wt, "candidate", "main")
18535            .await
18536            .unwrap();
18537        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18538        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
18539        assert!(wt.join("uncommitted").exists());
18540        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18541        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18542        let mut runner = runner_at(RunStatus::Implementing);
18543        runner.state.repo = repo.clone();
18544        runner.state.base_commit = "missing-base".to_owned();
18545        runner.state.candidates.push(Candidate {
18546            index: 0,
18547            label: 'A',
18548            agent: "alpha".into(),
18549            branch: "candidate".into(),
18550            worktree: wt.clone(),
18551            summary: "completed".into(),
18552            stat: String::new(),
18553            files: 0,
18554            commits: 0,
18555            empty: false,
18556            failed: None,
18557            verified_noop: None,
18558            duration_ms: 1,
18559            folded: false,
18560        });
18561        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18562        // Saved in the home the fold uses: without a record the fold would
18563        // refuse as `record gone` and say nothing about the dirty tree.
18564        let home = tmp.path().join("home");
18565        runner.state.save_under(&home).unwrap();
18566        let refusal = fold_run(&mut runner.state, true, &home).await.unwrap_err();
18567        assert!(
18568            refusal
18569                .to_string()
18570                .contains("worktree has uncommitted work; refusing removal"),
18571            "{refusal:#}"
18572        );
18573        assert!(refusal.downcast_ref::<FoldRefusal>().is_none());
18574        assert!(!runner.state.candidates[0].folded);
18575        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18576        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18577        runner
18578            .state
18579            .candidate_preservation
18580            .insert('A', "pending".into());
18581        assert!(runner.persist_candidates().await.is_err());
18582        assert!(!runner.state.candidates[0].empty);
18583        assert!(!runner.state.candidates[0].folded);
18584        assert!(wt.exists());
18585        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18586        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18587        std::fs::create_dir_all(&patch_path).unwrap();
18588        assert!(
18589            runner.persist_candidates().await.is_err(),
18590            "artifact failure stays pending"
18591        );
18592        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18593        assert!(!runner.state.candidates[0].empty);
18594        std::fs::remove_dir(patch_path).unwrap();
18595        runner.persist_candidates().await.unwrap();
18596        assert!(
18597            runner.state.candidates[0].empty,
18598            "only successful inspection confirms no change"
18599        );
18600    }
18601
18602    fn init_repo(dir: &Path) {
18603        let run = |args: &[&str]| {
18604            let out = std::process::Command::new("git")
18605                .args(args)
18606                .current_dir(dir)
18607                .quiet()
18608                .output()
18609                .expect("spawn git");
18610            assert!(
18611                out.status.success(),
18612                "git {args:?} failed: {}",
18613                String::from_utf8_lossy(&out.stderr)
18614            );
18615        };
18616        run(&["init", "-b", "main"]);
18617        run(&["config", "user.name", "magi test"]);
18618        run(&["config", "user.email", "magi@example.com"]);
18619        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18620        run(&["add", "-A"]);
18621        run(&["commit", "-m", "init"]);
18622    }
18623
18624    // `settle_questions` is what closes the ghost the phone showed: a run's
18625    // seat asked something, the run then ended, and nothing was left to
18626    // abandon the question it left `open`. `HOME` is a process-wide
18627    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18628    // first time it runs in the binary — every test below still reaches the
18629    // same directory whichever call won, and each gets its own run id from
18630    // `RunState::new`, so they never collide there.
18631    fn ask_test_home() {
18632        crate::run::pin_test_home();
18633    }
18634
18635    #[test]
18636    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18637        ask_test_home();
18638        let mut runner = runner_at(RunStatus::Prep);
18639        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18640        // A blocked temporary output path makes the terminal save fail while
18641        // preserving the already published reservation.
18642        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18643        let error = guard
18644            .finish(
18645                &mut runner.state,
18646                Err(
18647                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18648                        .into(),
18649                ),
18650            )
18651            .unwrap_err();
18652        assert_eq!(
18653            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18654            std::io::ErrorKind::PermissionDenied
18655        );
18656        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18657        let message = format!("{error:#}");
18658        assert!(message.contains("original refusal"));
18659        assert!(!message.contains("could not save terminal"));
18660        assert_eq!(
18661            error.chain().count(),
18662            2,
18663            "only startup attribution wraps the original error"
18664        );
18665        let saved = RunState::load(&runner.state.id).unwrap();
18666        assert_eq!(saved.status, RunStatus::Blocked);
18667        assert!(!saved.startup.unwrap().complete);
18668    }
18669
18670    #[test]
18671    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18672        ask_test_home();
18673        let mut runner = runner_at(RunStatus::Prep);
18674        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18675        let id = runner.state.id.clone();
18676        drop(guard);
18677        let saved = RunState::load(&id).unwrap();
18678        assert_eq!(saved.status, RunStatus::Blocked);
18679        assert!(!saved.startup.as_ref().unwrap().complete);
18680        assert!(
18681            saved
18682                .startup
18683                .unwrap()
18684                .failure
18685                .unwrap()
18686                .contains("interrupted")
18687        );
18688        assert!(Runner::resume(&id).is_err());
18689    }
18690
18691    #[test]
18692    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18693        ask_test_home();
18694        let mut runner = runner_at(RunStatus::Prep);
18695        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18696        let error = guard
18697            .finish(
18698                &mut runner.state,
18699                Err(
18700                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18701                        .into(),
18702                ),
18703            )
18704            .unwrap_err();
18705        assert_eq!(
18706            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18707            std::io::ErrorKind::PermissionDenied
18708        );
18709        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18710        let mut task = crate::queue::Task::new(
18711            "review".into(),
18712            "criteria".into(),
18713            runner.state.repo.clone(),
18714            crate::queue::Source::Human,
18715        );
18716        task.record_startup_failure(failure.clone());
18717        task.record_startup_failure(failure.clone());
18718        assert_eq!(task.startup_failures.len(), 1);
18719        assert!(task.runs.is_empty());
18720        assert_eq!(task.attempts, 0);
18721    }
18722
18723    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18724        ask_test_home();
18725        let tmp = tempfile::tempdir().unwrap();
18726        let repo = tmp.path().join("repo");
18727        std::fs::create_dir(&repo).unwrap();
18728        init_repo(&repo);
18729        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18730        let origin = tmp.path().join("origin.git");
18731        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18732            .await
18733            .unwrap();
18734        git::git(
18735            &repo,
18736            &["remote", "add", "origin", origin.to_str().unwrap()],
18737        )
18738        .await
18739        .unwrap();
18740        git::git(&repo, &["checkout", "-b", "fix/retained"])
18741            .await
18742            .unwrap();
18743        std::fs::write(repo.join("retained"), "retained change").unwrap();
18744        git::git(&repo, &["add", "."]).await.unwrap();
18745        git::git(&repo, &["commit", "-m", "retained implementation"])
18746            .await
18747            .unwrap();
18748        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18749        git::git(&repo, &["checkout", "main"]).await.unwrap();
18750        std::fs::write(repo.join("base-change"), "new base").unwrap();
18751        git::git(&repo, &["add", "."]).await.unwrap();
18752        git::git(&repo, &["commit", "-m", "base moved"])
18753            .await
18754            .unwrap();
18755        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18756        git::git(&repo, &["checkout", "fix/retained"])
18757            .await
18758            .unwrap();
18759        let mut runner = runner_at(RunStatus::Voting);
18760        runner.state.repo = repo.clone();
18761        runner.state.base_commit = base;
18762        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18763        runner.state.config.disk.min_free_bytes = 0;
18764        runner.state.config.graph.review_rounds = 1;
18765        runner.state.config.verify.e2e = vec!["true".into()];
18766        runner.state.config.verify.gate = vec!["true".into()];
18767        runner.state.candidates = vec![Candidate {
18768            index: 0,
18769            label: 'A',
18770            agent: "fixture".into(),
18771            branch: "fix/retained".into(),
18772            worktree: repo.clone(),
18773            summary: String::new(),
18774            stat: String::new(),
18775            files: 1,
18776            commits: 1,
18777            empty: false,
18778            failed: None,
18779            verified_noop: None,
18780            duration_ms: 0,
18781            folded: false,
18782        }];
18783        runner.state.tally = Some(Tally {
18784            first_choice: BTreeMap::new(),
18785            borda: BTreeMap::new(),
18786            winner: 'A',
18787            rankings: 0,
18788            unanimous_initial: true,
18789            deliberated: false,
18790            changed_votes: 0,
18791            unanimous_final: true,
18792            tie_break: None,
18793            judges: 0,
18794            present: 0,
18795            quorum: 0,
18796            met_quorum: true,
18797            uncontested: Some("review-only".into()),
18798        });
18799        let mut task = crate::queue::Task::new(
18800            "fixture".into(),
18801            "fixture".into(),
18802            repo,
18803            crate::queue::Source::Human,
18804        );
18805        task.link_run(&runner.state.id);
18806        crate::queue::Queue::open().put(&mut task).unwrap();
18807        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18808        runner.state.base_sync = Some(BaseSync {
18809            tip: String::new(),
18810            behind: 1,
18811            attempts: BASE_SYNC_ROUNDS,
18812            conflict: None,
18813            already_in: None,
18814        });
18815        runner.sync_to_base().await.unwrap();
18816        assert_eq!(runner.state.status, RunStatus::Blocked);
18817        (tmp, runner, head, task.id)
18818    }
18819
18820    #[tokio::test]
18821    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18822        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18823        runner.state.status = RunStatus::Voting;
18824        runner.state.base_sync = None;
18825        runner.state.base_sync_recovery = Default::default();
18826        let scratch = runner.state.dir().join("base-sync");
18827        std::fs::create_dir_all(&scratch).unwrap();
18828        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18829        runner.sync_to_base().await.unwrap();
18830        assert!(runner.state.resource_block.is_some());
18831        assert!(!runner.state.base_sync_blocked());
18832        assert!(runner.state.base_sync.is_none());
18833        assert_eq!(
18834            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18835            "keep"
18836        );
18837        assert_eq!(runner.state.base_episode_used(), 0);
18838        assert!(runner.state.base_sync_recovery.operations.is_empty());
18839        assert!(runner.state.rebase_fixes.is_empty());
18840        assert_eq!(
18841            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18842            head
18843        );
18844        std::fs::remove_dir_all(&scratch).unwrap();
18845        runner.state.resource_block = None;
18846        runner.sync_to_base().await.unwrap();
18847        assert!(!runner.state.base_sync_blocked());
18848        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18849        assert_eq!(runner.state.base_episode_used(), 1);
18850        assert!(runner.state.base_sync_recovery.operations[0].finished);
18851        assert!(runner.state.rebase_fixes.is_empty());
18852        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18853        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18854    }
18855
18856    #[tokio::test]
18857    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18858        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18859        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18860        runner.state.base_sync_recovery = Default::default();
18861        runner.state.task_instruction = Some("fixture".into());
18862        runner.state.config.agents = vec![spec("fixture")];
18863        runner.state.config.graph.review_rounds = 0;
18864        runner.state.config.merge.mode = MergeMode::None;
18865        runner.state.driver_exited = true;
18866        let sync = runner.state.base_sync.as_mut().unwrap();
18867        sync.conflict = None;
18868        sync.attempts = 0;
18869        runner.state.reserve_base_operation(&head, &tip);
18870        runner.state.finish_base_operation(None);
18871        let detail = format!(
18872            "fix/retained conflicts with origin/main and did not rebase: \
18873             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18874             remaining conflicted path(s): none recorded; git said: \
18875             warning: execution failed: {}",
18876            git::REBASE_EXEC
18877        );
18878        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18879        runner.state.record_base_sync_stop(&head);
18880        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18881            unstarted: false,
18882            agent: "fixture".into(),
18883            paths: Vec::new(),
18884            from: Some(head.clone()),
18885            finished: true,
18886            error: None,
18887            stop: None,
18888            onto: None,
18889            index_outside: None,
18890            launcher: None,
18891            infra: None,
18892            outage: None,
18893        });
18894        runner.state.save().unwrap();
18895        assert_eq!(
18896            crate::resume::validate(&crate::run::home(), &runner.state.id)
18897                .unwrap()
18898                .id,
18899            runner.state.id
18900        );
18901
18902        let dirty = runner.state.repo.join("owner-work");
18903        std::fs::write(&dirty, "keep").unwrap();
18904        runner.sync_to_base().await.unwrap();
18905        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18906        assert!(runner.state.base_sync_recovery.operations[0].finished);
18907        assert!(runner.state.base_sync_blocked());
18908        std::fs::remove_file(dirty).unwrap();
18909
18910        let queue = crate::queue::Queue::open();
18911        let id = runner.state.id.clone();
18912        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18913        let _claim = queue.claim(&owner).unwrap();
18914        let mut task = queue.get(&owner).unwrap();
18915        let config = tmp.path().join("test-config.toml");
18916        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18917        let opts = crate::daemon::Opts {
18918            repo: task.repo.clone(),
18919            config: Some(config),
18920            ..Default::default()
18921        };
18922        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18923        let task = queue.get(&owner).unwrap();
18924        assert_eq!(
18925            task.runs.as_slice(),
18926            std::slice::from_ref(&id),
18927            "{:?}",
18928            task.hold_reason
18929        );
18930        runner.state = RunState::load(&id).unwrap();
18931        assert!(!runner.state.base_sync_blocked());
18932        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18933        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18934        assert!(runner.state.base_sync_recovery.operations[0].finished);
18935        assert_eq!(
18936            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18937            detail
18938        );
18939        assert_eq!(runner.state.rebase_fixes.len(), 1);
18940        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18941    }
18942
18943    #[cfg(unix)]
18944    #[tokio::test]
18945    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18946        for routed in [false, true] {
18947            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18948            let home = crate::run::home();
18949            let queue = crate::queue::Queue::open();
18950            let task = queue.get(&owner).unwrap();
18951            runner.state.task_instruction = Some(task.instruction.clone());
18952            runner.state.driver_exited = true;
18953            runner.state.save().unwrap();
18954            let questions = crate::ask::Questions::at(home.join("questions"));
18955            let mut q = crate::ask::Question::new(
18956                runner.state.id.clone(),
18957                "base-recovery".into(),
18958                "owner".into(),
18959                "Recover bounded base movement?".into(),
18960                String::new(),
18961                vec!["recover".into()],
18962            );
18963            q.actions.insert(
18964                "recover".into(),
18965                crate::ask::ChoiceAction::RecoverBase {
18966                    run: runner.state.id.clone(),
18967                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
18968                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
18969                },
18970            );
18971            q.routed_task = Some(owner.clone());
18972            q.answer(crate::ask::Answer::Choice("recover".into()))
18973                .unwrap();
18974            questions.put(&mut q).unwrap();
18975            crate::base_recovery_control::recover(
18976                &queue,
18977                &home,
18978                crate::base_recovery_control::Request {
18979                    run: runner.state.id.clone(),
18980                    head: head.clone(),
18981                    actor: "decisions".into(),
18982                    request: q.id.clone(),
18983                    decision: Some((owner.clone(), q.answered_at.unwrap())),
18984                    expected_stop: Some((
18985                        runner.state.base_sync_recovery.stop.clone().unwrap(),
18986                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
18987                    )),
18988                    evidence_digest: None,
18989                },
18990            )
18991            .await
18992            .unwrap();
18993            if routed {
18994                questions
18995                    .update(&q.id, |q| {
18996                        q.routed_task = Some("another-owner".into());
18997                        Ok(())
18998                    })
18999                    .unwrap();
19000            } else {
19001                let mut task = queue.get(&owner).unwrap();
19002                task.hold_manual(Some("new owner decision".into()));
19003                // Keep the generation to exercise the separate owner-decision binding.
19004                task.status = crate::queue::TaskStatus::Queued;
19005                queue.put(&mut task).unwrap();
19006            }
19007            runner.state = RunState::load(&runner.state.id).unwrap();
19008            runner.sync_to_base().await.unwrap();
19009            let approval = runner
19010                .state
19011                .base_sync_recovery
19012                .authorizations
19013                .last()
19014                .unwrap();
19015            assert!(approval.consumed);
19016            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
19017                "routing"
19018            } else {
19019                "owner decision"
19020            }));
19021            assert_eq!(
19022                runner.state.base_sync.as_ref().unwrap().attempts,
19023                BASE_SYNC_ROUNDS
19024            );
19025            assert_eq!(
19026                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19027                head
19028            );
19029        }
19030    }
19031
19032    #[cfg(unix)]
19033    #[tokio::test]
19034    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
19035        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
19036        if std::env::var_os(CHILD).is_none() {
19037            let home = tempfile::tempdir().unwrap();
19038            let output = std::process::Command::new(std::env::current_exe().unwrap())
19039                .args([
19040                    "--exact",
19041                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
19042                    "--nocapture",
19043                ])
19044                .env(CHILD, "1")
19045                .env("MAGI_HOME", home.path())
19046                .env("MAGI_WORKER_HOME", home.path())
19047                .env("MAGI_WORKER_ID", "abcdef")
19048                .output()
19049                .unwrap();
19050            assert!(
19051                output.status.success()
19052                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19053                "{}\n{}",
19054                String::from_utf8_lossy(&output.stdout),
19055                String::from_utf8_lossy(&output.stderr)
19056            );
19057            return;
19058        }
19059        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
19060        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19061        let home = crate::run::home();
19062        let queue = crate::queue::Queue::open();
19063        let mut owner = queue.get(&task).unwrap();
19064        owner.release_operator("test-release", None);
19065        owner.start(runner.state.id.clone());
19066        queue.put(&mut owner).unwrap();
19067        runner.state.driver_exited = true;
19068        runner.state.task_instruction = Some(owner.instruction.clone());
19069        runner.state.save().unwrap();
19070        let _claim = queue.claim(&task).unwrap();
19071        let reserve = |id: &str| {
19072            let directory = home.join("workers/jobs").join(id);
19073            std::fs::create_dir_all(&directory).unwrap();
19074            let job = crate::worker::Job {
19075                id: id.into(),
19076                sequence: 1,
19077                kind: "task".into(),
19078                key: format!("task:{task}"),
19079                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
19080                generation: "fixture-generation".into(),
19081                version: None,
19082                status: crate::worker::Status::Running,
19083                result: None,
19084                pid: Some(std::process::id()),
19085                created_at: 0,
19086                finished_at: None,
19087            };
19088            std::fs::write(
19089                directory.join("job.json"),
19090                serde_json::to_vec(&job).unwrap(),
19091            )
19092            .unwrap();
19093            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
19094        };
19095        let _own = reserve("abcdef");
19096        let other = reserve("fedcba");
19097        assert!(
19098            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19099                .await
19100                .is_err()
19101        );
19102        assert!(
19103            RunState::load(&runner.state.id)
19104                .unwrap()
19105                .base_sync_recovery
19106                .authorizations
19107                .is_empty()
19108        );
19109        drop(other);
19110        assert!(crate::daemon::is_working_on(
19111            &home,
19112            &runner.state.id,
19113            Timestamp::now()
19114        ));
19115        assert!(
19116            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
19117        );
19118        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19119            .await
19120            .unwrap();
19121        assert!(
19122            RunState::load(&runner.state.id)
19123                .unwrap()
19124                .base_recovery_pending()
19125        );
19126    }
19127
19128    #[cfg(unix)]
19129    #[tokio::test]
19130    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
19131        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19132        let home = crate::run::home();
19133        runner.state.driver_pid = Some(std::process::id());
19134        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
19135        runner.state.driver_exited = false;
19136        runner.state.begin_pass();
19137        runner.state.save().unwrap();
19138        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
19139        driver.record(&runner.state).unwrap();
19140        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
19141        // Preserve the durable claim as if the process died before Drop saved.
19142        drop(driver);
19143        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
19144        assert_eq!(
19145            runner.state.liveness_under(&home, false),
19146            crate::run::Liveness::Dead
19147        );
19148        let queue = crate::queue::Queue::open();
19149        let _claim = queue.claim(&task).unwrap();
19150        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19151            .await
19152            .unwrap();
19153        let disk = RunState::load(&runner.state.id).unwrap();
19154        assert!(!disk.driver_exited);
19155        assert!(disk.base_recovery_pending());
19156    }
19157
19158    #[cfg(unix)]
19159    #[tokio::test]
19160    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
19161        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
19162        if std::env::var_os(CHILD).is_none() {
19163            use std::os::unix::fs::PermissionsExt;
19164            let tmp = tempfile::tempdir().unwrap();
19165            let gh = tmp.path().join("gh");
19166            std::fs::write(&gh, r#"#!/bin/sh
19167case "$1 $2" in
19168  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
19169  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
19170  *) exit 2 ;;
19171esac
19172"#).unwrap();
19173            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
19174            let mut paths = vec![tmp.path().to_path_buf()];
19175            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
19176            let output = std::process::Command::new(std::env::current_exe().unwrap())
19177                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
19178                .env(CHILD, "1")
19179                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
19180                .env("PATH", std::env::join_paths(paths).unwrap())
19181                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
19182                .output().unwrap();
19183            assert!(
19184                output.status.success()
19185                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19186                "{}\n{}",
19187                String::from_utf8_lossy(&output.stdout),
19188                String::from_utf8_lossy(&output.stderr)
19189            );
19190            return;
19191        }
19192        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19193        let repo = runner.state.repo.clone();
19194        git::git(&repo, &["checkout", "main"]).await.unwrap();
19195        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
19196        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19197        git::git(&repo, &["checkout", "fix/retained"])
19198            .await
19199            .unwrap();
19200        runner.state.pr = Some(crate::run::PrRecord {
19201            url: "https://example.test/project/pull/1".into(),
19202            number: 1,
19203            state: "open".into(),
19204            checks: "unknown".into(),
19205            round: 0,
19206            rounds: 1,
19207            red_at_merge: Vec::new(),
19208        });
19209        runner.sync_to_base().await.unwrap();
19210        assert_eq!(runner.state.status, RunStatus::Blocked);
19211        assert_eq!(
19212            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19213            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
19214        );
19215        assert!(runner.state.base_sync_closure_pending());
19216        assert!(crate::handover::can_resume(&runner.state));
19217        let queue = crate::queue::Queue::open();
19218        assert!(!crate::base_sync_recovery::held_task(
19219            &queue,
19220            &queue.get(&task).unwrap()
19221        ));
19222        assert!(runner.state.authorize_base_sync(&task).is_err());
19223        // Legacy closure stops have no typed stop but must retain the checkpoint.
19224        runner.state.base_sync_recovery.stop = None;
19225        runner.state.status = RunStatus::Voting;
19226        runner.state.gate_ran = true;
19227        runner.state.config.graph.review_rounds = 0;
19228        runner.state.save().unwrap();
19229        assert!(crate::handover::can_resume(&runner.state));
19230        runner.state = RunState::load(&runner.state.id).unwrap();
19231        runner.execute_graph().await.unwrap();
19232        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
19233        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
19234        assert_eq!(
19235            runner.state.base_sync.as_ref().unwrap().attempts,
19236            BASE_SYNC_ROUNDS
19237        );
19238        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
19239        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
19240        assert!(runner.state.reviews.is_empty());
19241        assert!(runner.state.gate.is_empty());
19242    }
19243
19244    #[cfg(unix)]
19245    #[tokio::test]
19246    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
19247        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19248        runner.state.driver_exited = true;
19249        runner.state.save().unwrap();
19250        let home = crate::run::home();
19251        let queue = crate::queue::Queue::open();
19252        let _claim = queue.claim(&task).unwrap();
19253        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
19254        assert!(
19255            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19256                .await
19257                .is_err()
19258        );
19259        drop(lease);
19260        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
19261        assert!(
19262            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19263                .await
19264                .is_err()
19265        );
19266        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
19267        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19268            .await
19269            .unwrap();
19270        let disk = RunState::load(&runner.state.id).unwrap();
19271        assert!(disk.base_recovery_pending());
19272        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
19273        assert!(
19274            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19275                .await
19276                .is_err()
19277        );
19278        assert_eq!(
19279            RunState::load(&runner.state.id)
19280                .unwrap()
19281                .base_sync_recovery
19282                .authorizations
19283                .len(),
19284            1
19285        );
19286        let mut owner = queue.get(&task).unwrap();
19287        owner.runs.push("20260101-000000-ffff".into());
19288        queue.put(&mut owner).unwrap();
19289        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19290            .await
19291            .unwrap_err();
19292        assert!(error.to_string().contains("run task ownership changed"));
19293    }
19294
19295    #[cfg(unix)]
19296    #[tokio::test]
19297    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
19298        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19299        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19300        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
19301        legacy["status"] = serde_json::json!("voting");
19302        runner.state = serde_json::from_value(legacy).unwrap();
19303        runner.state.save().unwrap();
19304        for _ in 0..3 {
19305            runner.execute_graph().await.unwrap();
19306            assert_eq!(runner.state.status, RunStatus::Blocked);
19307            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19308            assert!(!crate::handover::can_resume(&runner.state));
19309            assert_eq!(
19310                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19311                head
19312            );
19313            assert!(runner.state.reviews.is_empty());
19314            assert!(!runner.state.gate_ran);
19315        }
19316        let notice = crate::notices::run_ended(&runner.state).unwrap();
19317        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
19318        runner.state.begin_pass();
19319        runner.state.status = RunStatus::Voting;
19320        runner.deliberate().await.unwrap();
19321        runner.vote().await.unwrap();
19322        runner.finish_after_tally().await.unwrap();
19323        assert_eq!(runner.state.status, RunStatus::Blocked);
19324        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
19325        assert_eq!(
19326            crate::notices::run_ended(&runner.state).unwrap().since,
19327            notice.since
19328        );
19329    }
19330
19331    #[cfg(unix)]
19332    #[tokio::test]
19333    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
19334        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19335        for detail in [
19336            "fix/retained conflicts with origin/main and did not rebase: conflict",
19337            "rebased fix/retained locally but origin refused the push",
19338            "unknown failure",
19339        ] {
19340            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
19341            runner.state.record_base_sync_stop(&head);
19342            assert!(runner.state.authorize_base_sync(&task).is_err());
19343            runner.state.status = RunStatus::Voting;
19344            runner.execute_graph().await.unwrap();
19345            assert_eq!(runner.state.status, RunStatus::Blocked);
19346            assert!(!crate::handover::can_resume(&runner.state));
19347            assert_eq!(
19348                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19349                head
19350            );
19351        }
19352    }
19353
19354    #[tokio::test]
19355    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
19356        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19357        let state = &mut runner.state;
19358        let tip = state.base_sync.as_ref().unwrap().tip.clone();
19359        let branch = state.winner().unwrap().branch.clone();
19360        state.base_sync_recovery = Default::default();
19361        state.base_sync.as_mut().unwrap().attempts = 0;
19362        state.reserve_base_operation(&head, &tip);
19363        state.finish_base_operation(None);
19364        let detail = format!(
19365            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
19366        );
19367        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
19368        state.event("land", detail);
19369        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
19370        assert!(state.unknown_preparation_stop(&head));
19371        let digest = state.preparation_digest(&head).unwrap();
19372        state
19373            .base_sync_recovery
19374            .operations
19375            .last_mut()
19376            .unwrap()
19377            .validated_head = Some(head.clone());
19378        assert!(!state.unknown_preparation_stop(&head));
19379        state
19380            .base_sync_recovery
19381            .operations
19382            .last_mut()
19383            .unwrap()
19384            .validated_head = None;
19385        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
19386        state.driver_exited = true;
19387        state.save().unwrap();
19388        let home = crate::run::home();
19389        let queue = crate::queue::Queue::open();
19390        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
19391            .await
19392            .unwrap();
19393        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
19394        assert_eq!(inspection["evidence_digest"], digest);
19395        let request = crate::base_recovery_control::Request {
19396            run: state.id.clone(),
19397            head: head.clone(),
19398            actor: "test".into(),
19399            request: "preparation".into(),
19400            decision: None,
19401            expected_stop: None,
19402            evidence_digest: Some(digest),
19403        };
19404        let mut stale = request.clone();
19405        stale.evidence_digest = Some("stale".into());
19406        assert!(
19407            crate::base_recovery_control::recover(&queue, &home, stale)
19408                .await
19409                .is_err()
19410        );
19411        let scratch = state.dir().join("base-sync");
19412        std::fs::create_dir(&scratch).unwrap();
19413        assert!(
19414            crate::base_recovery_control::recover(&queue, &home, request.clone())
19415                .await
19416                .is_err()
19417        );
19418        std::fs::remove_dir(&scratch).unwrap();
19419        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
19420        git::git(
19421            &state.repo,
19422            &[
19423                "commit",
19424                "--allow-empty",
19425                "-m",
19426                "base advanced after inspection",
19427            ],
19428        )
19429        .await
19430        .unwrap();
19431        git::git(&state.repo, &["push", "origin", "main"])
19432            .await
19433            .unwrap();
19434        git::git(&state.repo, &["checkout", "fix/retained"])
19435            .await
19436            .unwrap();
19437        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
19438            .await
19439            .unwrap();
19440        assert!(!outcome.repeated);
19441        assert!(
19442            crate::base_recovery_control::recover(&queue, &home, request)
19443                .await
19444                .unwrap()
19445                .repeated
19446        );
19447        runner.state = RunState::load(&runner.state.id).unwrap();
19448        assert!(runner.state.base_recovery_pending());
19449        runner.sync_to_base().await.unwrap();
19450        assert!(!runner.state.base_sync_blocked());
19451        assert!(!runner.state.consume_base_recovery(&head));
19452        assert_eq!(runner.state.base_episode_used(), 2);
19453        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19454        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19455        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
19456    }
19457
19458    #[cfg(unix)]
19459    #[tokio::test]
19460    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
19461        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19462        runner.state.authorize_base_sync(&task).unwrap();
19463        assert!(runner.state.consume_base_recovery(&head));
19464        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19465        runner.state.reserve_base_operation(&head, &tip);
19466        runner.state.save().unwrap();
19467        runner.state = RunState::load(&runner.state.id).unwrap();
19468        assert!(!runner.state.consume_base_recovery(&head));
19469        runner.sync_to_base().await.unwrap();
19470        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19471        assert_eq!(runner.state.base_episode_used(), 1);
19472        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19473        assert!(
19474            runner
19475                .state
19476                .base_sync_recovery
19477                .operations
19478                .last()
19479                .unwrap()
19480                .finished
19481        );
19482        assert!(!runner.state.base_sync_blocked());
19483        runner.sync_to_base().await.unwrap();
19484        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19485    }
19486
19487    #[cfg(unix)]
19488    #[tokio::test]
19489    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
19490        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19491        // Both historical diagnostic spellings retain an exhaustion identity.
19492        let original = runner
19493            .state
19494            .base_sync
19495            .as_ref()
19496            .unwrap()
19497            .conflict
19498            .clone()
19499            .unwrap();
19500        runner.state.base_sync.as_mut().unwrap().conflict = Some(
19501            original
19502                .replace("synchronization(s)", "rebase(s)")
19503                .replace("synchronizing", "rebasing"),
19504        );
19505        runner.state.base_sync_recovery = Default::default();
19506        runner.state.record_base_sync_stop(&head);
19507        assert_eq!(
19508            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19509            crate::base_sync_recovery::StopKind::Exhausted
19510        );
19511        runner.state.authorize_base_sync(&task).unwrap();
19512        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19513        let auth = legacy["base_sync_recovery"]["authorizations"][0]
19514            .as_object_mut()
19515            .unwrap();
19516        auth.remove("interval");
19517        auth.remove("scope");
19518        runner.state = serde_json::from_value(legacy).unwrap();
19519        assert!(runner.state.consume_base_recovery(&head));
19520        assert_eq!(runner.state.base_episode_used(), 3);
19521        runner.sync_to_base().await.unwrap();
19522        assert_eq!(runner.state.base_episode_used(), 4);
19523        runner.state.resource_block = Some(crate::run::ResourceBlock {
19524            node: "gate".into(),
19525            kind: "cache".into(),
19526            detail: "legacy wait".into(),
19527            at: Timestamp::now(),
19528            cause: crate::run::ResourceBlockCause::Unrecorded,
19529        });
19530        runner.state.save().unwrap();
19531        assert!(
19532            runner
19533                .state
19534                .base_sync_recovery
19535                .episodes
19536                .last()
19537                .unwrap()
19538                .boundary
19539                .is_none()
19540        );
19541        runner.state.resource_block = None;
19542        advance_base_fixture(&runner).await;
19543        runner.sync_to_base().await.unwrap();
19544        assert!(runner.state.base_sync_blocked());
19545        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19546    }
19547
19548    #[cfg(unix)]
19549    async fn advance_base_fixture(runner: &Runner) {
19550        let repo = &runner.state.repo;
19551        for args in [
19552            vec!["checkout", "main"],
19553            vec!["commit", "--allow-empty", "-m", "base advanced"],
19554            vec!["push", "origin", "main"],
19555            vec!["checkout", "fix/retained"],
19556        ] {
19557            git::git(repo, &args).await.unwrap();
19558        }
19559    }
19560
19561    #[cfg(unix)]
19562    fn fresh_base_interval_fixture(runner: &mut Runner) {
19563        runner.state.base_sync.as_mut().unwrap().attempts = 0;
19564        runner.state.base_sync.as_mut().unwrap().conflict = None;
19565        runner.state.base_sync_recovery = Default::default();
19566        runner.state.status = RunStatus::Voting;
19567    }
19568
19569    #[cfg(unix)]
19570    #[tokio::test]
19571    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
19572        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19573        fresh_base_interval_fixture(&mut runner);
19574        runner.state.begin_pass();
19575        runner.sync_to_base().await.unwrap();
19576        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19577        runner.state.resource_block = Some(crate::run::ResourceBlock {
19578            node: "gate".into(),
19579            kind: "build cache".into(),
19580            detail: "busy".into(),
19581            at: Timestamp::now(),
19582            cause: crate::run::ResourceBlockCause::Timeout {
19583                waited_secs: 1,
19584                limit_secs: 1,
19585            },
19586        });
19587        runner.state.save().unwrap();
19588        let queue = crate::queue::Queue::open();
19589        let mut owner = queue.get(&task).unwrap();
19590        runner.state.task_instruction = Some(owner.instruction.clone());
19591        owner.release_operator("fixture-owner", None);
19592        queue.put(&mut owner).unwrap();
19593        let approval = owner.resumption.clone().unwrap();
19594        runner.state.resource_block = None;
19595        runner.state.save().unwrap();
19596        runner.state = RunState::load(&runner.state.id).unwrap();
19597        advance_base_fixture(&runner).await;
19598        runner.sync_to_base().await.unwrap();
19599        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19600        assert_eq!(runner.state.base_episode_used(), 1);
19601        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19602        assert!(
19603            runner.state.base_sync_recovery.episodes[0]
19604                .boundary
19605                .as_ref()
19606                .unwrap()
19607                .consumed
19608        );
19609        assert!(
19610            !runner
19611                .state
19612                .renew_base_episode(&task, &approval, &head, "base")
19613        );
19614        for _ in 0..3 {
19615            owner.release_operator("fixture-owner", None);
19616            queue.put(&mut owner).unwrap();
19617            runner.state = RunState::load(&runner.state.id).unwrap();
19618            runner.state.begin_pass();
19619            runner.sync_to_base().await.unwrap();
19620            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19621            assert_eq!(runner.state.base_episode_used(), 1);
19622        }
19623        runner.state.resource_block = Some(crate::run::ResourceBlock {
19624            node: "gate".into(),
19625            kind: "disk pressure".into(),
19626            detail: "free space required".into(),
19627            at: Timestamp::now(),
19628            cause: crate::run::ResourceBlockCause::Other,
19629        });
19630        runner.state.end_pass_parked(ParkCause::Interrupt {
19631            reason: "disk pressure".into(),
19632        });
19633        runner.state.save().unwrap();
19634        owner.release_operator("fixture-owner-after-disk", None);
19635        queue.put(&mut owner).unwrap();
19636        runner.state.resource_block = None;
19637        advance_base_fixture(&runner).await;
19638        runner.sync_to_base().await.unwrap();
19639        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19640        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19641        assert_eq!(runner.state.base_episode_used(), 1);
19642        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19643    }
19644
19645    #[cfg(unix)]
19646    #[tokio::test]
19647    async fn base_recovery_continuous_advancement_stops_at_four() {
19648        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19649        fresh_base_interval_fixture(&mut runner);
19650        for spent in 1..=BASE_SYNC_ROUNDS {
19651            runner.sync_to_base().await.unwrap();
19652            assert!(!runner.state.base_sync_blocked());
19653            assert_eq!(runner.state.base_episode_used(), spent);
19654            advance_base_fixture(&runner).await;
19655        }
19656        runner.sync_to_base().await.unwrap();
19657        assert_eq!(
19658            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19659            crate::base_sync_recovery::StopKind::Exhausted
19660        );
19661        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19662        assert!(stop.unverified_sync);
19663        let action = runner.state.base_sync_next_action();
19664        assert!(action.contains("never reached its gate"));
19665        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19666        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19667        runner.state = RunState::load(&runner.state.id).unwrap();
19668        runner.sync_to_base().await.unwrap();
19669        assert_eq!(runner.state.base_episode_used(), 4);
19670        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19671    }
19672
19673    #[cfg(unix)]
19674    #[tokio::test]
19675    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19676        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19677        runner.state.ensure_base_episode();
19678        // Verification progress alone is not evidence of a successful sync.
19679        runner.state.record_base_progress(&head);
19680        runner.state.base_sync_recovery.stop = None;
19681        runner.state.record_base_sync_stop(&head);
19682        assert!(
19683            !runner
19684                .state
19685                .base_sync_recovery
19686                .stop
19687                .as_ref()
19688                .unwrap()
19689                .unverified_sync
19690        );
19691
19692        runner.state.finish_base_operation(Some(&head));
19693        // A gate for another head cannot verify this synchronization.
19694        runner.state.gate_ran = true;
19695        runner.state.gate_head = Some("older-head".into());
19696        runner.state.base_sync_recovery.stop = None;
19697        runner.state.record_base_sync_stop(&head);
19698        runner.state.save().unwrap();
19699        runner.state = RunState::load(&runner.state.id).unwrap();
19700        assert!(
19701            runner
19702                .state
19703                .base_sync_recovery
19704                .stop
19705                .as_ref()
19706                .unwrap()
19707                .unverified_sync
19708        );
19709
19710        runner.state.gate_head = Some(head.clone());
19711        runner.state.base_sync_recovery.stop = None;
19712        runner.state.record_base_sync_stop(&head);
19713        assert!(
19714            !runner
19715                .state
19716                .base_sync_recovery
19717                .stop
19718                .as_ref()
19719                .unwrap()
19720                .unverified_sync
19721        );
19722        assert!(
19723            !runner
19724                .state
19725                .base_sync_next_action()
19726                .contains("never reached its gate")
19727        );
19728
19729        // Historical records cannot establish the missing synchronization evidence.
19730        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19731        legacy["base_sync_recovery"]["stop"]
19732            .as_object_mut()
19733            .unwrap()
19734            .remove("unverified_sync");
19735        legacy["base_sync_recovery"]["episodes"][0]
19736            .as_object_mut()
19737            .unwrap()
19738            .remove("last_sync_head");
19739        runner.state = serde_json::from_value(legacy).unwrap();
19740        assert!(
19741            !runner
19742                .state
19743                .base_sync_recovery
19744                .stop
19745                .as_ref()
19746                .unwrap()
19747                .unverified_sync
19748        );
19749        assert!(
19750            runner.state.base_sync_recovery.episodes[0]
19751                .last_sync_head
19752                .is_none()
19753        );
19754    }
19755
19756    #[cfg(unix)]
19757    #[tokio::test]
19758    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19759        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19760        runner.state.authorize_base_sync(&task).unwrap();
19761        assert!(
19762            runner
19763                .state
19764                .base_sync_next_action()
19765                .contains("Approval recorded")
19766        );
19767        assert!(
19768            runner
19769                .state
19770                .base_sync_next_action()
19771                .contains("4/4 in episode 0, 4 lifetime")
19772        );
19773        assert!(runner.state.consume_base_recovery(&head));
19774        assert!(
19775            runner
19776                .state
19777                .base_sync_next_action()
19778                .contains("0/4 in episode 1, 4 lifetime")
19779        );
19780    }
19781
19782    #[cfg(unix)]
19783    #[tokio::test]
19784    async fn base_recovery_changed_head_invalidates_without_spending() {
19785        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19786        runner.state.authorize_base_sync(&task).unwrap();
19787        git::git(
19788            &runner.state.repo,
19789            &["commit", "--allow-empty", "-m", "external head change"],
19790        )
19791        .await
19792        .unwrap();
19793        runner.sync_to_base().await.unwrap();
19794        let a = runner
19795            .state
19796            .base_sync_recovery
19797            .authorizations
19798            .last()
19799            .unwrap();
19800        assert!(a.consumed);
19801        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19802        runner.state = RunState::load(&runner.state.id).unwrap();
19803        assert!(
19804            runner
19805                .state
19806                .base_sync_next_action()
19807                .contains("Approval invalidated")
19808        );
19809        assert!(!runner.state.base_recovery_pending());
19810        assert!(runner.state.base_sync_blocked());
19811        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19812    }
19813
19814    #[cfg(unix)]
19815    #[tokio::test]
19816    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19817        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19818        runner.state.driver_exited = true;
19819        runner.state.save().unwrap();
19820        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19821            .await
19822            .unwrap();
19823        runner.state = RunState::load(&runner.state.id).unwrap();
19824        advance_base_fixture(&runner).await;
19825        runner.sync_to_base().await.unwrap();
19826        let a = runner
19827            .state
19828            .base_sync_recovery
19829            .authorizations
19830            .last()
19831            .unwrap();
19832        assert!(
19833            a.consumed
19834                && a.invalidated
19835                    .as_deref()
19836                    .unwrap()
19837                    .contains("fetched base changed")
19838        );
19839        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19840        assert_eq!(
19841            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19842            head
19843        );
19844        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19845            .await
19846            .unwrap();
19847        runner.state = RunState::load(&runner.state.id).unwrap();
19848        runner.sync_to_base().await.unwrap();
19849        assert!(!runner.state.base_sync_blocked());
19850        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19851    }
19852
19853    #[cfg(unix)]
19854    #[tokio::test]
19855    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19856        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19857        runner.state.authorize_base_sync(&task).unwrap();
19858        assert!(runner.state.consume_base_recovery(&head));
19859        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19860        runner.state.reserve_base_operation(&head, &tip);
19861        runner.state.save().unwrap();
19862        let scratch = runner.state.dir().join("base-sync");
19863        assert_eq!(
19864            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19865                .await
19866                .unwrap(),
19867            crate::rebase::Rebased::Applied
19868        );
19869        runner.state = RunState::load(&runner.state.id).unwrap();
19870        runner.sync_to_base().await.unwrap();
19871        assert!(
19872            runner
19873                .state
19874                .base_sync_recovery
19875                .operations
19876                .last()
19877                .unwrap()
19878                .finished
19879        );
19880        assert_eq!(runner.state.base_episode_used(), 1);
19881        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19882        assert!(!runner.state.base_sync_blocked());
19883    }
19884
19885    #[cfg(unix)]
19886    #[tokio::test]
19887    async fn base_recovery_crash_preserves_untracked_files() {
19888        for ignored in [false, true] {
19889            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19890            runner.state.authorize_base_sync(&task).unwrap();
19891            assert!(runner.state.consume_base_recovery(&head));
19892            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19893            runner.state.reserve_base_operation(&head, &tip);
19894            runner.state.save().unwrap();
19895            let scratch = runner.state.dir().join("base-sync");
19896            assert_eq!(
19897                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19898                    .await
19899                    .unwrap(),
19900                crate::rebase::Rebased::Applied
19901            );
19902            let repo = &runner.state.repo;
19903            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19904            assert_ne!(result, head);
19905            if ignored {
19906                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19907                    .await
19908                    .unwrap();
19909                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19910            }
19911            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19912            assert!(
19913                git::git_raw(repo, &["diff", "--quiet", &head])
19914                    .await
19915                    .unwrap()
19916                    .ok()
19917            );
19918            // Resume after the branch moved, before its checkout was reset.
19919            runner.state = RunState::load(&runner.state.id).unwrap();
19920            runner.sync_to_base().await.unwrap();
19921            assert!(runner.state.base_sync_blocked());
19922            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19923            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19924            assert_eq!(
19925                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19926                result
19927            );
19928            assert_eq!(
19929                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19930                "retained work\n"
19931            );
19932            assert!(
19933                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19934                    .await
19935                    .unwrap()
19936                    .ok()
19937            );
19938        }
19939    }
19940
19941    #[cfg(unix)]
19942    #[tokio::test]
19943    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19944        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19945        runner.state.authorize_base_sync(&task).unwrap();
19946        assert!(runner.state.consume_base_recovery(&head));
19947        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19948        runner.state.reserve_base_operation(&head, &tip);
19949        runner.state.save().unwrap();
19950        let scratch = runner.state.dir().join("base-sync");
19951        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19952            .await
19953            .unwrap();
19954        git::sync_to_head(&runner.state.repo).await.unwrap();
19955        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19956        git::git(&runner.state.repo, &["add", "foreign"])
19957            .await
19958            .unwrap();
19959        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
19960            .await
19961            .unwrap();
19962        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19963        runner.state = RunState::load(&runner.state.id).unwrap();
19964        runner.sync_to_base().await.unwrap();
19965        assert!(runner.state.base_sync_blocked());
19966        assert!(
19967            !runner
19968                .state
19969                .base_sync_recovery
19970                .operations
19971                .last()
19972                .unwrap()
19973                .finished
19974        );
19975        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19976        assert_eq!(
19977            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19978            foreign_head
19979        );
19980    }
19981
19982    #[cfg(unix)]
19983    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
19984    {
19985        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19986        fresh_base_interval_fixture(&mut runner);
19987        let repo = &runner.state.repo;
19988        git::git(repo, &["checkout", "main"]).await.unwrap();
19989        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
19990        git::git(repo, &["add", "retained"]).await.unwrap();
19991        git::git(repo, &["commit", "-m", "upstream retained change"])
19992            .await
19993            .unwrap();
19994        git::git(repo, &["push", "origin", "main"]).await.unwrap();
19995        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
19996        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
19997        let scratch = runner.state.dir().join("base-sync");
19998        assert!(matches!(
19999            git::rebase_start(repo, &scratch, "fix/retained", &tip)
20000                .await
20001                .unwrap(),
20002            git::RebaseStart::Conflicted(_)
20003        ));
20004        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
20005            unstarted: false,
20006            agent: "fixture".into(),
20007            paths: vec!["retained".into()],
20008            from: Some(head.clone()),
20009            onto: None,
20010            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
20011            index_outside: None,
20012            finished: false,
20013            error: None,
20014            launcher: None,
20015            infra: None,
20016            outage: None,
20017        });
20018        (tmp, runner, head, tip, scratch)
20019    }
20020
20021    #[cfg(unix)]
20022    #[tokio::test]
20023    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
20024        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20025        // A resource stop from before reservations existed, with resolved
20026        // contents left for the launcher's ordinary staging continuation.
20027        std::fs::write(
20028            scratch.join("retained"),
20029            "upstream and retained resolution\n",
20030        )
20031        .unwrap();
20032        runner.state.resource_block = Some(crate::run::ResourceBlock {
20033            node: "rebase".into(),
20034            kind: "repository coordination".into(),
20035            detail: "busy".into(),
20036            at: Timestamp::now(),
20037            cause: crate::run::ResourceBlockCause::Other,
20038        });
20039        runner.state.save().unwrap();
20040        // Advance the remote without moving either checkout participating
20041        // in the standing rebase.
20042        let newer = git::git(
20043            &runner.state.repo,
20044            &[
20045                "commit-tree",
20046                "main^{tree}",
20047                "-p",
20048                "main",
20049                "-m",
20050                "base advanced during wait",
20051            ],
20052        )
20053        .await
20054        .unwrap();
20055        git::git(
20056            &runner.state.repo,
20057            &[
20058                "push",
20059                "origin",
20060                &format!("{}:refs/heads/main", newer.trim()),
20061            ],
20062        )
20063        .await
20064        .unwrap();
20065        runner.state = RunState::load(&runner.state.id).unwrap();
20066        runner.state.resource_block = None;
20067        runner.sync_to_base().await.unwrap();
20068        assert!(!runner.state.base_sync_blocked());
20069        let op = &runner.state.base_sync_recovery.operations[0];
20070        assert_eq!(op.head, head);
20071        assert_eq!(op.tip, tip);
20072        assert!(op.finished);
20073        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20074        assert_eq!(runner.state.rebase_fixes.len(), 1);
20075        let latest = git::rev_parse(&runner.state.repo, "origin/main")
20076            .await
20077            .unwrap();
20078        assert_ne!(latest, tip);
20079        runner.state = RunState::load(&runner.state.id).unwrap();
20080        runner.sync_to_base().await.unwrap();
20081        assert!(!runner.state.base_sync_blocked());
20082        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
20083        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
20084        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
20085    }
20086
20087    #[cfg(unix)]
20088    #[tokio::test]
20089    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
20090        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20091        runner.state.reserve_base_operation(&head, &tip);
20092        runner.state.save().unwrap();
20093        std::fs::write(
20094            scratch.join("retained"),
20095            "upstream and retained resolution\n",
20096        )
20097        .unwrap();
20098        git::git(&scratch, &["add", "retained"]).await.unwrap();
20099        git::git(
20100            &scratch,
20101            &["-c", "core.editor=true", "rebase", "--continue"],
20102        )
20103        .await
20104        .unwrap();
20105        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20106        assert!(
20107            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20108                .await
20109                .unwrap()
20110                .is_empty()
20111        );
20112        assert_eq!(
20113            crate::rebase::finish(
20114                &mut runner.state,
20115                &scratch,
20116                "fix/retained",
20117                &head,
20118                &tip,
20119                &["retained".into()],
20120                ""
20121            )
20122            .await
20123            .unwrap(),
20124            crate::rebase::Rebased::Applied
20125        );
20126        assert!(!scratch.exists());
20127        // Simulate losing the caller before finish_base_operation/save.
20128        runner.state = RunState::load(&runner.state.id).unwrap();
20129        let op = &runner.state.base_sync_recovery.operations[0];
20130        assert!(!op.finished);
20131        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
20132        runner.sync_to_base().await.unwrap();
20133        assert!(!runner.state.base_sync_blocked());
20134        assert!(runner.state.base_sync_recovery.operations[0].finished);
20135        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20136        assert_eq!(runner.state.rebase_fixes.len(), 1);
20137        let winner = runner.state.winner().unwrap().clone();
20138        let wait = runner.repository_wait();
20139        assert!(
20140            verify_current_head(&mut runner.state, &winner, &wait)
20141                .await
20142                .unwrap()
20143        );
20144        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20145    }
20146
20147    #[cfg(unix)]
20148    #[tokio::test]
20149    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
20150        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
20151            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20152            runner.state.reserve_base_operation(&head, &tip);
20153            runner.state.save().unwrap();
20154            std::fs::write(
20155                scratch.join("retained"),
20156                "upstream and retained resolution\n",
20157            )
20158            .unwrap();
20159            git::git(&scratch, &["add", "retained"]).await.unwrap();
20160            git::git(
20161                &scratch,
20162                &["-c", "core.editor=true", "rebase", "--continue"],
20163            )
20164            .await
20165            .unwrap();
20166            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20167            assert!(!git::rebase_in_progress(&scratch).await);
20168            assert!(
20169                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20170                    .await
20171                    .unwrap()
20172                    .is_empty()
20173            );
20174            match damage {
20175                Some("record") => {
20176                    let path =
20177                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
20178                            .await
20179                            .unwrap();
20180                    std::fs::write(scratch.join(path), "").unwrap();
20181                }
20182                Some("foreign") => {
20183                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
20184                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
20185                    git::git(&scratch, &["commit", "-m", "foreign work"])
20186                        .await
20187                        .unwrap();
20188                }
20189                Some("dirty") => {
20190                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
20191                }
20192                _ => {}
20193            }
20194            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20195            // Crash immediately after Git continuation, before finish runs.
20196            runner.state = RunState::load(&runner.state.id).unwrap();
20197            assert!(
20198                runner.state.base_sync_recovery.operations[0]
20199                    .validated_head
20200                    .is_none()
20201            );
20202            runner.sync_to_base().await.unwrap();
20203            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20204            assert_eq!(runner.state.base_episode_used(), 1);
20205            assert_eq!(runner.state.rebase_fixes.len(), 1);
20206            assert_eq!(
20207                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20208                retained_head
20209            );
20210            if damage.is_some() {
20211                assert!(runner.state.base_sync_blocked());
20212                assert!(scratch.exists());
20213                assert!(!runner.state.base_sync_recovery.operations[0].finished);
20214                assert!(
20215                    runner.state.base_sync_recovery.operations[0]
20216                        .validated_head
20217                        .is_none()
20218                );
20219            } else {
20220                assert!(!runner.state.base_sync_blocked());
20221                assert!(!scratch.exists());
20222                assert!(runner.state.base_sync_recovery.operations[0].finished);
20223                assert_eq!(
20224                    runner.state.base_sync_recovery.operations[0]
20225                        .validated_head
20226                        .as_deref(),
20227                    Some(result.as_str())
20228                );
20229                let winner = runner.state.winner().unwrap().clone();
20230                let wait = runner.repository_wait();
20231                assert!(
20232                    verify_current_head(&mut runner.state, &winner, &wait)
20233                        .await
20234                        .unwrap()
20235                );
20236                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20237                runner.state = RunState::load(&runner.state.id).unwrap();
20238                runner.sync_to_base().await.unwrap();
20239                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20240            }
20241        }
20242    }
20243
20244    #[cfg(unix)]
20245    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
20246        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20247        // This is an ordinary gate stop, not an authorized base-budget recovery.
20248        runner.state.prep_complete = Some(true);
20249        runner.state.base_sync = None;
20250        runner.state.base_sync_recovery = Default::default();
20251        runner.state.config.graph.gate_fix_rounds = 1;
20252        let mut review = review_round(true, 0, 1, 1, false, true);
20253        review.head = head.clone();
20254        review.verified_head = Some(head.clone());
20255        runner.state.reviews = vec![review];
20256        runner.state.gate = vec![CommandOutcome {
20257            command: "old gate".into(),
20258            code: Some(1),
20259            output_tail: "old failure".into(),
20260            duration_ms: 0,
20261            resource_blocked: false,
20262            ..Default::default()
20263        }];
20264        runner.state.gate_head = Some(head.clone());
20265        runner.state.gate_ran = true;
20266        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
20267            agent: "fixture".into(),
20268            failed: runner.state.gate.clone(),
20269            notes: "spent".into(),
20270            committed: false,
20271            error: None,
20272        }];
20273        runner.state.land_approval = Some(crate::run::LandApproval {
20274            question: "old approval".into(),
20275            head: head.clone(),
20276        });
20277        runner.state.status = RunStatus::Blocked;
20278        (tmp, runner, head)
20279    }
20280
20281    #[cfg(unix)]
20282    #[tokio::test]
20283    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
20284        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
20285        runner.sync_to_base().await.unwrap();
20286        let winner = runner.state.winner().unwrap().clone();
20287        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
20288        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
20289        assert_ne!(head, base);
20290        runner.state.config.verify.e2e = vec![format!(
20291            "git update-ref refs/remotes/origin/main {head} && false"
20292        )];
20293        let wait = repository_wait(&runner.state, None);
20294        assert!(
20295            !verify_current_head(&mut runner.state, &winner, &wait)
20296                .await
20297                .unwrap()
20298        );
20299        assert_eq!(
20300            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
20301                .await
20302                .unwrap(),
20303            head
20304        );
20305        assert_eq!(
20306            runner
20307                .state
20308                .head_e2e
20309                .as_ref()
20310                .unwrap()
20311                .base_commit
20312                .as_deref(),
20313            Some(base.as_str())
20314        );
20315    }
20316
20317    #[cfg(unix)]
20318    #[tokio::test]
20319    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
20320        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
20321            let (tmp, mut runner, old) = resumed_gate_fixture().await;
20322            let phases = tmp.path().join("phases");
20323            runner.state.config.verify.e2e = vec![format!(
20324                "echo e2e >> '{}'; {}",
20325                phases.display(),
20326                if e2e_ok {
20327                    "true"
20328                } else {
20329                    "echo new-e2e-failure; false"
20330                }
20331            )];
20332            runner.state.config.verify.gate = vec![format!(
20333                "echo gate >> '{}'; {}",
20334                phases.display(),
20335                if gate_ok {
20336                    "true"
20337                } else {
20338                    "echo new-gate-failure; false"
20339                }
20340            )];
20341            runner.state.save().unwrap();
20342            runner.state = RunState::load(&runner.state.id).unwrap();
20343            runner.sync_to_base().await.unwrap();
20344            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20345            assert_ne!(head, old);
20346            // Reentry after Git updated but before verification was invalidated.
20347            runner.state = RunState::load(&runner.state.id).unwrap();
20348            runner.execute_graph().await.unwrap();
20349            assert_eq!(runner.state.gate_fixes.len(), 1);
20350            assert_eq!(runner.state.reviews.len(), 1);
20351            assert_eq!(runner.state.reviews[0].head, old);
20352            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
20353            assert_eq!(runner.state.verification_history.len(), 1);
20354            let history = &runner.state.verification_history[0];
20355            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
20356            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20357            assert!(history.archived_at.is_some());
20358            assert_eq!(history.fixes_spent, Some(1));
20359            assert_eq!(history.gate[0].output_tail, "old failure");
20360            let archive_events: Vec<_> = runner
20361                .state
20362                .events
20363                .iter()
20364                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
20365                .collect();
20366            assert_eq!(archive_events.len(), 1);
20367            assert!(archive_events[0].message.contains(&short(&old)));
20368            assert!(archive_events[0].message.contains(&short(&head)));
20369            assert!(
20370                archive_events[0]
20371                    .message
20372                    .contains("1 gate-fix round(s) already spent stay spent")
20373            );
20374            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
20375            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
20376            if e2e_ok {
20377                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20378                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
20379            } else {
20380                assert!(!runner.state.gate_ran);
20381            }
20382            assert_eq!(
20383                runner.state.status,
20384                if e2e_ok && gate_ok {
20385                    RunStatus::Ready
20386                } else {
20387                    RunStatus::Blocked
20388                }
20389            );
20390            if !e2e_ok || !gate_ok {
20391                let cause = runner.state.verification_blocking_cause().unwrap();
20392                assert!(cause.contains(&head));
20393                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
20394                // A later successful progress event must not become the cause.
20395                runner.state.event("land", "rebased successfully");
20396                let notice = crate::notices::run_ended(&runner.state).unwrap();
20397                assert!(!format!("{notice:?}").contains("rebased successfully"));
20398                assert!(runner.state.merge.is_none());
20399            }
20400            let before = std::fs::read_to_string(&phases).unwrap();
20401            runner.state.save().unwrap();
20402            runner.state = RunState::load(&runner.state.id).unwrap();
20403            runner.review_loop().await.unwrap();
20404            runner.gate().await.unwrap();
20405            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
20406            assert_eq!(runner.state.verification_history.len(), 1);
20407            let history = &runner.state.verification_history[0];
20408            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20409            assert!(history.archived_at.is_some());
20410            assert_eq!(history.fixes_spent, Some(1));
20411        }
20412    }
20413
20414    #[cfg(unix)]
20415    #[tokio::test]
20416    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
20417        let (tmp, mut runner, head) = resumed_gate_fixture().await;
20418        let marker = tmp.path().join("gate-ran");
20419        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
20420        runner.review_loop().await.unwrap();
20421        runner.gate().await.unwrap();
20422        assert_eq!(runner.state.status, RunStatus::Blocked);
20423        assert!(!marker.exists());
20424        assert!(runner.state.verification_history.is_empty());
20425        runner.state.gate_head = None;
20426        runner.gate().await.unwrap();
20427        assert!(marker.exists());
20428        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20429        assert_eq!(runner.state.verification_history.len(), 1);
20430        assert_eq!(runner.state.gate_fixes.len(), 1);
20431    }
20432
20433    #[cfg(unix)]
20434    #[tokio::test]
20435    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
20436        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20437        runner.sync_to_base().await.unwrap();
20438        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20439        runner.state.reconcile_verification_head(&head);
20440        // Both crash-before-command and resource wait are unresolved evidence.
20441        for outcomes in [
20442            Vec::new(),
20443            vec![CommandOutcome {
20444                command: "true".into(),
20445                code: None,
20446                output_tail: "cache unavailable".into(),
20447                duration_ms: 0,
20448                resource_blocked: true,
20449                ..Default::default()
20450            }],
20451        ] {
20452            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20453                head.clone(),
20454                false,
20455                outcomes,
20456            ));
20457            runner.state.gate_ran = false;
20458            runner.state.gate.clear();
20459            runner.state.save().unwrap();
20460            runner.state = RunState::load(&runner.state.id).unwrap();
20461            runner.merge().await.unwrap();
20462            assert!(runner.state.merge.is_none());
20463            runner.review_loop().await.unwrap();
20464            runner.gate().await.unwrap();
20465            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20466            assert!(runner.state.gate_allows_progress());
20467            assert_eq!(runner.state.gate_fixes.len(), 1);
20468            assert!(runner.state.merge.is_none());
20469        }
20470        // Moving the winner after a successful gate cannot publish an unchecked SHA.
20471        git::git(
20472            &runner.state.repo,
20473            &["commit", "--allow-empty", "-m", "external update"],
20474        )
20475        .await
20476        .unwrap();
20477        runner.merge().await.unwrap();
20478        assert!(runner.state.merge.is_none());
20479        assert_eq!(runner.state.status, RunStatus::Blocked);
20480    }
20481
20482    #[cfg(unix)]
20483    #[tokio::test]
20484    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
20485        for waiting_on_gate in [false, true] {
20486            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
20487            runner.sync_to_base().await.unwrap();
20488            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20489            runner.state.reconcile_verification_head(&head);
20490            if waiting_on_gate {
20491                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20492                    head.clone(),
20493                    true,
20494                    Vec::new(),
20495                ));
20496            }
20497            let cache = tmp.path().join("cache");
20498            runner.state.config.verify.e2e =
20499                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
20500            runner.state.config.verify.gate = vec!["true".into()];
20501            runner.state.config.graph.timeout_resource_wait = 1;
20502            let owner =
20503                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
20504            let guard =
20505                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
20506                    crate::cache::AcquireOutcome::Acquired(g) => g,
20507                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
20508                };
20509            runner.review_loop().await.unwrap();
20510            runner.gate().await.unwrap();
20511            assert!(!runner.state.gate_ran);
20512            assert_eq!(runner.state.gate_fixes.len(), 1);
20513            assert!(runner.state.resource_block.is_some());
20514            runner.merge().await.unwrap();
20515            assert!(runner.state.merge.is_none());
20516            drop(guard);
20517            runner.state = RunState::load(&runner.state.id).unwrap();
20518            // The driver clears the previous pass's resource stop on resume.
20519            runner.state.resource_block = None;
20520            runner.review_loop().await.unwrap();
20521            runner.gate().await.unwrap();
20522            assert!(runner.state.gate_allows_progress());
20523            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20524            assert_eq!(runner.state.gate_fixes.len(), 1);
20525        }
20526    }
20527
20528    #[cfg(unix)]
20529    #[tokio::test]
20530    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
20531        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20532        runner.sync_to_base().await.unwrap();
20533        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20534        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
20535        // Verification passes before pre_gate and fails on the mechanically changed head.
20536        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
20537        runner.review_loop().await.unwrap();
20538        runner.gate().await.unwrap();
20539        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20540        assert_ne!(before, after);
20541        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
20542        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
20543        assert!(!runner.state.gate_allows_progress());
20544        runner.merge().await.unwrap();
20545        assert!(runner.state.merge.is_none());
20546        assert!(
20547            runner
20548                .state
20549                .verification_history
20550                .iter()
20551                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
20552        );
20553
20554        // An incomplete review is still an independent hold on a changed head.
20555        runner.state.reviews[0].clean = false;
20556        runner.state.reviews[0].answered = 0;
20557        runner.state.config.verify.e2e = vec!["true".into()];
20558        runner.review_loop().await.unwrap();
20559        runner.gate().await.unwrap();
20560        runner.merge().await.unwrap();
20561        assert_eq!(runner.state.status, RunStatus::Blocked);
20562        assert!(runner.state.merge.is_none());
20563        assert!(
20564            runner
20565                .state
20566                .verification_blocking_cause()
20567                .unwrap()
20568                .contains("review blocked")
20569        );
20570    }
20571
20572    #[cfg(unix)]
20573    #[tokio::test]
20574    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
20575        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20576        runner.state.gate_head = None;
20577        runner.state.config.verify.gate =
20578            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20579        runner.review_loop().await.unwrap();
20580        runner.gate().await.unwrap();
20581        assert_ne!(
20582            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20583            old
20584        );
20585        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20586        assert!(!runner.state.gate_allows_progress());
20587        assert_eq!(runner.state.status, RunStatus::Blocked);
20588        runner.merge().await.unwrap();
20589        assert!(runner.state.merge.is_none());
20590    }
20591
20592    #[cfg(unix)]
20593    #[tokio::test]
20594    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20595        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20596        let mut old_review = review_round(true, 0, 1, 1, false, true);
20597        old_review.head = head.clone();
20598        old_review.verified_head = Some(head.clone());
20599        runner.state.reviews = vec![old_review];
20600        runner.state.gate = vec![CommandOutcome {
20601            command: "old gate".into(),
20602            code: None,
20603            output_tail: "timed out after 2400s".into(),
20604            duration_ms: 2_400_000,
20605            resource_blocked: false,
20606            ..Default::default()
20607        }];
20608        runner.state.gate_ran = true;
20609        runner.state.gate_head = Some(head.clone());
20610        runner.state.land_approval = Some(crate::run::LandApproval {
20611            question: "old-head-approval".into(),
20612            head: head.clone(),
20613        });
20614        runner.state.authorize_base_sync(&task).unwrap();
20615        runner.sync_to_base().await.unwrap();
20616        assert!(!runner.state.base_sync_blocked());
20617        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20618        assert_ne!(head, fresh);
20619        assert_eq!(runner.state.reviews.len(), 1);
20620        assert!(!runner.state.gate_ran);
20621        let saved = &runner.state.base_sync_recovery.authorizations[0];
20622        assert_eq!(saved.reviews[0].head, head);
20623        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20624        assert!(saved.gate_ran);
20625        assert!(!saved.gate[0].ok());
20626        runner.review_loop().await.unwrap();
20627        runner.gate().await.unwrap();
20628        assert_eq!(runner.state.reviews[0].head, head);
20629        assert_eq!(
20630            runner.state.reviews[0].verified_head.as_deref(),
20631            Some(head.as_str())
20632        );
20633        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20634        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20635        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20636        assert!(runner.state.gate_ran);
20637        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20638        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20639        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20640        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20641        assert_eq!(
20642            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20643            "retained change"
20644        );
20645    }
20646
20647    #[cfg(unix)]
20648    #[tokio::test]
20649    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20650        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20651        let queue = crate::queue::Queue::open();
20652        let mut owner = queue.get(&task).unwrap();
20653        owner.release_operator("test-resume", None);
20654        queue.put(&mut owner).unwrap();
20655        let generation = owner.resumption.as_ref().unwrap().generation;
20656        runner.state.task_instruction = Some(owner.instruction.clone());
20657        runner.state.driver_exited = true;
20658        runner.state.save().unwrap();
20659        let home = crate::run::home();
20660        let _claim = queue.claim(&task).unwrap();
20661        owner.resumption.as_mut().unwrap().at =
20662            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20663        queue.put(&mut owner).unwrap();
20664        assert!(
20665            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20666                .await
20667                .is_err(),
20668            "an approval from before the stop grants nothing"
20669        );
20670        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20671        queue.put(&mut owner).unwrap();
20672        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20673            .await
20674            .unwrap();
20675        assert!(
20676            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20677                .await
20678                .is_err()
20679        );
20680        runner.state = RunState::load(&runner.state.id).unwrap();
20681        assert_eq!(
20682            runner.state.base_sync_recovery.authorizations[0].generation,
20683            Some(generation)
20684        );
20685        runner.sync_to_base().await.unwrap();
20686        let repo = runner.state.repo.clone();
20687        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20688        git::git(&repo, &["checkout", "main"]).await.unwrap();
20689        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20690        git::git(&repo, &["add", "."]).await.unwrap();
20691        git::git(&repo, &["commit", "-m", "move base again"])
20692            .await
20693            .unwrap();
20694        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20695        git::git(&repo, &["checkout", "fix/retained"])
20696            .await
20697            .unwrap();
20698        runner.sync_to_base().await.unwrap();
20699        assert!(!runner.state.base_sync_blocked());
20700        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20701        assert_eq!(runner.state.base_episode_used(), 2);
20702        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20703        assert_ne!(fresh, head);
20704        assert!(!runner.state.base_recovery_pending());
20705        // Even replaying the generation with a later timestamp grants nothing.
20706        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20707        queue.put(&mut owner).unwrap();
20708        assert!(
20709            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20710                .await
20711                .is_err()
20712        );
20713        runner.state = RunState::load(&runner.state.id).unwrap();
20714        runner.sync_to_base().await.unwrap();
20715        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20716        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20717        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20718    }
20719
20720    #[cfg(unix)]
20721    #[tokio::test]
20722    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20723        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20724        runner.state.base_sync = None;
20725        runner.state.status = RunStatus::Blocked;
20726        let mut second = runner.state.candidates[0].clone();
20727        second.label = 'B';
20728        runner.state.candidates.push(second);
20729        assert!(runner.state.votes.is_empty());
20730        assert!(runner.state.deliberation.is_empty());
20731        runner.deliberate().await.unwrap();
20732        runner.vote().await.unwrap();
20733        assert_eq!(runner.state.status, RunStatus::Blocked);
20734        assert!(runner.state.votes.is_empty());
20735        assert!(runner.state.deliberation.is_empty());
20736    }
20737
20738    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20739    /// reads nothing else off it.
20740    fn runner_at(status: RunStatus) -> Runner {
20741        let mut state = RunState::new(
20742            PathBuf::from("/nonexistent/repo"),
20743            "main".to_owned(),
20744            "deadbeef".to_owned(),
20745            "task".to_owned(),
20746            Config::default(),
20747        );
20748        // These fixtures test execution flow, independent of host disk capacity.
20749        state.config.disk.min_free_bytes = 0;
20750        // These fixtures share one home and save concurrently. Short clock
20751        // IDs can collide, making an ownership test read another test's run.
20752        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20753        state.id = format!(
20754            "20000101-000000-{:04x}",
20755            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20756        );
20757        state.status = status;
20758        Runner {
20759            state,
20760            roles: ResolvedRoles {
20761                implementers: Vec::new(),
20762                judges: Vec::new(),
20763                reviewers: Vec::new(),
20764                fixer: None,
20765                conductor: conductor(),
20766                implementer_roster: Vec::new(),
20767                judge_roster: Vec::new(),
20768                reviewer_roster: Vec::new(),
20769            },
20770            sem: Arc::new(Semaphore::new(1)),
20771            pause: Pause::new(),
20772            interrupt: Pause::new(),
20773        }
20774    }
20775
20776    #[tokio::test]
20777    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20778        crate::run::pin_test_home();
20779        let home = crate::run::home();
20780        let mut runner = runner_at(RunStatus::Ready);
20781        runner.state.driver_exited = true;
20782        runner.state.save().unwrap();
20783        let id = runner.state.id.clone();
20784        let path = runner.state.dir().join("run.json");
20785        let ids = ["R1-1-1".into()];
20786        let lease = crate::driver::maintenance(&home, &id).unwrap();
20787        for (guard, expected) in [
20788            (Some(lease), "currently being worked on"),
20789            (None, "ownership is being updated"),
20790        ] {
20791            let owner = if guard.is_none() {
20792                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20793            } else {
20794                None
20795            };
20796            let before = std::fs::read(&path).unwrap();
20797            let err = runner
20798                .fix_selected(&ids, "ownership conflict", false)
20799                .await
20800                .unwrap_err();
20801            assert!(format!("{err:#}").contains(expected), "{err:#}");
20802            assert_eq!(std::fs::read(&path).unwrap(), before);
20803            assert!(!runner.state.dir().join("fix.lock").exists());
20804            drop(owner);
20805            drop(guard);
20806        }
20807        let mut disk = RunState::load(&id).unwrap();
20808        disk.driver_exited = false;
20809        disk.driver_pid = Some(std::process::id());
20810        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20811        disk.save().unwrap();
20812        assert_eq!(
20813            disk.liveness_under(&home, false),
20814            crate::run::Liveness::Live
20815        );
20816        let before = std::fs::read(&path).unwrap();
20817        let err = runner
20818            .fix_selected(&ids, "live driver", false)
20819            .await
20820            .unwrap_err();
20821        assert!(
20822            err.to_string().contains("currently being worked on"),
20823            "{err:#}"
20824        );
20825        assert_eq!(std::fs::read(&path).unwrap(), before);
20826        assert!(!runner.state.dir().join("fix.lock").exists());
20827        disk.driver_exited = true;
20828        disk.driver_pid = None;
20829        disk.driver_started_at = None;
20830        disk.status = RunStatus::Reviewing;
20831        disk.save().unwrap();
20832        let before = std::fs::read(&path).unwrap();
20833        let err = runner
20834            .fix_selected(&ids, "stale state", false)
20835            .await
20836            .unwrap_err();
20837        assert!(
20838            err.to_string().contains("run changed since it was loaded"),
20839            "{err:#}"
20840        );
20841        assert_eq!(std::fs::read(&path).unwrap(), before);
20842        assert!(!runner.state.dir().join("fix.lock").exists());
20843        assert!(runner.state.operator_fixes.is_empty());
20844    }
20845
20846    #[tokio::test]
20847    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20848        use std::future::Future;
20849        use std::task::Poll;
20850
20851        crate::run::pin_test_home();
20852        let home = crate::run::home();
20853        let repo = tempfile::tempdir().unwrap();
20854        let mut runner = runner_at(RunStatus::Ready);
20855        runner.state.repo = repo.path().to_path_buf();
20856        runner.state.driver_exited = true;
20857        runner.state.candidates.push(Candidate {
20858            index: 0,
20859            label: 'A',
20860            agent: "mock".into(),
20861            branch: "magi/test/A".into(),
20862            worktree: repo.path().join("wt"),
20863            summary: String::new(),
20864            stat: String::new(),
20865            files: 0,
20866            commits: 0,
20867            empty: false,
20868            failed: None,
20869            verified_noop: None,
20870            duration_ms: 0,
20871            folded: false,
20872        });
20873        runner.state.tally = Some(Tally {
20874            first_choice: BTreeMap::from([('A', 1)]),
20875            borda: BTreeMap::new(),
20876            winner: 'A',
20877            rankings: 1,
20878            unanimous_initial: true,
20879            deliberated: false,
20880            changed_votes: 0,
20881            unanimous_final: true,
20882            tie_break: None,
20883            judges: 1,
20884            present: 1,
20885            quorum: 1,
20886            met_quorum: true,
20887            uncontested: None,
20888        });
20889        runner.state.save().unwrap();
20890        let id = runner.state.id.clone();
20891        let dir = runner.state.dir();
20892        let before = std::fs::read(dir.join("run.json")).unwrap();
20893        let ids = ["R1-1-1".into()];
20894        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20895        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20896            Poll::Pending => Poll::Ready(()),
20897            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20898        })
20899        .await;
20900        assert!(FixClaim::acquire(&dir).is_err());
20901        assert!(crate::driver::maintenance(&home, &id).is_err());
20902        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20903        drop(fix);
20904        assert!(FixClaim::acquire(&dir).is_ok());
20905        assert!(crate::driver::maintenance(&home, &id).is_ok());
20906        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20907    }
20908
20909    #[tokio::test]
20910    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20911        crate::run::pin_test_home();
20912        let temp = tempfile::tempdir().unwrap();
20913        let root = temp.path().canonicalize().unwrap();
20914        let repo = root.join("repo");
20915        std::fs::create_dir(&repo).unwrap();
20916        init_repo(&repo);
20917        git::git(&repo, &["config", "core.autocrlf", "false"])
20918            .await
20919            .unwrap();
20920        let mut runner = runner_at(RunStatus::Blocked);
20921        runner.state.repo = repo.clone();
20922        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20923        runner.state.config.agents = vec![conductor()];
20924        runner.state.config.graph.selected_implementer = Some("conductor".into());
20925        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20926        let (shell, command, setup_output) = if cfg!(windows) {
20927            (
20928                vec!["cmd".into(), "/C".into()],
20929                "echo ready>seat-ready",
20930                "ready\r\n",
20931            )
20932        } else {
20933            (
20934                vec!["sh".into(), "-c".into()],
20935                "printf ready > seat-ready",
20936                "ready",
20937            )
20938        };
20939        runner.state.config.verify.shell = Some(shell);
20940        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20941            run: Some(command.into()),
20942            ..Default::default()
20943        }];
20944        runner.state.save().unwrap();
20945        let path = runner.state.worktree_root().join("judge-1");
20946        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20947            .await
20948            .unwrap();
20949        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20950        git::git(&path, &["add", "."]).await.unwrap();
20951        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20952        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20953            .await
20954            .unwrap();
20955        git::git(&path, &["checkout", "--detach", &head])
20956            .await
20957            .unwrap();
20958        let evidence = crate::fold_evidence::snapshot(
20959            &runner.state,
20960            &crate::run::home().canonicalize().unwrap(),
20961            &head,
20962            64 * 1024 * 1024,
20963        )
20964        .await
20965        .unwrap();
20966        let mut contents = BTreeMap::new();
20967        contents.insert(
20968            repo.join("logs/HEAD"),
20969            format!("{head} {head} fixture\n").into_bytes(),
20970        );
20971        let record = serde_json::json!({
20972            "version":1, "run":runner.state.id, "source":path, "head":head,
20973            "evidence":evidence, "admin":{}, "admin_contents":contents,
20974            "history":{head.clone():evidence}, "phase":"evicted"
20975        });
20976        std::fs::write(
20977            runner.state.dir().join("artifacts/eviction-judge-1.json"),
20978            serde_json::to_vec(&record).unwrap(),
20979        )
20980        .unwrap();
20981        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
20982        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
20983            .await
20984            .unwrap();
20985        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
20986        assert!(
20987            !git::git_raw(&repo, &["cat-file", "-e", &head])
20988                .await
20989                .unwrap()
20990                .ok()
20991        );
20992        let mut resumed = Runner::resume(&runner.state.id).unwrap();
20993        let error = resumed.execute().await.unwrap_err();
20994        assert!(
20995            error
20996                .to_string()
20997                .contains("selected implementation is held"),
20998            "{error:#}"
20999        );
21000        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
21001        assert_eq!(
21002            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
21003            setup_output
21004        );
21005        assert_eq!(
21006            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
21007            "unrelated seat"
21008        );
21009        let error = resumed.execute().await.unwrap_err();
21010        assert!(
21011            error
21012                .to_string()
21013                .contains("selected implementation is held"),
21014            "{error:#}"
21015        );
21016        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
21017        git::git(&path, &["add", "."]).await.unwrap();
21018        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
21019        let next = git::git(
21020            &path,
21021            &[
21022                "commit-tree",
21023                &next_tree,
21024                "-p",
21025                &head,
21026                "-m",
21027                "next review checkpoint",
21028            ],
21029        )
21030        .await
21031        .unwrap();
21032        git::git(&path, &["checkout", "--detach", &next])
21033            .await
21034            .unwrap();
21035        resumed.state.reviews.push(
21036            serde_json::from_value(serde_json::json!({
21037                "round":1, "head":next, "reviews":[]
21038            }))
21039            .unwrap(),
21040        );
21041        resumed.state.save().unwrap();
21042        let error = resumed.execute().await.unwrap_err();
21043        assert!(
21044            error
21045                .to_string()
21046                .contains("selected implementation is held"),
21047            "{error:#}"
21048        );
21049        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
21050    }
21051
21052    #[tokio::test]
21053    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
21054        crate::run::pin_test_home();
21055        let mut runner = runner_at(RunStatus::Gating);
21056        runner.state.save().unwrap();
21057        let id = runner.state.id.clone();
21058        let passes = runner.state.passes.len();
21059        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21060        let mut claiming = Box::pin(runner.claim_driver(None));
21061        std::future::poll_fn(|cx| {
21062            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
21063            std::task::Poll::Ready(())
21064        })
21065        .await;
21066        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
21067        drop(owner);
21068        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
21069            .await
21070            .unwrap()
21071            .unwrap();
21072        assert_eq!(execution.runner.state.passes.len(), passes + 1);
21073        assert!(execution.runner.state.resource_block.is_none());
21074        assert_eq!(
21075            execution.runner.state.liveness(false),
21076            crate::run::Liveness::Live
21077        );
21078        drop(execution);
21079        assert!(RunState::load(&id).unwrap().driver_exited);
21080    }
21081
21082    #[tokio::test]
21083    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
21084        crate::run::pin_test_home();
21085        let mut runner = runner_at(RunStatus::Gating);
21086        runner.state.save().unwrap();
21087        // run.json can commit, but the subsequent lease metadata write fails.
21088        // Cleanup must run after releasing the short ownership lock.
21089        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
21090        assert!(runner.claim_driver(None).await.is_err());
21091        assert!(runner.state.driver_exited);
21092        assert_eq!(runner.state.driver_pid, None);
21093        let disk = RunState::load(&runner.state.id).unwrap();
21094        assert!(disk.driver_exited);
21095        assert_eq!(disk.driver_pid, None);
21096        assert_eq!(disk.status, RunStatus::Gating);
21097    }
21098
21099    #[tokio::test]
21100    async fn an_early_graph_error_releases_its_driver() {
21101        crate::run::pin_test_home();
21102        let mut runner = runner_at(RunStatus::Blocked);
21103        runner.state.config.graph.selected_implementer = Some("selected".into());
21104        runner.state.save().unwrap();
21105        assert!(runner.execute().await.is_err());
21106        let disk = RunState::load(&runner.state.id).unwrap();
21107        assert!(disk.driver_exited);
21108        assert_eq!(disk.driver_pid, None);
21109        assert_eq!(disk.status, RunStatus::Blocked);
21110    }
21111
21112    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
21113        crate::run::MergeRepair {
21114            question: "repair-question".into(),
21115            head: "old-head".into(),
21116            pr: "https://github.com/o/r/pull/42".into(),
21117            reviews: vec![review_round(false, 1, 1, 1, false, true)],
21118            gate: vec![outcome(Some(0), false)],
21119            gate_head: Some("old-head".into()),
21120            gate_fixes: Vec::new(),
21121            pre_gate: Vec::new(),
21122            phase,
21123            failure: None,
21124        }
21125    }
21126
21127    #[tokio::test]
21128    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
21129        crate::run::pin_test_home();
21130        let mut runner = runner_at(RunStatus::Landing);
21131        runner.state.merge_repairs.push(merge_repair_request(
21132            crate::run::MergeRepairPhase::Requested,
21133        ));
21134        runner.state.save().unwrap();
21135        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
21136        assert!(
21137            runner
21138                .execute()
21139                .await
21140                .unwrap_err()
21141                .to_string()
21142                .contains("already running")
21143        );
21144        assert_eq!(
21145            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21146            crate::run::MergeRepairPhase::Requested
21147        );
21148        drop(claim);
21149        let mut disk = runner.state.clone();
21150        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
21151        disk.save().unwrap();
21152        assert!(
21153            runner
21154                .execute()
21155                .await
21156                .unwrap_err()
21157                .to_string()
21158                .contains("decision changed")
21159        );
21160        assert_eq!(
21161            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21162            crate::run::MergeRepairPhase::Complete
21163        );
21164    }
21165
21166    #[test]
21167    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
21168        crate::run::pin_test_home();
21169        let mut runner = runner_at(RunStatus::Landing);
21170        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
21171        runner.state.reviews = request.reviews.clone();
21172        runner.state.gate = request.gate.clone();
21173        runner.state.gate_ran = true;
21174        runner.state.land_approval = Some(crate::run::LandApproval {
21175            question: "old".into(),
21176            head: "old-head".into(),
21177        });
21178        runner.state.merge_repairs.push(request);
21179        runner.begin_merge_repair_review(0).unwrap();
21180        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
21181        assert!(!runner.state.gate_status().ok());
21182        assert!(runner.state.land_approval.is_none());
21183        let disk = RunState::load(&runner.state.id).unwrap();
21184        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
21185        assert!(disk.merge_repairs[0].gate[0].ok());
21186        assert_eq!(
21187            disk.merge_repairs[0].phase,
21188            crate::run::MergeRepairPhase::Reviewing
21189        );
21190        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
21191        assert!(disk.reviews.is_empty());
21192    }
21193
21194    #[tokio::test]
21195    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
21196        crate::run::pin_test_home();
21197        for phase in [
21198            crate::run::MergeRepairPhase::Fixing,
21199            crate::run::MergeRepairPhase::Requested,
21200        ] {
21201            let mut runner = runner_at(RunStatus::Landing);
21202            runner.state.config.graph.land_rounds = 0;
21203            runner.state.merge_repairs.push(merge_repair_request(phase));
21204            runner.state.save().unwrap();
21205            assert!(!runner.repair_merge_review().await.unwrap());
21206            assert_eq!(runner.state.status, RunStatus::Blocked);
21207            assert_eq!(
21208                runner.state.merge_repairs[0].phase,
21209                crate::run::MergeRepairPhase::Failed
21210            );
21211            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
21212            assert!(
21213                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
21214                    "interrupted"
21215                } else {
21216                    "budget exhausted"
21217                })
21218            );
21219            assert!(runner.state.merge.is_none());
21220        }
21221    }
21222
21223    /// `park_here` folding in the reason `Pause::park_because` recorded -
21224    /// this is what lets an operator reading a run's events tell an
21225    /// interrupt-driven park from an ordinary shutdown park.
21226    #[test]
21227    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
21228        crate::run::pin_test_home();
21229        let mut runner = runner_at(RunStatus::Implementing);
21230        let interrupt = Pause::new();
21231        runner.watch_interrupt(interrupt.clone());
21232
21233        interrupt.park_because("task a1b2 asked to run first");
21234
21235        assert!(runner.park_here().expect("park_here"));
21236        assert!(runner.state.parked);
21237        let last = runner.state.events.last().expect("a park event");
21238        assert_eq!(last.node, "park");
21239        assert!(
21240            last.message.contains("task a1b2 asked to run first"),
21241            "expected the interrupt reason in {:?}",
21242            last.message
21243        );
21244    }
21245
21246    /// The cause is stored on the pass when it parks, and the first cause a
21247    /// shared pause was given is the one that stays.
21248    #[test]
21249    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
21250        crate::run::pin_test_home();
21251        let mut runner = runner_at(RunStatus::Implementing);
21252        runner.state.begin_pass();
21253        let shutdown = Pause::new();
21254        runner.on_pause(shutdown.clone());
21255        let upgrade = ParkCause::Upgrade {
21256            from: "0.121.0".to_owned(),
21257            to: Some("0.121.1".to_owned()),
21258        };
21259        shutdown.park_for(upgrade.clone());
21260        shutdown.park_for(ParkCause::Operator);
21261
21262        assert!(runner.park_here().expect("park_here"));
21263        assert_eq!(
21264            runner.state.passes[0].end,
21265            Some(crate::run::PassEnd::Parked { cause: upgrade })
21266        );
21267        let last = runner.state.events.last().expect("a park event");
21268        assert!(last.message.contains("0.121.0"), "{}", last.message);
21269    }
21270
21271    #[tokio::test]
21272    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
21273        crate::run::pin_test_home();
21274        let mut runner = runner_at(RunStatus::Reviewing);
21275        runner.state.save().unwrap();
21276        let mut execution = runner.claim_driver(None).await.expect("first execution");
21277        assert_eq!(execution.runner.state.passes.len(), 1);
21278        execution
21279            .driver
21280            .finish(&mut execution.runner.state)
21281            .await
21282            .unwrap();
21283    }
21284
21285    #[tokio::test]
21286    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
21287        crate::run::pin_test_home();
21288        let mut runner = runner_at(RunStatus::Reviewing);
21289        runner.state.config.agents = vec![conductor()];
21290        runner.state.config.graph.timeout_resource_wait = 0;
21291        runner.state.save().unwrap();
21292        let id = runner.state.id.clone();
21293        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21294        assert!(runner.claim_driver(None).await.is_err());
21295        drop(owner);
21296        drop(runner);
21297        let mut resumed = Runner::resume(&id).unwrap();
21298        assert_eq!(resumed.state.driver_claimed, Some(false));
21299        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
21300        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
21301        let mut execution = resumed
21302            .claim_driver(None)
21303            .await
21304            .expect("retry initial claim after reload");
21305        assert_eq!(execution.runner.state.driver_claimed, Some(true));
21306        assert_eq!(execution.runner.state.passes.len(), 1);
21307        execution
21308            .driver
21309            .finish(&mut execution.runner.state)
21310            .await
21311            .unwrap();
21312    }
21313
21314    #[tokio::test]
21315    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
21316        crate::run::pin_test_home();
21317        let mut runner = runner_at(RunStatus::Reviewing);
21318        runner.state.config.agents = vec![conductor()];
21319        runner.state.save().unwrap();
21320        let id = runner.state.id.clone();
21321        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
21322        let mut resumed = Runner::resume(&id).unwrap();
21323        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
21324        assert!(resumed.claim_driver(None).await.is_err());
21325        assert!(RunState::load(&id).unwrap().passes.is_empty());
21326        drop(lease);
21327        let mut execution = resumed.claim_driver(None).await.unwrap();
21328        execution
21329            .driver
21330            .finish(&mut execution.runner.state)
21331            .await
21332            .unwrap();
21333    }
21334
21335    #[tokio::test]
21336    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
21337        crate::run::pin_test_home();
21338        let mut runner = runner_at(RunStatus::Reviewing);
21339        let state = &mut runner.state;
21340        state.config.agents = vec![conductor()];
21341        state.driver_claimed = None;
21342        state.driver_pid = Some(std::process::id());
21343        state.driver_started_at = None;
21344        state.begin_pass();
21345        state.save().unwrap();
21346        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
21347        std::fs::write(
21348            state.dir().join("driver.json"),
21349            serde_json::to_vec(&serde_json::json!({
21350                "pid": state.driver_pid, "started_at": null,
21351                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
21352            }))
21353            .unwrap(),
21354        )
21355        .unwrap();
21356        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
21357        drop(lease);
21358        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
21359        let mut resumed = Runner::resume(&state.id).unwrap();
21360        assert!(!resumed.state.driver_exited);
21361        let mut execution = resumed
21362            .claim_driver(None)
21363            .await
21364            .expect("lease proves previous execution ended");
21365        assert_eq!(execution.runner.state.passes.len(), 2);
21366        execution
21367            .driver
21368            .finish(&mut execution.runner.state)
21369            .await
21370            .unwrap();
21371    }
21372
21373    #[tokio::test]
21374    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
21375        crate::run::pin_test_home();
21376        let mut runner = runner_at(RunStatus::Reviewing);
21377        let mut json = serde_json::to_value(&runner.state).unwrap();
21378        json.as_object_mut().unwrap().remove("driver_claimed");
21379        runner.state = serde_json::from_value(json).unwrap();
21380        assert_eq!(runner.state.driver_claimed, None);
21381        runner.state.save().unwrap();
21382        let mut execution = runner
21383            .claim_driver(None)
21384            .await
21385            .expect("the execution lease, not a missing marker, excludes a second driver");
21386        assert_eq!(execution.runner.state.passes.len(), 1);
21387        execution
21388            .driver
21389            .finish(&mut execution.runner.state)
21390            .await
21391            .unwrap();
21392    }
21393
21394    #[tokio::test]
21395    async fn driver_admission_refuses_a_proven_live_driver() {
21396        crate::run::pin_test_home();
21397        let mut runner = runner_at(RunStatus::Reviewing);
21398        let pid = std::process::id();
21399        runner.state.driver_pid = Some(pid);
21400        runner.state.driver_started_at = crate::proc::process_started_at(pid);
21401        assert!(runner.state.driver_started_at.is_some());
21402        runner.state.save().unwrap();
21403        let error = runner
21404            .claim_driver(None)
21405            .await
21406            .err()
21407            .expect("a live driver must refuse");
21408        let message = error.to_string();
21409        assert!(
21410            message.starts_with("run already has a live driver: "),
21411            "{message}"
21412        );
21413        assert!(message.contains(&format!("pid={pid}")), "{message}");
21414        assert!(
21415            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
21416            "{message}"
21417        );
21418        let saved = RunState::load(&runner.state.id).unwrap();
21419        assert_eq!(saved.driver_pid, Some(pid));
21420        assert_eq!(saved.status, RunStatus::Reviewing);
21421        assert!(saved.passes.is_empty());
21422    }
21423
21424    #[tokio::test]
21425    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
21426        crate::run::pin_test_home();
21427        let home = crate::run::home();
21428        let mut runner = runner_at(RunStatus::Reviewing);
21429        runner.state.driver_exited = true;
21430        runner.state.driver_pid = None;
21431        runner.state.driver_started_at = None;
21432        runner.state.save().unwrap();
21433
21434        let queue = crate::queue::Queue::at(home.join("queue"));
21435        let mut task = crate::queue::Task::new(
21436            "task".into(),
21437            "task".into(),
21438            runner.state.repo.clone(),
21439            crate::queue::Source::Human,
21440        );
21441        task.runs.push(runner.state.id.clone());
21442        queue.put(&mut task).unwrap();
21443        let payload = serde_json::json!({
21444            "queue": home.join("queue"),
21445            "task": task.id,
21446            "opts": crate::daemon::Opts::default(),
21447            "standalone": false,
21448        });
21449        let (job, lease) =
21450            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
21451
21452        let error = runner
21453            .claim_driver(None)
21454            .await
21455            .err()
21456            .expect("another active worker claim must refuse");
21457        let message = error.to_string();
21458        assert!(
21459            message.starts_with("run already has a live driver: worker claim"),
21460            "{message}"
21461        );
21462        assert!(message.contains(&job.id), "{message}");
21463        assert!(message.contains("status=running"), "{message}");
21464        assert!(message.contains("live.lock held"), "{message}");
21465
21466        drop(lease);
21467        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
21468    }
21469
21470    #[test]
21471    fn parking_resource_halt_persists_the_pass_once() {
21472        crate::run::pin_test_home();
21473        let mut runner = runner_at(RunStatus::Reviewing);
21474        runner.state.begin_pass();
21475        runner.state.resource_block = Some(crate::run::ResourceBlock {
21476            node: "fix".into(),
21477            kind: "shared build cache".into(),
21478            detail: "cancelled".into(),
21479            at: Timestamp::now(),
21480            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
21481        });
21482        let cause = ParkCause::Upgrade {
21483            from: "old".into(),
21484            to: Some("new".into()),
21485        };
21486        runner.pause.park_for(cause.clone());
21487        // Both direct fixer exits and graph resource boundaries must complete
21488        // parking, rather than returning a stale Reviewing record.
21489        runner.stop_for_resource().unwrap();
21490        assert!(runner.resource_halt().unwrap());
21491        assert!(runner.park_here().unwrap());
21492        let saved = RunState::load(&runner.state.id).unwrap();
21493        assert!(saved.parked);
21494        assert_eq!(saved.status, RunStatus::Reviewing);
21495        assert!(saved.passes[0].ended_at.is_some());
21496        assert_eq!(
21497            saved.passes[0].end,
21498            Some(crate::run::PassEnd::Parked {
21499                cause: cause.clone()
21500            })
21501        );
21502        assert_eq!(
21503            saved.resource_block.unwrap().cause,
21504            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
21505        );
21506        assert_eq!(
21507            saved
21508                .events
21509                .iter()
21510                .filter(|event| event.node == "park")
21511                .count(),
21512            1
21513        );
21514    }
21515
21516    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
21517    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
21518    /// cleared) must not make a *different* run - one only watching its own,
21519    /// unshared interrupt `Pause` - see itself as parked. If a future change
21520    /// ever collapsed these back into one handle, the interrupt scheduler
21521    /// would park every run for the rest of the daemon's life, not just the
21522    /// one it meant to interrupt.
21523    #[test]
21524    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
21525        crate::run::pin_test_home();
21526        let mut runner = runner_at(RunStatus::Implementing);
21527        let shutdown = Pause::new();
21528        runner.on_pause(shutdown.clone());
21529        let interrupt = Pause::new();
21530        runner.watch_interrupt(interrupt.clone());
21531
21532        // Nobody has asked for anything yet.
21533        assert!(!runner.park_here().expect("park_here"));
21534        assert!(!runner.state.parked);
21535
21536        // Only the interrupt handle fires; the shutdown handle stays clear.
21537        interrupt.park_because("test");
21538        assert!(!shutdown.parked());
21539        assert!(runner.park_here().expect("park_here"));
21540    }
21541
21542    /// The property every prior attempt at this feature failed to pin down:
21543    /// asking a run to park while one of its nodes has a real, in-flight
21544    /// async operation running (an agent call, in production) must not cut
21545    /// that operation short. `park_here` is only ever consulted *between*
21546    /// `execute`'s node calls - see its own doc - so nothing inside a node
21547    /// can observe a park request until the node itself returns. This proves
21548    /// that structurally, with real `tokio` concurrency and a channel
21549    /// handshake (never a sleep, which would only prove "usually", not
21550    /// "cannot"): the "node" below reports that it has genuinely started,
21551    /// and only then is the park requested; the node still has to be told to
21552    /// finish before `park_here` is ever called, exactly mirroring every
21553    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
21554    /// in `execute`.
21555    #[tokio::test]
21556    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
21557        crate::run::pin_test_home();
21558        let mut runner = runner_at(RunStatus::Implementing);
21559        let interrupt = Pause::new();
21560        runner.watch_interrupt(interrupt.clone());
21561
21562        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
21563        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
21564
21565        // Stands in for one node's in-flight agent call: it proves it has
21566        // genuinely started, then blocks - exactly as a spawned CLI process
21567        // does - until told to finish.
21568        let node = async move {
21569            started_tx.send(()).expect("send started");
21570            finish_rx.await.expect("recv finish");
21571            "node finished"
21572        };
21573
21574        let interrupter = async move {
21575            started_rx.await.expect("recv started");
21576            // The call is now genuinely in flight. Ask it to park.
21577            interrupt.park_because("higher-priority task waiting");
21578            // Nothing the node does can observe this yet - there is no
21579            // check inside it, by construction - so let the executor run
21580            // anything pending and then let the node finish on its own.
21581            tokio::task::yield_now().await;
21582            finish_tx.send(()).expect("send finish");
21583        };
21584
21585        let (node_result, ()) = tokio::join!(node, interrupter);
21586        assert_eq!(
21587            node_result, "node finished",
21588            "the in-flight call ran to completion"
21589        );
21590
21591        // Only now, at the boundary the real `execute` would check right
21592        // after this node, does the park take effect.
21593        assert!(runner.park_here().expect("park_here"));
21594        assert!(runner.state.parked);
21595    }
21596
21597    /// A run parked mid-competition carries every field it had accumulated
21598    /// through the exact same disk round-trip an ordinary resume uses -
21599    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21600    /// Nothing about parking for an interrupt is a special case of that path;
21601    /// this is what proves it rather than assuming it.
21602    #[test]
21603    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21604        crate::run::pin_test_home();
21605        let mut runner = runner_at(RunStatus::Judging);
21606        // `Runner::resume` re-resolves roles from the saved config, which
21607        // refuses an empty roster - give it the same minimal one `conductor`
21608        // itself uses.
21609        runner.state.config.agents = vec![conductor()];
21610        runner.state.candidates = vec![Candidate {
21611            index: 0,
21612            label: 'A',
21613            agent: "alpha".to_owned(),
21614            branch: "magi/x/A".to_owned(),
21615            worktree: PathBuf::from("/nonexistent/worktree"),
21616            summary: "did the thing".to_owned(),
21617            stat: "1 file changed".to_owned(),
21618            files: 1,
21619            commits: 1,
21620            empty: false,
21621            failed: None,
21622            verified_noop: None,
21623            duration_ms: 1234,
21624            folded: false,
21625        }];
21626        let run_id = runner.state.id.clone();
21627
21628        let interrupt = Pause::new();
21629        runner.watch_interrupt(interrupt.clone());
21630        interrupt.park_because("task c3d4 asked to run first");
21631        assert!(runner.park_here().expect("park_here"));
21632
21633        let resumed = Runner::resume(&run_id).expect("resume");
21634        assert_eq!(resumed.state.candidates.len(), 1);
21635        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21636        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21637        assert_eq!(resumed.state.status, runner.state.status);
21638        assert!(
21639            resumed.state.parked,
21640            "still parked until `execute` actually walks the graph again"
21641        );
21642        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21643    }
21644
21645    /// A fresh open question on `run`, stored and handed back for assertions.
21646    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21647        let mut q = ask::Question::new(
21648            run.to_owned(),
21649            "implement".to_owned(),
21650            "impl-A".to_owned(),
21651            "Which storage backend should the cache use?".to_owned(),
21652            String::new(),
21653            vec!["SQLite".to_owned(), "Redis".to_owned()],
21654        );
21655        store.put(&mut q).unwrap();
21656        q
21657    }
21658
21659    #[test]
21660    fn a_failed_runs_open_question_is_abandoned() {
21661        ask_test_home();
21662        let store = ask::Questions::open();
21663        let mut runner = runner_at(RunStatus::Failed);
21664        let run = runner.state.id.clone();
21665        let q = ask_open_question(&store, &run);
21666
21667        runner.settle_questions();
21668
21669        let back = store.get(&q.id).unwrap();
21670        assert!(
21671            !back.status.open(),
21672            "the seat that asked died with the run; nobody is left to read an answer"
21673        );
21674        assert!(
21675            back.detail.contains(&run) && back.detail.contains("failed"),
21676            "the reason names what the run became, not just that it is gone: {}",
21677            back.detail
21678        );
21679    }
21680
21681    #[test]
21682    fn a_merged_runs_open_question_is_abandoned_too() {
21683        ask_test_home();
21684        let store = ask::Questions::open();
21685        // A run that finishes cleanly still leaves nobody to read an answer -
21686        // this is not only a failure-path cleanup.
21687        for status in [RunStatus::Merged, RunStatus::Ready] {
21688            let mut runner = runner_at(status);
21689            let run = runner.state.id.clone();
21690            let q = ask_open_question(&store, &run);
21691
21692            runner.settle_questions();
21693
21694            let back = store.get(&q.id).unwrap();
21695            assert!(
21696                !back.status.open(),
21697                "{status:?} run's question must not outlive the run"
21698            );
21699        }
21700    }
21701
21702    #[test]
21703    fn a_still_resumable_runs_open_question_is_left_alone() {
21704        ask_test_home();
21705        let store = ask::Questions::open();
21706        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21707        // review round and the seat sessions are all still on disk — so a
21708        // question asked mid-round may yet get a real answer from a real
21709        // resume. Sweeping it here would be exactly the failure mode this
21710        // whole feature exists to avoid on the other side.
21711        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21712            let mut runner = runner_at(status);
21713            let run = runner.state.id.clone();
21714            let q = ask_open_question(&store, &run);
21715
21716            runner.settle_questions();
21717
21718            let back = store.get(&q.id).unwrap();
21719            assert!(
21720                back.status.open(),
21721                "{status:?} is still alive; the question must still be waiting"
21722            );
21723        }
21724    }
21725
21726    #[test]
21727    fn settle_questions_never_touches_an_already_answered_question() {
21728        ask_test_home();
21729        let store = ask::Questions::open();
21730        let mut runner = runner_at(RunStatus::Failed);
21731        let run = runner.state.id.clone();
21732        let mut q = ask_open_question(&store, &run);
21733        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21734            .unwrap();
21735        store.put(&mut q).unwrap();
21736
21737        // Called twice, the way a crash-recovered daemon reclaim and the
21738        // graph's own cleanup both can for the same run — `abandon_for_run`
21739        // only ever touches what is still open, so this must be inert both
21740        // times, not merely the second.
21741        runner.settle_questions();
21742        runner.settle_questions();
21743
21744        let back = store.get(&q.id).unwrap();
21745        assert_eq!(
21746            back.status,
21747            ask::QuestionStatus::Answered,
21748            "a real answer is a decision on record, never overwritten by a sweep"
21749        );
21750    }
21751
21752    #[tokio::test]
21753    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21754        let tmp = tempfile::tempdir().unwrap();
21755        let home = tmp.path().join("home");
21756        let repo = tmp.path().join("repo");
21757        std::fs::create_dir(&home).unwrap();
21758        std::fs::create_dir(&repo).unwrap();
21759        init_repo(&repo);
21760
21761        let mut config = Config::default();
21762        config.graph.worktree_root = Some(tmp.path().join("wt"));
21763        config.verify.build_cache = crate::config::BuildCache::Isolated;
21764        let mut state = RunState::new(
21765            repo.clone(),
21766            "main".into(),
21767            "base".into(),
21768            "fold fixture".into(),
21769            config,
21770        );
21771        let root = state.worktree_root();
21772        let mut outputs = Vec::new();
21773        for name in ["idle", "busy"] {
21774            let checkout = root.join(name);
21775            git::worktree_add_detached(&repo, &checkout, "main")
21776                .await
21777                .unwrap();
21778            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21779            let output = target.join("generated");
21780            std::fs::write(&output, name).unwrap();
21781            outputs.push((target, output));
21782        }
21783        let unknown = crate::build_target::root(&home)
21784            .join("00000000-0000-0000-0000-000000000000")
21785            .join("target");
21786        std::fs::create_dir_all(&unknown).unwrap();
21787        let unowned = unknown.join("generated");
21788        std::fs::write(&unowned, "keep").unwrap();
21789        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21790        let crate::cache::AcquireOutcome::Acquired(_lease) =
21791            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21792        else {
21793            panic!("fixture target must be free");
21794        };
21795
21796        state.save_under(&home).unwrap();
21797        fold_run(&mut state, true, &home).await.unwrap();
21798        assert!(!root.exists());
21799        assert!(!outputs[0].1.exists());
21800        assert!(outputs[1].1.is_file());
21801        assert!(unowned.is_file());
21802    }
21803
21804    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21805    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21806    /// without merging, whose winner is still the operator's answer to read.
21807    /// Nothing previously called `fold_run` itself with a real `tally`, so
21808    /// this is the first test to pin down the one distinction the whole
21809    /// automatic-fold feature depends on: the winner's worktree and branch
21810    /// must survive, everything else sharing the run's worktree bay - a
21811    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21812    /// second sweep treats every non-winner directory under the bay alike -
21813    /// must not.
21814    #[tokio::test]
21815    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21816        crate::run::pin_test_home();
21817        let tmp = tempfile::tempdir().expect("tempdir");
21818        let repo = tmp.path().join("repo");
21819        std::fs::create_dir_all(&repo).unwrap();
21820        init_repo(&repo);
21821
21822        let mut config = Config::default();
21823        config.graph.worktree_root = Some(tmp.path().join("wt"));
21824
21825        let mut state = RunState::new(
21826            repo.clone(),
21827            "main".to_owned(),
21828            "deadbeef".to_owned(),
21829            "task".to_owned(),
21830            config,
21831        );
21832        let root = state.worktree_root();
21833        let wt_a = root.join("cand-A");
21834        let wt_b = root.join("cand-B");
21835        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21836            .await
21837            .expect("worktree A");
21838        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21839            .await
21840            .expect("worktree B");
21841
21842        state.candidates = vec![
21843            Candidate {
21844                index: 0,
21845                label: 'A',
21846                agent: "alpha".to_owned(),
21847                branch: "magi/x/A".to_owned(),
21848                worktree: wt_a.clone(),
21849                summary: String::new(),
21850                stat: String::new(),
21851                files: 0,
21852                commits: 0,
21853                empty: false,
21854                failed: None,
21855                verified_noop: None,
21856                duration_ms: 0,
21857                folded: false,
21858            },
21859            Candidate {
21860                index: 1,
21861                label: 'B',
21862                agent: "beta".to_owned(),
21863                branch: "magi/x/B".to_owned(),
21864                worktree: wt_b.clone(),
21865                summary: String::new(),
21866                stat: String::new(),
21867                files: 0,
21868                commits: 0,
21869                empty: false,
21870                failed: None,
21871                verified_noop: None,
21872                duration_ms: 0,
21873                folded: false,
21874            },
21875        ];
21876        state.tally = Some(Tally {
21877            first_choice: BTreeMap::from([('A', 1)]),
21878            borda: BTreeMap::new(),
21879            winner: 'A',
21880            rankings: 1,
21881            unanimous_initial: true,
21882            deliberated: false,
21883            changed_votes: 0,
21884            unanimous_final: true,
21885            tie_break: None,
21886            judges: 1,
21887            present: 1,
21888            quorum: 1,
21889            met_quorum: true,
21890            uncontested: None,
21891        });
21892        state.status = RunStatus::Ready;
21893
21894        state.save_under(&crate::run::home()).unwrap();
21895        fold_run(&mut state, false, &crate::run::home())
21896            .await
21897            .expect("fold_run");
21898
21899        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21900        assert!(
21901            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21902            "the unmerged winner's branch survives"
21903        );
21904        assert!(
21905            !state.candidates[0].folded,
21906            "the winner is not marked folded"
21907        );
21908
21909        assert!(!wt_b.exists(), "the loser's worktree is removed");
21910        assert!(
21911            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
21912            "the loser's branch is removed"
21913        );
21914        assert!(state.candidates[1].folded, "the loser is marked folded");
21915    }
21916
21917    #[tokio::test]
21918    #[cfg(unix)]
21919    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
21920        use std::os::fd::AsRawFd as _;
21921        use std::time::Duration;
21922
21923        let tmp = tempfile::tempdir().unwrap();
21924        let repo = tmp.path().join("repo");
21925        std::fs::create_dir_all(&repo).unwrap();
21926        init_repo(&repo);
21927        let common = repo.join(".git");
21928        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
21929        let home = tmp.path().join("home");
21930        let mut config = Config::default();
21931        config.coordination = crate::config::test_coordination();
21932        config.graph.worktree_root = Some(tmp.path().join("wt"));
21933        config.graph.timeout_resource_wait = 1;
21934        let mut state = RunState::new(
21935            repo.clone(),
21936            "main".into(),
21937            "deadbeef".into(),
21938            "task".into(),
21939            config,
21940        );
21941        let root = state.worktree_root();
21942        let candidate = root.join("cand-A");
21943        let reviewer = root.join("review-1");
21944        let branch = state.branch_for('A');
21945        git::worktree_add_branch(&repo, &candidate, &branch, "main")
21946            .await
21947            .unwrap();
21948        git::worktree_add_detached(&repo, &reviewer, "main")
21949            .await
21950            .unwrap();
21951        git::acquire_worktree_config(&repo).await.unwrap();
21952        state.enabled_worktree_config = true;
21953        state.status = RunStatus::Ready;
21954        state.candidates.push(Candidate {
21955            index: 0,
21956            label: 'A',
21957            agent: "implement".into(),
21958            branch: branch.clone(),
21959            worktree: candidate.clone(),
21960            summary: String::new(),
21961            stat: String::new(),
21962            files: 0,
21963            commits: 0,
21964            empty: false,
21965            failed: None,
21966            verified_noop: None,
21967            duration_ms: 0,
21968            folded: false,
21969        });
21970        state.save_under(&home).unwrap();
21971        let config_before = std::fs::read(common.join("config")).unwrap();
21972        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
21973            .await
21974            .unwrap();
21975        // A separate OS handle bypasses the launcher's local gate, exactly as
21976        // an external updater does, and must still prevent all folding work.
21977        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
21978        assert_eq!(
21979            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
21980            0
21981        );
21982        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21983        assert!(
21984            tokio::time::timeout(Duration::from_millis(200), &mut fold)
21985                .await
21986                .is_err()
21987        );
21988        assert!(candidate.exists());
21989        assert!(reviewer.exists());
21990        assert!(git::branch_exists(&repo, &branch).await.unwrap());
21991        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21992        assert_eq!(
21993            git::git(&repo, &["worktree", "list", "--porcelain"])
21994                .await
21995                .unwrap(),
21996            worktrees_before
21997        );
21998        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
21999            .await
22000            .unwrap()
22001            .unwrap_err();
22002        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
22003        drop(fold);
22004        assert!(candidate.exists() && reviewer.exists());
22005        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
22006        assert_eq!(
22007            state.resource_block.as_ref().unwrap().kind,
22008            "repository coordination"
22009        );
22010        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
22011        drop(external);
22012        let mut fold = Box::pin(fold_run(&mut state, true, &home));
22013        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
22014            .await
22015            .unwrap()
22016            .unwrap();
22017        drop(fold);
22018        assert!(removed.contains(&branch));
22019        assert!(!root.exists());
22020        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
22021        assert!(state.candidates[0].folded);
22022        assert!(!state.enabled_worktree_config);
22023        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
22024        let enabled = git::git_raw(
22025            &repo,
22026            &["config", "--local", "--get", "extensions.worktreeConfig"],
22027        )
22028        .await
22029        .unwrap();
22030        assert!(!enabled.ok(), "the last config reference was released");
22031    }
22032
22033    /// A handover holds repository coordination and then asks for the
22034    /// predecessor's owner lock; an automatic fold already holds that lock. The
22035    /// fold asks for coordination once and gives way, so the handover's short
22036    /// retry succeeds - waiting for it would leave both waiting for each other.
22037    /// Nothing is changed or saved on the way out and the refusal is `live`;
22038    /// the explicit entry points (`magi fold`) still wait, bounded as before.
22039    #[tokio::test]
22040    #[cfg(unix)]
22041    async fn an_automatic_fold_gives_way_to_busy_coordination_instead_of_waiting() {
22042        use std::os::fd::AsRawFd as _;
22043        use std::time::Duration;
22044
22045        let tmp = tempfile::tempdir().unwrap();
22046        let repo = tmp.path().join("repo");
22047        std::fs::create_dir_all(&repo).unwrap();
22048        init_repo(&repo);
22049        let common = repo.join(".git");
22050        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22051        let home = tmp.path().join("home");
22052        let mut config = Config::default();
22053        config.coordination = crate::config::test_coordination();
22054        config.graph.worktree_root = Some(tmp.path().join("wt"));
22055        config.graph.timeout_resource_wait = 60;
22056        let mut state = RunState::new(
22057            repo.clone(),
22058            "main".into(),
22059            "deadbeef".into(),
22060            "task".into(),
22061            config,
22062        );
22063        let candidate = state.worktree_root().join("cand-A");
22064        let branch = state.branch_for('A');
22065        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22066            .await
22067            .unwrap();
22068        state.status = RunStatus::Ready;
22069        state.driver_exited = true;
22070        state.candidates.push(Candidate {
22071            index: 0,
22072            label: 'A',
22073            agent: "implement".into(),
22074            branch: branch.clone(),
22075            worktree: candidate.clone(),
22076            summary: String::new(),
22077            stat: String::new(),
22078            files: 0,
22079            commits: 0,
22080            empty: false,
22081            failed: None,
22082            verified_noop: None,
22083            duration_ms: 0,
22084            folded: false,
22085        });
22086        state.save_under(&home).unwrap();
22087        let id = state.id.clone();
22088        let record = std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap();
22089
22090        // A separate OS handle bypasses the launcher's local gate, exactly as
22091        // another process holding coordination does.
22092        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22093        assert_eq!(
22094            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22095            0
22096        );
22097        let error = tokio::time::timeout(
22098            Duration::from_secs(10),
22099            fold_run_when(&mut state, &home, &|_| Ok(true)),
22100        )
22101        .await
22102        .expect("the automatic fold does not wait out the 60 s resource wait")
22103        .unwrap_err();
22104        assert!(
22105            matches!(
22106                error.downcast_ref::<FoldRefusal>(),
22107                Some(FoldRefusal::Live(_))
22108            ),
22109            "{error:#}"
22110        );
22111        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
22112        // It gave way: both locks it held are free, nothing was removed and
22113        // nothing was saved (no resource block recorded on the record either).
22114        drop(crate::pr_head::owner_lock(&home, &id).expect("the owner lock was released"));
22115        drop(crate::driver::maintenance(&home, &id).expect("the execution lease was released"));
22116        assert!(candidate.exists() && git::branch_exists(&repo, &branch).await.unwrap());
22117        assert_eq!(
22118            std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap(),
22119            record
22120        );
22121
22122        // The explicit entry point was asked for by a person and still waits.
22123        assert!(
22124            tokio::time::timeout(
22125                Duration::from_millis(300),
22126                fold_run(&mut state, true, &home)
22127            )
22128            .await
22129            .is_err(),
22130            "an explicit fold keeps waiting for coordination"
22131        );
22132        assert!(candidate.exists());
22133
22134        drop(external);
22135        let removed = fold_run_when(&mut state, &home, &|_| Ok(true))
22136            .await
22137            .unwrap();
22138        assert!(removed.contains(&branch));
22139        assert!(!candidate.exists());
22140    }
22141
22142    /// A branch handed to a later run is that run's (and its pull request's):
22143    /// folding the run that released it must not delete it.
22144    #[tokio::test]
22145    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
22146        let tmp = tempfile::tempdir().expect("tempdir");
22147        let repo = tmp.path().join("repo");
22148        std::fs::create_dir_all(&repo).unwrap();
22149        init_repo(&repo);
22150        let home = tmp.path().join("home");
22151
22152        let mut config = Config::default();
22153        config.graph.worktree_root = Some(tmp.path().join("wt"));
22154        let mut state = RunState::new(
22155            repo.clone(),
22156            "main".to_owned(),
22157            "deadbeef".to_owned(),
22158            "task".to_owned(),
22159            config,
22160        );
22161        // The worktree is already gone (released); the branch survives.
22162        git::git(&repo, &["branch", "magi/x/A", "main"])
22163            .await
22164            .expect("branch");
22165        state.candidates = vec![Candidate {
22166            index: 0,
22167            label: 'A',
22168            agent: "alpha".to_owned(),
22169            branch: "magi/x/A".to_owned(),
22170            worktree: state.worktree_root().join("cand-A"),
22171            summary: String::new(),
22172            stat: String::new(),
22173            files: 0,
22174            commits: 0,
22175            empty: false,
22176            failed: None,
22177            verified_noop: None,
22178            duration_ms: 0,
22179            folded: true,
22180        }];
22181        state.released_to = Some("20260901-000000-new1".to_owned());
22182        state.released_branches = vec!["magi/x/A".to_owned()];
22183
22184        state.save_under(&home).unwrap();
22185        fold_run(&mut state, true, &home).await.expect("fold_run");
22186        state.status = RunStatus::Merged;
22187        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
22188        state.merge = Some(crate::run::MergeOutcome {
22189            mode: MergeMode::Pr,
22190            ok: true,
22191            detail: "confirmed merged".into(),
22192            empty: false,
22193        });
22194        state.save_under(&home).unwrap();
22195        fold_run(&mut state, true, &home)
22196            .await
22197            .expect("merged fold");
22198
22199        assert!(
22200            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
22201            "the handed-over branch survives a fold"
22202        );
22203    }
22204
22205    /// A winner with nothing ahead of the base is caught before `gh` is ever
22206    /// asked for a pull request, and the message carries what the task's
22207    /// references resolved to.
22208    #[tokio::test]
22209    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
22210        let tmp = tempfile::tempdir().expect("tempdir");
22211        let repo = tmp.path().join("repo");
22212        std::fs::create_dir_all(&repo).unwrap();
22213        init_repo(&repo);
22214        let run = |args: &[&str]| {
22215            let out = std::process::Command::new("git")
22216                .quiet()
22217                .args(args)
22218                .current_dir(&repo)
22219                .output()
22220                .expect("spawn git");
22221            assert!(out.status.success(), "git {args:?}");
22222        };
22223        run(&["branch", "magi/x/A"]);
22224        run(&["checkout", "-q", "-b", "magi/x/B"]);
22225        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
22226        run(&["add", "-A"]);
22227        run(&["commit", "-q", "-m", "work"]);
22228        run(&["checkout", "-q", "main"]);
22229
22230        // A pull request is compared against the remote's base, so the
22231        // fixture needs one. Before it exists nothing can be read, and the
22232        // answer must be "not empty".
22233        let probe = RunState::new(
22234            repo.clone(),
22235            "main".to_owned(),
22236            "deadbeef".to_owned(),
22237            "task".to_owned(),
22238            Config::default(),
22239        );
22240        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
22241        let bare = tmp.path().join("origin.git");
22242        let out = std::process::Command::new("git")
22243            .quiet()
22244            .args(["init", "-q", "--bare"])
22245            .arg(&bare)
22246            .output()
22247            .expect("spawn git");
22248        assert!(out.status.success(), "git init --bare");
22249        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
22250        run(&["push", "-q", "origin", "main"]);
22251
22252        let mut state = RunState::new(
22253            repo.clone(),
22254            "main".to_owned(),
22255            "deadbeef".to_owned(),
22256            "task".to_owned(),
22257            Config::default(),
22258        );
22259        state.seeds = vec![refs::Seed {
22260            token: "magi/27b2/A".to_owned(),
22261            kind: refs::SeedKind::Unresolved,
22262            sha: String::new(),
22263            branch: true,
22264            detail: "no branch or commit named magi/27b2/A".to_owned(),
22265        }];
22266
22267        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
22268        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
22269        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
22270        let detail = empty_candidate_detail(&state, "main");
22271        assert!(detail.starts_with("empty candidate"), "{detail}");
22272        assert!(!detail.contains("magi/27b2/A"), "{detail}");
22273        assert!(detail.contains("--start-from"), "{detail}");
22274    }
22275
22276    /// `status == Ready` used to be read as "this is the harmless
22277    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
22278    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
22279    /// run's PR was closed without merging — and reentering `merge` with
22280    /// `mode` still `Pr` does not know the difference, so it pushed and
22281    /// opened a second pull request. `mode == Local` reproduces the same
22282    /// blind spot without a network call: reentry must not attempt another
22283    /// git merge once this node has already recorded an outcome.
22284    #[tokio::test]
22285    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
22286        let tmp = tempfile::tempdir().expect("tempdir");
22287        let repo = tmp.path().join("repo");
22288        std::fs::create_dir_all(&repo).unwrap();
22289        init_repo(&repo);
22290
22291        let mut config = Config::default();
22292        config.merge.mode = MergeMode::Local;
22293
22294        let mut state = RunState::new(
22295            repo.clone(),
22296            "main".to_owned(),
22297            "deadbeef".to_owned(),
22298            "task".to_owned(),
22299            config,
22300        );
22301        state.candidates = vec![Candidate {
22302            index: 0,
22303            label: 'A',
22304            agent: "alpha".to_owned(),
22305            branch: "does-not-exist".to_owned(),
22306            worktree: repo.clone(),
22307            summary: String::new(),
22308            stat: String::new(),
22309            files: 0,
22310            commits: 0,
22311            empty: false,
22312            failed: None,
22313            verified_noop: None,
22314            duration_ms: 0,
22315            folded: false,
22316        }];
22317        state.tally = Some(Tally {
22318            first_choice: BTreeMap::from([('A', 1)]),
22319            borda: BTreeMap::new(),
22320            winner: 'A',
22321            rankings: 1,
22322            unanimous_initial: true,
22323            deliberated: false,
22324            changed_votes: 0,
22325            unanimous_final: true,
22326            tie_break: None,
22327            judges: 0,
22328            present: 0,
22329            quorum: 0,
22330            met_quorum: true,
22331            uncontested: Some("only candidate A produced a change".to_owned()),
22332        });
22333        state.reviews = vec![ReviewRound {
22334            round: 1,
22335            head: "deadbeef".to_owned(),
22336            verified_head: None,
22337            verified_at: None,
22338            reviews: Vec::new(),
22339            e2e: Vec::new(),
22340            fix: None,
22341            blocking: 0,
22342            answered: 0,
22343            expected: 0,
22344            clean: true,
22345            verify_retried: false,
22346            e2e_deferred: false,
22347            e2e_defer_reason: None,
22348            progressed: false,
22349            vote_split: false,
22350            reconsideration: Vec::new(),
22351            verdict: None,
22352        }];
22353        state.gate = vec![CommandOutcome {
22354            command: "test".to_owned(),
22355            code: Some(0),
22356            output_tail: String::new(),
22357            duration_ms: 0,
22358            resource_blocked: false,
22359            ..Default::default()
22360        }];
22361        state.gate_ran = true;
22362        // Reached its conclusion already — e.g. `land` closing the PR without
22363        // merging it, which (like the honest `MergeMode::None` path) leaves
22364        // `status` at `Ready`. The recorded outcome is what actually marks
22365        // this node done.
22366        state.status = RunStatus::Ready;
22367        state.merge = Some(MergeOutcome {
22368            mode: MergeMode::Local,
22369            ok: false,
22370            detail: "already concluded".to_owned(),
22371            empty: false,
22372        });
22373
22374        let mut runner = Runner {
22375            state,
22376            roles: ResolvedRoles {
22377                implementers: Vec::new(),
22378                judges: Vec::new(),
22379                reviewers: Vec::new(),
22380                fixer: None,
22381                conductor: conductor(),
22382                implementer_roster: Vec::new(),
22383                judge_roster: Vec::new(),
22384                reviewer_roster: Vec::new(),
22385            },
22386            sem: Arc::new(Semaphore::new(1)),
22387            pause: Pause::new(),
22388            interrupt: Pause::new(),
22389        };
22390
22391        runner.merge().await.expect("merge");
22392
22393        assert_eq!(
22394            runner.state.status,
22395            RunStatus::Ready,
22396            "a concluded run's status must not change on reentry"
22397        );
22398        assert_eq!(
22399            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22400            Some("already concluded"),
22401            "merge must not run again once the node already recorded an outcome"
22402        );
22403    }
22404
22405    /// `gate` leaves `state.gate_ran` false both before it has ever run and
22406    /// when its last attempt was resource-blocked (the shared build cache
22407    /// could not be acquired or confirmed fresh in time - see
22408    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
22409    /// `Vec` this also leaves behind used to read as "nothing failed" and let
22410    /// a run merge a tree the gate never actually checked - exactly the case
22411    /// a contended cache produces on every retry until it clears. `merge`
22412    /// must refuse until `gate` has actually recorded an attempt.
22413    #[tokio::test]
22414    async fn merge_refuses_a_gate_that_has_not_actually_run() {
22415        let tmp = tempfile::tempdir().expect("tempdir");
22416        let repo = tmp.path().join("repo");
22417        std::fs::create_dir_all(&repo).unwrap();
22418        init_repo(&repo);
22419
22420        let mut config = Config::default();
22421        config.merge.mode = MergeMode::Local;
22422
22423        let mut state = RunState::new(
22424            repo.clone(),
22425            "main".to_owned(),
22426            "deadbeef".to_owned(),
22427            "task".to_owned(),
22428            config,
22429        );
22430        state.candidates = vec![Candidate {
22431            index: 0,
22432            label: 'A',
22433            agent: "alpha".to_owned(),
22434            branch: "does-not-exist".to_owned(),
22435            worktree: repo.clone(),
22436            summary: String::new(),
22437            stat: String::new(),
22438            files: 0,
22439            commits: 0,
22440            empty: false,
22441            failed: None,
22442            verified_noop: None,
22443            duration_ms: 0,
22444            folded: false,
22445        }];
22446        state.tally = Some(Tally {
22447            first_choice: BTreeMap::from([('A', 1)]),
22448            borda: BTreeMap::new(),
22449            winner: 'A',
22450            rankings: 1,
22451            unanimous_initial: true,
22452            deliberated: false,
22453            changed_votes: 0,
22454            unanimous_final: true,
22455            tie_break: None,
22456            judges: 0,
22457            present: 0,
22458            quorum: 0,
22459            met_quorum: true,
22460            uncontested: Some("only candidate A produced a change".to_owned()),
22461        });
22462        state.reviews = vec![ReviewRound {
22463            round: 1,
22464            head: "deadbeef".to_owned(),
22465            verified_head: None,
22466            verified_at: None,
22467            reviews: Vec::new(),
22468            e2e: Vec::new(),
22469            fix: None,
22470            blocking: 0,
22471            answered: 0,
22472            expected: 0,
22473            clean: true,
22474            verify_retried: false,
22475            e2e_deferred: false,
22476            e2e_defer_reason: None,
22477            progressed: false,
22478            vote_split: false,
22479            reconsideration: Vec::new(),
22480            verdict: None,
22481        }];
22482        // The point: `gate` has not recorded anything yet.
22483        state.gate = Vec::new();
22484        state.gate_ran = false;
22485        state.status = RunStatus::Gating;
22486
22487        let mut runner = Runner {
22488            state,
22489            roles: ResolvedRoles {
22490                implementers: Vec::new(),
22491                judges: Vec::new(),
22492                reviewers: Vec::new(),
22493                fixer: None,
22494                conductor: conductor(),
22495                implementer_roster: Vec::new(),
22496                judge_roster: Vec::new(),
22497                reviewer_roster: Vec::new(),
22498            },
22499            sem: Arc::new(Semaphore::new(1)),
22500            pause: Pause::new(),
22501            interrupt: Pause::new(),
22502        };
22503
22504        runner.merge().await.expect("merge");
22505
22506        assert!(
22507            runner.state.merge.is_none(),
22508            "an empty gate must never be read as a passing one: {:?}",
22509            runner.state.merge
22510        );
22511    }
22512
22513    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
22514    /// commands configured and `merge.mode` is `none` (a review-only run).
22515    /// `gate` must still record a real attempt — zero commands, vacuously
22516    /// passed — rather than leaving `state.gate` empty in a way `merge`
22517    /// cannot tell apart from "never ran"; otherwise the run reaches
22518    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
22519    #[tokio::test]
22520    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
22521        let tmp = tempfile::tempdir().expect("tempdir");
22522        let repo = tmp.path().join("repo");
22523        std::fs::create_dir_all(&repo).unwrap();
22524        init_repo(&repo);
22525
22526        // Default config: `verify.gate` empty, `merge.mode` is `none`.
22527        let config = Config::default();
22528
22529        let mut state = RunState::new(
22530            repo.clone(),
22531            "main".to_owned(),
22532            "deadbeef".to_owned(),
22533            "task".to_owned(),
22534            config,
22535        );
22536        state.candidates = vec![Candidate {
22537            index: 0,
22538            label: 'A',
22539            agent: "alpha".to_owned(),
22540            branch: "does-not-exist".to_owned(),
22541            worktree: repo.clone(),
22542            summary: String::new(),
22543            stat: String::new(),
22544            files: 0,
22545            commits: 0,
22546            empty: false,
22547            failed: None,
22548            verified_noop: None,
22549            duration_ms: 0,
22550            folded: false,
22551        }];
22552        state.tally = Some(Tally {
22553            first_choice: BTreeMap::from([('A', 1)]),
22554            borda: BTreeMap::new(),
22555            winner: 'A',
22556            rankings: 1,
22557            unanimous_initial: true,
22558            deliberated: false,
22559            changed_votes: 0,
22560            unanimous_final: true,
22561            tie_break: None,
22562            judges: 0,
22563            present: 0,
22564            quorum: 0,
22565            met_quorum: true,
22566            uncontested: Some("only candidate A produced a change".to_owned()),
22567        });
22568        state.reviews = vec![ReviewRound {
22569            round: 1,
22570            head: "deadbeef".to_owned(),
22571            verified_head: None,
22572            verified_at: None,
22573            reviews: Vec::new(),
22574            e2e: Vec::new(),
22575            fix: None,
22576            blocking: 0,
22577            answered: 0,
22578            expected: 0,
22579            clean: true,
22580            verify_retried: false,
22581            e2e_deferred: false,
22582            e2e_defer_reason: None,
22583            progressed: false,
22584            vote_split: false,
22585            reconsideration: Vec::new(),
22586            verdict: None,
22587        }];
22588
22589        let mut runner = Runner {
22590            state,
22591            roles: ResolvedRoles {
22592                implementers: Vec::new(),
22593                judges: Vec::new(),
22594                reviewers: Vec::new(),
22595                fixer: None,
22596                conductor: conductor(),
22597                implementer_roster: Vec::new(),
22598                judge_roster: Vec::new(),
22599                reviewer_roster: Vec::new(),
22600            },
22601            sem: Arc::new(Semaphore::new(1)),
22602            pause: Pause::new(),
22603            interrupt: Pause::new(),
22604        };
22605
22606        runner.gate().await.expect("gate");
22607        assert!(
22608            runner.state.gate_ran,
22609            "zero configured commands is still a real attempt, not an unrun gate"
22610        );
22611        assert!(runner.state.gate.is_empty());
22612        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
22613        assert_ne!(
22614            runner.state.status,
22615            RunStatus::Blocked,
22616            "a gate with nothing to check must not read as failed"
22617        );
22618
22619        runner.merge().await.expect("merge");
22620        assert_eq!(
22621            runner.state.status,
22622            RunStatus::Ready,
22623            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
22624        );
22625    }
22626
22627    /// `Config::cache_dir` is derived from `verify.e2e` as well as
22628    /// `verify.gate` (so the e2e leg and the final gate never build against
22629    /// different directories). With zero `verify.gate` commands but a
22630    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
22631    /// that lease before discovering it had nothing to run - so a repo with
22632    /// no gate commands could come back `resource_blocked` (and therefore
22633    /// still `gate_ran == false`) on nothing but an unrelated run holding the
22634    /// cache, exactly the contention this run's own zero commands could
22635    /// never have touched. `gate` must recognise there is nothing to check
22636    /// before it ever asks for the lease.
22637    #[tokio::test]
22638    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
22639        crate::run::pin_test_home();
22640        let home = crate::run::home();
22641
22642        let tmp = tempfile::tempdir().expect("tempdir");
22643        let repo = tmp.path().join("repo");
22644        std::fs::create_dir_all(&repo).unwrap();
22645        init_repo(&repo);
22646        // Unique to this test, so holding its lease cannot collide with
22647        // another test sharing the same process-wide `home`.
22648        let cache_dir = tmp.path().join("target");
22649
22650        let mut config = Config::default();
22651        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
22652        // `verify.gate` stays empty (the default). Any accidental cache
22653        // acquisition must report contention immediately, regardless of how
22654        // long unrelated Git subprocesses take under parallel test load.
22655        config.graph.timeout_verify = Some(2);
22656        config.graph.timeout_resource_wait = 0;
22657
22658        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22659        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22660            .expect("no io error acquiring directly")
22661        {
22662            crate::cache::AcquireOutcome::Acquired(g) => g,
22663            crate::cache::AcquireOutcome::Busy(b) => {
22664                panic!("expected the direct acquire to win the lease first: {b:?}")
22665            }
22666        };
22667
22668        let mut state = RunState::new(
22669            repo.clone(),
22670            "main".to_owned(),
22671            "deadbeef".to_owned(),
22672            "task".to_owned(),
22673            config,
22674        );
22675        state.candidates = vec![Candidate {
22676            index: 0,
22677            label: 'A',
22678            agent: "alpha".to_owned(),
22679            branch: "does-not-exist".to_owned(),
22680            worktree: repo.clone(),
22681            summary: String::new(),
22682            stat: String::new(),
22683            files: 0,
22684            commits: 0,
22685            empty: false,
22686            failed: None,
22687            verified_noop: None,
22688            duration_ms: 0,
22689            folded: false,
22690        }];
22691        state.tally = Some(Tally {
22692            first_choice: BTreeMap::from([('A', 1)]),
22693            borda: BTreeMap::new(),
22694            winner: 'A',
22695            rankings: 1,
22696            unanimous_initial: true,
22697            deliberated: false,
22698            changed_votes: 0,
22699            unanimous_final: true,
22700            tie_break: None,
22701            judges: 0,
22702            present: 0,
22703            quorum: 0,
22704            met_quorum: true,
22705            uncontested: Some("only candidate A produced a change".to_owned()),
22706        });
22707        state.reviews = vec![ReviewRound {
22708            round: 1,
22709            head: "deadbeef".to_owned(),
22710            verified_head: None,
22711            verified_at: None,
22712            reviews: Vec::new(),
22713            e2e: Vec::new(),
22714            fix: None,
22715            blocking: 0,
22716            answered: 0,
22717            expected: 0,
22718            clean: true,
22719            verify_retried: false,
22720            e2e_deferred: false,
22721            e2e_defer_reason: None,
22722            progressed: false,
22723            vote_split: false,
22724            reconsideration: Vec::new(),
22725            verdict: None,
22726        }];
22727
22728        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22729        state.reviews[0].e2e = vec![CommandOutcome {
22730            command: state.config.verify.e2e[0].clone(),
22731            code: Some(0),
22732            output_tail: String::new(),
22733            duration_ms: 0,
22734            resource_blocked: false,
22735            ..Default::default()
22736        }];
22737        let mut runner = Runner {
22738            state,
22739            roles: ResolvedRoles {
22740                implementers: Vec::new(),
22741                judges: Vec::new(),
22742                reviewers: Vec::new(),
22743                fixer: None,
22744                conductor: conductor(),
22745                implementer_roster: Vec::new(),
22746                judge_roster: Vec::new(),
22747                reviewer_roster: Vec::new(),
22748            },
22749            sem: Arc::new(Semaphore::new(1)),
22750            pause: Pause::new(),
22751            interrupt: Pause::new(),
22752        };
22753
22754        runner.gate().await.expect("gate");
22755        assert!(runner.state.resource_block.is_none());
22756        assert!(
22757            !runner
22758                .state
22759                .events
22760                .iter()
22761                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22762            "a gate with nothing to run must never request the held cache lease"
22763        );
22764        assert!(
22765            runner.state.gate_ran,
22766            "zero commands is still a real, immediate attempt"
22767        );
22768        assert!(runner.state.gate.is_empty());
22769        assert_ne!(
22770            runner.state.status,
22771            RunStatus::Blocked,
22772            "must not read as resource-blocked on a lease it never asked for"
22773        );
22774    }
22775
22776    /// A separate process carries a live worker's environment throughout all
22777    /// verification entry points; the parallel harness never changes its env.
22778    #[cfg(unix)]
22779    #[tokio::test]
22780    async fn verification_is_standalone_inside_a_live_worker() {
22781        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22782        if std::env::var_os(CHILD).is_none() {
22783            let home = tempfile::tempdir().unwrap();
22784            let generation = crate::worker::pin_current(home.path()).unwrap();
22785            let output = std::process::Command::new(std::env::current_exe().unwrap())
22786                .args([
22787                    "--exact",
22788                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22789                    "--nocapture",
22790                ])
22791                .env(CHILD, "1")
22792                .env("MAGI_HOME", home.path())
22793                .env("MAGI_WORKER_HOME", home.path())
22794                .env("MAGI_WORKER_ID", "abcdef")
22795                .env("MAGI_WORKER_GENERATION", &generation.id)
22796                .env("MAGI_WORKER_EXE", &generation.executable)
22797                .env("MAGI_RUN", "verification-parent")
22798                .env("MAGI_NODE", "gate")
22799                .env("MAGI_SEAT", "worker-fixture")
22800                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22801                .env("MAGI_NO_AUTOUPDATE", "0")
22802                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22803                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22804                .env(
22805                    "VERIFY_EXPECT_TOOLCHAIN",
22806                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22807                )
22808                .env(
22809                    "VERIFY_EXPECT_CACHE",
22810                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22811                )
22812                .output()
22813                .unwrap();
22814            assert!(
22815                output.status.success()
22816                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22817                "{}\n{}",
22818                String::from_utf8_lossy(&output.stdout),
22819                String::from_utf8_lossy(&output.stderr)
22820            );
22821            return;
22822        }
22823        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22824        let home = crate::run::home();
22825        let directory = home.join("workers/jobs/abcdef");
22826        std::fs::create_dir_all(&directory).unwrap();
22827        let job = crate::worker::Job {
22828            id: "abcdef".into(),
22829            sequence: 1,
22830            kind: "task".into(),
22831            key: "task:verification".into(),
22832            payload: serde_json::json!({}),
22833            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22834            version: Some(env!("CARGO_PKG_VERSION").into()),
22835            status: crate::worker::Status::Running,
22836            result: None,
22837            pid: Some(std::process::id()),
22838            created_at: 0,
22839            finished_at: None,
22840        };
22841        std::fs::write(
22842            directory.join("job.json"),
22843            serde_json::to_vec(&job).unwrap(),
22844        )
22845        .unwrap();
22846        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22847        let assert_worker = || {
22848            assert_eq!(
22849                crate::worker::current_job(&home).unwrap().unwrap().id,
22850                job.id
22851            );
22852            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22853            assert_eq!(
22854                crate::worker::helper_executable(&home).unwrap(),
22855                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22856            );
22857            assert!(
22858                crate::updater::Checker::new(&crate::config::Update {
22859                    mode: crate::config::UpdateMode::Notify,
22860                    interval: None,
22861                    auto_restart: false,
22862                })
22863                .is_none(),
22864                "the driver remains pinned, even while tests are standalone"
22865            );
22866        };
22867        assert_worker();
22868        let repo = home.join("repo");
22869        std::fs::create_dir_all(&repo).unwrap();
22870        init_repo(&repo);
22871        // Keep storage, seat/control context, containment and tool lookup.
22872        // No inherited values (or credentials) are printed on success.
22873        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22874            test -z "${MAGI_WORKER_GENERATION+x}" &&
22875            test -z "${MAGI_WORKER_HOME+x}" &&
22876            test -z "${MAGI_WORKER_EXE+x}" &&
22877            test "$MAGI_HOME/repo" -ef . &&
22878            test "$MAGI_RUN" = verification-parent &&
22879            test "$MAGI_NODE" = gate &&
22880            test "$MAGI_SEAT" = worker-fixture &&
22881            test -n "$MAGI_PROCESS_OWNER" &&
22882            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22883            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22884            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22885            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22886        // Negative control: an ordinary child inherits the contamination.
22887        assert!(
22888            !std::process::Command::new("sh")
22889                .args(["-c", probe])
22890                .current_dir(&repo)
22891                .status()
22892                .unwrap()
22893                .success()
22894        );
22895        let unrelated_home = tempfile::tempdir().unwrap();
22896        assert!(
22897            crate::worker::current_job(unrelated_home.path()).is_err(),
22898            "an inherited worker id cannot be resolved in a unit fixture's home"
22899        );
22900        let mut runner = runner_at(RunStatus::Gating);
22901        runner.state.repo = repo.clone();
22902        runner.state.config.disk.min_free_bytes = 0;
22903        runner.state.config.coordination = crate::config::test_coordination();
22904        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
22905        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
22906        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
22907        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
22908        let winner = Candidate {
22909            index: 0,
22910            label: 'A',
22911            agent: "fixture".into(),
22912            branch: "main".into(),
22913            worktree: repo.clone(),
22914            summary: String::new(),
22915            stat: String::new(),
22916            files: 0,
22917            commits: 0,
22918            empty: false,
22919            failed: None,
22920            verified_noop: None,
22921            duration_ms: 0,
22922            folded: false,
22923        };
22924        let (e2e, retried, pids) = run_e2e_with_retry(
22925            &mut runner.state,
22926            &["sh".into(), "-c".into()],
22927            &[format!("{probe} && printf initial")],
22928            &repo,
22929            Duration::from_secs(10),
22930            "initial",
22931            None,
22932        )
22933        .await;
22934        assert!(!retried && pids.is_empty());
22935        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
22936        assert_eq!(e2e[0].output_tail, "initial");
22937        let gate = runner.run_gate(&winner).await.unwrap();
22938        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
22939        // An interrupted repair must recheck e2e from saved state. Landing
22940        // reuses that state and must run both pre-gate and gate again.
22941        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
22942            git::rev_parse(&repo, "HEAD").await.unwrap(),
22943            false,
22944            Vec::new(),
22945        ));
22946        runner.state.save().unwrap();
22947        let mut resumed = RunState::load(&runner.state.id).unwrap();
22948        let wait = crate::repo_lock::WaitPolicy::default();
22949        assert!(matches!(
22950            check_gate_repair_e2e(&mut resumed, &winner, &wait)
22951                .await
22952                .unwrap(),
22953            GateFix::Retry
22954        ));
22955        let saved = RunState::load(&resumed.id).unwrap();
22956        let repair = saved.gate_repair_e2e.unwrap();
22957        assert!(repair.passed);
22958        assert_eq!(repair.outcomes.len(), 1);
22959        assert!(repair.outcomes[0].ok());
22960        let landing = run_landing_gate(&mut resumed, &winner, &wait)
22961            .await
22962            .unwrap();
22963        assert_eq!(landing.len(), 1);
22964        assert!(landing[0].ok(), "{landing:?}");
22965        assert_eq!(
22966            std::fs::read_to_string(repo.join("phases")).unwrap(),
22967            "pre\ngate\ne2e\npre\ngate\n"
22968        );
22969        assert_worker();
22970    }
22971
22972    #[cfg(unix)]
22973    #[tokio::test]
22974    async fn verification_keeps_the_panic_and_the_full_output() {
22975        crate::run::pin_test_home();
22976        let tmp = tempfile::tempdir().unwrap();
22977        let mut config = Config::default();
22978        config.disk.min_free_bytes = 0;
22979        let mut state = RunState::new(
22980            tmp.path().to_owned(),
22981            "main".into(),
22982            "base".into(),
22983            "verification evidence".into(),
22984            config,
22985        );
22986        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
22987                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
22988                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
22989        let mut names = Vec::new();
22990        for _ in 0..2 {
22991            let (outcomes, _) = run_commands(
22992                &mut state,
22993                "gate",
22994                "gate",
22995                0,
22996                &["sh".into(), "-c".into()],
22997                &[script.into()],
22998                tmp.path(),
22999                Duration::from_secs(60),
23000            )
23001            .await;
23002            let tail = &outcomes[0].output_tail;
23003            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
23004            assert!(tail.contains("boom assertion"));
23005            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
23006            let line = tail.lines().next().unwrap();
23007            names.push(line.to_owned());
23008        }
23009        assert_ne!(names[0], names[1], "the second run must not overwrite");
23010        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
23011        assert!(full.len() > 500_000 && full.contains("boom assertion"));
23012        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
23013
23014        // Storage failures are evidence too; preserve the command's verdict.
23015        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
23016        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
23017        let (outcomes, _) = run_commands(
23018            &mut state,
23019            "gate",
23020            "gate",
23021            0,
23022            &["sh".into(), "-c".into()],
23023            &["echo failure-output; exit 7".into()],
23024            tmp.path(),
23025            Duration::from_secs(10),
23026        )
23027        .await;
23028        assert_eq!(outcomes[0].code, Some(7));
23029        assert!(state.events.iter().any(|e| {
23030            e.node == "gate" && e.message.contains("could not save the full gate output:")
23031        }));
23032    }
23033
23034    #[cfg(unix)]
23035    #[tokio::test]
23036    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
23037        crate::run::pin_test_home();
23038        let tmp = tempfile::tempdir().unwrap();
23039        let mut config = Config::default();
23040        config.disk.min_free_bytes = 0;
23041        let mut state = RunState::new(
23042            tmp.path().to_owned(),
23043            "main".into(),
23044            "base".into(),
23045            "verification evidence".into(),
23046            config,
23047        );
23048        let (outcomes, pids) = run_commands(
23049            &mut state,
23050            "gate",
23051            "gate",
23052            1,
23053            &["sh".into(), "-c".into()],
23054            &[
23055                "printf before-timeout; exec sleep 30".into(),
23056                "kill -TERM $$".into(),
23057                "exit 7".into(),
23058                "printf success".into(),
23059            ],
23060            tmp.path(),
23061            Duration::from_secs(1),
23062        )
23063        .await;
23064        wait_for_timed_out_children_to_die(&pids).await;
23065        assert_eq!(
23066            pids.len(),
23067            1,
23068            "unleased timeout retains its death-check PID"
23069        );
23070        assert_eq!(outcomes.len(), 4);
23071        assert_eq!(outcomes[0].code, None);
23072        assert!(outcomes[0].output_tail.contains("before-timeout"));
23073        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
23074        assert_eq!(outcomes[1].code, None);
23075        assert!(outcomes[1].output_tail.contains("command terminated:"));
23076        assert!(!outcomes[1].output_tail.contains("timed out"));
23077        assert_eq!(outcomes[2].code, Some(7));
23078        assert!(!outcomes[2].output_tail.contains("timed out"));
23079        assert_eq!(outcomes[3].code, Some(0));
23080        assert_eq!(outcomes[3].output_tail, "success");
23081        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
23082    }
23083
23084    /// The addendum's second gap: a `verify.gate` command running for real
23085    /// wall-clock time had nothing at all to show for it in `active` before
23086    /// `run_commands` learned to record it — a run could sit in `Gating` for
23087    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
23088    /// what was actually happening. Proven with a genuinely still-running
23089    /// command, not just a before/after check on the final state: a poller
23090    /// task reads the same `run.json` `gate()` is writing, the same way the
23091    /// phone or `magi show` would, while the shell command is still blocked
23092    /// on its own release marker.
23093    #[tokio::test]
23094    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
23095        crate::run::pin_test_home();
23096
23097        let tmp = tempfile::tempdir().expect("tempdir");
23098        let repo = tmp.path().join("repo");
23099        std::fs::create_dir_all(&repo).unwrap();
23100        init_repo(&repo);
23101
23102        let mut config = Config::default();
23103        config.disk.min_free_bytes = 0;
23104        config.verify.gate = vec![
23105            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
23106             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
23107                .to_owned(),
23108        ];
23109
23110        let mut state = RunState::new(
23111            repo.clone(),
23112            "main".to_owned(),
23113            "deadbeef".to_owned(),
23114            "task".to_owned(),
23115            config,
23116        );
23117        let run_id = state.id.clone();
23118        state.candidates = vec![Candidate {
23119            index: 0,
23120            label: 'A',
23121            agent: "alpha".to_owned(),
23122            branch: "does-not-exist".to_owned(),
23123            worktree: repo.clone(),
23124            summary: String::new(),
23125            stat: String::new(),
23126            files: 0,
23127            commits: 0,
23128            empty: false,
23129            failed: None,
23130            verified_noop: None,
23131            duration_ms: 0,
23132            folded: false,
23133        }];
23134        state.tally = Some(Tally {
23135            first_choice: BTreeMap::from([('A', 1)]),
23136            borda: BTreeMap::new(),
23137            winner: 'A',
23138            rankings: 1,
23139            unanimous_initial: true,
23140            deliberated: false,
23141            changed_votes: 0,
23142            unanimous_final: true,
23143            tie_break: None,
23144            judges: 0,
23145            present: 0,
23146            quorum: 0,
23147            met_quorum: true,
23148            uncontested: Some("only candidate A produced a change".to_owned()),
23149        });
23150        state.reviews = vec![ReviewRound {
23151            round: 1,
23152            head: "deadbeef".to_owned(),
23153            verified_head: None,
23154            verified_at: None,
23155            reviews: Vec::new(),
23156            e2e: Vec::new(),
23157            fix: None,
23158            blocking: 0,
23159            answered: 0,
23160            expected: 0,
23161            clean: true,
23162            verify_retried: false,
23163            e2e_deferred: false,
23164            e2e_defer_reason: None,
23165            progressed: false,
23166            vote_split: false,
23167            reconsideration: Vec::new(),
23168            verdict: None,
23169        }];
23170
23171        let mut runner = Runner {
23172            state,
23173            roles: ResolvedRoles {
23174                implementers: Vec::new(),
23175                judges: Vec::new(),
23176                reviewers: Vec::new(),
23177                fixer: None,
23178                conductor: conductor(),
23179                implementer_roster: Vec::new(),
23180                judge_roster: Vec::new(),
23181                reviewer_roster: Vec::new(),
23182            },
23183            sem: Arc::new(Semaphore::new(1)),
23184            pause: Pause::new(),
23185            interrupt: Pause::new(),
23186        };
23187
23188        let started_marker = repo.join("started.marker");
23189        let release_marker = repo.join("release.marker");
23190        let observe = async {
23191            loop {
23192                if started_marker.exists()
23193                    && let Ok(s) = crate::run::RunState::load(&run_id)
23194                    && let Some(a) = s.active.get("gate")
23195                {
23196                    std::fs::write(&release_marker, b"go").expect("release marker");
23197                    break a.clone();
23198                }
23199                tokio::time::sleep(Duration::from_millis(50)).await;
23200            }
23201        };
23202        let captured = {
23203            let gate = runner.gate();
23204            tokio::pin!(gate);
23205            let captured = tokio::select! {
23206                observed = observe => observed,
23207                result = &mut gate => panic!(
23208                    "gate exited before its in-flight entry was observed: {result:?}"
23209                ),
23210            };
23211            gate.await.expect("gate");
23212            captured
23213        };
23214
23215        assert_eq!(captured.task.as_deref(), Some("gate"));
23216        assert_eq!(captured.node, "gate");
23217        assert_eq!(captured.index, Some(1));
23218        assert_eq!(captured.total, Some(1));
23219        assert!(
23220            captured
23221                .command
23222                .as_deref()
23223                .is_some_and(|c| c.contains("started.marker")),
23224            "{captured:?}"
23225        );
23226
23227        assert!(
23228            runner.state.active.is_empty(),
23229            "the entry must be cleared once the command actually finished: {:?}",
23230            runner.state.active
23231        );
23232        assert!(runner.state.gate_ran);
23233        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
23234    }
23235
23236    /// The hand-off over a blocking finding a reviewer rejected on leaves a
23237    /// record for `land`; one with only a Minor, or no reject, leaves none.
23238    #[tokio::test]
23239    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
23240        use crate::verdict::{Finding, ReviewVote, Severity};
23241        crate::run::pin_test_home();
23242        let tmp = tempfile::tempdir().expect("tempdir");
23243        let repo = tmp.path().join("repo");
23244        std::fs::create_dir_all(&repo).unwrap();
23245        init_repo(&repo);
23246
23247        for (severity, vote, expect) in [
23248            (Severity::Major, ReviewVote::Reject, true),
23249            (Severity::Minor, ReviewVote::Reject, false),
23250            (Severity::Major, ReviewVote::Approve, false),
23251        ] {
23252            let mut round = review_round(false, 1, 1, 1, false, true);
23253            round.reviews = vec![ReviewRecord {
23254                reviewer: 1,
23255                agent: "alpha".to_owned(),
23256                summary: String::new(),
23257                findings: vec![Finding {
23258                    id: "R1-1-1".to_owned(),
23259                    severity,
23260                    file: None,
23261                    line: None,
23262                    title: "t".to_owned(),
23263                    detail: String::new(),
23264                }],
23265                vote: Some(vote),
23266                failed: None,
23267                duration_ms: 0,
23268                attempts: 0,
23269            }];
23270            let mut state = RunState::new(
23271                repo.clone(),
23272                "main".to_owned(),
23273                "deadbeef".to_owned(),
23274                "task".to_owned(),
23275                Config::default(),
23276            );
23277            state.reviews = vec![round];
23278            let mut runner = Runner {
23279                state,
23280                roles: ResolvedRoles {
23281                    implementers: Vec::new(),
23282                    judges: Vec::new(),
23283                    reviewers: Vec::new(),
23284                    fixer: None,
23285                    conductor: conductor(),
23286                    implementer_roster: Vec::new(),
23287                    judge_roster: Vec::new(),
23288                    reviewer_roster: Vec::new(),
23289                },
23290                sem: Arc::new(Semaphore::new(1)),
23291                pause: Pause::new(),
23292                interrupt: Pause::new(),
23293            };
23294            let shell = runner.state.config.shell();
23295            runner
23296                .stop_reviewing("round budget spent", &shell, &repo)
23297                .await
23298                .expect("stop_reviewing");
23299            assert_eq!(runner.state.status, RunStatus::Gating);
23300            assert_eq!(
23301                runner.state.contested_handoff.is_some(),
23302                expect,
23303                "{severity:?} + {vote:?}"
23304            );
23305        }
23306    }
23307
23308    /// The shape the incident this whole fix responds to actually had: the
23309    /// round budget spent, the last round's own e2e blocked on the shared
23310    /// build cache (held here by a live pid — this test process — exactly
23311    /// `cache`'s own unit tests' pattern for "another owner, still alive"
23312    /// without forking a process). `stop_reviewing` must retry it — not
23313    /// silently leave the round looking untouched (the catch-up-only half of
23314    /// the bug), and not read the contention as a red `e2e` and block the
23315    /// run on it (the other half). Called directly, the same way
23316    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
23317    /// above exercises `gate`, so this never needs a real cargo build to
23318    /// reach: the lease is never released, so `with_cache_lease` never gets
23319    /// past acquiring it into anything that would need a real workspace.
23320    #[tokio::test]
23321    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
23322        crate::run::pin_test_home();
23323        let home = crate::run::home();
23324
23325        let tmp = tempfile::tempdir().expect("tempdir");
23326        let repo = tmp.path().join("repo");
23327        std::fs::create_dir_all(&repo).unwrap();
23328        init_repo(&repo);
23329        let head = crate::git::rev_parse(&repo, "HEAD")
23330            .await
23331            .expect("rev-parse");
23332        // Unique to this test, so holding its lease cannot collide with
23333        // another test sharing the same process-wide `home`.
23334        let cache_dir = tmp.path().join("target");
23335
23336        let mut config = Config::default();
23337        config.verify.e2e = vec![format!(
23338            "CARGO_TARGET_DIR='{}' test -f README.md",
23339            cache_dir.display()
23340        )];
23341        config.graph.review_rounds = 1;
23342        // Bounded so a regression that does start waiting fails the test in
23343        // seconds, not hangs it.
23344        config.graph.timeout_verify = Some(2);
23345        config.graph.timeout_resource_wait = 2;
23346
23347        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23348        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23349            .expect("no io error acquiring directly")
23350        {
23351            crate::cache::AcquireOutcome::Acquired(g) => g,
23352            crate::cache::AcquireOutcome::Busy(b) => {
23353                panic!("expected the direct acquire to win the lease first: {b:?}")
23354            }
23355        };
23356
23357        let mut state = RunState::new(
23358            repo.clone(),
23359            "main".to_owned(),
23360            head.clone(),
23361            "task".to_owned(),
23362            config,
23363        );
23364        state.candidates = vec![Candidate {
23365            index: 0,
23366            label: 'A',
23367            agent: "alpha".to_owned(),
23368            branch: "does-not-exist".to_owned(),
23369            worktree: repo.clone(),
23370            summary: String::new(),
23371            stat: String::new(),
23372            files: 0,
23373            commits: 0,
23374            empty: false,
23375            failed: None,
23376            verified_noop: None,
23377            duration_ms: 0,
23378            folded: false,
23379        }];
23380        state.tally = Some(Tally {
23381            first_choice: BTreeMap::from([('A', 1)]),
23382            borda: BTreeMap::new(),
23383            winner: 'A',
23384            rankings: 1,
23385            unanimous_initial: true,
23386            deliberated: false,
23387            changed_votes: 0,
23388            unanimous_final: true,
23389            tie_break: None,
23390            judges: 0,
23391            present: 0,
23392            quorum: 0,
23393            met_quorum: true,
23394            uncontested: Some("only candidate A produced a change".to_owned()),
23395        });
23396        // The round budget's last round, deferred: `needs_catchup_run`'s
23397        // other trigger. `stop_reviewing`'s retry machinery must treat this
23398        // exactly like a resource-blocked attempt once it actually runs.
23399        state.reviews = vec![ReviewRound {
23400            round: 1,
23401            head: head.clone(),
23402            verified_head: None,
23403            verified_at: None,
23404            reviews: Vec::new(),
23405            e2e: Vec::new(),
23406            fix: None,
23407            blocking: 1,
23408            answered: 1,
23409            expected: 1,
23410            clean: false,
23411            verify_retried: false,
23412            e2e_deferred: true,
23413            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
23414            progressed: false,
23415            vote_split: false,
23416            reconsideration: Vec::new(),
23417            verdict: None,
23418        }];
23419
23420        let mut runner = Runner {
23421            state,
23422            roles: ResolvedRoles {
23423                implementers: Vec::new(),
23424                judges: Vec::new(),
23425                reviewers: Vec::new(),
23426                fixer: None,
23427                conductor: conductor(),
23428                implementer_roster: Vec::new(),
23429                judge_roster: Vec::new(),
23430                reviewer_roster: Vec::new(),
23431            },
23432            sem: Arc::new(Semaphore::new(1)),
23433            pause: Pause::new(),
23434            interrupt: Pause::new(),
23435        };
23436
23437        let shell = runner.state.config.shell();
23438        runner
23439            .stop_reviewing("round budget spent", &shell, &repo)
23440            .await
23441            .expect("stop_reviewing");
23442
23443        let last = runner.state.reviews.last().expect("round record");
23444        assert_eq!(
23445            last.e2e_status(),
23446            E2eStatus::ResourceBlocked,
23447            "the shared cache is still held; the attempt must read as blocked, not deferred or \
23448             failed: {last:?}"
23449        );
23450        assert_eq!(
23451            last.verified_head.as_deref(),
23452            Some(head.as_str()),
23453            "which commit this attempt targeted is known even though nothing finished checking \
23454             it"
23455        );
23456        let first_attempt_at = last
23457            .verified_at
23458            .expect("when this attempt ran is known too");
23459        assert_ne!(
23460            runner.state.status,
23461            RunStatus::Blocked,
23462            "contention is evidence about the machine, not the patch — it must not settle the \
23463             run as blocked: {:?}",
23464            runner.state.status
23465        );
23466        assert!(
23467            !runner
23468                .state
23469                .events
23470                .iter()
23471                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
23472            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
23473            runner.state.events
23474        );
23475
23476        // The cache is still held: a later reentry must retry the same
23477        // round's verification again — not leave it looking exactly as
23478        // untouched as the first blocked attempt, which is indistinguishable
23479        // from never having tried again at all.
23480        runner
23481            .stop_reviewing("round budget spent", &shell, &repo)
23482            .await
23483            .expect("stop_reviewing retry");
23484        assert_eq!(
23485            runner.state.reviews.len(),
23486            1,
23487            "no new round was started: {:?}",
23488            runner.state.reviews
23489        );
23490        let last = runner.state.reviews.last().expect("round record");
23491        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
23492        assert!(
23493            last.verified_at.expect("still known") > first_attempt_at,
23494            "a second reentry must be a fresh attempt, not a stale copy of the first"
23495        );
23496        assert_ne!(runner.state.status, RunStatus::Blocked);
23497
23498        held.release();
23499    }
23500
23501    #[cfg(unix)]
23502    #[tokio::test]
23503    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
23504        ask_test_home();
23505        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
23506            let tmp = tempfile::tempdir().unwrap();
23507            let repo = tmp.path().join("repo");
23508            std::fs::create_dir(&repo).unwrap();
23509            init_repo(&repo);
23510            let run_git = |args: &[&str]| {
23511                let out = std::process::Command::new("git")
23512                    .args(args)
23513                    .current_dir(&repo)
23514                    .output()
23515                    .unwrap();
23516                assert!(
23517                    out.status.success(),
23518                    "{args:?}: {}",
23519                    String::from_utf8_lossy(&out.stderr)
23520                );
23521            };
23522            let origin = tmp.path().join("origin.git");
23523            run_git(&["init", "--bare", origin.to_str().unwrap()]);
23524            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
23525            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
23526            run_git(&["add", "spec.rs"]);
23527            run_git(&["commit", "-m", "initial spec"]);
23528            run_git(&["push", "origin", "main"]);
23529            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
23530            run_git(&["checkout", "-b", "fix/review"]);
23531            std::fs::write(
23532                repo.join("check.rs"),
23533                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
23534            )
23535            .unwrap();
23536            run_git(&["add", "check.rs"]);
23537            run_git(&["commit", "-m", "use spec"]);
23538            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
23539            run_git(&["checkout", "main"]);
23540            std::fs::write(
23541                repo.join("spec.rs"),
23542                "struct AgentSpec { max_turn_secs: u64 }\n",
23543            )
23544            .unwrap();
23545            run_git(&["add", "spec.rs"]);
23546            run_git(&["commit", "-m", "extend spec"]);
23547            run_git(&["push", "origin", "main"]);
23548            run_git(&["checkout", "fix/review"]);
23549
23550            let mut runner = runner_at(RunStatus::Reviewing);
23551            runner.state.repo = repo.clone();
23552            runner.state.base_commit = base;
23553            runner.state.pr_head = Some("fix/review".into());
23554            runner.state.config.graph.review_rounds = max_rounds;
23555            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
23556            runner.state.config.graph.sessions = false;
23557            runner.state.config.disk.min_free_bytes = 0;
23558            runner.state.config.verify.e2e =
23559                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
23560            runner.state.candidates = vec![Candidate {
23561                index: 0,
23562                label: 'A',
23563                agent: "fixture".into(),
23564                branch: "fix/review".into(),
23565                worktree: repo.clone(),
23566                summary: String::new(),
23567                stat: String::new(),
23568                files: 1,
23569                commits: 1,
23570                empty: false,
23571                failed: None,
23572                verified_noop: None,
23573                duration_ms: 0,
23574                folded: false,
23575            }];
23576            runner.state.tally = Some(Tally {
23577                first_choice: BTreeMap::new(),
23578                borda: BTreeMap::new(),
23579                winner: 'A',
23580                rankings: 0,
23581                unanimous_initial: true,
23582                deliberated: false,
23583                changed_votes: 0,
23584                unanimous_final: true,
23585                tie_break: None,
23586                judges: 0,
23587                present: 0,
23588                quorum: 0,
23589                met_quorum: true,
23590                uncontested: Some("review-only".into()),
23591            });
23592            let mut last = review_round(false, 0, 1, 1, false, false);
23593            last.head = reviewed.clone();
23594            last.e2e_deferred = true;
23595            last.e2e[0].resource_blocked = true;
23596            last.e2e[0].output_tail = "waiting for the shared build cache".into();
23597            if max_rounds == 1 {
23598                last.e2e.clear();
23599            }
23600            runner.state.reviews = vec![last];
23601            let calls = tmp.path().join("fix-calls");
23602            let mut fixer = spec("repair");
23603            fixer
23604                .env
23605                .insert("FIX_CALLS".into(), calls.display().to_string());
23606            fixer.command = vec!["sh".into(), "-c".into(), r#"
23607                echo fix >> "$FIX_CALLS"
23608                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
23609                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
23610                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
23611                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
23612            "#.into()];
23613            let mut reviewer = spec("reviewer");
23614            reviewer.command = vec![
23615                "sh".into(),
23616                "-c".into(),
23617                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
23618                    .into(),
23619            ];
23620            runner.roles.fixer = Some(vec![fixer]);
23621            runner.roles.reviewers = vec![reviewer];
23622
23623            runner.sync_to_base().await.unwrap();
23624            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
23625            assert_ne!(rebased, reviewed);
23626            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
23627            if reentry {
23628                // Simulate a crash after catch-up evidence was saved but before
23629                // dispatching the fixer. No dedicated pending-repair field exists.
23630                let shell = runner.state.config.shell();
23631                runner
23632                    .stop_unresolved_review("deferred verification", &shell, &repo)
23633                    .await
23634                    .unwrap();
23635                assert!(runner.catchup_repairable());
23636                assert!(!calls.exists());
23637                runner.state = RunState::load(&runner.state.id).unwrap();
23638                assert!(runner.catchup_repairable());
23639            }
23640            runner.review_loop().await.unwrap();
23641            let first = &runner.state.reviews[0];
23642            assert_eq!(first.head, reviewed);
23643            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
23644            assert!(
23645                first.verify_retried,
23646                "a reproduced build failure gets exactly one retry: {:?}",
23647                first.e2e
23648            );
23649            assert!(first.e2e[0].output_tail.contains("E0063"));
23650            assert!(!runner.catchup_repairable());
23651            if max_rounds == 2 {
23652                assert_eq!(
23653                    runner.state.status,
23654                    RunStatus::Gating,
23655                    "{}",
23656                    crate::report::run(&runner.state)
23657                );
23658                assert_eq!(runner.state.reviews.len(), 2);
23659                assert!(first.fix.as_ref().unwrap().committed);
23660                assert!(runner.state.reviews[1].clean);
23661                assert_eq!(
23662                    runner
23663                        .state
23664                        .reviews
23665                        .iter()
23666                        .filter(|r| r.fix.is_some())
23667                        .count(),
23668                    1
23669                );
23670                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
23671                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
23672            } else {
23673                assert_eq!(runner.state.status, RunStatus::Blocked);
23674                assert!(first.fix.is_none());
23675                assert!(!calls.exists());
23676                let recovery = crate::recovery::assess(
23677                    "prior",
23678                    Some(&runner.state),
23679                    &runner.landing_base(),
23680                    crate::recovery::Relation::Diverged,
23681                );
23682                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
23683                let reasons = recovery.reasons.join("\n");
23684                assert!(
23685                    reasons.contains(&reviewed) && reasons.contains(&rebased),
23686                    "{reasons}"
23687                );
23688                assert!(
23689                    reasons.contains("base sync to")
23690                        && reasons.contains("additional review is required"),
23691                    "{reasons}"
23692                );
23693            }
23694        }
23695    }
23696
23697    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23698    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23699    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23700    /// own top-of-function fast path (`review_conclusion`) correctly reads
23701    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23702    /// own `for` range is empty once the round budget is spent, so
23703    /// `review_loop` must retry the check itself rather than silently doing
23704    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23705    /// above exercises directly, but through `review_loop`'s own entry point
23706    /// this time, proving the wiring between the two rather than just the
23707    /// retry logic in isolation.
23708    #[tokio::test]
23709    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23710        crate::run::pin_test_home();
23711        let home = crate::run::home();
23712
23713        let tmp = tempfile::tempdir().expect("tempdir");
23714        let repo = tmp.path().join("repo");
23715        std::fs::create_dir_all(&repo).unwrap();
23716        init_repo(&repo);
23717        let head = crate::git::rev_parse(&repo, "HEAD")
23718            .await
23719            .expect("rev-parse");
23720        let cache_dir = tmp.path().join("target");
23721
23722        let mut config = Config::default();
23723        config.verify.e2e = vec![format!(
23724            "CARGO_TARGET_DIR='{}' test -f README.md",
23725            cache_dir.display()
23726        )];
23727        config.graph.review_rounds = 1;
23728        config.graph.timeout_verify = Some(2);
23729        config.graph.timeout_resource_wait = 2;
23730
23731        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23732        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23733            .expect("no io error acquiring directly")
23734        {
23735            crate::cache::AcquireOutcome::Acquired(g) => g,
23736            crate::cache::AcquireOutcome::Busy(b) => {
23737                panic!("expected the direct acquire to win the lease first: {b:?}")
23738            }
23739        };
23740
23741        let mut state = RunState::new(
23742            repo.clone(),
23743            "main".to_owned(),
23744            head.clone(),
23745            "task".to_owned(),
23746            config,
23747        );
23748        state.candidates = vec![Candidate {
23749            index: 0,
23750            label: 'A',
23751            agent: "alpha".to_owned(),
23752            branch: "does-not-exist".to_owned(),
23753            worktree: repo.clone(),
23754            summary: String::new(),
23755            stat: String::new(),
23756            files: 0,
23757            commits: 0,
23758            empty: false,
23759            failed: None,
23760            verified_noop: None,
23761            duration_ms: 0,
23762            folded: false,
23763        }];
23764        state.tally = Some(Tally {
23765            first_choice: BTreeMap::from([('A', 1)]),
23766            borda: BTreeMap::new(),
23767            winner: 'A',
23768            rankings: 1,
23769            unanimous_initial: true,
23770            deliberated: false,
23771            changed_votes: 0,
23772            unanimous_final: true,
23773            tie_break: None,
23774            judges: 0,
23775            present: 0,
23776            quorum: 0,
23777            met_quorum: true,
23778            uncontested: Some("only candidate A produced a change".to_owned()),
23779        });
23780        // The exact shape a prior process's `stop_reviewing` would have left
23781        // on disk: the round budget's last round, a real attempt already
23782        // made and already resource-blocked.
23783        state.reviews = vec![ReviewRound {
23784            round: 1,
23785            head: head.clone(),
23786            verified_head: Some(head.clone()),
23787            verified_at: Some(jiff::Timestamp::now()),
23788            reviews: Vec::new(),
23789            e2e: vec![CommandOutcome {
23790                command: format!(
23791                    "CARGO_TARGET_DIR='{}' test -f README.md",
23792                    cache_dir.display()
23793                ),
23794                code: None,
23795                output_tail: "waiting for the shared build cache".to_owned(),
23796                duration_ms: 0,
23797                resource_blocked: true,
23798                ..Default::default()
23799            }],
23800            fix: None,
23801            blocking: 1,
23802            answered: 1,
23803            expected: 1,
23804            clean: false,
23805            verify_retried: false,
23806            e2e_deferred: false,
23807            e2e_defer_reason: None,
23808            progressed: false,
23809            vote_split: false,
23810            reconsideration: Vec::new(),
23811            verdict: None,
23812        }];
23813
23814        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23815        let mut runner = Runner {
23816            state,
23817            roles: ResolvedRoles {
23818                implementers: Vec::new(),
23819                judges: Vec::new(),
23820                reviewers: Vec::new(),
23821                fixer: None,
23822                conductor: conductor(),
23823                implementer_roster: Vec::new(),
23824                judge_roster: Vec::new(),
23825                reviewer_roster: Vec::new(),
23826            },
23827            sem: Arc::new(Semaphore::new(1)),
23828            pause: Pause::new(),
23829            interrupt: Pause::new(),
23830        };
23831
23832        // The lease is still held throughout, so this reentry's own retry is
23833        // also contended — proving `review_loop` actually tried again (not
23834        // that it happened to succeed) is what the timestamp comparison
23835        // below is for.
23836        runner.review_loop().await.expect("review_loop");
23837
23838        assert_eq!(
23839            runner.state.reviews.len(),
23840            1,
23841            "no new round was started on top of the unresolved one: {:?}",
23842            runner.state.reviews
23843        );
23844        let last = &runner.state.reviews[0];
23845        assert_eq!(
23846            last.e2e_status(),
23847            E2eStatus::ResourceBlocked,
23848            "still contended: {last:?}"
23849        );
23850        assert!(
23851            last.verified_at.expect("still known") > first_attempt_at,
23852            "review_loop must have actually retried the check, not left it exactly as found"
23853        );
23854        assert_ne!(
23855            runner.state.status,
23856            RunStatus::Blocked,
23857            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
23858            runner.state.status
23859        );
23860
23861        held.release();
23862    }
23863
23864    #[tokio::test]
23865    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
23866        crate::run::pin_test_home();
23867        for status in [RunStatus::Blocked, RunStatus::Gating] {
23868            let mut runner = runner_at(status);
23869            runner.state.config.graph.land = true;
23870            runner.state.gate_ran = true;
23871            runner.state.merge = Some(MergeOutcome {
23872                mode: MergeMode::Pr,
23873                ok: false,
23874                detail: "the fixer produced no commit".into(),
23875                empty: false,
23876            });
23877            let url = "https://example.invalid/o/r/pull/1";
23878            runner.state.pr = Some(crate::run::PrRecord {
23879                url: url.into(),
23880                number: 1,
23881                state: "open".into(),
23882                checks: "red".into(),
23883                round: 1,
23884                rounds: 1,
23885                red_at_merge: Vec::new(),
23886            });
23887            runner.state.save().unwrap();
23888            // The nonexistent repository makes observation fail before a forge
23889            // command can run. We still must reach land, rather than silently
23890            // return from the graph with its old gate and merge records.
23891            runner.execute_graph().await.unwrap();
23892            assert_eq!(runner.state.status, RunStatus::Blocked);
23893            assert!(runner.state.land_sync_pending);
23894            assert!(runner.state.events.iter().any(|event|
23895                event.node == "land" && event.message == format!("watching {url}")));
23896            assert_eq!(
23897                runner.state.merge.as_ref().unwrap().detail,
23898                "the fixer produced no commit"
23899            );
23900        }
23901    }
23902
23903    #[tokio::test]
23904    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
23905        crate::run::pin_test_home();
23906        let tmp = tempfile::tempdir().expect("tempdir");
23907        let repo = tmp.path().join("repo");
23908        std::fs::create_dir_all(&repo).unwrap();
23909        init_repo(&repo);
23910
23911        let mut config = Config::default();
23912        config.merge.mode = MergeMode::Pr;
23913        config.graph.land = true;
23914        config.graph.land_approval = false;
23915
23916        let mut state = RunState::new(
23917            repo.clone(),
23918            "main".to_owned(),
23919            "deadbeef".to_owned(),
23920            "task".to_owned(),
23921            config,
23922        );
23923        state.candidates = vec![Candidate {
23924            index: 0,
23925            label: 'A',
23926            agent: "alpha".to_owned(),
23927            branch: "does-not-exist".to_owned(),
23928            worktree: repo.clone(),
23929            summary: String::new(),
23930            stat: String::new(),
23931            files: 0,
23932            commits: 0,
23933            empty: false,
23934            failed: None,
23935            verified_noop: None,
23936            duration_ms: 0,
23937            folded: false,
23938        }];
23939        state.tally = Some(Tally {
23940            first_choice: BTreeMap::from([('A', 1)]),
23941            borda: BTreeMap::new(),
23942            winner: 'A',
23943            rankings: 1,
23944            unanimous_initial: true,
23945            deliberated: false,
23946            changed_votes: 0,
23947            unanimous_final: true,
23948            tie_break: None,
23949            judges: 0,
23950            present: 0,
23951            quorum: 0,
23952            met_quorum: true,
23953            uncontested: Some("only candidate A produced a change".to_owned()),
23954        });
23955        state.reviews = vec![ReviewRound {
23956            round: 1,
23957            head: "deadbeef".to_owned(),
23958            verified_head: None,
23959            verified_at: None,
23960            reviews: Vec::new(),
23961            e2e: Vec::new(),
23962            fix: None,
23963            blocking: 0,
23964            answered: 0,
23965            expected: 0,
23966            clean: true,
23967            verify_retried: false,
23968            e2e_deferred: false,
23969            e2e_defer_reason: None,
23970            progressed: false,
23971            vote_split: false,
23972            reconsideration: Vec::new(),
23973            verdict: None,
23974        }];
23975        state.gate = vec![CommandOutcome {
23976            command: "test".to_owned(),
23977            code: Some(0),
23978            output_tail: String::new(),
23979            duration_ms: 0,
23980            resource_blocked: false,
23981            ..Default::default()
23982        }];
23983        state.gate_ran = true;
23984        // A first pass through `merge` already pushed and opened this pull
23985        // request; `status` is `Landing` because a previous call into `land`
23986        // parked or was interrupted before it reached a terminal outcome.
23987        state.status = RunStatus::Landing;
23988        state.merge = Some(MergeOutcome {
23989            mode: MergeMode::Pr,
23990            ok: true,
23991            detail: "https://example.invalid/x/y/pull/1".to_owned(),
23992            empty: false,
23993        });
23994
23995        // The Landing-resume shortcut calls `run_land` directly rather than
23996        // through `merge`, which is exactly the call site that used to skip
23997        // `settle_questions` - see the fixture below.
23998        ask_test_home();
23999        // A real resume loads a persisted run; driver ownership is checked
24000        // against that record before the Landing shortcut is entered.
24001        state.save().expect("save landing run");
24002        let store = ask::Questions::open();
24003        let q = ask_open_question(&store, &state.id);
24004
24005        let mut runner = Runner {
24006            state,
24007            roles: ResolvedRoles {
24008                implementers: Vec::new(),
24009                judges: Vec::new(),
24010                reviewers: Vec::new(),
24011                fixer: None,
24012                conductor: conductor(),
24013                implementer_roster: Vec::new(),
24014                judge_roster: Vec::new(),
24015                reviewer_roster: Vec::new(),
24016            },
24017            sem: Arc::new(Semaphore::new(1)),
24018            pause: Pause::new(),
24019            interrupt: Pause::new(),
24020        };
24021
24022        // `execute`, not `merge` directly: the Landing-resume shortcut lives
24023        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
24024        // exactly because `review_loop` would otherwise clobber the marker
24025        // first.
24026        runner.execute().await.expect("execute");
24027
24028        assert_eq!(
24029            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
24030            Some("https://example.invalid/x/y/pull/1"),
24031            "reentry must not push again or open a second pull request over the \
24032             one `land` is already watching"
24033        );
24034        assert_ne!(
24035            runner.state.status,
24036            RunStatus::Landing,
24037            "land could not actually reach the fake pull request, so it must \
24038             have given up rather than left the run silently parked forever"
24039        );
24040        // `land` could not reach the fake pull request, so it gave up into
24041        // `Blocked` - still resumable, so the question must not have been
24042        // swept just because this branch now also calls `settle_questions`.
24043        assert_eq!(runner.state.status, RunStatus::Blocked);
24044        assert!(
24045            store.get(&q.id).unwrap().status.open(),
24046            "Blocked is still alive; settle_questions must have been a no-op here"
24047        );
24048    }
24049
24050    fn state_with_round(round: ReviewRound) -> RunState {
24051        let mut s = RunState::new(
24052            PathBuf::from("/repo"),
24053            "main".to_owned(),
24054            "abc1234".to_owned(),
24055            "add retries".to_owned(),
24056            Config::default(),
24057        );
24058        s.reviews = vec![round];
24059        s
24060    }
24061
24062    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
24063        crate::verdict::Finding {
24064            id: id.to_owned(),
24065            severity,
24066            file: None,
24067            line: None,
24068            title: title.to_owned(),
24069            detail: String::new(),
24070        }
24071    }
24072
24073    #[test]
24074    fn pr_body_names_open_findings_and_declined_ones() {
24075        let round = ReviewRound {
24076            round: 2,
24077            head: "deadbee".to_owned(),
24078            verified_head: None,
24079            verified_at: None,
24080            reviews: vec![ReviewRecord {
24081                attempts: 0,
24082                reviewer: 1,
24083                agent: "alpha".to_owned(),
24084                summary: String::new(),
24085                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
24086                vote: None,
24087                failed: None,
24088                duration_ms: 0,
24089            }],
24090            e2e: vec![CommandOutcome {
24091                command: "cargo test".to_owned(),
24092                code: Some(0),
24093                output_tail: String::new(),
24094                duration_ms: 0,
24095                resource_blocked: false,
24096                ..Default::default()
24097            }],
24098            verify_retried: false,
24099            e2e_deferred: false,
24100            e2e_defer_reason: None,
24101            fix: Some(FixRecord {
24102                agent: "alpha".to_owned(),
24103                addressed: Vec::new(),
24104                rejected: vec![crate::verdict::Rejection {
24105                    id: "R1-1-1".to_owned(),
24106                    why: "not reachable from any caller".to_owned(),
24107                }],
24108                notes: String::new(),
24109                committed: true,
24110                failed: None,
24111                duration_ms: 0,
24112                continuation: None,
24113            }),
24114            blocking: 0,
24115            answered: 1,
24116            expected: 1,
24117            clean: false,
24118            progressed: true,
24119            vote_split: false,
24120            reconsideration: Vec::new(),
24121            verdict: None,
24122        };
24123        let state = state_with_round(round);
24124        let body = pr_message(&state, 'A').body;
24125
24126        assert!(body.contains("add retries"), "the task must still be there");
24127        assert!(body.contains("R2-1-1"), "{body}");
24128        assert!(!body.contains("unused import"), "{body}");
24129        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
24130        assert!(
24131            !body.contains("not reachable from any caller"),
24132            "the reason it was declined: {body}"
24133        );
24134    }
24135
24136    #[test]
24137    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
24138        let round = ReviewRound {
24139            round: 1,
24140            head: "deadbee".to_owned(),
24141            verified_head: None,
24142            verified_at: None,
24143            reviews: vec![ReviewRecord {
24144                attempts: 0,
24145                reviewer: 1,
24146                agent: "alpha".to_owned(),
24147                summary: String::new(),
24148                findings: Vec::new(),
24149                vote: None,
24150                failed: None,
24151                duration_ms: 0,
24152            }],
24153            e2e: Vec::new(),
24154            verify_retried: false,
24155            e2e_deferred: false,
24156            e2e_defer_reason: None,
24157            fix: None,
24158            blocking: 0,
24159            answered: 1,
24160            expected: 1,
24161            clean: true,
24162            progressed: false,
24163            vote_split: false,
24164            reconsideration: Vec::new(),
24165            verdict: None,
24166        };
24167        let state = state_with_round(round);
24168        let body = pr_message(&state, 'A').body;
24169        assert!(!body.contains("Open review findings"), "{body}");
24170        assert!(!body.contains("Declined"), "{body}");
24171    }
24172
24173    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
24174        let mut state = RunState::new(
24175            PathBuf::from("/repo"),
24176            "main".to_owned(),
24177            "abc1234".to_owned(),
24178            instruction.to_owned(),
24179            Config::default(),
24180        );
24181        // These fixtures test execution flow, independent of host disk capacity.
24182        state.config.disk.min_free_bytes = 0;
24183        state.candidates.push(Candidate {
24184            index: 0,
24185            label: 'A',
24186            agent: "alpha".to_owned(),
24187            branch: "magi/x/A".to_owned(),
24188            worktree: PathBuf::from("/wt"),
24189            summary: summary.to_owned(),
24190            stat: String::new(),
24191            files: 1,
24192            commits: 1,
24193            empty: false,
24194            failed: None,
24195            verified_noop: None,
24196            folded: false,
24197            duration_ms: 0,
24198        });
24199        state
24200    }
24201
24202    fn review_state(subjects: &[&str]) -> RunState {
24203        let mut state = state_with_summary(
24204            "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",
24205            "",
24206        );
24207        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24208        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
24209        state
24210    }
24211
24212    /// A branch rebased onto a main that moved past the recorded
24213    /// `base_commit` is titled from its own first commit, never main's.
24214    #[tokio::test]
24215    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
24216        ask_test_home();
24217        let tmp = tempfile::tempdir().unwrap();
24218        let repo = tmp.path().join("repo");
24219        std::fs::create_dir_all(&repo).unwrap();
24220        init_repo(&repo);
24221        let origin = tmp.path().join("origin.git");
24222        let g = |dir: &Path, args: &[&str]| {
24223            let out = std::process::Command::new("git")
24224                .args(args)
24225                .current_dir(dir)
24226                .quiet()
24227                .output()
24228                .expect("spawn git");
24229            assert!(
24230                out.status.success(),
24231                "git {args:?}: {}",
24232                String::from_utf8_lossy(&out.stderr)
24233            );
24234        };
24235        g(
24236            tmp.path(),
24237            &[
24238                "clone",
24239                "--bare",
24240                "-q",
24241                repo.to_str().unwrap(),
24242                origin.to_str().unwrap(),
24243            ],
24244        );
24245        g(
24246            &repo,
24247            &["remote", "add", "origin", origin.to_str().unwrap()],
24248        );
24249        let c1 = git::rev_parse(&repo, "main").await.unwrap();
24250
24251        // Main moves on; the branch is built on top of the new main.
24252        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
24253        g(&repo, &["add", "-A"]);
24254        g(
24255            &repo,
24256            &["commit", "-q", "-m", "chore(deps): update a crate"],
24257        );
24258        g(&repo, &["push", "-q", "origin", "main"]);
24259        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
24260        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24261        g(&repo, &["add", "-A"]);
24262        g(
24263            &repo,
24264            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
24265        );
24266        g(&repo, &["checkout", "-q", "main"]);
24267
24268        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
24269        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
24270        // Without a readable tracking ref the recorded base's merge base is used.
24271        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
24272        assert_eq!(fallback, c1);
24273
24274        let mut state = review_state(&[
24275            "chore(deps): update a crate",
24276            "fix(daemon): apply a chosen action",
24277        ]);
24278        state.repo = repo.clone();
24279        state.base_branch = "main".to_owned();
24280        state.base_commit = c1;
24281        refresh_reviewed_commits(&mut state, "feat/own").await;
24282        assert_eq!(
24283            state.reviewed_commits,
24284            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
24285        );
24286        assert_eq!(
24287            review_title(&state).as_deref(),
24288            Some("fix(daemon): apply a chosen action")
24289        );
24290        assert_eq!(
24291            leaked_subjects(&state, "feat/own").await,
24292            Some(vec!["chore(deps): update a crate".to_owned()])
24293        );
24294        // A stale tracking ref is still used when the fetch fails, but the
24295        // leak list is withheld.
24296        state.config.merge.remote = "nowhere".to_owned();
24297        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
24298    }
24299
24300    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
24301    /// with `origin/main` one commit behind it, and a summarizing agent that
24302    /// prints whatever `reply` holds.
24303    struct SummaryFixture {
24304        _tmp: tempfile::TempDir,
24305        repo: PathBuf,
24306        reply: PathBuf,
24307        runner: Runner,
24308    }
24309
24310    fn summary_fixture() -> SummaryFixture {
24311        ask_test_home();
24312        let tmp = tempfile::tempdir().unwrap();
24313        let repo = tmp.path().join("repo");
24314        std::fs::create_dir_all(&repo).unwrap();
24315        init_repo(&repo);
24316        let origin = tmp.path().join("origin.git");
24317        let g = |args: &[&str]| {
24318            let out = std::process::Command::new("git")
24319                .args(args)
24320                .current_dir(&repo)
24321                .quiet()
24322                .output()
24323                .expect("spawn git");
24324            assert!(
24325                out.status.success(),
24326                "git {args:?}: {}",
24327                String::from_utf8_lossy(&out.stderr)
24328            );
24329        };
24330        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
24331        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
24332        g(&["push", "-q", "origin", "main"]);
24333        g(&["checkout", "-q", "-b", "feat/own"]);
24334        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24335        g(&["add", "-A"]);
24336        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
24337        let reply = tmp.path().join("reply.txt");
24338        std::fs::write(
24339            &reply,
24340            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
24341        )
24342        .unwrap();
24343        let mut runner = runner_at(RunStatus::Gating);
24344        let mut state = review_state(&["feat(own): add the own file"]);
24345        state.repo = repo.clone();
24346        state.base_branch = "main".to_owned();
24347        state.candidates[0].branch = "feat/own".to_owned();
24348        state.candidates[0].worktree = repo.clone();
24349        let mut author = spec("alpha");
24350        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
24351        author
24352            .env
24353            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
24354        state.config.agents = vec![author];
24355        runner.state = state;
24356        SummaryFixture {
24357            _tmp: tmp,
24358            repo,
24359            reply,
24360            runner,
24361        }
24362    }
24363
24364    async fn posted(f: &mut SummaryFixture) -> PrMessage {
24365        let winner = f.runner.state.candidates[0].clone();
24366        f.runner
24367            .guarded_pr_message(&winner, None, true)
24368            .await
24369            .unwrap()
24370            .expect("an English description never parks")
24371    }
24372
24373    fn clean_round_with_minor_findings() -> ReviewRound {
24374        let mut round = passing_round(2, None);
24375        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
24376        round.reviews = vec![ReviewRecord {
24377            attempts: 0,
24378            reviewer: 1,
24379            agent: "alpha".into(),
24380            summary: "内部レビュー".into(),
24381            findings: vec![
24382                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
24383                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
24384            ],
24385            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
24386            failed: None,
24387            duration_ms: 0,
24388        }];
24389        round
24390    }
24391
24392    #[tokio::test]
24393    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
24394        for review_only in [false, true] {
24395            let mut f = summary_fixture();
24396            if !review_only {
24397                f.runner.state.candidates[0].agent = "alpha".into();
24398            }
24399            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
24400            assert!(f.runner.state.reviews[0].clean);
24401            assert!(f.runner.state.reviews[0].fix.is_none());
24402            assert!(f.runner.state.open_findings().is_empty());
24403            assert_eq!(
24404                crate::pr_outcome::required_finding_ids(&f.runner.state),
24405                ["R2-1-1", "R2-1-2"]
24406            );
24407            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24408            let evidence = crate::pr_outcome::summary_evidence(
24409                &f.runner.state,
24410                crate::pr_outcome::FinalHead::At(&head),
24411            );
24412            assert!(
24413                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
24414            );
24415            // The ordinary reply omits both IDs: no cached description is adopted.
24416            let omitted = posted(&mut f).await;
24417            assert!(omitted.body.contains("No description"));
24418            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
24419            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
24420            assert!(f.runner.state.change_summary.is_none());
24421            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();
24422            let described = posted(&mut f).await;
24423            assert!(described.body.contains("improve documentation for callers"));
24424            assert!(described.body.contains("remaining edge case"));
24425            assert!(described.body.contains("## Open review findings"));
24426            assert!(!described.body.contains("未修正"));
24427        }
24428    }
24429
24430    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
24431        let mut f = summary_fixture();
24432        if !review_only {
24433            f.runner.state.candidates[0].agent = "alpha".into();
24434        }
24435        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24436        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
24437        fixed
24438            .fix
24439            .as_mut()
24440            .unwrap()
24441            .rejected
24442            .push(crate::verdict::Rejection {
24443                id: "R1-1-1".into(),
24444                why: "呼び出されないコードのため辞退".into(),
24445            });
24446        let mut clean = clean_round_with_minor_findings();
24447        clean.verified_head = Some(head.clone());
24448        f.runner.state.reviews = vec![fixed, clean];
24449        ok_gate(&mut f.runner.state, Some(&head));
24450        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
24451        f.runner.state.config.agents.push(scripted("beta", reply));
24452        f.runner.state.config.roles.language_judge =
24453            Some(crate::config::AgentChoice::One("beta".into()));
24454        f
24455    }
24456
24457    #[tokio::test]
24458    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
24459        for review_only in [false, true] {
24460            let mut f = rewrite_fixture_with_findings(review_only,
24461                "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;
24462            let m = posted(&mut f).await;
24463            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24464            let expected =
24465                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
24466            assert!(m.body.contains(&expected));
24467            assert!(m.body.contains("## Review rounds"));
24468            assert!(
24469                m.body
24470                    .contains("Gate (`verify.gate`): passed on the final commit")
24471            );
24472            assert!(
24473                m.body
24474                    .contains("Tests (`verify.e2e`): passed on the final commit")
24475            );
24476            let c = f.runner.state.change_summary.as_ref().unwrap();
24477            assert!(
24478                m.body
24479                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
24480            );
24481            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24482            assert!(crate::pr_outcome::covers_required_findings(
24483                &f.runner.state,
24484                &m.body
24485            ));
24486            assert!(m.body.contains("documentation remains incomplete"));
24487            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
24488            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
24489            assert!(f.runner.state.github_text.is_none());
24490        }
24491    }
24492
24493    #[tokio::test]
24494    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
24495        for review_only in [false, true] {
24496            for reply in [
24497                "TITLE: fix: public description\nA short English description.",
24498                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
24499            ] {
24500                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
24501                let winner = f.runner.state.candidates[0].clone();
24502                let posted = f
24503                    .runner
24504                    .guarded_pr_message(&winner, None, true)
24505                    .await
24506                    .unwrap();
24507                assert!(posted.is_none());
24508                assert!(f.runner.state.parked);
24509                let withheld = f.runner.state.github_text.as_ref().unwrap();
24510                assert!(
24511                    withheld.rewrite.is_none(),
24512                    "an incomplete rewrite must not be selectable"
24513                );
24514                let q = ask::Questions::open()
24515                    .get(withheld.question.as_ref().unwrap())
24516                    .unwrap();
24517                assert!(
24518                    !q.choices
24519                        .contains(&crate::github_text::USE_REWRITE.to_owned())
24520                );
24521                assert!(
24522                    q.detail.contains("R1-1-1")
24523                        && q.detail.contains("R2-1-1")
24524                        && q.detail.contains("R2-1-2")
24525                );
24526            }
24527        }
24528    }
24529
24530    #[tokio::test]
24531    async fn japanese_reports_stay_local_in_both_public_run_modes() {
24532        for review_only in [false, true] {
24533            let mut f = summary_fixture();
24534            if !review_only {
24535                f.runner.state.candidates[0].agent = "alpha".into();
24536            }
24537            f.runner.state.instruction = "内部タスクの説明".into();
24538            f.runner.state.candidates[0].summary = "内部の候補報告".into();
24539            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24540            f.runner.state.reviews = vec![
24541                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
24542                round_with_notes(2, Some("二回目の内部修正報告です。")),
24543                passing_round(3, Some(&head)),
24544            ];
24545            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
24546            ok_gate(&mut f.runner.state, Some(&head));
24547            let captured = f.repo.join("public-prompt.txt");
24548            let author = &mut f.runner.state.config.agents[0];
24549            author.command = vec![
24550                "sh".into(),
24551                "-c".into(),
24552                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24553            ];
24554            author.env.insert(
24555                "PROMPT_FILE".into(),
24556                captured.to_string_lossy().into_owned(),
24557            );
24558            let m = posted(&mut f).await;
24559            assert!(m.body.contains("Adds `own.txt`"));
24560            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
24561            assert!(m.body.contains("R1-1-1"));
24562            assert!(
24563                m.body
24564                    .contains("Gate (`verify.gate`): passed on the final commit")
24565            );
24566            assert!(
24567                m.body
24568                    .contains("Tests (`verify.e2e`): passed on the final commit")
24569            );
24570            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24571            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
24572            let prompt = std::fs::read_to_string(captured).unwrap();
24573            assert!(prompt.contains(&format!(
24574                "git diff {} {head}",
24575                f.runner.state.change_summary.as_ref().unwrap().base
24576            )));
24577            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
24578            assert_eq!(
24579                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
24580                "二回目の内部修正報告です。"
24581            );
24582        }
24583    }
24584
24585    #[tokio::test]
24586    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
24587        for review_only in [false, true] {
24588            let mut f = summary_fixture();
24589            if !review_only {
24590                f.runner.state.candidates[0].agent = "alpha".into();
24591            }
24592            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
24593            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
24594            std::fs::write(&f.reply, "no usable description").unwrap();
24595            let failed = posted(&mut f).await;
24596            assert!(
24597                failed
24598                    .body
24599                    .contains("No description of what this change does could be generated")
24600            );
24601            assert!(failed.body.is_ascii());
24602            assert!(f.runner.state.github_text.is_none());
24603            assert!(f.runner.state.change_summary.is_none());
24604            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24605            let evidence = crate::pr_outcome::summary_evidence(
24606                &f.runner.state,
24607                crate::pr_outcome::FinalHead::At(&head),
24608            );
24609            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
24610            assert!(
24611                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
24612                    .exists()
24613            );
24614            f.runner.state =
24615                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
24616            std::fs::write(
24617                &f.reply,
24618                "TITLE: feat(own): add the own file\nAdds the committed own file.",
24619            )
24620            .unwrap();
24621            let retried = posted(&mut f).await;
24622            assert!(retried.body.contains("Adds the committed own file."));
24623            assert_eq!(
24624                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
24625                "日本語の修正報告"
24626            );
24627        }
24628    }
24629
24630    #[tokio::test]
24631    async fn same_head_verification_and_findings_invalidate_public_prose() {
24632        let mut f = summary_fixture();
24633        posted(&mut f).await;
24634        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24635        let original = f
24636            .runner
24637            .state
24638            .change_summary
24639            .as_ref()
24640            .unwrap()
24641            .evidence
24642            .clone();
24643        ok_gate(&mut f.runner.state, Some(&head));
24644        std::fs::write(
24645            &f.reply,
24646            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
24647        )
24648        .unwrap();
24649        let verified = posted(&mut f).await;
24650        assert!(verified.body.contains("now verified"));
24651        assert_ne!(
24652            f.runner.state.change_summary.as_ref().unwrap().evidence,
24653            original
24654        );
24655        let mut round = round_with_notes(1, Some("内部報告"));
24656        round.reviews.push(ReviewRecord {
24657            attempts: 0,
24658            reviewer: 1,
24659            agent: "alpha".into(),
24660            summary: "内部レビュー".into(),
24661            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
24662            vote: None,
24663            failed: None,
24664            duration_ms: 0,
24665        });
24666        round
24667            .fix
24668            .as_mut()
24669            .unwrap()
24670            .rejected
24671            .push(crate::verdict::Rejection {
24672                id: "R1-1-1".into(),
24673                why: "呼び出し元から到達できない".into(),
24674            });
24675        f.runner.state.reviews = vec![round];
24676        // A description omitting the required ID is unusable, even with a title.
24677        let omitted = posted(&mut f).await;
24678        assert!(omitted.body.contains("No description"));
24679        assert!(omitted.body.contains("R1-1-1"));
24680        assert!(!omitted.body.contains("到達"));
24681        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();
24682        let described = posted(&mut f).await;
24683        assert!(described.body.contains("unreachable from callers"));
24684        assert!(described.body.contains("R1-1-1"));
24685        assert!(!described.body.contains("到達"));
24686        let evidence = f
24687            .runner
24688            .state
24689            .change_summary
24690            .as_ref()
24691            .unwrap()
24692            .evidence
24693            .clone();
24694        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24695        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24696        assert!(posted(&mut f).await.body.contains("rationale updated"));
24697        assert_ne!(
24698            f.runner.state.change_summary.as_ref().unwrap().evidence,
24699            evidence
24700        );
24701        // Old serialized summaries have no evidence fingerprint and must regenerate.
24702        f.runner
24703            .state
24704            .change_summary
24705            .as_mut()
24706            .unwrap()
24707            .evidence
24708            .clear();
24709        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24710        assert!(posted(&mut f).await.body.contains("current specification"));
24711    }
24712
24713    #[tokio::test]
24714    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24715        let mut f = summary_fixture();
24716        let m = posted(&mut f).await;
24717        assert_eq!(m.title, "feat(own): add the own file");
24718        assert!(
24719            m.body
24720                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24721            "{}",
24722            m.body
24723        );
24724        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24725        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24726        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24727        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24728        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24729        let kept = f.runner.state.change_summary.as_ref().unwrap();
24730        assert_eq!(
24731            (kept.head.as_str(), kept.base.as_str()),
24732            (head.as_str(), base.as_str())
24733        );
24734        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24735    }
24736
24737    #[tokio::test]
24738    async fn review_only_summary_receives_the_configured_github_language() {
24739        let mut f = summary_fixture();
24740        f.runner.state.config.graph.github_language = "ja".into();
24741        let captured = f.repo.join("summary-prompt.txt");
24742        let author = &mut f.runner.state.config.agents[0];
24743        author.command = vec![
24744            "sh".into(),
24745            "-c".into(),
24746            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24747        ];
24748        author.env.insert(
24749            "PROMPT_FILE".into(),
24750            captured.to_string_lossy().into_owned(),
24751        );
24752        std::fs::write(
24753            &f.reply,
24754            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24755        )
24756        .unwrap();
24757        let m = posted(&mut f).await;
24758        let prompt = std::fs::read_to_string(captured).unwrap();
24759        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24760        assert!(!prompt.contains("in English"));
24761        assert_eq!(m.title, "feat(own): ファイルを追加");
24762        assert!(m.body.contains("own.txt を追加します。"));
24763    }
24764
24765    #[tokio::test]
24766    async fn review_fixes_come_after_the_whole_change_summary() {
24767        let mut f = summary_fixture();
24768        f.runner.state.reviews = vec![
24769            round_with_notes(1, Some("handled the PATH case")),
24770            round_with_notes(2, None),
24771        ];
24772        let m = posted(&mut f).await;
24773        let summary = m.body.find("## Summary").expect("summary");
24774        let fixes = m.body.find("## Review rounds").expect("review rounds");
24775        assert!(summary < fixes, "{}", m.body);
24776        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24777        assert!(m.body.contains("## Final verification"), "{}", m.body);
24778    }
24779
24780    #[tokio::test]
24781    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24782        let mut f = summary_fixture();
24783        let first = posted(&mut f).await;
24784        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24785        // The same head reuses the record: a different reply is not read.
24786        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24787        let again = posted(&mut f).await;
24788        assert_eq!((again.title, again.body), (first.title, first.body));
24789
24790        let g = |args: &[&str]| {
24791            let out = std::process::Command::new("git")
24792                .args(args)
24793                .current_dir(&f.repo)
24794                .quiet()
24795                .output()
24796                .expect("spawn git");
24797            assert!(out.status.success(), "git {args:?}");
24798        };
24799        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24800        g(&["add", "-A"]);
24801        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24802        let second = posted(&mut f).await;
24803        let kept = f.runner.state.change_summary.clone().unwrap();
24804        assert_ne!(kept.head, first_head);
24805        assert!(second.body.contains("Not read yet."), "{}", second.body);
24806        assert!(!second.body.contains("so the first summary is read"));
24807        assert_eq!(second.title, "feat(own): other");
24808    }
24809
24810    #[tokio::test]
24811    async fn an_unavailable_summary_is_stated_and_never_invented() {
24812        let mut f = summary_fixture();
24813        std::fs::write(&f.reply, "no title line here").unwrap();
24814        let m = posted(&mut f).await;
24815        assert!(
24816            m.body
24817                .contains("No description of what this change does could be generated"),
24818            "{}",
24819            m.body
24820        );
24821        assert!(m.body.contains("internal reports remain in local records"));
24822        assert!(f.runner.state.change_summary.is_none());
24823        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24824        // A preview asks nobody and claims nothing.
24825        let winner = f.runner.state.candidates[0].clone();
24826        let preview = f
24827            .runner
24828            .guarded_pr_message(&winner, None, false)
24829            .await
24830            .unwrap()
24831            .unwrap();
24832        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24833    }
24834
24835    #[test]
24836    fn pr_message_review_single_commit_uses_its_subject() {
24837        let state = review_state(&["feat(nats): per-role user"]);
24838        let m = pr_message(&state, 'A');
24839        assert_eq!(m.title, "feat(nats): per-role user");
24840        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24841        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24842    }
24843
24844    #[test]
24845    fn pr_message_review_multi_commit_takes_the_oldest() {
24846        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24847        let m = pr_message(&state, 'A');
24848        assert_eq!(m.title, "feat: the change");
24849        for s in ["feat: the change", "fix: typo", "fix: again"] {
24850            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24851        }
24852    }
24853
24854    #[test]
24855    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
24856        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
24857            let mut state = review_state(&[first, "fix: later fixup"]);
24858            state.candidates[0].branch = "機能/ログイン".to_owned();
24859            let m = pr_message(&state, 'A');
24860            assert!(
24861                m.title.starts_with("chore: land candidate A of run"),
24862                "{}",
24863                m.title
24864            );
24865        }
24866    }
24867
24868    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
24869        BranchFacts {
24870            commits: commits
24871                .iter()
24872                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
24873                .collect(),
24874            stat: stat.to_owned(),
24875        }
24876    }
24877
24878    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
24879        let mut r = review_round(true, 0, 1, 1, true, true);
24880        r.round = round;
24881        r.fix = notes.map(|n| FixRecord {
24882            agent: "fixer".to_owned(),
24883            addressed: Vec::new(),
24884            rejected: Vec::new(),
24885            notes: n.to_owned(),
24886            committed: true,
24887            failed: None,
24888            duration_ms: 0,
24889            continuation: None,
24890        });
24891        r
24892    }
24893
24894    #[test]
24895    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
24896        let state = review_state(&["ignored"]);
24897        let f = facts(
24898            &[
24899                (
24900                    "fix(login): resolve PATH on macOS",
24901                    "Login shells skip rc files.",
24902                ),
24903                ("fix: address review", ""),
24904            ],
24905            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
24906        );
24907        let m = pr_message_with(&state, 'A', Some(&f));
24908        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
24909        assert!(
24910            m.body
24911                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
24912            "{}",
24913            m.body
24914        );
24915        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
24916        assert!(m.body.contains("## Diff stat"), "{}", m.body);
24917        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
24918        for banned in [
24919            "Review the work already",
24920            "no task statement",
24921            "Original task",
24922        ] {
24923            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
24924        }
24925        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
24926    }
24927
24928    #[test]
24929    fn pr_message_review_truncates_a_huge_first_commit_body() {
24930        let state = review_state(&["ignored"]);
24931        let f = facts(
24932            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
24933            "s",
24934        );
24935        let m = pr_message_with(&state, 'A', Some(&f));
24936        assert!(m.body.len() < 30_000, "{}", m.body.len());
24937        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
24938        assert!(
24939            m.body.contains("- ... 1 more commit(s)"),
24940            "{}",
24941            m.body.len()
24942        );
24943        assert!(m.body.ends_with("magi:candidate-a\n"));
24944    }
24945
24946    #[test]
24947    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
24948        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
24949        assert_eq!(m.title, "feat: x");
24950        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
24951        assert!(!m.body.contains("Diff stat"), "{}", m.body);
24952        assert!(!m.body.contains("no task statement"), "{}", m.body);
24953    }
24954
24955    #[test]
24956    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
24957        let mut state = review_state(&["日本語の件名"]);
24958        state.candidates[0].branch = "fix/macos-login-path".to_owned();
24959        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
24960        state.candidates[0].branch = "機能/ログイン".to_owned();
24961        assert!(
24962            pr_message(&state, 'A')
24963                .title
24964                .starts_with("chore: land candidate A")
24965        );
24966    }
24967
24968    #[test]
24969    fn pr_message_review_fixes_survive_a_clean_final_round() {
24970        let mut state = review_state(&["feat: x"]);
24971        state.reviews = vec![
24972            round_with_notes(1, Some("handled the PATH case")),
24973            round_with_notes(2, None),
24974        ];
24975        let body = pr_message(&state, 'A').body;
24976        assert!(
24977            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
24978            "{body}"
24979        );
24980        assert!(body.contains("### Round 1"), "{body}");
24981
24982        state.reviews = vec![
24983            round_with_notes(1, Some("first fix")),
24984            round_with_notes(2, Some("")),
24985            round_with_notes(3, Some("second fix")),
24986            round_with_notes(4, None),
24987        ];
24988        let body = pr_message(&state, 'A').body;
24989        assert!(
24990            body.contains("### Round 1") && !body.contains("first fix"),
24991            "{body}"
24992        );
24993        assert!(
24994            body.contains("### Round 3") && !body.contains("second fix"),
24995            "{body}"
24996        );
24997        assert!(body.contains("### Round 2"), "{body}");
24998    }
24999
25000    const FINAL: &str = "abcdef1234567890";
25001
25002    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
25003        let mut r = round_with_notes(round, None);
25004        r.verified_head = verified.map(str::to_owned);
25005        r
25006    }
25007
25008    fn ok_gate(state: &mut RunState, head: Option<&str>) {
25009        state.gate = vec![CommandOutcome {
25010            command: "gate".to_owned(),
25011            code: Some(0),
25012            output_tail: String::new(),
25013            duration_ms: 0,
25014            resource_blocked: false,
25015            ..Default::default()
25016        }];
25017        state.gate_ran = true;
25018        state.gate_head = head.map(str::to_owned);
25019    }
25020
25021    fn body_at(state: &RunState) -> String {
25022        pr_message_raw(
25023            state,
25024            'A',
25025            None,
25026            crate::pr_outcome::FinalHead::At(FINAL),
25027            ChangeNote::NotAsked,
25028        )
25029        .body
25030    }
25031
25032    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
25033
25034    #[test]
25035    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
25036        let mut state = review_state(&["feat: x"]);
25037        state.reviews = vec![
25038            round_with_notes(1, Some(SANDBOXED)),
25039            passing_round(2, Some(FINAL)),
25040        ];
25041        ok_gate(&mut state, Some(FINAL));
25042        let body = body_at(&state);
25043        assert!(!body.contains("Handled the PATH case."), "{body}");
25044        assert!(!body.contains("could not commit"), "{body}");
25045        assert!(!body.contains("could not run"), "{body}");
25046        assert!(
25047            body.contains("The fix is committed on the branch"),
25048            "{body}"
25049        );
25050        assert!(!body.contains("sandbox"), "{body}");
25051        assert!(
25052            body.contains("Tests (`verify.e2e`): passed on the final commit"),
25053            "{body}"
25054        );
25055        assert!(
25056            body.contains("Gate (`verify.gate`): passed on the final commit"),
25057            "{body}"
25058        );
25059        // The raw report is untouched in the record.
25060        assert!(
25061            state.reviews[0]
25062                .fix
25063                .as_ref()
25064                .unwrap()
25065                .notes
25066                .contains("could not commit")
25067        );
25068    }
25069
25070    #[test]
25071    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
25072        let mut state = review_state(&["feat: x"]);
25073        let mut r1 = round_with_notes(1, Some(SANDBOXED));
25074        r1.fix.as_mut().unwrap().committed = false;
25075        let mut r2 = passing_round(2, Some(FINAL));
25076        r2.e2e[0].code = Some(1);
25077        state.reviews = vec![r1, r2];
25078        let body = body_at(&state);
25079        assert!(!body.contains("could not commit"), "{body}");
25080        assert!(!body.contains("could not run"), "{body}");
25081        assert!(body.contains("This round produced no commit"), "{body}");
25082        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
25083        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
25084        assert!(!body.contains("passed"), "{body}");
25085    }
25086
25087    #[test]
25088    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
25089        let mut state = review_state(&["feat: x"]);
25090        state.reviews = vec![
25091            round_with_notes(1, Some(SANDBOXED)),
25092            passing_round(2, Some("0123456789abcdef")),
25093        ];
25094        ok_gate(&mut state, Some("0123456789abcdef"));
25095        let body = body_at(&state);
25096        assert!(!body.contains("HTTP tests could not run"), "{body}");
25097        // The commit claim is still settled by the structured record.
25098        assert!(!body.contains("could not commit"), "{body}");
25099        assert!(
25100            body.contains("passed on an earlier commit (`0123456`)"),
25101            "{body}"
25102        );
25103        assert!(!body.contains("passed on the final commit"), "{body}");
25104
25105        // A gate recorded before `gate_head` existed is "not recorded".
25106        ok_gate(&mut state, None);
25107        let body = body_at(&state);
25108        assert!(
25109            body.contains("passed on a commit that was not recorded"),
25110            "{body}"
25111        );
25112    }
25113
25114    #[test]
25115    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
25116        let state = state_with_summary(
25117            "add retries to the client",
25118            "TITLE: feat: retries\n\nDid it.",
25119        );
25120        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
25121        assert_eq!(m.title, "feat: retries");
25122        assert!(
25123            m.body.contains("<summary>Original task</summary>"),
25124            "{}",
25125            m.body
25126        );
25127        assert!(!m.body.contains("Commits under review"), "{}", m.body);
25128        assert!(
25129            m.body
25130                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
25131            "{}",
25132            m.body
25133        );
25134    }
25135
25136    #[test]
25137    fn pr_message_review_bounds_a_long_english_subject() {
25138        let long = format!("feat: {}", "word ".repeat(100));
25139        let m = pr_message(&review_state(&[&long]), 'A');
25140        assert!(m.title.starts_with("feat: word"), "{}", m.title);
25141        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25142    }
25143
25144    #[test]
25145    fn pr_message_implementation_run_is_unchanged_by_review_support() {
25146        let state = state_with_summary("add retries\n\ndetails", "- did some things");
25147        let m = pr_message(&state, 'A');
25148        assert_eq!(m.title, "add retries");
25149        assert!(m.body.contains("<summary>Original task</summary>"));
25150        assert!(!m.body.contains("Commits under review"));
25151        assert_eq!(landing_subject_source(&state), state.instruction);
25152    }
25153
25154    #[test]
25155    fn review_run_squash_subject_is_the_change_not_the_prompt() {
25156        let state = review_state(&["feat: the change", "fix: typo"]);
25157        let source = landing_subject_source(&state);
25158        assert_eq!(land::merge_subject("", &source), "feat: the change");
25159        assert_eq!(
25160            land::merge_subject("magi: candidate A (uncommitted work)", &source),
25161            "feat: the change"
25162        );
25163        // An operator's rename still wins.
25164        assert_eq!(
25165            land::merge_subject("feat: renamed by hand", &source),
25166            "feat: renamed by hand"
25167        );
25168        let blank = review_state(&["日本語"]);
25169        assert!(
25170            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
25171        );
25172    }
25173
25174    #[test]
25175    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
25176        let state = review_state(&["feat: the change"]);
25177        let source = landing_subject_source(&state);
25178        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
25179        assert_eq!(
25180            land::merge_subject(landing_title(&state, old), &source),
25181            "feat: the change"
25182        );
25183        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
25184        let task = state_with_summary("add retries", "");
25185        assert_eq!(landing_title(&task, old), old);
25186    }
25187
25188    #[test]
25189    fn pr_message_describes_the_change_not_the_task() {
25190        let state = state_with_summary(
25191            "今回やってほしいこと: results projector を直す",
25192            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
25193        );
25194        let m = pr_message(&state, 'A');
25195        assert_eq!(m.title, "fix(web): batch the runs list reads");
25196        assert!(
25197            m.body.starts_with("## Summary\n\n- reads run.json once"),
25198            "{}",
25199            m.body
25200        );
25201        assert!(!m.body.contains("TITLE:"), "{}", m.body);
25202        let task_at = m.body.find("今回やってほしいこと").unwrap();
25203        let details_at = m.body.find("<details>").unwrap();
25204        assert!(
25205            details_at < task_at,
25206            "the task lives inside <details>: {}",
25207            m.body
25208        );
25209        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
25210        assert!(m.body.contains("magi:candidate-a"));
25211    }
25212
25213    #[test]
25214    fn pr_message_falls_back_to_the_task_without_a_title_line() {
25215        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
25216        let m = pr_message(&state, 'A');
25217        assert_eq!(m.title, "add retries");
25218        assert!(
25219            m.body.contains("## Summary\n\n- did some things"),
25220            "{}",
25221            m.body
25222        );
25223
25224        let none = RunState::new(
25225            PathBuf::from("/repo"),
25226            "main".to_owned(),
25227            "abc1234".to_owned(),
25228            "add retries".to_owned(),
25229            Config::default(),
25230        );
25231        let m = pr_message(&none, 'A');
25232        assert_eq!(m.title, "add retries");
25233        assert!(!m.body.contains("## Summary"), "{}", m.body);
25234    }
25235
25236    #[test]
25237    fn pr_message_refuses_the_candidate_commit_subject() {
25238        for bad in [
25239            "TITLE: magi: candidate A (uncommitted work)",
25240            "TITLE: chore: stuff (uncommitted work)",
25241            "TITLE:   ",
25242        ] {
25243            let state = state_with_summary("add retries", bad);
25244            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
25245        }
25246    }
25247
25248    #[test]
25249    fn pr_message_bounds_a_very_long_task_and_title() {
25250        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
25251        let state = state_with_summary(&long, "- nothing");
25252        let m = pr_message(&state, 'A');
25253        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25254        assert!(!m.title.contains('\n'));
25255
25256        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
25257        let m = pr_message(&state, 'A');
25258        assert!(m.title.starts_with("feat: "));
25259        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25260        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
25261    }
25262
25263    fn long_title_of(instruction: &str) -> String {
25264        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
25265    }
25266
25267    #[test]
25268    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
25269        let first = "Make the landing path keep a readable title for long tasks";
25270        let line = format!(
25271            "{first}. {}",
25272            "And then keep going with more words ".repeat(20)
25273        );
25274        let t = long_title_of(&line);
25275        assert_eq!(t, first);
25276        assert!(!t.starts_with("chore: land"));
25277    }
25278
25279    #[test]
25280    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
25281        let line = "word ".repeat(200);
25282        let t = long_title_of(&line);
25283        assert!(t.ends_with("word..."), "{t}");
25284        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
25285    }
25286
25287    #[test]
25288    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
25289        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
25290            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
25291        }
25292    }
25293
25294    #[test]
25295    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
25296        let mut state = state_with_summary("再試行を追加する", "- nothing");
25297        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
25298        state.config.graph.github_language = "ja".into();
25299        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
25300    }
25301
25302    #[test]
25303    fn pr_message_title_limit_is_exact() {
25304        let at = "a".repeat(PR_TITLE_MAX);
25305        assert_eq!(long_title_of(&at), at);
25306        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
25307        assert!(over.ends_with("..."), "{over}");
25308        assert_eq!(over.chars().count(), PR_TITLE_MAX);
25309    }
25310
25311    #[test]
25312    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
25313        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
25314        let t = long_title_of(&line);
25315        assert!(t.ends_with("..."), "{t}");
25316        assert!(t.is_ascii(), "{t}");
25317    }
25318
25319    #[test]
25320    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
25321        let line = format!(
25322            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
25323            "plus more filler words ".repeat(20)
25324        );
25325        let t = long_title_of(&line);
25326        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
25327    }
25328
25329    #[test]
25330    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
25331        let line = format!("\n\n# {}", "title words ".repeat(40));
25332        let state = state_with_summary(&line, "- nothing");
25333        let m = pr_message(&state, 'A');
25334        assert!(m.title.starts_with("title words"), "{}", m.title);
25335        assert_eq!(
25336            land::merge_subject(&m.title, &landing_subject_source(&state)),
25337            m.title
25338        );
25339        // An operator's rename wins untouched.
25340        assert_eq!(
25341            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
25342            "feat: renamed by hand"
25343        );
25344    }
25345
25346    #[tokio::test]
25347    async fn github_text_rewrite_is_bounded_and_falls_back() {
25348        crate::run::pin_test_home();
25349        for (reply, accepted) in [
25350            (
25351                "TITLE: fix: retries\nAdd retries for failed requests.",
25352                true,
25353            ),
25354            (
25355                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
25356                false,
25357            ),
25358            (
25359                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
25360                true,
25361            ),
25362            (
25363                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
25364                true,
25365            ),
25366            (
25367                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
25368                true,
25369            ),
25370            (
25371                "TITLE: fix: retries\n日本語の説明です。 token=secret",
25372                false,
25373            ),
25374            ("TITLE: fix: retries\n", false),
25375        ] {
25376            let dir = tempfile::tempdir().unwrap();
25377            let mut runner = runner_at(RunStatus::Gating);
25378            runner.state = state_with_summary(
25379                "add retries",
25380                "TITLE: fix: retries\n日本語の説明を書きます。",
25381            );
25382            runner.state.repo = dir.path().to_owned();
25383            runner.state.candidates[0].worktree = dir.path().to_owned();
25384            let mut author = spec("alpha");
25385            author.command = vec![
25386                "sh".into(),
25387                "-c".into(),
25388                "printf '%s' \"$REWRITE_REPLY\"".into(),
25389            ];
25390            author.env.insert("REWRITE_REPLY".into(), reply.into());
25391            runner.state.config.agents = vec![author];
25392            seed_public_summary(&mut runner);
25393            let winner = runner.state.candidates[0].clone();
25394            let first = runner
25395                .guarded_pr_message(&winner, None, true)
25396                .await
25397                .unwrap();
25398            let message = if accepted {
25399                first.expect("a passing rewrite never asks")
25400            } else {
25401                // Withheld: the run parks on a question and posts nothing yet.
25402                assert!(first.is_none());
25403                assert!(runner.state.parked);
25404                let store = ask::Questions::open();
25405                let asked: Vec<_> = store
25406                    .list()
25407                    .into_iter()
25408                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25409                    .collect();
25410                assert_eq!(asked.len(), 1);
25411                assert!(!asked[0].detail.contains("secret"));
25412                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
25413                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
25414                assert_eq!(
25415                    asked[0]
25416                        .choices
25417                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
25418                    rewrite.is_some()
25419                );
25420                // Silence: the question lapses and the neutral text is used,
25421                // without a second rewrite call or a second question.
25422                store
25423                    .update(&asked[0].id, |q| {
25424                        q.abandon("test");
25425                        Ok(())
25426                    })
25427                    .unwrap();
25428                let again = runner
25429                    .guarded_pr_message(&winner, None, true)
25430                    .await
25431                    .unwrap()
25432                    .expect("an abandoned question falls back");
25433                let n = store
25434                    .list()
25435                    .into_iter()
25436                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25437                    .count();
25438                assert_eq!(n, 1, "asked once per rejected text");
25439                again
25440            };
25441            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
25442            assert!(!message.body.contains("secret"));
25443            assert!(!message.body.contains("prefix"));
25444            assert!(!message.title.contains("secret"));
25445            assert_eq!(
25446                message.body.contains("Add retries for failed requests."),
25447                accepted
25448            );
25449            assert_eq!(
25450                runner.state.seats["github-text-rewrite"].turns, 1,
25451                "only one rewrite invocation"
25452            );
25453            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
25454            if accepted {
25455                assert!(runner.state.github_text.is_none());
25456                assert!(!runner.state.parked);
25457                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
25458                assert!(message.body.contains("## Final verification"));
25459                assert!(message.body.contains("Evidence: final diff"));
25460                assert!(
25461                    message
25462                        .body
25463                        .contains(&format!("magi:run/{}", runner.state.id))
25464                );
25465            }
25466            if !accepted {
25467                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25468                assert!(
25469                    message
25470                        .body
25471                        .contains(&format!("magi:run/{}", runner.state.id))
25472                );
25473            }
25474        }
25475    }
25476
25477    fn scripted(id: &str, reply: &str) -> AgentSpec {
25478        let mut a = spec(id);
25479        a.command = vec![
25480            "sh".into(),
25481            "-c".into(),
25482            "printf '%s' \"$REWRITE_REPLY\"".into(),
25483        ];
25484        a.env.insert("REWRITE_REPLY".into(), reply.into());
25485        a
25486    }
25487
25488    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
25489    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
25490
25491    /// Gate tests inject generated public output, not internal reports.
25492    fn seed_public_summary(runner: &mut Runner) {
25493        let repo = &runner.state.repo;
25494        let g = |args: &[&str]| {
25495            let out = std::process::Command::new("git")
25496                .args(args)
25497                .current_dir(repo)
25498                .quiet()
25499                .output()
25500                .unwrap();
25501            assert!(out.status.success(), "git {args:?}");
25502            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25503        };
25504        g(&["init", "-q", "-b", "main"]);
25505        g(&[
25506            "-c",
25507            "user.name=Test",
25508            "-c",
25509            "user.email=test@example.invalid",
25510            "commit",
25511            "-q",
25512            "--allow-empty",
25513            "-m",
25514            "feat: fixture",
25515        ]);
25516        let head = g(&["rev-parse", "HEAD"]);
25517        g(&["update-ref", "refs/remotes/origin/main", &head]);
25518        let evidence = crate::pr_outcome::summary_evidence(
25519            &runner.state,
25520            crate::pr_outcome::FinalHead::At(&head),
25521        );
25522        let generated = &runner.state.candidates[0].summary;
25523        runner.state.change_summary = Some(crate::run::ChangeSummary {
25524            base: head.clone(),
25525            head,
25526            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
25527            title: summary_title(generated).unwrap(),
25528            body: summary_without_title(generated),
25529        });
25530    }
25531
25532    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
25533        let mut runner = runner_at(RunStatus::Gating);
25534        runner.state = state_with_summary("add retries", JA_SUMMARY);
25535        if review_only {
25536            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
25537        }
25538        runner.state.repo = dir.to_owned();
25539        runner.state.candidates[0].worktree = dir.to_owned();
25540        runner.state.config.agents = agents;
25541        seed_public_summary(&mut runner);
25542        runner
25543    }
25544
25545    fn gate_questions(runner: &Runner) -> usize {
25546        ask::Questions::open()
25547            .list()
25548            .into_iter()
25549            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25550            .count()
25551    }
25552
25553    #[tokio::test]
25554    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
25555        crate::run::pin_test_home();
25556        let dir = tempfile::tempdir().unwrap();
25557        let mut runner = rewrite_runner(
25558            dir.path(),
25559            true,
25560            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25561        );
25562        runner.state.config.roles.language_judge =
25563            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
25564        let winner = runner.state.candidates[0].clone();
25565        let msg = runner
25566            .guarded_pr_message(&winner, None, true)
25567            .await
25568            .unwrap()
25569            .expect("an English rewrite posts without asking");
25570        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
25571        assert!(msg.body.contains("<details>kept</details>"));
25572        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
25573        assert_eq!(gate_questions(&runner), 0);
25574        assert!(runner.state.github_text.is_none());
25575        assert!(!runner.state.seats.contains_key("impl-A"));
25576        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25577    }
25578
25579    #[tokio::test]
25580    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
25581        crate::run::pin_test_home();
25582        let dir = tempfile::tempdir().unwrap();
25583        let mut runner = rewrite_runner(
25584            dir.path(),
25585            false,
25586            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25587        );
25588        runner.state.config.roles.language_judge =
25589            Some(crate::config::AgentChoice::One("beta".into()));
25590        runner.state.seats.insert(
25591            "impl-A".into(),
25592            SeatState::new("impl-A", "alpha", runner.state.seed),
25593        );
25594        let winner = runner.state.candidates[0].clone();
25595        let msg = runner
25596            .guarded_pr_message(&winner, None, true)
25597            .await
25598            .unwrap()
25599            .expect("rewritten");
25600        assert!(msg.body.contains("<details>kept</details>"));
25601        assert_eq!(runner.state.seats["impl-A"].turns, 0);
25602        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25603        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25604    }
25605
25606    #[tokio::test]
25607    async fn rewrite_reuses_a_resumable_implementer_session() {
25608        crate::run::pin_test_home();
25609        let dir = tempfile::tempdir().unwrap();
25610        let mut runner = rewrite_runner(
25611            dir.path(),
25612            false,
25613            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
25614        );
25615        runner.state.config.roles.language_judge =
25616            Some(crate::config::AgentChoice::One("beta".into()));
25617        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25618        seat.turns = 1;
25619        runner.state.seats.insert("impl-A".into(), seat);
25620        let winner = runner.state.candidates[0].clone();
25621        runner
25622            .guarded_pr_message(&winner, None, true)
25623            .await
25624            .unwrap()
25625            .expect("rewritten");
25626        assert_eq!(runner.state.seats["impl-A"].turns, 2);
25627        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
25628    }
25629
25630    #[tokio::test]
25631    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
25632        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
25633        // session, was out of quota, and nothing else was asked.
25634        crate::run::pin_test_home();
25635        let dir = tempfile::tempdir().unwrap();
25636        let mut exhausted = spec("alpha");
25637        exhausted.command = vec!["false".into()];
25638        let mut runner = rewrite_runner(
25639            dir.path(),
25640            false,
25641            vec![exhausted, scripted("beta", EN_REWRITE)],
25642        );
25643        // The implementer's own agent is in the role too: it is not asked twice.
25644        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25645            "alpha".into(),
25646            "beta".into(),
25647        ]));
25648        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25649        seat.turns = 1;
25650        runner.state.seats.insert("impl-A".into(), seat);
25651        let winner = runner.state.candidates[0].clone();
25652        let msg = runner
25653            .guarded_pr_message(&winner, None, true)
25654            .await
25655            .unwrap()
25656            .expect("the role rewrites after the implementer fails");
25657        assert!(msg.body.contains("`src/net.rs`"));
25658        assert_eq!(
25659            runner.state.seats["impl-A"].turns, 2,
25660            "the implementer was tried once"
25661        );
25662        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25663        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25664    }
25665
25666    #[tokio::test]
25667    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
25668        crate::run::pin_test_home();
25669        let dir = tempfile::tempdir().unwrap();
25670        let mut broken = spec("bad");
25671        broken.command = vec!["false".into()];
25672        let mut runner = rewrite_runner(
25673            dir.path(),
25674            true,
25675            vec![
25676                broken,
25677                scripted("noformat", "Add retries."),
25678                scripted("good", EN_REWRITE),
25679            ],
25680        );
25681        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25682            "bad".into(),
25683            "noformat".into(),
25684            "good".into(),
25685        ]));
25686        let winner = runner.state.candidates[0].clone();
25687        let msg = runner
25688            .guarded_pr_message(&winner, None, true)
25689            .await
25690            .unwrap()
25691            .expect("the third agent rewrites");
25692        assert!(msg.body.contains("`src/net.rs`"));
25693        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25694        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25695    }
25696
25697    #[tokio::test]
25698    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25699        crate::run::pin_test_home();
25700        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25701        for (agents, role, saved) in [
25702            (
25703                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25704                Some("beta"),
25705                true,
25706            ),
25707            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25708            (Vec::new(), None, false),
25709        ] {
25710            let dir = tempfile::tempdir().unwrap();
25711            let mut runner = rewrite_runner(dir.path(), true, agents);
25712            runner.state.config.roles.language_judge =
25713                role.map(|r| crate::config::AgentChoice::One(r.into()));
25714            let winner = runner.state.candidates[0].clone();
25715            let first = runner
25716                .guarded_pr_message(&winner, None, true)
25717                .await
25718                .unwrap();
25719            assert!(first.is_none(), "withheld text parks the run");
25720            assert!(runner.state.parked);
25721            assert_eq!(gate_questions(&runner), 1);
25722            let g = runner.state.github_text.as_ref().unwrap();
25723            assert_eq!(g.rewrite.is_some(), saved);
25724            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25725        }
25726    }
25727
25728    #[tokio::test]
25729    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25730        crate::run::pin_test_home();
25731        let dir = tempfile::tempdir().unwrap();
25732        let mut runner = runner_at(RunStatus::Gating);
25733        runner.state =
25734            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25735        runner.state.repo = dir.path().to_owned();
25736        runner.state.candidates[0].worktree = dir.path().to_owned();
25737        let mut author = spec("alpha");
25738        author.command = vec![
25739            "sh".into(),
25740            "-c".into(),
25741            "printf '%s' \"$REWRITE_REPLY\"".into(),
25742        ];
25743        author.env.insert(
25744            "REWRITE_REPLY".into(),
25745            format!(
25746                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25747                "English sentence. ".repeat(600)
25748            ),
25749        );
25750        runner.state.config.agents = vec![author];
25751        seed_public_summary(&mut runner);
25752        let winner = runner.state.candidates[0].clone();
25753        assert!(
25754            runner
25755                .guarded_pr_message(&winner, None, true)
25756                .await
25757                .unwrap()
25758                .is_none()
25759        );
25760        let record = runner.state.github_text.clone().unwrap();
25761        let rewrite = record.rewrite.clone().unwrap();
25762        assert_eq!(rewrite.failed, ["body-language"]);
25763        assert!(
25764            rewrite
25765                .body
25766                .ends_with(&format!("magi:run/{}", runner.state.id))
25767        );
25768        let store = ask::Questions::open();
25769        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25770        assert!(
25771            q.choices
25772                .contains(&crate::github_text::USE_REWRITE.to_owned())
25773        );
25774        for label in [
25775            "ORIGINAL",
25776            "FALLBACK",
25777            "REWRITE",
25778            "Rules still failed: body-language",
25779            "truncated",
25780        ] {
25781            assert!(q.detail.contains(label), "{label}");
25782        }
25783        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25784            &runner.state,
25785            &crate::github_text::artifact_name(&record.fingerprint),
25786        ))
25787        .unwrap();
25788        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25789        // Restart from serialized state, then retry after a bad owner title.
25790        runner.state =
25791            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25792        store
25793            .update(&q.id, |q| {
25794                q.say("まだ日本語")?;
25795                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25796            })
25797            .unwrap();
25798        assert!(
25799            runner
25800                .guarded_pr_message(&winner, None, true)
25801                .await
25802                .unwrap()
25803                .is_none()
25804        );
25805        let retry = runner.state.github_text.as_ref().unwrap();
25806        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25807        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25808        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25809        assert!(
25810            q.posting_comparison
25811                .as_ref()
25812                .unwrap()
25813                .matches_detail(&q.detail)
25814        );
25815        store
25816            .update(&q.id, |q| {
25817                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25818            })
25819            .unwrap();
25820        let message = runner
25821            .guarded_pr_message(&winner, None, true)
25822            .await
25823            .unwrap()
25824            .unwrap();
25825        assert_eq!(message.title, rewrite.title);
25826        assert_eq!(message.body, rewrite.body);
25827        assert_eq!(
25828            runner.state.github_text.as_ref().unwrap().choice,
25829            Some(GithubTextChoice::Rewrite)
25830        );
25831        let again = runner
25832            .guarded_pr_message(&winner, None, true)
25833            .await
25834            .unwrap()
25835            .unwrap();
25836        assert_eq!(again.title, message.title);
25837        assert_eq!(again.body, message.body);
25838        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25839        assert!(
25840            !runner
25841                .state
25842                .events
25843                .iter()
25844                .any(|e| e.message.contains(&rewrite.title)
25845                    || e.message.contains("English sentence."))
25846        );
25847    }
25848
25849    #[tokio::test]
25850    async fn historical_posting_reply_never_expires_into_fallback() {
25851        crate::run::pin_test_home();
25852        let dir = tempfile::tempdir().unwrap();
25853        let mut runner = runner_at(RunStatus::Gating);
25854        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25855        runner.state.repo = dir.path().to_owned();
25856        runner.state.candidates[0].worktree = dir.path().to_owned();
25857        seed_public_summary(&mut runner);
25858        let winner = runner.state.candidates[0].clone();
25859        assert!(
25860            runner
25861                .guarded_pr_message(&winner, None, true)
25862                .await
25863                .unwrap()
25864                .is_none()
25865        );
25866        let id = runner
25867            .state
25868            .github_text
25869            .as_ref()
25870            .unwrap()
25871            .question
25872            .clone()
25873            .unwrap();
25874        let store = ask::Questions::open();
25875        let mut q = store.get(&id).unwrap();
25876        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
25877        q.answer(ask::Answer::Choice(
25878            crate::github_text::POST_ORIGINAL.into(),
25879        ))
25880        .unwrap();
25881        q.answer_delivered = true;
25882        store.put(&mut q).unwrap();
25883        let source = std::fs::read(store.path_of(&id)).unwrap();
25884        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
25885        std::fs::create_dir_all(&migration).unwrap();
25886        std::fs::write(
25887            migration.join("state.json"),
25888            serde_json::to_vec(&serde_json::json!({
25889                "schema": 1, "sources": [id], "pending": [id]
25890            }))
25891            .unwrap(),
25892        )
25893        .unwrap();
25894        for _ in 0..2 {
25895            assert!(
25896                runner
25897                    .guarded_pr_message(&winner, None, true)
25898                    .await
25899                    .unwrap()
25900                    .is_none()
25901            );
25902            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25903            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25904        }
25905        let home = crate::run::home();
25906        crate::task_chat::sweep(
25907            &crate::queue::Queue::at(home.join("queue")),
25908            &crate::talk::Talks::at(home.join("talks")),
25909            &store,
25910            &home,
25911        );
25912        let outbox = crate::task_inquiry::Outbox::at(&home);
25913        outbox
25914            .update_decision(&id, |d| {
25915                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
25916                d.source_answer_at = q.answered_at;
25917                Ok(true)
25918            })
25919            .unwrap();
25920        outbox
25921            .settle(
25922                &id,
25923                "owner-chat",
25924                "Owner confirms no publication remains necessary",
25925                None,
25926            )
25927            .unwrap();
25928        assert!(
25929            runner
25930                .guarded_pr_message(&winner, None, true)
25931                .await
25932                .unwrap()
25933                .is_none()
25934        );
25935        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25936        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25937    }
25938
25939    #[tokio::test]
25940    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
25941        crate::run::pin_test_home();
25942        let dir = tempfile::tempdir().unwrap();
25943        let mut runner = runner_at(RunStatus::Gating);
25944        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25945        runner.state.repo = dir.path().to_owned();
25946        runner.state.candidates[0].worktree = dir.path().to_owned();
25947        seed_public_summary(&mut runner);
25948        let winner = runner.state.candidates[0].clone();
25949        assert!(
25950            runner
25951                .guarded_pr_message(&winner, None, true)
25952                .await
25953                .unwrap()
25954                .is_none()
25955        );
25956        let record = runner.state.github_text.as_ref().unwrap();
25957        assert!(record.rewrite.is_none());
25958        // Records written before the additive field deserialize with no rewrite.
25959        let mut old = serde_json::to_value(record).unwrap();
25960        old.as_object_mut().unwrap().remove("rewrite");
25961        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
25962        assert!(old.rewrite.is_none());
25963        let id = record.question.clone().unwrap();
25964        ask::Questions::open()
25965            .update(&id, |q| {
25966                q.choices.push(crate::github_text::USE_REWRITE.into());
25967                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25968            })
25969            .unwrap();
25970        let message = runner
25971            .guarded_pr_message(&winner, None, true)
25972            .await
25973            .unwrap()
25974            .unwrap();
25975        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25976        assert_eq!(
25977            runner.state.github_text.as_ref().unwrap().choice,
25978            Some(GithubTextChoice::Fallback)
25979        );
25980    }
25981
25982    #[tokio::test]
25983    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
25984        crate::run::pin_test_home();
25985        let dir = tempfile::tempdir().unwrap();
25986        let mut runner = runner_at(RunStatus::Gating);
25987        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
25988        runner.state.repo = dir.path().to_owned();
25989        runner.state.candidates[0].worktree = dir.path().to_owned();
25990        seed_public_summary(&mut runner);
25991        let winner = runner.state.candidates[0].clone();
25992        assert!(
25993            runner
25994                .guarded_pr_message(&winner, None, true)
25995                .await
25996                .unwrap()
25997                .is_none()
25998        );
25999        let store = ask::Questions::open();
26000        let find = |run: &str| {
26001            store
26002                .list()
26003                .into_iter()
26004                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
26005                .unwrap()
26006        };
26007        let run = runner.state.id.clone();
26008        let q = find(&run);
26009        let fp = runner
26010            .state
26011            .github_text
26012            .as_ref()
26013            .unwrap()
26014            .fingerprint
26015            .clone();
26016        let name = crate::github_text::artifact_name(&fp);
26017        let path = crate::run::artifact_path(&runner.state, &name);
26018        assert!(q.detail.contains(&path.display().to_string()));
26019        assert!(q.detail.contains("title-language: title"));
26020        let saved = std::fs::read_to_string(&path).expect("artifact written");
26021        assert!(saved.contains("日本語のタイトル"));
26022        assert!(q.cwd.is_none());
26023        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
26024        // A bad replacement is refused and asked about once more.
26025        let say = |id: &str, text: &str, choice: &str| {
26026            store
26027                .update(id, |q| {
26028                    q.thread.push(ask::Turn {
26029                        who: ask::Who::Operator,
26030                        body: text.to_owned(),
26031                        at: jiff::Timestamp::now(),
26032                        note: None,
26033                    });
26034                    q.answer(ask::Answer::Choice(choice.to_owned()))
26035                })
26036                .unwrap();
26037        };
26038        say(&q.id, "まだ日本語", "use my text");
26039        assert!(
26040            runner
26041                .guarded_pr_message(&winner, None, true)
26042                .await
26043                .unwrap()
26044                .is_none()
26045        );
26046        let second = find(&run);
26047        assert_ne!(second.id, q.id);
26048        assert!(second.detail.contains("did not pass"));
26049        // The retry still compares the original text; the rejected
26050        // replacement is named by category only.
26051        assert!(second.detail.contains("日本語のタイトル"));
26052        assert!(!second.detail.contains("まだ日本語"));
26053        assert!(second.detail.contains(&path.display().to_string()));
26054        say(&second.id, "fix: retry failed requests", "use my text");
26055        let message = runner
26056            .guarded_pr_message(&winner, None, true)
26057            .await
26058            .unwrap()
26059            .expect("a vetted replacement is posted");
26060        assert_eq!(message.title, "fix: retry failed requests");
26061        assert_eq!(
26062            runner
26063                .state
26064                .github_text
26065                .as_ref()
26066                .unwrap()
26067                .chosen_title
26068                .as_deref(),
26069            Some("fix: retry failed requests")
26070        );
26071        assert!(runner.state.github_text.as_ref().unwrap().resolved);
26072        // Resumed again: the saved decision is applied, nothing is re-asked.
26073        let again = runner
26074            .guarded_pr_message(&winner, None, true)
26075            .await
26076            .unwrap()
26077            .unwrap();
26078        assert_eq!(again.title, message.title);
26079        assert_eq!(
26080            store
26081                .list()
26082                .into_iter()
26083                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
26084                .count(),
26085            2
26086        );
26087    }
26088
26089    #[test]
26090    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
26091        // What magi itself writes stays English under any configured language,
26092        // so a future localisation of these headings fails here. (The agents'
26093        // own text is also checked by the posting gate.)
26094        let mut state = state_with_summary(
26095            "add retries",
26096            "TITLE: fix(web): batch reads\n- reads run.json once",
26097        );
26098        state.config.graph.language = "ja".to_owned();
26099        let m = pr_message(&state, 'A');
26100        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
26101        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
26102
26103        // The task is the operator's own text: it goes in untouched, and the
26104        // fallback title (no summary) may be in its language too.
26105        let task = "今回やってほしいこと: results projector を直す";
26106        let mut state = state_with_summary(task, "- no title line");
26107        state.config.graph.language = "ja".to_owned();
26108        let m = pr_message(&state, 'A');
26109        assert_eq!(
26110            m.title,
26111            format!("chore: land candidate A of run {}", state.id)
26112        );
26113        assert!(
26114            m.body.contains(&format!(
26115                "<summary>Original task</summary>\n\n{task}\n\n</details>"
26116            )),
26117            "{}",
26118            m.body
26119        );
26120    }
26121
26122    #[test]
26123    fn pr_message_scrubs_home_paths_and_addresses() {
26124        let state = state_with_summary(
26125            "fix it in /Users/someone/src/x",
26126            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
26127        );
26128        let m = pr_message(&state, 'A');
26129        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
26130            assert!(!m.body.contains(leak), "{}", m.body);
26131        }
26132        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
26133    }
26134
26135    #[test]
26136    fn pr_message_survives_a_task_that_closes_details() {
26137        let state = state_with_summary("a </details> b", "TITLE: fix: x");
26138        let m = pr_message(&state, 'A');
26139        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
26140    }
26141
26142    #[test]
26143    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
26144        let cmd = manual_merge_command(
26145            MergeStyle::Squash,
26146            Path::new("/repo"),
26147            "b",
26148            "fix: \"quoted\" $(x) `y`\n\nbody",
26149        );
26150        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
26151    }
26152
26153    #[test]
26154    fn manual_merge_command_matches_the_configured_style() {
26155        let repo = Path::new("/repo");
26156        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
26157
26158        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
26159        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
26160
26161        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
26162        assert_eq!(
26163            squash,
26164            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
26165             \"Merge magi run 0832 (candidate A)\""
26166        );
26167
26168        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
26169        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
26170    }
26171
26172    #[test]
26173    fn a_nudge_gets_a_quarter_of_the_budget() {
26174        // The judge and implement budgets magi ships with.
26175        assert_eq!(retry_budget(secs(1200), true), secs(300));
26176        assert_eq!(retry_budget(secs(3600), true), secs(900));
26177    }
26178
26179    #[test]
26180    fn a_resent_prompt_keeps_the_whole_budget() {
26181        // The seat kept no context, so the retry is the original job again and
26182        // shortening it would only guarantee a second failure.
26183        assert_eq!(retry_budget(secs(1200), false), secs(1200));
26184        assert_eq!(retry_budget(secs(60), false), secs(60));
26185    }
26186
26187    #[test]
26188    fn the_floor_never_exceeds_the_original_budget() {
26189        // A short configured timeout must not be *raised* by the floor: the
26190        // operator asked for a bound, and a retry may not outlast the attempt
26191        // it is retrying.
26192        assert_eq!(retry_budget(secs(60), true), secs(60));
26193        assert_eq!(retry_budget(secs(480), true), secs(120));
26194        assert_eq!(retry_budget(secs(0), true), secs(0));
26195    }
26196
26197    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
26198        agent::CommandEvidence {
26199            id: "item1".to_owned(),
26200            description: "cargo test".to_owned(),
26201            exit_code,
26202            result_summary: String::new(),
26203            source: "codex".to_owned(),
26204        }
26205    }
26206
26207    #[test]
26208    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
26209        // No evidence is not the same fact as unconfirmed evidence: a
26210        // backend with no adapter, or a reply that ran no commands at all,
26211        // must not be misread as carrying a dangling job.
26212        assert!(!has_unconfirmed_command(&[]));
26213    }
26214
26215    fn reply(tool_calls: Option<u64>) -> AgentOutput {
26216        AgentOutput {
26217            text: "## SUMMARY\nImplementation incomplete.".to_owned(),
26218            exit_code: Some(0),
26219            timed_out: false,
26220            duration_ms: 7_000,
26221            artifacts: Vec::new(),
26222            quota: None,
26223            dropped: None,
26224            commands: Vec::new(),
26225            context_tokens: None,
26226            tool_calls,
26227        }
26228    }
26229
26230    #[test]
26231    fn a_clean_reply_with_no_tool_call_on_an_untouched_tree_is_unstarted() {
26232        assert!(ended_unstarted(
26233            &reply(Some(0)),
26234            Some("abc"),
26235            Some("abc"),
26236            Some(true)
26237        ));
26238    }
26239
26240    #[test]
26241    fn unknown_or_real_tool_activity_is_never_unstarted() {
26242        // A backend that reports no tool calls says nothing about them.
26243        assert!(!ended_unstarted(
26244            &reply(None),
26245            Some("abc"),
26246            Some("abc"),
26247            Some(true)
26248        ));
26249        // A seat that looked and then wrote nothing did start.
26250        assert!(!ended_unstarted(
26251            &reply(Some(3)),
26252            Some("abc"),
26253            Some("abc"),
26254            Some(true)
26255        ));
26256        let mut ran = reply(Some(0));
26257        ran.commands.push(evidence(Some(0)));
26258        assert!(!ended_unstarted(&ran, Some("abc"), Some("abc"), Some(true)));
26259    }
26260
26261    #[test]
26262    fn work_in_the_tree_or_an_unreadable_one_is_never_unstarted() {
26263        let out = reply(Some(0));
26264        // A commit, uncommitted edits, and each unknown: none may be replayed.
26265        assert!(!ended_unstarted(&out, Some("abc"), Some("def"), Some(true)));
26266        assert!(!ended_unstarted(
26267            &out,
26268            Some("abc"),
26269            Some("abc"),
26270            Some(false)
26271        ));
26272        assert!(!ended_unstarted(&out, None, Some("abc"), Some(true)));
26273        assert!(!ended_unstarted(&out, Some("abc"), None, Some(true)));
26274        assert!(!ended_unstarted(&out, Some("abc"), Some("abc"), None));
26275        assert!(!ended_unstarted(&out, None, None, Some(true)));
26276    }
26277
26278    #[test]
26279    fn a_failed_or_empty_turn_is_not_an_unstarted_reply() {
26280        let mut failed = reply(Some(0));
26281        failed.exit_code = Some(1);
26282        assert!(!ended_unstarted(
26283            &failed,
26284            Some("abc"),
26285            Some("abc"),
26286            Some(true)
26287        ));
26288        let mut silent = reply(Some(0));
26289        silent.text = String::new();
26290        assert!(!ended_unstarted(
26291            &silent,
26292            Some("abc"),
26293            Some("abc"),
26294            Some(true)
26295        ));
26296    }
26297
26298    #[test]
26299    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
26300        // Deliberately not a check on the exit code's *value*: a fixer
26301        // legitimately runs something that fails mid-iteration before it
26302        // succeeds, and that must never by itself reopen a valid report.
26303        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
26304        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
26305        assert!(!has_unconfirmed_command(&[
26306            evidence(Some(0)),
26307            evidence(Some(101))
26308        ]));
26309    }
26310
26311    #[test]
26312    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
26313        assert!(has_unconfirmed_command(&[
26314            evidence(Some(0)),
26315            evidence(None)
26316        ]));
26317    }
26318
26319    fn evidence_with(
26320        description: &str,
26321        exit_code: Option<i32>,
26322        result_summary: &str,
26323    ) -> agent::CommandEvidence {
26324        agent::CommandEvidence {
26325            id: "item1".to_owned(),
26326            description: description.to_owned(),
26327            exit_code,
26328            result_summary: result_summary.to_owned(),
26329            source: "codex".to_owned(),
26330        }
26331    }
26332
26333    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
26334        format!(
26335            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{commit}","method":"git merge-base --is-ancestor {commit} HEAD","observed":"exit 0; {commit} is on base","passed":true}},{{"id":"c2","kind":"test","target":"{test_name}","method":"cargo test --lib {test_name}","observed":"test result: ok. 1 passed; 0 failed","passed":true}}],"unresolved":[]}}"#
26336        )
26337    }
26338
26339    #[test]
26340    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
26341        let text = valid_noop_summary("b32cfc4", "retry_test");
26342        let claim = verified_noop_claim(true, &[], &text)
26343            .expect("valid structured report with no CommandEvidence must be accepted");
26344        assert!(claim.contains("b32cfc4"), "{claim}");
26345        assert!(claim.contains("retry_test"), "{claim}");
26346    }
26347
26348    #[test]
26349    fn operational_regression_and_legacy_noop_claims_are_rejected() {
26350        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
26351        assert!(verified_noop_claim(true, &[], regression).is_none());
26352        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
26353        assert!(err.contains("single JSON object"), "{err}");
26354
26355        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
26356        assert!(verified_noop_claim(true, &[], legacy).is_none());
26357    }
26358
26359    #[test]
26360    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
26361        // A timeout or a bad exit code reads as the ordinary loss it is,
26362        // whatever the reply's own structured JSON claims.
26363        let text = valid_noop_summary("b32cfc4", "retry_test");
26364        assert!(verified_noop_claim(false, &[], &text).is_none());
26365    }
26366
26367    #[test]
26368    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
26369        let text = valid_noop_summary("b32cfc4", "retry_test");
26370        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
26371        // A matching confirmed command alongside the marker is fine.
26372        assert!(
26373            verified_noop_claim(
26374                true,
26375                &[evidence_with(
26376                    "cargo test --lib retry_test",
26377                    Some(0),
26378                    "1 passed"
26379                )],
26380                &text
26381            )
26382            .is_some()
26383        );
26384    }
26385
26386    #[test]
26387    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
26388     {
26389        let text = valid_noop_summary("b32cfc4", "retry_test");
26390
26391        // Unrelated passing command cannot substantiate a claimed test run.
26392        let err = evaluate_noop_claim(
26393            true,
26394            &[evidence_with("git status", Some(0), "nothing to commit")],
26395            &text,
26396        )
26397        .unwrap_err();
26398        assert!(err.contains("no matching command was recorded"), "{err}");
26399
26400        // Final matching command exited non-zero -> rejected even if an
26401        // unrelated command succeeded afterward.
26402        let err = evaluate_noop_claim(
26403            true,
26404            &[
26405                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
26406                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26407                evidence_with("rg retry_test src", Some(0), "retry_test"),
26408            ],
26409            &text,
26410        )
26411        .unwrap_err();
26412        assert!(err.contains("exited with"), "{err}");
26413
26414        // A different invocation containing the entire method is not a rerun.
26415        let err = evaluate_noop_claim(
26416            true,
26417            &[evidence_with(
26418                "echo 'cargo test --lib retry_test'",
26419                Some(0),
26420                "retry_test",
26421            )],
26422            &text,
26423        )
26424        .unwrap_err();
26425        assert!(err.contains("no matching command was recorded"), "{err}");
26426
26427        // Mid-investigation failure followed by a passing re-run -> accepted!
26428        assert!(
26429            verified_noop_claim(
26430                true,
26431                &[
26432                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26433                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
26434                ],
26435                &text
26436            )
26437            .is_some()
26438        );
26439    }
26440
26441    #[test]
26442    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
26443        let text = valid_noop_summary("b32cfc4", "retry_test");
26444        let method = "cargo test --lib retry_test";
26445        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
26446        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
26447        let failed =
26448            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
26449        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
26450        for output in [empty, ignored, failed] {
26451            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
26452                .unwrap_err();
26453            assert!(err.contains("failure or no passing tests"), "{err}");
26454        }
26455        // Multiple harnesses can legitimately include a filtered-out suite.
26456        let mixed = format!("{passed}\n{empty}");
26457        assert!(
26458            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
26459        );
26460        // A later real rerun of the same command can establish success.
26461        assert!(
26462            verified_noop_claim(
26463                true,
26464                &[
26465                    evidence_with(method, Some(0), empty),
26466                    evidence_with(method, Some(0), passed),
26467                ],
26468                &text,
26469            )
26470            .is_some()
26471        );
26472    }
26473
26474    #[test]
26475    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
26476        let text = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"README includes the expected header","satisfied":true,"evidence":["p1"]}],"checks":[{"id":"p1","kind":"path","target":"README.md","method":"rg expected README.md","observed":"expected header found","passed":true}],"unresolved":[]}"#;
26477        let failed = evidence_with("rg expected README.md", Some(1), "");
26478        let unrelated = evidence_with("cat README.md", Some(0), "README");
26479        let err =
26480            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
26481        assert!(err.contains("exited with"), "{err}");
26482        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
26483        assert!(
26484            evaluate_noop_claim(
26485                true,
26486                &[
26487                    failed,
26488                    evidence_with("rg expected README.md", Some(0), "expected header"),
26489                ],
26490                text,
26491            )
26492            .unwrap()
26493            .is_some()
26494        );
26495    }
26496
26497    #[test]
26498    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
26499        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
26500        assert!(matches!(
26501            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
26502            Ok(None)
26503        ));
26504    }
26505
26506    #[tokio::test]
26507    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
26508        let tmp = tempfile::tempdir().unwrap();
26509        let repo = tmp.path().join("repo");
26510        std::fs::create_dir_all(&repo).unwrap();
26511        let run_git = |args: &[&str]| {
26512            let out = std::process::Command::new("git")
26513                .args(args)
26514                .current_dir(&repo)
26515                .output()
26516                .unwrap();
26517            assert!(out.status.success(), "git {args:?} failed");
26518            String::from_utf8_lossy(&out.stdout).trim().to_owned()
26519        };
26520        run_git(&["init", "-b", "main"]);
26521        run_git(&["config", "user.name", "test"]);
26522        run_git(&["config", "user.email", "test@example.com"]);
26523        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
26524        run_git(&["add", "-A"]);
26525        run_git(&["commit", "-m", "base commit"]);
26526        let base = run_git(&["rev-parse", "HEAD"]);
26527
26528        // Create a commit on a side branch not on `base`.
26529        run_git(&["checkout", "-b", "side"]);
26530        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
26531        run_git(&["add", "-A"]);
26532        run_git(&["commit", "-m", "side commit"]);
26533        let side = run_git(&["rev-parse", "HEAD"]);
26534        run_git(&["checkout", "main"]);
26535
26536        // Valid commit on base + existing path -> Accepted.
26537        let valid = format!(
26538            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"readme exists","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{base}","method":"git merge-base --is-ancestor {base} HEAD","observed":"exit 0; base commit is on main","passed":true}},{{"id":"c2","kind":"path","target":"README.md:1","method":"read README.md","observed":"contains expected greeting","passed":true}}],"unresolved":[]}}"#
26539        );
26540        assert!(matches!(
26541            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
26542            NoopClaimVerdict::Accepted
26543        ));
26544
26545        // Non-existent commit SHA -> Rejected.
26546        let missing_sha = valid.replace(&base, "deadbeef");
26547        assert!(matches!(
26548            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
26549            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
26550        ));
26551
26552        // Commit on unmerged side branch -> Rejected.
26553        let side_sha = valid.replace(&base, &side);
26554        assert!(matches!(
26555            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
26556            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
26557        ));
26558
26559        // Missing file path -> Rejected.
26560        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
26561        assert!(matches!(
26562            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
26563            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
26564        ));
26565    }
26566
26567    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
26568    /// pair, in order, labelled A, B, C, ...
26569    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
26570        runner.state.candidates = shape
26571            .iter()
26572            .enumerate()
26573            .map(|(i, &(empty, verified))| {
26574                let (summary, verified_noop) = match verified {
26575                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
26576                    None => (String::new(), None),
26577                };
26578                Candidate {
26579                    index: i,
26580                    label: (b'A' + i as u8) as char,
26581                    agent: "sonnet".to_owned(),
26582                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
26583                    worktree: PathBuf::from(format!("/wt/{i}")),
26584                    summary,
26585                    stat: String::new(),
26586                    files: 0,
26587                    commits: 0,
26588                    empty,
26589                    failed: None,
26590                    verified_noop,
26591                    duration_ms: 0,
26592                    folded: false,
26593                }
26594            })
26595            .collect();
26596    }
26597
26598    #[test]
26599    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
26600        ask_test_home();
26601        let mut runner = runner_at(RunStatus::Implementing);
26602        let a = valid_noop_summary("b32cfc4", "test_a");
26603        let b = valid_noop_summary("b32cfc4", "test_b");
26604        set_candidates(
26605            &mut runner,
26606            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
26607        );
26608
26609        runner
26610            .after_implement()
26611            .expect("a verified no-op is not an error");
26612
26613        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
26614    }
26615
26616    #[test]
26617    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
26618        ask_test_home();
26619        let mut runner = runner_at(RunStatus::Implementing);
26620        let a = valid_noop_summary("b32cfc4", "test_a");
26621        // Candidate A declares a verified no-op; candidate B simply wrote
26622        // nothing and said nothing about why. One candidate's claim is not
26623        // the whole run's agreement.
26624        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
26625
26626        let err = runner
26627            .after_implement()
26628            .expect_err("an unverified empty candidate must still fail the run");
26629
26630        assert!(
26631            err.to_string().contains("no candidate produced a change"),
26632            "{err}"
26633        );
26634        assert_eq!(runner.state.status, RunStatus::Failed);
26635    }
26636
26637    #[test]
26638    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
26639        ask_test_home();
26640        let mut runner = runner_at(RunStatus::Implementing);
26641        // Simulate a saved incomplete run that stored a legacy/incomplete
26642        // `verified_noop` string before this build's strict contract.
26643        set_candidates(
26644            &mut runner,
26645            &[(
26646                true,
26647                Some(
26648                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
26649                ),
26650            )],
26651        );
26652
26653        let err = runner
26654            .after_implement()
26655            .expect_err("invalid saved noop claim must fail the run");
26656        assert!(
26657            err.to_string().contains("no candidate produced a change"),
26658            "{err}"
26659        );
26660        assert_eq!(runner.state.status, RunStatus::Failed);
26661        assert!(runner.state.candidates[0].verified_noop.is_none());
26662        assert!(runner.state.candidates[0].failed.is_some());
26663        assert!(runner.state.events.iter().any(|e| {
26664            e.message
26665                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
26666        }));
26667    }
26668
26669    #[test]
26670    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
26671        ask_test_home();
26672        let mut runner = runner_at(RunStatus::Implementing);
26673        let a = valid_noop_summary("b32cfc4", "test_a");
26674        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
26675        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
26676
26677        let err = runner
26678            .after_implement()
26679            .expect_err("a failed candidate must never settle as verified no-op");
26680        assert!(err.to_string().contains("no candidate produced a change"));
26681        assert_eq!(runner.state.status, RunStatus::Failed);
26682        assert!(runner.state.candidates[0].verified_noop.is_none());
26683    }
26684
26685    #[test]
26686    fn after_implement_still_fails_an_ordinary_all_empty_run() {
26687        ask_test_home();
26688        let mut runner = runner_at(RunStatus::Implementing);
26689        set_candidates(&mut runner, &[(true, None), (true, None)]);
26690
26691        let err = runner
26692            .after_implement()
26693            .expect_err("no candidate declared anything; this is an ordinary failure");
26694
26695        assert!(
26696            err.to_string().contains("no candidate produced a change"),
26697            "{err}"
26698        );
26699        assert_eq!(runner.state.status, RunStatus::Failed);
26700    }
26701}
26702
26703/// A graft rollback whose restore could not be confirmed (see
26704/// [`Runner::graft`]).
26705#[derive(Debug)]
26706struct GraftRestoreFailed(String);
26707
26708impl std::fmt::Display for GraftRestoreFailed {
26709    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26710        write!(
26711            f,
26712            "could not restore the winner to its pre-graft commit: {}",
26713            self.0
26714        )
26715    }
26716}
26717
26718impl std::error::Error for GraftRestoreFailed {}
26719
26720/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
26721/// not the agent: they never draw on an agent's own timeout, and running out of
26722/// them never reads as an agent failure.
26723#[cfg(test)]
26724mod resource_wait_tests {
26725    use super::*;
26726    use std::collections::BTreeMap;
26727
26728    fn sh(id: &str, script: &str) -> AgentSpec {
26729        AgentSpec {
26730            id: id.to_owned(),
26731            kind: crate::config::AgentKind::Command,
26732            model: None,
26733            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
26734            extra_args: Vec::new(),
26735            env: BTreeMap::new(),
26736            prompt_delivery: None,
26737            max_turn_secs: None,
26738        }
26739    }
26740
26741    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
26742        SeatJob {
26743            seat: SeatState::new("impl-A", &spec.id, 1),
26744            spec,
26745            cwd: dir.to_path_buf(),
26746            prompt: "do it".to_owned(),
26747            timeout,
26748            allow_write: true,
26749            sessions: false,
26750            artifacts: dir.join("art"),
26751            stem: "impl-A".to_owned(),
26752            handover: None,
26753        }
26754    }
26755
26756    fn state(resource_wait_secs: u64) -> RunState {
26757        let mut config = Config::default();
26758        config.graph.timeout_resource_wait = resource_wait_secs;
26759        RunState::new(
26760            PathBuf::from("/repo"),
26761            "main".to_owned(),
26762            "abc1234".to_owned(),
26763            "task".to_owned(),
26764            config,
26765        )
26766    }
26767
26768    fn hold(cache: &Path) -> crate::cache::Guard {
26769        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
26770        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
26771            crate::cache::AcquireOutcome::Acquired(g) => g,
26772            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26773        }
26774    }
26775
26776    async fn run(
26777        jobs: Vec<SeatJob>,
26778        sem: Arc<Semaphore>,
26779        cache: Option<&Path>,
26780        st: &mut RunState,
26781    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26782        let prompts = Prompts::default();
26783        let ctx = WaveCtx {
26784            run: "r",
26785            node: "implement",
26786            prompts: &prompts,
26787            cache,
26788            round: None,
26789            carry_seats: false,
26790            pauses: None,
26791        };
26792        wave(jobs, sem, &ctx, st, 0).await
26793    }
26794
26795    #[tokio::test]
26796    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26797        crate::run::pin_test_home();
26798        let home = crate::run::home();
26799        let tmp = tempfile::tempdir().unwrap();
26800        let repo = tmp.path().join("repo");
26801        let checkout = tmp.path().join("checkout");
26802        std::fs::create_dir(&repo).unwrap();
26803        git::git(&repo, &["init"]).await.unwrap();
26804        git::git(
26805            &repo,
26806            &[
26807                "-c",
26808                "user.name=Fixture",
26809                "-c",
26810                "user.email=fixture@example.invalid",
26811                "commit",
26812                "--allow-empty",
26813                "-m",
26814                "initial",
26815            ],
26816        )
26817        .await
26818        .unwrap();
26819        git::worktree_add_detached(&repo, &checkout, "HEAD")
26820            .await
26821            .unwrap();
26822        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26823        let target_lease = hold(&target);
26824        let shared = tmp.path().join("unrelated");
26825        let _shared_lease = hold(&shared);
26826        let mut st = state(0);
26827        st.repo = repo.clone();
26828        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26829        st.config.verify.e2e = vec![format!(
26830            "CARGO_TARGET_DIR='{}' cargo test",
26831            git::path_arg(&shared)
26832        )];
26833        let config = tmp.path().join("config.toml");
26834        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26835        let prompts = Prompts::default();
26836        let run_id = st.id.clone();
26837        let ctx = WaveCtx {
26838            run: &run_id,
26839            node: "implement",
26840            prompts: &prompts,
26841            cache: None,
26842            round: None,
26843            carry_seats: false,
26844            pauses: None,
26845        };
26846        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26847        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26848        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26849        assert_eq!(results[0].1.turns, 0);
26850        let saved = RunState::load_under(&run_id, &home).unwrap();
26851        let block = saved.resource_block.unwrap();
26852        assert!(matches!(
26853            block.cause,
26854            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
26855                if actual == &target
26856        ));
26857        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
26858        let mut task = crate::queue::Task::new(
26859            "build".into(),
26860            "build".into(),
26861            repo,
26862            crate::queue::Source::Human,
26863        );
26864        task.runs.push(run_id);
26865        task.hold_machine(Some(format!(
26866            "{}{}",
26867            crate::cache::RESOURCE_HOLD,
26868            block.description()
26869        )));
26870        queue.put(&mut task).unwrap();
26871        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
26872        let triage =
26873            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
26874        let pending = triage();
26875        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
26876        assert_eq!(
26877            queue.get(&task.id).unwrap().status,
26878            crate::queue::TaskStatus::Held
26879        );
26880        drop(target_lease);
26881        assert_eq!(triage().resumed, vec![task.id.clone()]);
26882        assert_eq!(
26883            queue.get(&task.id).unwrap().status,
26884            crate::queue::TaskStatus::Queued
26885        );
26886        assert!(crate::cache::in_use(&home, &shared));
26887    }
26888
26889    #[tokio::test]
26890    async fn verification_cache_wait_preserves_the_command_budget() {
26891        crate::run::pin_test_home();
26892        let tmp = tempfile::tempdir().unwrap();
26893        let cache = tmp.path().join("target");
26894        let guard = hold(&cache);
26895        let release = tokio::spawn(async move {
26896            tokio::time::sleep(Duration::from_millis(100)).await;
26897            guard.release();
26898        });
26899        let mut st = state(10);
26900        let budget = Duration::from_millis(50);
26901        let wait = repository_wait(&st, None);
26902        let (outcomes, _) = with_cache_lease(
26903            &mut st,
26904            Some(&cache),
26905            "gate",
26906            "gate",
26907            tmp.path(),
26908            "abc1234",
26909            budget,
26910            "test gate",
26911            &wait,
26912            |_, available| async move {
26913                assert_eq!(
26914                    available, budget,
26915                    "contention must not shorten verification"
26916                );
26917                (Vec::new(), false, Vec::new())
26918            },
26919        )
26920        .await
26921        .unwrap();
26922        release.await.unwrap();
26923        assert!(outcomes.is_empty(), "{outcomes:?}");
26924        assert!(
26925            st.events
26926                .iter()
26927                .any(|event| event.message.contains("waiting for"))
26928        );
26929        assert!(st.resource_wait.is_none());
26930        // The verification body no longer owns the lease after returning.
26931        hold(&cache).release();
26932    }
26933
26934    #[tokio::test]
26935    async fn verification_cache_wait_expires_without_starting_commands() {
26936        crate::run::pin_test_home();
26937        let tmp = tempfile::tempdir().unwrap();
26938        let cache = tmp.path().join("target");
26939        let _held = hold(&cache);
26940        let mut st = state(0);
26941        let wait = repository_wait(&st, None);
26942        let (outcomes, _) = with_cache_lease(
26943            &mut st,
26944            Some(&cache),
26945            "gate",
26946            "gate",
26947            tmp.path(),
26948            "abc1234",
26949            Duration::from_secs(60),
26950            "test gate",
26951            &wait,
26952            |_, _| async { panic!("commands must not start without the cache lease") },
26953        )
26954        .await
26955        .unwrap();
26956        assert_eq!(outcomes.len(), 1);
26957        assert!(outcomes[0].resource_blocked);
26958        assert!(st.resource_wait.is_none());
26959        assert!(matches!(
26960            st.resource_block.unwrap().cause,
26961            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
26962        ));
26963    }
26964
26965    #[tokio::test]
26966    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
26967        crate::run::pin_test_home();
26968        let tmp = tempfile::tempdir().unwrap();
26969        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
26970        let cache = tmp.path().join("cache");
26971        let mut state = state(21600);
26972        let wait = repository_wait(&state, None);
26973        let (outcomes, _) = with_cache_lease(
26974            &mut state,
26975            Some(&cache),
26976            "gate",
26977            "gate",
26978            tmp.path(),
26979            "head",
26980            Duration::from_secs(60),
26981            "gate",
26982            &wait,
26983            |_, _| async { panic!("freshness failure must not start verification") },
26984        )
26985        .await
26986        .unwrap();
26987        assert_eq!(outcomes.len(), 1);
26988        assert!(outcomes[0].resource_blocked);
26989        let block = state.resource_block.unwrap();
26990        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
26991        assert!(!block.description().contains("timed out"));
26992    }
26993
26994    #[tokio::test]
26995    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
26996        crate::run::pin_test_home();
26997        let tmp = tempfile::tempdir().unwrap();
26998        let cache = tmp.path().join("cache");
26999        let _held = hold(&cache);
27000        let mut state = state(21600);
27001        let pause = Pause::new();
27002        let interrupt = Pause::new();
27003        let cause = ParkCause::Operator;
27004        pause.park_for(cause.clone());
27005        let prompts = Prompts::default();
27006        let ctx = WaveCtx {
27007            run: "test",
27008            node: "fix",
27009            prompts: &prompts,
27010            cache: Some(&cache),
27011            round: None,
27012            carry_seats: false,
27013            pauses: Some((&pause, &interrupt)),
27014        };
27015        let result = wave(
27016            vec![job(
27017                sh("writer", "exit 99"),
27018                tmp.path(),
27019                Duration::from_secs(1),
27020            )],
27021            Arc::new(Semaphore::new(1)),
27022            &ctx,
27023            &mut state,
27024            0,
27025        )
27026        .await;
27027        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
27028        assert_eq!(result[0].1.turns, 0);
27029        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27030        assert_eq!(
27031            state.resource_block.unwrap().cause,
27032            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
27033        );
27034        assert!(state.active.is_empty());
27035    }
27036
27037    #[tokio::test]
27038    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
27039        crate::run::pin_test_home();
27040        let tmp = tempfile::tempdir().unwrap();
27041        let cache = tmp.path().join("target-a");
27042        let guard = hold(&cache);
27043        // Held for longer than the agent's whole 1s budget.
27044        tokio::spawn(async move {
27045            tokio::time::sleep(Duration::from_millis(1500)).await;
27046            guard.release();
27047        });
27048        let mut st = state(60);
27049        let results = run(
27050            vec![job(
27051                sh("alpha", "echo ok"),
27052                tmp.path(),
27053                Duration::from_secs(1),
27054            )],
27055            Arc::new(Semaphore::new(1)),
27056            Some(&cache),
27057            &mut st,
27058        )
27059        .await;
27060        assert!(
27061            matches!(results[0].2, AgentOutcome::Ok(_)),
27062            "the wait must not be charged to the agent"
27063        );
27064        assert!(st.resource_block.is_none());
27065        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27066        assert!(st.resource_wait.is_none() && st.active.is_empty());
27067    }
27068
27069    #[tokio::test]
27070    #[cfg(unix)]
27071    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
27072        use std::os::fd::AsRawFd as _;
27073        crate::run::pin_test_home();
27074        let tmp = tempfile::tempdir().unwrap();
27075        crate::git::git(tmp.path(), &["init"]).await.unwrap();
27076        let common = tmp.path().join(".git");
27077        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
27078        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
27079        assert_eq!(
27080            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
27081            0
27082        );
27083        let mut st = state(1);
27084        st.config.coordination = crate::config::test_coordination();
27085        let mut reader = job(
27086            sh("reader", "echo must-not-run"),
27087            tmp.path(),
27088            Duration::from_secs(30),
27089        );
27090        reader.allow_write = false;
27091        let results = run(
27092            vec![reader.clone()],
27093            Arc::new(Semaphore::new(1)),
27094            None,
27095            &mut st,
27096        )
27097        .await;
27098        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27099        assert_eq!(results[0].1.turns, 0);
27100        assert!(FailClass::of(&results[0].2).is_none());
27101        assert_eq!(
27102            st.resource_block.as_ref().unwrap().kind,
27103            "repository coordination"
27104        );
27105        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27106        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27107        drop(external);
27108        let editor = crate::repo_lock::SeatLease::for_checkout(
27109            tmp.path(),
27110            true,
27111            crate::config::test_coordination().as_ref(),
27112        )
27113        .await
27114        .unwrap();
27115        let pause = Pause::new();
27116        let interrupt = Pause::new();
27117        let prompts = Prompts::default();
27118        let ctx = WaveCtx {
27119            run: "r",
27120            node: "review",
27121            prompts: &prompts,
27122            cache: None,
27123            round: None,
27124            carry_seats: false,
27125            pauses: Some((&pause, &interrupt)),
27126        };
27127        let (results, ()) = tokio::join!(
27128            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
27129            async {
27130                tokio::time::sleep(Duration::from_millis(50)).await;
27131                pause.park();
27132            }
27133        );
27134        assert!(
27135            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
27136        );
27137        assert_eq!(results[0].1.turns, 0);
27138        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27139        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27140        drop(editor);
27141    }
27142
27143    #[tokio::test]
27144    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
27145        crate::run::pin_test_home();
27146        let tmp = tempfile::tempdir().unwrap();
27147        let cache = tmp.path().join("target-b");
27148        let _held = hold(&cache);
27149        let mut st = state(1);
27150        let results = run(
27151            vec![job(
27152                sh("alpha", "echo ok"),
27153                tmp.path(),
27154                Duration::from_secs(1),
27155            )],
27156            Arc::new(Semaphore::new(1)),
27157            Some(&cache),
27158            &mut st,
27159        )
27160        .await;
27161        let (_, seat, out) = &results[0];
27162        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
27163        assert!(wave_blocked(&results));
27164        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
27165        assert_eq!(seat.turns, 0, "nothing was asked");
27166        assert!(
27167            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
27168            "no agent was spawned"
27169        );
27170        assert!(FailClass::of(out).is_none(), "not a failure class");
27171        let block = st.resource_block.as_ref().expect("recorded for the resume");
27172        assert_eq!(block.kind, "shared build cache");
27173        assert!(matches!(
27174            block.cause,
27175            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
27176        ));
27177        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27178        assert!(st.active.is_empty());
27179    }
27180
27181    #[tokio::test]
27182    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
27183        crate::run::pin_test_home();
27184        let tmp = tempfile::tempdir().unwrap();
27185        let mut st = state(1);
27186        let results = run(
27187            vec![job(
27188                sh("alpha", "echo ok"),
27189                tmp.path(),
27190                Duration::from_secs(1),
27191            )],
27192            Arc::new(Semaphore::new(0)),
27193            None,
27194            &mut st,
27195        )
27196        .await;
27197        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27198        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
27199        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
27200    }
27201
27202    #[tokio::test]
27203    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
27204        crate::run::pin_test_home();
27205        let tmp = tempfile::tempdir().unwrap();
27206        let mut st = state(60);
27207        let results = run(
27208            vec![job(
27209                sh("alpha", "sleep 30"),
27210                tmp.path(),
27211                Duration::from_secs(1),
27212            )],
27213            Arc::new(Semaphore::new(1)),
27214            None,
27215            &mut st,
27216        )
27217        .await;
27218        let out = &results[0].2;
27219        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
27220        let class = FailClass::of(out).expect("a failure");
27221        assert_eq!(class, FailClass::Timeout);
27222        assert!(should_hand_over(None, &class), "existing handover policy");
27223        assert!(st.resource_block.is_none());
27224    }
27225}
27226
27227/// A fold acts on the record it locked, and on nothing else.
27228#[cfg(test)]
27229mod fold_record_tests {
27230    use super::*;
27231
27232    fn refusal(error: &anyhow::Error) -> Option<&FoldRefusal> {
27233        error.downcast_ref::<FoldRefusal>()
27234    }
27235
27236    /// A deletion that lands after the fold's look at the record and before its
27237    /// locks must neither be undone (the fold's lock files bring the directory
27238    /// back, its stale copy the record) nor be acted on.
27239    #[tokio::test]
27240    async fn a_run_deleted_between_the_look_and_the_locks_is_refused_and_not_recreated() {
27241        let dir = tempfile::tempdir().unwrap();
27242        let home = dir.path();
27243        let repo = home.join("repo");
27244        std::fs::create_dir_all(&repo).unwrap();
27245        crate::clean::tests::init_repo(&repo);
27246        let (id, worktree) = crate::clean::tests::due_run_with_winner_worktree(
27247            &home.join("runs"),
27248            &home.join("wt"),
27249            &repo,
27250            "20260801-000000-y001",
27251            RunStatus::Superseded,
27252        )
27253        .await;
27254        let mut state = RunState::load_under(&id, home).unwrap();
27255        BEFORE_LOCKS.with(|hook| {
27256            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
27257                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
27258            }));
27259        });
27260
27261        let error = fold_run(&mut state, true, home).await.unwrap_err();
27262        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27263        assert!(
27264            !home.join("runs").join(&id).exists(),
27265            "the fold's own lock files must not bring a deleted run back"
27266        );
27267        assert!(worktree.exists(), "nothing of a deleted run is removed");
27268    }
27269
27270    /// The caller's `state` is only a first look: a record that was never
27271    /// saved is not a record the fold may write.
27272    #[tokio::test]
27273    async fn a_record_that_was_never_saved_is_not_folded_or_written() {
27274        let dir = tempfile::tempdir().unwrap();
27275        let home = dir.path();
27276        let mut state = RunState::new(
27277            home.join("repo"),
27278            "main".to_owned(),
27279            "abc".to_owned(),
27280            "fixture".to_owned(),
27281            crate::config::Config::default(),
27282        );
27283        state.status = RunStatus::Superseded;
27284        let error = fold_run(&mut state, true, home).await.unwrap_err();
27285        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27286        assert!(
27287            !home.join("runs").exists(),
27288            "nothing was created: {error:#}"
27289        );
27290    }
27291
27292    /// A refusal changes nothing. A directory whose record is another run's is
27293    /// not the run that was locked: every entry point answers `record gone`,
27294    /// the other run's worktree is left alone, the record stays as it was, and
27295    /// the lock files are not unlinked (an unlinked lock file lets the next
27296    /// caller lock a different inode - `pr_head::owner_lock`).
27297    #[tokio::test]
27298    async fn a_record_naming_another_run_is_refused_by_every_entry_point_and_nothing_is_touched() {
27299        let dir = tempfile::tempdir().unwrap();
27300        let home = dir.path();
27301        let repo = home.join("repo");
27302        std::fs::create_dir_all(&repo).unwrap();
27303        crate::clean::tests::init_repo(&repo);
27304        let runs = home.join("runs");
27305        let (id, own) = crate::clean::tests::due_run_with_winner_worktree(
27306            &runs,
27307            &home.join("wt"),
27308            &repo,
27309            "20260801-000000-y101",
27310            RunStatus::Superseded,
27311        )
27312        .await;
27313        let (other, theirs) = crate::clean::tests::due_run_with_winner_worktree(
27314            &runs,
27315            &home.join("wt"),
27316            &repo,
27317            "20260801-000000-y102",
27318            RunStatus::Superseded,
27319        )
27320        .await;
27321        let first_look = RunState::load_under(&id, home).unwrap();
27322        let record = runs.join(&id).join("run.json");
27323        std::fs::copy(runs.join(&other).join("run.json"), &record).unwrap();
27324        let before = std::fs::read(&record).unwrap();
27325        for entry in ["fold_run", "fold_run_when", "override"] {
27326            let mut state = first_look.clone();
27327            let result = match entry {
27328                "fold_run" => fold_run(&mut state, true, home).await,
27329                "fold_run_when" => fold_run_when(&mut state, home, &|_| Ok(true)).await,
27330                _ => fold_run_overriding_recovery_retention(&mut state, true, home).await,
27331            };
27332            let error = result.unwrap_err();
27333            assert_eq!(
27334                refusal(&error),
27335                Some(&FoldRefusal::RecordGone),
27336                "{entry}: {error:#}"
27337            );
27338            assert!(own.exists() && theirs.exists(), "{entry}");
27339            assert_eq!(std::fs::read(&record).unwrap(), before, "{entry}");
27340            for lock in ["pr-owner.lock", "driver.lock"] {
27341                assert!(
27342                    runs.join(&id).join(lock).exists(),
27343                    "{entry}: {lock} stays in place"
27344                );
27345            }
27346            assert!(
27347                !RunState::load_under(&other, home).unwrap().candidates[0].folded,
27348                "{entry}: the other run was not folded"
27349            );
27350        }
27351    }
27352
27353    /// The refusal is added to the error underneath, never substituted for it:
27354    /// callers match `ResourceBlocked` for a coordination wait.
27355    #[test]
27356    fn a_live_refusal_keeps_the_error_callers_match() {
27357        let blocked = anyhow::Error::new(crate::repo_lock::ResourceBlocked(
27358            "repository coordination".into(),
27359        ));
27360        let error = live_or(blocked);
27361        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
27362        assert!(matches!(refusal(&error), Some(FoldRefusal::Live(_))));
27363        // Anything that is not a held lock is passed through untouched.
27364        let other = live_or(anyhow::anyhow!("git exploded"));
27365        assert!(refusal(&other).is_none());
27366    }
27367
27368    /// Contention is `live`, a lock call that failed for another reason is a
27369    /// failure of its own (`failed`), missing evidence is an incomplete proof.
27370    #[test]
27371    fn source_verification_failures_are_told_apart() {
27372        let contended = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::WouldBlock))
27373            .context("Cargo build is active");
27374        let error = source_proof_failure(contended);
27375        assert!(
27376            matches!(refusal(&error), Some(FoldRefusal::Live(_))),
27377            "{error:#}"
27378        );
27379
27380        let failed = anyhow::Error::new(crate::retention::LockCallFailed::new(
27381            "Cargo lock target/debug/.cargo-lock".into(),
27382            std::io::Error::from(std::io::ErrorKind::Interrupted),
27383        ));
27384        let error = source_proof_failure(failed);
27385        assert!(refusal(&error).is_none(), "{error:#}");
27386        assert!(
27387            error
27388                .chain()
27389                .any(|cause| cause.is::<crate::retention::LockCallFailed>())
27390        );
27391
27392        let error = source_proof_failure(anyhow::anyhow!("Cargo residue changed"));
27393        assert!(matches!(
27394            refusal(&error),
27395            Some(FoldRefusal::ProofIncomplete(_))
27396        ));
27397    }
27398
27399    /// A run directory that is not there is `record gone` at the lock, not
27400    /// something to create for the lock's sake.
27401    #[test]
27402    fn a_missing_run_directory_at_the_lock_is_record_gone() {
27403        let dir = tempfile::tempdir().unwrap();
27404        let error = crate::pr_head::owner_lock(dir.path(), "20260801-000000-y103")
27405            .map(drop)
27406            .map_err(lock_refusal)
27407            .unwrap_err();
27408        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27409        assert!(!dir.path().join("runs").exists());
27410    }
27411}