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::land;
41use crate::proc::Quiet as _;
42use crate::prompt::{
43    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
44};
45use crate::queue;
46use crate::refs;
47use crate::run::{
48    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
49    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord, Handover,
50    JobRecord, JobStatus, Judgement, MergeOutcome, OperatorFixFinding, OperatorFixOutcome,
51    OperatorFixRequest, Origin, QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState,
52    RunStatus, SeatHistory, Tally, VoteRecord, tail, write_artifact,
53};
54use crate::verdict::{
55    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
56    ReviewVote, Severity,
57};
58
59/// How much verification output is kept and fed back to the fixer.
60const OUTPUT_TAIL: usize = 8_000;
61
62/// Bytes of a failing command's output kept in an event, so the reason a run
63/// stopped is readable from the report without opening `run.json`.
64const EVENT_OUTPUT_TAIL: usize = 2_000;
65
66/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
67/// command's pid before releasing the build cache's lease.
68const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
69
70/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
71/// command's pid to actually exit before giving up and releasing anyway.
72///
73/// A timeout means the process was asked to die (`kill_on_drop`,
74/// `start_kill`), not that it already has — on Windows in particular that can
75/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
76/// the instant the command returns would let the very next acquirer (this
77/// run's own next round, another run's verification, the janitor's prune)
78/// start touching the same directory while it might still be writing to it,
79/// so this polls the actual pid — real confirmation, not a fixed guess —
80/// until it is gone or this ceiling is reached. It is still not full
81/// process-tree reaping: a grandchild the timed-out process spawned and that
82/// outlives it independently is invisible to a pid check, and continuing to
83/// observe and collect *that* stays a different piece of work with its own
84/// owner. Set generously because the common case returns early the moment
85/// the pid is confirmed gone, not because every timeout pays this in full.
86const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
87
88/// Consecutive review rounds with no tree progress (see
89/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
90/// instead of spending the rest of the round budget.
91///
92/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
93/// legitimately finds nothing left to change (its previous round's fix already
94/// covered it, and this round's reviewers re-raised only nits) looks the same
95/// as one that is spinning, for exactly one round. Two in a row is where the
96/// two stop being distinguishable, and a review round on this workload has
97/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
98/// third attempt at a tree that has not moved twice running is pure cost.
99/// This does not touch `review_rounds` itself, which stays the operator's
100/// call.
101pub(crate) const STAGNANT_LIMIT: usize = 2;
102
103/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
104/// a base that moved before giving up and leaving the run `Blocked` for a
105/// person.
106///
107/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
108/// that keeps moving faster than a run can catch it is not something more
109/// rebasing fixes, it is a person's call. Not the same *number as*
110/// `land_rounds` - this budget is spent before a pull request exists, land's
111/// after - but bounded for the identical reason, so it uses the same
112/// default. Counted across both call sites in [`Runner::finish_after_tally`]
113/// (once before review, once before the gate), because either one finding
114/// the base still moving is the same signal.
115const BASE_SYNC_ROUNDS: usize = 4;
116
117/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
118/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
119/// reply held no [`FixReport`].
120///
121/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
122/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
123/// "I'll pause here until the `cargo make check` background run reports
124/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
125/// No `FixReport` was ever collected from that seat, and the run moved on to
126/// the next review round regardless.
127///
128/// Bounded independently of `review_rounds` and `graph.retries`: this
129/// recovers one seat's missing report mid-round, not a new round of review or
130/// an ordinary parse retry, and must not itself become the unbounded wait the
131/// rest of this module exists to avoid.
132const MAX_FIX_CONTINUATIONS: usize = 2;
133
134/// One queued agent invocation.
135///
136/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
137/// CLI hung up on its own stream is asked again from the same job rather than
138/// rebuilt from scratch. See [`Runner::resume_undelivered`].
139#[derive(Clone)]
140struct SeatJob {
141    spec: AgentSpec,
142    seat: SeatState,
143    cwd: PathBuf,
144    prompt: String,
145    timeout: Duration,
146    allow_write: bool,
147    sessions: bool,
148    artifacts: PathBuf,
149    stem: String,
150    /// The prompt for a seat that has been handed to another roster agent
151    /// (a fresh session): everything the original seat would have
152    /// remembered. `None` when `prompt` already carries it, as the first
153    /// ranking and the implement prompt do. Never a resume-style prompt.
154    handover: Option<String>,
155}
156
157/// How the graph reads one agent invocation.
158///
159/// Quota is split out from an ordinary failure on purpose: a rate-limited call
160/// is known to fail again if retried now, so the retry loop must not spend an
161/// attempt on it. `Dropped` is split out for the opposite reason: unlike
162/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
163/// error JSON, never the agent's answer — a caller that matched only
164/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
165/// left to read that JSON as if it were usable output. `resume_undelivered`
166/// is the only caller that acts on it; everywhere else it is reported like an
167/// ordinary failure.
168enum AgentOutcome {
169    /// A usable output.
170    Ok(AgentOutput),
171    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
172    Quota(AgentOutput),
173    /// The CLI hung up on its own stream after billed work. See
174    /// [`agent::AgentOutput::work_undelivered`].
175    Dropped(AgentOutput),
176    /// Any other failure: a timeout, a bad exit code, an empty reply.
177    Failed(String),
178}
179
180/// A request to park the run at its next node boundary.
181///
182/// Cloning is how the request travels: the loop keeps one handle and hands a
183/// clone to each [`Runner`], and every clone points at the same flag. There
184/// is no channel because there is nothing to send - the only message is
185/// "park", it is idempotent, and a flag cannot be missed by a receiver that
186/// was not listening yet.
187///
188/// The boundary is what makes this cheap. Every node writes the run's state
189/// before the next one starts, and every node skips what is already recorded:
190/// `prep` returns early once candidates exist, `implement` asks only the seats
191/// with nothing on disk, `judge` returns early once judgements exist. So a
192/// parked run resumes into exactly the node it stopped before, and no agent
193/// work is thrown away. Killing the process mid-node, by contrast, loses
194/// whatever the seats in flight had not yet written - which for an implement
195/// wave is an hour of paid work.
196///
197/// A [`Runner`] watches two independent handles of this type - see
198/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
199/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
200/// clone covering the whole daemon's lifetime and is never asked to un-park,
201/// which is correct exactly because nothing is dispatched after it fires.
202/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
203/// that parks for an interrupted task must go on to run other tasks
204/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
205/// reusing the daemon-wide one.
206#[derive(Debug, Clone, Default)]
207pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<String>>>);
208
209impl Pause {
210    /// A pause nobody has asked for yet.
211    #[must_use]
212    pub fn new() -> Self {
213        Self::default()
214    }
215
216    /// Ask the run to park at its next node boundary. Idempotent.
217    pub fn park(&self) {
218        self.0.store(true, Ordering::SeqCst);
219    }
220
221    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
222    /// fold into the run's own `park` event - so an operator reading the run
223    /// later knows this was a deliberate interrupt rather than a shutdown or
224    /// a binary swap. The first reason recorded wins; a park already in
225    /// flight is not relabelled by a second, unrelated request.
226    pub fn park_because(&self, reason: impl Into<String>) {
227        let mut reason_guard = self
228            .1
229            .lock()
230            .unwrap_or_else(std::sync::PoisonError::into_inner);
231        if reason_guard.is_none() {
232            *reason_guard = Some(reason.into());
233        }
234        drop(reason_guard);
235        self.park();
236    }
237
238    /// Has a park been asked for?
239    #[must_use]
240    pub fn parked(&self) -> bool {
241        self.0.load(Ordering::SeqCst)
242    }
243
244    /// Why the park was asked for, when the caller used [`Pause::park_because`].
245    #[must_use]
246    pub fn reason(&self) -> Option<String> {
247        self.1
248            .lock()
249            .unwrap_or_else(std::sync::PoisonError::into_inner)
250            .clone()
251    }
252}
253
254/// Drives one run.
255pub struct Runner {
256    /// Run state; public so the CLI can report on it.
257    pub state: RunState,
258    roles: ResolvedRoles,
259    sem: Arc<Semaphore>,
260    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
261    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
262    /// this is never the same handle as `interrupt`.
263    pause: Pause,
264    /// Set when `magi serve`'s interrupt scheduler wants this specific run
265    /// parked at its next node boundary, to let a task marked
266    /// [`crate::queue::Task::interrupt`] run alone before this one carries
267    /// on. Unlike `pause`, a fresh, unshared handle per run - see
268    /// [`Runner::watch_interrupt`].
269    interrupt: Pause,
270}
271
272/// Where the branch's own commits start: its merge base with the base branch
273/// as the remote has it now, else with the recorded `base_commit`. A branch
274/// rebased onto a base that moved past `base_commit` would otherwise count
275/// the base's commits as its own under `base_commit..branch`.
276async fn review_base(
277    repo: &Path,
278    remote: &str,
279    base_branch: &str,
280    base_commit: &str,
281    branch: &str,
282) -> String {
283    review_base_checked(repo, remote, base_branch, base_commit, branch)
284        .await
285        .0
286}
287
288/// [`review_base`] plus whether the base was read from a freshly fetched
289/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
290/// never older than `base_commit`'s view of the base), but the answer is then
291/// not trusted to rewrite a pull request's title.
292async fn review_base_checked(
293    repo: &Path,
294    remote: &str,
295    base_branch: &str,
296    base_commit: &str,
297    branch: &str,
298) -> (String, bool) {
299    let tracking = format!("{remote}/{base_branch}");
300    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
301    if git::rev_exists(repo, &tracking).await
302        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
303        && !mb.is_empty()
304    {
305        return (mb, fresh);
306    }
307    let mb = git::merge_base(repo, base_commit, branch)
308        .await
309        .ok()
310        .filter(|mb| !mb.is_empty())
311        .unwrap_or_else(|| base_commit.to_owned());
312    (mb, false)
313}
314
315/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
316/// when git cannot say or finds nothing: a stale list is better than a wrong
317/// or empty one.
318pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
319    if !is_review_run(state) {
320        return;
321    }
322    let base = review_base(
323        &state.repo,
324        &state.config.merge.remote,
325        &state.base_branch,
326        &state.base_commit,
327        branch,
328    )
329    .await;
330    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
331        && !subjects.is_empty()
332        && state.reviewed_commits.as_ref() != Some(&subjects)
333    {
334        state.reviewed_commits = Some(subjects);
335        state.save().ok();
336    }
337}
338
339/// Subjects of the base's commits between the recorded start and the branch's
340/// merge base: what a stale `base_commit..branch` would have mistaken for the
341/// branch's own work.
342async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
343    let (base, trusted) = review_base_checked(
344        &state.repo,
345        &state.config.merge.remote,
346        &state.base_branch,
347        &state.base_commit,
348        branch,
349    )
350    .await;
351    if !trusted {
352        return None;
353    }
354    git::subjects(&state.repo, &state.base_commit, &base)
355        .await
356        .ok()
357}
358
359/// May an adopted pull request's title be replaced with `computed`? Only when
360/// it is empty, magi's own shape, or a base commit's subject that leaked in;
361/// a title a person wrote stays. Never when `computed` is itself a leak.
362fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
363    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
364    if is_leak(computed) {
365        return false;
366    }
367    let cur = current.trim();
368    cur.is_empty()
369        || cur.starts_with(REVIEW_PROMPT_OPENING)
370        || cur.starts_with("chore: land candidate")
371        || cur.starts_with("magi: candidate")
372        || is_leak(cur)
373}
374
375/// The commit a run branches from: the base branch as the remote has it.
376///
377/// Two failures this replaces. A run used to branch off `HEAD` and so refused
378/// to start on a dirty tree, which made `magi serve` decline every task for as
379/// long as the operator had work in progress - most of the time. Branching off
380/// the *local* base branch fixed that and introduced a worse one: `land` merges
381/// the winner on GitHub, nothing updates the local ref, and the next run
382/// branches off a base missing everything the previous runs landed. Two tasks
383/// in a row from a phone would have had the second silently re-implementing
384/// against stale code and opening a pull request that reverted the first.
385///
386/// Only refs move here - no checkout, no local branch, no merge - so it is safe
387/// with uncommitted work in the tree. A machine with no network still starts:
388/// the fetch may fail and the local tip is used with a warning, because
389/// refusing to run offline is a worse failure than running against a base the
390/// operator can see for themselves.
391///
392/// One function, called by both entry points. Two answers to "where does a run
393/// branch from" is the kind of drift nobody notices until a diff is wrong.
394/// Bring the local `branch` in line with `<remote>/<branch>` before a review
395/// checks it out.
396///
397/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
398/// anything other than plain `git push` from this checkout (a jj colocated
399/// workspace, another clone) moves only the remote-tracking ref - so the local
400/// one can be a stale placeholder. It moves only when local is behind the remote or is an
401/// empty placeholder that diverged from it; unpushed local work is kept, and a real
402/// divergence is refused rather than guessed at.
403async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
404    let tracking = format!("{remote}/{branch}");
405    let fetched = git::fetch(repo, remote, branch).await;
406    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
407    let local_exists = git::branch_exists(repo, branch).await?;
408    if !fresh {
409        if !local_exists {
410            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
411        }
412        tracing::warn!(
413            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
414        );
415        return Ok(());
416    }
417    let remote_sha = git::rev_parse(repo, &tracking).await?;
418    if !local_exists {
419        git::git(repo, &["branch", branch, &tracking]).await?;
420        return Ok(());
421    }
422    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
423    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
424        return Ok(());
425    }
426    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
427        // Diverged. `reconcile` settles it only when it can prove nothing is
428        // lost: a local tip that is the remote's change rebased is pushed over
429        // it (lease pinned to the tip read here), a tip whose every extra
430        // commit is empty is a placeholder the remote's work replaced, and
431        // anything else is two different changes - a question for a person.
432        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
433            .await?
434        {
435            crate::reconcile::Reconciliation::Pushed => {
436                tracing::warn!(
437                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
438                    short(&local_sha),
439                    short(&remote_sha)
440                );
441                return Ok(());
442            }
443            crate::reconcile::Reconciliation::Placeholder => {}
444            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
445        }
446    }
447    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
448    if !out.ok() {
449        bail!(
450            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
451            short(&local_sha),
452            short(&remote_sha),
453            out.stderr
454        );
455    }
456    tracing::warn!(
457        "local `{branch}` was stale: fast-forwarded {} -> {}",
458        short(&local_sha),
459        short(&remote_sha)
460    );
461    Ok(())
462}
463
464async fn resolve_base(repo: &Path, base_branch: &str, remote: &str) -> Result<String> {
465    let tracking = format!("{remote}/{base_branch}");
466    let fetched = git::fetch(repo, remote, base_branch).await;
467    if let Ok(out) = &fetched
468        && out.ok()
469        && git::rev_exists(repo, &tracking).await
470    {
471        return git::rev_parse(repo, &tracking).await;
472    }
473    let why = match &fetched {
474        Ok(out) if !out.ok() => out.stderr.lines().next().unwrap_or("").to_owned(),
475        Ok(_) => format!("{remote} has no {base_branch}"),
476        Err(e) => e.to_string(),
477    };
478    // No fallback to the local branch: it may be behind, and branching off an
479    // old commit is the stale-checkout bug this check exists to prevent.
480    bail!(
481        "cannot read {tracking} ({why}); refusing to branch off the local \
482         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
483         base / remote in magi.toml"
484    )
485}
486
487/// Exclusive claim on one run's `magi fix` step, released on drop — including
488/// on an early return or a panic.
489///
490/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
491/// manual `magi fix` invocations against the same run are otherwise
492/// invisible to each other and would race to remove and recreate the same
493/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
494/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
495/// which is only ever reclaimed later, out of band, by
496/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
497/// `magi fix` invocation is not necessarily running under either of those, so
498/// nothing would ever sweep a lock a killed or crashed process left behind.
499/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
500/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
501/// lease use: an unreadable or unparsable pid, or a liveness query the
502/// platform cannot answer, reads as alive and the lock is left in place.
503struct FixClaim {
504    path: PathBuf,
505}
506
507impl FixClaim {
508    fn acquire(dir: &Path) -> Result<Self> {
509        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
510        let path = dir.join("fix.lock");
511        match Self::create(&path) {
512            Ok(claim) => Ok(claim),
513            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
514                if Self::reclaim_if_dead(&path) {
515                    Self::create(&path).with_context(|| format!("lock {}", path.display()))
516                } else {
517                    bail!(
518                        "another `magi fix` is already running for this run ({} exists)",
519                        path.display()
520                    )
521                }
522            }
523            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
524        }
525    }
526
527    fn create(path: &Path) -> std::io::Result<Self> {
528        let mut f = std::fs::OpenOptions::new()
529            .write(true)
530            .create_new(true)
531            .open(path)?;
532        use std::io::Write as _;
533        // Read back by `reclaim_if_dead` on a later, stuck invocation.
534        writeln!(f, "{}", std::process::id())?;
535        Ok(Self {
536            path: path.to_owned(),
537        })
538    }
539
540    /// True if the lock named a process confirmed dead, in which case it was
541    /// also removed. Never true on an unreadable file, an unparsable pid, or
542    /// a liveness query the platform cannot answer — see this type's own doc.
543    fn reclaim_if_dead(path: &Path) -> bool {
544        let dead = std::fs::read_to_string(path)
545            .ok()
546            .and_then(|body| body.trim().parse::<u32>().ok())
547            .is_some_and(|pid| !crate::proc::pid_alive(pid));
548        dead && std::fs::remove_file(path).is_ok()
549    }
550}
551
552impl Drop for FixClaim {
553    fn drop(&mut self) {
554        let _ = std::fs::remove_file(&self.path);
555    }
556}
557
558impl Runner {
559    /// Start a fresh run against `repo`.
560    pub async fn start(
561        repo: &Path,
562        instruction: String,
563        config: Config,
564        origin: Origin,
565    ) -> Result<Self> {
566        Self::start_naming(repo, instruction, "", config, origin).await
567    }
568
569    /// [`Runner::start`] for a queued task: `also_scan` (the task's title) is
570    /// searched for branch and commit references along with the instruction,
571    /// since a task may name the work it is about only in its title.
572    pub async fn start_naming(
573        repo: &Path,
574        instruction: String,
575        also_scan: &str,
576        config: Config,
577        origin: Origin,
578    ) -> Result<Self> {
579        let repo = git::toplevel(repo).await?;
580        let missing = agent::missing_programs(&config.agents);
581        if !missing.is_empty() {
582            bail!(
583                "these agent programs are not on PATH: {}. Fix the roster in \
584                 magi.toml or install them.",
585                missing.join(", ")
586            );
587        }
588        let base_branch =
589            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
590                .await?;
591        let base_commit = resolve_base(&repo, &base_branch, &config.merge.remote).await?;
592        let roles = config.resolve_roles()?;
593        let max_parallel = config.graph.max_parallel.max(1);
594        // A task that points at work already in the repository starts from
595        // it; what the repository says about each reference is recorded.
596        let seeds = refs::resolve(
597            &repo,
598            &base_commit,
599            &config.merge.remote,
600            &format!("{also_scan}\n{instruction}"),
601        )
602        .await;
603        refs::plan(&repo, &seeds).await?;
604        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
605        // Recorded before the first save, so a crash right after minting
606        // cannot leave a run with no origin. Legibility only: nothing reads it
607        // to decide anything.
608        state.origin = Some(origin);
609        for seed in &seeds {
610            state.event(
611                "seed",
612                refs::describe(std::slice::from_ref(seed)).unwrap_or_default(),
613            );
614        }
615        state.seeds = seeds;
616        state.event("start", format!("run {} created", state.id));
617        state.save()?;
618        Ok(Self {
619            state,
620            roles,
621            sem: Arc::new(Semaphore::new(max_parallel)),
622            pause: Pause::new(),
623            interrupt: Pause::new(),
624        })
625    }
626
627    /// Open a review-only run against work that already exists on `branch`.
628    ///
629    /// The expensive half of the graph is the implement wave — measured at
630    /// 111 and 134 internal tool-loop turns on this repository, against a
631    /// handful for a judge or a reviewer. The cheap half is worth running on
632    /// hand-written work too, and there was no way to reach it.
633    ///
634    /// No new state and no schema change are needed: a run with **one** viable
635    /// candidate and a tally already decided degrades `execute` to exactly
636    /// review → gate → merge, because `judge` skips a single-candidate field,
637    /// `deliberate` has fewer than two first choices to reconcile, `vote`
638    /// returns early, `tally` is already present and `fold_losers` has no
639    /// losers. Resuming such a run therefore does the right thing as well.
640    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
641        Self::review_taking_over(repo, branch, config, None, origin).await
642    }
643
644    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
645    /// at the same task still has `branch` checked out, its worktree is
646    /// released first if that is safe (see [`crate::handover`]), and the
647    /// review refuses with the reason if it is not. `None` is a hand-run
648    /// review: it has no earlier attempts, so only a worktree of a dead run
649    /// magi recorded itself can be released.
650    pub async fn review_taking_over(
651        repo: &Path,
652        branch: &str,
653        config: Config,
654        takeover: Option<crate::handover::Takeover>,
655        origin: Origin,
656    ) -> Result<Self> {
657        let repo = git::toplevel(repo).await?;
658        let missing = agent::missing_programs(&config.agents);
659        if !missing.is_empty() {
660            bail!(
661                "these agent programs are not on PATH: {}. Fix the roster in \
662                 magi.toml or install them.",
663                missing.join(", ")
664            );
665        }
666        let base_branch =
667            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
668                .await?;
669        if base_branch == branch {
670            bail!("`{branch}` is the base branch; there is nothing to review against");
671        }
672        let base_commit = resolve_base(&repo, &base_branch, &config.merge.remote).await?;
673
674        let roles = config.resolve_roles()?;
675        let max_parallel = config.graph.max_parallel.max(1);
676        let mut state = RunState::new(
677            repo.clone(),
678            base_branch,
679            base_commit.clone(),
680            String::new(),
681            config,
682        );
683        state.origin = Some(origin);
684
685        // Released before anything else touches the branch: a stale local
686        // branch is moved with `git branch -f`, which git refuses while an
687        // earlier attempt's worktree still has it checked out. Everything
688        // after this point that can fail puts the old run back.
689        // A hand-run review has no task, hence no earlier attempts, but a
690        // worktree of a dead run magi made may still be released.
691        let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
692            earlier: Vec::new(),
693            home: crate::run::home(),
694            choice: None,
695        });
696        let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
697        if let Some(released) = &released {
698            state.event(
699                "release",
700                format!(
701                    "took `{branch}` over from run {}: its worktree was released: {}",
702                    crate::run::short_of(&released.old_id),
703                    released.audit
704                ),
705            );
706        }
707        // The owner's answer to an earlier divergence question is applied
708        // here: after the release (git will not move a checked-out branch)
709        // and before the sync that would otherwise ask again.
710        if let Some(choice) = takeover.choice.as_ref()
711            && let Err(e) =
712                crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
713                    .await
714        {
715            if let Some(released) = &released {
716                released.restore(&repo, branch).await;
717            }
718            return Err(e.context("applying the owner's answer about the diverged branch"));
719        }
720        let opened =
721            Self::open_review(&repo, branch, state, roles, max_parallel, base_commit).await;
722        if opened.is_err()
723            && let Some(released) = &released
724        {
725            released.restore(&repo, branch).await;
726        }
727        opened
728    }
729
730    /// The half of [`Runner::review_taking_over`] that can fail after an
731    /// earlier attempt's worktree was released.
732    async fn open_review(
733        repo: &Path,
734        branch: &str,
735        mut state: RunState,
736        roles: ResolvedRoles,
737        max_parallel: usize,
738        base_commit: String,
739    ) -> Result<Self> {
740        sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
741        // The commit subjects are the closest thing to a task statement that
742        // existing work carries, and the reviewers are told as much.
743        let start = review_base(
744            repo,
745            &state.config.merge.remote,
746            &state.base_branch,
747            &base_commit,
748            branch,
749        )
750        .await;
751        let log = git::log_oneline(repo, &start, branch)
752            .await
753            .unwrap_or_default();
754        let instruction = format!(
755            "Review the work already on branch `{branch}`. There is no task \
756             statement: what the change claims to do is whatever its commits \
757             say.\n\n{}",
758            if log.trim().is_empty() {
759                "(no commit messages)"
760            } else {
761                log.trim()
762            }
763        );
764        state.instruction = instruction;
765        state.reviewed_commits = Some(
766            git::subjects(repo, &start, branch)
767                .await
768                .unwrap_or_default(),
769        );
770
771        // An attached worktree, so the fixer's commits land on the branch under
772        // review rather than on a detached head nobody will look at again.
773        let worktree = state.worktree_root().join("under-review");
774        if let Some(parent) = worktree.parent() {
775            tokio::fs::create_dir_all(parent).await.ok();
776        }
777        let path = worktree.to_string_lossy().to_string();
778        git::git(repo, &["worktree", "add", &path, branch])
779            .await
780            .with_context(|| {
781                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
782            })?;
783
784        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
785            .await
786            .unwrap_or(0);
787        if commits == 0 {
788            git::worktree_remove(repo, &worktree).await.ok();
789            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
790        }
791        let files = git::changed_files(&worktree, &base_commit, "HEAD")
792            .await
793            .map(|f| f.len())
794            .unwrap_or(0);
795        if files == 0
796            && let (Ok(head_tree), Ok(base_tree)) = (
797                git::tree_of(&worktree, "HEAD").await,
798                git::tree_of(&worktree, &base_commit).await,
799            )
800            && head_tree == base_tree
801        {
802            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
803            git::worktree_remove(repo, &worktree).await.ok();
804            bail!(
805                "`{branch}` at {} has a tree identical to base {}; this usually means \
806                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
807                 against `{}/{branch}`) rather than an empty change",
808                short(&head),
809                short(&base_commit),
810                state.config.merge.remote
811            );
812        }
813        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
814            .await
815            .unwrap_or_default();
816
817        state.candidates.push(Candidate {
818            index: 0,
819            label: 'A',
820            // Not an agent id on purpose: nothing in the roster wrote this, and
821            // the stats tables must not credit anyone with a win for it.
822            agent: EXISTING_BRANCH.to_owned(),
823            branch: branch.to_owned(),
824            worktree,
825            summary: String::new(),
826            stat,
827            files,
828            commits,
829            empty: false,
830            failed: None,
831            verified_noop: None,
832            duration_ms: 0,
833            folded: false,
834        });
835        state.tally = Some(Tally {
836            first_choice: BTreeMap::from([('A', 0)]),
837            borda: BTreeMap::new(),
838            winner: 'A',
839            rankings: 0,
840            unanimous_initial: false,
841            deliberated: false,
842            changed_votes: 0,
843            unanimous_final: false,
844            tie_break: None,
845            // No panel sat, so no quorum applies. Zero judges is the correct
846            // number for work that never competed, and must not be reported as
847            // a collapsed panel.
848            judges: 0,
849            present: 0,
850            quorum: 0,
851            met_quorum: true,
852            uncontested: Some("review-only run: nothing competed".to_owned()),
853        });
854        state.status = RunStatus::Reviewing;
855        state.event(
856            "start",
857            format!(
858                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
859                state.id
860            ),
861        );
862        state.save()?;
863        Ok(Self {
864            state,
865            roles,
866            sem: Arc::new(Semaphore::new(max_parallel)),
867            pause: Pause::new(),
868            interrupt: Pause::new(),
869        })
870    }
871
872    /// Reopen an existing run.
873    pub fn resume(id: &str) -> Result<Self> {
874        let state = RunState::load(id)?;
875        if let Some(to) = &state.released_to {
876            bail!(
877                "run {} cannot be resumed: its worktree was released to run {}",
878                state.short(),
879                crate::run::short_of(to)
880            );
881        }
882        let roles = state.config.resolve_roles()?;
883        let max_parallel = state.config.graph.max_parallel.max(1);
884        Ok(Self {
885            state,
886            roles,
887            sem: Arc::new(Semaphore::new(max_parallel)),
888            pause: Pause::new(),
889            interrupt: Pause::new(),
890        })
891    }
892
893    /// Walk the graph to a terminal state, skipping nodes already recorded.
894    ///
895    /// Every way a run is driven - the queue loop, `magi run`, a resume from
896    /// the phone - ends here, so this is the one place a run that ended
897    /// Blocked / Stalled / Failed, or died with an error, is announced to the
898    /// notification centre. Best-effort: see [`crate::notices::raise`].
899    pub async fn execute(&mut self) -> Result<()> {
900        let result = self.execute_graph().await;
901        self.mark_driver_exited();
902        let ended = if result.is_err() {
903            Some(crate::notices::run_stopped(&self.state.id, &self.state))
904        } else {
905            crate::notices::run_ended(&self.state)
906        };
907        if let Some(notice) = ended {
908            crate::notices::raise(notice);
909        }
910        result
911    }
912
913    /// Record that this process no longer drives the run, so its pid (a
914    /// daemon's outlives the run) is not read as a live driver.
915    ///
916    /// Written onto the record as it is on disk, never this copy: another
917    /// process may have resumed the run (recording its own pid and clearing
918    /// the flag) or released its worktree since this copy was read, and
919    /// saving over that would mark a running driver dead. Only a record still
920    /// naming this process as the driver is touched.
921    fn mark_driver_exited(&mut self) {
922        self.state.driver_exited = true;
923        let pid = std::process::id();
924        let Ok(mut disk) = RunState::load(&self.state.id) else {
925            return;
926        };
927        if disk.released_to.is_some() || disk.driver_pid != Some(pid) || disk.driver_exited {
928            return;
929        }
930        disk.driver_exited = true;
931        if let Err(e) = disk.save() {
932            tracing::warn!("could not record that run {} stopped: {e:#}", self.state.id);
933        }
934    }
935
936    async fn execute_graph(&mut self) -> Result<()> {
937        // Moving again, so it is no longer parked. Set before the walk rather
938        // than in `resume`, so every way of re-entering the graph clears it
939        // and a card cannot claim a run is waiting to be resumed while the
940        // agents are already working.
941        self.state.parked = false;
942        // Any seat this state still lists as answering belongs to whatever
943        // process last drove this run — this one included, if it crashed
944        // mid-wave. Cleared and flushed immediately, before anything else
945        // runs, so a resume can never show a seat as live when nothing is
946        // asking it anything yet; the node that actually dispatches the next
947        // wave repopulates it.
948        self.state.clear_active();
949        // Recorded in the same spot, and flushed together with the clear
950        // above: this is the pid a reader checks (`RunState::liveness`) when
951        // no daemon claim exists to answer "is a process still driving this
952        // run" — a plain `magi run` / `magi review` typed into a terminal
953        // claims nothing there. Always overwritten, never only-if-absent, so
954        // a resumed run's stale pid from a previous, possibly-dead process
955        // can never survive into this one's own report. Unlike
956        // `clear_active`, this changes on every single `execute()` call, so
957        // the save below is now unconditional rather than only-if-cleared.
958        //
959        // `driver_started_at` is recorded in the same breath, from this same
960        // pid, so `liveness` can tell a live pid that is genuinely still us
961        // apart from one the OS has since handed to an unrelated process —
962        // see that field's own doc for why the pid alone is not enough.
963        // A resume that raced a takeover: the record on disk says the worktree
964        // was handed to a later run after this copy was read. Saving over it
965        // would erase that and drive a run with nothing to run in.
966        if let Ok(disk) = RunState::load(&self.state.id)
967            && let Some(to) = &disk.released_to
968        {
969            bail!(
970                "run {} cannot continue: its worktree was released to run {}",
971                self.state.short(),
972                crate::run::short_of(to)
973            );
974        }
975        let pid = std::process::id();
976        self.state.driver_pid = Some(pid);
977        self.state.driver_started_at = crate::proc::process_started_at(pid);
978        self.state.driver_exited = false;
979        self.state.save()?;
980        // A run that already lost its quorum never resumes into the verdict
981        // machinery: `deliberate` and `vote` would otherwise clobber the
982        // stalled marker back to Voting and the run would keep going past a
983        // verdict that is no longer trustworthy. Everything already recorded is
984        // kept, so the run stays resumable (or foldable) for a human to pick up.
985        //
986        // On --resume the run gets one chance to repair itself: the seats a
987        // rate limit took out are re-asked. If their quota has since reset and
988        // the quorum is restored, the run picks up and finishes; otherwise it
989        // stays stale and still-resumable for a later retry. If it does not
990        // recover, the returned status stays `Stalled` and nothing was
991        // clobbered (the recovery only mutates entries for the lost seats).
992        if self.state.status == RunStatus::Stalled {
993            if self.recover_stall().await? {
994                self.finish_after_tally().await?;
995            } else {
996                // Still below quorum: persist the marker and stay resumable.
997                self.state.save()?;
998            }
999            return Ok(());
1000        }
1001        // A run parked inside `land` - watching CI, mid fix-round, or
1002        // waiting on the owner's merge approval - resumes directly into it,
1003        // never back through `prep`. Everything before `merge` already
1004        // concluded; that is the only way `status` reaches `Landing` in the
1005        // first place. Re-walking `review_loop` first would also be actively
1006        // wrong: its own status recomputation (see its doc) treats any
1007        // clean round as reason to set `status` to `Gating`, which would
1008        // clobber this marker before `merge` ever ran, and this run would
1009        // never find its way back into `land` at all.
1010        if self.state.status == RunStatus::Landing {
1011            self.run_land().await?;
1012            // `run_land` may have settled the run right here - CI came back
1013            // green and the PR merged, say - without ever passing back
1014            // through `merge`'s own trailing call. Whatever it left `status`
1015            // as is what this has to read.
1016            self.settle_questions();
1017            return Ok(());
1018        }
1019        self.prep().await?;
1020        if self.park_here()? {
1021            return Ok(());
1022        }
1023        self.advise().await?;
1024        if self.park_here()? {
1025            return Ok(());
1026        }
1027        self.implement().await?;
1028        if self.park_here()? {
1029            return Ok(());
1030        }
1031        // `after_implement` already saved the state and settled any open
1032        // questions when it set this; nothing later in the graph has
1033        // anything to judge.
1034        if self.state.status == RunStatus::VerifiedNoop {
1035            return Ok(());
1036        }
1037        self.judge().await?;
1038        if self.park_here()? {
1039            return Ok(());
1040        }
1041        self.deliberate().await?;
1042        if self.park_here()? {
1043            return Ok(());
1044        }
1045        self.vote().await?;
1046        if self.park_here()? {
1047            return Ok(());
1048        }
1049        self.tally()?;
1050        // A verdict that lost its quorum is not trustworthy: do not review,
1051        // gate, or merge on it. Everything already done is kept, so the run
1052        // stays resumable (or foldable); the human can replace the agent that
1053        // ran out of quota and pick it up.
1054        if self.state.status == RunStatus::Stalled {
1055            // Persist the stalled marker now — the normal end-of-execute save
1056            // below is below this early return, and without it a resumed run
1057            // would reload a pre-tally status and keep going.
1058            self.state.save()?;
1059            return Ok(());
1060        }
1061        self.finish_after_tally().await?;
1062        Ok(())
1063    }
1064
1065    /// Park here if asked to, recording it in the run's own timeline.
1066    ///
1067    /// Returns whether the caller should stop walking the graph. The state is
1068    /// saved either way by the node that just finished; this adds the event so
1069    /// the operator's card says why a run that is neither finished nor moving
1070    /// is sitting where it is.
1071    fn park_here(&mut self) -> Result<bool> {
1072        // Either handle asking is enough - see `Pause`'s own doc for why
1073        // they are never the same one. `interrupt` is checked second so a
1074        // reason it carries is preferred in the message below over a plain
1075        // shutdown park racing it at the same boundary.
1076        if !self.pause.parked() && !self.interrupt.parked() {
1077            return Ok(false);
1078        }
1079        let why = match self.interrupt.reason().or_else(|| self.pause.reason()) {
1080            Some(reason) => format!(
1081                "parked after `{}` ({reason}) — resume to carry on from here",
1082                self.state.status.as_str()
1083            ),
1084            None => format!(
1085                "parked after `{}` — resume to carry on from here",
1086                self.state.status.as_str()
1087            ),
1088        };
1089        self.state.event("park", why);
1090        self.state.parked = true;
1091        self.state.save()?;
1092        Ok(true)
1093    }
1094
1095    /// Hand the runner the pause `magi serve`'s own shutdown watches.
1096    pub fn on_pause(&mut self, pause: Pause) {
1097        self.pause = pause;
1098    }
1099
1100    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
1101    /// scheduler asking this one run - and no other - to park so a task
1102    /// marked [`crate::queue::Task::interrupt`] can run alone. See
1103    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
1104    /// handle.
1105    pub fn watch_interrupt(&mut self, pause: Pause) {
1106        self.interrupt = pause;
1107    }
1108
1109    /// Abandon this run's own open questions, once `status` has actually
1110    /// settled rather than merely paused.
1111    ///
1112    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
1113    /// either back up with the candidates, the review round and the seat
1114    /// sessions already on disk, so a question an implementer asked mid-round
1115    /// may still get a real answer read by a real resume. Only the statuses
1116    /// `resumable` excludes are actually final: the run merged, it reached
1117    /// `Ready` with nothing left to do, it failed outright with no
1118    /// established point to continue from, or every candidate agreed, with
1119    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
1120    /// every one of those the seat that asked is gone for good, exactly like
1121    /// the run being deleted under `magi run rm` - so the same cleanup
1122    /// applies, worded for what actually happened instead of "the run was
1123    /// deleted".
1124    ///
1125    /// Best-effort and silent on success: called from every place `status`
1126    /// can land on one of those three, including ones a resumed run revisits,
1127    /// so it must cost nothing when there was nothing open to begin with.
1128    fn settle_questions(&mut self) {
1129        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
1130            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
1131        }
1132    }
1133
1134    /// The tail of the graph after a trustworthy tally: fold losers, review,
1135    /// gate, merge, and persist.
1136    async fn finish_after_tally(&mut self) -> Result<()> {
1137        self.fold_losers().await?;
1138        // Before review starts, and again right before the gate: a run's
1139        // review rounds can themselves take long enough for the base to move
1140        // a second time, and the gate is the one node whose "green" gets
1141        // acted on.
1142        self.sync_to_base().await?;
1143        if self.state.status == RunStatus::AlreadyInBase {
1144            return Ok(());
1145        }
1146        self.review_loop().await?;
1147        self.sync_to_base().await?;
1148        if self.state.status == RunStatus::AlreadyInBase {
1149            return Ok(());
1150        }
1151        self.gate().await?;
1152        self.merge().await?;
1153        self.state.save()?;
1154        Ok(())
1155    }
1156
1157    // ---------------------------------------------------------------- prep
1158
1159    async fn prep(&mut self) -> Result<()> {
1160        if !self.state.candidates.is_empty() {
1161            return Ok(());
1162        }
1163        self.state.status = RunStatus::Prep;
1164        let repo = self.state.repo.clone();
1165        let base = self.state.base_commit.clone();
1166        let plan = refs::plan(&repo, &self.state.seeds).await?;
1167        let start = plan.start.clone().unwrap_or_else(|| base.clone());
1168        let root = self.state.worktree_root();
1169        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
1170
1171        // The hook is the write-time half of the blindness contract; the
1172        // presentation filter in `blind` is the half that cannot be bypassed.
1173        let hooks_dir = self.state.dir().join("hooks");
1174        if self.state.config.blind.commit_msg_hook {
1175            std::fs::create_dir_all(&hooks_dir)
1176                .with_context(|| format!("create {}", hooks_dir.display()))?;
1177            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
1178            let path = hooks_dir.join("commit-msg");
1179            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
1180            make_executable(&path)?;
1181            // Ref-counted rather than a plain idempotent set: with more than
1182            // one run able to be in flight in the same repository at once
1183            // (see `Config::daemon.max_concurrent_runs`), a bare "already
1184            // true?" check cannot tell "another run of mine still needs
1185            // this" from "nobody does", and the run that happens to finish
1186            // first would disable the hook out from under a sibling still
1187            // relying on it.
1188            git::acquire_worktree_config(&repo).await?;
1189            self.state.enabled_worktree_config = true;
1190        }
1191
1192        for (index, (spec, label)) in self
1193            .roles
1194            .implementers
1195            .clone()
1196            .into_iter()
1197            .zip(labels)
1198            .enumerate()
1199        {
1200            let branch = self.state.branch_for(label);
1201            let worktree = root.join(format!("cand-{label}"));
1202            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
1203            if self.state.config.blind.commit_msg_hook {
1204                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
1205            }
1206            git::local_exclude(&worktree, "/.magi/").await?;
1207            for pick in &plan.picks {
1208                if let Err(e) = git::cherry_pick(&worktree, pick).await {
1209                    self.state.status = RunStatus::Blocked;
1210                    self.state
1211                        .event("prep", format!("cannot apply referenced commit: {e}"));
1212                    self.state.save()?;
1213                    return Err(e);
1214                }
1215            }
1216            self.state.candidates.push(Candidate {
1217                index,
1218                label,
1219                agent: spec.id.clone(),
1220                branch,
1221                worktree,
1222                summary: String::new(),
1223                stat: String::new(),
1224                files: 0,
1225                commits: 0,
1226                empty: false,
1227                failed: None,
1228                verified_noop: None,
1229                duration_ms: 0,
1230                folded: false,
1231            });
1232        }
1233
1234        for j in 1..=self.roles.judges.len() {
1235            let wt = root.join(format!("judge-{j}"));
1236            if !wt.exists() {
1237                git::worktree_add_detached(&repo, &wt, &base).await?;
1238            }
1239        }
1240
1241        // Disposable, detached checkouts for the design-deliberation stage's
1242        // advisor seats — the same shape as the judges' above, at the same
1243        // base commit, since advisors also only ever read. Sized off the
1244        // configured count directly rather than a resolved roster: unlike
1245        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
1246        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
1247        // `prep` has no `ResolvedRoles` field to read a count from here.
1248        if self.state.config.graph.advise {
1249            for k in 1..=self.state.config.graph.advisors {
1250                let wt = root.join(format!("advisor-{k}"));
1251                if !wt.exists() {
1252                    git::worktree_add_detached(&repo, &wt, &base).await?;
1253                }
1254            }
1255        }
1256
1257        // A judge cannot tell it is looking at its own patch — the seats keep
1258        // separate conversations — but a panel that shares agents with the
1259        // field is less independent than it looks, and that is worth saying out
1260        // loud once per run rather than leaving it in the config.
1261        let authors: Vec<&str> = self
1262            .roles
1263            .implementers
1264            .iter()
1265            .map(|a| a.id.as_str())
1266            .collect();
1267        let overlap: Vec<String> = self
1268            .roles
1269            .judges
1270            .iter()
1271            .enumerate()
1272            .filter(|(_, j)| authors.contains(&j.id.as_str()))
1273            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
1274            .collect();
1275        if !overlap.is_empty() {
1276            let note = format!(
1277                "{} also authored a candidate; blind, but the panel is less \
1278                 independent than {} distinct agents would be",
1279                overlap.join(", "),
1280                self.roles.judges.len()
1281            );
1282            self.state.event("prep", note);
1283        }
1284
1285        self.state.event(
1286            "prep",
1287            format!(
1288                "{} candidates, {} judges, base {} ({})",
1289                self.state.candidates.len(),
1290                self.roles.judges.len(),
1291                &self.state.base_commit[..7.min(self.state.base_commit.len())],
1292                self.state.base_branch
1293            ),
1294        );
1295        self.state.status = RunStatus::Implementing;
1296        self.state.save()?;
1297        Ok(())
1298    }
1299
1300    // -------------------------------------------------------------- advise
1301
1302    /// The design-deliberation stage: independent, read-only advisor seats
1303    /// each sketch a design before any implementer touches the repository,
1304    /// and (when at least one produced a usable proposal) a synthesis seat
1305    /// blends them into a brief `implement` carries in every candidate's
1306    /// prompt.
1307    ///
1308    /// `[graph] advise` is the on/off switch, on by default; `[graph]
1309    /// advisors` is the proposal count. Everything here is best-effort and
1310    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
1311    /// that cannot reach quota, or a synthesis seat that produced nothing
1312    /// usable all leave `implement` exactly as it was before this stage
1313    /// existed — the task instruction alone — rather than failing the whole
1314    /// competition over an enrichment stage. Every outcome is still recorded
1315    /// as an event, so a run that got nothing from this stage says why.
1316    ///
1317    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
1318    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
1319    /// resumed run whose stage failed would re-run it, and re-spend the
1320    /// agent calls, on every reentry before `implement`.
1321    ///
1322    /// Also skipped once any candidate shows implementation progress — the
1323    /// exact predicate `implement` itself uses to decide a candidate is no
1324    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
1325    /// is not enough: a run created by an older binary that predates this
1326    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
1327    /// an already-`Implementing`-or-later run under this build would
1328    /// otherwise walk straight back through `prep` (a no-op once candidates
1329    /// exist) into this node and spawn every advisor seat against worktrees
1330    /// `prep` never recreated — after implementation has already started,
1331    /// which is exactly the invariant this stage exists to guarantee.
1332    async fn advise(&mut self) -> Result<()> {
1333        let implement_untouched = self
1334            .state
1335            .candidates
1336            .iter()
1337            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
1338        if !self.state.config.graph.advise || self.state.advise_attempted {
1339            return Ok(());
1340        }
1341        if !implement_untouched {
1342            self.state.event(
1343                "advise",
1344                "skipping the design-deliberation stage: at least one \
1345                 candidate already shows implementation progress, so this \
1346                 run is past the point the stage exists to run before"
1347                    .to_owned(),
1348            );
1349            self.state.advise_attempted = true;
1350            self.state.save()?;
1351            return Ok(());
1352        }
1353        let run_id = self.state.id.clone();
1354        let prompts = self.state.config.prompts.clone();
1355        let instruction = self.state.instruction.clone();
1356        let language = self.state.config.graph.language.clone();
1357        let root = self.state.worktree_root();
1358        let n = self.state.config.graph.advisors;
1359        let where_recorded = self.state.dir().join("run.json");
1360
1361        let seats = match self.state.config.advisors() {
1362            Ok(seats) if !seats.is_empty() => seats,
1363            Ok(_) => {
1364                self.state.event(
1365                    "advise",
1366                    format!(
1367                        "[graph] advisors is 0; skipping the design-deliberation \
1368                         stage and continuing without a synthesis brief (see {})",
1369                        where_recorded.display()
1370                    ),
1371                );
1372                self.state.advise_attempted = true;
1373                self.state.save()?;
1374                return Ok(());
1375            }
1376            Err(e) => {
1377                self.state.event(
1378                    "advise",
1379                    format!(
1380                        "could not resolve advisor seats ({e:#}); continuing \
1381                         without a design-deliberation brief (see {})",
1382                        where_recorded.display()
1383                    ),
1384                );
1385                self.state.advise_attempted = true;
1386                self.state.save()?;
1387                return Ok(());
1388            }
1389        };
1390
1391        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
1392        let artifacts = agent::artifacts_dir(&self.state.dir());
1393        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
1394
1395        let mut jobs = Vec::new();
1396        for (i, spec) in seats.iter().cloned().enumerate() {
1397            let seat_key = format!("advisor-{}", i + 1);
1398            let seat = self.seat(&seat_key, &spec.id);
1399            jobs.push(SeatJob {
1400                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
1401                spec,
1402                seat,
1403                cwd: worktrees[i % worktrees.len()].clone(),
1404                timeout,
1405                allow_write: false,
1406                sessions: false,
1407                artifacts: artifacts.clone(),
1408                stem: seat_key,
1409                handover: None,
1410            });
1411        }
1412
1413        self.state.event(
1414            "advise",
1415            format!(
1416                "{} advisor seat(s) sketching a design in parallel",
1417                jobs.len()
1418            ),
1419        );
1420        let mut quota_losses = Vec::new();
1421        let cache = self.state.config.cache_dir();
1422        let ctx = WaveCtx {
1423            carry_seats: false,
1424            run: &run_id,
1425            node: "advise",
1426            prompts: &prompts,
1427            cache: cache.as_deref(),
1428            round: None,
1429        };
1430        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
1431        let results = ask_json_wave::<Proposal>(
1432            jobs,
1433            Arc::clone(&self.sem),
1434            self.state.config.graph.retries,
1435            &advisor_roster,
1436            &ctx,
1437            &mut quota_losses,
1438            &mut self.state,
1439            &|p: &Proposal| p.validate(),
1440        )
1441        .await;
1442        self.state.quota.extend(quota_losses);
1443
1444        let mut records = Vec::with_capacity(results.len());
1445        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
1446            let agent_id = seat.agent.clone();
1447            self.state.seats.insert(seat.key.clone(), seat);
1448            match res {
1449                Ok((proposal, out)) => {
1450                    self.state
1451                        .event("advise", format!("advisor-{} proposed a design", i + 1));
1452                    records.push(advise::AdvisorRecord::proposed(
1453                        i + 1,
1454                        agent_id,
1455                        proposal,
1456                        out.duration_ms,
1457                    ));
1458                }
1459                Err(e) => {
1460                    self.state.event(
1461                        "advise",
1462                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
1463                    );
1464                    records.push(advise::AdvisorRecord::failed(
1465                        i + 1,
1466                        agent_id,
1467                        e.to_string(),
1468                    ));
1469                }
1470            }
1471        }
1472
1473        let mut advice = advise::Advice {
1474            records,
1475            synthesis: None,
1476        };
1477        if advice.proposals().is_empty() {
1478            self.state.event(
1479                "advise",
1480                "no advisor produced a usable proposal; continuing without a \
1481                 synthesis brief"
1482                    .to_owned(),
1483            );
1484        } else {
1485            match self
1486                .synthesize_brief(
1487                    &advice,
1488                    &instruction,
1489                    &language,
1490                    &worktrees[0],
1491                    &artifacts,
1492                    &run_id,
1493                    &prompts,
1494                    cache.as_deref(),
1495                )
1496                .await
1497            {
1498                Ok(Some(text)) => {
1499                    self.state.event(
1500                        "advise",
1501                        "synthesized a design brief for the implementer".to_owned(),
1502                    );
1503                    advice.synthesis = Some(text);
1504                }
1505                Ok(None) => {
1506                    self.state.event(
1507                        "advise",
1508                        "the synthesis seat produced nothing usable; continuing \
1509                         without a design brief"
1510                            .to_owned(),
1511                    );
1512                }
1513                Err(e) => {
1514                    self.state.event(
1515                        "advise",
1516                        format!("could not synthesize a design brief: {e:#}"),
1517                    );
1518                }
1519            }
1520        }
1521        advise::apply_reflection(&mut advice);
1522
1523        self.state.advice = Some(advice);
1524        self.state.advise_attempted = true;
1525        self.state.save()?;
1526        Ok(())
1527    }
1528
1529    /// The synthesis seat: reads every advisor's proposal and blends them
1530    /// into the design brief `advise` stores on [`RunState::advice`]. Split
1531    /// out of [`Runner::advise`] only for readability — it is not called
1532    /// anywhere else.
1533    ///
1534    /// Picked the same way [`crate::talk`]'s standing conversation and
1535    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
1536    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
1537    /// order (a claude seat, else the first runnable agent in roster order)
1538    /// used when that field is unset — see `[roles] synthesizer`'s own doc
1539    /// in [`crate::config`] for why a dedicated field exists here at all.
1540    #[allow(clippy::too_many_arguments)]
1541    async fn synthesize_brief(
1542        &mut self,
1543        advice: &advise::Advice,
1544        instruction: &str,
1545        language: &str,
1546        cwd: &Path,
1547        artifacts: &Path,
1548        run_id: &str,
1549        prompts: &Prompts,
1550        cache: Option<&Path>,
1551    ) -> Result<Option<String>> {
1552        let chain = agent::pick_chain(
1553            &self.state.config.agents,
1554            self.state.config.roles.synthesizer.as_ref(),
1555            &agent::installed,
1556            "synthesizer",
1557        )?;
1558        let proposals = advice.proposals();
1559        let mut prompt = prompt::with_overlay(
1560            prompt::synthesize_brief(instruction, &proposals, language),
1561            prompts.overlay("advise"),
1562        );
1563        if cache.is_some() {
1564            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
1565            // below — see `prompt::build_cache_note`'s doc for why telling a
1566            // read-only seat to build through the shared cache is exactly how
1567            // a sandbox's write refusal gets misread as a defect.
1568            prompt.push('\n');
1569            prompt.push_str(&prompt::build_cache_note("advise", false));
1570        }
1571        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
1572        // Each id is tried once, in order; a quota hit, error or unusable
1573        // answer moves to the next. The seat is single-turn (`sessions:
1574        // false`) and the prompt is the whole context, so a fallback agent
1575        // needs nothing carried over.
1576        let mut last = None;
1577        for (n, spec) in chain.iter().enumerate() {
1578            if n > 0 {
1579                self.state
1580                    .event("advise", format!("synthesis falling back to {}", spec.id));
1581            }
1582            let mut seat = self.seat("advise-synthesis", &spec.id);
1583            let outcome = agent::invoke(
1584                spec,
1585                &mut seat,
1586                &Invocation {
1587                    cwd,
1588                    prompt: &prompt,
1589                    timeout,
1590                    allow_write: false,
1591                    sessions: false,
1592                    artifacts,
1593                    stem: &if n == 0 {
1594                        "advise-synthesis".to_owned()
1595                    } else {
1596                        format!("advise-synthesis-{}", spec.id)
1597                    },
1598                    run: run_id,
1599                    node: "advise",
1600                    cache_dir: None,
1601                    attachments: &[],
1602                    writable: &[],
1603                },
1604            )
1605            .await;
1606            if outcome.is_ok() {
1607                self.state.seats.insert(seat.key.clone(), seat);
1608            }
1609            let advance = agent::chain_advances(&outcome);
1610            last = Some(outcome);
1611            if !advance {
1612                break;
1613            }
1614        }
1615        // Exhausted: the last attempt's result is what a single failed seat
1616        // would have produced.
1617        let out = last.expect("a chain holds at least one agent")?;
1618        if !out.usable() {
1619            return Ok(None);
1620        }
1621        let text =
1622            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
1623        Ok((!text.trim().is_empty()).then_some(text))
1624    }
1625
1626    // ----------------------------------------------------------- implement
1627
1628    async fn implement(&mut self) -> Result<()> {
1629        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
1630        // agent files with `magi task add` name the run that paid for it. The
1631        // prompt overlay is cloned alongside it because the waves borrow it
1632        // while `self` is mutably borrowed by the node's own bookkeeping.
1633        let run_id = self.state.id.clone();
1634        let prompts = self.state.config.prompts.clone();
1635        let todo: Vec<usize> = self
1636            .state
1637            .candidates
1638            .iter()
1639            .enumerate()
1640            .filter(|(_, c)| c.commits == 0 && c.failed.is_none() && !c.empty)
1641            .map(|(i, _)| i)
1642            .collect();
1643        if todo.is_empty() {
1644            return self.after_implement();
1645        }
1646        self.state.status = RunStatus::Implementing;
1647
1648        let language = self.state.config.graph.language.clone();
1649        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
1650        let sessions = self.state.config.graph.sessions;
1651        let artifacts = agent::artifacts_dir(&self.state.dir());
1652        // The design-deliberation stage's blended brief, when `advise` found
1653        // one — carried into every implementer's prompt the same way
1654        // regardless of which candidate it is.
1655        let brief = self
1656            .state
1657            .advice
1658            .as_ref()
1659            .and_then(|a| a.synthesis.as_deref())
1660            .map(str::to_owned);
1661        let attachments = self.state.attachments.clone();
1662
1663        let mut jobs = Vec::new();
1664        for &i in &todo {
1665            let (index, label, worktree) = {
1666                let c = &self.state.candidates[i];
1667                (c.index, c.label, c.worktree.clone())
1668            };
1669            let spec = self.roles.implementers[index].clone();
1670            let seat_key = format!("impl-{label}");
1671            let seat = self.seat(&seat_key, &spec.id);
1672            let instruction = seeded_instruction(&self.state);
1673            jobs.push(SeatJob {
1674                spec,
1675                seat,
1676                prompt: prompt::implement(
1677                    &instruction,
1678                    &worktree.to_string_lossy(),
1679                    &language,
1680                    brief.as_deref(),
1681                    &attachments,
1682                ),
1683                cwd: worktree,
1684                timeout,
1685                allow_write: true,
1686                sessions,
1687                artifacts: artifacts.clone(),
1688                stem: format!("impl-{label}"),
1689                handover: None,
1690            });
1691        }
1692
1693        self.state.event(
1694            "implement",
1695            format!("{} candidates in parallel", jobs.len()),
1696        );
1697        // Kept so a seat whose CLI hung up can be asked again from the same
1698        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
1699        // can update a seat's own entry once a fallback agent takes it over —
1700        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
1701        // whichever agent actually answered, not the one that quota'd out.
1702        let mut sent = jobs.clone();
1703        let cache = self.state.config.cache_dir();
1704        let ctx = WaveCtx {
1705            carry_seats: false,
1706            run: &run_id,
1707            node: "implement",
1708            prompts: &prompts,
1709            cache: cache.as_deref(),
1710            round: None,
1711        };
1712        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
1713        self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
1714            .await;
1715        self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
1716            .await;
1717        self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
1718            .await;
1719
1720        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
1721            let seat_key = seat.key.clone();
1722            // A quota fallback (`resume_seat_handovers`) may have handed this
1723            // seat to a different agent than the one `prep` recorded on the
1724            // candidate; the stats tables and any later fixer-defaults-to-
1725            // winner's-author lookup must credit whoever actually answered —
1726            // unless every fallback also quota'd out, in which case nobody
1727            // actually answered and crediting the last agent tried would
1728            // erase every earlier agent's own quota loss from the stats
1729            // tables instead of just this one seat's.
1730            let agent = seat.agent.clone();
1731            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
1732            self.state.seats.insert(seat.key.clone(), seat);
1733            let label = self.state.candidates[i].label;
1734            let worktree = self.state.candidates[i].worktree.clone();
1735            let base = self.state.base_commit.clone();
1736
1737            let (summary, duration, failed, verified_claim) = match out {
1738                AgentOutcome::Ok(o) => {
1739                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
1740                    let failed = (!o.usable()).then(|| {
1741                        if o.timed_out {
1742                            "agent timed out".to_owned()
1743                        } else {
1744                            format!("agent exited with {:?}", o.exit_code)
1745                        }
1746                    });
1747                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
1748                    (text, o.duration_ms, failed, verified_claim)
1749                }
1750                // Left un-resumed by `resume_undelivered` (a dirty tree
1751                // already rescues the work, or there was no session left to
1752                // resume into) — reported like the ordinary failure it is,
1753                // never as if `o.text` (the CLI's raw error JSON) were an
1754                // answer.
1755                AgentOutcome::Dropped(o) => {
1756                    let why = o
1757                        .dropped
1758                        .as_ref()
1759                        .map(|d| d.why.as_str())
1760                        .unwrap_or("the CLI ended the stream without delivering its answer");
1761                    (
1762                        String::new(),
1763                        o.duration_ms,
1764                        Some(format!("the CLI dropped the stream ({why})")),
1765                        None,
1766                    )
1767                }
1768                AgentOutcome::Quota(o) => {
1769                    self.state.quota.push(QuotaLoss {
1770                        seat: seat_key,
1771                        node: "implement".to_owned(),
1772                        at: Timestamp::now(),
1773                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
1774                    });
1775                    (
1776                        String::new(),
1777                        o.duration_ms,
1778                        Some("rate limited (quota); produced no change".to_owned()),
1779                        None,
1780                    )
1781                }
1782                AgentOutcome::Failed(e) => (String::new(), 0, Some(e), None),
1783            };
1784
1785            // Rescue anything the agent edited but never committed: an
1786            // uncommitted candidate would silently be an empty one.
1787            let rescued = match git::rescue_commit(
1788                &worktree,
1789                &format!("magi: candidate {label} (uncommitted work)"),
1790            )
1791            .await
1792            {
1793                Ok(r) => {
1794                    self.state.note_withheld("implement", &r.withheld);
1795                    r.committed
1796                }
1797                Err(_) => false,
1798            };
1799            let commits = git::commits_ahead(&worktree, &base, "HEAD")
1800                .await
1801                .unwrap_or(0);
1802            let patch = git::diff(&worktree, &base, "HEAD")
1803                .await
1804                .unwrap_or_default();
1805            let stat = git::diff_stat(&worktree, &base, "HEAD")
1806                .await
1807                .unwrap_or_default();
1808            let files = git::changed_files(&worktree, &base, "HEAD")
1809                .await
1810                .map(|f| f.len())
1811                .unwrap_or(0);
1812            write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
1813
1814            let c = &mut self.state.candidates[i];
1815            if !exhausted_the_fallback_chain {
1816                c.agent = agent;
1817            }
1818            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
1819            c.stat = stat;
1820            c.files = files;
1821            c.commits = commits;
1822            c.duration_ms = duration;
1823            c.empty = commits == 0 || patch.trim().is_empty();
1824            // An agent that failed but still produced a committed change stays
1825            // in the running: the patch is what gets judged, not the exit code.
1826            c.failed = match failed {
1827                Some(_) if c.empty => failed,
1828                _ => None,
1829            };
1830            // Only an empty candidate can be a verified no-op: a claim next
1831            // to a real patch is not what the marker is for, and `c.failed`
1832            // being `Some` here already implies `verified_claim` was never
1833            // set (see the guard above the match that produced it).
1834            c.verified_noop = if c.empty { verified_claim } else { None };
1835            let note = match (&c.failed, c.empty, &c.verified_noop, rescued) {
1836                (Some(e), _, _, _) => format!("candidate {label}: {e}"),
1837                (None, true, Some(_), _) => {
1838                    format!("candidate {label}: no change produced (agent-verified no-op)")
1839                }
1840                (None, true, None, _) => format!("candidate {label}: no change produced"),
1841                (None, false, _, true) => {
1842                    format!(
1843                        "candidate {label}: {files} files, {commits} commits (rescued an uncommitted tree)"
1844                    )
1845                }
1846                (None, false, _, false) => {
1847                    format!("candidate {label}: {files} files, {commits} commits")
1848                }
1849            };
1850            self.state.event("implement", note);
1851            self.state.save()?;
1852        }
1853
1854        self.after_implement()
1855    }
1856
1857    /// Ask again, once, for work a CLI did and then failed to hand over.
1858    ///
1859    /// [`agent::dropped_stream`] recognises the one shape observed: an error
1860    /// status with an empty response and a usage report showing output tokens,
1861    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
1862    /// seven minutes and 14,267 output tokens that arrived as an empty
1863    /// candidate, because `agy`'s own subscriber fell behind and hung up.
1864    ///
1865    /// Two conditions, and both matter:
1866    ///
1867    /// - **Only when the tree is untouched.** Often the agent has already
1868    ///   written its files and only the closing message was lost; the rescue
1869    ///   commit below picks that up and there is nothing to ask for. Re-asking
1870    ///   then would pay for a second implementation of work already on disk.
1871    /// - **Once.** A CLI that drops one stream can drop the next, and this
1872    ///   node is the most expensive in the graph.
1873    ///
1874    /// The re-ask is a resume, not a re-run: `has_context` is true because the
1875    /// dropped reply still carried its `conversation_id`, so the seat is asked
1876    /// to finish what it was doing rather than sent the whole task again. It
1877    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
1878    /// node's - for the same reason a re-ranked judge does: restating finished
1879    /// work is not the work.
1880    ///
1881    /// Unlike a quota this is worth retrying at all: a rate limit fails the
1882    /// same way until it resets, while an abandoned conversation is still
1883    /// there to be picked up.
1884    async fn resume_undelivered(
1885        &mut self,
1886        results: &mut [(usize, SeatState, AgentOutcome)],
1887        sent: &[SeatJob],
1888        prompts: &Prompts,
1889        run_id: &str,
1890    ) {
1891        for (wi, seat, out) in results.iter_mut() {
1892            let Some(dropped) = (match &*out {
1893                AgentOutcome::Dropped(o) => o.dropped.clone(),
1894                _ => None,
1895            }) else {
1896                continue;
1897            };
1898            let Some(job) = sent.get(*wi) else { continue };
1899            // Already on disk? Then only the closing message was lost.
1900            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
1901                self.state.event(
1902                    "implement",
1903                    format!(
1904                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
1905                         work is in the tree",
1906                        seat.key, dropped.output_tokens, dropped.why
1907                    ),
1908                );
1909                continue;
1910            }
1911            // The re-ask only makes sense as a resume: `resume_after_drop`
1912            // says nothing about the task, trusting the seat to still hold it.
1913            // Without a session to resume — sessions disabled, or this CLI's
1914            // drop shape happened not to carry a session id — that prompt
1915            // would open a brand-new conversation with no context at all,
1916            // which is worse than leaving this as the ordinary failure it
1917            // already is.
1918            if !has_context(&job.spec, seat, job.sessions) {
1919                self.state.event(
1920                    "implement",
1921                    format!(
1922                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
1923                         is no session left to resume",
1924                        seat.key, dropped.output_tokens, dropped.why
1925                    ),
1926                );
1927                continue;
1928            }
1929            self.state.event(
1930                "implement",
1931                format!(
1932                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
1933                     conversation",
1934                    seat.key, dropped.output_tokens, dropped.why
1935                ),
1936            );
1937            let mut retry = job.clone();
1938            retry.seat = seat.clone();
1939            retry.prompt = prompt::resume_after_drop(&dropped.why);
1940            retry.timeout = retry_budget(job.timeout, true);
1941            retry.stem = format!("{}-resume", job.stem);
1942            let cache = self.state.config.cache_dir();
1943            let ctx = WaveCtx {
1944                carry_seats: false,
1945                run: run_id,
1946                node: "implement",
1947                prompts,
1948                cache: cache.as_deref(),
1949                round: None,
1950            };
1951            let (resumed_seat, resumed) =
1952                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
1953            *seat = resumed_seat;
1954            *out = resumed;
1955        }
1956    }
1957
1958    /// Fall an implement seat through to the next untried agent in the
1959    /// implementer roster when it lost to quota — or, since the handover was
1960    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
1961    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
1962    /// quota path itself being unchanged — instead of leaving the
1963    /// seat's loss final the moment one agent's account runs dry.
1964    ///
1965    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
1966    /// are the motivating case: `Config::resolve_roles`'s `implementers`
1967    /// truncates to the single slot rotation picked, so a solo task whose one
1968    /// implementer hits quota mid-run used to have nothing else to try. This
1969    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
1970    /// unrotated roster — which is the only place the *other* candidates in
1971    /// the machine's roster still exist once `implementers` has been cut down
1972    /// to size.
1973    ///
1974    /// Walks forward from just past the seat's own original position in the
1975    /// roster, never wrapping back to the front: a later candidate slot (say
1976    /// `beta`, the roster's second entry) must fall through to the *next*
1977    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
1978    /// almost certainly a different candidate's own agent already — and once
1979    /// the roster's tail is exhausted there is nothing left to fall through
1980    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
1981    /// whole [`AgentSpec`]: a roster with the same id named twice must not
1982    /// let this retry that id forever. The loop keeps falling through until
1983    /// an attempt lands something other than `Quota` or the roster's tail
1984    /// runs out of untried ids, at which point the seat is left exactly as
1985    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
1986    /// `QuotaLoss` recorded, the candidate failed/empty.
1987    ///
1988    /// `sent` is taken mutably and updated with the fallback agent's spec:
1989    /// `resume_unconfirmed_commands`, which runs after this and also reads
1990    /// `sent`, must see whichever agent actually ended up answering the seat
1991    /// — reading the stale, original spec there would check session
1992    /// eligibility against the wrong CLI and could hand a fallback agent's
1993    /// session id to the agent that just lost the seat to quota.
1994    ///
1995    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
1996    /// — `self.seat` only reuses state when the agent id is unchanged, so
1997    /// handing it a different id already gets this for free. Reusing the old
1998    /// seat would resume a different CLI's session as if it were a
1999    /// continuation of this one.
2000    ///
2001    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
2002    /// a quota loss cuts an agent off mid-turn, so anything already in the
2003    /// tree is unfinished work, not a completed candidate a re-ask would pay
2004    /// for twice. A dirty tree is rescued into a commit first (the same
2005    /// neutral-identity rescue `implement`'s own outcome loop gives every
2006    /// candidate) so the next agent starts clean.
2007    ///
2008    /// The new agent gets the implementer's full prompt and full
2009    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
2010    /// it has no session and no context, and is implementing the task from
2011    /// nothing, unlike a resumed drop which is only restating work already
2012    /// done.
2013    ///
2014    /// Every intermediate `Quota` this loop absorbs is folded into a plain
2015    /// `implement` event, never into `self.state.quota` — that is what
2016    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
2017    /// go unspent, and a seat that ultimately recovered on its second or
2018    /// third agent is not the stalled panel that check exists to catch. Only
2019    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
2020    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
2021    /// outcome loop already has — this helper never pushes to it itself.
2022    async fn resume_seat_handovers(
2023        &mut self,
2024        results: &mut [(usize, SeatState, AgentOutcome)],
2025        sent: &mut [SeatJob],
2026        prompts: &Prompts,
2027        run_id: &str,
2028    ) {
2029        let instruction = seeded_instruction(&self.state);
2030        let language = self.state.config.graph.language.clone();
2031        let brief = self
2032            .state
2033            .advice
2034            .as_ref()
2035            .and_then(|a| a.synthesis.as_deref())
2036            .map(str::to_owned);
2037        let attachments = self.state.attachments.clone();
2038        for (wi, seat, out) in results.iter_mut() {
2039            // Who holds the other candidate seats of this wave right now
2040            // (earlier handovers already written back to `sent`).
2041            let others: BTreeSet<String> = sent
2042                .iter()
2043                .enumerate()
2044                .filter(|(j, _)| j != wi)
2045                .map(|(_, j)| j.spec.id.clone())
2046                .collect();
2047            let Some(job) = sent.get_mut(*wi) else {
2048                continue;
2049            };
2050            // Where the seat's own original agent sits in the roster — the
2051            // fallback walk starts just past here, never at the front, so a
2052            // later candidate slot's quota loss does not fall back onto an
2053            // earlier slot's own agent.
2054            let start = self
2055                .roles
2056                .implementer_roster
2057                .iter()
2058                .position(|s| s.id == job.spec.id)
2059                .unwrap_or(0);
2060            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
2061            let mut fallback_attempt = 0usize;
2062            let mut prev: Option<FailClass> = None;
2063            while let Some(cur) = FailClass::of(&*out) {
2064                if !should_hand_over(prev.as_ref(), &cur) {
2065                    break;
2066                }
2067                let Some(next) =
2068                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
2069                        .cloned()
2070                else {
2071                    break;
2072                };
2073                tried.insert(next.id.clone());
2074                fallback_attempt += 1;
2075
2076                if let Ok(r) = git::rescue_commit(
2077                    &job.cwd,
2078                    &format!(
2079                        "magi: candidate {} (uncommitted work before {} fallback)",
2080                        seat.key,
2081                        if cur == FailClass::Quota {
2082                            "quota"
2083                        } else {
2084                            "handover"
2085                        }
2086                    ),
2087                )
2088                .await
2089                {
2090                    self.state.note_withheld("implement", &r.withheld);
2091                }
2092
2093                record_handover(
2094                    &mut self.state,
2095                    "implement",
2096                    &seat.key,
2097                    &seat.agent,
2098                    &next.id,
2099                    &cur,
2100                    &fail_reason(&*out),
2101                );
2102                prev = Some(cur.clone());
2103
2104                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
2105                self.state.seats.insert(seat.key.clone(), new_seat.clone());
2106                // Kept in sync on `sent` itself, not just the local retry: a
2107                // later helper (`resume_unconfirmed_commands`) reads `sent`
2108                // after this one returns and must see whichever agent is now
2109                // occupying the seat, not the one that just quota'd out —
2110                // otherwise it would judge session/continuation eligibility
2111                // by the wrong CLI and could resend a fallback's session id
2112                // to the agent that lost it the seat in the first place.
2113                job.spec = next.clone();
2114                let mut retry = job.clone();
2115                retry.seat = new_seat;
2116                retry.prompt = prompt::implement(
2117                    &instruction,
2118                    &job.cwd.to_string_lossy(),
2119                    &language,
2120                    brief.as_deref(),
2121                    &attachments,
2122                );
2123                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
2124                let cache = self.state.config.cache_dir();
2125                let ctx = WaveCtx {
2126                    carry_seats: false,
2127                    run: run_id,
2128                    node: "implement",
2129                    prompts,
2130                    cache: cache.as_deref(),
2131                    round: None,
2132                };
2133                let (fallback_seat, fallback_out) = run_one(
2134                    retry,
2135                    Arc::clone(&self.sem),
2136                    &ctx,
2137                    &mut self.state,
2138                    fallback_attempt,
2139                )
2140                .await;
2141                *seat = fallback_seat;
2142                *out = fallback_out;
2143            }
2144        }
2145    }
2146
2147    /// Ask an implement seat's own CLI to confirm what it started, once, when
2148    /// its reply reported a command whose completion status it never
2149    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
2150    /// that does and does not mean.
2151    ///
2152    /// The completion contract this task asks for, extended to `implement`
2153    /// with the same signal `continue_fix_report` reads for the fixer,
2154    /// rather than a keyword search over the reply or a hard requirement on
2155    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
2156    /// a candidate's CLI turn ended cleanly while a test run it had started
2157    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
2158    /// named in it at all is untouched by this: `commands` is empty, so
2159    /// there is nothing to be unconfirmed.
2160    ///
2161    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
2162    /// this is not about recovering edits that might already be on disk, it
2163    /// is about a result the seat itself never vouched for, which resuming
2164    /// asks for regardless of what the tree already holds. Bounded to one
2165    /// attempt for the same reason `resume_undelivered` is — this is the
2166    /// most expensive node in the graph — and a seat that still cannot
2167    /// confirm on that attempt is left as whatever its (possibly still
2168    /// unconfirmed) reply says; this does not invent a new "failed" reason
2169    /// for a candidate that otherwise produced a real, committed change.
2170    async fn resume_unconfirmed_commands(
2171        &mut self,
2172        results: &mut [(usize, SeatState, AgentOutcome)],
2173        sent: &[SeatJob],
2174        prompts: &Prompts,
2175        run_id: &str,
2176    ) {
2177        for (wi, seat, out) in results.iter_mut() {
2178            let AgentOutcome::Ok(o) = &*out else {
2179                continue;
2180            };
2181            if !has_unconfirmed_command(&o.commands) {
2182                continue;
2183            }
2184            let Some(job) = sent.get(*wi) else { continue };
2185            if !has_context(&job.spec, seat, job.sessions) {
2186                self.state.event(
2187                    "implement",
2188                    format!(
2189                        "{}: the reply named a command whose own CLI never confirmed the exit \
2190                         status of, but there is no session left to resume",
2191                        seat.key
2192                    ),
2193                );
2194                continue;
2195            }
2196            self.state.event(
2197                "implement",
2198                format!(
2199                    "{}: the reply named a command whose own CLI never confirmed the exit \
2200                     status of; resuming the conversation",
2201                    seat.key
2202                ),
2203            );
2204            let mut retry = job.clone();
2205            retry.seat = seat.clone();
2206            retry.prompt = prompt::resume_incomplete(
2207                "a command in your last reply had no confirmed exit status",
2208            );
2209            retry.timeout = retry_budget(job.timeout, true);
2210            retry.stem = format!("{}-confirm", job.stem);
2211            let cache = self.state.config.cache_dir();
2212            let ctx = WaveCtx {
2213                carry_seats: false,
2214                run: run_id,
2215                node: "implement",
2216                prompts,
2217                cache: cache.as_deref(),
2218                round: None,
2219            };
2220            let (resumed_seat, resumed) =
2221                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
2222            *seat = resumed_seat;
2223            *out = resumed;
2224        }
2225    }
2226
2227    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
2228    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
2229    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
2230    /// that motivated this.
2231    ///
2232    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
2233    /// own nudge loop already covers for judge/review/vote seats, and not a
2234    /// dropped stream, which [`Runner::resume_undelivered`] covers for
2235    /// implement seats: here the CLI turn genuinely finished while the node's
2236    /// own work — the fixer's account of what it did — had not. Gated purely
2237    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
2238    /// reply, never on any wording in it, so a fixer whose valid, first-try
2239    /// `FixReport` happens to mention having waited on a background test is
2240    /// never resumed — the `Ok(report)` branch at the call site returns
2241    /// before this is ever invoked.
2242    ///
2243    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
2244    /// attempt ([`retry_budget`]), nothing attempted once the session is
2245    /// gone, and a quota hit ends the loop immediately rather than retrying a
2246    /// rate limit that fails the same way again.
2247    async fn continue_fix_report(
2248        &mut self,
2249        mut seat: SeatState,
2250        parse_err: String,
2251        job: &SeatJob,
2252        prompts: &Prompts,
2253        run_id: &str,
2254        round: usize,
2255    ) -> (
2256        SeatState,
2257        Option<FixReport>,
2258        Option<String>,
2259        ContinuationRecord,
2260    ) {
2261        let mut last_err = parse_err;
2262        let mut cumulative_wait_ms = 0u64;
2263        let mut attempts = 0usize;
2264        loop {
2265            if !has_context(&job.spec, &seat, job.sessions) {
2266                self.state.event(
2267                    "fix",
2268                    format!(
2269                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
2270                         session left to resume into"
2271                    ),
2272                );
2273                let outcome = if attempts == 0 {
2274                    ContinuationOutcome::NoSession
2275                } else {
2276                    ContinuationOutcome::Exhausted
2277                };
2278                return (
2279                    seat,
2280                    None,
2281                    Some(format!("unparsable fix report: {last_err}")),
2282                    ContinuationRecord {
2283                        attempts,
2284                        cumulative_wait_ms,
2285                        outcome,
2286                    },
2287                );
2288            }
2289            if attempts >= MAX_FIX_CONTINUATIONS {
2290                self.state.event(
2291                    "fix",
2292                    format!(
2293                        "round {round}: fixer's reply still had no adoption report after \
2294                         {attempts} continuation(s) ({last_err}); giving up"
2295                    ),
2296                );
2297                return (
2298                    seat,
2299                    None,
2300                    Some(format!(
2301                        "unparsable fix report after {attempts} continuation(s): {last_err}"
2302                    )),
2303                    ContinuationRecord {
2304                        attempts,
2305                        cumulative_wait_ms,
2306                        outcome: ContinuationOutcome::Exhausted,
2307                    },
2308                );
2309            }
2310            attempts += 1;
2311            self.state.event(
2312                "fix",
2313                format!(
2314                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
2315                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
2316                ),
2317            );
2318            let mut retry = job.clone();
2319            retry.seat = seat.clone();
2320            retry.prompt = prompt::resume_incomplete(&last_err);
2321            retry.timeout = retry_budget(job.timeout, true);
2322            retry.stem = format!("{}-continue{attempts}", job.stem);
2323            let cache = self.state.config.cache_dir();
2324            let ctx = WaveCtx {
2325                carry_seats: false,
2326                run: run_id,
2327                node: "fix",
2328                prompts,
2329                cache: cache.as_deref(),
2330                round: Some(round),
2331            };
2332            let (resumed_seat, resumed_out) = run_one(
2333                retry,
2334                Arc::clone(&self.sem),
2335                &ctx,
2336                &mut self.state,
2337                attempts,
2338            )
2339            .await;
2340            seat = resumed_seat;
2341            match resumed_out {
2342                AgentOutcome::Ok(o) => {
2343                    cumulative_wait_ms += o.duration_ms;
2344                    match verdict::extract_json::<FixReport>(&o.text) {
2345                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
2346                            self.state.event(
2347                                "fix",
2348                                format!(
2349                                    "round {round}: fixer's adoption report recovered after \
2350                                     {attempts} continuation(s)"
2351                                ),
2352                            );
2353                            return (
2354                                seat,
2355                                Some(report),
2356                                None,
2357                                ContinuationRecord {
2358                                    attempts,
2359                                    cumulative_wait_ms,
2360                                    outcome: ContinuationOutcome::Resumed,
2361                                },
2362                            );
2363                        }
2364                        // The report parsed, but this same reply's own
2365                        // CommandEvidence — the identical record `state.jobs`
2366                        // renders — names a command whose CLI never
2367                        // confirmed an exit status. Read together, that is
2368                        // not a resolved answer: keep nudging rather than
2369                        // accept a report standing next to a command the
2370                        // seat's own CLI cannot vouch for.
2371                        Ok(_) => {
2372                            last_err = "the reply parsed, but it reported a command whose own CLI \
2373                                 never confirmed an exit status"
2374                                .to_owned();
2375                        }
2376                        Err(e) => last_err = e.to_string(),
2377                    }
2378                }
2379                AgentOutcome::Quota(o) => {
2380                    cumulative_wait_ms += o.duration_ms;
2381                    self.state.quota.push(QuotaLoss {
2382                        seat: seat.key.clone(),
2383                        node: "fix".to_owned(),
2384                        at: Timestamp::now(),
2385                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
2386                    });
2387                    self.state.event(
2388                        "fix",
2389                        format!(
2390                            "round {round}: continuation rate limited (quota); not retrying now"
2391                        ),
2392                    );
2393                    return (
2394                        seat,
2395                        None,
2396                        Some("rate limited (quota) while recovering the fix report".to_owned()),
2397                        ContinuationRecord {
2398                            attempts,
2399                            cumulative_wait_ms,
2400                            outcome: ContinuationOutcome::QuotaLost,
2401                        },
2402                    );
2403                }
2404                AgentOutcome::Dropped(o) => {
2405                    cumulative_wait_ms += o.duration_ms;
2406                    let why = o
2407                        .dropped
2408                        .as_ref()
2409                        .map(|d| d.why.as_str())
2410                        .unwrap_or("the CLI ended the stream without delivering its answer");
2411                    last_err = format!("the CLI dropped the stream ({why})");
2412                }
2413                AgentOutcome::Failed(e) => last_err = e,
2414            }
2415        }
2416    }
2417
2418    fn after_implement(&mut self) -> Result<()> {
2419        // Scan every candidate patch once the set is complete.
2420        if self.state.leaks.is_empty() {
2421            let cfg = self.state.config.blind.clone();
2422            let mut leaks = Vec::new();
2423            for c in &self.state.candidates {
2424                let Some(patch) =
2425                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
2426                else {
2427                    continue;
2428                };
2429                leaks.extend(blind::scan(
2430                    &format!("candidate {} patch", c.label),
2431                    &patch,
2432                    &cfg.vendor_tokens,
2433                ));
2434            }
2435            if !leaks.is_empty() {
2436                let summary = leaks
2437                    .iter()
2438                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
2439                    .collect::<Vec<_>>()
2440                    .join(", ");
2441                match cfg.on_leak {
2442                    LeakPolicy::Fail => {
2443                        self.state.status = RunStatus::Failed;
2444                        self.state
2445                            .event("blind", format!("vendor text in a patch: {summary}"));
2446                        self.state.leaks = leaks;
2447                        self.state.save()?;
2448                        self.settle_questions();
2449                        bail!(
2450                            "blind.on_leak = \"fail\" and vendor text reached a \
2451                             judged patch: {summary}"
2452                        );
2453                    }
2454                    LeakPolicy::Redact => self.state.event(
2455                        "blind",
2456                        format!("redacting vendor text for judging: {summary}"),
2457                    ),
2458                    LeakPolicy::Warn => self.state.event(
2459                        "blind",
2460                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
2461                    ),
2462                }
2463                self.state.leaks = leaks;
2464            }
2465        }
2466
2467        if self.state.viable().is_empty() {
2468            if self.state.all_candidates_verified_noop() {
2469                // Every candidate agreed, with evidence the adoption guard
2470                // accepted, that nothing belongs in this worktree. That is
2471                // not the same fact as a candidate that simply failed to
2472                // write anything, and settling it as an ordinary `Failed`
2473                // (see `SCHEMA`'s doc for schema 10) is what let two of
2474                // task 391f's attempts burn a retry each re-discovering the
2475                // same already-landed fix. Terminal either way, so `judge`
2476                // must never run over an empty candidate set — unlike the
2477                // `Failed` branch below this returns `Ok`, not an error:
2478                // nothing here failed.
2479                self.state.status = RunStatus::VerifiedNoop;
2480                self.state.save()?;
2481                self.settle_questions();
2482                return Ok(());
2483            }
2484            self.state.status = RunStatus::Failed;
2485            self.state.save()?;
2486            self.settle_questions();
2487            bail!("no candidate produced a change; nothing to judge");
2488        }
2489        self.state.status = RunStatus::Judging;
2490        self.state.save()?;
2491        Ok(())
2492    }
2493
2494    // --------------------------------------------------------------- judge
2495
2496    async fn judge(&mut self) -> Result<()> {
2497        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2498        // agent files with `magi task add` name the run that paid for it. The
2499        // prompt overlay is cloned alongside it because the waves borrow it
2500        // while `self` is mutably borrowed by the node's own bookkeeping.
2501        let run_id = self.state.id.clone();
2502        let prompts = self.state.config.prompts.clone();
2503        if !self.state.judgements.is_empty() || self.state.judge_skipped {
2504            return Ok(());
2505        }
2506        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2507        if viable.len() == 1 {
2508            // Recorded so this is a one-time event: `judgements` stays empty
2509            // either way, which without this flag is indistinguishable from
2510            // "not yet judged" on the next reentry — and status is left
2511            // untouched, so a later node's conclusion (e.g. `Blocked` after
2512            // the review budget ran out) survives a resume instead of being
2513            // clobbered back to `Judging` by this node running again.
2514            self.state.judge_skipped = true;
2515            self.state.event(
2516                "judge",
2517                format!(
2518                    "only candidate {} produced a change; judging skipped",
2519                    viable[0].label
2520                ),
2521            );
2522            self.state.save()?;
2523            return Ok(());
2524        }
2525        self.state.status = RunStatus::Judging;
2526
2527        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
2528        let language = self.state.config.graph.language.clone();
2529        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2530        let sessions = self.state.config.graph.sessions;
2531        let artifacts = agent::artifacts_dir(&self.state.dir());
2532        let root = self.state.worktree_root();
2533        let base_short = short(&self.state.base_commit);
2534
2535        let mut jobs = Vec::new();
2536        let mut orders = Vec::new();
2537        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2538            let order = blind::presentation_order(viable.len(), j, self.state.seed);
2539            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
2540            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
2541            let seat_key = format!("judge-{}", j + 1);
2542            let seat = self.seat(&seat_key, &spec.id);
2543            jobs.push(SeatJob {
2544                prompt: prompt::judge(
2545                    &self.state.instruction,
2546                    &views,
2547                    self.roles.judges.len(),
2548                    &base_short,
2549                    &language,
2550                ),
2551                spec,
2552                seat,
2553                cwd: root.join(format!("judge-{}", j + 1)),
2554                timeout,
2555                allow_write: false,
2556                sessions,
2557                artifacts: artifacts.clone(),
2558                stem: format!("judge-{}", j + 1),
2559                handover: None,
2560            });
2561        }
2562
2563        self.state.event(
2564            "judge",
2565            format!(
2566                "{} judges ranking {} candidates blind",
2567                jobs.len(),
2568                viable.len()
2569            ),
2570        );
2571        let labels_for_check = labels.clone();
2572        let mut quota_losses = Vec::new();
2573        let cache = self.state.config.cache_dir();
2574        let ctx = WaveCtx {
2575            carry_seats: false,
2576            run: &run_id,
2577            node: "judge",
2578            prompts: &prompts,
2579            cache: cache.as_deref(),
2580            round: None,
2581        };
2582        let results = ask_json_wave::<Ranking>(
2583            jobs,
2584            Arc::clone(&self.sem),
2585            self.state.config.graph.retries,
2586            &self.roles.judge_roster,
2587            &ctx,
2588            &mut quota_losses,
2589            &mut self.state,
2590            &move |r: &Ranking| r.validate(&labels_for_check),
2591        )
2592        .await;
2593        self.state.quota.extend(quota_losses);
2594
2595        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
2596            let agent_id = seat.agent.clone();
2597            self.state.seats.insert(seat.key.clone(), seat);
2598            let mut record = Judgement {
2599                judge: j + 1,
2600                seat: format!("judge-{}", j + 1),
2601                agent: agent_id,
2602                ranking: Vec::new(),
2603                reasons: BTreeMap::new(),
2604                confidence: None,
2605                order: orders[j].clone(),
2606                failed: None,
2607                duration_ms: 0,
2608            };
2609            match res {
2610                Ok((ranking, out)) => {
2611                    record.ranking = ranking.normalized();
2612                    record.reasons = ranking.reasons;
2613                    record.confidence = ranking.confidence;
2614                    record.duration_ms = out.duration_ms;
2615                    self.state.event(
2616                        "judge",
2617                        format!(
2618                            "judge {} ranked {}",
2619                            j + 1,
2620                            record.ranking.iter().collect::<String>()
2621                        ),
2622                    );
2623                }
2624                Err(e) => {
2625                    record.failed = Some(e.to_string());
2626                    self.state
2627                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
2628                }
2629            }
2630            self.state.judgements.push(record);
2631            self.state.save()?;
2632        }
2633        Ok(())
2634    }
2635
2636    // ---------------------------------------------------------- deliberate
2637
2638    async fn deliberate(&mut self) -> Result<()> {
2639        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2640        // agent files with `magi task add` name the run that paid for it. The
2641        // prompt overlay is cloned alongside it because the waves borrow it
2642        // while `self` is mutably borrowed by the node's own bookkeeping.
2643        let run_id = self.state.id.clone();
2644        let prompts = self.state.config.prompts.clone();
2645        if !self.state.deliberation.is_empty() {
2646            return Ok(());
2647        }
2648        let tops: Vec<char> = self
2649            .state
2650            .judgements
2651            .iter()
2652            .filter_map(|j| j.ranking.first().copied())
2653            .collect();
2654        let rounds = self.state.config.graph.deliberate_rounds;
2655        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
2656            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
2657                self.state.event(
2658                    "deliberate",
2659                    format!("judges agreed on {} outright; no deliberation", tops[0]),
2660                );
2661            }
2662            self.state.status = RunStatus::Voting;
2663            self.state.save()?;
2664            return Ok(());
2665        }
2666
2667        self.state.status = RunStatus::Deliberating;
2668        self.state.event(
2669            "deliberate",
2670            format!(
2671                "split: first choices were {} — opening {rounds} round(s)",
2672                tops.iter().collect::<String>()
2673            ),
2674        );
2675
2676        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2677        let language = self.state.config.graph.language.clone();
2678        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2679        let sessions = self.state.config.graph.sessions;
2680        let artifacts = agent::artifacts_dir(&self.state.dir());
2681        let root = self.state.worktree_root();
2682        let base_short = short(&self.state.base_commit);
2683
2684        // Judges argue in sequence so that a turn can answer the one before it;
2685        // that is the difference between deliberation and three parallel
2686        // monologues.
2687        for round in 1..=rounds {
2688            let mut turns: Vec<DeliberationTurn> = Vec::new();
2689            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2690                if self.state.judgements[j].failed.is_some() {
2691                    continue;
2692                }
2693                let seat_key = format!("judge-{}", j + 1);
2694                let spec = self.occupant(&seat_key, spec);
2695                let mut seat = self.seat(&seat_key, &spec.id);
2696                let transcript = self.transcript(&turns, j);
2697                let build = |context: Option<&str>| {
2698                    prompt::deliberate(
2699                        &self.state.instruction,
2700                        context,
2701                        &transcript,
2702                        round,
2703                        rounds,
2704                        &language,
2705                    )
2706                };
2707                let block = self.candidate_block(&viable, &base_short);
2708                let full = build(Some(&block));
2709                let text = if has_context(&spec, &seat, sessions) {
2710                    build(None)
2711                } else {
2712                    full.clone()
2713                };
2714                let job = SeatJob {
2715                    spec,
2716                    seat: seat.clone(),
2717                    prompt: text,
2718                    cwd: root.join(format!("judge-{}", j + 1)),
2719                    timeout,
2720                    allow_write: false,
2721                    sessions,
2722                    artifacts: artifacts.clone(),
2723                    stem: format!("delib-{round}-judge-{}", j + 1),
2724                    handover: Some(full),
2725                };
2726                let cache = self.state.config.cache_dir();
2727                let ctx = WaveCtx {
2728                    carry_seats: false,
2729                    run: &run_id,
2730                    node: "deliberate",
2731                    prompts: &prompts,
2732                    cache: cache.as_deref(),
2733                    round: None,
2734                };
2735                // A turn is never nudged (`retries` 0): a failed seat is
2736                // handed to the next roster agent, which gets the full
2737                // context. An empty answer is a turn, not a failure.
2738                let mut losses = Vec::new();
2739                let mut results = ask_wave_with::<String>(
2740                    vec![job],
2741                    Arc::clone(&self.sem),
2742                    0,
2743                    &self.roles.judge_roster,
2744                    &ctx,
2745                    &mut losses,
2746                    &mut self.state,
2747                    &|text: &str| {
2748                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
2749                    },
2750                )
2751                .await;
2752                self.state.quota.extend(losses);
2753                let (updated, res, _) = results.pop().expect("one job in, one result out");
2754                seat = updated;
2755                let agent_id = seat.agent.clone();
2756                self.state.seats.insert(seat.key.clone(), seat);
2757                let body = match res {
2758                    Ok((body, _)) => body,
2759                    // Skip the seat; a CLI's raw error JSON is never read as
2760                    // this judge's position.
2761                    Err(e) => {
2762                        self.state
2763                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
2764                        continue;
2765                    }
2766                };
2767                let tentative = verdict::extract_json::<Position>(&body)
2768                    .ok()
2769                    .and_then(|p| p.tentative)
2770                    .and_then(|s| s.trim().chars().next())
2771                    .map(|c| c.to_ascii_uppercase());
2772                self.state.event(
2773                    "deliberate",
2774                    format!(
2775                        "round {round}: judge {} now favours {}",
2776                        j + 1,
2777                        tentative.map_or("—".to_owned(), |c| c.to_string())
2778                    ),
2779                );
2780                turns.push(DeliberationTurn {
2781                    judge: j + 1,
2782                    agent: agent_id,
2783                    body: blind::sanitize_prose(&body, &self.state.config.blind),
2784                    tentative,
2785                });
2786            }
2787            self.state
2788                .deliberation
2789                .push(DeliberationRound { round, turns });
2790            self.state.save()?;
2791        }
2792
2793        self.state.status = RunStatus::Voting;
2794        self.state.save()?;
2795        Ok(())
2796    }
2797
2798    // ---------------------------------------------------------------- vote
2799
2800    async fn vote(&mut self) -> Result<()> {
2801        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2802        // agent files with `magi task add` name the run that paid for it. The
2803        // prompt overlay is cloned alongside it because the waves borrow it
2804        // while `self` is mutably borrowed by the node's own bookkeeping.
2805        let run_id = self.state.id.clone();
2806        let prompts = self.state.config.prompts.clone();
2807        if !self.state.votes.is_empty() {
2808            return Ok(());
2809        }
2810        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
2811        if viable.len() == 1 {
2812            return Ok(());
2813        }
2814        self.state.status = RunStatus::Voting;
2815
2816        let language = self.state.config.graph.language.clone();
2817        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2818        let sessions = self.state.config.graph.sessions;
2819        let artifacts = agent::artifacts_dir(&self.state.dir());
2820        let root = self.state.worktree_root();
2821        let base_short = short(&self.state.base_commit);
2822        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2823
2824        let mut jobs = Vec::new();
2825        let mut seats_at = Vec::new();
2826        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2827            if self
2828                .state
2829                .judgements
2830                .get(j)
2831                .is_some_and(|r| r.failed.is_some())
2832            {
2833                continue;
2834            }
2835            let seat_key = format!("judge-{}", j + 1);
2836            let spec = self.occupant(&seat_key, spec);
2837            let seat = self.seat(&seat_key, &spec.id);
2838            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
2839            let text = if has_context(&spec, &seat, sessions) {
2840                prompt::final_vote(&viable, &language)
2841            } else {
2842                full.clone()
2843            };
2844            jobs.push(SeatJob {
2845                spec,
2846                seat,
2847                prompt: text,
2848                cwd: root.join(format!("judge-{}", j + 1)),
2849                timeout,
2850                allow_write: false,
2851                sessions,
2852                artifacts: artifacts.clone(),
2853                stem: format!("vote-judge-{}", j + 1),
2854                handover: Some(full),
2855            });
2856            seats_at.push(j);
2857        }
2858
2859        self.state.event(
2860            "vote",
2861            format!(
2862                "collecting {} final votes one by one, privately",
2863                jobs.len()
2864            ),
2865        );
2866        let allowed = viable.clone();
2867        let mut quota_losses = Vec::new();
2868        let cache = self.state.config.cache_dir();
2869        let ctx = WaveCtx {
2870            carry_seats: false,
2871            run: &run_id,
2872            node: "vote",
2873            prompts: &prompts,
2874            cache: cache.as_deref(),
2875            round: None,
2876        };
2877        let results = ask_json_wave::<FinalVote>(
2878            jobs,
2879            Arc::clone(&self.sem),
2880            self.state.config.graph.retries,
2881            &self.roles.judge_roster,
2882            &ctx,
2883            &mut quota_losses,
2884            &mut self.state,
2885            &move |v: &FinalVote| match v.label() {
2886                Some(c) if allowed.contains(&c) => Ok(()),
2887                other => bail!("vote {other:?} is not one of {allowed:?}"),
2888            },
2889        )
2890        .await;
2891        self.state.quota.extend(quota_losses);
2892
2893        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
2894            let agent_id = seat.agent.clone();
2895            self.state.seats.insert(seat.key.clone(), seat);
2896            let initial = self
2897                .state
2898                .judgements
2899                .get(j)
2900                .and_then(|r| r.ranking.first().copied());
2901            let mut record = VoteRecord {
2902                judge: j + 1,
2903                agent: agent_id,
2904                vote: None,
2905                reason: String::new(),
2906                changed: false,
2907            };
2908            match res {
2909                Ok((v, _)) => {
2910                    record.vote = v.label();
2911                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
2912                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
2913                    self.state.event(
2914                        "vote",
2915                        format!(
2916                            "judge {} voted {}{}",
2917                            j + 1,
2918                            record.vote.unwrap_or('?'),
2919                            if record.changed { " (changed)" } else { "" }
2920                        ),
2921                    );
2922                }
2923                Err(e) => {
2924                    self.state
2925                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
2926                }
2927            }
2928            self.state.votes.push(record);
2929            self.state.save()?;
2930        }
2931        Ok(())
2932    }
2933
2934    // --------------------------------------------------------------- tally
2935
2936    fn tally(&mut self) -> Result<()> {
2937        if self.state.tally.is_some() {
2938            return Ok(());
2939        }
2940        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
2941        let tops: Vec<char> = self
2942            .state
2943            .judgements
2944            .iter()
2945            .filter_map(|j| j.ranking.first().copied())
2946            .collect();
2947        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
2948
2949        // A judge whose private vote failed still counted once, in the initial
2950        // ranking; using it beats discarding a whole seat.
2951        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
2952        let mut cast: Vec<char> = Vec::new();
2953        for (i, j) in self.state.judgements.iter().enumerate() {
2954            let vote = self
2955                .state
2956                .votes
2957                .iter()
2958                .find(|v| v.judge == i + 1)
2959                .and_then(|v| v.vote)
2960                .or_else(|| j.ranking.first().copied());
2961            if let Some(v) = vote {
2962                *first_choice.entry(v).or_insert(0) += 1;
2963                cast.push(v);
2964            }
2965        }
2966
2967        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
2968        for j in &self.state.judgements {
2969            let n = j.ranking.len();
2970            for (pos, label) in j.ranking.iter().enumerate() {
2971                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
2972            }
2973        }
2974
2975        let best = first_choice.values().copied().max().unwrap_or(0);
2976        let mut leaders: Vec<char> = first_choice
2977            .iter()
2978            .filter(|(_, v)| **v == best)
2979            .map(|(k, _)| *k)
2980            .collect();
2981        let mut tie_break = None;
2982        if leaders.len() > 1 {
2983            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
2984            let borda_leaders: Vec<char> = leaders
2985                .iter()
2986                .copied()
2987                .filter(|l| borda[l] == top_borda)
2988                .collect();
2989            tie_break = Some(if borda_leaders.len() == 1 {
2990                format!(
2991                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
2992                    leaders.len()
2993                )
2994            } else {
2995                format!(
2996                    "{} way tie on both first-choice votes and Borda points, broken by label order",
2997                    leaders.len()
2998                )
2999            });
3000            leaders = borda_leaders;
3001            leaders.sort_unstable();
3002        }
3003        let winner = *leaders
3004            .first()
3005            .or(viable.first())
3006            .context("no candidate to declare a winner from")?;
3007
3008        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
3009        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
3010        let deliberated = !self.state.deliberation.is_empty();
3011
3012        // Whose verdict is this? A rate-limited seat is absent even if it
3013        // ranked before the limit hit, so presence is measured against the
3014        // recorded losses, not just "did a ranking ever appear".
3015        let quota_seats: std::collections::BTreeSet<&str> =
3016            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
3017        let mut present = 0usize;
3018        for (i, j) in self.state.judgements.iter().enumerate() {
3019            if quota_seats.contains(j.seat.as_str()) {
3020                continue;
3021            }
3022            let ranked = !j.ranking.is_empty() && j.failed.is_none();
3023            let voted = self
3024                .state
3025                .votes
3026                .iter()
3027                .any(|v| v.judge == i + 1 && v.vote.is_some());
3028            if ranked || voted {
3029                present += 1;
3030            }
3031        }
3032        // Strict majority of the configured panel. A bare majority is real
3033        // signal we can act on, while a minority verdict must never stand in
3034        // for a healthy one. A one-candidate run needs no panel at all, and
3035        // `judges` stays `0` rather than the roster size a panel that never
3036        // sat would otherwise be credited with.
3037        let needs_quorum = viable.len() > 1;
3038        let judges_total = if needs_quorum {
3039            self.roles.judges.len()
3040        } else {
3041            0
3042        };
3043        let quorum = if needs_quorum {
3044            judges_total / 2 + 1
3045        } else {
3046            0
3047        };
3048        let met_quorum = !needs_quorum || present >= quorum;
3049        let uncontested = (!needs_quorum).then(|| {
3050            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
3051        });
3052
3053        self.state.event(
3054            "tally",
3055            match &uncontested {
3056                Some(reason) => format!("winner {winner} — {reason}"),
3057                None => format!(
3058                    "winner {winner} — votes {} | initial {} | {} changed | \
3059                     {present}/{judges_total} judges{}",
3060                    first_choice
3061                        .iter()
3062                        .map(|(k, v)| format!("{k}:{v}"))
3063                        .collect::<Vec<_>>()
3064                        .join(" "),
3065                    if unanimous_initial {
3066                        "unanimous"
3067                    } else {
3068                        "split"
3069                    },
3070                    changed_votes,
3071                    if met_quorum {
3072                        String::new()
3073                    } else {
3074                        format!(" — below quorum ({quorum} required)")
3075                    },
3076                ),
3077            },
3078        );
3079        if !met_quorum {
3080            self.state.event(
3081                "stall",
3082                format!(
3083                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
3084                     the run stops here, resumable"
3085                ),
3086            );
3087        }
3088        self.state.tally = Some(Tally {
3089            first_choice,
3090            borda,
3091            winner,
3092            rankings: tops.len(),
3093            unanimous_initial,
3094            deliberated,
3095            changed_votes,
3096            unanimous_final,
3097            tie_break,
3098            judges: judges_total,
3099            present,
3100            quorum,
3101            met_quorum,
3102            uncontested,
3103        });
3104        self.state.status = if met_quorum {
3105            RunStatus::Reviewing
3106        } else {
3107            RunStatus::Stalled
3108        };
3109        self.state.save()?;
3110        Ok(())
3111    }
3112
3113    // ------------------------------------------------------------- recover
3114
3115    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
3116    /// resumed toward completion once the transient cause clears.
3117    ///
3118    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
3119    /// it toward the quorum, which is exactly the set of seats whose absence
3120    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
3121    /// not depend on which node happened to hit the limit), or an ordinary
3122    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
3123    /// seat is never disturbed.
3124    ///
3125    /// A seat that now answers with a usable ranking is "recovered": its
3126    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
3127    /// `tally` counts it present again), and its vote re-collected. A seat that
3128    /// still fails keeps its loss and stays absent.
3129    ///
3130    /// Returns `true` when the re-tally restores the quorum (the run may proceed
3131    /// to review/gate/merge), `false` when it is still below quorum (the run
3132    /// stays `Stalled`, still resumable for a later retry).
3133    #[allow(clippy::too_many_lines)]
3134    async fn recover_stall(&mut self) -> Result<bool> {
3135        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3136        // agent files with `magi task add` name the run that paid for it. The
3137        // prompt overlay is cloned alongside it because the waves borrow it
3138        // while `self` is mutably borrowed by the node's own bookkeeping.
3139        let run_id = self.state.id.clone();
3140        let prompts = self.state.config.prompts.clone();
3141        // Absent seats = quota-lost at any node, or failed outright. Mirroring
3142        // `tally`'s presence test (rather than the old quota-judge/vote filter)
3143        // is what keeps a non-quota collapse — or a quota loss recorded at the
3144        // deliberate node — from being a permanent dead-end on `--resume`.
3145        let quota_seats: BTreeSet<&str> =
3146            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
3147        let absent: Vec<String> = self
3148            .state
3149            .judgements
3150            .iter()
3151            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
3152            .map(|j| j.seat.clone())
3153            .collect();
3154        if absent.is_empty() {
3155            return Ok(false);
3156        }
3157        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
3158        if viable.len() <= 1 {
3159            return Ok(false);
3160        }
3161        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
3162        let language = self.state.config.graph.language.clone();
3163        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
3164        let sessions = self.state.config.graph.sessions;
3165        let artifacts = agent::artifacts_dir(&self.state.dir());
3166        let root = self.state.worktree_root();
3167        let base_short = short(&self.state.base_commit);
3168        let candidates: Vec<Candidate> = viable.clone();
3169
3170        // Map each absent seat key to its 0-based position in `roles.judges`.
3171        let mut positions: Vec<usize> = absent
3172            .iter()
3173            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
3174            .collect();
3175        if positions.is_empty() {
3176            return Ok(false);
3177        }
3178        positions.sort_unstable();
3179        positions.dedup();
3180
3181        // Re-rank the lost seats, one blind prompt each.
3182        let mut judge_jobs = Vec::new();
3183        for &j in &positions {
3184            let order = blind::presentation_order(viable.len(), j, self.state.seed);
3185            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
3186            let seat_key = format!("judge-{}", j + 1);
3187            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
3188            let seat = self.seat(&seat_key, &spec.id);
3189            judge_jobs.push(SeatJob {
3190                spec,
3191                seat,
3192                prompt: prompt::judge(
3193                    &self.state.instruction,
3194                    &views,
3195                    self.roles.judges.len(),
3196                    &base_short,
3197                    &language,
3198                ),
3199                cwd: root.join(seat_key),
3200                timeout,
3201                allow_write: false,
3202                sessions,
3203                artifacts: artifacts.clone(),
3204                stem: format!("judge-{}-recover", j + 1),
3205                handover: None,
3206            });
3207        }
3208
3209        let labels_for_check = labels.clone();
3210        let mut judge_losses = Vec::new();
3211        let retries = self.state.config.graph.retries;
3212        let cache = self.state.config.cache_dir();
3213        let ctx = WaveCtx {
3214            carry_seats: false,
3215            run: &run_id,
3216            node: "judge",
3217            prompts: &prompts,
3218            cache: cache.as_deref(),
3219            round: None,
3220        };
3221        let results = ask_json_wave::<Ranking>(
3222            judge_jobs,
3223            Arc::clone(&self.sem),
3224            retries,
3225            &self.roles.judge_roster,
3226            &ctx,
3227            &mut judge_losses,
3228            &mut self.state,
3229            &move |r: &Ranking| r.validate(&labels_for_check),
3230        )
3231        .await;
3232
3233        // Refresh the judgement of every seat that ranked again.
3234        let mut recovered: BTreeSet<usize> = BTreeSet::new();
3235        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
3236            let agent_id = seat.agent.clone();
3237            self.state.seats.insert(seat.key.clone(), seat);
3238            let record = &mut self.state.judgements[j];
3239            match res {
3240                Ok((ranking, out)) => {
3241                    record.agent = agent_id;
3242                    record.ranking = ranking.normalized();
3243                    record.reasons = ranking.reasons;
3244                    record.confidence = ranking.confidence;
3245                    record.failed = None;
3246                    record.duration_ms = out.duration_ms;
3247                    recovered.insert(j);
3248                    self.state.event(
3249                        "recover",
3250                        format!("judge {} ranked again after the limit", j + 1),
3251                    );
3252                }
3253                Err(e) => {
3254                    self.state
3255                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
3256                }
3257            }
3258        }
3259
3260        // Re-ask the votes of the seats that recovered a ranking.
3261        let mut vote_jobs = Vec::new();
3262        let mut vote_pos: Vec<usize> = Vec::new();
3263        for &j in &recovered {
3264            let seat_key = format!("judge-{}", j + 1);
3265            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
3266            let seat = self.seat(&seat_key, &spec.id);
3267            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
3268            let text = if has_context(&spec, &seat, sessions) {
3269                prompt::final_vote(&labels, &language)
3270            } else {
3271                full.clone()
3272            };
3273            vote_jobs.push(SeatJob {
3274                spec,
3275                seat,
3276                prompt: text,
3277                cwd: root.join(seat_key),
3278                timeout,
3279                allow_write: false,
3280                sessions,
3281                artifacts: artifacts.clone(),
3282                stem: format!("vote-judge-{}-recover", j + 1),
3283                handover: Some(full),
3284            });
3285            vote_pos.push(j);
3286        }
3287        let allowed = labels.clone();
3288        let mut vote_losses = Vec::new();
3289        let vote_retries = self.state.config.graph.retries;
3290        let vote_cache = self.state.config.cache_dir();
3291        let ctx = WaveCtx {
3292            carry_seats: false,
3293            run: &run_id,
3294            node: "vote",
3295            prompts: &prompts,
3296            cache: vote_cache.as_deref(),
3297            round: None,
3298        };
3299        let votes = ask_json_wave::<FinalVote>(
3300            vote_jobs,
3301            Arc::clone(&self.sem),
3302            vote_retries,
3303            &self.roles.judge_roster,
3304            &ctx,
3305            &mut vote_losses,
3306            &mut self.state,
3307            &move |v: &FinalVote| match v.label() {
3308                Some(c) if allowed.contains(&c) => Ok(()),
3309                other => bail!("vote {other:?} is not one of {allowed:?}"),
3310            },
3311        )
3312        .await;
3313        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
3314            let agent_id = seat.agent.clone();
3315            self.state.seats.insert(seat.key.clone(), seat);
3316            match res {
3317                Ok((v, _)) => {
3318                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
3319                        rec.vote = v.label();
3320                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
3321                    } else {
3322                        self.state.votes.push(VoteRecord {
3323                            judge: j + 1,
3324                            agent: agent_id,
3325                            vote: v.label(),
3326                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
3327                            changed: false,
3328                        });
3329                    }
3330                    self.state.event(
3331                        "recover",
3332                        format!("judge {} voted again after the limit", j + 1),
3333                    );
3334                }
3335                Err(e) => {
3336                    self.state
3337                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
3338                }
3339            }
3340        }
3341
3342        // A seat that ranked again is present even if its re-vote failed —
3343        // `tally` falls back to the initial ranking's first choice — so clear
3344        // its quota loss. Seats that still fail keep theirs and stay absent.
3345        let recovered_keys: BTreeSet<String> = recovered
3346            .iter()
3347            .map(|&j| format!("judge-{}", j + 1))
3348            .collect();
3349        self.state
3350            .quota
3351            .retain(|q| !recovered_keys.contains(&q.seat));
3352        // A seat that hit the limit again is a fresh loss, not the old one:
3353        // replace the stale entry so the history stays one-per-seat and the
3354        // daemon can tell this attempt's loss from a previous session's.
3355        for loss in judge_losses.into_iter().chain(vote_losses) {
3356            if recovered_keys.contains(&loss.seat) {
3357                continue;
3358            }
3359            self.state.quota.retain(|q| q.seat != loss.seat);
3360            self.state.quota.push(loss);
3361        }
3362
3363        // Recompute the verdict from the refreshed panel.
3364        self.state.tally = None;
3365        self.tally()?;
3366        Ok(self
3367            .state
3368            .tally
3369            .as_ref()
3370            .map(|t| t.met_quorum)
3371            .unwrap_or(false))
3372    }
3373
3374    // ----------------------------------------------------------------- fold
3375
3376    async fn fold_losers(&mut self) -> Result<()> {
3377        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
3378            return Ok(());
3379        };
3380        let repo = self.state.repo.clone();
3381        let mut folded = Vec::new();
3382        for i in 0..self.state.candidates.len() {
3383            let c = &self.state.candidates[i];
3384            if c.label == winner || c.folded {
3385                continue;
3386            }
3387            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
3388            git::worktree_remove(&repo, &wt).await.ok();
3389            git::branch_delete(&repo, &branch).await.ok();
3390            self.state.candidates[i].folded = true;
3391            folded.push(label.to_string());
3392        }
3393        // The judges are finished; their checkouts are pure cost from here.
3394        let root = self.state.worktree_root();
3395        for j in 1..=self.roles.judges.len() {
3396            let wt = root.join(format!("judge-{j}"));
3397            if wt.exists() {
3398                git::worktree_remove(&repo, &wt).await.ok();
3399            }
3400        }
3401        // The design-deliberation stage is finished by the time a tally
3402        // exists — same reasoning as the judges above.
3403        if self.state.config.graph.advise {
3404            for k in 1..=self.state.config.graph.advisors {
3405                let wt = root.join(format!("advisor-{k}"));
3406                if wt.exists() {
3407                    git::worktree_remove(&repo, &wt).await.ok();
3408                }
3409            }
3410        }
3411        if !folded.is_empty() {
3412            self.state
3413                .event("fold", format!("folded candidates {}", folded.join(", ")));
3414            self.state.save()?;
3415        }
3416        Ok(())
3417    }
3418
3419    // ------------------------------------------------------------ base sync
3420
3421    /// Land the winner's tree on the current tip of `<remote>/<base>` before
3422    /// anything verifies it.
3423    ///
3424    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
3425    /// read whatever is checked out in the winner's worktree. Left alone that
3426    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
3427    /// it when the run *branched* - and a run takes long enough that the base
3428    /// has usually moved by the time it gets here. A gate that ran there
3429    /// answers "green on the commit this run started from", not "green on
3430    /// what is about to land", and the difference showed up three times in
3431    /// one day as a green run whose merge would have reverted a file another
3432    /// pull request had already landed.
3433    ///
3434    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
3435    /// `land::Step::Rebase` calls, rather than a second implementation of the
3436    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
3437    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
3438    /// doc warns about ("two answers to a question nobody notices until a
3439    /// diff is wrong").
3440    ///
3441    /// A conflict is not the end of the road: the standing rebase is handed
3442    /// to the fixer seat, at most `graph.review_rounds` times, counted in
3443    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
3444    /// land). Once it finishes, review and the gate run as usual on the
3445    /// rebased tree, which is where a breakage the new base caused is caught
3446    /// by the ordinary gate-fix round. magi resolves nothing itself.
3447    ///
3448    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
3449    /// `state.base_sync.attempts`, is how many times the base is *rebased
3450    /// onto* (a base that keeps moving); `rebase_fixes` is how many times a
3451    /// *conflict* was given to a fixer. When the fixer cannot finish the
3452    /// rebase the branch is restored, `state.base_sync.conflict` is set with
3453    /// what was tried (rounds spent, paths still conflicted) and the branch
3454    /// and worktree stay exactly as they were - untouched, for a person to
3455    /// look at - which is also what makes re-entering this function
3456    /// afterwards a no-op instead of a second attempt at the same wall. A
3457    /// push failure ends the same way.
3458    async fn sync_to_base(&mut self) -> Result<()> {
3459        if self.state.status == RunStatus::AlreadyInBase {
3460            return Ok(());
3461        }
3462        let conflicted = self
3463            .state
3464            .base_sync
3465            .as_ref()
3466            .is_some_and(|s| s.conflict.is_some());
3467        let Some(winner) = self.state.winner().cloned() else {
3468            return Ok(());
3469        };
3470
3471        let repo = self.state.repo.clone();
3472        let remote = self.state.config.merge.remote.clone();
3473        let base_branch = self.state.base_branch.clone();
3474        let tracking = format!("{remote}/{base_branch}");
3475
3476        git::fetch(&repo, &remote, &base_branch).await.ok();
3477        // No network, or the remote never had this branch: the run already
3478        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
3479        // otherwise), and one that got this far is not blocked by a fetch
3480        // that fails now. It just has no newer tip to compare against.
3481        let Ok(tip) = git::rev_parse(&repo, &tracking).await else {
3482            return Ok(());
3483        };
3484
3485        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3486        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
3487        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
3488
3489        // Before any rebase, and before a recorded conflict is honoured: a
3490        // branch whose change reached the base under other commit ids has
3491        // nothing to rebase and nothing to conflict with, and a run that
3492        // already stopped on that phantom conflict recovers here on resume.
3493        // `behind == 0` with head == tip is a branch the base has since taken
3494        // in whole, whether or not a conflict was ever recorded: the ancestry
3495        // proof must still run (`classify` ignores a head still on the start
3496        // commit).
3497        if (behind > 0 || conflicted || head == tip)
3498            && self
3499                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
3500                .await?
3501        {
3502            return Ok(());
3503        }
3504        if conflicted {
3505            return Ok(());
3506        }
3507
3508        if behind == 0 {
3509            // A fixer-finished rebase moves the branch ref before the
3510            // winner's worktree is told (`sync_to_head` below). A run that
3511            // died in between resumes here with `behind == 0` and a tree still
3512            // holding the pre-rebase files, which review and the gate would
3513            // then read. That state is exactly: HEAD moved off the tip the
3514            // rebase started from, yet the tree is still identical to that
3515            // tip. A tree with edits of its own differs from it, so nothing
3516            // is thrown away.
3517            if let Some(from) = self
3518                .state
3519                .rebase_fixes
3520                .iter()
3521                .rev()
3522                .find_map(|r| r.from.clone())
3523                && from != head
3524                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
3525                    .await
3526                    .is_ok_and(|o| o.ok())
3527            {
3528                git::sync_to_head(&winner.worktree).await?;
3529            }
3530            // An earlier attempt may have rebased the branch locally and died
3531            // before pushing it (only the fresh-rebase arm below pushes).
3532            // Publish it now, so the plain push at PR time is not refused as
3533            // a non-fast-forward. A run already holding a recorded conflict
3534            // never reaches here; that case is out of scope.
3535            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
3536            if let Some(why) = &conflict {
3537                self.state.status = RunStatus::Blocked;
3538                self.state.event("land", why.clone());
3539            }
3540            self.state.base_sync = Some(BaseSync {
3541                tip,
3542                behind: 0,
3543                attempts,
3544                conflict,
3545                already_in: None,
3546            });
3547            self.state.save()?;
3548            return Ok(());
3549        }
3550
3551        if attempts >= BASE_SYNC_ROUNDS {
3552            let why = format!(
3553                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
3554                 rebase(s); rebasing again would only race it",
3555                winner.branch
3556            );
3557            self.state.status = RunStatus::Blocked;
3558            self.state.base_sync = Some(BaseSync {
3559                tip,
3560                behind,
3561                attempts,
3562                conflict: Some(why.clone()),
3563                already_in: None,
3564            });
3565            self.state.event("land", why);
3566            self.state.save()?;
3567            return Ok(());
3568        }
3569
3570        self.state.event(
3571            "land",
3572            format!(
3573                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
3574                winner.branch
3575            ),
3576        );
3577        self.state.save()?;
3578
3579        // The remote's copy of the branch, read now and only if the fetch
3580        // really succeeded (a stale tracking ref must never pin a lease). It is
3581        // pushed over after a rebase only when it is a commit this branch
3582        // already contains, by ancestry or by patch (an earlier rebase of ours
3583        // that never reached the remote): anything else is somebody else's work.
3584        let branch_tracking = format!("{remote}/{}", winner.branch);
3585        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
3586        let remote_tip = if matches!(&fetched_branch, Ok(o) if o.ok()) {
3587            git::rev_parse(&repo, &branch_tracking).await.ok()
3588        } else {
3589            None
3590        };
3591        // A remote tip this branch does not contain is somebody else's work:
3592        // rebasing would leave a local tip that can never be pushed. Stop
3593        // before touching anything and say so.
3594        if let Some(theirs) = &remote_tip
3595            && !git::is_ancestor(&repo, theirs, &head).await
3596            && !crate::reconcile::origin_missing(&repo, &head, theirs)
3597                .await
3598                .is_ok_and(|missing| missing.is_empty())
3599        {
3600            let why = format!(
3601                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
3602                 them",
3603                short(theirs),
3604                winner.branch
3605            );
3606            self.state.status = RunStatus::Blocked;
3607            self.state.base_sync = Some(BaseSync {
3608                tip,
3609                behind,
3610                attempts,
3611                conflict: Some(why.clone()),
3612                already_in: None,
3613            });
3614            self.state.event("land", why);
3615            self.state.save()?;
3616            return Ok(());
3617        }
3618
3619        let scratch = self.state.dir().join("base-sync");
3620        let rebased = match crate::rebase::rebase_with_fixer(
3621            &mut self.state,
3622            &scratch,
3623            &winner.branch,
3624            &tracking,
3625        )
3626        .await
3627        {
3628            Ok(crate::rebase::Rebased::Applied) => Ok(None),
3629            Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
3630            Err(e) => Err(e),
3631        };
3632        let attempts = attempts + 1;
3633        match rebased {
3634            Ok(None) => {
3635                // The branch ref moved, but a worktree that already had it
3636                // checked out (the winner's) was not told; sync its index and
3637                // files before anything reads them.
3638                git::sync_to_head(&winner.worktree).await?;
3639                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
3640                let mut conflict = None;
3641                if let Some(pinned) = &remote_tip {
3642                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
3643                    match pushed {
3644                        Ok(o) if o.ok() => self.state.event(
3645                            "land",
3646                            format!("pushed rebased {} to {remote}", winner.branch),
3647                        ),
3648                        Ok(o) => {
3649                            conflict = Some(format!(
3650                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
3651                                winner.branch,
3652                                short(pinned),
3653                                o.stderr.chars().take(600).collect::<String>()
3654                            ));
3655                        }
3656                        Err(e) => {
3657                            conflict = Some(format!(
3658                                "rebased {} locally but could not push it: {e:#}",
3659                                winner.branch
3660                            ));
3661                        }
3662                    }
3663                }
3664                if let Some(why) = &conflict {
3665                    self.state.status = RunStatus::Blocked;
3666                    self.state.event("land", why.clone());
3667                }
3668                self.state.base_sync = Some(BaseSync {
3669                    tip: tip.clone(),
3670                    behind: 0,
3671                    attempts,
3672                    conflict,
3673                    already_in: None,
3674                });
3675                self.state
3676                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
3677            }
3678            Ok(Some(conflict)) => {
3679                let why = format!(
3680                    "{} conflicts with {tracking} and did not rebase: {}",
3681                    winner.branch,
3682                    conflict.chars().take(600).collect::<String>()
3683                );
3684                self.state.status = RunStatus::Blocked;
3685                self.state.base_sync = Some(BaseSync {
3686                    tip,
3687                    behind,
3688                    attempts,
3689                    conflict: Some(why.clone()),
3690                    already_in: None,
3691                });
3692                self.state.event("land", why);
3693            }
3694            Err(e) => {
3695                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
3696                self.state.status = RunStatus::Blocked;
3697                self.state.base_sync = Some(BaseSync {
3698                    tip,
3699                    behind,
3700                    attempts,
3701                    conflict: Some(why.clone()),
3702                    already_in: None,
3703                });
3704                self.state.event("land", why);
3705            }
3706        }
3707        self.state.save()?;
3708        Ok(())
3709    }
3710
3711    /// Push a branch an earlier attempt rebased locally but never published,
3712    /// pinned to the remote tip read right after a successful fetch. Returns
3713    /// the reason when the run must stop; `None` when there was nothing to do
3714    /// (no remote copy, the same tip, or a remote copy this branch already
3715    /// contains, which the PR-time push fast-forwards) or the push succeeded.
3716    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
3717        let repo = self.state.repo.clone();
3718        let remote = self.state.config.merge.remote.clone();
3719        let fetched = git::fetch(&repo, &remote, branch).await;
3720        if !matches!(&fetched, Ok(o) if o.ok()) {
3721            return None;
3722        }
3723        let branch_tracking = format!("{remote}/{branch}");
3724        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
3725        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
3726            return None;
3727        }
3728        if !crate::reconcile::origin_missing(&repo, head, &theirs)
3729            .await
3730            .is_ok_and(|missing| missing.is_empty())
3731        {
3732            return Some(format!(
3733                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
3734                 them",
3735                short(&theirs)
3736            ));
3737        }
3738        match git::push_pinned(&repo, &remote, branch, &theirs).await {
3739            Ok(o) if o.ok() => {
3740                self.state
3741                    .event("land", format!("pushed rebased {branch} to {remote}"));
3742                None
3743            }
3744            Ok(o) => Some(format!(
3745                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
3746                 someone may have pushed): {}",
3747                short(&theirs),
3748                o.stderr.chars().take(600).collect::<String>()
3749            )),
3750            Err(e) => Some(format!(
3751                "{branch} is rebased locally but could not be pushed: {e:#}"
3752            )),
3753        }
3754    }
3755
3756    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
3757    /// is already on `tip` under other commit ids ([`crate::already`]); returns
3758    /// whether it did.
3759    ///
3760    /// Checked only when the base is ahead of the branch. A failing check is
3761    /// "not proven" - the ordinary rebase path then decides - never a reason to
3762    /// stop the run.
3763    ///
3764    /// The remote copy of the branch is held to the same standard as the local
3765    /// one: if it carries a tip this worktree does not, that tip must itself be
3766    /// proven in the base, or nothing is settled (a pull request would
3767    /// otherwise be closed over commits nobody checked). The pull request is
3768    /// closed *before* the terminal status is saved; if that fails for a
3769    /// reason other than a refusal (no network, a `gh` error) the run is left
3770    /// `Blocked` with the reason as its conflict, which a resume retries -
3771    /// the same recovery a phantom conflict gets.
3772    async fn settle_already_in(
3773        &mut self,
3774        branch: &str,
3775        tip: &str,
3776        head: &str,
3777        attempts: usize,
3778        behind: usize,
3779    ) -> Result<bool> {
3780        let repo = self.state.repo.clone();
3781        let remote = self.state.config.merge.remote.clone();
3782        let start = self.state.base_commit.clone();
3783        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
3784            Ok(Some(e)) => e,
3785            Ok(None) => return Ok(false),
3786            Err(e) => {
3787                tracing::warn!("already-in-base check for {branch}: {e:#}");
3788                return Ok(false);
3789            }
3790        };
3791        let mut verified = vec![head.to_owned()];
3792        let fetched = git::fetch(&repo, &remote, branch).await;
3793        if matches!(&fetched, Ok(o) if o.ok())
3794            && let Ok(theirs) = git::rev_parse(&repo, &format!("{remote}/{branch}")).await
3795            && theirs != head
3796        {
3797            match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
3798                Ok(Some(_)) => verified.push(theirs),
3799                _ => return Ok(false),
3800            }
3801        }
3802        let base_branch = self.state.base_branch.clone();
3803        let message = format!(
3804            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
3805             land",
3806            evidence.names(),
3807            evidence.proof.as_str()
3808        );
3809        let closed =
3810            crate::land::close_superseded_pr(&mut self.state, branch, &evidence, &verified).await;
3811        match closed {
3812            Ok(Ok(url)) => self
3813                .state
3814                .event("land", format!("closed {url}: superseded on {base_branch}")),
3815            Ok(Err(why)) => self
3816                .state
3817                .event("land", format!("did not close a pull request: {why}")),
3818            Err(e) => {
3819                let why = format!(
3820                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
3821                     not be closed ({e:#}); resume to retry"
3822                );
3823                self.state.status = RunStatus::Blocked;
3824                self.state.base_sync = Some(BaseSync {
3825                    tip: tip.to_owned(),
3826                    behind,
3827                    attempts,
3828                    conflict: Some(why.clone()),
3829                    already_in: None,
3830                });
3831                self.state.event("land", why);
3832                self.state.save()?;
3833                return Ok(true);
3834            }
3835        }
3836        self.state.status = RunStatus::AlreadyInBase;
3837        self.state.base_sync = Some(BaseSync {
3838            tip: tip.to_owned(),
3839            behind,
3840            attempts,
3841            conflict: None,
3842            already_in: Some(evidence),
3843        });
3844        self.state.event("land", message);
3845        self.state.save()?;
3846        self.settle_questions();
3847        Ok(true)
3848    }
3849
3850    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
3851    /// last landed the winner on, once it has run, else the commit the run
3852    /// branched from.
3853    ///
3854    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
3855    /// and `vote` all happen before there is a winner to rebase, so they
3856    /// compare every candidate against the branch point on purpose, and a
3857    /// base that moves after they are already done cannot change an answer
3858    /// they already gave.
3859    fn landing_base(&self) -> String {
3860        self.state
3861            .base_sync
3862            .as_ref()
3863            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
3864    }
3865
3866    // ------------------------------------------------------- operator fix
3867
3868    /// Route specific, already-recorded review findings to a fixer for a
3869    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
3870    /// entry point.
3871    ///
3872    /// Distinct from `review_loop`'s own fix step in three ways: it never
3873    /// runs a reviewer wave, it never spends review-round budget, and what
3874    /// happened is recorded as an [`OperatorFixRequest`] appended to
3875    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
3876    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
3877    /// and vote must never be rewritten to look like a manufactured blocking
3878    /// verdict.
3879    ///
3880    /// Only meaningful once review has actually concluded: `Ready` (handed
3881    /// off with findings still open, or simply concluded clean while minor
3882    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
3883    /// gate failed). Everything else is refused: a run still in progress
3884    /// should simply be resumed, and a `Merged` run's branch has already
3885    /// landed — reopening *this* run's own record cannot change that, so the
3886    /// answer there is a fresh `magi review <branch>`.
3887    ///
3888    /// A real commit here re-verifies through a fresh, ordinary review-only
3889    /// run on the same branch ([`Self::review`]) rather than reopening this
3890    /// run's own `review_loop`: once any round in this run's history went
3891    /// clean, `review_conclusion` treats that as permanent by design (the
3892    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
3893    /// way to force one more genuine reviewer wave out of *this* run without
3894    /// either rewriting history or weakening that guarantee for every other
3895    /// caller. A review-only run costs nothing extra — no implementation, no
3896    /// judging, no vote — and exercises the exact same review → verify →
3897    /// gate → (human) merge path, unmodified.
3898    pub async fn fix_selected(
3899        &mut self,
3900        ids: &[String],
3901        reason: &str,
3902        allow_stale: bool,
3903    ) -> Result<()> {
3904        let reason = reason.trim();
3905        if reason.is_empty() {
3906            bail!("a fix request needs a reason — that is the operator's own record of why");
3907        }
3908        if ids.is_empty() {
3909            bail!("no finding id given");
3910        }
3911        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
3912            bail!(
3913                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
3914                 has already concluded — can be given a targeted fix. A run still \
3915                 in progress should simply be resumed; a `merged` run's branch has \
3916                 already landed, so its answer is a fresh `magi review <branch>`, \
3917                 not reopening this run's own record",
3918                self.state.id,
3919                self.state.status.as_str()
3920            );
3921        }
3922        let Some(winner) = self.state.winner().cloned() else {
3923            bail!("run {} has no winning candidate to fix", self.state.id);
3924        };
3925        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
3926            bail!(
3927                "branch `{}` no longer exists; this run cannot be extended",
3928                winner.branch
3929            );
3930        }
3931        let home = crate::run::home();
3932        if crate::daemon::is_working_on(&home, &self.state.id, Timestamp::now()) {
3933            bail!(
3934                "run {} is currently being worked on by another magi process",
3935                self.state.id
3936            );
3937        }
3938        // Held for the rest of this call, including the follow-up review
3939        // below: two `magi fix` invocations against the same run must not
3940        // both reach the worktree manipulation further down, which would
3941        // otherwise race to remove and recreate the same directory — see
3942        // [`FixClaim`]'s own doc.
3943        let _claim = FixClaim::acquire(&self.state.dir())?;
3944
3945        // Resolve every id before spending anything — an unknown id refuses
3946        // the whole request rather than silently dropping it — and dedup
3947        // while keeping the operator's own order.
3948        let mut seen = BTreeSet::new();
3949        let mut findings = Vec::new();
3950        let mut missing = Vec::new();
3951        for id in ids {
3952            if !seen.insert(id.clone()) {
3953                continue;
3954            }
3955            match self.state.finding(id) {
3956                Some((round, rec, f)) => findings.push(OperatorFixFinding {
3957                    id: f.id.clone(),
3958                    severity: f.severity,
3959                    reviewer_vote: rec.vote,
3960                    round: round.round,
3961                    round_head: round.head.clone(),
3962                    reviewer: rec.reviewer,
3963                    agent: rec.agent.clone(),
3964                    file: f.file.clone(),
3965                    line: f.line,
3966                    title: f.title.clone(),
3967                    detail: f.detail.clone(),
3968                    outcome: OperatorFixOutcome::Pending,
3969                }),
3970                None => missing.push(id.clone()),
3971            }
3972        }
3973        if !missing.is_empty() {
3974            bail!(
3975                "unknown finding id(s): {}; nothing was changed",
3976                missing.join(", ")
3977            );
3978        }
3979
3980        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
3981        let stale_details: Vec<(String, String)> = findings
3982            .iter()
3983            .filter(|f| f.round_head != head_at_request)
3984            .map(|f| (f.id.clone(), f.round_head.clone()))
3985            .collect();
3986        let stale = !stale_details.is_empty();
3987        if stale && !allow_stale {
3988            bail!(
3989                "the branch has moved since some finding(s) were raised — {} — now \
3990                 at {}; pass --allow-stale to fix anyway, or re-run review first",
3991                stale_details
3992                    .iter()
3993                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
3994                    .collect::<Vec<_>>()
3995                    .join(", "),
3996                short(&head_at_request)
3997            );
3998        }
3999
4000        let request = OperatorFixRequest {
4001            requested_at: Timestamp::now(),
4002            reason: reason.to_owned(),
4003            findings,
4004            head_at_request: head_at_request.clone(),
4005            allow_stale,
4006            stale,
4007            fix: None,
4008            result_head: None,
4009            follow_up_review_run: None,
4010        };
4011        self.state.event(
4012            "fix",
4013            format!(
4014                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
4015                request.findings.len(),
4016                request
4017                    .findings
4018                    .iter()
4019                    .map(|f| f.id.as_str())
4020                    .collect::<Vec<_>>()
4021                    .join(", "),
4022            ),
4023        );
4024        // Recorded now, before any worktree work or the fixer call itself —
4025        // and re-saved at each checkpoint below: a crash at any point after
4026        // this (mid fixer call, mid follow-up review) must not lose the fact
4027        // that this was requested, for which findings, and why. Everything
4028        // past this point reads and writes through `request_index` rather
4029        // than a local variable, since `request` itself is moved here.
4030        self.state.operator_fixes.push(request);
4031        self.state.save()?;
4032        let request_index = self.state.operator_fixes.len() - 1;
4033
4034        // A fresh, dedicated worktree for this one call, never the winner's
4035        // own worktree in place: that one may already be gone (folded away),
4036        // and reusing it in place would leave the branch checked out there
4037        // when the follow-up review below tries to check it out again. Freed
4038        // immediately after, either way — but only once confirmed clean:
4039        // `worktree_remove` is a `git worktree remove --force`, which would
4040        // otherwise discard uncommitted work left there by the operator or
4041        // another process before this had a chance to even look at it.
4042        if winner.worktree.exists() {
4043            // Lockfiles a rescue commit withheld stay untracked on purpose and
4044            // are already recorded; they are not the operator's work to protect.
4045            let dirty = git::git(
4046                &winner.worktree,
4047                &["status", "--porcelain", "--untracked-files=all"],
4048            )
4049            .await?;
4050            let only_withheld = dirty.lines().all(|l| {
4051                l.strip_prefix("?? ")
4052                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
4053            });
4054            if !only_withheld {
4055                bail!(
4056                    "`{}` has uncommitted changes; refusing to touch it — commit or \
4057                     discard them first",
4058                    winner.worktree.display()
4059                );
4060            }
4061            git::worktree_remove(&self.state.repo, &winner.worktree)
4062                .await
4063                .ok();
4064        }
4065        let fix_worktree = self.state.worktree_root().join("operator-fix");
4066        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
4067        git::git(
4068            &self.state.repo,
4069            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
4070        )
4071        .await
4072        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
4073        if !git::is_clean(&fix_worktree).await? {
4074            git::worktree_remove(&self.state.repo, &fix_worktree)
4075                .await
4076                .ok();
4077            bail!(
4078                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
4079                winner.branch
4080            );
4081        }
4082
4083        let run_id = self.state.id.clone();
4084        let prompts = self.state.config.prompts.clone();
4085        let language = self.state.config.graph.language.clone();
4086        let sessions = self.state.config.graph.sessions;
4087        let artifacts = agent::artifacts_dir(&self.state.dir());
4088        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
4089            .findings
4090            .iter()
4091            .map(|f| Finding {
4092                id: f.id.clone(),
4093                severity: f.severity,
4094                file: f.file.clone(),
4095                line: f.line,
4096                title: f.title.clone(),
4097                detail: f.detail.clone(),
4098            })
4099            .collect();
4100        let fix_prompt = prompt::operator_fix(
4101            &self.state.instruction,
4102            &finding_list,
4103            reason,
4104            &stale_details,
4105            &head_at_request,
4106            &language,
4107        );
4108        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
4109        let (job, seat, out) = self
4110            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
4111                prompt: fix_prompt.clone(),
4112                spec,
4113                seat,
4114                cwd: fix_worktree.clone(),
4115                timeout,
4116                allow_write: true,
4117                sessions,
4118                artifacts: artifacts.clone(),
4119                stem: "operator-fix".to_owned(),
4120                handover: None,
4121            })
4122            .await;
4123        let agent_id = seat.agent.clone();
4124
4125        let mut fix = FixRecord {
4126            agent: agent_id,
4127            addressed: Vec::new(),
4128            rejected: Vec::new(),
4129            notes: String::new(),
4130            committed: false,
4131            failed: None,
4132            duration_ms: 0,
4133            continuation: None,
4134        };
4135        let mut final_seat = seat.clone();
4136        match out {
4137            AgentOutcome::Ok(o) => {
4138                fix.duration_ms = o.duration_ms;
4139                let parsed = verdict::extract_json::<FixReport>(&o.text);
4140                let incomplete_reason = match &parsed {
4141                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
4142                        "the reply parsed, but it reported a command whose own CLI \
4143                         never confirmed an exit status"
4144                            .to_owned(),
4145                    ),
4146                    Ok(_) => None,
4147                    Err(e) => Some(e.to_string()),
4148                };
4149                match incomplete_reason {
4150                    None => {
4151                        let report = parsed.expect("checked Ok above");
4152                        fix.addressed = report.addressed;
4153                        fix.rejected = report.rejected;
4154                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
4155                    }
4156                    Some(reason) => {
4157                        let (resumed_seat, resolved, failure, cont) = self
4158                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
4159                            .await;
4160                        fix.duration_ms += cont.cumulative_wait_ms;
4161                        fix.continuation = Some(cont);
4162                        final_seat = resumed_seat;
4163                        match resolved {
4164                            Some(report) => {
4165                                fix.addressed = report.addressed;
4166                                fix.rejected = report.rejected;
4167                                fix.notes =
4168                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
4169                            }
4170                            None => fix.failed = failure,
4171                        }
4172                    }
4173                }
4174            }
4175            AgentOutcome::Dropped(o) => {
4176                fix.duration_ms = o.duration_ms;
4177                let why = o
4178                    .dropped
4179                    .as_ref()
4180                    .map(|d| d.why.as_str())
4181                    .unwrap_or("the CLI ended the stream without delivering its answer");
4182                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
4183            }
4184            AgentOutcome::Quota(o) => {
4185                self.state.quota.push(QuotaLoss {
4186                    seat: final_seat.key.clone(),
4187                    node: "fix".to_owned(),
4188                    at: Timestamp::now(),
4189                    reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
4190                });
4191                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
4192            }
4193            AgentOutcome::Failed(e) => fix.failed = Some(e),
4194        }
4195        if fix.continuation.is_none() {
4196            fix.continuation = Some(ContinuationRecord::not_needed());
4197        }
4198        self.state.seats.insert(final_seat.key.clone(), final_seat);
4199
4200        let rescue_message = format!(
4201            "magi: operator-selected fix ({}) (uncommitted work)",
4202            self.state.operator_fixes[request_index]
4203                .findings
4204                .iter()
4205                .map(|f| f.id.as_str())
4206                .collect::<Vec<_>>()
4207                .join(", ")
4208        );
4209        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
4210            self.state.note_withheld("fix", &r.withheld);
4211        }
4212        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
4213        fix.committed = after != head_at_request;
4214        git::worktree_remove(&self.state.repo, &fix_worktree)
4215            .await
4216            .ok();
4217
4218        self.state.event(
4219            "fix",
4220            match &fix.failed {
4221                Some(reason) => format!(
4222                    "operator fix: adoption report was lost ({reason}); {}",
4223                    if fix.committed {
4224                        "committed"
4225                    } else {
4226                        "NO new commit"
4227                    }
4228                ),
4229                None => format!(
4230                    "operator fix: {} addressed, {} rejected, {}",
4231                    fix.addressed.len(),
4232                    fix.rejected.len(),
4233                    if fix.committed {
4234                        "committed"
4235                    } else {
4236                        "NO new commit"
4237                    }
4238                ),
4239            },
4240        );
4241
4242        // Every selected finding gets an outcome — never left `Pending` once
4243        // the fixer's own turn is over. A report that never came back at all
4244        // marks every one of them `Unreported`, not silently "not addressed":
4245        // quota, a dropped stream, or an exhausted continuation are gaps in
4246        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
4247        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
4248        for f in &mut self.state.operator_fixes[request_index].findings {
4249            f.outcome = if fix.failed.is_some() {
4250                OperatorFixOutcome::Unreported
4251            } else if fix.addressed.contains(&f.id) {
4252                OperatorFixOutcome::Addressed
4253            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
4254                OperatorFixOutcome::Rejected { why: r.why.clone() }
4255            } else {
4256                OperatorFixOutcome::Unreported
4257            };
4258        }
4259
4260        let committed = fix.committed;
4261        if committed {
4262            self.state.operator_fixes[request_index].result_head = Some(after.clone());
4263        }
4264        self.state.operator_fixes[request_index].fix = Some(fix);
4265        // Saved again now that the fixer's own outcome is final, on top of
4266        // the save right after the request was first pushed above.
4267        self.state.save()?;
4268
4269        if committed {
4270            self.state.event(
4271                "fix",
4272                format!(
4273                    "operator fix committed {}; opening a follow-up review-only run",
4274                    short(&after)
4275                ),
4276            );
4277            // The operator asked for the fix, and the follow-up serves whatever
4278            // task the run it follows served.
4279            let origin =
4280                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
4281            match Self::review(
4282                &self.state.repo,
4283                &winner.branch,
4284                self.state.config.clone(),
4285                origin,
4286            )
4287            .await
4288            {
4289                Ok(mut follow_up) => {
4290                    follow_up.state.event(
4291                        "start",
4292                        format!(
4293                            "requested by an operator fix on run {} for finding(s) {}",
4294                            self.state.id,
4295                            self.state.operator_fixes[request_index]
4296                                .findings
4297                                .iter()
4298                                .map(|f| f.id.as_str())
4299                                .collect::<Vec<_>>()
4300                                .join(", "),
4301                        ),
4302                    );
4303                    follow_up.state.save()?;
4304                    let follow_up_id = follow_up.state.id.clone();
4305                    // The follow-up is a run like any other: it belongs to the
4306                    // task of the run it follows, or to one filed for it.
4307                    let adopted = match crate::direct::adopt(
4308                        &follow_up.state,
4309                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
4310                    ) {
4311                        Ok(a) => a,
4312                        Err(e) => {
4313                            // An ownerless run must not spend agent calls; it
4314                            // stays saved, and `magi run --resume` adopts it.
4315                            self.state.event(
4316                                "fix",
4317                                format!(
4318                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
4319                                ),
4320                            );
4321                            self.state.save()?;
4322                            return Ok(());
4323                        }
4324                    };
4325                    let executed = follow_up.execute().await;
4326                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
4327                    if let Some(a) = adopted {
4328                        a.finish(&follow_up.state, executed);
4329                    }
4330                    if let Some(e) = failure {
4331                        self.state.event(
4332                            "fix",
4333                            format!(
4334                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
4335                            ),
4336                        );
4337                    }
4338                    self.state.operator_fixes[request_index].follow_up_review_run =
4339                        Some(follow_up_id);
4340                }
4341                Err(e) => {
4342                    self.state.event(
4343                        "fix",
4344                        format!("committed the fix but could not open a follow-up review: {e:#}"),
4345                    );
4346                }
4347            }
4348            self.state.save()?;
4349        }
4350
4351        Ok(())
4352    }
4353
4354    // --------------------------------------------------------------- review
4355
4356    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
4357    /// names, in order, each at most once, moving on only when the call
4358    /// advances (an error, a quota hit or nothing usable - the same decision
4359    /// point `agent::chain_advances` is for the other chained roles).
4360    ///
4361    /// Each agent gets its own seat from `Runner::seat`: the same agent
4362    /// continues its conversation (the winner's own implementer seat when it
4363    /// is the winner's author, now that the competition is over), another
4364    /// takes a fresh one so the full prompt is sent again. A handover is
4365    /// recorded under `node`, which is what makes the fallback stick for the
4366    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
4367    /// is returned, so an exhausted chain reads exactly like a single failed
4368    /// fixer: one quota loss, the same wording, the same refund. An earlier
4369    /// attempt's edits are left in the tree and judged, with the final
4370    /// attempt's, by what git says afterwards.
4371    ///
4372    /// Returns the job that produced the outcome, for `continue_fix_report`.
4373    async fn ask_fixer(
4374        &mut self,
4375        winner: &Candidate,
4376        node: &'static str,
4377        round: Option<usize>,
4378        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
4379    ) -> (SeatJob, SeatState, AgentOutcome) {
4380        let run_id = self.state.id.clone();
4381        let prompts = self.state.config.prompts.clone();
4382        let cache = self.state.config.cache_dir();
4383        let attempts = fixer::attempts(&self.state, &self.roles, winner);
4384        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
4385        let mut last = None;
4386        for (i, (spec, key)) in attempts.into_iter().enumerate() {
4387            let seat = self.seat(&key, &spec.id);
4388            let mut job = build(spec.clone(), seat);
4389            if i > 0 {
4390                job.stem = format!("{}-{}", job.stem, spec.id);
4391            }
4392            let ctx = WaveCtx {
4393                carry_seats: false,
4394                run: &run_id,
4395                node,
4396                prompts: &prompts,
4397                cache: cache.as_deref(),
4398                round,
4399            };
4400            let (seat, out) =
4401                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
4402            let advances = match &out {
4403                AgentOutcome::Ok(o) => agent::output_advances(o),
4404                _ => true,
4405            };
4406            if let Some(next) = ids.get(i + 1)
4407                && advances
4408            {
4409                self.state.seats.insert(seat.key.clone(), seat.clone());
4410                let class =
4411                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
4412                let reason = match &out {
4413                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
4414                    other => fail_reason(other),
4415                };
4416                record_handover(
4417                    &mut self.state,
4418                    node,
4419                    &seat.key,
4420                    &spec.id,
4421                    next,
4422                    &class,
4423                    &reason,
4424                );
4425                continue;
4426            }
4427            last = Some((job, seat, out));
4428            break;
4429        }
4430        last.expect("the fixer chain always has an entry")
4431    }
4432
4433    async fn review_loop(&mut self) -> Result<()> {
4434        // A base that would not rebase is a person's decision, not a review
4435        // round: nothing here would change the answer, and reviewers and a
4436        // fixer would be spending real budget on a tree that cannot land
4437        // regardless of what they find.
4438        if self
4439            .state
4440            .base_sync
4441            .as_ref()
4442            .is_some_and(|s| s.conflict.is_some())
4443        {
4444            return Ok(());
4445        }
4446        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4447        // agent files with `magi task add` name the run that paid for it. The
4448        // prompt overlay is cloned alongside it because the waves borrow it
4449        // while `self` is mutably borrowed by the node's own bookkeeping.
4450        let run_id = self.state.id.clone();
4451        let prompts = self.state.config.prompts.clone();
4452        let Some(winner) = self.state.winner().cloned() else {
4453            return Ok(());
4454        };
4455        let max_rounds = self.state.config.graph.review_rounds;
4456        // A clean round, an exhausted round budget, or a stalled tree (see
4457        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
4458        // they are recorded — recomputed here, not read off `status`, so a
4459        // reentry into a run that already stopped restates the identical
4460        // verdict instead of silently handing back whatever an earlier node
4461        // in this same walk clobbered `status` to (a solo-candidate
4462        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
4463        // below runs an empty range once the budget is spent, and would
4464        // otherwise fall through without touching `status` at all.
4465        if let Some(status) = review_conclusion(&self.state.reviews, max_rounds) {
4466            // A reentry after a crash between the last round's save and
4467            // `stop_reviewing` reaches the hand-off here, not there.
4468            if status == RunStatus::Gating {
4469                self.record_contested_handoff();
4470            }
4471            self.state.status = status;
4472            self.state.save()?;
4473            return Ok(());
4474        }
4475        self.state.status = RunStatus::Reviewing;
4476        // A last recorded round whose own verification never resolved
4477        // (`ResourceBlocked` — the shared build cache, not the patch) is
4478        // never a concluded round, whatever the round budget says: starting
4479        // a fresh round on top of it would spend a whole new reviewer wave
4480        // re-reading an unchanged patch instead of just retrying the one
4481        // check that actually needs it, and once the budget is spent the
4482        // loop below has nothing left to do at all (its range is empty).
4483        // Retry that check directly instead, exactly the same retry
4484        // `stop_reviewing` already does for its own catch-up case.
4485        if self
4486            .state
4487            .reviews
4488            .last()
4489            .is_some_and(|r| r.e2e_status() == E2eStatus::ResourceBlocked)
4490        {
4491            let shell = self.state.config.shell();
4492            return self
4493                .stop_reviewing(
4494                    "the last round's own verification never resolved",
4495                    &shell,
4496                    &winner.worktree,
4497                )
4498                .await;
4499        }
4500
4501        let repo = self.state.repo.clone();
4502        let root = self.state.worktree_root();
4503        let language = self.state.config.graph.language.clone();
4504        let sessions = self.state.config.graph.sessions;
4505        let artifacts = agent::artifacts_dir(&self.state.dir());
4506        let base = self.landing_base();
4507        let base_short = short(&base);
4508        let reviewers = self.roles.reviewers.clone();
4509        let shell = self.state.config.shell();
4510
4511        for round in (self.state.reviews.len() + 1)..=max_rounds {
4512            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4513            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
4514            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
4515            // The prior round's own record, already persisted — never a
4516            // hand-carried variable of just its failing output: that is
4517            // exactly what let a round's e2e result drift out of sync with
4518            // which commit it was actually about (see `SCHEMA`'s doc for
4519            // schema 8). Judged against `head`, the commit reviewers are
4520            // about to look at now, so the summary always reads as "an
4521            // earlier head" here — this round's own patch has not been
4522            // checked yet.
4523            let prev_verification = self
4524                .state
4525                .reviews
4526                .last()
4527                .and_then(|r| r.verification_summary(&head));
4528
4529            // Each reviewer gets its own detached checkout of exactly this
4530            // commit: nobody can perturb the winner's tree, and the fixer can
4531            // keep working without racing a reviewer.
4532            let mut jobs = Vec::new();
4533            for (r, spec) in reviewers.iter().cloned().enumerate() {
4534                let wt = root.join(format!("review-{}", r + 1));
4535                if wt.exists() {
4536                    git::reset_detached(&wt, &head).await?;
4537                } else {
4538                    git::worktree_add_detached(&repo, &wt, &head).await?;
4539                }
4540                let seat_key = format!("review-{}", r + 1);
4541                // The seat starts the round on whoever answered it last, not
4542                // on the agent the spec names, so a failure is not re-paid.
4543                let spec = pick_start_spec(
4544                    &self.roles.reviewer_roster,
4545                    spec,
4546                    self.state.seat_history.get(&seat_key),
4547                );
4548                let seat = self.seat(&seat_key, &spec.id);
4549                jobs.push(SeatJob {
4550                    prompt: prompt::review(&prompt::ReviewCtx {
4551                        instruction: &self.state.instruction,
4552                        branch: &winner.branch,
4553                        base_short: &base_short,
4554                        stat: &stat,
4555                        patch: &patch,
4556                        verification: prev_verification.as_ref(),
4557                        reviewers: reviewers.len(),
4558                        round,
4559                        rounds: max_rounds,
4560                        // A review-only run has no rankings, so nothing
4561                        // competed for this patch and the reviewer is told so.
4562                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
4563                        lens: Lens::for_seat(r),
4564                        language: &language,
4565                    }),
4566                    spec,
4567                    seat,
4568                    cwd: wt,
4569                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
4570                    allow_write: false,
4571                    sessions,
4572                    artifacts: artifacts.clone(),
4573                    stem: format!("review-{round}-{}", r + 1),
4574                    handover: None,
4575                });
4576            }
4577
4578            self.state.event(
4579                "review",
4580                format!(
4581                    "round {round}: {} reviewers on {}",
4582                    jobs.len(),
4583                    short(&head)
4584                ),
4585            );
4586            let mut quota_losses = Vec::new();
4587            let review_retries = self.state.config.graph.retries;
4588            let review_cache = self.state.config.cache_dir();
4589            let ctx = WaveCtx {
4590                carry_seats: true,
4591                run: &run_id,
4592                node: "review",
4593                prompts: &prompts,
4594                cache: review_cache.as_deref(),
4595                round: Some(round),
4596            };
4597            let results = ask_json_wave::<Review>(
4598                jobs,
4599                Arc::clone(&self.sem),
4600                review_retries,
4601                &self.roles.reviewer_roster,
4602                &ctx,
4603                &mut quota_losses,
4604                &mut self.state,
4605                &|_: &Review| Ok(()),
4606            )
4607            .await;
4608            // Counted before the move below: how many of *this* round's
4609            // reviewer seats were lost to their own rate limit, as opposed to
4610            // a crash, a timeout, or unparsable output — see `round_is_clean`.
4611            let round_quota_missing = quota_losses.len();
4612            self.state.quota.extend(quota_losses);
4613
4614            let mut records = Vec::new();
4615            let mut all_findings = Vec::new();
4616            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
4617                let agent_id = seat.agent.clone();
4618                self.state.seats.insert(seat.key.clone(), seat);
4619                let mut record = ReviewRecord {
4620                    reviewer: r + 1,
4621                    agent: agent_id,
4622                    summary: String::new(),
4623                    findings: Vec::new(),
4624                    vote: None,
4625                    failed: None,
4626                    duration_ms: 0,
4627                    // Set for both outcomes: `failed: Some(_)` with
4628                    // `attempts > 0` is a seat every retry still lost, not a
4629                    // recovered one — only `failed: None` with `attempts > 0`
4630                    // reads as "answered after a nudge" (see this field's own
4631                    // doc).
4632                    attempts,
4633                };
4634                match res {
4635                    Ok((review, out)) => {
4636                        // Sanitized here, at the point every other piece of
4637                        // agent prose in this file is (candidate summaries,
4638                        // deliberation turns, vote reasons): a reviewer's own
4639                        // words are the one thing about it that could name
4640                        // it, and reconsideration below broadcasts this same
4641                        // summary and these same findings to every other
4642                        // seat on the panel.
4643                        record.summary =
4644                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
4645                        record.vote = Some(review.vote);
4646                        record.duration_ms = out.duration_ms;
4647                        for (n, mut f) in review.findings.into_iter().enumerate() {
4648                            // ids are magi's, never the agent's: the fixer's
4649                            // adoption report is keyed by them.
4650                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
4651                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
4652                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
4653                            // `file` is agent-supplied prose too, never
4654                            // checked against the real tree — the same
4655                            // exposure `title`/`detail` above have, just in
4656                            // a field easy to forget because it looks like a
4657                            // path rather than free text.
4658                            f.file = f
4659                                .file
4660                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
4661                            all_findings.push(f.clone());
4662                            record.findings.push(f);
4663                        }
4664                        self.state.event(
4665                            "review",
4666                            format!(
4667                                "round {round}: reviewer {} voted {} with {} finding(s)",
4668                                r + 1,
4669                                review.vote.label(),
4670                                record.findings.len()
4671                            ),
4672                        );
4673                    }
4674                    Err(e) => {
4675                        record.failed = Some(e.to_string());
4676                        self.state.event(
4677                            "review",
4678                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
4679                        );
4680                    }
4681                }
4682                records.push(record);
4683            }
4684
4685            // Tally the round's votes and, if they split, spend the one
4686            // round of reconsideration the split -> deliberate -> revote
4687            // shape `judge`/`vote` use for the panel, sized down to what a
4688            // read-only review round can afford: one round, and a revote
4689            // rather than an argument, because the panel already wrote its
4690            // reasoning down as findings the first time around.
4691            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
4692            let vote_split =
4693                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
4694            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
4695            if vote_split {
4696                self.state.event(
4697                    "review",
4698                    format!(
4699                        "round {round}: votes split ({}) — one round of reconsideration",
4700                        initial_votes
4701                            .iter()
4702                            .map(|v| v.label())
4703                            .collect::<Vec<_>>()
4704                            .join(", ")
4705                    ),
4706                );
4707                // Seats read every seat's findings and votes, still numbered
4708                // and never named — the same anonymity `review` itself keeps.
4709                let panel: Vec<ReviewSeatReport<'_>> = records
4710                    .iter()
4711                    .filter_map(|r| {
4712                        r.vote.map(|vote| ReviewSeatReport {
4713                            reviewer: r.reviewer,
4714                            vote,
4715                            summary: &r.summary,
4716                            findings: &r.findings,
4717                        })
4718                    })
4719                    .collect();
4720
4721                let mut jobs = Vec::new();
4722                let mut seats_at = Vec::new();
4723                for (r, spec) in reviewers.iter().cloned().enumerate() {
4724                    // A seat with no initial vote has nothing to reconsider
4725                    // from and stays absent, the same as it stayed absent
4726                    // from `panel` above.
4727                    if records[r].vote.is_none() {
4728                        continue;
4729                    }
4730                    let wt = root.join(format!("review-{}", r + 1));
4731                    let seat_key = format!("review-{}", r + 1);
4732                    let spec = self.occupant(&seat_key, spec);
4733                    let seat = self.seat(&seat_key, &spec.id);
4734                    // A seat with no live session has already forgotten the
4735                    // initial review's prompt — restate the patch it is
4736                    // voting on, the same as `deliberate`/`vote` do for a
4737                    // judge in the same position.
4738                    // The panel already carries this seat's own review and
4739                    // vote, so restating the patch makes the prompt whole for
4740                    // a seat handed to another agent.
4741                    let build = |with_patch: bool| {
4742                        prompt::review_reconsider(&ReviewReconsiderCtx {
4743                            instruction: &self.state.instruction,
4744                            reviewer: r + 1,
4745                            lens: Lens::for_seat(r),
4746                            panel: &panel,
4747                            patch: with_patch.then_some(ReviewPatch {
4748                                branch: &winner.branch,
4749                                base_short: &base_short,
4750                                stat: &stat,
4751                                patch: &patch,
4752                            }),
4753                            round,
4754                            rounds: max_rounds,
4755                            language: &language,
4756                        })
4757                    };
4758                    let full = build(true);
4759                    let prompt = if has_context(&spec, &seat, sessions) {
4760                        build(false)
4761                    } else {
4762                        full.clone()
4763                    };
4764                    jobs.push(SeatJob {
4765                        prompt,
4766                        spec,
4767                        seat,
4768                        cwd: wt,
4769                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
4770                        allow_write: false,
4771                        sessions,
4772                        artifacts: artifacts.clone(),
4773                        stem: format!("review-{round}-reconsider-{}", r + 1),
4774                        handover: Some(full),
4775                    });
4776                    seats_at.push(r);
4777                }
4778
4779                let mut recon_quota_losses = Vec::new();
4780                let recon_cache = self.state.config.cache_dir();
4781                let recon_ctx = WaveCtx {
4782                    carry_seats: true,
4783                    run: &run_id,
4784                    node: "review",
4785                    prompts: &prompts,
4786                    cache: recon_cache.as_deref(),
4787                    round: Some(round),
4788                };
4789                let recon_results = ask_json_wave::<ReviewRevote>(
4790                    jobs,
4791                    Arc::clone(&self.sem),
4792                    review_retries,
4793                    &self.roles.reviewer_roster,
4794                    &recon_ctx,
4795                    &mut recon_quota_losses,
4796                    &mut self.state,
4797                    &|_: &ReviewRevote| Ok(()),
4798                )
4799                .await;
4800                self.state.quota.extend(recon_quota_losses);
4801
4802                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
4803                    let agent_id = seat.agent.clone();
4804                    self.state.seats.insert(seat.key.clone(), seat);
4805                    let mut rec = ReviewRevoteRecord {
4806                        reviewer: r + 1,
4807                        agent: agent_id,
4808                        vote: None,
4809                        reason: String::new(),
4810                        failed: None,
4811                    };
4812                    match res {
4813                        Ok((rv, _)) => {
4814                            rec.vote = Some(rv.vote);
4815                            rec.reason =
4816                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
4817                            self.state.event(
4818                                "review",
4819                                format!(
4820                                    "round {round}: reviewer {} revoted {}",
4821                                    r + 1,
4822                                    rv.vote.label()
4823                                ),
4824                            );
4825                        }
4826                        Err(e) => {
4827                            rec.failed = Some(e.to_string());
4828                            self.state.event(
4829                                "review",
4830                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
4831                            );
4832                        }
4833                    }
4834                    reconsideration.push(rec);
4835                }
4836            } else if initial_votes.len() > 1 {
4837                self.state.event(
4838                    "review",
4839                    format!(
4840                        "round {round}: votes agreed ({}) — no reconsideration",
4841                        initial_votes[0].label()
4842                    ),
4843                );
4844            }
4845
4846            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
4847            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
4848            // A round that already has a blocking finding and a round left to
4849            // try is going back to the fixer no matter what `verify.e2e`
4850            // says, so running it first only spends the loop's slowest step
4851            // (minutes, for a Rust repo's full test suite) on a head about
4852            // to be rewritten. Deferred, never skipped: `verify.e2e` still
4853            // runs once a round has no blocking findings left (see
4854            // `round_is_clean`, which a deferred — empty — `e2e` can never
4855            // satisfy since `blocking` is nonzero whenever this branch is
4856            // taken), and `stop_reviewing` forces a real run before it will
4857            // ever read a deferred round as green.
4858            let defer_e2e =
4859                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
4860            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
4861                let reason =
4862                    format!("{blocking} blocking finding(s) already required a fix this round");
4863                self.state.event(
4864                    "verify",
4865                    format!(
4866                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
4867                         {}); it will run once a round has none left",
4868                        short(&head)
4869                    ),
4870                );
4871                (Vec::new(), false, true, Some(reason))
4872            } else {
4873                let e2e_commands = self.state.config.verify.e2e.clone();
4874                let cache_dir = self.state.config.cache_dir();
4875                let context = format!("round {round}");
4876                let (e2e, verify_retried) = with_cache_lease(
4877                    &mut self.state,
4878                    cache_dir.as_deref(),
4879                    "e2e",
4880                    "e2e",
4881                    &winner.worktree,
4882                    &head,
4883                    verify_timeout,
4884                    &context,
4885                    |state, budget| {
4886                        let shell = shell.clone();
4887                        let e2e_commands = e2e_commands.clone();
4888                        let worktree = winner.worktree.clone();
4889                        let context = context.clone();
4890                        async move {
4891                            run_e2e_with_retry(
4892                                state,
4893                                &shell,
4894                                &e2e_commands,
4895                                &worktree,
4896                                budget,
4897                                &context,
4898                            )
4899                            .await
4900                        }
4901                    },
4902                )
4903                .await;
4904                (e2e, verify_retried, false, None)
4905            };
4906
4907            let expected = records.len();
4908            let answered = records.iter().filter(|r| r.failed.is_none()).count();
4909            let incomplete = answered < expected;
4910            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
4911            let policy = self.state.config.graph.incomplete_review;
4912            let clean = round_is_clean(
4913                blocking,
4914                e2e_ok,
4915                answered,
4916                expected,
4917                round_quota_missing,
4918                policy,
4919            );
4920
4921            let mut round_record = ReviewRound {
4922                round,
4923                head: head.clone(),
4924                verified_head: None,
4925                verified_at: None,
4926                reviews: records,
4927                e2e,
4928                verify_retried,
4929                e2e_deferred,
4930                e2e_defer_reason,
4931                fix: None,
4932                blocking,
4933                answered,
4934                expected,
4935                clean,
4936                progressed: false,
4937                vote_split,
4938                reconsideration,
4939                verdict: None,
4940            };
4941            // The final vote per seat is its revote where reconsideration
4942            // ran and answered, its initial vote otherwise — the same
4943            // fallback `tally` uses for a judge whose private vote failed.
4944            round_record.verdict = ReviewVote::worst(
4945                round_record
4946                    .final_votes()
4947                    .into_iter()
4948                    .map(|(_, _, vote)| vote),
4949            );
4950            // Which commit and when magi actually attempted to check —
4951            // known the moment a command was dispatched against `head`,
4952            // whether or not it finished: a resource-blocked attempt still
4953            // targeted a specific commit at a specific time, and leaving
4954            // that unrecorded is exactly what made `verification_summary`
4955            // report a fresh attempt as "commit unknown ... recorded before
4956            // this was tracked", indistinguishable from a genuinely old,
4957            // untracked record. Only a deferred or unconfigured round never
4958            // ran at all and has nothing to record — see
4959            // `ReviewRound::verified_head`'s own doc.
4960            if !matches!(
4961                round_record.e2e_status(),
4962                E2eStatus::Deferred | E2eStatus::NotConfigured
4963            ) {
4964                round_record.verified_head = Some(head.clone());
4965                round_record.verified_at = Some(Timestamp::now());
4966            }
4967            let this_round_verification = round_record.verification_summary(&head);
4968
4969            if incomplete {
4970                let missing: Vec<String> = round_record
4971                    .reviews
4972                    .iter()
4973                    .filter(|r| r.failed.is_some())
4974                    .map(|r| format!("review-{}", r.reviewer))
4975                    .collect();
4976                self.state.event(
4977                    "review",
4978                    format!(
4979                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
4980                        missing.join(", ")
4981                    ),
4982                );
4983            }
4984
4985            if clean {
4986                self.state.event(
4987                    "review",
4988                    if incomplete && policy == IncompleteReviewPolicy::Warn {
4989                        format!(
4990                            "round {round}: clean (warn policy, incomplete panel) — no \
4991                             blocking findings from the seats that answered, verification green"
4992                        )
4993                    } else if incomplete {
4994                        format!(
4995                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
4996                             quorum) — no blocking findings from the seats that answered, \
4997                             verification green",
4998                            expected - answered
4999                        )
5000                    } else {
5001                        format!("round {round}: clean — no blocking findings, verification green")
5002                    },
5003                );
5004                self.state.reviews.push(round_record);
5005                self.state.status = RunStatus::Gating;
5006                self.state.save()?;
5007                return Ok(());
5008            }
5009
5010            // Nothing was raised and verification passed, but not every seat
5011            // answered and `round_is_clean` still refused to call it clean —
5012            // either a seat is missing for a reason other than its own quota
5013            // (a crash, a timeout, unparsable output — worth another try), or
5014            // every seat that could have answered lost its quota and nobody
5015            // is left to decide on: re-review rather than send the fixer
5016            // after a round with nothing to fix.
5017            if incomplete && blocking == 0 && e2e_ok {
5018                self.state.reviews.push(round_record);
5019                self.state.save()?;
5020                if round == max_rounds {
5021                    self.state.status = RunStatus::Blocked;
5022                    self.state.event(
5023                        "review",
5024                        format!(
5025                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
5026                             refusing to call it clean",
5027                            expected - answered
5028                        ),
5029                    );
5030                    return Ok(());
5031                }
5032                continue;
5033            }
5034
5035            // Nothing for the fixer to act on (`blocking == 0`) and the only
5036            // reason this round is not clean is that magi itself never got
5037            // a command to run — the shared build cache, not the patch (see
5038            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
5039            // the fixer would invite a change to appease contention that has
5040            // nothing to do with the diff, and would leave this attempt
5041            // sitting in the next round's prompt as if it were about an
5042            // earlier, superseded commit rather than what it actually is:
5043            // the same head, still waiting to be checked. Wait for it the
5044            // same way the final round's own contention is already handled,
5045            // whatever round this happens to be.
5046            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
5047                self.state.reviews.push(round_record);
5048                return self
5049                    .stop_reviewing(
5050                        "the round's own verification could not run",
5051                        &shell,
5052                        &winner.worktree,
5053                    )
5054                    .await;
5055            }
5056
5057            if round == max_rounds {
5058                self.state.reviews.push(round_record);
5059                return self
5060                    .stop_reviewing(
5061                        &format!(
5062                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
5063                        ),
5064                        &shell,
5065                        &winner.worktree,
5066                    )
5067                    .await;
5068            }
5069
5070            // Fix. The winner's own implementer seat continues its conversation:
5071            // the competition is over, so context is pure benefit now.
5072            let blocking_findings: Vec<_> = all_findings
5073                .iter()
5074                .filter(|f| f.severity.blocks())
5075                .cloned()
5076                .collect();
5077            let fix_prompt = prompt::fix(
5078                &self.state.instruction,
5079                &blocking_findings,
5080                this_round_verification.as_ref(),
5081                round,
5082                max_rounds,
5083                &language,
5084            );
5085            let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5086            let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5087            let (job, seat, out) = self
5088                .ask_fixer(&winner, "fix", Some(round), |spec, seat| SeatJob {
5089                    prompt: fix_prompt.clone(),
5090                    spec,
5091                    seat,
5092                    cwd: winner.worktree.clone(),
5093                    timeout,
5094                    allow_write: true,
5095                    sessions,
5096                    artifacts: artifacts.clone(),
5097                    stem: format!("fix-{round}"),
5098                    handover: None,
5099                })
5100                .await;
5101            let agent_id = seat.agent.clone();
5102
5103            let mut fix = FixRecord {
5104                agent: agent_id,
5105                addressed: Vec::new(),
5106                rejected: Vec::new(),
5107                notes: String::new(),
5108                committed: false,
5109                failed: None,
5110                duration_ms: 0,
5111                continuation: None,
5112            };
5113            let mut continuation = ContinuationRecord::not_needed();
5114            let mut final_seat = seat.clone();
5115            match out {
5116                AgentOutcome::Ok(o) => {
5117                    fix.duration_ms = o.duration_ms;
5118                    let parsed = verdict::extract_json::<FixReport>(&o.text);
5119                    // A parsed report standing next to a command this same
5120                    // reply's own CLI never confirmed the exit status of is
5121                    // not a resolved answer — the identical `CommandEvidence`
5122                    // `state.jobs` renders, read here instead of only on
5123                    // display, per the completion judgment and the shown
5124                    // record needing to agree.
5125                    let incomplete_reason = match &parsed {
5126                        Ok(_) if has_unconfirmed_command(&o.commands) => Some(
5127                            "the reply parsed, but it reported a command whose own CLI never \
5128                             confirmed an exit status"
5129                                .to_owned(),
5130                        ),
5131                        Ok(_) => None,
5132                        Err(e) => Some(e.to_string()),
5133                    };
5134                    match incomplete_reason {
5135                        None => {
5136                            let report = parsed.expect("checked Ok above");
5137                            fix.addressed = report.addressed;
5138                            fix.rejected = report.rejected;
5139                            fix.notes =
5140                                blind::sanitize_prose(&report.notes, &self.state.config.blind);
5141                        }
5142                        Some(reason) => {
5143                            let (resumed_seat, resolved, failure, cont) = self
5144                                .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
5145                                .await;
5146                            fix.duration_ms += cont.cumulative_wait_ms;
5147                            continuation = cont;
5148                            final_seat = resumed_seat;
5149                            match resolved {
5150                                Some(report) => {
5151                                    fix.addressed = report.addressed;
5152                                    fix.rejected = report.rejected;
5153                                    fix.notes = blind::sanitize_prose(
5154                                        &report.notes,
5155                                        &self.state.config.blind,
5156                                    );
5157                                }
5158                                None => fix.failed = failure,
5159                            }
5160                        }
5161                    }
5162                }
5163                // The CLI's raw error JSON is not a fix report to parse.
5164                AgentOutcome::Dropped(o) => {
5165                    fix.duration_ms = o.duration_ms;
5166                    let why = o
5167                        .dropped
5168                        .as_ref()
5169                        .map(|d| d.why.as_str())
5170                        .unwrap_or("the CLI ended the stream without delivering its answer");
5171                    fix.failed = Some(format!("the CLI dropped the stream ({why})"));
5172                }
5173                AgentOutcome::Quota(o) => {
5174                    self.state.quota.push(QuotaLoss {
5175                        seat: final_seat.key.clone(),
5176                        node: "fix".to_owned(),
5177                        at: Timestamp::now(),
5178                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
5179                    });
5180                    fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
5181                }
5182                AgentOutcome::Failed(e) => fix.failed = Some(e),
5183            }
5184            fix.continuation = Some(continuation);
5185            self.state.seats.insert(final_seat.key.clone(), final_seat);
5186            if let Ok(r) = git::rescue_commit(
5187                &winner.worktree,
5188                &format!("magi: review round {round} fixes (uncommitted work)"),
5189            )
5190            .await
5191            {
5192                self.state.note_withheld("fix", &r.withheld);
5193            }
5194            let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5195            fix.committed = after != before;
5196            // Judged by what `git` says moved against base, never by the
5197            // fixer's own `addressed`/`rejected` count — see
5198            // `ReviewRound::progressed`. Propagated with `?`, the same as the
5199            // `patch` snapshot above: swallowing this error would default
5200            // `diff_after` to empty, which almost always differs from a
5201            // non-empty `patch` and reads as "progressed" — exactly backwards
5202            // for a `git` failure the stagnation check cannot see through.
5203            let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
5204            let progressed = diff_after != patch;
5205            let commit_note = if fix.committed {
5206                "committed"
5207            } else {
5208                "NO new commit"
5209            };
5210            let tree_note = if progressed {
5211                "changed vs base"
5212            } else {
5213                "unchanged vs base"
5214            };
5215            self.state.event(
5216                "fix",
5217                match &fix.failed {
5218                    // Distinct on purpose from "0 addressed, 0 rejected": the
5219                    // fixer's own diff still landed (blocking counts do keep
5220                    // falling round over round), only its adoption report did
5221                    // not come back, so this must never read like every
5222                    // finding was reviewed and declined.
5223                    Some(reason) => {
5224                        format!(
5225                            "round {round}: fixer's adoption report was lost ({reason}); \
5226                             {commit_note}, tree {tree_note}"
5227                        )
5228                    }
5229                    None => format!(
5230                        "round {round}: {} addressed, {} rejected, {commit_note}, tree \
5231                         {tree_note}{}",
5232                        fix.addressed.len(),
5233                        fix.rejected.len(),
5234                        if continuation.outcome == ContinuationOutcome::Resumed {
5235                            format!(
5236                                " (adoption report recovered after {} continuation(s))",
5237                                continuation.attempts
5238                            )
5239                        } else {
5240                            String::new()
5241                        },
5242                    ),
5243                },
5244            );
5245            round_record.fix = Some(fix);
5246            round_record.progressed = progressed;
5247            self.state.reviews.push(round_record);
5248            self.state.save()?;
5249
5250            // The fixer's own report never came back this round, even after
5251            // `continue_fix_report`'s own budget was spent on it — not an
5252            // ordinary "no report" (dropped stream, quota, plain failure),
5253            // which already reads that way and is left to the existing round
5254            // budget. Stopping here, rather than opening another round, is
5255            // what keeps a next reviewer/fixer wave from ever being
5256            // dispatched onto `winner.worktree` while whatever the seat's
5257            // last call may still have running there is unaccounted for: no
5258            // process liveness check exists (and none is being added — see
5259            // AGENTS.md/this task's own scope), so the only way to honour
5260            // "nothing starts before a valid report returns" is to not start
5261            // anything further on this worktree from this run at all.
5262            if matches!(
5263                continuation.outcome,
5264                ContinuationOutcome::Exhausted
5265                    | ContinuationOutcome::QuotaLost
5266                    | ContinuationOutcome::NoSession
5267            ) {
5268                return self
5269                    .stop_reviewing(
5270                        "the fixer's adoption report never came back, even after resuming its \
5271                         own seat; refusing to start another round against the same worktree \
5272                         while that is unresolved",
5273                        &shell,
5274                        &winner.worktree,
5275                    )
5276                    .await;
5277            }
5278
5279            let streak = self
5280                .state
5281                .reviews
5282                .iter()
5283                .rev()
5284                .take_while(|r| !r.progressed)
5285                .count();
5286            if streak >= STAGNANT_LIMIT {
5287                return self
5288                    .stop_reviewing(
5289                        &format!(
5290                            "the tree has not moved against base for {streak} round(s) in a row"
5291                        ),
5292                        &shell,
5293                        &winner.worktree,
5294                    )
5295                    .await;
5296            }
5297        }
5298        Ok(())
5299    }
5300
5301    /// Decide, from the last recorded round's own verification, whether
5302    /// stopping the review loop is a hand-off or a genuine block.
5303    ///
5304    /// Called once the loop has given up trying — the round budget is spent,
5305    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
5306    /// findings still open, never while a round is still clean or the
5307    /// incomplete-panel case handled inline above. Gate and e2e are facts
5308    /// about the tree; a lingering review finding is an opinion, and this
5309    /// workload's own `magi stats` puts reviewer precision low enough
5310    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
5311    /// must not by itself stand between a green, verified change and the
5312    /// human who decides what to do with it. A red e2e is not an opinion, so
5313    /// that case still blocks, with the failing command and a tail of its
5314    /// output recorded here rather than left in `run.json` for someone to go
5315    /// find.
5316    ///
5317    /// A round that deferred its own e2e (see [`Config::graph`]'s
5318    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
5319    /// only because nothing ran, and treating an empty list as a passing one
5320    /// here is exactly the "deferred painted green" bug this function exists
5321    /// to not have. When the last round's own verification never resolved —
5322    /// deferred on purpose, or a real attempt the shared build cache blocked
5323    /// — this makes (or retries) the real run, on the actual worktree this
5324    /// loop is about to stop touching, before deciding anything. A
5325    /// resource-blocked attempt is likewise never read as either green or
5326    /// red: it is evidence about the machine, not the patch (see
5327    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
5328    /// blocked cache leaves this call without deciding rather than guessing
5329    /// — the caller retries on a later reentry.
5330    /// Record, once, that the review loop handed off over a blocking finding
5331    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
5332    /// `land` asks the owner even with `land_approval` off. Called from every
5333    /// path that concludes `Gating`; a reentry keeps the first record.
5334    fn record_contested_handoff(&mut self) {
5335        if self.state.contested_handoff.is_some() {
5336            return;
5337        }
5338        let Some(contested) = self
5339            .state
5340            .reviews
5341            .last()
5342            .and_then(ReviewRound::contested_handoff)
5343        else {
5344            return;
5345        };
5346        self.state.event(
5347            "review",
5348            format!(
5349                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
5350                 wait for the owner's approval",
5351                contested.findings.len(),
5352                contested.rejecters.len()
5353            ),
5354        );
5355        self.state.contested_handoff = Some(contested);
5356    }
5357
5358    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
5359        let round_idx = self.state.reviews.len() - 1;
5360        // A deferred round and a resource-blocked one are the same shape
5361        // here: neither has a real result yet, and both get one more
5362        // attempt. Read off `e2e_status` — the single source for this —
5363        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
5364        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
5365        // still retries instead of being read as a settled result the
5366        // instant it stops being empty.
5367        let needs_catchup_run = matches!(
5368            self.state.reviews[round_idx].e2e_status(),
5369            E2eStatus::Deferred | E2eStatus::ResourceBlocked
5370        );
5371        if needs_catchup_run {
5372            let round = self.state.reviews[round_idx].round;
5373            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5374            let commands = self.state.config.verify.e2e.clone();
5375            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
5376            let cache_dir = self.state.config.cache_dir();
5377            let context = format!(
5378                "round {round}: verification unresolved, catching up before the final decision"
5379            );
5380            let (outcomes, verify_retried) = with_cache_lease(
5381                &mut self.state,
5382                cache_dir.as_deref(),
5383                "e2e",
5384                "e2e",
5385                worktree,
5386                &attempted_head,
5387                timeout,
5388                &context,
5389                |state, budget| {
5390                    let shell = shell.to_vec();
5391                    let commands = commands.clone();
5392                    let context = context.clone();
5393                    async move {
5394                        run_e2e_with_retry(state, &shell, &commands, worktree, budget, &context)
5395                            .await
5396                    }
5397                },
5398            )
5399            .await;
5400            let last = &mut self.state.reviews[round_idx];
5401            last.e2e = outcomes;
5402            last.verify_retried = verify_retried;
5403            // Always the commit and time this attempt actually targeted,
5404            // whether or not it happens to equal the reviewed `head` and
5405            // whether or not a command finished — see
5406            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
5407            // attempt is recorded too, so a later reader sees "attempted
5408            // again at T2" rather than silence.
5409            last.verified_head = Some(attempted_head);
5410            last.verified_at = Some(Timestamp::now());
5411            if verify_inconclusive(&last.e2e) {
5412                // Still not a real result: `e2e_deferred` is left exactly
5413                // as it was, so `needs_catchup_run` above reads
5414                // `ResourceBlocked` (via `e2e_status`, which checks
5415                // `resource_blocked` before `e2e_deferred`) and retries
5416                // again on the next reentry, rather than recording
5417                // contention as a red e2e and blocking the run on it.
5418                self.state.save()?;
5419                return Ok(());
5420            }
5421            last.e2e_deferred = false;
5422        }
5423        let last = &self.state.reviews[round_idx];
5424        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
5425
5426        match last.e2e_status() {
5427            E2eStatus::Failed => {
5428                let red: Vec<String> = last
5429                    .e2e
5430                    .iter()
5431                    .filter(|o| !o.ok())
5432                    .map(|o| {
5433                        format!(
5434                            "`{}` -> {:?}\n{}",
5435                            o.command,
5436                            o.code,
5437                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
5438                        )
5439                    })
5440                    .collect();
5441                self.state
5442                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
5443                self.state.status = RunStatus::Blocked;
5444            }
5445            // `needs_catchup_run` above already retried once this call; if
5446            // it is still blocked, this is magi's own admission it could
5447            // not get a command to run, never a verdict on the patch — the
5448            // run is left exactly where a later reentry can retry again.
5449            E2eStatus::ResourceBlocked => {
5450                self.state.event(
5451                    "review",
5452                    format!(
5453                        "{why}; e2e could not run (shared build cache unavailable); not \
5454                         deciding yet"
5455                    ),
5456                );
5457            }
5458            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
5459                self.state.event(
5460                    "review",
5461                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
5462                );
5463                self.record_contested_handoff();
5464                self.state.status = RunStatus::Gating;
5465            }
5466        }
5467        self.state.save()?;
5468        Ok(())
5469    }
5470
5471    // ----------------------------------------------------------------- gate
5472
5473    async fn gate(&mut self) -> Result<()> {
5474        // Judged by the review record itself, not by `status`: a solo
5475        // candidate's `judge`/`deliberate` skip rewrites `status` on every
5476        // reentry (see `judge`), and trusting it here is exactly how a run
5477        // that exhausted its review budget got gated and merged a second
5478        // time around. `review_conclusion` recomputes the review loop's own
5479        // verdict from the round records themselves — `Gating` for a clean
5480        // round or a hand-off (see `stop_reviewing`), anything else means the
5481        // loop is still going or genuinely blocked.
5482        // A base the winner could not be replayed onto is a decision, not a
5483        // round: there is no landing tree to gate. Read as its own record for
5484        // the same reason the review verdict is.
5485        if self.state.status == RunStatus::Failed
5486            || self
5487                .state
5488                .base_sync
5489                .as_ref()
5490                .is_some_and(|s| s.conflict.is_some())
5491            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
5492                != Some(RunStatus::Gating)
5493        {
5494            return Ok(());
5495        }
5496        if self.state.gate_ran {
5497            // `review_loop` derives its conclusion from the clean review
5498            // record on every reentry and therefore puts a completed run back
5499            // in `Gating`. A recorded gate is a stronger, terminal fact:
5500            // retain its original command output (or lack of any, for a repo
5501            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
5502            // doc) and restore `Blocked` on a real failure rather than
5503            // pretending the command is still running or running it a second
5504            // time. `gate_ran == false` remains the only shape — unattempted,
5505            // or a resource-blocked retry — that may still need to execute a
5506            // command.
5507            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
5508                self.state.status = RunStatus::Blocked;
5509                self.state.save()?;
5510            }
5511            return Ok(());
5512        }
5513        let Some(winner) = self.state.winner().cloned() else {
5514            return Ok(());
5515        };
5516        self.state.status = RunStatus::Gating;
5517        let mut outcomes = self.run_gate(&winner).await?;
5518        loop {
5519            // A resource-blocked outcome means the gate command never actually
5520            // ran - the shared build cache could not be acquired or confirmed
5521            // fresh in time - which is evidence about the machine, not about
5522            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
5523            // Recording it as a red gate would mark a run `Blocked` on nothing
5524            // but contention magi has already logged; leaving `self.state.gate`
5525            // empty and `self.state.gate_ran` false instead keeps the shape
5526            // this function already treats as "still needs to run" (see the
5527            // early-return above), so the next call retries the command
5528            // rather than concluding anything.
5529            if verify_inconclusive(&outcomes) {
5530                self.state.save()?;
5531                return Ok(());
5532            }
5533            if outcomes.iter().all(CommandOutcome::ok) {
5534                break;
5535            }
5536            match self.gate_fix_round(&winner, &outcomes).await? {
5537                GateFix::Retry => outcomes = self.run_gate(&winner).await?,
5538                GateFix::Stop => break,
5539                GateFix::Defer => {
5540                    self.state.save()?;
5541                    return Ok(());
5542                }
5543            }
5544        }
5545        let passed = outcomes.iter().all(CommandOutcome::ok);
5546        self.state.gate = outcomes;
5547        self.state.gate_ran = true;
5548        if !passed {
5549            self.state.status = RunStatus::Blocked;
5550            let spent = self.state.gate_fixes.len();
5551            self.state.event(
5552                "gate",
5553                if spent == 0 {
5554                    "gate failed; not merging".to_owned()
5555                } else {
5556                    format!("gate failed after {spent} gate-fix round(s); not merging")
5557                },
5558            );
5559        }
5560        self.state.save()?;
5561        Ok(())
5562    }
5563
5564    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
5565    /// changed into one commit. Reached only from [`Self::run_gate`], i.e.
5566    /// after review is clean and never on a candidate awaiting judging.
5567    ///
5568    /// Never fails the run: a non-zero exit or timeout is a warning and a
5569    /// recorded outcome, and the gate remains the single arbiter. Nothing
5570    /// configured means nothing happens - no event, no commit. `commit_all`
5571    /// commits any leftover change under the neutral identity and returns
5572    /// `false` when the tree is clean, so no empty commit is ever made.
5573    async fn run_pre_gate(&mut self, winner: &Candidate) {
5574        let commands = self.state.config.verify.pre_gate.clone();
5575        if commands.is_empty() {
5576            return;
5577        }
5578        let shell = self.state.config.shell();
5579        let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5580        let (outcomes, _) = run_commands(
5581            &mut self.state,
5582            "pre_gate",
5583            "pre_gate",
5584            0,
5585            &shell,
5586            &commands,
5587            &winner.worktree,
5588            timeout,
5589        )
5590        .await;
5591        for o in &outcomes {
5592            if !o.ok() {
5593                tracing::warn!(
5594                    "pre_gate `{}` failed ({:?}); the gate decides",
5595                    o.command,
5596                    o.code
5597                );
5598            }
5599            self.state.event(
5600                "pre_gate",
5601                format!(
5602                    "`{}` -> {}",
5603                    o.command,
5604                    if o.ok() {
5605                        "pass".to_owned()
5606                    } else {
5607                        format!(
5608                            "FAIL ({:?})\n{}",
5609                            o.code,
5610                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
5611                        )
5612                    }
5613                ),
5614            );
5615        }
5616        self.state.pre_gate = outcomes;
5617        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
5618            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
5619                Ok(head) => {
5620                    self.state
5621                        .event("pre_gate", format!("committed mechanical fixes ({head})"));
5622                    self.state.pre_gate_commit = Some(head);
5623                }
5624                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
5625            },
5626            Ok(false) => {}
5627            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
5628        }
5629        if let Err(e) = self.state.save() {
5630            tracing::warn!("could not persist the pre_gate record: {e:#}");
5631        }
5632    }
5633
5634    /// Run `verify.gate` once against the winner's current tree, logging one
5635    /// event per command. Empty when nothing is configured.
5636    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
5637        self.run_pre_gate(winner).await;
5638        let shell = self.state.config.shell();
5639        let gate_commands = self.state.config.verify.gate.clone();
5640        // Zero commands has nothing to run and nothing that could touch the
5641        // shared build cache, so it never needs a lease: `Config::cache_dir`
5642        // is derived from `verify.e2e` too, so a repo with no `verify.gate`
5643        // commands but a `CARGO_TARGET_DIR`-using `verify.e2e` would
5644        // otherwise queue behind an unrelated run's lease and come back
5645        // resource-blocked - `gate_ran` would stay false on nothing but
5646        // cache contention, for a step that had nothing to check in the
5647        // first place.
5648        let outcomes = if gate_commands.is_empty() {
5649            Vec::new()
5650        } else {
5651            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5652            let cache_dir = self.state.config.cache_dir();
5653            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5654            let (outcomes, _) = with_cache_lease(
5655                &mut self.state,
5656                cache_dir.as_deref(),
5657                "gate",
5658                "gate",
5659                &winner.worktree,
5660                &head,
5661                timeout,
5662                "final gate",
5663                |state, budget| {
5664                    let shell = shell.clone();
5665                    let gate_commands = gate_commands.clone();
5666                    let worktree = winner.worktree.clone();
5667                    async move {
5668                        let (outcomes, timed_out_pids) = run_commands(
5669                            state,
5670                            "gate",
5671                            "gate",
5672                            0,
5673                            &shell,
5674                            &gate_commands,
5675                            &worktree,
5676                            budget,
5677                        )
5678                        .await;
5679                        (outcomes, false, timed_out_pids)
5680                    }
5681                },
5682            )
5683            .await;
5684            outcomes
5685        };
5686        if outcomes.is_empty() {
5687            // Nothing configured to check — distinct from every other
5688            // silence in this run's event log, since an empty `gate` alone
5689            // no longer says whether the gate ran at all (see
5690            // `RunState::gate_ran`'s own doc).
5691            self.state.event(
5692                "gate",
5693                "no gate commands configured; nothing to check, passing",
5694            );
5695        }
5696        for o in &outcomes {
5697            self.state.event(
5698                "gate",
5699                format!(
5700                    "`{}` -> {}",
5701                    o.command,
5702                    if o.ok() {
5703                        "pass".to_owned()
5704                    } else {
5705                        format!(
5706                            "FAIL ({:?})\n{}",
5707                            o.code,
5708                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
5709                        )
5710                    }
5711                ),
5712            );
5713        }
5714        Ok(outcomes)
5715    }
5716
5717    /// One bounded fix round for a failing gate.
5718    ///
5719    /// The fixer is told the failure came from the gate itself, not from a
5720    /// reviewer, and is shown the failed commands, their exit codes and a tail
5721    /// of their output - whatever `[verify].gate` holds, nothing here knows
5722    /// what those commands run. Only a normal non-zero exit that printed
5723    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
5724    /// command or a full disk says nothing about the code, and a fixer sent
5725    /// after it can only appease the machine. The round is judged by what git
5726    /// says moved, never by the fixer's own report, and `verify.e2e` runs
5727    /// again before the gate does, so a fix cannot trade a green gate for a
5728    /// red e2e unnoticed.
5729    async fn gate_fix_round(
5730        &mut self,
5731        winner: &Candidate,
5732        outcomes: &[CommandOutcome],
5733    ) -> Result<GateFix> {
5734        let cap = self.state.config.graph.gate_fix_rounds;
5735        let spent = self.state.gate_fixes.len();
5736        if spent >= cap {
5737            if cap > 0 {
5738                self.state.event(
5739                    "gate",
5740                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
5741                );
5742            }
5743            return Ok(GateFix::Stop);
5744        }
5745        if !gate_fixable(outcomes) {
5746            self.state.event(
5747                "gate",
5748                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
5749                 command or similar); not spending a fix round on it",
5750            );
5751            return Ok(GateFix::Stop);
5752        }
5753        let min_free = self.state.config.disk.min_free_bytes;
5754        if min_free > 0 {
5755            match crate::disk::free_bytes(&winner.worktree) {
5756                Ok(free) if crate::disk::enough_space(free, min_free) => {}
5757                Ok(free) => {
5758                    self.state.event(
5759                        "gate",
5760                        format!(
5761                            "only {free} bytes free ({min_free} required by `[disk] \
5762                             min_free_bytes`); not spending a fix round on a failure the disk \
5763                             may explain"
5764                        ),
5765                    );
5766                    return Ok(GateFix::Stop);
5767                }
5768                Err(e) => {
5769                    self.state.event(
5770                        "gate",
5771                        format!("free disk space could not be measured ({e:#}); no fix round"),
5772                    );
5773                    return Ok(GateFix::Stop);
5774                }
5775            }
5776        }
5777
5778        let attempt = spent + 1;
5779        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
5780        let base = self.landing_base();
5781        let fix_prompt = prompt::gate_fix(
5782            &self.state.instruction,
5783            &failed,
5784            attempt,
5785            cap,
5786            &self.state.config.graph.language,
5787        );
5788        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5789        let sessions = self.state.config.graph.sessions;
5790        let artifacts = agent::artifacts_dir(&self.state.dir());
5791        self.state.event(
5792            "gate",
5793            format!("gate failed; gate-fix round {attempt} of {cap}"),
5794        );
5795        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5796        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
5797        let (_, seat, out) = self
5798            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
5799                prompt: fix_prompt.clone(),
5800                spec,
5801                seat,
5802                cwd: winner.worktree.clone(),
5803                timeout,
5804                allow_write: true,
5805                sessions,
5806                artifacts: artifacts.clone(),
5807                stem: format!("gate-fix-{attempt}"),
5808                handover: None,
5809            })
5810            .await;
5811        let mut record = GateFixRecord {
5812            agent: seat.agent.clone(),
5813            failed,
5814            notes: String::new(),
5815            committed: false,
5816            error: None,
5817        };
5818        match out {
5819            AgentOutcome::Ok(o) => {
5820                // A missing report is not a failed fix: the round is judged
5821                // by the tree below, and the report only carries prose.
5822                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
5823                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
5824                }
5825            }
5826            AgentOutcome::Dropped(_) => {
5827                record.error = Some("the CLI dropped the stream".to_owned());
5828            }
5829            AgentOutcome::Quota(o) => {
5830                self.state.quota.push(QuotaLoss {
5831                    seat: seat.key.clone(),
5832                    node: "gate-fix".to_owned(),
5833                    at: Timestamp::now(),
5834                    reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
5835                });
5836                record.error = Some("rate limited (quota); fixer could not run".to_owned());
5837            }
5838            AgentOutcome::Failed(e) => record.error = Some(e),
5839        }
5840        self.state.seats.insert(seat.key.clone(), seat);
5841        if let Ok(r) = git::rescue_commit(
5842            &winner.worktree,
5843            &format!("magi: gate fix {attempt} (uncommitted work)"),
5844        )
5845        .await
5846        {
5847            self.state.note_withheld("gate-fix", &r.withheld);
5848        }
5849        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5850        record.committed = after != before;
5851        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
5852        let note = record.error.clone();
5853        self.state.gate_fixes.push(record);
5854        self.state.save()?;
5855        if !changed {
5856            self.state.event(
5857                "gate",
5858                match note {
5859                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
5860                    None => format!("gate-fix round {attempt}: the tree did not change"),
5861                },
5862            );
5863            return Ok(GateFix::Stop);
5864        }
5865        self.state.event(
5866            "gate",
5867            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
5868        );
5869
5870        let commands = self.state.config.verify.e2e.clone();
5871        if !commands.is_empty() {
5872            let shell = self.state.config.shell();
5873            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5874            let cache_dir = self.state.config.cache_dir();
5875            let context = format!("gate-fix round {attempt}");
5876            let (e2e, _) = with_cache_lease(
5877                &mut self.state,
5878                cache_dir.as_deref(),
5879                "e2e",
5880                "e2e",
5881                &winner.worktree,
5882                &after,
5883                timeout,
5884                &context,
5885                |state, budget| {
5886                    let shell = shell.clone();
5887                    let commands = commands.clone();
5888                    let context = context.clone();
5889                    let worktree = winner.worktree.clone();
5890                    async move {
5891                        run_e2e_with_retry(state, &shell, &commands, &worktree, budget, &context)
5892                            .await
5893                    }
5894                },
5895            )
5896            .await;
5897            if verify_inconclusive(&e2e) {
5898                return Ok(GateFix::Defer);
5899            }
5900            if e2e.iter().any(|o| !o.ok()) {
5901                self.state.event(
5902                    "gate",
5903                    format!("gate-fix round {attempt}: verify.e2e failed after the fix"),
5904                );
5905                return Ok(GateFix::Stop);
5906            }
5907        }
5908        Ok(GateFix::Retry)
5909    }
5910
5911    // ---------------------------------------------------------------- merge
5912
5913    /// One read-only rewrite by the summary's author, followed by a fixed fallback.
5914    async fn guarded_pr_message(
5915        &mut self,
5916        winner: &Candidate,
5917        facts: Option<&BranchFacts>,
5918        posting: bool,
5919    ) -> PrMessage {
5920        let mut pr = pr_message_raw(&self.state, winner.label, facts);
5921        if !posting {
5922            let identity = crate::scrub::Identity::current();
5923            return PrMessage {
5924                title: crate::scrub::scrub(&pr.title, &identity),
5925                body: crate::scrub::scrub(&pr.body, &identity),
5926            };
5927        }
5928        let mut violations = crate::github_text::check(&pr.title, &pr.body);
5929        let identity = crate::scrub::Identity::current();
5930        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
5931            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
5932            && !violations.contains(&crate::github_text::Violation::SensitiveData)
5933        {
5934            violations.push(crate::github_text::Violation::SensitiveData);
5935        }
5936        // Sensitive-only hits are handled by `prepare`'s span redaction; a
5937        // rewrite cannot fix them (e.g. a quoted original task) and the
5938        // fallback would discard a useful description.
5939        violations.retain(|v| *v != crate::github_text::Violation::SensitiveData);
5940        if self.state.config.graph.github_text_guard && !violations.is_empty() {
5941            self.state.event(
5942                "github-text",
5943                format!("description rejected: {violations:?}; requesting one rewrite"),
5944            );
5945            let mut rewritten = false;
5946            if let Some(spec) = self
5947                .state
5948                .config
5949                .agents
5950                .iter()
5951                .find(|a| a.id == winner.agent)
5952                .cloned()
5953            {
5954                let key = format!("impl-{}", winner.label);
5955                let seat = self.seat(&key, &spec.id);
5956                let prompt = format!(
5957                    "Rewrite only the following pull request description. The posting gate reported {violations:?}. Write English prose and remove all machine or operator identifying data and secrets. Do not edit files or run commands. Return TITLE: followed by the title, then the complete Markdown body. Preserve the magi run marker.\n\nTITLE: {}\n{}",
5958                    pr.title, pr.body
5959                );
5960                let job = SeatJob {
5961                    spec,
5962                    seat,
5963                    cwd: winner.worktree.clone(),
5964                    prompt,
5965                    timeout: retry_budget(
5966                        Duration::from_secs(self.state.config.graph.timeout_implement),
5967                        true,
5968                    ),
5969                    allow_write: false,
5970                    sessions: self.state.config.graph.sessions,
5971                    artifacts: agent::artifacts_dir(&self.state.dir()),
5972                    stem: "github-text-rewrite".to_owned(),
5973                    handover: None,
5974                };
5975                let prompts = self.state.config.prompts.clone();
5976                let cache = self.state.config.cache_dir();
5977                let run = self.state.id.clone();
5978                let ctx = WaveCtx {
5979                    run: &run,
5980                    node: "github-text",
5981                    prompts: &prompts,
5982                    cache: cache.as_deref(),
5983                    round: None,
5984                    carry_seats: false,
5985                };
5986                let (seat, outcome) =
5987                    run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
5988                self.state.seats.insert(seat.key.clone(), seat);
5989                if let AgentOutcome::Ok(output) = outcome
5990                    && let Some(title) = summary_title(&output.text)
5991                {
5992                    let mut body = summary_without_title(&output.text);
5993                    if !body.trim().is_empty()
5994                        && crate::github_text::check(&title, &body).is_empty()
5995                    {
5996                        let marker = format!("magi:run/{}", self.state.id);
5997                        if !body.contains(&marker) {
5998                            body.push_str(&format!("\n\n{marker}"));
5999                        }
6000                        pr = PrMessage { title, body };
6001                        rewritten = true;
6002                        self.state
6003                            .event("github-text", "description rewrite passed");
6004                    }
6005                }
6006            }
6007            if !rewritten {
6008                self.state.event(
6009                    "github-text",
6010                    "description rewrite unavailable or rejected; using neutral body",
6011                );
6012                pr = PrMessage {
6013                    title: pr.title,
6014                    body: format!(
6015                        "{}\n\nmagi:run/{}",
6016                        crate::github_text::NEUTRAL_BODY,
6017                        self.state.id
6018                    ),
6019                };
6020            }
6021        }
6022        let (title, body) = crate::github_text::prepare(&mut self.state, &pr.title, &pr.body);
6023        PrMessage { title, body }
6024    }
6025
6026    async fn merge(&mut self) -> Result<()> {
6027        // Same reasoning as `gate`: ask the review and gate records directly
6028        // rather than `status`, which a solo-candidate `judge`/`deliberate`
6029        // skip can rewrite on reentry to something that no longer says
6030        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
6031        // so a hand-off (open findings, green verification) reaches merge
6032        // exactly like a genuinely clean round does.
6033        //
6034        // A run resumed mid-`land` never reaches here at all: `execute`
6035        // recognises `RunStatus::Landing` before it even calls `prep`, and
6036        // routes straight to `run_land` instead. That has to happen a level
6037        // up from this function, not with a check in here, because
6038        // `review_loop`'s own status recomputation (see its doc) runs
6039        // *before* `merge` on every reentry and would otherwise overwrite
6040        // the `Landing` marker with `Gating` before this node ever saw it.
6041        if self
6042            .state
6043            .base_sync
6044            .as_ref()
6045            .is_some_and(|s| s.conflict.is_some())
6046            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
6047                != Some(RunStatus::Gating)
6048            // `gate_ran == false` is not "passed" - `gate` leaves it false
6049            // both before it has ever run and when its last attempt was
6050            // resource-blocked (see `Runner::gate`'s own doc), and neither is
6051            // permission to merge on nothing but the review record. Only a
6052            // gate that actually ran - zero commands configured and
6053            // vacuously passed, or one or more that all exited 0 - may
6054            // proceed; `RunState::gate_status` is the single place that
6055            // reading is computed.
6056            || !self.state.gate_status().ok()
6057        {
6058            return Ok(());
6059        }
6060        // This node's own record, not `status`: `status == Ready` is not
6061        // unique to the harmless `MergeMode::None` path this line was
6062        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
6063        // run's PR was closed without merging — and on that run `mode` is
6064        // still `Pr`, so a reentry that fell through here would push and
6065        // open a second pull request. `self.state.merge` is set exactly once
6066        // this node (or `land`) has already produced a verdict, under every
6067        // mode, which is what "already done" actually means here.
6068        if self.state.merge.is_some() {
6069            return Ok(());
6070        }
6071        let Some(winner) = self.state.winner().cloned() else {
6072            return Ok(());
6073        };
6074        let repo = self.state.repo.clone();
6075        let base = self.state.base_branch.clone();
6076        let mode = self.state.config.merge.mode;
6077        let style = self.state.config.merge.style;
6078        let facts = if is_review_run(&self.state) {
6079            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6080            let start = review_base(
6081                &repo,
6082                &self.state.config.merge.remote,
6083                &base,
6084                &self.state.base_commit,
6085                &winner.branch,
6086            )
6087            .await;
6088            branch_facts(&repo, &start, &winner.branch).await
6089        } else {
6090            None
6091        };
6092        // `None` when the base could not be freshly read: then an adopted
6093        // pull request's title is left alone.
6094        let leaked = if is_review_run(&self.state) {
6095            leaked_subjects(&self.state, &winner.branch).await
6096        } else {
6097            Some(Vec::new())
6098        };
6099        let pr = self
6100            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
6101            .await;
6102        let message = pr.commit_message();
6103
6104        let outcome = match mode {
6105            MergeMode::None => MergeOutcome {
6106                mode,
6107                ok: true,
6108                detail: manual_merge_command(style, &repo, &winner.branch, &message),
6109                empty: false,
6110            },
6111            MergeMode::Pr | MergeMode::Local
6112                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
6113            {
6114                MergeOutcome {
6115                    mode,
6116                    ok: false,
6117                    detail: empty_candidate_detail(&self.state, &base),
6118                    empty: true,
6119                }
6120            }
6121            MergeMode::Local => {
6122                let on = git::current_branch(&repo).await?;
6123                if on.as_deref() != Some(base.as_str()) {
6124                    MergeOutcome {
6125                        mode,
6126                        ok: false,
6127                        detail: format!(
6128                            "{} has {} checked out, not the base branch {base}",
6129                            repo.display(),
6130                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
6131                        ),
6132                        empty: false,
6133                    }
6134                } else if !git::is_clean(&repo).await? {
6135                    MergeOutcome {
6136                        mode,
6137                        ok: false,
6138                        detail: format!("{} is dirty; refusing to merge", repo.display()),
6139                        empty: false,
6140                    }
6141                } else {
6142                    let out = match style {
6143                        MergeStyle::Merge => {
6144                            git::merge_no_ff(&repo, &winner.branch, &message).await?
6145                        }
6146                        MergeStyle::Squash => {
6147                            git::merge_squash(&repo, &winner.branch, &message).await?
6148                        }
6149                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
6150                    };
6151                    MergeOutcome {
6152                        mode,
6153                        ok: out.ok(),
6154                        detail: if out.ok() { out.stdout } else { out.stderr },
6155                        empty: false,
6156                    }
6157                }
6158            }
6159            MergeMode::Pr => {
6160                let remote = self.state.config.merge.remote.clone();
6161                let pushed = git::push(&winner.worktree, &remote, &winner.branch).await?;
6162                if !pushed.ok() {
6163                    MergeOutcome {
6164                        mode,
6165                        ok: false,
6166                        detail: pushed.stderr,
6167                        empty: false,
6168                    }
6169                } else {
6170                    // A retry or resume of a run whose branch already has an
6171                    // open pull request adopts it rather than failing on a
6172                    // duplicate. Only this winner branch into this base:
6173                    // `branch_for` derives the name from the run id, so a
6174                    // different run's pull request never matches.
6175                    let found = land::find_open_pr(&winner.worktree, &winner.branch, &base).await;
6176                    let out = match pr_merge_plan(found) {
6177                        PrPlan::Create => {
6178                            gh_pr_create(
6179                                &winner.worktree,
6180                                &base,
6181                                &winner.branch,
6182                                &pr.title,
6183                                &pr.body,
6184                            )
6185                            .await
6186                        }
6187                        PrPlan::Adopt { url, title } => {
6188                            self.state
6189                                .event("merge", format!("Pr: adopted open pull request {url}"));
6190                            if title != pr.title
6191                                && (!is_review_run(&self.state)
6192                                    || leaked
6193                                        .as_deref()
6194                                        .is_some_and(|l| should_retitle(&title, &pr.title, l)))
6195                                && let Err(e) = land::set_pr_title(
6196                                    &mut self.state,
6197                                    &winner.worktree,
6198                                    &url,
6199                                    &pr.title,
6200                                )
6201                                .await
6202                            {
6203                                tracing::warn!("could not refresh title of {url}: {e:#}");
6204                                self.state
6205                                    .event("merge", format!("Pr: title refresh failed: {e:#}"));
6206                            }
6207                            Ok(url)
6208                        }
6209                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
6210                    };
6211                    match out {
6212                        Ok(url) => MergeOutcome {
6213                            mode,
6214                            ok: true,
6215                            detail: url,
6216                            empty: false,
6217                        },
6218                        Err(e) => MergeOutcome {
6219                            mode,
6220                            ok: false,
6221                            detail: e.to_string(),
6222                            empty: false,
6223                        },
6224                    }
6225                }
6226            }
6227        };
6228
6229        self.state.status = match (mode, outcome.ok) {
6230            (MergeMode::None, _) => RunStatus::Ready,
6231            (_, true) => RunStatus::Merged,
6232            (_, false) => RunStatus::Blocked,
6233        };
6234        self.state.event(
6235            "merge",
6236            format!(
6237                "{:?}: {}",
6238                mode,
6239                outcome.detail.lines().next().unwrap_or("")
6240            ),
6241        );
6242        self.state.merge = Some(outcome);
6243        self.state.save()?;
6244
6245        // The PR is open and the run would historically stop here, leaving the
6246        // operator to watch checks, feed review comments back to a fixer, and
6247        // merge. That was done by hand six times in one session before this
6248        // existed. Opt-in, because merging is the one irreversible thing magi
6249        // can do to a repository.
6250        if self.state.config.graph.land
6251            && mode == MergeMode::Pr
6252            && self.state.status == RunStatus::Merged
6253        {
6254            self.run_land().await?;
6255        }
6256        // `run_land` may have left `status` at `Landing` - still waiting on
6257        // CI or the owner's approval, not actually settled - so this has to
6258        // read whatever `status` ended up as here, not the `Merged` this
6259        // function set a few lines up.
6260        self.settle_questions();
6261        Ok(())
6262    }
6263
6264    /// Enter `land`.
6265    ///
6266    /// Shared between a fresh run's first pass through [`Runner::merge`] and
6267    /// a resumed run's re-entry. `land::land` itself is what serialises the
6268    /// two git-mutating moments inside the loop — the rebase push and
6269    /// `gh pr merge` — per repository (see its own doc); nothing here needs
6270    /// to hold a lock across the whole call, and doing so would serialise
6271    /// this run's CI wait against a *different* run's land-approval resume
6272    /// in the same repository, which is exactly the "must not wait on
6273    /// another task" property the daemon's slot-freeing exists to give.
6274    async fn run_land(&mut self) -> Result<()> {
6275        let url = self
6276            .state
6277            .merge
6278            .as_ref()
6279            .map(|m| m.detail.clone())
6280            .unwrap_or_default();
6281        let url = url.lines().next().unwrap_or("").trim().to_owned();
6282        if !url.starts_with("http") {
6283            return Ok(());
6284        }
6285        // A land failure is not a lost run: the work is on a branch and the
6286        // pull request is open, which is exactly where a human takes over.
6287        match land::land(&mut self.state, &url).await {
6288            Ok(pr) if self.state.parked => {
6289                // `land` already saved the parked marker; nothing here
6290                // overrides `status` back to a terminal value while an
6291                // approval is still outstanding.
6292                let _ = pr;
6293            }
6294            Ok(pr) => {
6295                self.state.status = match pr.state {
6296                    land::PrLifecycle::Merged => RunStatus::Merged,
6297                    _ => RunStatus::Blocked,
6298                };
6299                // Downstream of a confirmed merge only - see
6300                // `bump::should_release_bump`'s own doc for why this one
6301                // check covers all three of `land`'s success paths.
6302                // Best-effort: the run already landed, so a failure here
6303                // (the decision call, `gh`, `cargo`) is recorded and never
6304                // turns a landed run into a failed one.
6305                if bump::should_release_bump(self.state.status)
6306                    && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
6307                {
6308                    // The event is the run's own record. Not-eligible cases
6309                    // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
6310                    // `Err` is a bump that was tried and failed:
6311                    // `after_merge` itself raises the operator notice for
6312                    // that, whether or not a release PR exists yet.
6313                    self.state
6314                        .event("bump", format!("release bump skipped: {e:#}"));
6315                }
6316                // Independent of the bump, and best-effort in the same way:
6317                // findings the merge left open become follow-up tasks.
6318                if self.state.status == RunStatus::Merged {
6319                    crate::followup::after_merge(&mut self.state, &pr.url).await;
6320                }
6321                self.state.save()?;
6322            }
6323            Err(e) => {
6324                self.state.status = RunStatus::Blocked;
6325                self.state.event("land", format!("gave up: {e}"));
6326                self.state.save()?;
6327            }
6328        }
6329        Ok(())
6330    }
6331
6332    // -------------------------------------------------------------- helpers
6333
6334    /// Fetch or create a seat, keeping its conversation across nodes.
6335    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
6336        if let Some(existing) = self.state.seats.get(key)
6337            && existing.agent == agent
6338        {
6339            return existing.clone();
6340        }
6341        // A seat that changes agent mints its session id from the agent too,
6342        // like a handover: the old agent's uuid is already taken by the CLI.
6343        let fresh = if self.state.seats.contains_key(key) {
6344            handover_seat(key, agent, self.state.next_seat_seed())
6345        } else {
6346            SeatState::new(key, agent, self.state.seed)
6347        };
6348        self.state.seats.insert(key.to_owned(), fresh.clone());
6349        fresh
6350    }
6351
6352    /// The agent now holding seat `key`: `spec`, unless a handover moved the
6353    /// seat to another roster agent, in which case that agent. Nodes that
6354    /// continue a seat's conversation (deliberation, the votes, a reviewer's
6355    /// reconsideration) must keep talking to whoever answered it, not slip
6356    /// back to the agent that failed it.
6357    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
6358        match self.state.seats.get(key) {
6359            Some(s) if s.agent != spec.id => {
6360                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
6361            }
6362            _ => spec,
6363        }
6364    }
6365
6366    /// A candidate rendered for judging, with the leak policy applied.
6367    fn view(&self, c: &Candidate) -> CandidateView {
6368        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
6369            .unwrap_or_default();
6370        let (patch, _) = blind::sanitize_patch(
6371            &format!("candidate {} patch", c.label),
6372            &raw,
6373            &self.state.config.blind,
6374        );
6375        CandidateView {
6376            label: c.label,
6377            branch: c.branch.clone(),
6378            summary: c.summary.clone(),
6379            stat: c.stat.clone(),
6380            patch,
6381        }
6382    }
6383
6384    /// The full candidate set as prompt text, for seats with no live session.
6385    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
6386        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
6387        prompt::judge(
6388            "(see above)",
6389            &views,
6390            self.roles.judges.len(),
6391            base_short,
6392            "en",
6393        )
6394    }
6395
6396    /// The final-vote prompt with everything a seat that has no session of its
6397    /// own needs: the candidates, the seat's own ranking and reasons, and the
6398    /// anonymised deliberation it took part in (only when there was one, so a
6399    /// handed-over seat never sees more than the seat it replaces did). The
6400    /// `Final vote` heading stays first.
6401    fn vote_prompt_full(
6402        &self,
6403        j: usize,
6404        labels: &[char],
6405        language: &str,
6406        candidates: &[Candidate],
6407        base_short: &str,
6408    ) -> String {
6409        let mut text = format!(
6410            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
6411            prompt::final_vote(labels, language),
6412            self.state.instruction,
6413            self.candidate_block(candidates, base_short)
6414        );
6415        if let Some(own) = self
6416            .state
6417            .judgements
6418            .get(j)
6419            .filter(|r| !r.ranking.is_empty())
6420        {
6421            let reasons = own
6422                .reasons
6423                .iter()
6424                .map(|(k, v)| format!("- {k}: {v}"))
6425                .collect::<Vec<_>>()
6426                .join("\n");
6427            text.push_str(&format!(
6428                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
6429                own.ranking.iter().collect::<String>(),
6430                if reasons.is_empty() {
6431                    ""
6432                } else {
6433                    ", because:\n"
6434                }
6435            ));
6436        }
6437        if !self.state.deliberation.is_empty() {
6438            text.push_str("\n# What was argued before this vote\n");
6439            for t in self.transcript(&[], j) {
6440                text.push_str(&format!(
6441                    "\n## {}{}\n\n{}\n",
6442                    t.who,
6443                    if t.is_self { " (you)" } else { "" },
6444                    t.body.trim()
6445                ));
6446            }
6447        }
6448        text
6449    }
6450
6451    /// Anonymised transcript for judge `self_idx`.
6452    ///
6453    /// The initial rankings are always the opening statements. Seeding them
6454    /// only when no turn had been taken yet meant every judge after the first
6455    /// argued against a single voice instead of against the actual split — the
6456    /// disagreement is the information, so it is always on the table.
6457    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
6458        let mut turns = Vec::new();
6459        for j in &self.state.judgements {
6460            if j.ranking.is_empty() {
6461                continue;
6462            }
6463            let reasons = j
6464                .reasons
6465                .iter()
6466                .map(|(k, v)| format!("- {k}: {v}"))
6467                .collect::<Vec<_>>()
6468                .join("\n");
6469            turns.push(Turn {
6470                who: format!("Judge {} (opening ranking)", j.judge),
6471                is_self: j.judge == self_idx + 1,
6472                body: format!(
6473                    "Ranked {}{}{reasons}",
6474                    j.ranking.iter().collect::<String>(),
6475                    if reasons.is_empty() {
6476                        ""
6477                    } else {
6478                        ", because:\n"
6479                    }
6480                ),
6481            });
6482        }
6483        for t in self
6484            .state
6485            .deliberation
6486            .iter()
6487            .flat_map(|r| r.turns.iter())
6488            .chain(current)
6489        {
6490            turns.push(Turn {
6491                who: format!("Judge {}", t.judge),
6492                is_self: t.judge == self_idx + 1,
6493                body: t.body.clone(),
6494            });
6495        }
6496        turns
6497    }
6498}
6499
6500/// Does this seat still hold the context a follow-up prompt would rely on?
6501fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
6502    agent::has_session(spec.kind, seat, sessions)
6503}
6504
6505/// The next entry in `roster` after `start`, never wrapping back to the
6506/// front, whose id is not in `tried` yet.
6507///
6508/// Starts one past `start` rather than at the front of `roster`: `start` is
6509/// the seat's own original position, and a seat whose candidate slot already
6510/// sits on the roster's second entry must fall through to the third next, not
6511/// restart at the first — which is very likely a different candidate's own
6512/// agent already. Never wraps back past `start`, for the same reason: an
6513/// entry earlier in the roster than the seat's own position is almost
6514/// certainly some *other* candidate slot's own agent, and once the tail of
6515/// the roster is exhausted there are no more untried agents for *this* seat
6516/// to fall through to — the caller's fallback chain ends there, exactly as
6517/// "no further untried agents remain in the list for that seat" asks for.
6518///
6519/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
6520/// the same id twice (an operator's `roles.implementers` typo, or a
6521/// `[[agents]]` list reused across roles) must not let
6522/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
6523/// over `roster` either finds an untried id or runs out, so this always
6524/// terminates regardless of duplicates.
6525fn next_untried_in_roster<'a>(
6526    roster: &'a [AgentSpec],
6527    start: usize,
6528    tried: &BTreeSet<String>,
6529) -> Option<&'a AgentSpec> {
6530    roster
6531        .get(start + 1..)?
6532        .iter()
6533        .find(|s| !tried.contains(&s.id))
6534}
6535
6536/// The successor for a seat, shared by all four seat kinds (implement, judge,
6537/// review, advise). `others` holds the ids that *currently* occupy the other
6538/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
6539/// sees them), so roster entries beyond the seat count act as spares: a failed
6540/// seat goes to an agent no other seat holds whenever the roster permits.
6541///
6542/// `carried` is `Some` only for the review loop's carried failure history.
6543/// Order: (1) forward from `start`, never wrapping, untried, not a carried
6544/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
6545/// whole roster: untried and not another seat's occupant; (3) the plain walk
6546/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
6547/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
6548/// a better outcome than an empty seat, and it keeps the answer to "is there
6549/// a successor at all" exactly what it was before occupants were considered,
6550/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
6551/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
6552/// carried failure is a cheaper bet than doubling an agent on the panel, and
6553/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
6554/// the same round are handled one at a time, so a seat later in the batch
6555/// sees an earlier one's new occupant but not yet its own freed agent.
6556fn pick_successor<'a>(
6557    roster: &'a [AgentSpec],
6558    start: usize,
6559    tried: &BTreeSet<String>,
6560    carried: Option<&BTreeSet<String>>,
6561    others: &BTreeSet<String>,
6562) -> Option<&'a AgentSpec> {
6563    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
6564    roster
6565        .get(start + 1..)
6566        .and_then(|tail| {
6567            tail.iter()
6568                .filter(free)
6569                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
6570        })
6571        .or_else(|| {
6572            carried
6573                .is_some()
6574                .then(|| roster.iter().find(free))
6575                .flatten()
6576        })
6577        .or_else(|| match carried {
6578            Some(c) => next_for_seat(roster, start, tried, c),
6579            None => next_untried_in_roster(roster, start, tried),
6580        })
6581}
6582
6583/// The next agent for a seat that carries its failure history across rounds
6584/// (the review loop). `round_tried` is this round's own bound and starts
6585/// empty every round; `carried_failed` only decides priority.
6586///
6587/// First: an id walking forward from `start`, never wrapping, that is neither
6588/// tried this round nor failed in an earlier one. Only when that is exhausted
6589/// does it rescue: the first roster id (in roster order, so this one *does*
6590/// look before `start`) not yet tried this round, which is by then a carried
6591/// failure. Each id is rescued at most once per round, so it cannot loop.
6592fn next_for_seat<'a>(
6593    roster: &'a [AgentSpec],
6594    start: usize,
6595    round_tried: &BTreeSet<String>,
6596    carried_failed: &BTreeSet<String>,
6597) -> Option<&'a AgentSpec> {
6598    roster
6599        .get(start + 1..)?
6600        .iter()
6601        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
6602        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
6603}
6604
6605/// Where a reviewer seat starts a round: the agent that last answered it when
6606/// it is still on the roster and not marked failed, else the spec's own agent
6607/// unless it failed, else the next roster agent that has not failed, else the
6608/// spec's own agent again (the whole roster failed). Ids no longer on the
6609/// roster are ignored. An empty roster has no handover, so the spec stands.
6610fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
6611    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
6612        return spec;
6613    };
6614    let ok = |id: &str| !h.failed.contains(id);
6615    if let Some(last) = h.last_ok.as_deref()
6616        && ok(last)
6617        && let Some(s) = roster.iter().find(|s| s.id == last)
6618    {
6619        return s.clone();
6620    }
6621    if ok(&spec.id) {
6622        return spec;
6623    }
6624    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
6625    roster
6626        .get(from + 1..)
6627        .into_iter()
6628        .flatten()
6629        .chain(roster.iter())
6630        .find(|s| ok(&s.id))
6631        .cloned()
6632        .unwrap_or(spec)
6633}
6634
6635/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
6636/// seed so a CLI that mints its session id up front (`--session-id`) never
6637/// reuses the uuid the previous agent already opened under the same seat key.
6638pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
6639    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
6640}
6641
6642/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
6643/// so the classifier below and the code that builds the message cannot drift.
6644const TIMED_OUT: &str = "timed out";
6645
6646impl FailClass {
6647    /// `None` for an answer; otherwise how the turn failed.
6648    fn of(out: &AgentOutcome) -> Option<Self> {
6649        match out {
6650            AgentOutcome::Ok(_) => None,
6651            AgentOutcome::Quota(_) => Some(Self::Quota),
6652            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
6653            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
6654            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
6655        }
6656    }
6657
6658    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
6659    fn stem_word(&self) -> &'static str {
6660        match self {
6661            Self::Quota => "quota",
6662            _ => "handover",
6663        }
6664    }
6665}
6666
6667/// The message's first line with its variable parts removed — digit runs and
6668/// path-like tokens — so "exited with Some(2)" and "exited with Some(7)" read
6669/// as one kind of failure.
6670fn failure_signature(msg: &str) -> String {
6671    let line = msg.lines().next().unwrap_or("").trim().to_lowercase();
6672    let mut out = Vec::new();
6673    for word in line.split_whitespace() {
6674        if word.contains('/') || word.contains('\\') {
6675            out.push("<path>".to_owned());
6676            continue;
6677        }
6678        let mut w = String::new();
6679        let mut in_digits = false;
6680        for c in word.chars() {
6681            if c.is_ascii_digit() {
6682                if !in_digits {
6683                    w.push('#');
6684                }
6685                in_digits = true;
6686            } else {
6687                in_digits = false;
6688                w.push(c);
6689            }
6690        }
6691        out.push(w);
6692    }
6693    out.join(" ").chars().take(120).collect()
6694}
6695
6696/// Whether a seat that just failed with `cur` may go to the next roster agent.
6697/// A quota or a timeout always may. Any other failure may not when the agent
6698/// before it failed the same way: an error the prompt causes would otherwise
6699/// walk the whole roster. `prev` is the class of the immediately preceding
6700/// agent's failure, so a quota or timeout in between breaks the run of
6701/// identical failures by itself.
6702fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
6703    match cur {
6704        FailClass::Quota | FailClass::Timeout => true,
6705        FailClass::Other(_) => prev != Some(cur),
6706    }
6707}
6708
6709/// A short human reason for a failed outcome, for the handover record.
6710fn fail_reason(out: &AgentOutcome) -> String {
6711    match out {
6712        AgentOutcome::Ok(_) => String::new(),
6713        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
6714        AgentOutcome::Dropped(o) => format!(
6715            "the CLI dropped the stream ({})",
6716            o.dropped
6717                .as_ref()
6718                .map(|d| d.why.as_str())
6719                .unwrap_or("it ended without delivering its answer")
6720        ),
6721        AgentOutcome::Failed(e) => e.lines().next().unwrap_or("").chars().take(160).collect(),
6722    }
6723}
6724
6725/// Note one handover in the run: the structured record and, in the timeline,
6726/// the sentence a person reads. A quota keeps the wording it always had.
6727pub(crate) fn record_handover(
6728    state: &mut RunState,
6729    node: &str,
6730    seat: &str,
6731    from: &str,
6732    to: &str,
6733    class: &FailClass,
6734    reason: &str,
6735) {
6736    let message = if *class == FailClass::Quota {
6737        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
6738    } else {
6739        format!("{seat}: handed over {from} -> {to} ({reason})")
6740    };
6741    state.event(node, message);
6742    state.handovers.push(Handover {
6743        at: Timestamp::now(),
6744        node: node.to_owned(),
6745        seat: seat.to_owned(),
6746        from: from.to_owned(),
6747        to: to.to_owned(),
6748        reason: reason.to_owned(),
6749    });
6750}
6751
6752/// Did this reply report running a command whose own CLI never confirmed an
6753/// exit status?
6754///
6755/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
6756/// command *finished* (see that type's own doc), so this can only be `true`
6757/// for a command whose completion event carried no readable exit code — not
6758/// for one that simply is not mentioned at all. That is the one signal this
6759/// crate can read, from the same record `state.jobs` renders, about a reply
6760/// standing next to work its own CLI cannot vouch for finishing; it is
6761/// deliberately not a check on the exit code's *value* (a fixer legitimately
6762/// runs a command that fails mid-iteration before it succeeds) and not a
6763/// guess at a command still running in the background (which emits no event
6764/// at all, and so leaves no evidence here to find).
6765fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
6766    commands.iter().any(|c| c.exit_code.is_none())
6767}
6768
6769/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
6770/// trusted as a verified no-op — the adoption guard's own text-level half.
6771///
6772/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
6773/// timed out): a marker only earns the benefit of the doubt from a turn the
6774/// CLI itself vouches for finishing properly, the same house style
6775/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
6776/// *fix* report to for `commands`. A candidate that timed out, exited
6777/// non-zero, or left a command unconfirmed is read as the ordinary loss it
6778/// is, whatever prose it wrote — this returns `None` before it ever looks at
6779/// `text`. The remaining guards (the tree really is empty, the evidence is
6780/// non-empty) are the caller's: this only reads what the reply *claimed*.
6781fn verified_noop_claim(
6782    usable: bool,
6783    commands: &[agent::CommandEvidence],
6784    text: &str,
6785) -> Option<String> {
6786    (usable && !has_unconfirmed_command(commands))
6787        .then(|| verdict::verified_noop(text))
6788        .flatten()
6789}
6790
6791fn short(commit: &str) -> String {
6792    commit.chars().take(7).collect()
6793}
6794
6795fn make_executable(path: &Path) -> Result<()> {
6796    #[cfg(unix)]
6797    {
6798        use std::os::unix::fs::PermissionsExt as _;
6799        let mut perms = std::fs::metadata(path)?.permissions();
6800        perms.set_mode(0o755);
6801        std::fs::set_permissions(path, perms)?;
6802    }
6803    #[cfg(not(unix))]
6804    {
6805        let _ = path;
6806    }
6807    Ok(())
6808}
6809
6810/// What every seat in one batch shares: where the answers are attributed, the
6811/// prompt overlay they inherit, and the build cache they are told to use.
6812///
6813/// A struct rather than four more parameters: `wave` also needs the run's
6814/// state (to record who is answering right now) and the attempt number, and
6815/// eight positional arguments is both unreadable and a clippy error.
6816struct WaveCtx<'a> {
6817    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
6818    /// paid for it.
6819    run: &'a str,
6820    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
6821    node: &'a str,
6822    prompts: &'a Prompts,
6823    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
6824    cache: Option<&'a Path>,
6825    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
6826    /// `JobRecord::round`. `None` for every other node.
6827    round: Option<usize>,
6828    /// Carry each seat's failed-agent history across waves (the review loop
6829    /// only): start-of-round priority and handover choice read
6830    /// [`RunState::seat_history`], and every answer or failure writes it.
6831    carry_seats: bool,
6832}
6833
6834/// Run one job, honouring the parallelism budget.
6835async fn run_one(
6836    job: SeatJob,
6837    sem: Arc<Semaphore>,
6838    ctx: &WaveCtx<'_>,
6839    state: &mut RunState,
6840    attempt: usize,
6841) -> (SeatState, AgentOutcome) {
6842    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
6843        .await
6844        .pop()
6845        .expect("one job in, one result out");
6846    (seat, out)
6847}
6848
6849/// Run every job concurrently, capped by the semaphore, preserving order.
6850///
6851/// Every seat in the batch is recorded into [`RunState::active`] before the
6852/// wave starts and cleared as each answer lands, so the run's own record says
6853/// who is still being waited on rather than only who finished.
6854async fn wave(
6855    jobs: Vec<SeatJob>,
6856    sem: Arc<Semaphore>,
6857    ctx: &WaveCtx<'_>,
6858    state: &mut RunState,
6859    attempt: usize,
6860) -> Vec<(usize, SeatState, AgentOutcome)> {
6861    let WaveCtx {
6862        run,
6863        node,
6864        prompts,
6865        cache,
6866        round,
6867        carry_seats: _,
6868    } = *ctx;
6869    for job in &jobs {
6870        state.seat_started(node, &job.seat.key, job.timeout, attempt);
6871    }
6872    if let Err(e) = state.save() {
6873        // A failed persist of "who is answering right now" must not abort the
6874        // wave: the seats are already being asked, and the alternative is
6875        // losing the answers to save a status line nobody may even be
6876        // watching.
6877        tracing::warn!("could not persist in-progress seats: {e:#}");
6878    }
6879    // Hold the shared build cache's lease for the whole batch, not per job:
6880    // several candidates (an implement wave) or a fixer legitimately share
6881    // one cache concurrently within this run, and that stays untouched — a
6882    // single lease taken once for the whole wave and released once it is
6883    // done is what stops a *different* borrower (another run's own wave, its
6884    // e2e/gate, a human's `magi review`) from interleaving a build into the
6885    // same directory while this one is in flight. Best-effort, not
6886    // all-or-nothing: a wave that cannot get the lease within its own
6887    // longest job's budget still runs — an hour of paid implementer calls is
6888    // not thrown away over cache contention — but every write-allowed seat
6889    // then goes without `CARGO_TARGET_DIR` for this wave too (see the filter
6890    // below), the same fallback a read-only seat always gets, rather than
6891    // building into a directory this run was never granted. The identity
6892    // record is still invalidated below either way, so the next tracked
6893    // caller (`e2e`/`gate`) never trusts a match it cannot vouch for.
6894    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
6895    let wait_started = Instant::now();
6896    let cache_guard = if let Some(cache_dir) = cache {
6897        if jobs_had_a_writer {
6898            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
6899            let budget = jobs
6900                .iter()
6901                .map(|j| j.timeout)
6902                .max()
6903                .unwrap_or(Duration::from_secs(60));
6904            acquire_cache_lease(state, cache_dir, &owner, budget, node)
6905                .await
6906                .ok()
6907        } else {
6908            None
6909        }
6910    } else {
6911        None
6912    };
6913    // Carved out of each job's own budget, not added on top of it: a seat
6914    // that waited behind the lease must not also get its full timeout
6915    // afterward, or a run contended on the cache could double the time it
6916    // spends per wave. `saturating_sub` floors at zero rather than
6917    // wrapping - a job whose whole budget was spent waiting starts with
6918    // none left, which is the honest number, not a free minimum.
6919    let waited_for_lease = wait_started.elapsed();
6920    let mut set = tokio::task::JoinSet::new();
6921    let overlay = prompts.overlay(node);
6922    for (i, mut job) in jobs.into_iter().enumerate() {
6923        job.timeout = job.timeout.saturating_sub(waited_for_lease);
6924        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
6925        if cache.is_some() {
6926            job.prompt.push('\n');
6927            job.prompt
6928                .push_str(&prompt::build_cache_note(node, job.allow_write));
6929        }
6930        let sem = Arc::clone(&sem);
6931        let run = run.to_owned();
6932        let node = node.to_owned();
6933        // Only implementers were told about the task's attachments, so only
6934        // their seats get the directory widened for reading.
6935        let attachments = if node == "implement" {
6936            state.attachments.clone()
6937        } else {
6938            Vec::new()
6939        };
6940        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
6941        // `prompt::build_cache_note`'s doc for why setting it anyway is
6942        // exactly how a sandboxed reviewer's write refusal got reported as a
6943        // defect in the patch, not a property of its own seat. And a
6944        // write-allowed one is handed it only when the lease above was
6945        // actually acquired: a wave that could not get it (`cache_guard` is
6946        // `None`, see its own comment) must not send seats to build into a
6947        // directory this run does not hold - that is the exact concurrent,
6948        // unmanaged-write race this module exists to prevent, not something
6949        // "proceeding anyway" is allowed to reintroduce.
6950        let cache = cache
6951            .filter(|_| job.allow_write && cache_guard.is_some())
6952            .map(Path::to_path_buf);
6953        set.spawn(async move {
6954            let _permit = sem.acquire().await;
6955            let mut seat = job.seat;
6956            let out = agent::invoke(
6957                &job.spec,
6958                &mut seat,
6959                &Invocation {
6960                    cwd: &job.cwd,
6961                    prompt: &job.prompt,
6962                    timeout: job.timeout,
6963                    allow_write: job.allow_write,
6964                    sessions: job.sessions,
6965                    artifacts: &job.artifacts,
6966                    stem: &job.stem,
6967                    run: &run,
6968                    node: &node,
6969                    cache_dir: cache.as_deref(),
6970                    attachments: &attachments,
6971                    writable: &[],
6972                },
6973            )
6974            .await;
6975            let out = match out {
6976                Ok(o) if o.usable() => AgentOutcome::Ok(o),
6977                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
6978                // Billed work the CLI failed to hand over is not an ordinary
6979                // failure, but its text is the CLI's raw error JSON, not an
6980                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
6981                // read it as one by forgetting to check. `usable()` is always
6982                // false here (dropped implies an empty response), so this has
6983                // to be checked before the catch-all `Failed` below or the
6984                // one shape this exists for is lost with the rest.
6985                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
6986                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
6987                Ok(o) => AgentOutcome::Failed(format!(
6988                    "exited with {:?} and no usable output",
6989                    o.exit_code
6990                )),
6991                Err(e) => AgentOutcome::Failed(e.to_string()),
6992            };
6993            (i, seat, out)
6994        });
6995    }
6996    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
6997    while let Some(joined) = set.join_next().await {
6998        let (i, seat, out) = match joined {
6999            Ok(v) => v,
7000            // No seat to clear: a panicked task never reported which one it
7001            // was. The defensive sweep below this loop is what stops that
7002            // seat's `active` entry from surviving forever.
7003            Err(e) => {
7004                tracing::error!("agent task panicked: {e}");
7005                continue;
7006            }
7007        };
7008        state.seat_finished(&seat.key);
7009        record_jobs(state, node, round, &seat.key, &out);
7010        if let Err(e) = state.save() {
7011            tracing::warn!("could not persist a seat's completion: {e:#}");
7012        }
7013        if collected.len() <= i {
7014            collected.resize_with(i + 1, || None);
7015        }
7016        collected[i] = Some((i, seat, out));
7017    }
7018    // Belt-and-braces for the panic branch above: every seat this exact batch
7019    // started shares this `(node, attempt)` pair, and every seat that finished
7020    // normally already cleared itself, so anything left tagged with it here
7021    // can only be a panicked task's leftover. Cleared unconditionally rather
7022    // than left to read as still answering forever.
7023    if state
7024        .active
7025        .values()
7026        .any(|a| a.node == node && a.attempt == attempt)
7027    {
7028        state
7029            .active
7030            .retain(|_, a| !(a.node == node && a.attempt == attempt));
7031        if let Err(e) = state.save() {
7032            tracing::warn!("could not persist the end of a wave: {e:#}");
7033        }
7034    }
7035    // Whether or not the lease above was actually held, several worktrees
7036    // may just have built into the cache with nothing here able to name one
7037    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
7038    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
7039    // clean it might not have strictly needed; trusting a stale match would
7040    // cost it a wrong answer.
7041    if let Some(cache_dir) = cache
7042        && jobs_had_a_writer
7043    {
7044        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
7045    }
7046    if let Some(guard) = cache_guard {
7047        guard.release();
7048    }
7049    collected.into_iter().flatten().collect()
7050}
7051
7052/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
7053/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
7054/// this is data collection, not the fix-specific completion contract in
7055/// [`Runner::continue_fix_report`], and applies regardless of which node
7056/// asked.
7057///
7058/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
7059/// evidence from; `Failed` does not, and correctly contributes nothing — a
7060/// timeout or crash is not itself evidence about a command the seat may have
7061/// started.
7062fn record_jobs(
7063    state: &mut RunState,
7064    node: &str,
7065    round: Option<usize>,
7066    seat: &str,
7067    out: &AgentOutcome,
7068) {
7069    let commands: &[agent::CommandEvidence] = match out {
7070        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
7071        AgentOutcome::Failed(_) => &[],
7072    };
7073    let checked_at = Timestamp::now();
7074    for c in commands {
7075        state.jobs.push(JobRecord {
7076            node: node.to_owned(),
7077            round,
7078            seat: seat.to_owned(),
7079            id: c.id.clone(),
7080            description: c.description.clone(),
7081            checked_at,
7082            status: match c.exit_code {
7083                Some(0) => JobStatus::Completed,
7084                Some(_) => JobStatus::Failed,
7085                None => JobStatus::Unknown,
7086            },
7087            exit_code: c.exit_code,
7088            result_summary: c.result_summary.clone(),
7089            source: c.source.clone(),
7090        });
7091    }
7092}
7093
7094/// Is a review round clean, given how many reviewer seats answered against
7095/// how many the round expected?
7096///
7097/// A seat that never answered (timeout, crash, unparsable output) is not a
7098/// seat that read the patch and found nothing — treating it as such is
7099/// exactly the bug this function exists to close. Under the default `block`
7100/// policy a missing seat can never be clean; `warn` still requires the seats
7101/// that *did* answer to have found nothing blocking and verification to be
7102/// green.
7103///
7104/// `quota_missing` narrows that `block` default for exactly one cause of
7105/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
7106/// a session limit lifts by the very next round buys nothing — the seat is
7107/// asked again with the same quota — so once every missing seat is accounted
7108/// for by a quota loss (and at least one seat *did* answer, so a decision has
7109/// something to rest on) the round is decided on the panel that could answer,
7110/// same as `warn` would. A panel that lost every seat to quota is not
7111/// decided here: `answered == 0` falls through to the existing `block`
7112/// fallback so a fully collapsed panel still waits rather than landing on no
7113/// review at all.
7114fn round_is_clean(
7115    blocking: usize,
7116    e2e_ok: bool,
7117    answered: usize,
7118    expected: usize,
7119    quota_missing: usize,
7120    policy: IncompleteReviewPolicy,
7121) -> bool {
7122    if blocking != 0 || !e2e_ok {
7123        return false;
7124    }
7125    if answered == expected || policy == IncompleteReviewPolicy::Warn {
7126        return true;
7127    }
7128    answered > 0 && expected - answered <= quota_missing
7129}
7130
7131/// The review loop's own conclusion, derived entirely from its persisted
7132/// round records and the round budget that produced them — never from
7133/// `status`, so a reentry (or `gate`/`merge` reading it independently)
7134/// recomputes the identical answer regardless of what an earlier node in the
7135/// same walk, or a previous walk, did to `status`.
7136///
7137/// `None` while more rounds remain to try, including when review never ran
7138/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
7139/// gone clean, or the budget is spent, or the tree has stopped moving (see
7140/// [`STAGNANT_LIMIT`]), the answer is one of two things:
7141///
7142/// - An incomplete panel that raised nothing is missing input, not a
7143///   verified tree — never a hand-off candidate, whatever verification said
7144///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
7145/// - Otherwise, green e2e on the last round hands off (see
7146///   [`Runner::stop_reviewing`]); red e2e blocks.
7147///
7148/// A last round whose own verification is still `ResourceBlocked` — magi
7149/// itself never got a command to run, not evidence the patch is broken —
7150/// is neither: this returns `None` for it too, the same as "more rounds
7151/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
7152/// handling of that shape) instead of this cheap recomputation guessing a
7153/// verdict a real attempt never produced.
7154fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
7155    if max_rounds == 0 || reviews.iter().any(|r| r.clean) {
7156        return Some(RunStatus::Gating);
7157    }
7158    let last = reviews.last()?;
7159    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
7160    if reviews.len() < max_rounds && !stagnant {
7161        return None;
7162    }
7163    if last.incomplete() && last.blocking == 0 {
7164        return Some(RunStatus::Blocked);
7165    }
7166    if last.e2e_status() == E2eStatus::ResourceBlocked {
7167        return None;
7168    }
7169    Some(if last.e2e.iter().all(CommandOutcome::ok) {
7170        RunStatus::Gating
7171    } else {
7172        RunStatus::Blocked
7173    })
7174}
7175
7176/// How long a re-ask may take, given the budget the first attempt had.
7177///
7178/// A `nudged` retry is a request to restate an answer the seat has already
7179/// worked out: it carries no new work, so it does not deserve the original
7180/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
7181/// 133 seconds while a third sat for over ten minutes on a resumed session
7182/// holding 410 KB of prior output - and because the retry had inherited the
7183/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
7184/// judging round whose other seats were long finished.
7185///
7186/// A quarter of the budget, with a floor so that a deliberately short timeout
7187/// does not collapse to nothing. A retry that re-sends the whole prompt
7188/// (because the seat kept no context) is the original job again, and keeps the
7189/// original budget.
7190pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
7191    if nudged {
7192        (full / 4).max(Duration::from_secs(120)).min(full)
7193    } else {
7194        full
7195    }
7196}
7197
7198/// Run a wave and parse each reply, re-asking the seats whose reply was
7199/// unusable.
7200///
7201/// The re-ask is a nudge rather than the whole prompt again when the seat still
7202/// holds its conversation, which is the difference between a cheap retry and
7203/// paying for the entire candidate set twice.
7204///
7205/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
7206/// successor in `roster` is handed to it instead of being re-asked: the
7207/// handover is the retry. A seat with no successor left (a single-agent
7208/// roster, the roster's tail) is nudged as before, up to `retries` times. So
7209/// the asks to one seat in one node number at most
7210/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
7211/// is asked once (a dropped stream is nudged first), and only the last agent
7212/// of the chain gets the `retries` same-agent nudges. Each roster agent is
7213/// tried at most once per seat, walking forward from the seat's own position and never wrapping
7214/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
7215/// other failure stops the chain when the previous agent failed the same way
7216/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
7217/// [`has_context`] is false and the job's own full prompt and full budget are
7218/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
7219/// intermediate ones are not losses) and is returned as a failure like any
7220/// other absent seat — the caller decides whether the panel still has a
7221/// quorum. An empty `roster` disables handover: failures are nudged as they
7222/// always were, and a quota is simply lost. A reply that fails to parse or
7223/// validate is the prompt's doing and is only ever nudged, never handed over.
7224///
7225/// The returned [`SeatState`] names the agent that answered (or tried last).
7226#[allow(clippy::too_many_arguments)]
7227async fn ask_json_wave<T>(
7228    jobs: Vec<SeatJob>,
7229    sem: Arc<Semaphore>,
7230    retries: usize,
7231    roster: &[AgentSpec],
7232    ctx: &WaveCtx<'_>,
7233    losses: &mut Vec<QuotaLoss>,
7234    state: &mut RunState,
7235    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
7236) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
7237where
7238    T: serde::de::DeserializeOwned + Send + 'static,
7239{
7240    ask_wave_with(
7241        jobs,
7242        sem,
7243        retries,
7244        roster,
7245        ctx,
7246        losses,
7247        state,
7248        &|text: &str| {
7249            let v = verdict::extract_json::<T>(text)?;
7250            validate(&v)?;
7251            Ok(v)
7252        },
7253    )
7254    .await
7255}
7256
7257/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
7258/// a node whose answer is prose (deliberation) shares the same handover,
7259/// failure classification, quota bookkeeping and bounds instead of a copy.
7260///
7261/// A seat handed to another roster agent is sent the job's `handover` prompt
7262/// (when it has one) rather than `prompt`: the new agent has no session, so a
7263/// resume-style prompt would be incomplete. That holds for the handover ask
7264/// and for every nudge to that agent whose `has_context` is false.
7265#[allow(clippy::too_many_arguments)]
7266async fn ask_wave_with<T>(
7267    jobs: Vec<SeatJob>,
7268    sem: Arc<Semaphore>,
7269    retries: usize,
7270    roster: &[AgentSpec],
7271    ctx: &WaveCtx<'_>,
7272    losses: &mut Vec<QuotaLoss>,
7273    state: &mut RunState,
7274    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
7275) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
7276where
7277    T: Send + 'static,
7278{
7279    let n = jobs.len();
7280    let originals: Vec<SeatJob> = jobs;
7281    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
7282    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
7283    // Nudges each seat's *current* agent has taken — 0 for a first-ask
7284    // answer, N once it has gone through N nudges. Read back once this
7285    // returns, so a caller building a history record (`ReviewRecord`) can
7286    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
7287    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
7288    // field's own doc.
7289    let mut nudges: Vec<usize> = vec![0; n];
7290    // The agent now occupying each seat, the ids it has already been through,
7291    // where in the roster the walk began, the class of the last failure, and
7292    // the stem word of a handover not yet asked (full prompt, full budget).
7293    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
7294    let mut tried: Vec<BTreeSet<String>> = specs
7295        .iter()
7296        .map(|s| BTreeSet::from([s.id.clone()]))
7297        .collect();
7298    let starts: Vec<usize> = specs
7299        .iter()
7300        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
7301        .collect();
7302    let carry = ctx.carry_seats && !roster.is_empty();
7303    // Carried across rounds: ids that failed the seat earlier, and how the
7304    // last failure went (so a repeat of it is not handed over again).
7305    let carried: Vec<BTreeSet<String>> = originals
7306        .iter()
7307        .map(|j| {
7308            state
7309                .seat_history
7310                .get(&j.seat.key)
7311                .filter(|_| carry)
7312                .map(|h| h.failed.clone())
7313                .unwrap_or_default()
7314        })
7315        .collect();
7316    let mut prev: Vec<Option<FailClass>> = originals
7317        .iter()
7318        .map(|j| {
7319            state
7320                .seat_history
7321                .get(&j.seat.key)
7322                .filter(|_| carry)
7323                .and_then(|h| h.last_fail.clone())
7324        })
7325        .collect();
7326    let next_agent =
7327        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
7328            let others: BTreeSet<String> = specs
7329                .iter()
7330                .enumerate()
7331                .filter(|(j, _)| *j != i)
7332                .map(|(_, s)| s.id.clone())
7333                .collect();
7334            pick_successor(
7335                roster,
7336                starts[i],
7337                tried,
7338                carry.then(|| &carried[i]),
7339                &others,
7340            )
7341            .cloned()
7342        };
7343    let mut fresh: Vec<Option<String>> = vec![None; n];
7344    let mut last_quota: Vec<Option<Option<String>>> = vec![None; n];
7345    let mut pending: Vec<usize> = (0..n).collect();
7346
7347    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
7348    // asks: an agent with a successor is asked once and handed over, and only
7349    // a seat with no successor spends `retries` nudges on the same agent. This
7350    // only guarantees the loop's own termination whatever those say.
7351    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
7352    for round in 0..max_rounds {
7353        if pending.is_empty() {
7354            break;
7355        }
7356        let mut batch = Vec::with_capacity(pending.len());
7357        let mut renudged: Vec<&str> = Vec::new();
7358        for &i in &pending {
7359            let src = &originals[i];
7360            // A seat now held by another agent than the job named has no
7361            // session of its own: it gets the full-context prompt whenever
7362            // it is asked in full (the handover ask, a nudge it cannot
7363            // resume).
7364            let full: &str = match &src.handover {
7365                Some(h) if specs[i].id != src.spec.id => h,
7366                _ => &src.prompt,
7367            };
7368            // The prompt and the budget are one decision: a nudge restates
7369            // finished work, a re-sent prompt redoes it.
7370            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
7371                (
7372                    full.to_owned(),
7373                    src.timeout,
7374                    format!("{}-{word}-{}", src.stem, specs[i].id),
7375                )
7376            } else if nudges[i] == 0 {
7377                (full.to_owned(), src.timeout, src.stem.clone())
7378            } else {
7379                renudged.push(src.seat.key.as_str());
7380                let why = done[i]
7381                    .as_ref()
7382                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
7383                    .unwrap_or_else(|| "no parsable answer".to_owned());
7384                let nudge = prompt::nudge(&why);
7385                let nudged = has_context(&specs[i], &seats[i], src.sessions);
7386                let prompt = if nudged {
7387                    nudge
7388                } else {
7389                    format!("{full}\n\n---\n\n{nudge}")
7390                };
7391                (
7392                    prompt,
7393                    retry_budget(src.timeout, nudged),
7394                    format!("{}-retry{}", src.stem, nudges[i]),
7395                )
7396            };
7397            batch.push(SeatJob {
7398                spec: specs[i].clone(),
7399                seat: seats[i].clone(),
7400                cwd: src.cwd.clone(),
7401                prompt,
7402                timeout,
7403                allow_write: src.allow_write,
7404                sessions: src.sessions,
7405                artifacts: src.artifacts.clone(),
7406                stem,
7407                handover: None,
7408            });
7409        }
7410
7411        if !renudged.is_empty() {
7412            state.event(
7413                ctx.node,
7414                format!("retry {round}: re-asking {}", renudged.join(", ")),
7415            );
7416        }
7417        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
7418        let mut still = Vec::new();
7419        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
7420            seats[i] = seat;
7421            let class = FailClass::of(&out);
7422            // A dropped stream is nudged first (the conversation is still
7423            // there to pick up); only a seat whose nudges are spent hands over.
7424            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
7425                && nudges[i] < retries
7426                && !roster.is_empty();
7427            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
7428                let next = should_hand_over(prev[i].as_ref(), &cur)
7429                    .then(|| next_agent(i, &tried[i], &specs))
7430                    .flatten();
7431                if carry {
7432                    let h = state
7433                        .seat_history
7434                        .entry(originals[i].seat.key.clone())
7435                        .or_default();
7436                    h.failed.insert(specs[i].id.clone());
7437                    h.last_fail = Some(cur.clone());
7438                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
7439                        h.last_ok = None;
7440                    }
7441                    // Saved before the next agent is asked, so a restart in
7442                    // between does not forget who failed.
7443                    if let Err(e) = state.save() {
7444                        tracing::warn!("could not persist a seat's failure history: {e:#}");
7445                    }
7446                }
7447                if let Some(next) = next {
7448                    record_handover(
7449                        state,
7450                        ctx.node,
7451                        &originals[i].seat.key,
7452                        &specs[i].id,
7453                        &next.id,
7454                        &cur,
7455                        &fail_reason(&out),
7456                    );
7457                    tried[i].insert(next.id.clone());
7458                    prev[i] = Some(cur.clone());
7459                    seats[i] =
7460                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
7461                    specs[i] = next;
7462                    fresh[i] = Some(cur.stem_word().to_owned());
7463                    nudges[i] = 0;
7464                    done[i] = Some(Err(anyhow::anyhow!(
7465                        "handed over after: {}",
7466                        fail_reason(&out)
7467                    )));
7468                    still.push(i);
7469                    continue;
7470                }
7471            }
7472            if carry
7473                && !nudge_first
7474                && let Some(cur) = class.clone()
7475            {
7476                // The chain ended here (no successor, or a repeated failure).
7477                let h = state
7478                    .seat_history
7479                    .entry(originals[i].seat.key.clone())
7480                    .or_default();
7481                h.failed.insert(specs[i].id.clone());
7482                h.last_fail = Some(cur);
7483            }
7484            let parsed = match out {
7485                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
7486                AgentOutcome::Quota(o) => {
7487                    last_quota[i] = Some(o.quota.as_ref().and_then(|q| q.reset.clone()));
7488                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
7489                }
7490                // Not a parseable answer: the nudge loop re-asks it, which is
7491                // exactly what a dropped stream needs. Just don't hand its raw
7492                // error JSON to `extract_json`.
7493                AgentOutcome::Dropped(o) => {
7494                    let why = o
7495                        .dropped
7496                        .as_ref()
7497                        .map(|d| d.why.as_str())
7498                        .unwrap_or("the CLI ended the stream without delivering its answer");
7499                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
7500                }
7501                AgentOutcome::Failed(e) => Err(anyhow::anyhow!(e)),
7502            };
7503            let quota = class == Some(FailClass::Quota);
7504            let failed = parsed.is_err();
7505            done[i] = Some(parsed);
7506            if carry && !failed {
7507                let h = state
7508                    .seat_history
7509                    .entry(originals[i].seat.key.clone())
7510                    .or_default();
7511                h.failed.remove(&specs[i].id);
7512                h.last_ok = Some(specs[i].id.clone());
7513                h.last_fail = None;
7514            }
7515            // Do not re-ask a rate-limited seat (quota) — a retry is known to
7516            // fail the same way; and never re-ask a seat that already parsed.
7517            // A failed agent that still has a successor is not re-asked
7518            // either: the handover was its remedy and has just been refused
7519            // (the chain stops on a repeated failure class). A seat with no
7520            // successor left (a single-agent roster, the roster's tail, or an
7521            // empty roster) keeps the same-agent nudge, bounded by `retries`.
7522            let agent_failure = class.is_some()
7523                && !nudge_first
7524                && !roster.is_empty()
7525                && next_agent(i, &tried[i], &specs).is_some();
7526            if failed && !quota && !agent_failure && nudges[i] < retries {
7527                nudges[i] += 1;
7528                still.push(i);
7529            }
7530        }
7531        pending = still;
7532    }
7533
7534    // One loss per seat whose chain ended on a quota: the intermediate ones
7535    // were absorbed by a handover and are not losses.
7536    for (i, q) in last_quota.into_iter().enumerate() {
7537        if let Some(reset) = q {
7538            losses.push(QuotaLoss {
7539                seat: originals[i].seat.key.clone(),
7540                node: ctx.node.to_owned(),
7541                at: Timestamp::now(),
7542                reset,
7543            });
7544        }
7545    }
7546
7547    seats
7548        .into_iter()
7549        .zip(done)
7550        .zip(nudges)
7551        .map(|((seat, res), attempts)| {
7552            (
7553                seat,
7554                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
7555                attempts,
7556            )
7557        })
7558        .collect()
7559}
7560
7561/// Acquire the shared build cache's lease, waiting out contention within
7562/// `budget` (never past it — see AGENTS.md's build-cache section on why an
7563/// unbounded wait is never acceptable).
7564///
7565/// A first, non-blocking check happens before ever waiting; if it finds the
7566/// lease busy, that fact is logged as a `verify` event *and* flushed with
7567/// [`RunState::save`] immediately — not only once the wait finally succeeds
7568/// or gives up — so a `magi show` run by a different process while this one
7569/// is still waiting reads a `run.json` that says so, rather than whatever it
7570/// looked like before the wait started. The same applies to the terminal
7571/// failure: logged and saved before this returns `Err`, so a caller that
7572/// could not get the lease at all still leaves a legible record of why.
7573async fn acquire_cache_lease(
7574    state: &mut RunState,
7575    cache_dir: &Path,
7576    owner: &crate::cache::Owner,
7577    budget: Duration,
7578    context: &str,
7579) -> Result<crate::cache::Guard> {
7580    let home = crate::run::home();
7581    let started = Instant::now();
7582    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
7583        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(g),
7584        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
7585        Err(e) => {
7586            state.event(
7587                "verify",
7588                format!("{context}: could not check the shared build cache: {e:#}"),
7589            );
7590            if let Err(e2) = state.save() {
7591                tracing::warn!("could not persist a cache-check failure: {e2:#}");
7592            }
7593            return Err(e);
7594        }
7595    };
7596    state.event(
7597        "verify",
7598        format!(
7599            "{context}: waiting for the shared build cache at {} ({})",
7600            cache_dir.display(),
7601            busy.describe()
7602        ),
7603    );
7604    if let Err(e) = state.save() {
7605        tracing::warn!("could not persist a cache wait: {e:#}");
7606    }
7607    let remaining = budget.saturating_sub(started.elapsed());
7608    match crate::cache::wait_for(&home, cache_dir, owner, remaining, Duration::from_secs(5)).await {
7609        Ok(g) => Ok(g),
7610        Err(e) => {
7611            state.event("verify", format!("{context}: {e:#}"));
7612            if let Err(e2) = state.save() {
7613                tracing::warn!("could not persist a cache wait timeout: {e2:#}");
7614            }
7615            Err(e)
7616        }
7617    }
7618}
7619
7620/// Run `body` — a verify command batch — while holding the shared build
7621/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
7622/// never interleave with another borrower's build against the same
7623/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
7624/// timeout, or a human's own `magi review`. See the `cache` module doc for
7625/// why this matters more than Cargo's own per-target locking covers — two
7626/// *different* worktrees building the same package name/version into one
7627/// cache directory is a staleness bug, not a lock contention one.
7628///
7629/// The wait for the lease is carved out of `budget`, never on top of it —
7630/// `body` is handed whatever is left, so a caller's own node timeout is the
7631/// only clock involved, exactly what AGENTS.md's build-cache section asks
7632/// for ("never an unbounded wait"). When `cache_dir` is `None` — no shared
7633/// cache configured at all — this is a pass-through: `body` runs with the
7634/// full budget and nothing is leased.
7635///
7636/// A lease that cannot be acquired within `budget` is reported as a single
7637/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
7638/// verification — the same shape a spawn failure already takes in
7639/// [`run_commands`], so a caller need not special-case it.
7640#[allow(clippy::too_many_arguments)]
7641async fn with_cache_lease<'s, F, Fut>(
7642    state: &'s mut RunState,
7643    cache_dir: Option<&Path>,
7644    node: &str,
7645    seat: &str,
7646    worktree: &Path,
7647    head: &str,
7648    budget: Duration,
7649    context: &str,
7650    body: F,
7651) -> (Vec<CommandOutcome>, bool)
7652where
7653    F: FnOnce(&'s mut RunState, Duration) -> Fut,
7654    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
7655{
7656    let Some(cache_dir) = cache_dir else {
7657        let (outcomes, retried, _timed_out_pids) = body(state, budget).await;
7658        return (outcomes, retried);
7659    };
7660    let home = crate::run::home();
7661    let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
7662    let started = Instant::now();
7663    let guard = match acquire_cache_lease(state, cache_dir, &owner, budget, context).await {
7664        Ok(g) => g,
7665        Err(e) => {
7666            return (
7667                vec![CommandOutcome {
7668                    command: "(waiting for the shared build cache)".to_owned(),
7669                    code: None,
7670                    output_tail: e.to_string(),
7671                    duration_ms: started.elapsed().as_millis() as u64,
7672                    resource_blocked: true,
7673                }],
7674                false,
7675            );
7676        }
7677    };
7678    let identity = crate::cache::Identity::new(worktree, head);
7679    if let Err(e) = crate::cache::ensure_fresh(&home, cache_dir, &identity) {
7680        // A failed freshness check means this process cannot vouch for what
7681        // is sitting in the cache right now - on Windows this is exactly the
7682        // "a stale test executable is still locked, `cargo clean -p` cannot
7683        // remove it" case the evidence log records. Running verify anyway
7684        // and reporting whatever it says would let a result nobody can trust
7685        // stand for the tree it claims to have checked; fail the step
7686        // instead of the patch.
7687        state.event(
7688            "verify",
7689            format!(
7690                "{context}: could not confirm the shared build cache matches {} at {}: {e:#}",
7691                worktree.display(),
7692                short(head)
7693            ),
7694        );
7695        guard.release();
7696        return (
7697            vec![CommandOutcome {
7698                command: "(confirming the shared build cache is fresh)".to_owned(),
7699                code: None,
7700                output_tail: e.to_string(),
7701                duration_ms: started.elapsed().as_millis() as u64,
7702                resource_blocked: true,
7703            }],
7704            false,
7705        );
7706    }
7707    let remaining = budget.saturating_sub(started.elapsed());
7708    let (outcomes, retried, timed_out_pids) = body(state, remaining).await;
7709    // A timed-out command's process was only *asked* to die (`kill_on_drop`,
7710    // `start_kill`); confirm it actually has before handing the directory to
7711    // the next acquirer. See `wait_for_timed_out_children_to_die`'s own doc
7712    // for what this can and cannot see.
7713    if !timed_out_pids.is_empty() {
7714        wait_for_timed_out_children_to_die(&timed_out_pids).await;
7715    }
7716    guard.release();
7717    (outcomes, retried)
7718}
7719
7720/// Poll `pids` — commands [`run_commands`] reports as still running when its
7721/// own timeout elapsed — until every one is confirmed gone, or
7722/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
7723///
7724/// Real confirmation where confirmation is possible, not a substitute for
7725/// full process-tree observation: a grandchild the timed-out process spawned
7726/// and that survives independently of it is invisible to a pid check the
7727/// same way it always was, and continuing to observe and collect *that*
7728/// stays a different piece of work with its own owner. This only narrows a
7729/// fixed blind wait into an actual check of the pids this process does know
7730/// about.
7731async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
7732    wait_for_pids_with(
7733        pids,
7734        crate::proc::pid_alive,
7735        LEASE_RELEASE_POLL,
7736        LEASE_RELEASE_MAX_WAIT,
7737    )
7738    .await;
7739}
7740
7741/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
7742/// interval and ceiling supplied by the caller, so the polling *logic* -
7743/// returns as soon as every pid reports dead, gives up at the ceiling
7744/// otherwise - is testable on millisecond durations without asking the real
7745/// OS about a pid at all.
7746async fn wait_for_pids_with<F: Fn(u32) -> bool>(
7747    pids: &[u32],
7748    alive: F,
7749    poll: Duration,
7750    max_wait: Duration,
7751) {
7752    let deadline = Instant::now() + max_wait;
7753    loop {
7754        if pids.iter().all(|&pid| !alive(pid)) {
7755            return;
7756        }
7757        if Instant::now() >= deadline {
7758            return;
7759        }
7760        tokio::time::sleep(poll).await;
7761    }
7762}
7763
7764/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
7765/// admission that it could not even get a verify command to run, as opposed
7766/// to evidence the command actually produced? A caller that would otherwise
7767/// read a resource-blocked outcome as a red command must check this first:
7768/// see [`Runner::gate`], which retries rather than records `Blocked` when
7769/// this is true.
7770fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
7771    outcomes.iter().any(|o| o.resource_blocked)
7772}
7773
7774/// What [`Runner::gate_fix_round`] decided.
7775enum GateFix {
7776    /// The tree changed and `verify.e2e` is still green: run the gate again.
7777    Retry,
7778    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
7779    /// last failure stands and the run ends blocked.
7780    Stop,
7781    /// `verify.e2e` could not run after the fix (magi's own contention):
7782    /// decide nothing now, a later reentry retries.
7783    Defer,
7784}
7785
7786/// Is every red command in `outcomes` an ordinary failure the code could
7787/// explain: it ran, exited non-zero, and said something?
7788///
7789/// A timeout, a spawn failure and a killed process all leave `code` `None`;
7790/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
7791/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
7792/// what the command is stays the gate's business.
7793fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
7794    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
7795    red.peek().is_some()
7796        && red.all(|o| {
7797            !o.resource_blocked
7798                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
7799                && !o.output_tail.trim().is_empty()
7800        })
7801}
7802
7803/// Describe one verify command's outcome for the event log, distinguishing a
7804/// build/link failure — the toolchain never produced a binary to run — from
7805/// an actual test failure, since only the latter is a verdict on the patch.
7806fn e2e_outcome_label(o: &CommandOutcome) -> String {
7807    if o.ok() {
7808        return "pass".to_owned();
7809    }
7810    let reason = if o.build_failed() {
7811        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
7812    } else {
7813        format!("FAIL ({:?})", o.code)
7814    };
7815    format!("{reason}\n{}", tail(&o.output_tail, EVENT_OUTPUT_TAIL))
7816}
7817
7818/// Run `verify.e2e`, retrying once if the first attempt could not build or
7819/// link — a build/link failure is frequently a race against a shared
7820/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
7821/// `verify` event per command, tagged with `context` (normally `"round N"`)
7822/// so the two call sites that need this — the ordinary per-round leg in
7823/// `review_loop`, and the deferred catch-up run `stop_reviewing` makes before
7824/// it will ever call a round green — read identically in the event log.
7825async fn run_e2e_with_retry(
7826    state: &mut RunState,
7827    shell: &[String],
7828    commands: &[String],
7829    worktree: &Path,
7830    timeout: Duration,
7831    context: &str,
7832) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
7833    let (mut e2e, mut timed_out_pids) = run_commands(
7834        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
7835    )
7836    .await;
7837    for o in &e2e {
7838        state.event(
7839            "verify",
7840            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
7841        );
7842    }
7843    // A build/link failure is not a verdict on the patch — it is frequently a
7844    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
7845    // one retry before letting a red like that decide the round.
7846    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
7847    if verify_retried {
7848        state.event(
7849            "verify",
7850            format!(
7851                "{context}: verify could not build/link, not a test result — retrying once \
7852                 before concluding"
7853            ),
7854        );
7855        let retried = run_commands(
7856            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
7857        )
7858        .await;
7859        e2e = retried.0;
7860        // Both attempts' timeouts matter, not just the last one: the first
7861        // attempt's descendants may still be alive alongside the retry's.
7862        timed_out_pids.extend(retried.1);
7863        for o in &e2e {
7864            state.event(
7865                "verify",
7866                format!(
7867                    "{context}: retry `{}` -> {}",
7868                    o.command,
7869                    e2e_outcome_label(o)
7870                ),
7871            );
7872        }
7873    }
7874    (e2e, verify_retried, timed_out_pids)
7875}
7876
7877/// Run configured shell commands in `cwd`, in order. The second element is
7878/// the pid of every command that hit `timeout` and was still running when
7879/// this stopped waiting on it (best-effort: `None` when the platform did not
7880/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
7881/// that releases a shared resource afterward needs to know.
7882///
7883/// Records `task` into [`RunState::active`] at every command boundary
7884/// (`RunState::task_command`) and clears it once the whole list has run
7885/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
7886/// for minutes with no seat and no output of its own to show for it (see
7887/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
7888/// apart from "not yet run" without this), and this is the only place that
7889/// knows which command is running right now and how many are left. Three
7890/// saves per command — start, not per second — matching the same "only at a
7891/// boundary" rule [`wave`] already follows for seats.
7892#[allow(clippy::too_many_arguments)]
7893async fn run_commands(
7894    state: &mut RunState,
7895    node: &str,
7896    task: &str,
7897    attempt: usize,
7898    shell: &[String],
7899    commands: &[String],
7900    cwd: &Path,
7901    timeout: Duration,
7902) -> (Vec<CommandOutcome>, Vec<u32>) {
7903    if commands.is_empty() {
7904        // Nothing to mark as running and nothing to clear — an empty list
7905        // means "not configured", and touching `active` (or the disk) over
7906        // that would be a write for every round of a repo with no
7907        // `verify.e2e` / `verify.gate` commands at all.
7908        return (Vec::new(), Vec::new());
7909    }
7910    let mut out = Vec::new();
7911    let mut timed_out_pids = Vec::new();
7912    let total = commands.len();
7913    for (idx, command) in commands.iter().enumerate() {
7914        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
7915        if let Err(e) = state.save() {
7916            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
7917        }
7918        let started = Instant::now();
7919        let mut cmd = tokio::process::Command::new(&shell[0]);
7920        cmd.quiet();
7921        cmd.args(&shell[1..])
7922            .arg(command)
7923            .current_dir(cwd)
7924            .stdin(std::process::Stdio::null())
7925            .stdout(std::process::Stdio::piped())
7926            .stderr(std::process::Stdio::piped())
7927            .kill_on_drop(true);
7928        let spawned = cmd.spawn();
7929        let (code, body) = match spawned {
7930            Ok(child) => {
7931                // Captured before the child is consumed below: `kill_on_drop`
7932                // only *asks* the process to die when the timeout branch
7933                // drops it, and the pid is the only way anyone downstream can
7934                // later check whether that request actually took.
7935                let pid = child.id();
7936                match tokio::time::timeout(timeout, child.wait_with_output()).await {
7937                    Ok(Ok(o)) => {
7938                        let mut body = String::from_utf8_lossy(&o.stdout).into_owned();
7939                        body.push_str(&String::from_utf8_lossy(&o.stderr));
7940                        (o.status.code(), body)
7941                    }
7942                    Ok(Err(e)) => (None, format!("failed to run: {e}")),
7943                    Err(_) => {
7944                        if let Some(pid) = pid {
7945                            timed_out_pids.push(pid);
7946                        }
7947                        (None, format!("timed out after {}s", timeout.as_secs()))
7948                    }
7949                }
7950            }
7951            Err(e) => (None, format!("failed to spawn `{}`: {e}", shell[0])),
7952        };
7953        out.push(CommandOutcome {
7954            command: command.clone(),
7955            code,
7956            output_tail: tail(&body, OUTPUT_TAIL),
7957            duration_ms: started.elapsed().as_millis() as u64,
7958            resource_blocked: false,
7959        });
7960    }
7961    state.task_finished(task);
7962    if let Err(e) = state.save() {
7963        tracing::warn!("could not persist the end of {task}: {e:#}");
7964    }
7965    (out, timed_out_pids)
7966}
7967
7968/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
7969/// section (`report::run`) and in the `merge` event this node records — for
7970/// the operator to run by hand.
7971///
7972/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
7973/// branch whose ruleset forbids merge commits (GitHub's "must not contain
7974/// merge commits", or "require linear history") rejects the push a `--no-ff`
7975/// merge would produce, which is exactly the guidance this function replaces.
7976/// `message`'s first line becomes the squash commit's subject, matching the
7977/// note `report::run` prints alongside this command — see that function for
7978/// why an explicit subject is not optional there.
7979fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
7980    let repo = repo.display();
7981    match style {
7982        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
7983        MergeStyle::Squash => {
7984            // The subject sits inside double quotes, and a title an agent
7985            // wrote may carry the characters that break out of them.
7986            let subject = message
7987                .lines()
7988                .next()
7989                .unwrap_or(branch)
7990                .replace(['\\', '"', '$', '`'], "");
7991            format!(
7992                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
7993            )
7994        }
7995        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
7996    }
7997}
7998
7999/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
8000/// under the hood, rejects a `title` over 256 characters and the whole
8001/// command fails — no PR at all, for a run whose body was otherwise fine
8002/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
8003/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
8004/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
8005/// this bound. It is a margin, not a guarantee — a title packed
8006/// with multi-unit characters could still in principle land close to the
8007/// edge, but a real task title's occasional emoji or accented letter fits
8008/// comfortably inside it.
8009const PR_TITLE_MAX: usize = 240;
8010
8011/// A pull request title from the opening line of `text`, or `None` when that
8012/// line is not English (GitHub text is) or has no letters.
8013///
8014/// A line within `max` is kept as is. A longer one is cut at the end of its
8015/// first sentence when that falls inside `max`, else at a word boundary with a
8016/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
8017/// make every merely-truncated title look non-English). The language check
8018/// runs on the kept text before any mark is added, so only what GitHub will
8019/// show is judged: an English opening followed by non-ASCII far past the cut
8020/// still passes.
8021fn english_title(text: &str, max: usize) -> Option<String> {
8022    let line = queue::first_line(text)?;
8023    let chars: Vec<char> = line.chars().collect();
8024    let (kept, mark) = if chars.len() <= max {
8025        (line.to_owned(), "")
8026    } else if let Some(end) = sentence_end(&chars, max) {
8027        (chars[..end].iter().collect::<String>(), "")
8028    } else {
8029        let room = max.saturating_sub(3);
8030        // Cut at the last space inside the room; when the char just past the
8031        // room is a space the room already ends on a word.
8032        let cut = if chars[room].is_whitespace() {
8033            room
8034        } else {
8035            chars[..room]
8036                .iter()
8037                .rposition(|c| c.is_whitespace())
8038                .unwrap_or(room)
8039        };
8040        let head: String = chars[..cut].iter().collect();
8041        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
8042        (head.to_owned(), "...")
8043    };
8044    if kept.is_empty() || !kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic()) {
8045        return None;
8046    }
8047    Some(format!("{kept}{mark}"))
8048}
8049
8050/// The char length of the first sentence of `chars` when it ends within `max`
8051/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
8052/// abbreviations so `e.g. foo` does not end a title early.
8053fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
8054    const MIN: usize = 20;
8055    for i in MIN..max.min(chars.len()) {
8056        if !matches!(chars[i], '.' | '!' | '?') {
8057            continue;
8058        }
8059        let Some(&next) = chars.get(i + 1) else {
8060            continue;
8061        };
8062        if !next.is_whitespace() {
8063            continue;
8064        }
8065        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
8066        if after.is_some_and(|c| c.is_ascii_lowercase()) {
8067            continue;
8068        }
8069        let word: String = chars[..i]
8070            .iter()
8071            .rev()
8072            .take_while(|c| !c.is_whitespace())
8073            .collect::<Vec<_>>()
8074            .into_iter()
8075            .rev()
8076            .collect();
8077        let word = word.to_ascii_lowercase();
8078        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
8079            continue;
8080        }
8081        let end = chars[..i]
8082            .iter()
8083            .rposition(|c| !c.is_whitespace())
8084            .map_or(i, |p| p + 1);
8085        return Some(end);
8086    }
8087    None
8088}
8089
8090/// What `merge = "pr"` (and the merge commit of the other modes) says about a
8091/// change: a title and a body describing what was *implemented*, not the task
8092/// that asked for it. A task reads as a request; a reader of the merged
8093/// history wants the change.
8094struct PrMessage {
8095    title: String,
8096    body: String,
8097}
8098
8099impl PrMessage {
8100    /// Title, blank line, body. The first line is the squash/merge commit
8101    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
8102    /// has to stay one sensible line.
8103    fn commit_message(&self) -> String {
8104        format!("{}\n\n{}", self.title, self.body)
8105    }
8106}
8107
8108/// The text after a leading `TITLE:` (any case) on `line`.
8109fn title_marker(line: &str) -> Option<&str> {
8110    let line = line.trim();
8111    let head = line.get(..6)?;
8112    head.eq_ignore_ascii_case("title:")
8113        .then(|| line[6..].trim())
8114}
8115
8116/// The implementer's own one-line title: the `TITLE:` line the implement
8117/// prompt asks for at the top of its SUMMARY. Candidate commits are all
8118/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
8119/// source, and a title that says as much is refused here too.
8120fn summary_title(summary: &str) -> Option<String> {
8121    let first = summary.lines().find(|l| !l.trim().is_empty())?;
8122    let raw = title_marker(first)?;
8123    if raw.is_empty() {
8124        return None;
8125    }
8126    let title = queue::title_from(raw, PR_TITLE_MAX);
8127    let lower = title.to_ascii_lowercase();
8128    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
8129        return None;
8130    }
8131    Some(title)
8132}
8133
8134/// How `open_review`'s instruction begins; see [`landing_title`].
8135const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
8136
8137/// Marker `open_review` gives a candidate that nothing in the roster wrote.
8138const EXISTING_BRANCH: &str = "(existing branch)";
8139
8140/// Does this run review work that already existed, rather than implement a
8141/// task? Runs recorded before `reviewed_commits` existed carry only the
8142/// candidate marker.
8143fn is_review_run(state: &RunState) -> bool {
8144    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
8145}
8146
8147/// The title of a review-only run: the subject of the oldest commit under
8148/// review. Later commits are usually fixups, and `instruction` is the review
8149/// prompt, which says nothing about the change. GitHub text is English, so a
8150/// non-ASCII or blank subject yields `None` and the caller's neutral title.
8151fn review_title(state: &RunState) -> Option<String> {
8152    english_subject(state.reviewed_commits.as_ref()?.first()?)
8153}
8154
8155/// `raw` as a pull request title, or `None` when it is blank, not English
8156/// (GitHub text is), or one of magi's own candidate commit subjects.
8157fn english_subject(raw: &str) -> Option<String> {
8158    let raw = raw.trim();
8159    if raw.is_empty() || !raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic()) {
8160        return None;
8161    }
8162    let title = queue::title_from(raw, PR_TITLE_MAX);
8163    let lower = title.to_ascii_lowercase();
8164    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
8165        return None;
8166    }
8167    Some(title)
8168}
8169
8170/// What a review-only run's branch says about itself, read at the moment the
8171/// pull request is opened.
8172#[derive(Debug, Clone, PartialEq, Eq)]
8173struct BranchFacts {
8174    /// `(subject, body)` of each commit, oldest first.
8175    commits: Vec<(String, String)>,
8176    /// Trimmed `git diff --stat`.
8177    stat: String,
8178}
8179
8180/// Longest diff stat shown: this many file lines plus the summary line.
8181const STAT_FILE_LINES: usize = 25;
8182/// Cap on the commit list, well inside GitHub's 65536-character body limit.
8183const COMMITS_MAX_CHARS: usize = 20_000;
8184
8185/// Read the commits and diff stat of `base..branch`. `None` when git cannot
8186/// say or finds nothing, so the caller falls back to what the run recorded.
8187async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
8188    let commits = git::commit_log(repo, base, branch).await.ok()?;
8189    if commits.is_empty() {
8190        return None;
8191    }
8192    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
8193    let lines: Vec<&str> = stat.lines().collect();
8194    let stat = if lines.len() > STAT_FILE_LINES + 1 {
8195        let omitted = lines.len() - 1 - STAT_FILE_LINES;
8196        let more = format!(" ... {omitted} more file(s)");
8197        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
8198        kept.push(&more);
8199        kept.push(lines[lines.len() - 1]);
8200        kept.join("\n")
8201    } else {
8202        lines.join("\n")
8203    };
8204    Some(BranchFacts { commits, stat })
8205}
8206
8207/// Defang what would break the surrounding markdown: a closing `</details>`
8208/// and a code fence.
8209fn markdown_safe(text: &str) -> String {
8210    text.replace("</details>", "&lt;/details&gt;")
8211        .replace("\x60\x60\x60", "~~~")
8212}
8213
8214fn neutral_title(state: &RunState, winner: char) -> String {
8215    format!(
8216        "chore: land candidate {} of run {}",
8217        winner.to_ascii_uppercase(),
8218        state.id
8219    )
8220}
8221
8222/// The pull request title to hand to `land::merge_subject`. A review-only run
8223/// opened by an earlier build titled its pull request with the review prompt;
8224/// that title is dropped (empty, so the fallback applies) rather than landed.
8225/// Any other title, including an operator's rename, passes through untouched,
8226/// and so does every title of a run that implements a task.
8227pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
8228    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
8229        ""
8230    } else {
8231        pr_title
8232    }
8233}
8234
8235/// What the squash subject falls back to when the pull request title is empty
8236/// or candidate-shaped: for a review-only run the derived title, never the
8237/// review prompt held in `instruction`.
8238pub fn landing_subject_source(state: &RunState) -> String {
8239    if is_review_run(state) {
8240        let winner = state.candidates.first().map_or('A', |c| c.label);
8241        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
8242    }
8243    state.instruction.clone()
8244}
8245
8246/// `summary` without its `TITLE:` line, which the pull request title already
8247/// carries.
8248fn summary_without_title(summary: &str) -> String {
8249    let mut lines = summary.trim().lines().peekable();
8250    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
8251        lines.next();
8252    }
8253    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
8254}
8255
8256/// The pull request title and body for the winning candidate.
8257///
8258/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
8259/// the task's own opening line via [`queue::title_from`] when there is none.
8260/// `state.instruction` can open with blank lines (`task_text` only rejects a
8261/// body that is blank *entirely*), which `title_from` skips.
8262///
8263/// Body: the implementer's summary and the fixer's notes, then — when the
8264/// winning review round was not clean — the findings still open and whatever
8265/// the fixer declined, so `merge = "pr"` hands the reader the same material
8266/// `magi show` does. The task follows inside a collapsed block, and the
8267/// footer repeats the run and candidate as plain tags for a reader holding
8268/// only the merged commit or the PR body.
8269#[cfg(test)]
8270fn pr_message(state: &RunState, winner: char) -> PrMessage {
8271    pr_message_with(state, winner, None)
8272}
8273
8274/// [`pr_message`] with what the branch of a review-only run says about itself.
8275/// `facts` is ignored for a run that implements a task.
8276#[cfg(test)]
8277fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
8278    let raw = pr_message_raw(state, winner, facts);
8279    let id = crate::scrub::Identity::current();
8280    PrMessage {
8281        title: crate::scrub::scrub(&raw.title, &id),
8282        body: crate::scrub::scrub(&raw.body, &id),
8283    }
8284}
8285
8286fn pr_message_raw(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
8287    let summary = state
8288        .candidates
8289        .iter()
8290        .find(|c| c.label == winner)
8291        .map(|c| c.summary.as_str())
8292        .unwrap_or_default();
8293    // The fallback is the operator's own words and may not be English; GitHub
8294    // text always is, so a non-English task gets a neutral title instead.
8295    let review = is_review_run(state);
8296    let title = if review {
8297        facts
8298            .and_then(|f| english_subject(&f.commits.first()?.0))
8299            .or_else(|| review_title(state))
8300            .or_else(|| {
8301                state
8302                    .candidates
8303                    .iter()
8304                    .find(|c| c.label == winner)
8305                    .filter(|c| !c.branch.starts_with("magi/"))
8306                    .and_then(|c| english_subject(&c.branch))
8307            })
8308            .unwrap_or_else(|| neutral_title(state, winner))
8309    } else {
8310        summary_title(summary).unwrap_or_else(|| {
8311            english_title(&state.instruction, PR_TITLE_MAX)
8312                .unwrap_or_else(|| neutral_title(state, winner))
8313        })
8314    };
8315
8316    let mut body = String::new();
8317    let what = summary_without_title(summary);
8318    if !what.is_empty() {
8319        body.push_str("## Summary\n\n");
8320        body.push_str(&what);
8321        body.push_str("\n\n");
8322    }
8323
8324    // The last round is usually a clean verification pass with no fix of its
8325    // own, so every round's notes are read, not just the final one's.
8326    let notes: Vec<(usize, &str)> = state
8327        .reviews
8328        .iter()
8329        .filter_map(|r| {
8330            let n = r.fix.as_ref()?.notes.trim();
8331            (!n.is_empty()).then_some((r.round, n))
8332        })
8333        .collect();
8334    if !notes.is_empty() {
8335        body.push_str("## Review fixes\n\n");
8336        if let [(_, only)] = notes.as_slice() {
8337            body.push_str(only);
8338            body.push_str("\n\n");
8339        } else {
8340            for (round, n) in &notes {
8341                body.push_str(&format!("### Round {round}\n\n{n}\n\n"));
8342            }
8343        }
8344    }
8345    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
8346
8347    let open = state.open_findings();
8348    if !open.is_empty() {
8349        body.push_str("## Open review findings\n\n");
8350        for f in &open {
8351            body.push_str(&format!("- `{}` [{:?}] {}\n", f.id, f.severity, f.title));
8352        }
8353        body.push('\n');
8354    }
8355
8356    if let Some(fix) = fix
8357        && !fix.rejected.is_empty()
8358    {
8359        body.push_str("## Declined by the fixer\n\n");
8360        for r in &fix.rejected {
8361            body.push_str(&format!("- `{}`: {}\n", r.id, r.why));
8362        }
8363        body.push('\n');
8364    }
8365
8366    if review {
8367        // The review prompt is not the task; list what the branch carries.
8368        body.push_str("## Commits under review\n\n");
8369        if let Some(facts) = facts {
8370            let mut left = COMMITS_MAX_CHARS;
8371            for (i, (subject, text)) in facts.commits.iter().enumerate() {
8372                let mut entry = format!("- {}\n", markdown_safe(subject));
8373                for l in markdown_safe(text).lines() {
8374                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
8375                }
8376                if left == 0 {
8377                    body.push_str(&format!(
8378                        "- ... {} more commit(s)\n",
8379                        facts.commits.len() - i
8380                    ));
8381                    break;
8382                }
8383                if entry.len() > left {
8384                    // Even the first commit is cut: one huge body must not
8385                    // push the whole description past GitHub's limit.
8386                    let mut end = left;
8387                    while !entry.is_char_boundary(end) {
8388                        end -= 1;
8389                    }
8390                    entry.truncate(end);
8391                    entry.push_str("\n  ... (truncated)\n");
8392                    left = 0;
8393                } else {
8394                    left -= entry.len();
8395                }
8396                body.push_str(&entry);
8397            }
8398            if !facts.stat.trim().is_empty() {
8399                body.push_str(&format!(
8400                    "\n## Diff stat\n\n```\n{}\n```\n",
8401                    markdown_safe(facts.stat.trim())
8402                ));
8403            }
8404        } else {
8405            match &state.reviewed_commits {
8406                Some(subjects) => {
8407                    for s in subjects {
8408                        body.push_str(&format!("- {}\n", s.trim()));
8409                    }
8410                }
8411                None => {
8412                    // An older run kept only the prompt, with the commit list
8413                    // after its first paragraph.
8414                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
8415                    body.push_str(rest.trim());
8416                    body.push('\n');
8417                }
8418            }
8419        }
8420    } else {
8421        let task = state.instruction.trim();
8422        let task = if task.is_empty() {
8423            "(empty task)"
8424        } else {
8425            task
8426        };
8427        body.push_str(&format!(
8428            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
8429            task.replace("</details>", "&lt;/details&gt;")
8430        ));
8431    }
8432
8433    body.push_str(&format!(
8434        "\n---\nmagi:run/{} magi:candidate-{}\n",
8435        state.id,
8436        winner.to_ascii_lowercase()
8437    ));
8438
8439    PrMessage { title, body }
8440}
8441
8442/// The task with what the repository says about the existing work it names
8443/// appended, so an implementer knows what it started from and what it must
8444/// not redo. Unchanged when the task names nothing.
8445fn seeded_instruction(state: &RunState) -> String {
8446    match refs::describe(&state.seeds) {
8447        Some(facts) => format!(
8448            "{}\n\n# Existing work the task refers to\n\n{facts}\n\n\
8449             Candidates start from the unmerged branch named above, when there \
8450             is one, and carry any unmerged commit named by sha as a \
8451             cherry-pick. Check that this is what the task meant before \
8452             building on it.",
8453            state.instruction
8454        ),
8455        None => state.instruction.clone(),
8456    }
8457}
8458
8459/// Does the winner have no commits ahead of the base it would land on?
8460/// Any failure to find out reads as "not empty": the merge then behaves as it
8461/// always did rather than refusing on a guess.
8462async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
8463    let base = &state.base_branch;
8464    let mut against = base.clone();
8465    if mode == MergeMode::Pr {
8466        // A pull request lands on the remote's base, never the local branch
8467        // of the same name: if that cannot be read, "not empty" is the safe
8468        // answer.
8469        let remote = &state.config.merge.remote;
8470        let tracking = format!("{remote}/{base}");
8471        let fetched = git::fetch(repo, remote, base).await;
8472        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
8473            against = tracking;
8474        } else {
8475            return false;
8476        }
8477    }
8478    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
8479}
8480
8481/// Why nothing was opened for an empty winner, with what the task's own
8482/// references resolved to.
8483fn empty_candidate_detail(state: &RunState, base: &str) -> String {
8484    let mut detail = format!(
8485        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
8486         nothing to open a pull request for"
8487    );
8488    match refs::describe(&state.seeds) {
8489        Some(facts) => detail.push_str(&format!("\nReferences in the task:\n{facts}")),
8490        None => detail.push_str(
8491            "\nThe task names no existing branch or commit; if it means to land work \
8492             that lives elsewhere, name the branch (magi/<run>/<label>) or the sha.",
8493        ),
8494    }
8495    detail
8496}
8497
8498/// What the `Pr` merge does once it knows whether the branch already has an
8499/// open pull request.
8500#[derive(Debug, PartialEq, Eq)]
8501enum PrPlan {
8502    Create,
8503    Adopt { url: String, title: String },
8504    Stop(String),
8505}
8506
8507/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
8508/// a failed lookup -> stop with the real reason. Never guesses.
8509fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
8510    match found {
8511        Ok(land::OpenPr::None) => PrPlan::Create,
8512        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
8513        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
8514            "several open pull requests exist for this branch, not picking one: {}",
8515            urls.join(" ")
8516        )),
8517        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
8518    }
8519}
8520
8521/// `gh pr create`, returning the PR url.
8522async fn gh_pr_create(
8523    cwd: &Path,
8524    base: &str,
8525    head: &str,
8526    title: &str,
8527    body: &str,
8528) -> Result<String> {
8529    let out = tokio::process::Command::new("gh")
8530        .args([
8531            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
8532        ])
8533        .current_dir(cwd)
8534        .quiet()
8535        .stdin(std::process::Stdio::null())
8536        .output()
8537        .await
8538        .context("spawn gh")?;
8539    if out.status.success() {
8540        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
8541    } else {
8542        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
8543    }
8544}
8545
8546/// Tear a run's worktrees and branches down.
8547///
8548/// `home` is where the updated `run.json` is saved (via
8549/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
8550/// a housekeeping pass already has its own honest `home` handed to it, and
8551/// falling through to the global here would write back through whichever
8552/// directory some other process or test pinned into that `OnceLock` first,
8553/// not the one the caller actually resolved its `runs` and `state` from.
8554pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
8555    let repo = state.repo.clone();
8556    let root = state.worktree_root();
8557    let winner = state.tally.as_ref().map(|t| t.winner);
8558    let mut removed = Vec::new();
8559
8560    for i in 0..state.candidates.len() {
8561        let c = state.candidates[i].clone();
8562        let is_winner = Some(c.label) == winner;
8563        if is_winner && !drop_winner {
8564            continue;
8565        }
8566        if c.worktree.exists() {
8567            git::worktree_remove(&repo, &c.worktree).await.ok();
8568            removed.push(c.worktree.to_string_lossy().into_owned());
8569        }
8570        // A branch handed to a later run (and its pull request) is not this
8571        // run's to delete.
8572        let handed_over = state.released_branches.contains(&c.branch);
8573        if !handed_over && git::branch_exists(&repo, &c.branch).await.unwrap_or(false) {
8574            git::branch_delete(&repo, &c.branch).await.ok();
8575            removed.push(c.branch.clone());
8576        }
8577        state.candidates[i].folded = true;
8578    }
8579
8580    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
8581        let path = name.path();
8582        let keep = !drop_winner
8583            && winner.is_some_and(|w| {
8584                path.file_name()
8585                    .is_some_and(|n| n == format!("cand-{w}").as_str())
8586            });
8587        if keep {
8588            continue;
8589        }
8590        git::worktree_remove(&repo, &path).await.ok();
8591        removed.push(path.to_string_lossy().into_owned());
8592    }
8593
8594    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
8595    // judge worktrees, so once the loop above has cleared all of them out,
8596    // the parent is a bare directory nobody else was ever going to remove -
8597    // git only ever managed what was inside it. Left alone, one of these
8598    // accumulates per fully-folded run; the operator's own machine had 74.
8599    // `remove_if_empty` re-checks rather than assuming: a run whose winner
8600    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
8601    // so does anything a run never claimed that happens to share the bay.
8602    remove_if_empty(&root);
8603
8604    if state.enabled_worktree_config && drop_winner {
8605        // A release, not a raw disable: some sibling run in this repository
8606        // may still hold its own reference (see `git::acquire_worktree_config`),
8607        // and only the last release actually turns the setting back off.
8608        git::release_worktree_config(&repo).await.ok();
8609        state.enabled_worktree_config = false;
8610    }
8611    state.save_under(home)?;
8612    Ok(removed)
8613}
8614
8615/// Remove `dir` if it exists and has nothing in it.
8616///
8617/// Best-effort and silent by design: a directory that is not empty (a run
8618/// whose winner is still parked there, a stray file some other process left)
8619/// is exactly the case this must refuse, and a directory that is already gone
8620/// is not a failure worth reporting either. `std::fs::remove_dir` itself
8621/// already refuses a non-empty directory, so the emptiness check below is
8622/// belt, not suspenders - it is what keeps this from ever attempting the
8623/// removal in the case that matters, rather than trusting `remove_dir`'s
8624/// error path to have no side effects if it ever changed.
8625fn remove_if_empty(dir: &Path) {
8626    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
8627        std::fs::remove_dir(dir).ok();
8628    }
8629}
8630
8631/// Severity of the worst open finding in the last review round, for reporting.
8632pub fn worst_open(state: &RunState) -> Option<Severity> {
8633    state
8634        .reviews
8635        .last()?
8636        .reviews
8637        .iter()
8638        .flat_map(|r| r.findings.iter())
8639        .map(|f| f.severity)
8640        .max()
8641}
8642
8643#[cfg(test)]
8644mod tests {
8645    #[test]
8646    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
8647        let leaked = vec!["chore(deps): update a crate".to_owned()];
8648        let own = "fix(daemon): apply a chosen action";
8649        assert!(should_retitle("", own, &leaked));
8650        assert!(should_retitle(
8651            &format!("{REVIEW_PROMPT_OPENING} `x`"),
8652            own,
8653            &leaked
8654        ));
8655        assert!(should_retitle(
8656            "chore: land candidate A of run 1",
8657            own,
8658            &leaked
8659        ));
8660        assert!(should_retitle(
8661            "magi: candidate A (uncommitted work)",
8662            own,
8663            &leaked
8664        ));
8665        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
8666        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
8667        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
8668    }
8669
8670    #[test]
8671    fn pr_merge_plan_creates_adopts_or_stops() {
8672        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
8673        assert_eq!(
8674            pr_merge_plan(Ok(land::OpenPr::One {
8675                url: "u".into(),
8676                title: "t".into()
8677            })),
8678            PrPlan::Adopt {
8679                url: "u".into(),
8680                title: "t".into()
8681            }
8682        );
8683        let PrPlan::Stop(many) =
8684            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
8685        else {
8686            panic!("many must stop");
8687        };
8688        assert!(many.contains('a') && many.contains('b'));
8689        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
8690            panic!("a failed lookup must stop");
8691        };
8692        assert!(err.contains("bad token"));
8693    }
8694
8695    use super::*;
8696    use crate::run::GateStatus;
8697    use std::collections::BTreeMap;
8698    use std::time::Duration;
8699
8700    fn conductor() -> AgentSpec {
8701        AgentSpec {
8702            id: "conductor".to_owned(),
8703            kind: crate::config::AgentKind::Command,
8704            model: None,
8705            command: vec!["true".to_owned()],
8706            extra_args: Vec::new(),
8707            env: BTreeMap::new(),
8708            prompt_delivery: None,
8709        }
8710    }
8711
8712    fn spec(id: &str) -> AgentSpec {
8713        AgentSpec {
8714            id: id.to_owned(),
8715            kind: crate::config::AgentKind::Command,
8716            model: None,
8717            command: vec!["true".to_owned()],
8718            extra_args: Vec::new(),
8719            env: BTreeMap::new(),
8720            prompt_delivery: None,
8721        }
8722    }
8723
8724    fn ids(xs: &[&str]) -> BTreeSet<String> {
8725        xs.iter().map(|s| (*s).to_owned()).collect()
8726    }
8727
8728    #[test]
8729    fn pick_successor_skips_an_agent_another_seat_holds() {
8730        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
8731        let roster = [spec("a"), spec("b"), spec("c")];
8732        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
8733        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
8734    }
8735
8736    #[test]
8737    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
8738        // The other seat started on c but was handed to d; c is free again.
8739        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
8740        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
8741        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
8742        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
8743        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
8744    }
8745
8746    #[test]
8747    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
8748        let roster = [spec("a"), spec("b")];
8749        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
8750        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8751        let carried = ids(&["b"]);
8752        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
8753        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8754    }
8755
8756    #[test]
8757    fn pick_successor_returns_none_without_any_untried_successor() {
8758        let roster = [spec("a"), spec("b")];
8759        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
8760        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
8761        let carried = ids(&["a"]);
8762        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
8763    }
8764
8765    #[test]
8766    fn pick_successor_rescue_avoids_another_seats_occupant() {
8767        // b is a carried failure and free; a is held by the other seat.
8768        let roster = [spec("a"), spec("b"), spec("c")];
8769        let carried = ids(&["b", "c"]);
8770        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
8771        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8772    }
8773
8774    #[test]
8775    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
8776        let roster = [spec("a"), spec("b"), spec("c")];
8777        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
8778        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
8779    }
8780
8781    #[test]
8782    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
8783        let roster = [spec("a"), spec("b"), spec("c")];
8784        let failed = ids(&["a", "b", "c"]);
8785        // Rescue looks at the whole roster, once per id, then runs out.
8786        let mut tried = ids(&["b"]);
8787        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
8788        assert_eq!(first.id, "a");
8789        tried.insert(first.id.clone());
8790        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
8791        assert_eq!(second.id, "c");
8792        tried.insert(second.id.clone());
8793        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
8794    }
8795
8796    #[test]
8797    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
8798        let roster = [spec("a"), spec("b")];
8799        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
8800        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8801    }
8802
8803    #[test]
8804    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
8805        let roster = [spec("a"), spec("b"), spec("c")];
8806        let h = SeatHistory {
8807            failed: ids(&["a"]),
8808            last_ok: Some("b".to_owned()),
8809            last_fail: None,
8810        };
8811        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
8812        // A last answerer that left the roster, or later failed, is ignored.
8813        let gone = SeatHistory {
8814            last_ok: Some("zzz".to_owned()),
8815            ..h.clone()
8816        };
8817        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
8818        let failed = SeatHistory {
8819            failed: ids(&["a", "b"]),
8820            last_ok: Some("b".to_owned()),
8821            last_fail: None,
8822        };
8823        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
8824    }
8825
8826    #[test]
8827    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
8828        let first = SeatState::new("review-1", "alpha", 7);
8829        let next = handover_seat("review-1", "gamma", 7);
8830        assert_ne!(first.claude_session, next.claude_session);
8831    }
8832
8833    #[test]
8834    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
8835        let mut state = state_with_summary("x", "y");
8836        let a = handover_seat("review-1", "beta", state.next_seat_seed());
8837        let b = handover_seat("review-1", "beta", state.next_seat_seed());
8838        assert_ne!(a.claude_session, b.claude_session);
8839    }
8840
8841    #[test]
8842    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
8843        let roster = [spec("a"), spec("b")];
8844        let h = SeatHistory {
8845            failed: ids(&["a", "b"]),
8846            ..SeatHistory::default()
8847        };
8848        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
8849        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
8850        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
8851    }
8852
8853    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
8854    // fallback loop depends on to terminate: it must walk forward from the
8855    // seat's own position, never restart at the front of the roster, and it
8856    // must never hand back an id already tried, however many times that id
8857    // happens to appear.
8858
8859    #[test]
8860    fn failure_signature_ignores_numbers_and_paths() {
8861        assert_eq!(
8862            failure_signature("exited with Some(2) and no usable output"),
8863            failure_signature("exited with Some(137) and no usable output")
8864        );
8865        assert_eq!(
8866            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
8867            failure_signature("cannot open /var/x.txt: denied")
8868        );
8869        assert_ne!(failure_signature("boom"), failure_signature("bang"));
8870    }
8871
8872    #[test]
8873    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
8874        let other = FailClass::Other("x".into());
8875        assert!(should_hand_over(None, &FailClass::Quota));
8876        assert!(should_hand_over(Some(&other), &FailClass::Quota));
8877        assert!(should_hand_over(
8878            Some(&FailClass::Timeout),
8879            &FailClass::Timeout
8880        ));
8881        assert!(should_hand_over(None, &other));
8882        assert!(!should_hand_over(Some(&other), &other));
8883        assert!(should_hand_over(
8884            Some(&other),
8885            &FailClass::Other("y".into())
8886        ));
8887        // A quota or timeout in between ends the run of identical failures.
8888        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
8889        assert!(should_hand_over(Some(&FailClass::Quota), &other));
8890    }
8891
8892    #[test]
8893    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
8894        let a = SeatState::new("judge-1", "alpha", 7);
8895        let b = handover_seat("judge-1", "beta", 7);
8896        assert_ne!(a.claude_session, b.claude_session);
8897        assert_eq!(b.turns, 0);
8898    }
8899
8900    #[test]
8901    fn a_timeout_is_classified_apart_from_other_failures() {
8902        assert_eq!(
8903            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
8904            Some(FailClass::Timeout)
8905        );
8906        assert!(matches!(
8907            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
8908            Some(FailClass::Other(_))
8909        ));
8910    }
8911
8912    #[test]
8913    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
8914        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
8915        let tried = BTreeSet::from(["beta".to_owned()]);
8916        // beta sits at index 1; the next candidate is gamma, never alpha —
8917        // which is very likely a different candidate slot's own agent.
8918        let next = next_untried_in_roster(&roster, 1, &tried);
8919        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
8920    }
8921
8922    #[test]
8923    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
8924        let roster = vec![spec("alpha"), spec("beta")];
8925        let tried = BTreeSet::from(["beta".to_owned()]);
8926        // beta is the roster's last entry: nothing follows it, and alpha —
8927        // earlier in the roster, almost certainly a different candidate
8928        // slot's own agent — must not be reached by wrapping back to it.
8929        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
8930    }
8931
8932    #[test]
8933    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
8934        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
8935        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
8936        // beta (index 1) and gamma (index 2, the only entry after it) have
8937        // both been tried; alpha (index 0) never has, but it comes before
8938        // beta's own position, so there is nothing further for this seat.
8939        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
8940    }
8941
8942    #[test]
8943    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
8944        let roster = vec![spec("a"), spec("a"), spec("b")];
8945        let tried = BTreeSet::from(["a".to_owned()]);
8946        let next = next_untried_in_roster(&roster, 0, &tried);
8947        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8948    }
8949
8950    #[test]
8951    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
8952        let roster = vec![spec("a"), spec("b")];
8953        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
8954        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
8955    }
8956
8957    #[test]
8958    fn remove_if_empty_only_ever_takes_a_bare_directory() {
8959        let dir = tempfile::tempdir().unwrap();
8960        let bay = dir.path().join("ffff");
8961
8962        // Not there yet: nothing to do, nothing to panic on.
8963        remove_if_empty(&bay);
8964        assert!(!bay.exists());
8965
8966        // Something still inside - the winner's worktree, or a stray file -
8967        // keeps the directory standing.
8968        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
8969        remove_if_empty(&bay);
8970        assert!(bay.exists(), "non-empty directory must survive");
8971
8972        // Once the last entry is gone, so is the directory itself.
8973        std::fs::remove_dir(bay.join("cand-A")).unwrap();
8974        remove_if_empty(&bay);
8975        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
8976    }
8977
8978    // `round_is_clean` is the exact decision this task fixed: a round with a
8979    // seat that never answered must not read the same as a round every seat
8980    // actually reviewed. These are deterministic and process-free by design —
8981    // the equivalent end-to-end check (a real reviewer timing out under a
8982    // live graph run) is a genuine race against wall-clock contention, and a
8983    // spawn slow enough to blow even a generous budget under a loaded test
8984    // run must not turn this specific regression check flaky.
8985
8986    #[test]
8987    fn a_full_panel_that_found_nothing_is_clean() {
8988        assert!(round_is_clean(
8989            0,
8990            true,
8991            2,
8992            2,
8993            0,
8994            IncompleteReviewPolicy::Block
8995        ));
8996    }
8997
8998    #[test]
8999    fn a_missing_seat_is_never_clean_under_the_default_policy() {
9000        assert!(!round_is_clean(
9001            0,
9002            true,
9003            1,
9004            2,
9005            0,
9006            IncompleteReviewPolicy::Block
9007        ));
9008    }
9009
9010    #[test]
9011    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
9012        assert!(!round_is_clean(
9013            1,
9014            true,
9015            1,
9016            2,
9017            0,
9018            IncompleteReviewPolicy::Warn
9019        ));
9020    }
9021
9022    #[test]
9023    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
9024        assert!(round_is_clean(
9025            0,
9026            true,
9027            1,
9028            2,
9029            0,
9030            IncompleteReviewPolicy::Warn
9031        ));
9032    }
9033
9034    #[test]
9035    fn a_full_panel_with_an_open_finding_is_not_clean() {
9036        assert!(!round_is_clean(
9037            1,
9038            true,
9039            2,
9040            2,
9041            0,
9042            IncompleteReviewPolicy::Block
9043        ));
9044    }
9045
9046    #[test]
9047    fn a_full_panel_with_a_red_e2e_is_not_clean() {
9048        assert!(!round_is_clean(
9049            0,
9050            false,
9051            2,
9052            2,
9053            0,
9054            IncompleteReviewPolicy::Block
9055        ));
9056    }
9057
9058    // The stall this task closes: under the default `block` policy, a seat
9059    // missing only because it was rate limited must not force a wait for a
9060    // session limit that will not lift by the next round. `round_is_clean`
9061    // is where that quorum carve-out lives; the review loop around it never
9062    // changes what a reviewer's vote or a finding's severity means.
9063
9064    #[test]
9065    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
9066        // 1 of 2 answered, and the one missing was quota'd — the exact
9067        // "review-2 rate limited (quota)" shape from the field report.
9068        assert!(round_is_clean(
9069            0,
9070            true,
9071            1,
9072            2,
9073            1,
9074            IncompleteReviewPolicy::Block
9075        ));
9076    }
9077
9078    #[test]
9079    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
9080        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
9081        // not a quota loss (`quota_missing` stays 0) — worth another try.
9082        assert!(!round_is_clean(
9083            0,
9084            true,
9085            1,
9086            2,
9087            0,
9088            IncompleteReviewPolicy::Block
9089        ));
9090    }
9091
9092    #[test]
9093    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
9094        assert!(!round_is_clean(
9095            1,
9096            true,
9097            1,
9098            2,
9099            1,
9100            IncompleteReviewPolicy::Block
9101        ));
9102        assert!(!round_is_clean(
9103            0,
9104            false,
9105            1,
9106            2,
9107            1,
9108            IncompleteReviewPolicy::Block
9109        ));
9110    }
9111
9112    #[test]
9113    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
9114        // Every seat quota'd, nobody answered: there is no panel to decide
9115        // on, so this must fall through to the existing block-and-retry
9116        // fallback rather than call an unreviewed patch clean.
9117        assert!(!round_is_clean(
9118            0,
9119            true,
9120            0,
9121            2,
9122            2,
9123            IncompleteReviewPolicy::Block
9124        ));
9125    }
9126
9127    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
9128        CommandOutcome {
9129            command: "test".to_owned(),
9130            code,
9131            output_tail: String::new(),
9132            duration_ms: 0,
9133            resource_blocked,
9134        }
9135    }
9136
9137    #[test]
9138    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
9139        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
9140        assert!(
9141            !verify_inconclusive(&[outcome(Some(1), false)]),
9142            "an ordinary failure is still evidence about the patch"
9143        );
9144        assert!(verify_inconclusive(&[outcome(None, true)]));
9145        assert!(
9146            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
9147            "one inconclusive outcome taints the whole batch"
9148        );
9149        assert!(!verify_inconclusive(&[]));
9150    }
9151
9152    #[tokio::test]
9153    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
9154        // Alive for the first two checks, then dead - confirms the loop
9155        // actually re-polls rather than deciding once and sleeping out the
9156        // ceiling regardless.
9157        let calls = std::sync::atomic::AtomicUsize::new(0);
9158        let started = Instant::now();
9159        wait_for_pids_with(
9160            &[123],
9161            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
9162            Duration::from_millis(5),
9163            Duration::from_secs(5),
9164        )
9165        .await;
9166        assert!(
9167            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
9168            "must keep checking rather than deciding on the first answer"
9169        );
9170        assert!(
9171            started.elapsed() < Duration::from_secs(1),
9172            "must return the moment it is confirmed dead, not wait out the ceiling"
9173        );
9174    }
9175
9176    #[tokio::test]
9177    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
9178        let started = Instant::now();
9179        wait_for_pids_with(
9180            &[123],
9181            |_| true, // never reports dead
9182            Duration::from_millis(5),
9183            Duration::from_millis(30),
9184        )
9185        .await;
9186        let elapsed = started.elapsed();
9187        assert!(
9188            elapsed >= Duration::from_millis(30),
9189            "must not give up before its own ceiling: {elapsed:?}"
9190        );
9191        assert!(
9192            elapsed < Duration::from_secs(1),
9193            "must not wait past its own ceiling either: {elapsed:?}"
9194        );
9195    }
9196
9197    #[tokio::test]
9198    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
9199        let started = Instant::now();
9200        wait_for_pids_with(
9201            &[],
9202            |_| true,
9203            Duration::from_secs(5),
9204            Duration::from_secs(5),
9205        )
9206        .await;
9207        assert!(
9208            started.elapsed() < Duration::from_millis(200),
9209            "an empty pid list has nothing to confirm"
9210        );
9211    }
9212
9213    // `review_conclusion` is the exact decision the review hand-off task
9214    // fixed: a round budget spent (or a tree that stopped moving) must not
9215    // collapse into `Blocked` regardless of what verification actually
9216    // said. Deterministic and process-free for the same reason the
9217    // `round_is_clean` family above is.
9218    fn review_round(
9219        clean: bool,
9220        blocking: usize,
9221        answered: usize,
9222        expected: usize,
9223        progressed: bool,
9224        e2e_ok: bool,
9225    ) -> ReviewRound {
9226        ReviewRound {
9227            round: 1,
9228            head: "h".to_owned(),
9229            verified_head: None,
9230            verified_at: None,
9231            reviews: Vec::new(),
9232            e2e: vec![CommandOutcome {
9233                command: "test".to_owned(),
9234                code: Some(if e2e_ok { 0 } else { 1 }),
9235                output_tail: String::new(),
9236                duration_ms: 0,
9237                resource_blocked: false,
9238            }],
9239            verify_retried: false,
9240            e2e_deferred: false,
9241            e2e_defer_reason: None,
9242            fix: None,
9243            blocking,
9244            answered,
9245            expected,
9246            clean,
9247            progressed,
9248            vote_split: false,
9249            reconsideration: Vec::new(),
9250            verdict: None,
9251        }
9252    }
9253
9254    #[test]
9255    fn review_conclusion_is_none_when_nothing_has_run() {
9256        assert_eq!(review_conclusion(&[], 3), None);
9257    }
9258
9259    #[test]
9260    fn review_conclusion_is_none_while_rounds_remain() {
9261        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
9262        assert_eq!(review_conclusion(&rounds, 3), None);
9263    }
9264
9265    #[test]
9266    fn review_conclusion_is_gating_once_a_round_is_clean() {
9267        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
9268        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
9269    }
9270
9271    #[test]
9272    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
9273        let rounds = vec![
9274            review_round(false, 1, 2, 2, true, true),
9275            review_round(false, 1, 2, 2, true, true),
9276        ];
9277        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
9278    }
9279
9280    #[test]
9281    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
9282        let rounds = vec![
9283            review_round(false, 1, 2, 2, true, true),
9284            review_round(false, 1, 2, 2, true, false),
9285        ];
9286        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
9287    }
9288
9289    #[test]
9290    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
9291        // Magi never got a command to run against this round's own head — a
9292        // resource-blocked attempt, not a red one — so this must never
9293        // settle on `Blocked` the way a genuine e2e failure would. `None`
9294        // here is what tells `Runner::review_loop` to retry the check
9295        // itself rather than trust this cheap recomputation with a verdict
9296        // it cannot actually produce.
9297        let mut blocked = review_round(false, 1, 2, 2, true, false);
9298        blocked.e2e[0].resource_blocked = true;
9299        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
9300        assert_eq!(review_conclusion(&rounds, 2), None);
9301    }
9302
9303    #[test]
9304    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
9305        // Missing input, not a verified tree — never a hand-off candidate.
9306        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
9307        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
9308    }
9309
9310    #[test]
9311    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
9312        let rounds = vec![
9313            review_round(false, 1, 2, 2, false, true),
9314            review_round(false, 1, 2, 2, false, true),
9315        ];
9316        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
9317    }
9318
9319    fn secs(n: u64) -> Duration {
9320        Duration::from_secs(n)
9321    }
9322
9323    /// A throwaway repo with one commit on `main`, for tests that need `merge`
9324    /// to make real (and, if it runs at all, real*ly fail*) git calls.
9325    fn init_repo(dir: &Path) {
9326        let run = |args: &[&str]| {
9327            let out = std::process::Command::new("git")
9328                .args(args)
9329                .current_dir(dir)
9330                .quiet()
9331                .output()
9332                .expect("spawn git");
9333            assert!(
9334                out.status.success(),
9335                "git {args:?} failed: {}",
9336                String::from_utf8_lossy(&out.stderr)
9337            );
9338        };
9339        run(&["init", "-b", "main"]);
9340        run(&["config", "user.name", "magi test"]);
9341        run(&["config", "user.email", "magi@example.com"]);
9342        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
9343        run(&["add", "-A"]);
9344        run(&["commit", "-m", "init"]);
9345    }
9346
9347    // `settle_questions` is what closes the ghost the phone showed: a run's
9348    // seat asked something, the run then ended, and nothing was left to
9349    // abandon the question it left `open`. `HOME` is a process-wide
9350    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
9351    // first time it runs in the binary — every test below still reaches the
9352    // same directory whichever call won, and each gets its own run id from
9353    // `RunState::new`, so they never collide there.
9354    fn ask_test_home() {
9355        crate::run::pin_test_home();
9356    }
9357
9358    /// A minimal, git-free `Runner` at a given status — `settle_questions`
9359    /// reads nothing else off it.
9360    fn runner_at(status: RunStatus) -> Runner {
9361        let mut state = RunState::new(
9362            PathBuf::from("/nonexistent/repo"),
9363            "main".to_owned(),
9364            "deadbeef".to_owned(),
9365            "task".to_owned(),
9366            Config::default(),
9367        );
9368        state.status = status;
9369        Runner {
9370            state,
9371            roles: ResolvedRoles {
9372                implementers: Vec::new(),
9373                judges: Vec::new(),
9374                reviewers: Vec::new(),
9375                fixer: None,
9376                conductor: conductor(),
9377                implementer_roster: Vec::new(),
9378                judge_roster: Vec::new(),
9379                reviewer_roster: Vec::new(),
9380            },
9381            sem: Arc::new(Semaphore::new(1)),
9382            pause: Pause::new(),
9383            interrupt: Pause::new(),
9384        }
9385    }
9386
9387    /// `park_here` folding in the reason `Pause::park_because` recorded -
9388    /// this is what lets an operator reading a run's events tell an
9389    /// interrupt-driven park from an ordinary shutdown park.
9390    #[test]
9391    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
9392        crate::run::pin_test_home();
9393        let mut runner = runner_at(RunStatus::Implementing);
9394        let interrupt = Pause::new();
9395        runner.watch_interrupt(interrupt.clone());
9396
9397        interrupt.park_because("task a1b2 asked to run first");
9398
9399        assert!(runner.park_here().expect("park_here"));
9400        assert!(runner.state.parked);
9401        let last = runner.state.events.last().expect("a park event");
9402        assert_eq!(last.node, "park");
9403        assert!(
9404            last.message.contains("task a1b2 asked to run first"),
9405            "expected the interrupt reason in {:?}",
9406            last.message
9407        );
9408    }
9409
9410    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
9411    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
9412    /// cleared) must not make a *different* run - one only watching its own,
9413    /// unshared interrupt `Pause` - see itself as parked. If a future change
9414    /// ever collapsed these back into one handle, the interrupt scheduler
9415    /// would park every run for the rest of the daemon's life, not just the
9416    /// one it meant to interrupt.
9417    #[test]
9418    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
9419        crate::run::pin_test_home();
9420        let mut runner = runner_at(RunStatus::Implementing);
9421        let shutdown = Pause::new();
9422        runner.on_pause(shutdown.clone());
9423        let interrupt = Pause::new();
9424        runner.watch_interrupt(interrupt.clone());
9425
9426        // Nobody has asked for anything yet.
9427        assert!(!runner.park_here().expect("park_here"));
9428        assert!(!runner.state.parked);
9429
9430        // Only the interrupt handle fires; the shutdown handle stays clear.
9431        interrupt.park_because("test");
9432        assert!(!shutdown.parked());
9433        assert!(runner.park_here().expect("park_here"));
9434    }
9435
9436    /// The property every prior attempt at this feature failed to pin down:
9437    /// asking a run to park while one of its nodes has a real, in-flight
9438    /// async operation running (an agent call, in production) must not cut
9439    /// that operation short. `park_here` is only ever consulted *between*
9440    /// `execute`'s node calls - see its own doc - so nothing inside a node
9441    /// can observe a park request until the node itself returns. This proves
9442    /// that structurally, with real `tokio` concurrency and a channel
9443    /// handshake (never a sleep, which would only prove "usually", not
9444    /// "cannot"): the "node" below reports that it has genuinely started,
9445    /// and only then is the park requested; the node still has to be told to
9446    /// finish before `park_here` is ever called, exactly mirroring every
9447    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
9448    /// in `execute`.
9449    #[tokio::test]
9450    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
9451        crate::run::pin_test_home();
9452        let mut runner = runner_at(RunStatus::Implementing);
9453        let interrupt = Pause::new();
9454        runner.watch_interrupt(interrupt.clone());
9455
9456        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
9457        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
9458
9459        // Stands in for one node's in-flight agent call: it proves it has
9460        // genuinely started, then blocks - exactly as a spawned CLI process
9461        // does - until told to finish.
9462        let node = async move {
9463            started_tx.send(()).expect("send started");
9464            finish_rx.await.expect("recv finish");
9465            "node finished"
9466        };
9467
9468        let interrupter = async move {
9469            started_rx.await.expect("recv started");
9470            // The call is now genuinely in flight. Ask it to park.
9471            interrupt.park_because("higher-priority task waiting");
9472            // Nothing the node does can observe this yet - there is no
9473            // check inside it, by construction - so let the executor run
9474            // anything pending and then let the node finish on its own.
9475            tokio::task::yield_now().await;
9476            finish_tx.send(()).expect("send finish");
9477        };
9478
9479        let (node_result, ()) = tokio::join!(node, interrupter);
9480        assert_eq!(
9481            node_result, "node finished",
9482            "the in-flight call ran to completion"
9483        );
9484
9485        // Only now, at the boundary the real `execute` would check right
9486        // after this node, does the park take effect.
9487        assert!(runner.park_here().expect("park_here"));
9488        assert!(runner.state.parked);
9489    }
9490
9491    /// A run parked mid-competition carries every field it had accumulated
9492    /// through the exact same disk round-trip an ordinary resume uses -
9493    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
9494    /// Nothing about parking for an interrupt is a special case of that path;
9495    /// this is what proves it rather than assuming it.
9496    #[test]
9497    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
9498        crate::run::pin_test_home();
9499        let mut runner = runner_at(RunStatus::Judging);
9500        // `Runner::resume` re-resolves roles from the saved config, which
9501        // refuses an empty roster - give it the same minimal one `conductor`
9502        // itself uses.
9503        runner.state.config.agents = vec![conductor()];
9504        runner.state.candidates = vec![Candidate {
9505            index: 0,
9506            label: 'A',
9507            agent: "alpha".to_owned(),
9508            branch: "magi/x/A".to_owned(),
9509            worktree: PathBuf::from("/nonexistent/worktree"),
9510            summary: "did the thing".to_owned(),
9511            stat: "1 file changed".to_owned(),
9512            files: 1,
9513            commits: 1,
9514            empty: false,
9515            failed: None,
9516            verified_noop: None,
9517            duration_ms: 1234,
9518            folded: false,
9519        }];
9520        let run_id = runner.state.id.clone();
9521
9522        let interrupt = Pause::new();
9523        runner.watch_interrupt(interrupt.clone());
9524        interrupt.park_because("task c3d4 asked to run first");
9525        assert!(runner.park_here().expect("park_here"));
9526
9527        let resumed = Runner::resume(&run_id).expect("resume");
9528        assert_eq!(resumed.state.candidates.len(), 1);
9529        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
9530        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
9531        assert_eq!(resumed.state.status, runner.state.status);
9532        assert!(
9533            resumed.state.parked,
9534            "still parked until `execute` actually walks the graph again"
9535        );
9536        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
9537    }
9538
9539    /// A fresh open question on `run`, stored and handed back for assertions.
9540    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
9541        let mut q = ask::Question::new(
9542            run.to_owned(),
9543            "implement".to_owned(),
9544            "impl-A".to_owned(),
9545            "Which storage backend should the cache use?".to_owned(),
9546            String::new(),
9547            vec!["SQLite".to_owned(), "Redis".to_owned()],
9548        );
9549        store.put(&mut q).unwrap();
9550        q
9551    }
9552
9553    #[test]
9554    fn a_failed_runs_open_question_is_abandoned() {
9555        ask_test_home();
9556        let store = ask::Questions::open();
9557        let mut runner = runner_at(RunStatus::Failed);
9558        let run = runner.state.id.clone();
9559        let q = ask_open_question(&store, &run);
9560
9561        runner.settle_questions();
9562
9563        let back = store.get(&q.id).unwrap();
9564        assert!(
9565            !back.status.open(),
9566            "the seat that asked died with the run; nobody is left to read an answer"
9567        );
9568        assert!(
9569            back.detail.contains(&run) && back.detail.contains("failed"),
9570            "the reason names what the run became, not just that it is gone: {}",
9571            back.detail
9572        );
9573    }
9574
9575    #[test]
9576    fn a_merged_runs_open_question_is_abandoned_too() {
9577        ask_test_home();
9578        let store = ask::Questions::open();
9579        // A run that finishes cleanly still leaves nobody to read an answer -
9580        // this is not only a failure-path cleanup.
9581        for status in [RunStatus::Merged, RunStatus::Ready] {
9582            let mut runner = runner_at(status);
9583            let run = runner.state.id.clone();
9584            let q = ask_open_question(&store, &run);
9585
9586            runner.settle_questions();
9587
9588            let back = store.get(&q.id).unwrap();
9589            assert!(
9590                !back.status.open(),
9591                "{status:?} run's question must not outlive the run"
9592            );
9593        }
9594    }
9595
9596    #[test]
9597    fn a_still_resumable_runs_open_question_is_left_alone() {
9598        ask_test_home();
9599        let store = ask::Questions::open();
9600        // `Blocked` and `Stalled` can still be resumed — the candidates, the
9601        // review round and the seat sessions are all still on disk — so a
9602        // question asked mid-round may yet get a real answer from a real
9603        // resume. Sweeping it here would be exactly the failure mode this
9604        // whole feature exists to avoid on the other side.
9605        for status in [RunStatus::Blocked, RunStatus::Stalled] {
9606            let mut runner = runner_at(status);
9607            let run = runner.state.id.clone();
9608            let q = ask_open_question(&store, &run);
9609
9610            runner.settle_questions();
9611
9612            let back = store.get(&q.id).unwrap();
9613            assert!(
9614                back.status.open(),
9615                "{status:?} is still alive; the question must still be waiting"
9616            );
9617        }
9618    }
9619
9620    #[test]
9621    fn settle_questions_never_touches_an_already_answered_question() {
9622        ask_test_home();
9623        let store = ask::Questions::open();
9624        let mut runner = runner_at(RunStatus::Failed);
9625        let run = runner.state.id.clone();
9626        let mut q = ask_open_question(&store, &run);
9627        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
9628            .unwrap();
9629        store.put(&mut q).unwrap();
9630
9631        // Called twice, the way a crash-recovered daemon reclaim and the
9632        // graph's own cleanup both can for the same run — `abandon_for_run`
9633        // only ever touches what is still open, so this must be inert both
9634        // times, not merely the second.
9635        runner.settle_questions();
9636        runner.settle_questions();
9637
9638        let back = store.get(&q.id).unwrap();
9639        assert_eq!(
9640            back.status,
9641            ask::QuestionStatus::Answered,
9642            "a real answer is a decision on record, never overwritten by a sweep"
9643        );
9644    }
9645
9646    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
9647    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
9648    /// without merging, whose winner is still the operator's answer to read.
9649    /// Nothing previously called `fold_run` itself with a real `tally`, so
9650    /// this is the first test to pin down the one distinction the whole
9651    /// automatic-fold feature depends on: the winner's worktree and branch
9652    /// must survive, everything else sharing the run's worktree bay - a
9653    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
9654    /// second sweep treats every non-winner directory under the bay alike -
9655    /// must not.
9656    #[tokio::test]
9657    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
9658        crate::run::pin_test_home();
9659        let tmp = tempfile::tempdir().expect("tempdir");
9660        let repo = tmp.path().join("repo");
9661        std::fs::create_dir_all(&repo).unwrap();
9662        init_repo(&repo);
9663
9664        let mut config = Config::default();
9665        config.graph.worktree_root = Some(tmp.path().join("wt"));
9666
9667        let mut state = RunState::new(
9668            repo.clone(),
9669            "main".to_owned(),
9670            "deadbeef".to_owned(),
9671            "task".to_owned(),
9672            config,
9673        );
9674        let root = state.worktree_root();
9675        let wt_a = root.join("cand-A");
9676        let wt_b = root.join("cand-B");
9677        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
9678            .await
9679            .expect("worktree A");
9680        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
9681            .await
9682            .expect("worktree B");
9683
9684        state.candidates = vec![
9685            Candidate {
9686                index: 0,
9687                label: 'A',
9688                agent: "alpha".to_owned(),
9689                branch: "magi/x/A".to_owned(),
9690                worktree: wt_a.clone(),
9691                summary: String::new(),
9692                stat: String::new(),
9693                files: 0,
9694                commits: 0,
9695                empty: false,
9696                failed: None,
9697                verified_noop: None,
9698                duration_ms: 0,
9699                folded: false,
9700            },
9701            Candidate {
9702                index: 1,
9703                label: 'B',
9704                agent: "beta".to_owned(),
9705                branch: "magi/x/B".to_owned(),
9706                worktree: wt_b.clone(),
9707                summary: String::new(),
9708                stat: String::new(),
9709                files: 0,
9710                commits: 0,
9711                empty: false,
9712                failed: None,
9713                verified_noop: None,
9714                duration_ms: 0,
9715                folded: false,
9716            },
9717        ];
9718        state.tally = Some(Tally {
9719            first_choice: BTreeMap::from([('A', 1)]),
9720            borda: BTreeMap::new(),
9721            winner: 'A',
9722            rankings: 1,
9723            unanimous_initial: true,
9724            deliberated: false,
9725            changed_votes: 0,
9726            unanimous_final: true,
9727            tie_break: None,
9728            judges: 1,
9729            present: 1,
9730            quorum: 1,
9731            met_quorum: true,
9732            uncontested: None,
9733        });
9734        state.status = RunStatus::Ready;
9735
9736        fold_run(&mut state, false, &crate::run::home())
9737            .await
9738            .expect("fold_run");
9739
9740        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
9741        assert!(
9742            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
9743            "the unmerged winner's branch survives"
9744        );
9745        assert!(
9746            !state.candidates[0].folded,
9747            "the winner is not marked folded"
9748        );
9749
9750        assert!(!wt_b.exists(), "the loser's worktree is removed");
9751        assert!(
9752            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
9753            "the loser's branch is removed"
9754        );
9755        assert!(state.candidates[1].folded, "the loser is marked folded");
9756    }
9757
9758    /// A branch handed to a later run is that run's (and its pull request's):
9759    /// folding the run that released it must not delete it.
9760    #[tokio::test]
9761    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
9762        let tmp = tempfile::tempdir().expect("tempdir");
9763        let repo = tmp.path().join("repo");
9764        std::fs::create_dir_all(&repo).unwrap();
9765        init_repo(&repo);
9766        let home = tmp.path().join("home");
9767
9768        let mut config = Config::default();
9769        config.graph.worktree_root = Some(tmp.path().join("wt"));
9770        let mut state = RunState::new(
9771            repo.clone(),
9772            "main".to_owned(),
9773            "deadbeef".to_owned(),
9774            "task".to_owned(),
9775            config,
9776        );
9777        // The worktree is already gone (released); the branch survives.
9778        git::git(&repo, &["branch", "magi/x/A", "main"])
9779            .await
9780            .expect("branch");
9781        state.candidates = vec![Candidate {
9782            index: 0,
9783            label: 'A',
9784            agent: "alpha".to_owned(),
9785            branch: "magi/x/A".to_owned(),
9786            worktree: state.worktree_root().join("cand-A"),
9787            summary: String::new(),
9788            stat: String::new(),
9789            files: 0,
9790            commits: 0,
9791            empty: false,
9792            failed: None,
9793            verified_noop: None,
9794            duration_ms: 0,
9795            folded: true,
9796        }];
9797        state.released_to = Some("20260901-000000-new1".to_owned());
9798        state.released_branches = vec!["magi/x/A".to_owned()];
9799
9800        fold_run(&mut state, true, &home).await.expect("fold_run");
9801
9802        assert!(
9803            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
9804            "the handed-over branch survives a fold"
9805        );
9806    }
9807
9808    /// A winner with nothing ahead of the base is caught before `gh` is ever
9809    /// asked for a pull request, and the message carries what the task's
9810    /// references resolved to.
9811    #[tokio::test]
9812    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
9813        let tmp = tempfile::tempdir().expect("tempdir");
9814        let repo = tmp.path().join("repo");
9815        std::fs::create_dir_all(&repo).unwrap();
9816        init_repo(&repo);
9817        let run = |args: &[&str]| {
9818            let out = std::process::Command::new("git")
9819                .quiet()
9820                .args(args)
9821                .current_dir(&repo)
9822                .output()
9823                .expect("spawn git");
9824            assert!(out.status.success(), "git {args:?}");
9825        };
9826        run(&["branch", "magi/x/A"]);
9827        run(&["checkout", "-q", "-b", "magi/x/B"]);
9828        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
9829        run(&["add", "-A"]);
9830        run(&["commit", "-q", "-m", "work"]);
9831        run(&["checkout", "-q", "main"]);
9832
9833        // A pull request is compared against the remote's base, so the
9834        // fixture needs one. Before it exists nothing can be read, and the
9835        // answer must be "not empty".
9836        let probe = RunState::new(
9837            repo.clone(),
9838            "main".to_owned(),
9839            "deadbeef".to_owned(),
9840            "task".to_owned(),
9841            Config::default(),
9842        );
9843        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
9844        let bare = tmp.path().join("origin.git");
9845        let out = std::process::Command::new("git")
9846            .quiet()
9847            .args(["init", "-q", "--bare"])
9848            .arg(&bare)
9849            .output()
9850            .expect("spawn git");
9851        assert!(out.status.success(), "git init --bare");
9852        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
9853        run(&["push", "-q", "origin", "main"]);
9854
9855        let mut state = RunState::new(
9856            repo.clone(),
9857            "main".to_owned(),
9858            "deadbeef".to_owned(),
9859            "task".to_owned(),
9860            Config::default(),
9861        );
9862        state.seeds = vec![refs::Seed {
9863            token: "magi/27b2/A".to_owned(),
9864            kind: refs::SeedKind::Unresolved,
9865            sha: String::new(),
9866            branch: true,
9867            detail: "no branch or commit named magi/27b2/A".to_owned(),
9868        }];
9869
9870        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
9871        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
9872        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
9873        let detail = empty_candidate_detail(&state, "main");
9874        assert!(detail.starts_with("empty candidate"), "{detail}");
9875        assert!(detail.contains("magi/27b2/A"), "{detail}");
9876    }
9877
9878    /// `status == Ready` used to be read as "this is the harmless
9879    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
9880    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
9881    /// run's PR was closed without merging — and reentering `merge` with
9882    /// `mode` still `Pr` does not know the difference, so it pushed and
9883    /// opened a second pull request. `mode == Local` reproduces the same
9884    /// blind spot without a network call: reentry must not attempt another
9885    /// git merge once this node has already recorded an outcome.
9886    #[tokio::test]
9887    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
9888        let tmp = tempfile::tempdir().expect("tempdir");
9889        let repo = tmp.path().join("repo");
9890        std::fs::create_dir_all(&repo).unwrap();
9891        init_repo(&repo);
9892
9893        let mut config = Config::default();
9894        config.merge.mode = MergeMode::Local;
9895
9896        let mut state = RunState::new(
9897            repo.clone(),
9898            "main".to_owned(),
9899            "deadbeef".to_owned(),
9900            "task".to_owned(),
9901            config,
9902        );
9903        state.candidates = vec![Candidate {
9904            index: 0,
9905            label: 'A',
9906            agent: "alpha".to_owned(),
9907            branch: "does-not-exist".to_owned(),
9908            worktree: repo.clone(),
9909            summary: String::new(),
9910            stat: String::new(),
9911            files: 0,
9912            commits: 0,
9913            empty: false,
9914            failed: None,
9915            verified_noop: None,
9916            duration_ms: 0,
9917            folded: false,
9918        }];
9919        state.tally = Some(Tally {
9920            first_choice: BTreeMap::from([('A', 1)]),
9921            borda: BTreeMap::new(),
9922            winner: 'A',
9923            rankings: 1,
9924            unanimous_initial: true,
9925            deliberated: false,
9926            changed_votes: 0,
9927            unanimous_final: true,
9928            tie_break: None,
9929            judges: 0,
9930            present: 0,
9931            quorum: 0,
9932            met_quorum: true,
9933            uncontested: Some("only candidate A produced a change".to_owned()),
9934        });
9935        state.reviews = vec![ReviewRound {
9936            round: 1,
9937            head: "deadbeef".to_owned(),
9938            verified_head: None,
9939            verified_at: None,
9940            reviews: Vec::new(),
9941            e2e: Vec::new(),
9942            fix: None,
9943            blocking: 0,
9944            answered: 0,
9945            expected: 0,
9946            clean: true,
9947            verify_retried: false,
9948            e2e_deferred: false,
9949            e2e_defer_reason: None,
9950            progressed: false,
9951            vote_split: false,
9952            reconsideration: Vec::new(),
9953            verdict: None,
9954        }];
9955        state.gate = vec![CommandOutcome {
9956            command: "test".to_owned(),
9957            code: Some(0),
9958            output_tail: String::new(),
9959            duration_ms: 0,
9960            resource_blocked: false,
9961        }];
9962        state.gate_ran = true;
9963        // Reached its conclusion already — e.g. `land` closing the PR without
9964        // merging it, which (like the honest `MergeMode::None` path) leaves
9965        // `status` at `Ready`. The recorded outcome is what actually marks
9966        // this node done.
9967        state.status = RunStatus::Ready;
9968        state.merge = Some(MergeOutcome {
9969            mode: MergeMode::Local,
9970            ok: false,
9971            detail: "already concluded".to_owned(),
9972            empty: false,
9973        });
9974
9975        let mut runner = Runner {
9976            state,
9977            roles: ResolvedRoles {
9978                implementers: Vec::new(),
9979                judges: Vec::new(),
9980                reviewers: Vec::new(),
9981                fixer: None,
9982                conductor: conductor(),
9983                implementer_roster: Vec::new(),
9984                judge_roster: Vec::new(),
9985                reviewer_roster: Vec::new(),
9986            },
9987            sem: Arc::new(Semaphore::new(1)),
9988            pause: Pause::new(),
9989            interrupt: Pause::new(),
9990        };
9991
9992        runner.merge().await.expect("merge");
9993
9994        assert_eq!(
9995            runner.state.status,
9996            RunStatus::Ready,
9997            "a concluded run's status must not change on reentry"
9998        );
9999        assert_eq!(
10000            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
10001            Some("already concluded"),
10002            "merge must not run again once the node already recorded an outcome"
10003        );
10004    }
10005
10006    /// `gate` leaves `state.gate_ran` false both before it has ever run and
10007    /// when its last attempt was resource-blocked (the shared build cache
10008    /// could not be acquired or confirmed fresh in time - see
10009    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
10010    /// `Vec` this also leaves behind used to read as "nothing failed" and let
10011    /// a run merge a tree the gate never actually checked - exactly the case
10012    /// a contended cache produces on every retry until it clears. `merge`
10013    /// must refuse until `gate` has actually recorded an attempt.
10014    #[tokio::test]
10015    async fn merge_refuses_a_gate_that_has_not_actually_run() {
10016        let tmp = tempfile::tempdir().expect("tempdir");
10017        let repo = tmp.path().join("repo");
10018        std::fs::create_dir_all(&repo).unwrap();
10019        init_repo(&repo);
10020
10021        let mut config = Config::default();
10022        config.merge.mode = MergeMode::Local;
10023
10024        let mut state = RunState::new(
10025            repo.clone(),
10026            "main".to_owned(),
10027            "deadbeef".to_owned(),
10028            "task".to_owned(),
10029            config,
10030        );
10031        state.candidates = vec![Candidate {
10032            index: 0,
10033            label: 'A',
10034            agent: "alpha".to_owned(),
10035            branch: "does-not-exist".to_owned(),
10036            worktree: repo.clone(),
10037            summary: String::new(),
10038            stat: String::new(),
10039            files: 0,
10040            commits: 0,
10041            empty: false,
10042            failed: None,
10043            verified_noop: None,
10044            duration_ms: 0,
10045            folded: false,
10046        }];
10047        state.tally = Some(Tally {
10048            first_choice: BTreeMap::from([('A', 1)]),
10049            borda: BTreeMap::new(),
10050            winner: 'A',
10051            rankings: 1,
10052            unanimous_initial: true,
10053            deliberated: false,
10054            changed_votes: 0,
10055            unanimous_final: true,
10056            tie_break: None,
10057            judges: 0,
10058            present: 0,
10059            quorum: 0,
10060            met_quorum: true,
10061            uncontested: Some("only candidate A produced a change".to_owned()),
10062        });
10063        state.reviews = vec![ReviewRound {
10064            round: 1,
10065            head: "deadbeef".to_owned(),
10066            verified_head: None,
10067            verified_at: None,
10068            reviews: Vec::new(),
10069            e2e: Vec::new(),
10070            fix: None,
10071            blocking: 0,
10072            answered: 0,
10073            expected: 0,
10074            clean: true,
10075            verify_retried: false,
10076            e2e_deferred: false,
10077            e2e_defer_reason: None,
10078            progressed: false,
10079            vote_split: false,
10080            reconsideration: Vec::new(),
10081            verdict: None,
10082        }];
10083        // The point: `gate` has not recorded anything yet.
10084        state.gate = Vec::new();
10085        state.gate_ran = false;
10086        state.status = RunStatus::Gating;
10087
10088        let mut runner = Runner {
10089            state,
10090            roles: ResolvedRoles {
10091                implementers: Vec::new(),
10092                judges: Vec::new(),
10093                reviewers: Vec::new(),
10094                fixer: None,
10095                conductor: conductor(),
10096                implementer_roster: Vec::new(),
10097                judge_roster: Vec::new(),
10098                reviewer_roster: Vec::new(),
10099            },
10100            sem: Arc::new(Semaphore::new(1)),
10101            pause: Pause::new(),
10102            interrupt: Pause::new(),
10103        };
10104
10105        runner.merge().await.expect("merge");
10106
10107        assert!(
10108            runner.state.merge.is_none(),
10109            "an empty gate must never be read as a passing one: {:?}",
10110            runner.state.merge
10111        );
10112    }
10113
10114    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
10115    /// commands configured and `merge.mode` is `none` (a review-only run).
10116    /// `gate` must still record a real attempt — zero commands, vacuously
10117    /// passed — rather than leaving `state.gate` empty in a way `merge`
10118    /// cannot tell apart from "never ran"; otherwise the run reaches
10119    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
10120    #[tokio::test]
10121    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
10122        let tmp = tempfile::tempdir().expect("tempdir");
10123        let repo = tmp.path().join("repo");
10124        std::fs::create_dir_all(&repo).unwrap();
10125        init_repo(&repo);
10126
10127        // Default config: `verify.gate` empty, `merge.mode` is `none`.
10128        let config = Config::default();
10129
10130        let mut state = RunState::new(
10131            repo.clone(),
10132            "main".to_owned(),
10133            "deadbeef".to_owned(),
10134            "task".to_owned(),
10135            config,
10136        );
10137        state.candidates = vec![Candidate {
10138            index: 0,
10139            label: 'A',
10140            agent: "alpha".to_owned(),
10141            branch: "does-not-exist".to_owned(),
10142            worktree: repo.clone(),
10143            summary: String::new(),
10144            stat: String::new(),
10145            files: 0,
10146            commits: 0,
10147            empty: false,
10148            failed: None,
10149            verified_noop: None,
10150            duration_ms: 0,
10151            folded: false,
10152        }];
10153        state.tally = Some(Tally {
10154            first_choice: BTreeMap::from([('A', 1)]),
10155            borda: BTreeMap::new(),
10156            winner: 'A',
10157            rankings: 1,
10158            unanimous_initial: true,
10159            deliberated: false,
10160            changed_votes: 0,
10161            unanimous_final: true,
10162            tie_break: None,
10163            judges: 0,
10164            present: 0,
10165            quorum: 0,
10166            met_quorum: true,
10167            uncontested: Some("only candidate A produced a change".to_owned()),
10168        });
10169        state.reviews = vec![ReviewRound {
10170            round: 1,
10171            head: "deadbeef".to_owned(),
10172            verified_head: None,
10173            verified_at: None,
10174            reviews: Vec::new(),
10175            e2e: Vec::new(),
10176            fix: None,
10177            blocking: 0,
10178            answered: 0,
10179            expected: 0,
10180            clean: true,
10181            verify_retried: false,
10182            e2e_deferred: false,
10183            e2e_defer_reason: None,
10184            progressed: false,
10185            vote_split: false,
10186            reconsideration: Vec::new(),
10187            verdict: None,
10188        }];
10189
10190        let mut runner = Runner {
10191            state,
10192            roles: ResolvedRoles {
10193                implementers: Vec::new(),
10194                judges: Vec::new(),
10195                reviewers: Vec::new(),
10196                fixer: None,
10197                conductor: conductor(),
10198                implementer_roster: Vec::new(),
10199                judge_roster: Vec::new(),
10200                reviewer_roster: Vec::new(),
10201            },
10202            sem: Arc::new(Semaphore::new(1)),
10203            pause: Pause::new(),
10204            interrupt: Pause::new(),
10205        };
10206
10207        runner.gate().await.expect("gate");
10208        assert!(
10209            runner.state.gate_ran,
10210            "zero configured commands is still a real attempt, not an unrun gate"
10211        );
10212        assert!(runner.state.gate.is_empty());
10213        assert_eq!(runner.state.gate_status(), GateStatus::PassedWithNoCommands);
10214        assert_ne!(
10215            runner.state.status,
10216            RunStatus::Blocked,
10217            "a gate with nothing to check must not read as failed"
10218        );
10219
10220        runner.merge().await.expect("merge");
10221        assert_eq!(
10222            runner.state.status,
10223            RunStatus::Ready,
10224            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
10225        );
10226    }
10227
10228    /// `Config::cache_dir` is derived from `verify.e2e` as well as
10229    /// `verify.gate` (so the e2e leg and the final gate never build against
10230    /// different directories). With zero `verify.gate` commands but a
10231    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
10232    /// that lease before discovering it had nothing to run - so a repo with
10233    /// no gate commands could come back `resource_blocked` (and therefore
10234    /// still `gate_ran == false`) on nothing but an unrelated run holding the
10235    /// cache, exactly the contention this run's own zero commands could
10236    /// never have touched. `gate` must recognise there is nothing to check
10237    /// before it ever asks for the lease.
10238    #[tokio::test]
10239    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
10240        crate::run::pin_test_home();
10241        let home = crate::run::home();
10242
10243        let tmp = tempfile::tempdir().expect("tempdir");
10244        let repo = tmp.path().join("repo");
10245        std::fs::create_dir_all(&repo).unwrap();
10246        init_repo(&repo);
10247        // Unique to this test, so holding its lease cannot collide with
10248        // another test sharing the same process-wide `home`.
10249        let cache_dir = tmp.path().join("target");
10250
10251        let mut config = Config::default();
10252        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
10253        // `verify.gate` stays empty (the default). Bounded so a regression
10254        // that does start waiting fails the test in seconds, not hangs it.
10255        config.graph.timeout_verify = Some(2);
10256
10257        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10258        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10259            .expect("no io error acquiring directly")
10260        {
10261            crate::cache::AcquireOutcome::Acquired(g) => g,
10262            crate::cache::AcquireOutcome::Busy(b) => {
10263                panic!("expected the direct acquire to win the lease first: {b:?}")
10264            }
10265        };
10266
10267        let mut state = RunState::new(
10268            repo.clone(),
10269            "main".to_owned(),
10270            "deadbeef".to_owned(),
10271            "task".to_owned(),
10272            config,
10273        );
10274        state.candidates = vec![Candidate {
10275            index: 0,
10276            label: 'A',
10277            agent: "alpha".to_owned(),
10278            branch: "does-not-exist".to_owned(),
10279            worktree: repo.clone(),
10280            summary: String::new(),
10281            stat: String::new(),
10282            files: 0,
10283            commits: 0,
10284            empty: false,
10285            failed: None,
10286            verified_noop: None,
10287            duration_ms: 0,
10288            folded: false,
10289        }];
10290        state.tally = Some(Tally {
10291            first_choice: BTreeMap::from([('A', 1)]),
10292            borda: BTreeMap::new(),
10293            winner: 'A',
10294            rankings: 1,
10295            unanimous_initial: true,
10296            deliberated: false,
10297            changed_votes: 0,
10298            unanimous_final: true,
10299            tie_break: None,
10300            judges: 0,
10301            present: 0,
10302            quorum: 0,
10303            met_quorum: true,
10304            uncontested: Some("only candidate A produced a change".to_owned()),
10305        });
10306        state.reviews = vec![ReviewRound {
10307            round: 1,
10308            head: "deadbeef".to_owned(),
10309            verified_head: None,
10310            verified_at: None,
10311            reviews: Vec::new(),
10312            e2e: Vec::new(),
10313            fix: None,
10314            blocking: 0,
10315            answered: 0,
10316            expected: 0,
10317            clean: true,
10318            verify_retried: false,
10319            e2e_deferred: false,
10320            e2e_defer_reason: None,
10321            progressed: false,
10322            vote_split: false,
10323            reconsideration: Vec::new(),
10324            verdict: None,
10325        }];
10326
10327        let mut runner = Runner {
10328            state,
10329            roles: ResolvedRoles {
10330                implementers: Vec::new(),
10331                judges: Vec::new(),
10332                reviewers: Vec::new(),
10333                fixer: None,
10334                conductor: conductor(),
10335                implementer_roster: Vec::new(),
10336                judge_roster: Vec::new(),
10337                reviewer_roster: Vec::new(),
10338            },
10339            sem: Arc::new(Semaphore::new(1)),
10340            pause: Pause::new(),
10341            interrupt: Pause::new(),
10342        };
10343
10344        let started = std::time::Instant::now();
10345        runner.gate().await.expect("gate");
10346        assert!(
10347            started.elapsed() < Duration::from_secs(1),
10348            "a gate with nothing to run must never wait on a lease it never needed"
10349        );
10350        assert!(
10351            runner.state.gate_ran,
10352            "zero commands is still a real, immediate attempt"
10353        );
10354        assert!(runner.state.gate.is_empty());
10355        assert_ne!(
10356            runner.state.status,
10357            RunStatus::Blocked,
10358            "must not read as resource-blocked on a lease it never asked for"
10359        );
10360    }
10361
10362    /// The addendum's second gap: a `verify.gate` command running for real
10363    /// wall-clock time had nothing at all to show for it in `active` before
10364    /// `run_commands` learned to record it — a run could sit in `Gating` for
10365    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
10366    /// what was actually happening. Proven with a genuinely still-running
10367    /// command, not just a before/after check on the final state: a poller
10368    /// task reads the same `run.json` `gate()` is writing, the same way the
10369    /// phone or `magi show` would, while the shell command is still blocked
10370    /// on its own release marker.
10371    #[tokio::test]
10372    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
10373        crate::run::pin_test_home();
10374
10375        let tmp = tempfile::tempdir().expect("tempdir");
10376        let repo = tmp.path().join("repo");
10377        std::fs::create_dir_all(&repo).unwrap();
10378        init_repo(&repo);
10379
10380        let mut config = Config::default();
10381        config.verify.gate = vec![
10382            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
10383             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done"
10384                .to_owned(),
10385        ];
10386
10387        let mut state = RunState::new(
10388            repo.clone(),
10389            "main".to_owned(),
10390            "deadbeef".to_owned(),
10391            "task".to_owned(),
10392            config,
10393        );
10394        let run_id = state.id.clone();
10395        state.candidates = vec![Candidate {
10396            index: 0,
10397            label: 'A',
10398            agent: "alpha".to_owned(),
10399            branch: "does-not-exist".to_owned(),
10400            worktree: repo.clone(),
10401            summary: String::new(),
10402            stat: String::new(),
10403            files: 0,
10404            commits: 0,
10405            empty: false,
10406            failed: None,
10407            verified_noop: None,
10408            duration_ms: 0,
10409            folded: false,
10410        }];
10411        state.tally = Some(Tally {
10412            first_choice: BTreeMap::from([('A', 1)]),
10413            borda: BTreeMap::new(),
10414            winner: 'A',
10415            rankings: 1,
10416            unanimous_initial: true,
10417            deliberated: false,
10418            changed_votes: 0,
10419            unanimous_final: true,
10420            tie_break: None,
10421            judges: 0,
10422            present: 0,
10423            quorum: 0,
10424            met_quorum: true,
10425            uncontested: Some("only candidate A produced a change".to_owned()),
10426        });
10427        state.reviews = vec![ReviewRound {
10428            round: 1,
10429            head: "deadbeef".to_owned(),
10430            verified_head: None,
10431            verified_at: None,
10432            reviews: Vec::new(),
10433            e2e: Vec::new(),
10434            fix: None,
10435            blocking: 0,
10436            answered: 0,
10437            expected: 0,
10438            clean: true,
10439            verify_retried: false,
10440            e2e_deferred: false,
10441            e2e_defer_reason: None,
10442            progressed: false,
10443            vote_split: false,
10444            reconsideration: Vec::new(),
10445            verdict: None,
10446        }];
10447
10448        let mut runner = Runner {
10449            state,
10450            roles: ResolvedRoles {
10451                implementers: Vec::new(),
10452                judges: Vec::new(),
10453                reviewers: Vec::new(),
10454                fixer: None,
10455                conductor: conductor(),
10456                implementer_roster: Vec::new(),
10457                judge_roster: Vec::new(),
10458                reviewer_roster: Vec::new(),
10459            },
10460            sem: Arc::new(Semaphore::new(1)),
10461            pause: Pause::new(),
10462            interrupt: Pause::new(),
10463        };
10464
10465        let started_marker = repo.join("started.marker");
10466        let release_marker = repo.join("release.marker");
10467        let poller = tokio::spawn(async move {
10468            // Bounded so a regression that never records the task entry
10469            // fails this test in seconds instead of hanging the suite —
10470            // the same shape `a_park_requested_while_a_seat_is_mid_call_
10471            // does_not_cut_it_short` uses for the same reason.
10472            for _ in 0..100 {
10473                if started_marker.exists()
10474                    && let Ok(s) = crate::run::RunState::load(&run_id)
10475                    && let Some(a) = s.active.get("gate")
10476                {
10477                    std::fs::write(&release_marker, b"go").expect("release marker");
10478                    return Some(a.clone());
10479                }
10480                tokio::time::sleep(Duration::from_millis(50)).await;
10481            }
10482            None
10483        });
10484
10485        runner.gate().await.expect("gate");
10486        let captured = poller.await.expect("poller task");
10487        let captured = captured.expect(
10488            "the poller never saw a `gate` task entry in run.json while the command was \
10489             still blocked on its own release marker",
10490        );
10491
10492        assert_eq!(captured.task.as_deref(), Some("gate"));
10493        assert_eq!(captured.node, "gate");
10494        assert_eq!(captured.index, Some(1));
10495        assert_eq!(captured.total, Some(1));
10496        assert!(
10497            captured
10498                .command
10499                .as_deref()
10500                .is_some_and(|c| c.contains("started.marker")),
10501            "{captured:?}"
10502        );
10503
10504        assert!(
10505            runner.state.active.is_empty(),
10506            "the entry must be cleared once the command actually finished: {:?}",
10507            runner.state.active
10508        );
10509        assert!(runner.state.gate_ran);
10510        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
10511    }
10512
10513    /// The hand-off over a blocking finding a reviewer rejected on leaves a
10514    /// record for `land`; one with only a Minor, or no reject, leaves none.
10515    #[tokio::test]
10516    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
10517        use crate::verdict::{Finding, ReviewVote, Severity};
10518        crate::run::pin_test_home();
10519        let tmp = tempfile::tempdir().expect("tempdir");
10520        let repo = tmp.path().join("repo");
10521        std::fs::create_dir_all(&repo).unwrap();
10522        init_repo(&repo);
10523
10524        for (severity, vote, expect) in [
10525            (Severity::Major, ReviewVote::Reject, true),
10526            (Severity::Minor, ReviewVote::Reject, false),
10527            (Severity::Major, ReviewVote::Approve, false),
10528        ] {
10529            let mut round = review_round(false, 1, 1, 1, false, true);
10530            round.reviews = vec![ReviewRecord {
10531                reviewer: 1,
10532                agent: "alpha".to_owned(),
10533                summary: String::new(),
10534                findings: vec![Finding {
10535                    id: "R1-1-1".to_owned(),
10536                    severity,
10537                    file: None,
10538                    line: None,
10539                    title: "t".to_owned(),
10540                    detail: String::new(),
10541                }],
10542                vote: Some(vote),
10543                failed: None,
10544                duration_ms: 0,
10545                attempts: 0,
10546            }];
10547            let mut state = RunState::new(
10548                repo.clone(),
10549                "main".to_owned(),
10550                "deadbeef".to_owned(),
10551                "task".to_owned(),
10552                Config::default(),
10553            );
10554            state.reviews = vec![round];
10555            let mut runner = Runner {
10556                state,
10557                roles: ResolvedRoles {
10558                    implementers: Vec::new(),
10559                    judges: Vec::new(),
10560                    reviewers: Vec::new(),
10561                    fixer: None,
10562                    conductor: conductor(),
10563                    implementer_roster: Vec::new(),
10564                    judge_roster: Vec::new(),
10565                    reviewer_roster: Vec::new(),
10566                },
10567                sem: Arc::new(Semaphore::new(1)),
10568                pause: Pause::new(),
10569                interrupt: Pause::new(),
10570            };
10571            let shell = runner.state.config.shell();
10572            runner
10573                .stop_reviewing("round budget spent", &shell, &repo)
10574                .await
10575                .expect("stop_reviewing");
10576            assert_eq!(runner.state.status, RunStatus::Gating);
10577            assert_eq!(
10578                runner.state.contested_handoff.is_some(),
10579                expect,
10580                "{severity:?} + {vote:?}"
10581            );
10582        }
10583    }
10584
10585    /// The shape the incident this whole fix responds to actually had: the
10586    /// round budget spent, the last round's own e2e blocked on the shared
10587    /// build cache (held here by a live pid — this test process — exactly
10588    /// `cache`'s own unit tests' pattern for "another owner, still alive"
10589    /// without forking a process). `stop_reviewing` must retry it — not
10590    /// silently leave the round looking untouched (the catch-up-only half of
10591    /// the bug), and not read the contention as a red `e2e` and block the
10592    /// run on it (the other half). Called directly, the same way
10593    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
10594    /// above exercises `gate`, so this never needs a real cargo build to
10595    /// reach: the lease is never released, so `with_cache_lease` never gets
10596    /// past acquiring it into anything that would need a real workspace.
10597    #[tokio::test]
10598    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
10599        crate::run::pin_test_home();
10600        let home = crate::run::home();
10601
10602        let tmp = tempfile::tempdir().expect("tempdir");
10603        let repo = tmp.path().join("repo");
10604        std::fs::create_dir_all(&repo).unwrap();
10605        init_repo(&repo);
10606        let head = crate::git::rev_parse(&repo, "HEAD")
10607            .await
10608            .expect("rev-parse");
10609        // Unique to this test, so holding its lease cannot collide with
10610        // another test sharing the same process-wide `home`.
10611        let cache_dir = tmp.path().join("target");
10612
10613        let mut config = Config::default();
10614        config.verify.e2e = vec![format!(
10615            "CARGO_TARGET_DIR='{}' test -f README.md",
10616            cache_dir.display()
10617        )];
10618        config.graph.review_rounds = 1;
10619        // Bounded so a regression that does start waiting fails the test in
10620        // seconds, not hangs it.
10621        config.graph.timeout_verify = Some(2);
10622
10623        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10624        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10625            .expect("no io error acquiring directly")
10626        {
10627            crate::cache::AcquireOutcome::Acquired(g) => g,
10628            crate::cache::AcquireOutcome::Busy(b) => {
10629                panic!("expected the direct acquire to win the lease first: {b:?}")
10630            }
10631        };
10632
10633        let mut state = RunState::new(
10634            repo.clone(),
10635            "main".to_owned(),
10636            head.clone(),
10637            "task".to_owned(),
10638            config,
10639        );
10640        state.candidates = vec![Candidate {
10641            index: 0,
10642            label: 'A',
10643            agent: "alpha".to_owned(),
10644            branch: "does-not-exist".to_owned(),
10645            worktree: repo.clone(),
10646            summary: String::new(),
10647            stat: String::new(),
10648            files: 0,
10649            commits: 0,
10650            empty: false,
10651            failed: None,
10652            verified_noop: None,
10653            duration_ms: 0,
10654            folded: false,
10655        }];
10656        state.tally = Some(Tally {
10657            first_choice: BTreeMap::from([('A', 1)]),
10658            borda: BTreeMap::new(),
10659            winner: 'A',
10660            rankings: 1,
10661            unanimous_initial: true,
10662            deliberated: false,
10663            changed_votes: 0,
10664            unanimous_final: true,
10665            tie_break: None,
10666            judges: 0,
10667            present: 0,
10668            quorum: 0,
10669            met_quorum: true,
10670            uncontested: Some("only candidate A produced a change".to_owned()),
10671        });
10672        // The round budget's last round, deferred: `needs_catchup_run`'s
10673        // other trigger. `stop_reviewing`'s retry machinery must treat this
10674        // exactly like a resource-blocked attempt once it actually runs.
10675        state.reviews = vec![ReviewRound {
10676            round: 1,
10677            head: head.clone(),
10678            verified_head: None,
10679            verified_at: None,
10680            reviews: Vec::new(),
10681            e2e: Vec::new(),
10682            fix: None,
10683            blocking: 1,
10684            answered: 1,
10685            expected: 1,
10686            clean: false,
10687            verify_retried: false,
10688            e2e_deferred: true,
10689            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
10690            progressed: false,
10691            vote_split: false,
10692            reconsideration: Vec::new(),
10693            verdict: None,
10694        }];
10695
10696        let mut runner = Runner {
10697            state,
10698            roles: ResolvedRoles {
10699                implementers: Vec::new(),
10700                judges: Vec::new(),
10701                reviewers: Vec::new(),
10702                fixer: None,
10703                conductor: conductor(),
10704                implementer_roster: Vec::new(),
10705                judge_roster: Vec::new(),
10706                reviewer_roster: Vec::new(),
10707            },
10708            sem: Arc::new(Semaphore::new(1)),
10709            pause: Pause::new(),
10710            interrupt: Pause::new(),
10711        };
10712
10713        let shell = runner.state.config.shell();
10714        runner
10715            .stop_reviewing("round budget spent", &shell, &repo)
10716            .await
10717            .expect("stop_reviewing");
10718
10719        let last = runner.state.reviews.last().expect("round record");
10720        assert_eq!(
10721            last.e2e_status(),
10722            E2eStatus::ResourceBlocked,
10723            "the shared cache is still held; the attempt must read as blocked, not deferred or \
10724             failed: {last:?}"
10725        );
10726        assert_eq!(
10727            last.verified_head.as_deref(),
10728            Some(head.as_str()),
10729            "which commit this attempt targeted is known even though nothing finished checking \
10730             it"
10731        );
10732        let first_attempt_at = last
10733            .verified_at
10734            .expect("when this attempt ran is known too");
10735        assert_ne!(
10736            runner.state.status,
10737            RunStatus::Blocked,
10738            "contention is evidence about the machine, not the patch — it must not settle the \
10739             run as blocked: {:?}",
10740            runner.state.status
10741        );
10742        assert!(
10743            !runner
10744                .state
10745                .events
10746                .iter()
10747                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
10748            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
10749            runner.state.events
10750        );
10751
10752        // The cache is still held: a later reentry must retry the same
10753        // round's verification again — not leave it looking exactly as
10754        // untouched as the first blocked attempt, which is indistinguishable
10755        // from never having tried again at all.
10756        runner
10757            .stop_reviewing("round budget spent", &shell, &repo)
10758            .await
10759            .expect("stop_reviewing retry");
10760        assert_eq!(
10761            runner.state.reviews.len(),
10762            1,
10763            "no new round was started: {:?}",
10764            runner.state.reviews
10765        );
10766        let last = runner.state.reviews.last().expect("round record");
10767        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
10768        assert!(
10769            last.verified_at.expect("still known") > first_attempt_at,
10770            "a second reentry must be a fresh attempt, not a stale copy of the first"
10771        );
10772        assert_ne!(runner.state.status, RunStatus::Blocked);
10773
10774        held.release();
10775    }
10776
10777    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
10778    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
10779    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
10780    /// own top-of-function fast path (`review_conclusion`) correctly reads
10781    /// this shape as `None` rather than guessing `Blocked`, and the loop's
10782    /// own `for` range is empty once the round budget is spent, so
10783    /// `review_loop` must retry the check itself rather than silently doing
10784    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
10785    /// above exercises directly, but through `review_loop`'s own entry point
10786    /// this time, proving the wiring between the two rather than just the
10787    /// retry logic in isolation.
10788    #[tokio::test]
10789    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
10790        crate::run::pin_test_home();
10791        let home = crate::run::home();
10792
10793        let tmp = tempfile::tempdir().expect("tempdir");
10794        let repo = tmp.path().join("repo");
10795        std::fs::create_dir_all(&repo).unwrap();
10796        init_repo(&repo);
10797        let head = crate::git::rev_parse(&repo, "HEAD")
10798            .await
10799            .expect("rev-parse");
10800        let cache_dir = tmp.path().join("target");
10801
10802        let mut config = Config::default();
10803        config.verify.e2e = vec![format!(
10804            "CARGO_TARGET_DIR='{}' test -f README.md",
10805            cache_dir.display()
10806        )];
10807        config.graph.review_rounds = 1;
10808        config.graph.timeout_verify = Some(2);
10809
10810        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10811        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10812            .expect("no io error acquiring directly")
10813        {
10814            crate::cache::AcquireOutcome::Acquired(g) => g,
10815            crate::cache::AcquireOutcome::Busy(b) => {
10816                panic!("expected the direct acquire to win the lease first: {b:?}")
10817            }
10818        };
10819
10820        let mut state = RunState::new(
10821            repo.clone(),
10822            "main".to_owned(),
10823            head.clone(),
10824            "task".to_owned(),
10825            config,
10826        );
10827        state.candidates = vec![Candidate {
10828            index: 0,
10829            label: 'A',
10830            agent: "alpha".to_owned(),
10831            branch: "does-not-exist".to_owned(),
10832            worktree: repo.clone(),
10833            summary: String::new(),
10834            stat: String::new(),
10835            files: 0,
10836            commits: 0,
10837            empty: false,
10838            failed: None,
10839            verified_noop: None,
10840            duration_ms: 0,
10841            folded: false,
10842        }];
10843        state.tally = Some(Tally {
10844            first_choice: BTreeMap::from([('A', 1)]),
10845            borda: BTreeMap::new(),
10846            winner: 'A',
10847            rankings: 1,
10848            unanimous_initial: true,
10849            deliberated: false,
10850            changed_votes: 0,
10851            unanimous_final: true,
10852            tie_break: None,
10853            judges: 0,
10854            present: 0,
10855            quorum: 0,
10856            met_quorum: true,
10857            uncontested: Some("only candidate A produced a change".to_owned()),
10858        });
10859        // The exact shape a prior process's `stop_reviewing` would have left
10860        // on disk: the round budget's last round, a real attempt already
10861        // made and already resource-blocked.
10862        state.reviews = vec![ReviewRound {
10863            round: 1,
10864            head: head.clone(),
10865            verified_head: Some(head.clone()),
10866            verified_at: Some(jiff::Timestamp::now()),
10867            reviews: Vec::new(),
10868            e2e: vec![CommandOutcome {
10869                command: format!(
10870                    "CARGO_TARGET_DIR='{}' test -f README.md",
10871                    cache_dir.display()
10872                ),
10873                code: None,
10874                output_tail: "waiting for the shared build cache".to_owned(),
10875                duration_ms: 0,
10876                resource_blocked: true,
10877            }],
10878            fix: None,
10879            blocking: 1,
10880            answered: 1,
10881            expected: 1,
10882            clean: false,
10883            verify_retried: false,
10884            e2e_deferred: false,
10885            e2e_defer_reason: None,
10886            progressed: false,
10887            vote_split: false,
10888            reconsideration: Vec::new(),
10889            verdict: None,
10890        }];
10891
10892        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
10893        let mut runner = Runner {
10894            state,
10895            roles: ResolvedRoles {
10896                implementers: Vec::new(),
10897                judges: Vec::new(),
10898                reviewers: Vec::new(),
10899                fixer: None,
10900                conductor: conductor(),
10901                implementer_roster: Vec::new(),
10902                judge_roster: Vec::new(),
10903                reviewer_roster: Vec::new(),
10904            },
10905            sem: Arc::new(Semaphore::new(1)),
10906            pause: Pause::new(),
10907            interrupt: Pause::new(),
10908        };
10909
10910        // The lease is still held throughout, so this reentry's own retry is
10911        // also contended — proving `review_loop` actually tried again (not
10912        // that it happened to succeed) is what the timestamp comparison
10913        // below is for.
10914        runner.review_loop().await.expect("review_loop");
10915
10916        assert_eq!(
10917            runner.state.reviews.len(),
10918            1,
10919            "no new round was started on top of the unresolved one: {:?}",
10920            runner.state.reviews
10921        );
10922        let last = &runner.state.reviews[0];
10923        assert_eq!(
10924            last.e2e_status(),
10925            E2eStatus::ResourceBlocked,
10926            "still contended: {last:?}"
10927        );
10928        assert!(
10929            last.verified_at.expect("still known") > first_attempt_at,
10930            "review_loop must have actually retried the check, not left it exactly as found"
10931        );
10932        assert_ne!(
10933            runner.state.status,
10934            RunStatus::Blocked,
10935            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
10936            runner.state.status
10937        );
10938
10939        held.release();
10940    }
10941
10942    #[tokio::test]
10943    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
10944        crate::run::pin_test_home();
10945        let tmp = tempfile::tempdir().expect("tempdir");
10946        let repo = tmp.path().join("repo");
10947        std::fs::create_dir_all(&repo).unwrap();
10948        init_repo(&repo);
10949
10950        let mut config = Config::default();
10951        config.merge.mode = MergeMode::Pr;
10952        config.graph.land = true;
10953        config.graph.land_approval = false;
10954
10955        let mut state = RunState::new(
10956            repo.clone(),
10957            "main".to_owned(),
10958            "deadbeef".to_owned(),
10959            "task".to_owned(),
10960            config,
10961        );
10962        state.candidates = vec![Candidate {
10963            index: 0,
10964            label: 'A',
10965            agent: "alpha".to_owned(),
10966            branch: "does-not-exist".to_owned(),
10967            worktree: repo.clone(),
10968            summary: String::new(),
10969            stat: String::new(),
10970            files: 0,
10971            commits: 0,
10972            empty: false,
10973            failed: None,
10974            verified_noop: None,
10975            duration_ms: 0,
10976            folded: false,
10977        }];
10978        state.tally = Some(Tally {
10979            first_choice: BTreeMap::from([('A', 1)]),
10980            borda: BTreeMap::new(),
10981            winner: 'A',
10982            rankings: 1,
10983            unanimous_initial: true,
10984            deliberated: false,
10985            changed_votes: 0,
10986            unanimous_final: true,
10987            tie_break: None,
10988            judges: 0,
10989            present: 0,
10990            quorum: 0,
10991            met_quorum: true,
10992            uncontested: Some("only candidate A produced a change".to_owned()),
10993        });
10994        state.reviews = vec![ReviewRound {
10995            round: 1,
10996            head: "deadbeef".to_owned(),
10997            verified_head: None,
10998            verified_at: None,
10999            reviews: Vec::new(),
11000            e2e: Vec::new(),
11001            fix: None,
11002            blocking: 0,
11003            answered: 0,
11004            expected: 0,
11005            clean: true,
11006            verify_retried: false,
11007            e2e_deferred: false,
11008            e2e_defer_reason: None,
11009            progressed: false,
11010            vote_split: false,
11011            reconsideration: Vec::new(),
11012            verdict: None,
11013        }];
11014        state.gate = vec![CommandOutcome {
11015            command: "test".to_owned(),
11016            code: Some(0),
11017            output_tail: String::new(),
11018            duration_ms: 0,
11019            resource_blocked: false,
11020        }];
11021        state.gate_ran = true;
11022        // A first pass through `merge` already pushed and opened this pull
11023        // request; `status` is `Landing` because a previous call into `land`
11024        // parked or was interrupted before it reached a terminal outcome.
11025        state.status = RunStatus::Landing;
11026        state.merge = Some(MergeOutcome {
11027            mode: MergeMode::Pr,
11028            ok: true,
11029            detail: "https://example.invalid/x/y/pull/1".to_owned(),
11030            empty: false,
11031        });
11032
11033        // The Landing-resume shortcut calls `run_land` directly rather than
11034        // through `merge`, which is exactly the call site that used to skip
11035        // `settle_questions` - see the fixture below.
11036        ask_test_home();
11037        let store = ask::Questions::open();
11038        let q = ask_open_question(&store, &state.id);
11039
11040        let mut runner = Runner {
11041            state,
11042            roles: ResolvedRoles {
11043                implementers: Vec::new(),
11044                judges: Vec::new(),
11045                reviewers: Vec::new(),
11046                fixer: None,
11047                conductor: conductor(),
11048                implementer_roster: Vec::new(),
11049                judge_roster: Vec::new(),
11050                reviewer_roster: Vec::new(),
11051            },
11052            sem: Arc::new(Semaphore::new(1)),
11053            pause: Pause::new(),
11054            interrupt: Pause::new(),
11055        };
11056
11057        // `execute`, not `merge` directly: the Landing-resume shortcut lives
11058        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
11059        // exactly because `review_loop` would otherwise clobber the marker
11060        // first.
11061        runner.execute().await.expect("execute");
11062
11063        assert_eq!(
11064            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
11065            Some("https://example.invalid/x/y/pull/1"),
11066            "reentry must not push again or open a second pull request over the \
11067             one `land` is already watching"
11068        );
11069        assert_ne!(
11070            runner.state.status,
11071            RunStatus::Landing,
11072            "land could not actually reach the fake pull request, so it must \
11073             have given up rather than left the run silently parked forever"
11074        );
11075        // `land` could not reach the fake pull request, so it gave up into
11076        // `Blocked` - still resumable, so the question must not have been
11077        // swept just because this branch now also calls `settle_questions`.
11078        assert_eq!(runner.state.status, RunStatus::Blocked);
11079        assert!(
11080            store.get(&q.id).unwrap().status.open(),
11081            "Blocked is still alive; settle_questions must have been a no-op here"
11082        );
11083    }
11084
11085    fn state_with_round(round: ReviewRound) -> RunState {
11086        let mut s = RunState::new(
11087            PathBuf::from("/repo"),
11088            "main".to_owned(),
11089            "abc1234".to_owned(),
11090            "add retries".to_owned(),
11091            Config::default(),
11092        );
11093        s.reviews = vec![round];
11094        s
11095    }
11096
11097    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
11098        crate::verdict::Finding {
11099            id: id.to_owned(),
11100            severity,
11101            file: None,
11102            line: None,
11103            title: title.to_owned(),
11104            detail: String::new(),
11105        }
11106    }
11107
11108    #[test]
11109    fn pr_body_names_open_findings_and_declined_ones() {
11110        let round = ReviewRound {
11111            round: 2,
11112            head: "deadbee".to_owned(),
11113            verified_head: None,
11114            verified_at: None,
11115            reviews: vec![ReviewRecord {
11116                attempts: 0,
11117                reviewer: 1,
11118                agent: "alpha".to_owned(),
11119                summary: String::new(),
11120                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
11121                vote: None,
11122                failed: None,
11123                duration_ms: 0,
11124            }],
11125            e2e: vec![CommandOutcome {
11126                command: "cargo test".to_owned(),
11127                code: Some(0),
11128                output_tail: String::new(),
11129                duration_ms: 0,
11130                resource_blocked: false,
11131            }],
11132            verify_retried: false,
11133            e2e_deferred: false,
11134            e2e_defer_reason: None,
11135            fix: Some(FixRecord {
11136                agent: "alpha".to_owned(),
11137                addressed: Vec::new(),
11138                rejected: vec![crate::verdict::Rejection {
11139                    id: "R1-1-1".to_owned(),
11140                    why: "not reachable from any caller".to_owned(),
11141                }],
11142                notes: String::new(),
11143                committed: true,
11144                failed: None,
11145                duration_ms: 0,
11146                continuation: None,
11147            }),
11148            blocking: 0,
11149            answered: 1,
11150            expected: 1,
11151            clean: false,
11152            progressed: true,
11153            vote_split: false,
11154            reconsideration: Vec::new(),
11155            verdict: None,
11156        };
11157        let state = state_with_round(round);
11158        let body = pr_message(&state, 'A').body;
11159
11160        assert!(body.contains("add retries"), "the task must still be there");
11161        assert!(body.contains("R2-1-1"), "{body}");
11162        assert!(body.contains("unused import"), "{body}");
11163        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
11164        assert!(
11165            body.contains("not reachable from any caller"),
11166            "the reason it was declined: {body}"
11167        );
11168    }
11169
11170    #[test]
11171    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
11172        let round = ReviewRound {
11173            round: 1,
11174            head: "deadbee".to_owned(),
11175            verified_head: None,
11176            verified_at: None,
11177            reviews: vec![ReviewRecord {
11178                attempts: 0,
11179                reviewer: 1,
11180                agent: "alpha".to_owned(),
11181                summary: String::new(),
11182                findings: Vec::new(),
11183                vote: None,
11184                failed: None,
11185                duration_ms: 0,
11186            }],
11187            e2e: Vec::new(),
11188            verify_retried: false,
11189            e2e_deferred: false,
11190            e2e_defer_reason: None,
11191            fix: None,
11192            blocking: 0,
11193            answered: 1,
11194            expected: 1,
11195            clean: true,
11196            progressed: false,
11197            vote_split: false,
11198            reconsideration: Vec::new(),
11199            verdict: None,
11200        };
11201        let state = state_with_round(round);
11202        let body = pr_message(&state, 'A').body;
11203        assert!(!body.contains("Open review findings"), "{body}");
11204        assert!(!body.contains("Declined"), "{body}");
11205    }
11206
11207    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
11208        let mut state = RunState::new(
11209            PathBuf::from("/repo"),
11210            "main".to_owned(),
11211            "abc1234".to_owned(),
11212            instruction.to_owned(),
11213            Config::default(),
11214        );
11215        state.candidates.push(Candidate {
11216            index: 0,
11217            label: 'A',
11218            agent: "alpha".to_owned(),
11219            branch: "magi/x/A".to_owned(),
11220            worktree: PathBuf::from("/wt"),
11221            summary: summary.to_owned(),
11222            stat: String::new(),
11223            files: 1,
11224            commits: 1,
11225            empty: false,
11226            failed: None,
11227            verified_noop: None,
11228            folded: false,
11229            duration_ms: 0,
11230        });
11231        state
11232    }
11233
11234    fn review_state(subjects: &[&str]) -> RunState {
11235        let mut state = state_with_summary(
11236            "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",
11237            "",
11238        );
11239        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
11240        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
11241        state
11242    }
11243
11244    /// A branch rebased onto a main that moved past the recorded
11245    /// `base_commit` is titled from its own first commit, never main's.
11246    #[tokio::test]
11247    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
11248        ask_test_home();
11249        let tmp = tempfile::tempdir().unwrap();
11250        let repo = tmp.path().join("repo");
11251        std::fs::create_dir_all(&repo).unwrap();
11252        init_repo(&repo);
11253        let origin = tmp.path().join("origin.git");
11254        let g = |dir: &Path, args: &[&str]| {
11255            let out = std::process::Command::new("git")
11256                .args(args)
11257                .current_dir(dir)
11258                .quiet()
11259                .output()
11260                .expect("spawn git");
11261            assert!(
11262                out.status.success(),
11263                "git {args:?}: {}",
11264                String::from_utf8_lossy(&out.stderr)
11265            );
11266        };
11267        g(
11268            tmp.path(),
11269            &[
11270                "clone",
11271                "--bare",
11272                "-q",
11273                repo.to_str().unwrap(),
11274                origin.to_str().unwrap(),
11275            ],
11276        );
11277        g(
11278            &repo,
11279            &["remote", "add", "origin", origin.to_str().unwrap()],
11280        );
11281        let c1 = git::rev_parse(&repo, "main").await.unwrap();
11282
11283        // Main moves on; the branch is built on top of the new main.
11284        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
11285        g(&repo, &["add", "-A"]);
11286        g(
11287            &repo,
11288            &["commit", "-q", "-m", "chore(deps): update a crate"],
11289        );
11290        g(&repo, &["push", "-q", "origin", "main"]);
11291        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
11292        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
11293        g(&repo, &["add", "-A"]);
11294        g(
11295            &repo,
11296            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
11297        );
11298        g(&repo, &["checkout", "-q", "main"]);
11299
11300        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
11301        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
11302        // Without a readable tracking ref the recorded base's merge base is used.
11303        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
11304        assert_eq!(fallback, c1);
11305
11306        let mut state = review_state(&[
11307            "chore(deps): update a crate",
11308            "fix(daemon): apply a chosen action",
11309        ]);
11310        state.repo = repo.clone();
11311        state.base_branch = "main".to_owned();
11312        state.base_commit = c1;
11313        refresh_reviewed_commits(&mut state, "feat/own").await;
11314        assert_eq!(
11315            state.reviewed_commits,
11316            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
11317        );
11318        assert_eq!(
11319            review_title(&state).as_deref(),
11320            Some("fix(daemon): apply a chosen action")
11321        );
11322        assert_eq!(
11323            leaked_subjects(&state, "feat/own").await,
11324            Some(vec!["chore(deps): update a crate".to_owned()])
11325        );
11326        // A stale tracking ref is still used when the fetch fails, but the
11327        // leak list is withheld.
11328        state.config.merge.remote = "nowhere".to_owned();
11329        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
11330    }
11331
11332    #[test]
11333    fn pr_message_review_single_commit_uses_its_subject() {
11334        let state = review_state(&["feat(nats): per-role user"]);
11335        let m = pr_message(&state, 'A');
11336        assert_eq!(m.title, "feat(nats): per-role user");
11337        assert!(!m.body.contains("Review the work already"), "{}", m.body);
11338        assert!(m.body.contains("## Commits under review"), "{}", m.body);
11339    }
11340
11341    #[test]
11342    fn pr_message_review_multi_commit_takes_the_oldest() {
11343        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
11344        let m = pr_message(&state, 'A');
11345        assert_eq!(m.title, "feat: the change");
11346        for s in ["feat: the change", "fix: typo", "fix: again"] {
11347            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
11348        }
11349    }
11350
11351    #[test]
11352    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
11353        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
11354            let mut state = review_state(&[first, "fix: later fixup"]);
11355            state.candidates[0].branch = "機能/ログイン".to_owned();
11356            let m = pr_message(&state, 'A');
11357            assert!(
11358                m.title.starts_with("chore: land candidate A of run"),
11359                "{}",
11360                m.title
11361            );
11362        }
11363    }
11364
11365    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
11366        BranchFacts {
11367            commits: commits
11368                .iter()
11369                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
11370                .collect(),
11371            stat: stat.to_owned(),
11372        }
11373    }
11374
11375    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
11376        let mut r = review_round(true, 0, 1, 1, true, true);
11377        r.round = round;
11378        r.fix = notes.map(|n| FixRecord {
11379            agent: "fixer".to_owned(),
11380            addressed: Vec::new(),
11381            rejected: Vec::new(),
11382            notes: n.to_owned(),
11383            committed: true,
11384            failed: None,
11385            duration_ms: 0,
11386            continuation: None,
11387        });
11388        r
11389    }
11390
11391    #[test]
11392    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
11393        let state = review_state(&["ignored"]);
11394        let f = facts(
11395            &[
11396                (
11397                    "fix(login): resolve PATH on macOS",
11398                    "Login shells skip rc files.",
11399                ),
11400                ("fix: address review", ""),
11401            ],
11402            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
11403        );
11404        let m = pr_message_with(&state, 'A', Some(&f));
11405        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
11406        assert!(
11407            m.body
11408                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
11409            "{}",
11410            m.body
11411        );
11412        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
11413        assert!(m.body.contains("## Diff stat"), "{}", m.body);
11414        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
11415        for banned in [
11416            "Review the work already",
11417            "no task statement",
11418            "Original task",
11419        ] {
11420            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
11421        }
11422        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
11423    }
11424
11425    #[test]
11426    fn pr_message_review_truncates_a_huge_first_commit_body() {
11427        let state = review_state(&["ignored"]);
11428        let f = facts(
11429            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
11430            "s",
11431        );
11432        let m = pr_message_with(&state, 'A', Some(&f));
11433        assert!(m.body.len() < 30_000, "{}", m.body.len());
11434        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
11435        assert!(
11436            m.body.contains("- ... 1 more commit(s)"),
11437            "{}",
11438            m.body.len()
11439        );
11440        assert!(m.body.ends_with("magi:candidate-a\n"));
11441    }
11442
11443    #[test]
11444    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
11445        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
11446        assert_eq!(m.title, "feat: x");
11447        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
11448        assert!(!m.body.contains("Diff stat"), "{}", m.body);
11449        assert!(!m.body.contains("no task statement"), "{}", m.body);
11450    }
11451
11452    #[test]
11453    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
11454        let mut state = review_state(&["日本語の件名"]);
11455        state.candidates[0].branch = "fix/macos-login-path".to_owned();
11456        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
11457        state.candidates[0].branch = "機能/ログイン".to_owned();
11458        assert!(
11459            pr_message(&state, 'A')
11460                .title
11461                .starts_with("chore: land candidate A")
11462        );
11463    }
11464
11465    #[test]
11466    fn pr_message_review_fixes_survive_a_clean_final_round() {
11467        let mut state = review_state(&["feat: x"]);
11468        state.reviews = vec![
11469            round_with_notes(1, Some("handled the PATH case")),
11470            round_with_notes(2, None),
11471        ];
11472        let body = pr_message(&state, 'A').body;
11473        assert!(
11474            body.contains("## Review fixes\n\nhandled the PATH case\n"),
11475            "{body}"
11476        );
11477        assert!(!body.contains("### Round"), "{body}");
11478
11479        state.reviews = vec![
11480            round_with_notes(1, Some("first fix")),
11481            round_with_notes(2, Some("")),
11482            round_with_notes(3, Some("second fix")),
11483            round_with_notes(4, None),
11484        ];
11485        let body = pr_message(&state, 'A').body;
11486        assert!(body.contains("### Round 1\n\nfirst fix"), "{body}");
11487        assert!(body.contains("### Round 3\n\nsecond fix"), "{body}");
11488        assert!(!body.contains("### Round 2"), "{body}");
11489    }
11490
11491    #[test]
11492    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
11493        let state = state_with_summary(
11494            "add retries to the client",
11495            "TITLE: feat: retries\n\nDid it.",
11496        );
11497        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
11498        assert_eq!(m.title, "feat: retries");
11499        assert!(
11500            m.body.contains("<summary>Original task</summary>"),
11501            "{}",
11502            m.body
11503        );
11504        assert!(!m.body.contains("Commits under review"), "{}", m.body);
11505        assert!(
11506            m.body
11507                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
11508            "{}",
11509            m.body
11510        );
11511    }
11512
11513    #[test]
11514    fn pr_message_review_bounds_a_long_english_subject() {
11515        let long = format!("feat: {}", "word ".repeat(100));
11516        let m = pr_message(&review_state(&[&long]), 'A');
11517        assert!(m.title.starts_with("feat: word"), "{}", m.title);
11518        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11519    }
11520
11521    #[test]
11522    fn pr_message_implementation_run_is_unchanged_by_review_support() {
11523        let state = state_with_summary("add retries\n\ndetails", "- did some things");
11524        let m = pr_message(&state, 'A');
11525        assert_eq!(m.title, "add retries");
11526        assert!(m.body.contains("<summary>Original task</summary>"));
11527        assert!(!m.body.contains("Commits under review"));
11528        assert_eq!(landing_subject_source(&state), state.instruction);
11529    }
11530
11531    #[test]
11532    fn review_run_squash_subject_is_the_change_not_the_prompt() {
11533        let state = review_state(&["feat: the change", "fix: typo"]);
11534        let source = landing_subject_source(&state);
11535        assert_eq!(land::merge_subject("", &source), "feat: the change");
11536        assert_eq!(
11537            land::merge_subject("magi: candidate A (uncommitted work)", &source),
11538            "feat: the change"
11539        );
11540        // An operator's rename still wins.
11541        assert_eq!(
11542            land::merge_subject("feat: renamed by hand", &source),
11543            "feat: renamed by hand"
11544        );
11545        let blank = review_state(&["日本語"]);
11546        assert!(
11547            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
11548        );
11549    }
11550
11551    #[test]
11552    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
11553        let state = review_state(&["feat: the change"]);
11554        let source = landing_subject_source(&state);
11555        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
11556        assert_eq!(
11557            land::merge_subject(landing_title(&state, old), &source),
11558            "feat: the change"
11559        );
11560        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
11561        let task = state_with_summary("add retries", "");
11562        assert_eq!(landing_title(&task, old), old);
11563    }
11564
11565    #[test]
11566    fn pr_message_describes_the_change_not_the_task() {
11567        let state = state_with_summary(
11568            "今回やってほしいこと: results projector を直す",
11569            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
11570        );
11571        let m = pr_message(&state, 'A');
11572        assert_eq!(m.title, "fix(web): batch the runs list reads");
11573        assert!(
11574            m.body.starts_with("## Summary\n\n- reads run.json once"),
11575            "{}",
11576            m.body
11577        );
11578        assert!(!m.body.contains("TITLE:"), "{}", m.body);
11579        let task_at = m.body.find("今回やってほしいこと").unwrap();
11580        let details_at = m.body.find("<details>").unwrap();
11581        assert!(
11582            details_at < task_at,
11583            "the task lives inside <details>: {}",
11584            m.body
11585        );
11586        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
11587        assert!(m.body.contains("magi:candidate-a"));
11588    }
11589
11590    #[test]
11591    fn pr_message_falls_back_to_the_task_without_a_title_line() {
11592        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
11593        let m = pr_message(&state, 'A');
11594        assert_eq!(m.title, "add retries");
11595        assert!(
11596            m.body.contains("## Summary\n\n- did some things"),
11597            "{}",
11598            m.body
11599        );
11600
11601        let none = RunState::new(
11602            PathBuf::from("/repo"),
11603            "main".to_owned(),
11604            "abc1234".to_owned(),
11605            "add retries".to_owned(),
11606            Config::default(),
11607        );
11608        let m = pr_message(&none, 'A');
11609        assert_eq!(m.title, "add retries");
11610        assert!(!m.body.contains("## Summary"), "{}", m.body);
11611    }
11612
11613    #[test]
11614    fn pr_message_refuses_the_candidate_commit_subject() {
11615        for bad in [
11616            "TITLE: magi: candidate A (uncommitted work)",
11617            "TITLE: chore: stuff (uncommitted work)",
11618            "TITLE:   ",
11619        ] {
11620            let state = state_with_summary("add retries", bad);
11621            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
11622        }
11623    }
11624
11625    #[test]
11626    fn pr_message_bounds_a_very_long_task_and_title() {
11627        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
11628        let state = state_with_summary(&long, "- nothing");
11629        let m = pr_message(&state, 'A');
11630        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11631        assert!(!m.title.contains('\n'));
11632
11633        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
11634        let m = pr_message(&state, 'A');
11635        assert!(m.title.starts_with("feat: "));
11636        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11637        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
11638    }
11639
11640    fn long_title_of(instruction: &str) -> String {
11641        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
11642    }
11643
11644    #[test]
11645    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
11646        let first = "Make the landing path keep a readable title for long tasks";
11647        let line = format!(
11648            "{first}. {}",
11649            "And then keep going with more words ".repeat(20)
11650        );
11651        let t = long_title_of(&line);
11652        assert_eq!(t, first);
11653        assert!(!t.starts_with("chore: land"));
11654    }
11655
11656    #[test]
11657    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
11658        let line = "word ".repeat(200);
11659        let t = long_title_of(&line);
11660        assert!(t.ends_with("word..."), "{t}");
11661        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
11662    }
11663
11664    #[test]
11665    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
11666        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
11667            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
11668        }
11669    }
11670
11671    #[test]
11672    fn pr_message_title_limit_is_exact() {
11673        let at = "a".repeat(PR_TITLE_MAX);
11674        assert_eq!(long_title_of(&at), at);
11675        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
11676        assert!(over.ends_with("..."), "{over}");
11677        assert_eq!(over.chars().count(), PR_TITLE_MAX);
11678    }
11679
11680    #[test]
11681    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
11682        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
11683        let t = long_title_of(&line);
11684        assert!(t.ends_with("..."), "{t}");
11685        assert!(t.is_ascii(), "{t}");
11686    }
11687
11688    #[test]
11689    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
11690        let line = format!(
11691            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
11692            "plus more filler words ".repeat(20)
11693        );
11694        let t = long_title_of(&line);
11695        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
11696    }
11697
11698    #[test]
11699    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
11700        let line = format!("\n\n# {}", "title words ".repeat(40));
11701        let state = state_with_summary(&line, "- nothing");
11702        let m = pr_message(&state, 'A');
11703        assert!(m.title.starts_with("title words"), "{}", m.title);
11704        assert_eq!(
11705            land::merge_subject(&m.title, &landing_subject_source(&state)),
11706            m.title
11707        );
11708        // An operator's rename wins untouched.
11709        assert_eq!(
11710            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
11711            "feat: renamed by hand"
11712        );
11713    }
11714
11715    #[tokio::test]
11716    async fn github_text_rewrite_is_bounded_and_falls_back() {
11717        crate::run::pin_test_home();
11718        for (reply, accepted) in [
11719            (
11720                "TITLE: fix: retries\nAdd retries for failed requests.",
11721                true,
11722            ),
11723            (
11724                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
11725                false,
11726            ),
11727            ("TITLE: fix: retries\nUse token=secret", false),
11728        ] {
11729            let dir = tempfile::tempdir().unwrap();
11730            let mut runner = runner_at(RunStatus::Gating);
11731            runner.state = state_with_summary(
11732                "add retries",
11733                "TITLE: fix: retries\n日本語の説明を書きます。",
11734            );
11735            runner.state.repo = dir.path().to_owned();
11736            runner.state.candidates[0].worktree = dir.path().to_owned();
11737            let mut author = spec("alpha");
11738            author.command = vec![
11739                "sh".into(),
11740                "-c".into(),
11741                "printf '%s' \"$REWRITE_REPLY\"".into(),
11742            ];
11743            author.env.insert("REWRITE_REPLY".into(), reply.into());
11744            runner.state.config.agents = vec![author];
11745            let winner = runner.state.candidates[0].clone();
11746            let message = runner.guarded_pr_message(&winner, None, true).await;
11747            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
11748            assert_eq!(
11749                message.body.contains("Add retries for failed requests."),
11750                accepted
11751            );
11752            assert_eq!(
11753                runner.state.seats["impl-A"].turns, 1,
11754                "only one rewrite invocation"
11755            );
11756            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
11757            if !accepted {
11758                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
11759                assert!(
11760                    message
11761                        .body
11762                        .contains(&format!("magi:run/{}", runner.state.id))
11763                );
11764            }
11765        }
11766    }
11767
11768    #[test]
11769    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
11770        // What magi itself writes stays English under any configured language,
11771        // so a future localisation of these headings fails here. (The agents'
11772        // own text is also checked by the posting gate.)
11773        let mut state = state_with_summary(
11774            "add retries",
11775            "TITLE: fix(web): batch reads\n- reads run.json once",
11776        );
11777        state.config.graph.language = "ja".to_owned();
11778        let m = pr_message(&state, 'A');
11779        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
11780        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
11781
11782        // The task is the operator's own text: it goes in untouched, and the
11783        // fallback title (no summary) may be in its language too.
11784        let task = "今回やってほしいこと: results projector を直す";
11785        let mut state = state_with_summary(task, "- no title line");
11786        state.config.graph.language = "ja".to_owned();
11787        let m = pr_message(&state, 'A');
11788        assert_eq!(
11789            m.title,
11790            format!("chore: land candidate A of run {}", state.id)
11791        );
11792        assert!(
11793            m.body.contains(&format!(
11794                "<summary>Original task</summary>\n\n{task}\n\n</details>"
11795            )),
11796            "{}",
11797            m.body
11798        );
11799    }
11800
11801    #[test]
11802    fn pr_message_scrubs_home_paths_and_addresses() {
11803        let state = state_with_summary(
11804            "fix it in /Users/someone/src/x",
11805            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
11806        );
11807        let m = pr_message(&state, 'A');
11808        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
11809            assert!(!m.body.contains(leak), "{}", m.body);
11810        }
11811        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
11812    }
11813
11814    #[test]
11815    fn pr_message_survives_a_task_that_closes_details() {
11816        let state = state_with_summary("a </details> b", "TITLE: fix: x");
11817        let m = pr_message(&state, 'A');
11818        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
11819    }
11820
11821    #[test]
11822    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
11823        let cmd = manual_merge_command(
11824            MergeStyle::Squash,
11825            Path::new("/repo"),
11826            "b",
11827            "fix: \"quoted\" $(x) `y`\n\nbody",
11828        );
11829        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
11830    }
11831
11832    #[test]
11833    fn manual_merge_command_matches_the_configured_style() {
11834        let repo = Path::new("/repo");
11835        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
11836
11837        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
11838        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
11839
11840        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
11841        assert_eq!(
11842            squash,
11843            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
11844             \"Merge magi run 0832 (candidate A)\""
11845        );
11846
11847        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
11848        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
11849    }
11850
11851    #[test]
11852    fn a_nudge_gets_a_quarter_of_the_budget() {
11853        // The judge and implement budgets magi ships with.
11854        assert_eq!(retry_budget(secs(1200), true), secs(300));
11855        assert_eq!(retry_budget(secs(3600), true), secs(900));
11856    }
11857
11858    #[test]
11859    fn a_resent_prompt_keeps_the_whole_budget() {
11860        // The seat kept no context, so the retry is the original job again and
11861        // shortening it would only guarantee a second failure.
11862        assert_eq!(retry_budget(secs(1200), false), secs(1200));
11863        assert_eq!(retry_budget(secs(60), false), secs(60));
11864    }
11865
11866    #[test]
11867    fn the_floor_never_exceeds_the_original_budget() {
11868        // A short configured timeout must not be *raised* by the floor: the
11869        // operator asked for a bound, and a retry may not outlast the attempt
11870        // it is retrying.
11871        assert_eq!(retry_budget(secs(60), true), secs(60));
11872        assert_eq!(retry_budget(secs(480), true), secs(120));
11873        assert_eq!(retry_budget(secs(0), true), secs(0));
11874    }
11875
11876    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
11877        agent::CommandEvidence {
11878            id: "item1".to_owned(),
11879            description: "cargo test".to_owned(),
11880            exit_code,
11881            result_summary: String::new(),
11882            source: "codex".to_owned(),
11883        }
11884    }
11885
11886    #[test]
11887    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
11888        // No evidence is not the same fact as unconfirmed evidence: a
11889        // backend with no adapter, or a reply that ran no commands at all,
11890        // must not be misread as carrying a dangling job.
11891        assert!(!has_unconfirmed_command(&[]));
11892    }
11893
11894    #[test]
11895    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
11896        // Deliberately not a check on the exit code's *value*: a fixer
11897        // legitimately runs something that fails mid-iteration before it
11898        // succeeds, and that must never by itself reopen a valid report.
11899        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
11900        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
11901        assert!(!has_unconfirmed_command(&[
11902            evidence(Some(0)),
11903            evidence(Some(101))
11904        ]));
11905    }
11906
11907    #[test]
11908    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
11909        assert!(has_unconfirmed_command(&[
11910            evidence(Some(0)),
11911            evidence(None)
11912        ]));
11913    }
11914
11915    #[test]
11916    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
11917        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11918        assert_eq!(
11919            verified_noop_claim(true, &[], text).as_deref(),
11920            Some("already fixed by b32cfc4, on main.")
11921        );
11922    }
11923
11924    #[test]
11925    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
11926        // A timeout or a bad exit code reads as the ordinary loss it is,
11927        // whatever the reply's own prose claims.
11928        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11929        assert!(verified_noop_claim(false, &[], text).is_none());
11930    }
11931
11932    #[test]
11933    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
11934        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11935        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
11936        // A confirmed command alongside the marker is fine.
11937        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
11938    }
11939
11940    #[test]
11941    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
11942        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
11943    }
11944
11945    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
11946    /// pair, in order, labelled A, B, C, ...
11947    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
11948        runner.state.candidates = shape
11949            .iter()
11950            .enumerate()
11951            .map(|(i, &(empty, verified))| Candidate {
11952                index: i,
11953                label: (b'A' + i as u8) as char,
11954                agent: "sonnet".to_owned(),
11955                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
11956                worktree: PathBuf::from(format!("/wt/{i}")),
11957                summary: String::new(),
11958                stat: String::new(),
11959                files: 0,
11960                commits: 0,
11961                empty,
11962                failed: None,
11963                verified_noop: verified.map(str::to_owned),
11964                duration_ms: 0,
11965                folded: false,
11966            })
11967            .collect();
11968    }
11969
11970    #[test]
11971    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
11972        ask_test_home();
11973        let mut runner = runner_at(RunStatus::Implementing);
11974        set_candidates(
11975            &mut runner,
11976            &[
11977                (true, Some("already on main at b32cfc4")),
11978                (true, Some("same fix, see the existing test")),
11979            ],
11980        );
11981
11982        runner
11983            .after_implement()
11984            .expect("a verified no-op is not an error");
11985
11986        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
11987    }
11988
11989    #[test]
11990    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
11991        ask_test_home();
11992        let mut runner = runner_at(RunStatus::Implementing);
11993        // Candidate A declares a verified no-op; candidate B simply wrote
11994        // nothing and said nothing about why. One candidate's claim is not
11995        // the whole run's agreement.
11996        set_candidates(
11997            &mut runner,
11998            &[(true, Some("already on main at b32cfc4")), (true, None)],
11999        );
12000
12001        let err = runner
12002            .after_implement()
12003            .expect_err("an unverified empty candidate must still fail the run");
12004
12005        assert!(
12006            err.to_string().contains("no candidate produced a change"),
12007            "{err}"
12008        );
12009        assert_eq!(runner.state.status, RunStatus::Failed);
12010    }
12011
12012    #[test]
12013    fn after_implement_still_fails_an_ordinary_all_empty_run() {
12014        ask_test_home();
12015        let mut runner = runner_at(RunStatus::Implementing);
12016        set_candidates(&mut runner, &[(true, None), (true, None)]);
12017
12018        let err = runner
12019            .after_implement()
12020            .expect_err("no candidate declared anything; this is an ordinary failure");
12021
12022        assert!(
12023            err.to_string().contains("no candidate produced a change"),
12024            "{err}"
12025        );
12026        assert_eq!(runner.state.status, RunStatus::Failed);
12027    }
12028}