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    async fn merge(&mut self) -> Result<()> {
5914        // Same reasoning as `gate`: ask the review and gate records directly
5915        // rather than `status`, which a solo-candidate `judge`/`deliberate`
5916        // skip can rewrite on reentry to something that no longer says
5917        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
5918        // so a hand-off (open findings, green verification) reaches merge
5919        // exactly like a genuinely clean round does.
5920        //
5921        // A run resumed mid-`land` never reaches here at all: `execute`
5922        // recognises `RunStatus::Landing` before it even calls `prep`, and
5923        // routes straight to `run_land` instead. That has to happen a level
5924        // up from this function, not with a check in here, because
5925        // `review_loop`'s own status recomputation (see its doc) runs
5926        // *before* `merge` on every reentry and would otherwise overwrite
5927        // the `Landing` marker with `Gating` before this node ever saw it.
5928        if self
5929            .state
5930            .base_sync
5931            .as_ref()
5932            .is_some_and(|s| s.conflict.is_some())
5933            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
5934                != Some(RunStatus::Gating)
5935            // `gate_ran == false` is not "passed" - `gate` leaves it false
5936            // both before it has ever run and when its last attempt was
5937            // resource-blocked (see `Runner::gate`'s own doc), and neither is
5938            // permission to merge on nothing but the review record. Only a
5939            // gate that actually ran - zero commands configured and
5940            // vacuously passed, or one or more that all exited 0 - may
5941            // proceed; `RunState::gate_status` is the single place that
5942            // reading is computed.
5943            || !self.state.gate_status().ok()
5944        {
5945            return Ok(());
5946        }
5947        // This node's own record, not `status`: `status == Ready` is not
5948        // unique to the harmless `MergeMode::None` path this line was
5949        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
5950        // run's PR was closed without merging — and on that run `mode` is
5951        // still `Pr`, so a reentry that fell through here would push and
5952        // open a second pull request. `self.state.merge` is set exactly once
5953        // this node (or `land`) has already produced a verdict, under every
5954        // mode, which is what "already done" actually means here.
5955        if self.state.merge.is_some() {
5956            return Ok(());
5957        }
5958        let Some(winner) = self.state.winner().cloned() else {
5959            return Ok(());
5960        };
5961        let repo = self.state.repo.clone();
5962        let base = self.state.base_branch.clone();
5963        let mode = self.state.config.merge.mode;
5964        let style = self.state.config.merge.style;
5965        let facts = if is_review_run(&self.state) {
5966            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
5967            let start = review_base(
5968                &repo,
5969                &self.state.config.merge.remote,
5970                &base,
5971                &self.state.base_commit,
5972                &winner.branch,
5973            )
5974            .await;
5975            branch_facts(&repo, &start, &winner.branch).await
5976        } else {
5977            None
5978        };
5979        // `None` when the base could not be freshly read: then an adopted
5980        // pull request's title is left alone.
5981        let leaked = if is_review_run(&self.state) {
5982            leaked_subjects(&self.state, &winner.branch).await
5983        } else {
5984            Some(Vec::new())
5985        };
5986        let pr = pr_message_with(&self.state, winner.label, facts.as_ref());
5987        let message = pr.commit_message();
5988
5989        let outcome = match mode {
5990            MergeMode::None => MergeOutcome {
5991                mode,
5992                ok: true,
5993                detail: manual_merge_command(style, &repo, &winner.branch, &message),
5994                empty: false,
5995            },
5996            MergeMode::Pr | MergeMode::Local
5997                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
5998            {
5999                MergeOutcome {
6000                    mode,
6001                    ok: false,
6002                    detail: empty_candidate_detail(&self.state, &base),
6003                    empty: true,
6004                }
6005            }
6006            MergeMode::Local => {
6007                let on = git::current_branch(&repo).await?;
6008                if on.as_deref() != Some(base.as_str()) {
6009                    MergeOutcome {
6010                        mode,
6011                        ok: false,
6012                        detail: format!(
6013                            "{} has {} checked out, not the base branch {base}",
6014                            repo.display(),
6015                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
6016                        ),
6017                        empty: false,
6018                    }
6019                } else if !git::is_clean(&repo).await? {
6020                    MergeOutcome {
6021                        mode,
6022                        ok: false,
6023                        detail: format!("{} is dirty; refusing to merge", repo.display()),
6024                        empty: false,
6025                    }
6026                } else {
6027                    let out = match style {
6028                        MergeStyle::Merge => {
6029                            git::merge_no_ff(&repo, &winner.branch, &message).await?
6030                        }
6031                        MergeStyle::Squash => {
6032                            git::merge_squash(&repo, &winner.branch, &message).await?
6033                        }
6034                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
6035                    };
6036                    MergeOutcome {
6037                        mode,
6038                        ok: out.ok(),
6039                        detail: if out.ok() { out.stdout } else { out.stderr },
6040                        empty: false,
6041                    }
6042                }
6043            }
6044            MergeMode::Pr => {
6045                let remote = self.state.config.merge.remote.clone();
6046                let pushed = git::push(&winner.worktree, &remote, &winner.branch).await?;
6047                if !pushed.ok() {
6048                    MergeOutcome {
6049                        mode,
6050                        ok: false,
6051                        detail: pushed.stderr,
6052                        empty: false,
6053                    }
6054                } else {
6055                    // A retry or resume of a run whose branch already has an
6056                    // open pull request adopts it rather than failing on a
6057                    // duplicate. Only this winner branch into this base:
6058                    // `branch_for` derives the name from the run id, so a
6059                    // different run's pull request never matches.
6060                    let found = land::find_open_pr(&winner.worktree, &winner.branch, &base).await;
6061                    let out = match pr_merge_plan(found) {
6062                        PrPlan::Create => {
6063                            gh_pr_create(
6064                                &winner.worktree,
6065                                &base,
6066                                &winner.branch,
6067                                &pr.title,
6068                                &pr.body,
6069                            )
6070                            .await
6071                        }
6072                        PrPlan::Adopt { url, title } => {
6073                            self.state
6074                                .event("merge", format!("Pr: adopted open pull request {url}"));
6075                            if title != pr.title
6076                                && (!is_review_run(&self.state)
6077                                    || leaked
6078                                        .as_deref()
6079                                        .is_some_and(|l| should_retitle(&title, &pr.title, l)))
6080                                && let Err(e) =
6081                                    land::set_pr_title(&winner.worktree, &url, &pr.title).await
6082                            {
6083                                tracing::warn!("could not refresh title of {url}: {e:#}");
6084                                self.state
6085                                    .event("merge", format!("Pr: title refresh failed: {e:#}"));
6086                            }
6087                            Ok(url)
6088                        }
6089                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
6090                    };
6091                    match out {
6092                        Ok(url) => MergeOutcome {
6093                            mode,
6094                            ok: true,
6095                            detail: url,
6096                            empty: false,
6097                        },
6098                        Err(e) => MergeOutcome {
6099                            mode,
6100                            ok: false,
6101                            detail: e.to_string(),
6102                            empty: false,
6103                        },
6104                    }
6105                }
6106            }
6107        };
6108
6109        self.state.status = match (mode, outcome.ok) {
6110            (MergeMode::None, _) => RunStatus::Ready,
6111            (_, true) => RunStatus::Merged,
6112            (_, false) => RunStatus::Blocked,
6113        };
6114        self.state.event(
6115            "merge",
6116            format!(
6117                "{:?}: {}",
6118                mode,
6119                outcome.detail.lines().next().unwrap_or("")
6120            ),
6121        );
6122        self.state.merge = Some(outcome);
6123        self.state.save()?;
6124
6125        // The PR is open and the run would historically stop here, leaving the
6126        // operator to watch checks, feed review comments back to a fixer, and
6127        // merge. That was done by hand six times in one session before this
6128        // existed. Opt-in, because merging is the one irreversible thing magi
6129        // can do to a repository.
6130        if self.state.config.graph.land
6131            && mode == MergeMode::Pr
6132            && self.state.status == RunStatus::Merged
6133        {
6134            self.run_land().await?;
6135        }
6136        // `run_land` may have left `status` at `Landing` - still waiting on
6137        // CI or the owner's approval, not actually settled - so this has to
6138        // read whatever `status` ended up as here, not the `Merged` this
6139        // function set a few lines up.
6140        self.settle_questions();
6141        Ok(())
6142    }
6143
6144    /// Enter `land`.
6145    ///
6146    /// Shared between a fresh run's first pass through [`Runner::merge`] and
6147    /// a resumed run's re-entry. `land::land` itself is what serialises the
6148    /// two git-mutating moments inside the loop — the rebase push and
6149    /// `gh pr merge` — per repository (see its own doc); nothing here needs
6150    /// to hold a lock across the whole call, and doing so would serialise
6151    /// this run's CI wait against a *different* run's land-approval resume
6152    /// in the same repository, which is exactly the "must not wait on
6153    /// another task" property the daemon's slot-freeing exists to give.
6154    async fn run_land(&mut self) -> Result<()> {
6155        let url = self
6156            .state
6157            .merge
6158            .as_ref()
6159            .map(|m| m.detail.clone())
6160            .unwrap_or_default();
6161        let url = url.lines().next().unwrap_or("").trim().to_owned();
6162        if !url.starts_with("http") {
6163            return Ok(());
6164        }
6165        // A land failure is not a lost run: the work is on a branch and the
6166        // pull request is open, which is exactly where a human takes over.
6167        match land::land(&mut self.state, &url).await {
6168            Ok(pr) if self.state.parked => {
6169                // `land` already saved the parked marker; nothing here
6170                // overrides `status` back to a terminal value while an
6171                // approval is still outstanding.
6172                let _ = pr;
6173            }
6174            Ok(pr) => {
6175                self.state.status = match pr.state {
6176                    land::PrLifecycle::Merged => RunStatus::Merged,
6177                    _ => RunStatus::Blocked,
6178                };
6179                // Downstream of a confirmed merge only - see
6180                // `bump::should_release_bump`'s own doc for why this one
6181                // check covers all three of `land`'s success paths.
6182                // Best-effort: the run already landed, so a failure here
6183                // (the decision call, `gh`, `cargo`) is recorded and never
6184                // turns a landed run into a failed one.
6185                if bump::should_release_bump(self.state.status)
6186                    && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
6187                {
6188                    // The event is the run's own record. Not-eligible cases
6189                    // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
6190                    // `Err` is a bump that was tried and failed:
6191                    // `after_merge` itself raises the operator notice for
6192                    // that, whether or not a release PR exists yet.
6193                    self.state
6194                        .event("bump", format!("release bump skipped: {e:#}"));
6195                }
6196                // Independent of the bump, and best-effort in the same way:
6197                // findings the merge left open become follow-up tasks.
6198                if self.state.status == RunStatus::Merged {
6199                    crate::followup::after_merge(&mut self.state, &pr.url).await;
6200                }
6201                self.state.save()?;
6202            }
6203            Err(e) => {
6204                self.state.status = RunStatus::Blocked;
6205                self.state.event("land", format!("gave up: {e}"));
6206                self.state.save()?;
6207            }
6208        }
6209        Ok(())
6210    }
6211
6212    // -------------------------------------------------------------- helpers
6213
6214    /// Fetch or create a seat, keeping its conversation across nodes.
6215    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
6216        if let Some(existing) = self.state.seats.get(key)
6217            && existing.agent == agent
6218        {
6219            return existing.clone();
6220        }
6221        // A seat that changes agent mints its session id from the agent too,
6222        // like a handover: the old agent's uuid is already taken by the CLI.
6223        let fresh = if self.state.seats.contains_key(key) {
6224            handover_seat(key, agent, self.state.next_seat_seed())
6225        } else {
6226            SeatState::new(key, agent, self.state.seed)
6227        };
6228        self.state.seats.insert(key.to_owned(), fresh.clone());
6229        fresh
6230    }
6231
6232    /// The agent now holding seat `key`: `spec`, unless a handover moved the
6233    /// seat to another roster agent, in which case that agent. Nodes that
6234    /// continue a seat's conversation (deliberation, the votes, a reviewer's
6235    /// reconsideration) must keep talking to whoever answered it, not slip
6236    /// back to the agent that failed it.
6237    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
6238        match self.state.seats.get(key) {
6239            Some(s) if s.agent != spec.id => {
6240                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
6241            }
6242            _ => spec,
6243        }
6244    }
6245
6246    /// A candidate rendered for judging, with the leak policy applied.
6247    fn view(&self, c: &Candidate) -> CandidateView {
6248        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
6249            .unwrap_or_default();
6250        let (patch, _) = blind::sanitize_patch(
6251            &format!("candidate {} patch", c.label),
6252            &raw,
6253            &self.state.config.blind,
6254        );
6255        CandidateView {
6256            label: c.label,
6257            branch: c.branch.clone(),
6258            summary: c.summary.clone(),
6259            stat: c.stat.clone(),
6260            patch,
6261        }
6262    }
6263
6264    /// The full candidate set as prompt text, for seats with no live session.
6265    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
6266        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
6267        prompt::judge(
6268            "(see above)",
6269            &views,
6270            self.roles.judges.len(),
6271            base_short,
6272            "en",
6273        )
6274    }
6275
6276    /// The final-vote prompt with everything a seat that has no session of its
6277    /// own needs: the candidates, the seat's own ranking and reasons, and the
6278    /// anonymised deliberation it took part in (only when there was one, so a
6279    /// handed-over seat never sees more than the seat it replaces did). The
6280    /// `Final vote` heading stays first.
6281    fn vote_prompt_full(
6282        &self,
6283        j: usize,
6284        labels: &[char],
6285        language: &str,
6286        candidates: &[Candidate],
6287        base_short: &str,
6288    ) -> String {
6289        let mut text = format!(
6290            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
6291            prompt::final_vote(labels, language),
6292            self.state.instruction,
6293            self.candidate_block(candidates, base_short)
6294        );
6295        if let Some(own) = self
6296            .state
6297            .judgements
6298            .get(j)
6299            .filter(|r| !r.ranking.is_empty())
6300        {
6301            let reasons = own
6302                .reasons
6303                .iter()
6304                .map(|(k, v)| format!("- {k}: {v}"))
6305                .collect::<Vec<_>>()
6306                .join("\n");
6307            text.push_str(&format!(
6308                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
6309                own.ranking.iter().collect::<String>(),
6310                if reasons.is_empty() {
6311                    ""
6312                } else {
6313                    ", because:\n"
6314                }
6315            ));
6316        }
6317        if !self.state.deliberation.is_empty() {
6318            text.push_str("\n# What was argued before this vote\n");
6319            for t in self.transcript(&[], j) {
6320                text.push_str(&format!(
6321                    "\n## {}{}\n\n{}\n",
6322                    t.who,
6323                    if t.is_self { " (you)" } else { "" },
6324                    t.body.trim()
6325                ));
6326            }
6327        }
6328        text
6329    }
6330
6331    /// Anonymised transcript for judge `self_idx`.
6332    ///
6333    /// The initial rankings are always the opening statements. Seeding them
6334    /// only when no turn had been taken yet meant every judge after the first
6335    /// argued against a single voice instead of against the actual split — the
6336    /// disagreement is the information, so it is always on the table.
6337    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
6338        let mut turns = Vec::new();
6339        for j in &self.state.judgements {
6340            if j.ranking.is_empty() {
6341                continue;
6342            }
6343            let reasons = j
6344                .reasons
6345                .iter()
6346                .map(|(k, v)| format!("- {k}: {v}"))
6347                .collect::<Vec<_>>()
6348                .join("\n");
6349            turns.push(Turn {
6350                who: format!("Judge {} (opening ranking)", j.judge),
6351                is_self: j.judge == self_idx + 1,
6352                body: format!(
6353                    "Ranked {}{}{reasons}",
6354                    j.ranking.iter().collect::<String>(),
6355                    if reasons.is_empty() {
6356                        ""
6357                    } else {
6358                        ", because:\n"
6359                    }
6360                ),
6361            });
6362        }
6363        for t in self
6364            .state
6365            .deliberation
6366            .iter()
6367            .flat_map(|r| r.turns.iter())
6368            .chain(current)
6369        {
6370            turns.push(Turn {
6371                who: format!("Judge {}", t.judge),
6372                is_self: t.judge == self_idx + 1,
6373                body: t.body.clone(),
6374            });
6375        }
6376        turns
6377    }
6378}
6379
6380/// Does this seat still hold the context a follow-up prompt would rely on?
6381fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
6382    agent::has_session(spec.kind, seat, sessions)
6383}
6384
6385/// The next entry in `roster` after `start`, never wrapping back to the
6386/// front, whose id is not in `tried` yet.
6387///
6388/// Starts one past `start` rather than at the front of `roster`: `start` is
6389/// the seat's own original position, and a seat whose candidate slot already
6390/// sits on the roster's second entry must fall through to the third next, not
6391/// restart at the first — which is very likely a different candidate's own
6392/// agent already. Never wraps back past `start`, for the same reason: an
6393/// entry earlier in the roster than the seat's own position is almost
6394/// certainly some *other* candidate slot's own agent, and once the tail of
6395/// the roster is exhausted there are no more untried agents for *this* seat
6396/// to fall through to — the caller's fallback chain ends there, exactly as
6397/// "no further untried agents remain in the list for that seat" asks for.
6398///
6399/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
6400/// the same id twice (an operator's `roles.implementers` typo, or a
6401/// `[[agents]]` list reused across roles) must not let
6402/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
6403/// over `roster` either finds an untried id or runs out, so this always
6404/// terminates regardless of duplicates.
6405fn next_untried_in_roster<'a>(
6406    roster: &'a [AgentSpec],
6407    start: usize,
6408    tried: &BTreeSet<String>,
6409) -> Option<&'a AgentSpec> {
6410    roster
6411        .get(start + 1..)?
6412        .iter()
6413        .find(|s| !tried.contains(&s.id))
6414}
6415
6416/// The successor for a seat, shared by all four seat kinds (implement, judge,
6417/// review, advise). `others` holds the ids that *currently* occupy the other
6418/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
6419/// sees them), so roster entries beyond the seat count act as spares: a failed
6420/// seat goes to an agent no other seat holds whenever the roster permits.
6421///
6422/// `carried` is `Some` only for the review loop's carried failure history.
6423/// Order: (1) forward from `start`, never wrapping, untried, not a carried
6424/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
6425/// whole roster: untried and not another seat's occupant; (3) the plain walk
6426/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
6427/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
6428/// a better outcome than an empty seat, and it keeps the answer to "is there
6429/// a successor at all" exactly what it was before occupants were considered,
6430/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
6431/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
6432/// carried failure is a cheaper bet than doubling an agent on the panel, and
6433/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
6434/// the same round are handled one at a time, so a seat later in the batch
6435/// sees an earlier one's new occupant but not yet its own freed agent.
6436fn pick_successor<'a>(
6437    roster: &'a [AgentSpec],
6438    start: usize,
6439    tried: &BTreeSet<String>,
6440    carried: Option<&BTreeSet<String>>,
6441    others: &BTreeSet<String>,
6442) -> Option<&'a AgentSpec> {
6443    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
6444    roster
6445        .get(start + 1..)
6446        .and_then(|tail| {
6447            tail.iter()
6448                .filter(free)
6449                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
6450        })
6451        .or_else(|| {
6452            carried
6453                .is_some()
6454                .then(|| roster.iter().find(free))
6455                .flatten()
6456        })
6457        .or_else(|| match carried {
6458            Some(c) => next_for_seat(roster, start, tried, c),
6459            None => next_untried_in_roster(roster, start, tried),
6460        })
6461}
6462
6463/// The next agent for a seat that carries its failure history across rounds
6464/// (the review loop). `round_tried` is this round's own bound and starts
6465/// empty every round; `carried_failed` only decides priority.
6466///
6467/// First: an id walking forward from `start`, never wrapping, that is neither
6468/// tried this round nor failed in an earlier one. Only when that is exhausted
6469/// does it rescue: the first roster id (in roster order, so this one *does*
6470/// look before `start`) not yet tried this round, which is by then a carried
6471/// failure. Each id is rescued at most once per round, so it cannot loop.
6472fn next_for_seat<'a>(
6473    roster: &'a [AgentSpec],
6474    start: usize,
6475    round_tried: &BTreeSet<String>,
6476    carried_failed: &BTreeSet<String>,
6477) -> Option<&'a AgentSpec> {
6478    roster
6479        .get(start + 1..)?
6480        .iter()
6481        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
6482        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
6483}
6484
6485/// Where a reviewer seat starts a round: the agent that last answered it when
6486/// it is still on the roster and not marked failed, else the spec's own agent
6487/// unless it failed, else the next roster agent that has not failed, else the
6488/// spec's own agent again (the whole roster failed). Ids no longer on the
6489/// roster are ignored. An empty roster has no handover, so the spec stands.
6490fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
6491    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
6492        return spec;
6493    };
6494    let ok = |id: &str| !h.failed.contains(id);
6495    if let Some(last) = h.last_ok.as_deref()
6496        && ok(last)
6497        && let Some(s) = roster.iter().find(|s| s.id == last)
6498    {
6499        return s.clone();
6500    }
6501    if ok(&spec.id) {
6502        return spec;
6503    }
6504    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
6505    roster
6506        .get(from + 1..)
6507        .into_iter()
6508        .flatten()
6509        .chain(roster.iter())
6510        .find(|s| ok(&s.id))
6511        .cloned()
6512        .unwrap_or(spec)
6513}
6514
6515/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
6516/// seed so a CLI that mints its session id up front (`--session-id`) never
6517/// reuses the uuid the previous agent already opened under the same seat key.
6518pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
6519    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
6520}
6521
6522/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
6523/// so the classifier below and the code that builds the message cannot drift.
6524const TIMED_OUT: &str = "timed out";
6525
6526impl FailClass {
6527    /// `None` for an answer; otherwise how the turn failed.
6528    fn of(out: &AgentOutcome) -> Option<Self> {
6529        match out {
6530            AgentOutcome::Ok(_) => None,
6531            AgentOutcome::Quota(_) => Some(Self::Quota),
6532            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
6533            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
6534            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
6535        }
6536    }
6537
6538    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
6539    fn stem_word(&self) -> &'static str {
6540        match self {
6541            Self::Quota => "quota",
6542            _ => "handover",
6543        }
6544    }
6545}
6546
6547/// The message's first line with its variable parts removed — digit runs and
6548/// path-like tokens — so "exited with Some(2)" and "exited with Some(7)" read
6549/// as one kind of failure.
6550fn failure_signature(msg: &str) -> String {
6551    let line = msg.lines().next().unwrap_or("").trim().to_lowercase();
6552    let mut out = Vec::new();
6553    for word in line.split_whitespace() {
6554        if word.contains('/') || word.contains('\\') {
6555            out.push("<path>".to_owned());
6556            continue;
6557        }
6558        let mut w = String::new();
6559        let mut in_digits = false;
6560        for c in word.chars() {
6561            if c.is_ascii_digit() {
6562                if !in_digits {
6563                    w.push('#');
6564                }
6565                in_digits = true;
6566            } else {
6567                in_digits = false;
6568                w.push(c);
6569            }
6570        }
6571        out.push(w);
6572    }
6573    out.join(" ").chars().take(120).collect()
6574}
6575
6576/// Whether a seat that just failed with `cur` may go to the next roster agent.
6577/// A quota or a timeout always may. Any other failure may not when the agent
6578/// before it failed the same way: an error the prompt causes would otherwise
6579/// walk the whole roster. `prev` is the class of the immediately preceding
6580/// agent's failure, so a quota or timeout in between breaks the run of
6581/// identical failures by itself.
6582fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
6583    match cur {
6584        FailClass::Quota | FailClass::Timeout => true,
6585        FailClass::Other(_) => prev != Some(cur),
6586    }
6587}
6588
6589/// A short human reason for a failed outcome, for the handover record.
6590fn fail_reason(out: &AgentOutcome) -> String {
6591    match out {
6592        AgentOutcome::Ok(_) => String::new(),
6593        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
6594        AgentOutcome::Dropped(o) => format!(
6595            "the CLI dropped the stream ({})",
6596            o.dropped
6597                .as_ref()
6598                .map(|d| d.why.as_str())
6599                .unwrap_or("it ended without delivering its answer")
6600        ),
6601        AgentOutcome::Failed(e) => e.lines().next().unwrap_or("").chars().take(160).collect(),
6602    }
6603}
6604
6605/// Note one handover in the run: the structured record and, in the timeline,
6606/// the sentence a person reads. A quota keeps the wording it always had.
6607pub(crate) fn record_handover(
6608    state: &mut RunState,
6609    node: &str,
6610    seat: &str,
6611    from: &str,
6612    to: &str,
6613    class: &FailClass,
6614    reason: &str,
6615) {
6616    let message = if *class == FailClass::Quota {
6617        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
6618    } else {
6619        format!("{seat}: handed over {from} -> {to} ({reason})")
6620    };
6621    state.event(node, message);
6622    state.handovers.push(Handover {
6623        at: Timestamp::now(),
6624        node: node.to_owned(),
6625        seat: seat.to_owned(),
6626        from: from.to_owned(),
6627        to: to.to_owned(),
6628        reason: reason.to_owned(),
6629    });
6630}
6631
6632/// Did this reply report running a command whose own CLI never confirmed an
6633/// exit status?
6634///
6635/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
6636/// command *finished* (see that type's own doc), so this can only be `true`
6637/// for a command whose completion event carried no readable exit code — not
6638/// for one that simply is not mentioned at all. That is the one signal this
6639/// crate can read, from the same record `state.jobs` renders, about a reply
6640/// standing next to work its own CLI cannot vouch for finishing; it is
6641/// deliberately not a check on the exit code's *value* (a fixer legitimately
6642/// runs a command that fails mid-iteration before it succeeds) and not a
6643/// guess at a command still running in the background (which emits no event
6644/// at all, and so leaves no evidence here to find).
6645fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
6646    commands.iter().any(|c| c.exit_code.is_none())
6647}
6648
6649/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
6650/// trusted as a verified no-op — the adoption guard's own text-level half.
6651///
6652/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
6653/// timed out): a marker only earns the benefit of the doubt from a turn the
6654/// CLI itself vouches for finishing properly, the same house style
6655/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
6656/// *fix* report to for `commands`. A candidate that timed out, exited
6657/// non-zero, or left a command unconfirmed is read as the ordinary loss it
6658/// is, whatever prose it wrote — this returns `None` before it ever looks at
6659/// `text`. The remaining guards (the tree really is empty, the evidence is
6660/// non-empty) are the caller's: this only reads what the reply *claimed*.
6661fn verified_noop_claim(
6662    usable: bool,
6663    commands: &[agent::CommandEvidence],
6664    text: &str,
6665) -> Option<String> {
6666    (usable && !has_unconfirmed_command(commands))
6667        .then(|| verdict::verified_noop(text))
6668        .flatten()
6669}
6670
6671fn short(commit: &str) -> String {
6672    commit.chars().take(7).collect()
6673}
6674
6675fn make_executable(path: &Path) -> Result<()> {
6676    #[cfg(unix)]
6677    {
6678        use std::os::unix::fs::PermissionsExt as _;
6679        let mut perms = std::fs::metadata(path)?.permissions();
6680        perms.set_mode(0o755);
6681        std::fs::set_permissions(path, perms)?;
6682    }
6683    #[cfg(not(unix))]
6684    {
6685        let _ = path;
6686    }
6687    Ok(())
6688}
6689
6690/// What every seat in one batch shares: where the answers are attributed, the
6691/// prompt overlay they inherit, and the build cache they are told to use.
6692///
6693/// A struct rather than four more parameters: `wave` also needs the run's
6694/// state (to record who is answering right now) and the attempt number, and
6695/// eight positional arguments is both unreadable and a clippy error.
6696struct WaveCtx<'a> {
6697    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
6698    /// paid for it.
6699    run: &'a str,
6700    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
6701    node: &'a str,
6702    prompts: &'a Prompts,
6703    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
6704    cache: Option<&'a Path>,
6705    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
6706    /// `JobRecord::round`. `None` for every other node.
6707    round: Option<usize>,
6708    /// Carry each seat's failed-agent history across waves (the review loop
6709    /// only): start-of-round priority and handover choice read
6710    /// [`RunState::seat_history`], and every answer or failure writes it.
6711    carry_seats: bool,
6712}
6713
6714/// Run one job, honouring the parallelism budget.
6715async fn run_one(
6716    job: SeatJob,
6717    sem: Arc<Semaphore>,
6718    ctx: &WaveCtx<'_>,
6719    state: &mut RunState,
6720    attempt: usize,
6721) -> (SeatState, AgentOutcome) {
6722    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
6723        .await
6724        .pop()
6725        .expect("one job in, one result out");
6726    (seat, out)
6727}
6728
6729/// Run every job concurrently, capped by the semaphore, preserving order.
6730///
6731/// Every seat in the batch is recorded into [`RunState::active`] before the
6732/// wave starts and cleared as each answer lands, so the run's own record says
6733/// who is still being waited on rather than only who finished.
6734async fn wave(
6735    jobs: Vec<SeatJob>,
6736    sem: Arc<Semaphore>,
6737    ctx: &WaveCtx<'_>,
6738    state: &mut RunState,
6739    attempt: usize,
6740) -> Vec<(usize, SeatState, AgentOutcome)> {
6741    let WaveCtx {
6742        run,
6743        node,
6744        prompts,
6745        cache,
6746        round,
6747        carry_seats: _,
6748    } = *ctx;
6749    for job in &jobs {
6750        state.seat_started(node, &job.seat.key, job.timeout, attempt);
6751    }
6752    if let Err(e) = state.save() {
6753        // A failed persist of "who is answering right now" must not abort the
6754        // wave: the seats are already being asked, and the alternative is
6755        // losing the answers to save a status line nobody may even be
6756        // watching.
6757        tracing::warn!("could not persist in-progress seats: {e:#}");
6758    }
6759    // Hold the shared build cache's lease for the whole batch, not per job:
6760    // several candidates (an implement wave) or a fixer legitimately share
6761    // one cache concurrently within this run, and that stays untouched — a
6762    // single lease taken once for the whole wave and released once it is
6763    // done is what stops a *different* borrower (another run's own wave, its
6764    // e2e/gate, a human's `magi review`) from interleaving a build into the
6765    // same directory while this one is in flight. Best-effort, not
6766    // all-or-nothing: a wave that cannot get the lease within its own
6767    // longest job's budget still runs — an hour of paid implementer calls is
6768    // not thrown away over cache contention — but every write-allowed seat
6769    // then goes without `CARGO_TARGET_DIR` for this wave too (see the filter
6770    // below), the same fallback a read-only seat always gets, rather than
6771    // building into a directory this run was never granted. The identity
6772    // record is still invalidated below either way, so the next tracked
6773    // caller (`e2e`/`gate`) never trusts a match it cannot vouch for.
6774    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
6775    let wait_started = Instant::now();
6776    let cache_guard = if let Some(cache_dir) = cache {
6777        if jobs_had_a_writer {
6778            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
6779            let budget = jobs
6780                .iter()
6781                .map(|j| j.timeout)
6782                .max()
6783                .unwrap_or(Duration::from_secs(60));
6784            acquire_cache_lease(state, cache_dir, &owner, budget, node)
6785                .await
6786                .ok()
6787        } else {
6788            None
6789        }
6790    } else {
6791        None
6792    };
6793    // Carved out of each job's own budget, not added on top of it: a seat
6794    // that waited behind the lease must not also get its full timeout
6795    // afterward, or a run contended on the cache could double the time it
6796    // spends per wave. `saturating_sub` floors at zero rather than
6797    // wrapping - a job whose whole budget was spent waiting starts with
6798    // none left, which is the honest number, not a free minimum.
6799    let waited_for_lease = wait_started.elapsed();
6800    let mut set = tokio::task::JoinSet::new();
6801    let overlay = prompts.overlay(node);
6802    for (i, mut job) in jobs.into_iter().enumerate() {
6803        job.timeout = job.timeout.saturating_sub(waited_for_lease);
6804        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
6805        if cache.is_some() {
6806            job.prompt.push('\n');
6807            job.prompt
6808                .push_str(&prompt::build_cache_note(node, job.allow_write));
6809        }
6810        let sem = Arc::clone(&sem);
6811        let run = run.to_owned();
6812        let node = node.to_owned();
6813        // Only implementers were told about the task's attachments, so only
6814        // their seats get the directory widened for reading.
6815        let attachments = if node == "implement" {
6816            state.attachments.clone()
6817        } else {
6818            Vec::new()
6819        };
6820        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
6821        // `prompt::build_cache_note`'s doc for why setting it anyway is
6822        // exactly how a sandboxed reviewer's write refusal got reported as a
6823        // defect in the patch, not a property of its own seat. And a
6824        // write-allowed one is handed it only when the lease above was
6825        // actually acquired: a wave that could not get it (`cache_guard` is
6826        // `None`, see its own comment) must not send seats to build into a
6827        // directory this run does not hold - that is the exact concurrent,
6828        // unmanaged-write race this module exists to prevent, not something
6829        // "proceeding anyway" is allowed to reintroduce.
6830        let cache = cache
6831            .filter(|_| job.allow_write && cache_guard.is_some())
6832            .map(Path::to_path_buf);
6833        set.spawn(async move {
6834            let _permit = sem.acquire().await;
6835            let mut seat = job.seat;
6836            let out = agent::invoke(
6837                &job.spec,
6838                &mut seat,
6839                &Invocation {
6840                    cwd: &job.cwd,
6841                    prompt: &job.prompt,
6842                    timeout: job.timeout,
6843                    allow_write: job.allow_write,
6844                    sessions: job.sessions,
6845                    artifacts: &job.artifacts,
6846                    stem: &job.stem,
6847                    run: &run,
6848                    node: &node,
6849                    cache_dir: cache.as_deref(),
6850                    attachments: &attachments,
6851                    writable: &[],
6852                },
6853            )
6854            .await;
6855            let out = match out {
6856                Ok(o) if o.usable() => AgentOutcome::Ok(o),
6857                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
6858                // Billed work the CLI failed to hand over is not an ordinary
6859                // failure, but its text is the CLI's raw error JSON, not an
6860                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
6861                // read it as one by forgetting to check. `usable()` is always
6862                // false here (dropped implies an empty response), so this has
6863                // to be checked before the catch-all `Failed` below or the
6864                // one shape this exists for is lost with the rest.
6865                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
6866                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
6867                Ok(o) => AgentOutcome::Failed(format!(
6868                    "exited with {:?} and no usable output",
6869                    o.exit_code
6870                )),
6871                Err(e) => AgentOutcome::Failed(e.to_string()),
6872            };
6873            (i, seat, out)
6874        });
6875    }
6876    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
6877    while let Some(joined) = set.join_next().await {
6878        let (i, seat, out) = match joined {
6879            Ok(v) => v,
6880            // No seat to clear: a panicked task never reported which one it
6881            // was. The defensive sweep below this loop is what stops that
6882            // seat's `active` entry from surviving forever.
6883            Err(e) => {
6884                tracing::error!("agent task panicked: {e}");
6885                continue;
6886            }
6887        };
6888        state.seat_finished(&seat.key);
6889        record_jobs(state, node, round, &seat.key, &out);
6890        if let Err(e) = state.save() {
6891            tracing::warn!("could not persist a seat's completion: {e:#}");
6892        }
6893        if collected.len() <= i {
6894            collected.resize_with(i + 1, || None);
6895        }
6896        collected[i] = Some((i, seat, out));
6897    }
6898    // Belt-and-braces for the panic branch above: every seat this exact batch
6899    // started shares this `(node, attempt)` pair, and every seat that finished
6900    // normally already cleared itself, so anything left tagged with it here
6901    // can only be a panicked task's leftover. Cleared unconditionally rather
6902    // than left to read as still answering forever.
6903    if state
6904        .active
6905        .values()
6906        .any(|a| a.node == node && a.attempt == attempt)
6907    {
6908        state
6909            .active
6910            .retain(|_, a| !(a.node == node && a.attempt == attempt));
6911        if let Err(e) = state.save() {
6912            tracing::warn!("could not persist the end of a wave: {e:#}");
6913        }
6914    }
6915    // Whether or not the lease above was actually held, several worktrees
6916    // may just have built into the cache with nothing here able to name one
6917    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
6918    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
6919    // clean it might not have strictly needed; trusting a stale match would
6920    // cost it a wrong answer.
6921    if let Some(cache_dir) = cache
6922        && jobs_had_a_writer
6923    {
6924        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
6925    }
6926    if let Some(guard) = cache_guard {
6927        guard.release();
6928    }
6929    collected.into_iter().flatten().collect()
6930}
6931
6932/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
6933/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
6934/// this is data collection, not the fix-specific completion contract in
6935/// [`Runner::continue_fix_report`], and applies regardless of which node
6936/// asked.
6937///
6938/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
6939/// evidence from; `Failed` does not, and correctly contributes nothing — a
6940/// timeout or crash is not itself evidence about a command the seat may have
6941/// started.
6942fn record_jobs(
6943    state: &mut RunState,
6944    node: &str,
6945    round: Option<usize>,
6946    seat: &str,
6947    out: &AgentOutcome,
6948) {
6949    let commands: &[agent::CommandEvidence] = match out {
6950        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
6951        AgentOutcome::Failed(_) => &[],
6952    };
6953    let checked_at = Timestamp::now();
6954    for c in commands {
6955        state.jobs.push(JobRecord {
6956            node: node.to_owned(),
6957            round,
6958            seat: seat.to_owned(),
6959            id: c.id.clone(),
6960            description: c.description.clone(),
6961            checked_at,
6962            status: match c.exit_code {
6963                Some(0) => JobStatus::Completed,
6964                Some(_) => JobStatus::Failed,
6965                None => JobStatus::Unknown,
6966            },
6967            exit_code: c.exit_code,
6968            result_summary: c.result_summary.clone(),
6969            source: c.source.clone(),
6970        });
6971    }
6972}
6973
6974/// Is a review round clean, given how many reviewer seats answered against
6975/// how many the round expected?
6976///
6977/// A seat that never answered (timeout, crash, unparsable output) is not a
6978/// seat that read the patch and found nothing — treating it as such is
6979/// exactly the bug this function exists to close. Under the default `block`
6980/// policy a missing seat can never be clean; `warn` still requires the seats
6981/// that *did* answer to have found nothing blocking and verification to be
6982/// green.
6983///
6984/// `quota_missing` narrows that `block` default for exactly one cause of
6985/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
6986/// a session limit lifts by the very next round buys nothing — the seat is
6987/// asked again with the same quota — so once every missing seat is accounted
6988/// for by a quota loss (and at least one seat *did* answer, so a decision has
6989/// something to rest on) the round is decided on the panel that could answer,
6990/// same as `warn` would. A panel that lost every seat to quota is not
6991/// decided here: `answered == 0` falls through to the existing `block`
6992/// fallback so a fully collapsed panel still waits rather than landing on no
6993/// review at all.
6994fn round_is_clean(
6995    blocking: usize,
6996    e2e_ok: bool,
6997    answered: usize,
6998    expected: usize,
6999    quota_missing: usize,
7000    policy: IncompleteReviewPolicy,
7001) -> bool {
7002    if blocking != 0 || !e2e_ok {
7003        return false;
7004    }
7005    if answered == expected || policy == IncompleteReviewPolicy::Warn {
7006        return true;
7007    }
7008    answered > 0 && expected - answered <= quota_missing
7009}
7010
7011/// The review loop's own conclusion, derived entirely from its persisted
7012/// round records and the round budget that produced them — never from
7013/// `status`, so a reentry (or `gate`/`merge` reading it independently)
7014/// recomputes the identical answer regardless of what an earlier node in the
7015/// same walk, or a previous walk, did to `status`.
7016///
7017/// `None` while more rounds remain to try, including when review never ran
7018/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
7019/// gone clean, or the budget is spent, or the tree has stopped moving (see
7020/// [`STAGNANT_LIMIT`]), the answer is one of two things:
7021///
7022/// - An incomplete panel that raised nothing is missing input, not a
7023///   verified tree — never a hand-off candidate, whatever verification said
7024///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
7025/// - Otherwise, green e2e on the last round hands off (see
7026///   [`Runner::stop_reviewing`]); red e2e blocks.
7027///
7028/// A last round whose own verification is still `ResourceBlocked` — magi
7029/// itself never got a command to run, not evidence the patch is broken —
7030/// is neither: this returns `None` for it too, the same as "more rounds
7031/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
7032/// handling of that shape) instead of this cheap recomputation guessing a
7033/// verdict a real attempt never produced.
7034fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
7035    if max_rounds == 0 || reviews.iter().any(|r| r.clean) {
7036        return Some(RunStatus::Gating);
7037    }
7038    let last = reviews.last()?;
7039    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
7040    if reviews.len() < max_rounds && !stagnant {
7041        return None;
7042    }
7043    if last.incomplete() && last.blocking == 0 {
7044        return Some(RunStatus::Blocked);
7045    }
7046    if last.e2e_status() == E2eStatus::ResourceBlocked {
7047        return None;
7048    }
7049    Some(if last.e2e.iter().all(CommandOutcome::ok) {
7050        RunStatus::Gating
7051    } else {
7052        RunStatus::Blocked
7053    })
7054}
7055
7056/// How long a re-ask may take, given the budget the first attempt had.
7057///
7058/// A `nudged` retry is a request to restate an answer the seat has already
7059/// worked out: it carries no new work, so it does not deserve the original
7060/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
7061/// 133 seconds while a third sat for over ten minutes on a resumed session
7062/// holding 410 KB of prior output - and because the retry had inherited the
7063/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
7064/// judging round whose other seats were long finished.
7065///
7066/// A quarter of the budget, with a floor so that a deliberately short timeout
7067/// does not collapse to nothing. A retry that re-sends the whole prompt
7068/// (because the seat kept no context) is the original job again, and keeps the
7069/// original budget.
7070fn retry_budget(full: Duration, nudged: bool) -> Duration {
7071    if nudged {
7072        (full / 4).max(Duration::from_secs(120)).min(full)
7073    } else {
7074        full
7075    }
7076}
7077
7078/// Run a wave and parse each reply, re-asking the seats whose reply was
7079/// unusable.
7080///
7081/// The re-ask is a nudge rather than the whole prompt again when the seat still
7082/// holds its conversation, which is the difference between a cheap retry and
7083/// paying for the entire candidate set twice.
7084///
7085/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
7086/// successor in `roster` is handed to it instead of being re-asked: the
7087/// handover is the retry. A seat with no successor left (a single-agent
7088/// roster, the roster's tail) is nudged as before, up to `retries` times. So
7089/// the asks to one seat in one node number at most
7090/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
7091/// is asked once (a dropped stream is nudged first), and only the last agent
7092/// of the chain gets the `retries` same-agent nudges. Each roster agent is
7093/// tried at most once per seat, walking forward from the seat's own position and never wrapping
7094/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
7095/// other failure stops the chain when the previous agent failed the same way
7096/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
7097/// [`has_context`] is false and the job's own full prompt and full budget are
7098/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
7099/// intermediate ones are not losses) and is returned as a failure like any
7100/// other absent seat — the caller decides whether the panel still has a
7101/// quorum. An empty `roster` disables handover: failures are nudged as they
7102/// always were, and a quota is simply lost. A reply that fails to parse or
7103/// validate is the prompt's doing and is only ever nudged, never handed over.
7104///
7105/// The returned [`SeatState`] names the agent that answered (or tried last).
7106#[allow(clippy::too_many_arguments)]
7107async fn ask_json_wave<T>(
7108    jobs: Vec<SeatJob>,
7109    sem: Arc<Semaphore>,
7110    retries: usize,
7111    roster: &[AgentSpec],
7112    ctx: &WaveCtx<'_>,
7113    losses: &mut Vec<QuotaLoss>,
7114    state: &mut RunState,
7115    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
7116) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
7117where
7118    T: serde::de::DeserializeOwned + Send + 'static,
7119{
7120    ask_wave_with(
7121        jobs,
7122        sem,
7123        retries,
7124        roster,
7125        ctx,
7126        losses,
7127        state,
7128        &|text: &str| {
7129            let v = verdict::extract_json::<T>(text)?;
7130            validate(&v)?;
7131            Ok(v)
7132        },
7133    )
7134    .await
7135}
7136
7137/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
7138/// a node whose answer is prose (deliberation) shares the same handover,
7139/// failure classification, quota bookkeeping and bounds instead of a copy.
7140///
7141/// A seat handed to another roster agent is sent the job's `handover` prompt
7142/// (when it has one) rather than `prompt`: the new agent has no session, so a
7143/// resume-style prompt would be incomplete. That holds for the handover ask
7144/// and for every nudge to that agent whose `has_context` is false.
7145#[allow(clippy::too_many_arguments)]
7146async fn ask_wave_with<T>(
7147    jobs: Vec<SeatJob>,
7148    sem: Arc<Semaphore>,
7149    retries: usize,
7150    roster: &[AgentSpec],
7151    ctx: &WaveCtx<'_>,
7152    losses: &mut Vec<QuotaLoss>,
7153    state: &mut RunState,
7154    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
7155) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
7156where
7157    T: Send + 'static,
7158{
7159    let n = jobs.len();
7160    let originals: Vec<SeatJob> = jobs;
7161    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
7162    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
7163    // Nudges each seat's *current* agent has taken — 0 for a first-ask
7164    // answer, N once it has gone through N nudges. Read back once this
7165    // returns, so a caller building a history record (`ReviewRecord`) can
7166    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
7167    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
7168    // field's own doc.
7169    let mut nudges: Vec<usize> = vec![0; n];
7170    // The agent now occupying each seat, the ids it has already been through,
7171    // where in the roster the walk began, the class of the last failure, and
7172    // the stem word of a handover not yet asked (full prompt, full budget).
7173    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
7174    let mut tried: Vec<BTreeSet<String>> = specs
7175        .iter()
7176        .map(|s| BTreeSet::from([s.id.clone()]))
7177        .collect();
7178    let starts: Vec<usize> = specs
7179        .iter()
7180        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
7181        .collect();
7182    let carry = ctx.carry_seats && !roster.is_empty();
7183    // Carried across rounds: ids that failed the seat earlier, and how the
7184    // last failure went (so a repeat of it is not handed over again).
7185    let carried: Vec<BTreeSet<String>> = originals
7186        .iter()
7187        .map(|j| {
7188            state
7189                .seat_history
7190                .get(&j.seat.key)
7191                .filter(|_| carry)
7192                .map(|h| h.failed.clone())
7193                .unwrap_or_default()
7194        })
7195        .collect();
7196    let mut prev: Vec<Option<FailClass>> = originals
7197        .iter()
7198        .map(|j| {
7199            state
7200                .seat_history
7201                .get(&j.seat.key)
7202                .filter(|_| carry)
7203                .and_then(|h| h.last_fail.clone())
7204        })
7205        .collect();
7206    let next_agent =
7207        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
7208            let others: BTreeSet<String> = specs
7209                .iter()
7210                .enumerate()
7211                .filter(|(j, _)| *j != i)
7212                .map(|(_, s)| s.id.clone())
7213                .collect();
7214            pick_successor(
7215                roster,
7216                starts[i],
7217                tried,
7218                carry.then(|| &carried[i]),
7219                &others,
7220            )
7221            .cloned()
7222        };
7223    let mut fresh: Vec<Option<String>> = vec![None; n];
7224    let mut last_quota: Vec<Option<Option<String>>> = vec![None; n];
7225    let mut pending: Vec<usize> = (0..n).collect();
7226
7227    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
7228    // asks: an agent with a successor is asked once and handed over, and only
7229    // a seat with no successor spends `retries` nudges on the same agent. This
7230    // only guarantees the loop's own termination whatever those say.
7231    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
7232    for round in 0..max_rounds {
7233        if pending.is_empty() {
7234            break;
7235        }
7236        let mut batch = Vec::with_capacity(pending.len());
7237        let mut renudged: Vec<&str> = Vec::new();
7238        for &i in &pending {
7239            let src = &originals[i];
7240            // A seat now held by another agent than the job named has no
7241            // session of its own: it gets the full-context prompt whenever
7242            // it is asked in full (the handover ask, a nudge it cannot
7243            // resume).
7244            let full: &str = match &src.handover {
7245                Some(h) if specs[i].id != src.spec.id => h,
7246                _ => &src.prompt,
7247            };
7248            // The prompt and the budget are one decision: a nudge restates
7249            // finished work, a re-sent prompt redoes it.
7250            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
7251                (
7252                    full.to_owned(),
7253                    src.timeout,
7254                    format!("{}-{word}-{}", src.stem, specs[i].id),
7255                )
7256            } else if nudges[i] == 0 {
7257                (full.to_owned(), src.timeout, src.stem.clone())
7258            } else {
7259                renudged.push(src.seat.key.as_str());
7260                let why = done[i]
7261                    .as_ref()
7262                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
7263                    .unwrap_or_else(|| "no parsable answer".to_owned());
7264                let nudge = prompt::nudge(&why);
7265                let nudged = has_context(&specs[i], &seats[i], src.sessions);
7266                let prompt = if nudged {
7267                    nudge
7268                } else {
7269                    format!("{full}\n\n---\n\n{nudge}")
7270                };
7271                (
7272                    prompt,
7273                    retry_budget(src.timeout, nudged),
7274                    format!("{}-retry{}", src.stem, nudges[i]),
7275                )
7276            };
7277            batch.push(SeatJob {
7278                spec: specs[i].clone(),
7279                seat: seats[i].clone(),
7280                cwd: src.cwd.clone(),
7281                prompt,
7282                timeout,
7283                allow_write: src.allow_write,
7284                sessions: src.sessions,
7285                artifacts: src.artifacts.clone(),
7286                stem,
7287                handover: None,
7288            });
7289        }
7290
7291        if !renudged.is_empty() {
7292            state.event(
7293                ctx.node,
7294                format!("retry {round}: re-asking {}", renudged.join(", ")),
7295            );
7296        }
7297        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
7298        let mut still = Vec::new();
7299        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
7300            seats[i] = seat;
7301            let class = FailClass::of(&out);
7302            // A dropped stream is nudged first (the conversation is still
7303            // there to pick up); only a seat whose nudges are spent hands over.
7304            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
7305                && nudges[i] < retries
7306                && !roster.is_empty();
7307            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
7308                let next = should_hand_over(prev[i].as_ref(), &cur)
7309                    .then(|| next_agent(i, &tried[i], &specs))
7310                    .flatten();
7311                if carry {
7312                    let h = state
7313                        .seat_history
7314                        .entry(originals[i].seat.key.clone())
7315                        .or_default();
7316                    h.failed.insert(specs[i].id.clone());
7317                    h.last_fail = Some(cur.clone());
7318                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
7319                        h.last_ok = None;
7320                    }
7321                    // Saved before the next agent is asked, so a restart in
7322                    // between does not forget who failed.
7323                    if let Err(e) = state.save() {
7324                        tracing::warn!("could not persist a seat's failure history: {e:#}");
7325                    }
7326                }
7327                if let Some(next) = next {
7328                    record_handover(
7329                        state,
7330                        ctx.node,
7331                        &originals[i].seat.key,
7332                        &specs[i].id,
7333                        &next.id,
7334                        &cur,
7335                        &fail_reason(&out),
7336                    );
7337                    tried[i].insert(next.id.clone());
7338                    prev[i] = Some(cur.clone());
7339                    seats[i] =
7340                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
7341                    specs[i] = next;
7342                    fresh[i] = Some(cur.stem_word().to_owned());
7343                    nudges[i] = 0;
7344                    done[i] = Some(Err(anyhow::anyhow!(
7345                        "handed over after: {}",
7346                        fail_reason(&out)
7347                    )));
7348                    still.push(i);
7349                    continue;
7350                }
7351            }
7352            if carry
7353                && !nudge_first
7354                && let Some(cur) = class.clone()
7355            {
7356                // The chain ended here (no successor, or a repeated failure).
7357                let h = state
7358                    .seat_history
7359                    .entry(originals[i].seat.key.clone())
7360                    .or_default();
7361                h.failed.insert(specs[i].id.clone());
7362                h.last_fail = Some(cur);
7363            }
7364            let parsed = match out {
7365                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
7366                AgentOutcome::Quota(o) => {
7367                    last_quota[i] = Some(o.quota.as_ref().and_then(|q| q.reset.clone()));
7368                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
7369                }
7370                // Not a parseable answer: the nudge loop re-asks it, which is
7371                // exactly what a dropped stream needs. Just don't hand its raw
7372                // error JSON to `extract_json`.
7373                AgentOutcome::Dropped(o) => {
7374                    let why = o
7375                        .dropped
7376                        .as_ref()
7377                        .map(|d| d.why.as_str())
7378                        .unwrap_or("the CLI ended the stream without delivering its answer");
7379                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
7380                }
7381                AgentOutcome::Failed(e) => Err(anyhow::anyhow!(e)),
7382            };
7383            let quota = class == Some(FailClass::Quota);
7384            let failed = parsed.is_err();
7385            done[i] = Some(parsed);
7386            if carry && !failed {
7387                let h = state
7388                    .seat_history
7389                    .entry(originals[i].seat.key.clone())
7390                    .or_default();
7391                h.failed.remove(&specs[i].id);
7392                h.last_ok = Some(specs[i].id.clone());
7393                h.last_fail = None;
7394            }
7395            // Do not re-ask a rate-limited seat (quota) — a retry is known to
7396            // fail the same way; and never re-ask a seat that already parsed.
7397            // A failed agent that still has a successor is not re-asked
7398            // either: the handover was its remedy and has just been refused
7399            // (the chain stops on a repeated failure class). A seat with no
7400            // successor left (a single-agent roster, the roster's tail, or an
7401            // empty roster) keeps the same-agent nudge, bounded by `retries`.
7402            let agent_failure = class.is_some()
7403                && !nudge_first
7404                && !roster.is_empty()
7405                && next_agent(i, &tried[i], &specs).is_some();
7406            if failed && !quota && !agent_failure && nudges[i] < retries {
7407                nudges[i] += 1;
7408                still.push(i);
7409            }
7410        }
7411        pending = still;
7412    }
7413
7414    // One loss per seat whose chain ended on a quota: the intermediate ones
7415    // were absorbed by a handover and are not losses.
7416    for (i, q) in last_quota.into_iter().enumerate() {
7417        if let Some(reset) = q {
7418            losses.push(QuotaLoss {
7419                seat: originals[i].seat.key.clone(),
7420                node: ctx.node.to_owned(),
7421                at: Timestamp::now(),
7422                reset,
7423            });
7424        }
7425    }
7426
7427    seats
7428        .into_iter()
7429        .zip(done)
7430        .zip(nudges)
7431        .map(|((seat, res), attempts)| {
7432            (
7433                seat,
7434                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
7435                attempts,
7436            )
7437        })
7438        .collect()
7439}
7440
7441/// Acquire the shared build cache's lease, waiting out contention within
7442/// `budget` (never past it — see AGENTS.md's build-cache section on why an
7443/// unbounded wait is never acceptable).
7444///
7445/// A first, non-blocking check happens before ever waiting; if it finds the
7446/// lease busy, that fact is logged as a `verify` event *and* flushed with
7447/// [`RunState::save`] immediately — not only once the wait finally succeeds
7448/// or gives up — so a `magi show` run by a different process while this one
7449/// is still waiting reads a `run.json` that says so, rather than whatever it
7450/// looked like before the wait started. The same applies to the terminal
7451/// failure: logged and saved before this returns `Err`, so a caller that
7452/// could not get the lease at all still leaves a legible record of why.
7453async fn acquire_cache_lease(
7454    state: &mut RunState,
7455    cache_dir: &Path,
7456    owner: &crate::cache::Owner,
7457    budget: Duration,
7458    context: &str,
7459) -> Result<crate::cache::Guard> {
7460    let home = crate::run::home();
7461    let started = Instant::now();
7462    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
7463        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(g),
7464        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
7465        Err(e) => {
7466            state.event(
7467                "verify",
7468                format!("{context}: could not check the shared build cache: {e:#}"),
7469            );
7470            if let Err(e2) = state.save() {
7471                tracing::warn!("could not persist a cache-check failure: {e2:#}");
7472            }
7473            return Err(e);
7474        }
7475    };
7476    state.event(
7477        "verify",
7478        format!(
7479            "{context}: waiting for the shared build cache at {} ({})",
7480            cache_dir.display(),
7481            busy.describe()
7482        ),
7483    );
7484    if let Err(e) = state.save() {
7485        tracing::warn!("could not persist a cache wait: {e:#}");
7486    }
7487    let remaining = budget.saturating_sub(started.elapsed());
7488    match crate::cache::wait_for(&home, cache_dir, owner, remaining, Duration::from_secs(5)).await {
7489        Ok(g) => Ok(g),
7490        Err(e) => {
7491            state.event("verify", format!("{context}: {e:#}"));
7492            if let Err(e2) = state.save() {
7493                tracing::warn!("could not persist a cache wait timeout: {e2:#}");
7494            }
7495            Err(e)
7496        }
7497    }
7498}
7499
7500/// Run `body` — a verify command batch — while holding the shared build
7501/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
7502/// never interleave with another borrower's build against the same
7503/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
7504/// timeout, or a human's own `magi review`. See the `cache` module doc for
7505/// why this matters more than Cargo's own per-target locking covers — two
7506/// *different* worktrees building the same package name/version into one
7507/// cache directory is a staleness bug, not a lock contention one.
7508///
7509/// The wait for the lease is carved out of `budget`, never on top of it —
7510/// `body` is handed whatever is left, so a caller's own node timeout is the
7511/// only clock involved, exactly what AGENTS.md's build-cache section asks
7512/// for ("never an unbounded wait"). When `cache_dir` is `None` — no shared
7513/// cache configured at all — this is a pass-through: `body` runs with the
7514/// full budget and nothing is leased.
7515///
7516/// A lease that cannot be acquired within `budget` is reported as a single
7517/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
7518/// verification — the same shape a spawn failure already takes in
7519/// [`run_commands`], so a caller need not special-case it.
7520#[allow(clippy::too_many_arguments)]
7521async fn with_cache_lease<'s, F, Fut>(
7522    state: &'s mut RunState,
7523    cache_dir: Option<&Path>,
7524    node: &str,
7525    seat: &str,
7526    worktree: &Path,
7527    head: &str,
7528    budget: Duration,
7529    context: &str,
7530    body: F,
7531) -> (Vec<CommandOutcome>, bool)
7532where
7533    F: FnOnce(&'s mut RunState, Duration) -> Fut,
7534    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
7535{
7536    let Some(cache_dir) = cache_dir else {
7537        let (outcomes, retried, _timed_out_pids) = body(state, budget).await;
7538        return (outcomes, retried);
7539    };
7540    let home = crate::run::home();
7541    let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
7542    let started = Instant::now();
7543    let guard = match acquire_cache_lease(state, cache_dir, &owner, budget, context).await {
7544        Ok(g) => g,
7545        Err(e) => {
7546            return (
7547                vec![CommandOutcome {
7548                    command: "(waiting for the shared build cache)".to_owned(),
7549                    code: None,
7550                    output_tail: e.to_string(),
7551                    duration_ms: started.elapsed().as_millis() as u64,
7552                    resource_blocked: true,
7553                }],
7554                false,
7555            );
7556        }
7557    };
7558    let identity = crate::cache::Identity::new(worktree, head);
7559    if let Err(e) = crate::cache::ensure_fresh(&home, cache_dir, &identity) {
7560        // A failed freshness check means this process cannot vouch for what
7561        // is sitting in the cache right now - on Windows this is exactly the
7562        // "a stale test executable is still locked, `cargo clean -p` cannot
7563        // remove it" case the evidence log records. Running verify anyway
7564        // and reporting whatever it says would let a result nobody can trust
7565        // stand for the tree it claims to have checked; fail the step
7566        // instead of the patch.
7567        state.event(
7568            "verify",
7569            format!(
7570                "{context}: could not confirm the shared build cache matches {} at {}: {e:#}",
7571                worktree.display(),
7572                short(head)
7573            ),
7574        );
7575        guard.release();
7576        return (
7577            vec![CommandOutcome {
7578                command: "(confirming the shared build cache is fresh)".to_owned(),
7579                code: None,
7580                output_tail: e.to_string(),
7581                duration_ms: started.elapsed().as_millis() as u64,
7582                resource_blocked: true,
7583            }],
7584            false,
7585        );
7586    }
7587    let remaining = budget.saturating_sub(started.elapsed());
7588    let (outcomes, retried, timed_out_pids) = body(state, remaining).await;
7589    // A timed-out command's process was only *asked* to die (`kill_on_drop`,
7590    // `start_kill`); confirm it actually has before handing the directory to
7591    // the next acquirer. See `wait_for_timed_out_children_to_die`'s own doc
7592    // for what this can and cannot see.
7593    if !timed_out_pids.is_empty() {
7594        wait_for_timed_out_children_to_die(&timed_out_pids).await;
7595    }
7596    guard.release();
7597    (outcomes, retried)
7598}
7599
7600/// Poll `pids` — commands [`run_commands`] reports as still running when its
7601/// own timeout elapsed — until every one is confirmed gone, or
7602/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
7603///
7604/// Real confirmation where confirmation is possible, not a substitute for
7605/// full process-tree observation: a grandchild the timed-out process spawned
7606/// and that survives independently of it is invisible to a pid check the
7607/// same way it always was, and continuing to observe and collect *that*
7608/// stays a different piece of work with its own owner. This only narrows a
7609/// fixed blind wait into an actual check of the pids this process does know
7610/// about.
7611async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
7612    wait_for_pids_with(
7613        pids,
7614        crate::proc::pid_alive,
7615        LEASE_RELEASE_POLL,
7616        LEASE_RELEASE_MAX_WAIT,
7617    )
7618    .await;
7619}
7620
7621/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
7622/// interval and ceiling supplied by the caller, so the polling *logic* -
7623/// returns as soon as every pid reports dead, gives up at the ceiling
7624/// otherwise - is testable on millisecond durations without asking the real
7625/// OS about a pid at all.
7626async fn wait_for_pids_with<F: Fn(u32) -> bool>(
7627    pids: &[u32],
7628    alive: F,
7629    poll: Duration,
7630    max_wait: Duration,
7631) {
7632    let deadline = Instant::now() + max_wait;
7633    loop {
7634        if pids.iter().all(|&pid| !alive(pid)) {
7635            return;
7636        }
7637        if Instant::now() >= deadline {
7638            return;
7639        }
7640        tokio::time::sleep(poll).await;
7641    }
7642}
7643
7644/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
7645/// admission that it could not even get a verify command to run, as opposed
7646/// to evidence the command actually produced? A caller that would otherwise
7647/// read a resource-blocked outcome as a red command must check this first:
7648/// see [`Runner::gate`], which retries rather than records `Blocked` when
7649/// this is true.
7650fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
7651    outcomes.iter().any(|o| o.resource_blocked)
7652}
7653
7654/// What [`Runner::gate_fix_round`] decided.
7655enum GateFix {
7656    /// The tree changed and `verify.e2e` is still green: run the gate again.
7657    Retry,
7658    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
7659    /// last failure stands and the run ends blocked.
7660    Stop,
7661    /// `verify.e2e` could not run after the fix (magi's own contention):
7662    /// decide nothing now, a later reentry retries.
7663    Defer,
7664}
7665
7666/// Is every red command in `outcomes` an ordinary failure the code could
7667/// explain: it ran, exited non-zero, and said something?
7668///
7669/// A timeout, a spawn failure and a killed process all leave `code` `None`;
7670/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
7671/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
7672/// what the command is stays the gate's business.
7673fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
7674    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
7675    red.peek().is_some()
7676        && red.all(|o| {
7677            !o.resource_blocked
7678                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
7679                && !o.output_tail.trim().is_empty()
7680        })
7681}
7682
7683/// Describe one verify command's outcome for the event log, distinguishing a
7684/// build/link failure — the toolchain never produced a binary to run — from
7685/// an actual test failure, since only the latter is a verdict on the patch.
7686fn e2e_outcome_label(o: &CommandOutcome) -> String {
7687    if o.ok() {
7688        return "pass".to_owned();
7689    }
7690    let reason = if o.build_failed() {
7691        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
7692    } else {
7693        format!("FAIL ({:?})", o.code)
7694    };
7695    format!("{reason}\n{}", tail(&o.output_tail, EVENT_OUTPUT_TAIL))
7696}
7697
7698/// Run `verify.e2e`, retrying once if the first attempt could not build or
7699/// link — a build/link failure is frequently a race against a shared
7700/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
7701/// `verify` event per command, tagged with `context` (normally `"round N"`)
7702/// so the two call sites that need this — the ordinary per-round leg in
7703/// `review_loop`, and the deferred catch-up run `stop_reviewing` makes before
7704/// it will ever call a round green — read identically in the event log.
7705async fn run_e2e_with_retry(
7706    state: &mut RunState,
7707    shell: &[String],
7708    commands: &[String],
7709    worktree: &Path,
7710    timeout: Duration,
7711    context: &str,
7712) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
7713    let (mut e2e, mut timed_out_pids) = run_commands(
7714        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
7715    )
7716    .await;
7717    for o in &e2e {
7718        state.event(
7719            "verify",
7720            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
7721        );
7722    }
7723    // A build/link failure is not a verdict on the patch — it is frequently a
7724    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
7725    // one retry before letting a red like that decide the round.
7726    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
7727    if verify_retried {
7728        state.event(
7729            "verify",
7730            format!(
7731                "{context}: verify could not build/link, not a test result — retrying once \
7732                 before concluding"
7733            ),
7734        );
7735        let retried = run_commands(
7736            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
7737        )
7738        .await;
7739        e2e = retried.0;
7740        // Both attempts' timeouts matter, not just the last one: the first
7741        // attempt's descendants may still be alive alongside the retry's.
7742        timed_out_pids.extend(retried.1);
7743        for o in &e2e {
7744            state.event(
7745                "verify",
7746                format!(
7747                    "{context}: retry `{}` -> {}",
7748                    o.command,
7749                    e2e_outcome_label(o)
7750                ),
7751            );
7752        }
7753    }
7754    (e2e, verify_retried, timed_out_pids)
7755}
7756
7757/// Run configured shell commands in `cwd`, in order. The second element is
7758/// the pid of every command that hit `timeout` and was still running when
7759/// this stopped waiting on it (best-effort: `None` when the platform did not
7760/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
7761/// that releases a shared resource afterward needs to know.
7762///
7763/// Records `task` into [`RunState::active`] at every command boundary
7764/// (`RunState::task_command`) and clears it once the whole list has run
7765/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
7766/// for minutes with no seat and no output of its own to show for it (see
7767/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
7768/// apart from "not yet run" without this), and this is the only place that
7769/// knows which command is running right now and how many are left. Three
7770/// saves per command — start, not per second — matching the same "only at a
7771/// boundary" rule [`wave`] already follows for seats.
7772#[allow(clippy::too_many_arguments)]
7773async fn run_commands(
7774    state: &mut RunState,
7775    node: &str,
7776    task: &str,
7777    attempt: usize,
7778    shell: &[String],
7779    commands: &[String],
7780    cwd: &Path,
7781    timeout: Duration,
7782) -> (Vec<CommandOutcome>, Vec<u32>) {
7783    if commands.is_empty() {
7784        // Nothing to mark as running and nothing to clear — an empty list
7785        // means "not configured", and touching `active` (or the disk) over
7786        // that would be a write for every round of a repo with no
7787        // `verify.e2e` / `verify.gate` commands at all.
7788        return (Vec::new(), Vec::new());
7789    }
7790    let mut out = Vec::new();
7791    let mut timed_out_pids = Vec::new();
7792    let total = commands.len();
7793    for (idx, command) in commands.iter().enumerate() {
7794        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
7795        if let Err(e) = state.save() {
7796            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
7797        }
7798        let started = Instant::now();
7799        let mut cmd = tokio::process::Command::new(&shell[0]);
7800        cmd.quiet();
7801        cmd.args(&shell[1..])
7802            .arg(command)
7803            .current_dir(cwd)
7804            .stdin(std::process::Stdio::null())
7805            .stdout(std::process::Stdio::piped())
7806            .stderr(std::process::Stdio::piped())
7807            .kill_on_drop(true);
7808        let spawned = cmd.spawn();
7809        let (code, body) = match spawned {
7810            Ok(child) => {
7811                // Captured before the child is consumed below: `kill_on_drop`
7812                // only *asks* the process to die when the timeout branch
7813                // drops it, and the pid is the only way anyone downstream can
7814                // later check whether that request actually took.
7815                let pid = child.id();
7816                match tokio::time::timeout(timeout, child.wait_with_output()).await {
7817                    Ok(Ok(o)) => {
7818                        let mut body = String::from_utf8_lossy(&o.stdout).into_owned();
7819                        body.push_str(&String::from_utf8_lossy(&o.stderr));
7820                        (o.status.code(), body)
7821                    }
7822                    Ok(Err(e)) => (None, format!("failed to run: {e}")),
7823                    Err(_) => {
7824                        if let Some(pid) = pid {
7825                            timed_out_pids.push(pid);
7826                        }
7827                        (None, format!("timed out after {}s", timeout.as_secs()))
7828                    }
7829                }
7830            }
7831            Err(e) => (None, format!("failed to spawn `{}`: {e}", shell[0])),
7832        };
7833        out.push(CommandOutcome {
7834            command: command.clone(),
7835            code,
7836            output_tail: tail(&body, OUTPUT_TAIL),
7837            duration_ms: started.elapsed().as_millis() as u64,
7838            resource_blocked: false,
7839        });
7840    }
7841    state.task_finished(task);
7842    if let Err(e) = state.save() {
7843        tracing::warn!("could not persist the end of {task}: {e:#}");
7844    }
7845    (out, timed_out_pids)
7846}
7847
7848/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
7849/// section (`report::run`) and in the `merge` event this node records — for
7850/// the operator to run by hand.
7851///
7852/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
7853/// branch whose ruleset forbids merge commits (GitHub's "must not contain
7854/// merge commits", or "require linear history") rejects the push a `--no-ff`
7855/// merge would produce, which is exactly the guidance this function replaces.
7856/// `message`'s first line becomes the squash commit's subject, matching the
7857/// note `report::run` prints alongside this command — see that function for
7858/// why an explicit subject is not optional there.
7859fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
7860    let repo = repo.display();
7861    match style {
7862        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
7863        MergeStyle::Squash => {
7864            // The subject sits inside double quotes, and a title an agent
7865            // wrote may carry the characters that break out of them.
7866            let subject = message
7867                .lines()
7868                .next()
7869                .unwrap_or(branch)
7870                .replace(['\\', '"', '$', '`'], "");
7871            format!(
7872                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
7873            )
7874        }
7875        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
7876    }
7877}
7878
7879/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
7880/// under the hood, rejects a `title` over 256 characters and the whole
7881/// command fails — no PR at all, for a run whose body was otherwise fine
7882/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
7883/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
7884/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
7885/// this bound. It is a margin, not a guarantee — a title packed
7886/// with multi-unit characters could still in principle land close to the
7887/// edge, but a real task title's occasional emoji or accented letter fits
7888/// comfortably inside it.
7889const PR_TITLE_MAX: usize = 240;
7890
7891/// A pull request title from the opening line of `text`, or `None` when that
7892/// line is not English (GitHub text is) or has no letters.
7893///
7894/// A line within `max` is kept as is. A longer one is cut at the end of its
7895/// first sentence when that falls inside `max`, else at a word boundary with a
7896/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
7897/// make every merely-truncated title look non-English). The language check
7898/// runs on the kept text before any mark is added, so only what GitHub will
7899/// show is judged: an English opening followed by non-ASCII far past the cut
7900/// still passes.
7901fn english_title(text: &str, max: usize) -> Option<String> {
7902    let line = queue::first_line(text)?;
7903    let chars: Vec<char> = line.chars().collect();
7904    let (kept, mark) = if chars.len() <= max {
7905        (line.to_owned(), "")
7906    } else if let Some(end) = sentence_end(&chars, max) {
7907        (chars[..end].iter().collect::<String>(), "")
7908    } else {
7909        let room = max.saturating_sub(3);
7910        // Cut at the last space inside the room; when the char just past the
7911        // room is a space the room already ends on a word.
7912        let cut = if chars[room].is_whitespace() {
7913            room
7914        } else {
7915            chars[..room]
7916                .iter()
7917                .rposition(|c| c.is_whitespace())
7918                .unwrap_or(room)
7919        };
7920        let head: String = chars[..cut].iter().collect();
7921        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
7922        (head.to_owned(), "...")
7923    };
7924    if kept.is_empty() || !kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic()) {
7925        return None;
7926    }
7927    Some(format!("{kept}{mark}"))
7928}
7929
7930/// The char length of the first sentence of `chars` when it ends within `max`
7931/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
7932/// abbreviations so `e.g. foo` does not end a title early.
7933fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
7934    const MIN: usize = 20;
7935    for i in MIN..max.min(chars.len()) {
7936        if !matches!(chars[i], '.' | '!' | '?') {
7937            continue;
7938        }
7939        let Some(&next) = chars.get(i + 1) else {
7940            continue;
7941        };
7942        if !next.is_whitespace() {
7943            continue;
7944        }
7945        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
7946        if after.is_some_and(|c| c.is_ascii_lowercase()) {
7947            continue;
7948        }
7949        let word: String = chars[..i]
7950            .iter()
7951            .rev()
7952            .take_while(|c| !c.is_whitespace())
7953            .collect::<Vec<_>>()
7954            .into_iter()
7955            .rev()
7956            .collect();
7957        let word = word.to_ascii_lowercase();
7958        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
7959            continue;
7960        }
7961        let end = chars[..i]
7962            .iter()
7963            .rposition(|c| !c.is_whitespace())
7964            .map_or(i, |p| p + 1);
7965        return Some(end);
7966    }
7967    None
7968}
7969
7970/// What `merge = "pr"` (and the merge commit of the other modes) says about a
7971/// change: a title and a body describing what was *implemented*, not the task
7972/// that asked for it. A task reads as a request; a reader of the merged
7973/// history wants the change.
7974struct PrMessage {
7975    title: String,
7976    body: String,
7977}
7978
7979impl PrMessage {
7980    /// Title, blank line, body. The first line is the squash/merge commit
7981    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
7982    /// has to stay one sensible line.
7983    fn commit_message(&self) -> String {
7984        format!("{}\n\n{}", self.title, self.body)
7985    }
7986}
7987
7988/// The text after a leading `TITLE:` (any case) on `line`.
7989fn title_marker(line: &str) -> Option<&str> {
7990    let line = line.trim();
7991    let head = line.get(..6)?;
7992    head.eq_ignore_ascii_case("title:")
7993        .then(|| line[6..].trim())
7994}
7995
7996/// The implementer's own one-line title: the `TITLE:` line the implement
7997/// prompt asks for at the top of its SUMMARY. Candidate commits are all
7998/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
7999/// source, and a title that says as much is refused here too.
8000fn summary_title(summary: &str) -> Option<String> {
8001    let first = summary.lines().find(|l| !l.trim().is_empty())?;
8002    let raw = title_marker(first)?;
8003    if raw.is_empty() {
8004        return None;
8005    }
8006    let title = queue::title_from(raw, PR_TITLE_MAX);
8007    let lower = title.to_ascii_lowercase();
8008    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
8009        return None;
8010    }
8011    Some(title)
8012}
8013
8014/// How `open_review`'s instruction begins; see [`landing_title`].
8015const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
8016
8017/// Marker `open_review` gives a candidate that nothing in the roster wrote.
8018const EXISTING_BRANCH: &str = "(existing branch)";
8019
8020/// Does this run review work that already existed, rather than implement a
8021/// task? Runs recorded before `reviewed_commits` existed carry only the
8022/// candidate marker.
8023fn is_review_run(state: &RunState) -> bool {
8024    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
8025}
8026
8027/// The title of a review-only run: the subject of the oldest commit under
8028/// review. Later commits are usually fixups, and `instruction` is the review
8029/// prompt, which says nothing about the change. GitHub text is English, so a
8030/// non-ASCII or blank subject yields `None` and the caller's neutral title.
8031fn review_title(state: &RunState) -> Option<String> {
8032    english_subject(state.reviewed_commits.as_ref()?.first()?)
8033}
8034
8035/// `raw` as a pull request title, or `None` when it is blank, not English
8036/// (GitHub text is), or one of magi's own candidate commit subjects.
8037fn english_subject(raw: &str) -> Option<String> {
8038    let raw = raw.trim();
8039    if raw.is_empty() || !raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic()) {
8040        return None;
8041    }
8042    let title = queue::title_from(raw, PR_TITLE_MAX);
8043    let lower = title.to_ascii_lowercase();
8044    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
8045        return None;
8046    }
8047    Some(title)
8048}
8049
8050/// What a review-only run's branch says about itself, read at the moment the
8051/// pull request is opened.
8052#[derive(Debug, Clone, PartialEq, Eq)]
8053struct BranchFacts {
8054    /// `(subject, body)` of each commit, oldest first.
8055    commits: Vec<(String, String)>,
8056    /// Trimmed `git diff --stat`.
8057    stat: String,
8058}
8059
8060/// Longest diff stat shown: this many file lines plus the summary line.
8061const STAT_FILE_LINES: usize = 25;
8062/// Cap on the commit list, well inside GitHub's 65536-character body limit.
8063const COMMITS_MAX_CHARS: usize = 20_000;
8064
8065/// Read the commits and diff stat of `base..branch`. `None` when git cannot
8066/// say or finds nothing, so the caller falls back to what the run recorded.
8067async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
8068    let commits = git::commit_log(repo, base, branch).await.ok()?;
8069    if commits.is_empty() {
8070        return None;
8071    }
8072    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
8073    let lines: Vec<&str> = stat.lines().collect();
8074    let stat = if lines.len() > STAT_FILE_LINES + 1 {
8075        let omitted = lines.len() - 1 - STAT_FILE_LINES;
8076        let more = format!(" ... {omitted} more file(s)");
8077        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
8078        kept.push(&more);
8079        kept.push(lines[lines.len() - 1]);
8080        kept.join("\n")
8081    } else {
8082        lines.join("\n")
8083    };
8084    Some(BranchFacts { commits, stat })
8085}
8086
8087/// Defang what would break the surrounding markdown: a closing `</details>`
8088/// and a code fence.
8089fn markdown_safe(text: &str) -> String {
8090    text.replace("</details>", "&lt;/details&gt;")
8091        .replace("\x60\x60\x60", "~~~")
8092}
8093
8094fn neutral_title(state: &RunState, winner: char) -> String {
8095    format!(
8096        "chore: land candidate {} of run {}",
8097        winner.to_ascii_uppercase(),
8098        state.id
8099    )
8100}
8101
8102/// The pull request title to hand to `land::merge_subject`. A review-only run
8103/// opened by an earlier build titled its pull request with the review prompt;
8104/// that title is dropped (empty, so the fallback applies) rather than landed.
8105/// Any other title, including an operator's rename, passes through untouched,
8106/// and so does every title of a run that implements a task.
8107pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
8108    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
8109        ""
8110    } else {
8111        pr_title
8112    }
8113}
8114
8115/// What the squash subject falls back to when the pull request title is empty
8116/// or candidate-shaped: for a review-only run the derived title, never the
8117/// review prompt held in `instruction`.
8118pub fn landing_subject_source(state: &RunState) -> String {
8119    if is_review_run(state) {
8120        let winner = state.candidates.first().map_or('A', |c| c.label);
8121        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
8122    }
8123    state.instruction.clone()
8124}
8125
8126/// `summary` without its `TITLE:` line, which the pull request title already
8127/// carries.
8128fn summary_without_title(summary: &str) -> String {
8129    let mut lines = summary.trim().lines().peekable();
8130    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
8131        lines.next();
8132    }
8133    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
8134}
8135
8136/// The pull request title and body for the winning candidate.
8137///
8138/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
8139/// the task's own opening line via [`queue::title_from`] when there is none.
8140/// `state.instruction` can open with blank lines (`task_text` only rejects a
8141/// body that is blank *entirely*), which `title_from` skips.
8142///
8143/// Body: the implementer's summary and the fixer's notes, then — when the
8144/// winning review round was not clean — the findings still open and whatever
8145/// the fixer declined, so `merge = "pr"` hands the reader the same material
8146/// `magi show` does. The task follows inside a collapsed block, and the
8147/// footer repeats the run and candidate as plain tags for a reader holding
8148/// only the merged commit or the PR body.
8149#[cfg(test)]
8150fn pr_message(state: &RunState, winner: char) -> PrMessage {
8151    pr_message_with(state, winner, None)
8152}
8153
8154/// [`pr_message`] with what the branch of a review-only run says about itself.
8155/// `facts` is ignored for a run that implements a task.
8156fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
8157    let summary = state
8158        .candidates
8159        .iter()
8160        .find(|c| c.label == winner)
8161        .map(|c| c.summary.as_str())
8162        .unwrap_or_default();
8163    // The fallback is the operator's own words and may not be English; GitHub
8164    // text always is, so a non-English task gets a neutral title instead.
8165    let review = is_review_run(state);
8166    let title = if review {
8167        facts
8168            .and_then(|f| english_subject(&f.commits.first()?.0))
8169            .or_else(|| review_title(state))
8170            .or_else(|| {
8171                state
8172                    .candidates
8173                    .iter()
8174                    .find(|c| c.label == winner)
8175                    .filter(|c| !c.branch.starts_with("magi/"))
8176                    .and_then(|c| english_subject(&c.branch))
8177            })
8178            .unwrap_or_else(|| neutral_title(state, winner))
8179    } else {
8180        summary_title(summary).unwrap_or_else(|| {
8181            english_title(&state.instruction, PR_TITLE_MAX)
8182                .unwrap_or_else(|| neutral_title(state, winner))
8183        })
8184    };
8185
8186    let mut body = String::new();
8187    let what = summary_without_title(summary);
8188    if !what.is_empty() {
8189        body.push_str("## Summary\n\n");
8190        body.push_str(&what);
8191        body.push_str("\n\n");
8192    }
8193
8194    // The last round is usually a clean verification pass with no fix of its
8195    // own, so every round's notes are read, not just the final one's.
8196    let notes: Vec<(usize, &str)> = state
8197        .reviews
8198        .iter()
8199        .filter_map(|r| {
8200            let n = r.fix.as_ref()?.notes.trim();
8201            (!n.is_empty()).then_some((r.round, n))
8202        })
8203        .collect();
8204    if !notes.is_empty() {
8205        body.push_str("## Review fixes\n\n");
8206        if let [(_, only)] = notes.as_slice() {
8207            body.push_str(only);
8208            body.push_str("\n\n");
8209        } else {
8210            for (round, n) in &notes {
8211                body.push_str(&format!("### Round {round}\n\n{n}\n\n"));
8212            }
8213        }
8214    }
8215    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
8216
8217    let open = state.open_findings();
8218    if !open.is_empty() {
8219        body.push_str("## Open review findings\n\n");
8220        for f in &open {
8221            body.push_str(&format!("- `{}` [{:?}] {}\n", f.id, f.severity, f.title));
8222        }
8223        body.push('\n');
8224    }
8225
8226    if let Some(fix) = fix
8227        && !fix.rejected.is_empty()
8228    {
8229        body.push_str("## Declined by the fixer\n\n");
8230        for r in &fix.rejected {
8231            body.push_str(&format!("- `{}`: {}\n", r.id, r.why));
8232        }
8233        body.push('\n');
8234    }
8235
8236    if review {
8237        // The review prompt is not the task; list what the branch carries.
8238        body.push_str("## Commits under review\n\n");
8239        if let Some(facts) = facts {
8240            let mut left = COMMITS_MAX_CHARS;
8241            for (i, (subject, text)) in facts.commits.iter().enumerate() {
8242                let mut entry = format!("- {}\n", markdown_safe(subject));
8243                for l in markdown_safe(text).lines() {
8244                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
8245                }
8246                if left == 0 {
8247                    body.push_str(&format!(
8248                        "- ... {} more commit(s)\n",
8249                        facts.commits.len() - i
8250                    ));
8251                    break;
8252                }
8253                if entry.len() > left {
8254                    // Even the first commit is cut: one huge body must not
8255                    // push the whole description past GitHub's limit.
8256                    let mut end = left;
8257                    while !entry.is_char_boundary(end) {
8258                        end -= 1;
8259                    }
8260                    entry.truncate(end);
8261                    entry.push_str("\n  ... (truncated)\n");
8262                    left = 0;
8263                } else {
8264                    left -= entry.len();
8265                }
8266                body.push_str(&entry);
8267            }
8268            if !facts.stat.trim().is_empty() {
8269                body.push_str(&format!(
8270                    "\n## Diff stat\n\n```\n{}\n```\n",
8271                    markdown_safe(facts.stat.trim())
8272                ));
8273            }
8274        } else {
8275            match &state.reviewed_commits {
8276                Some(subjects) => {
8277                    for s in subjects {
8278                        body.push_str(&format!("- {}\n", s.trim()));
8279                    }
8280                }
8281                None => {
8282                    // An older run kept only the prompt, with the commit list
8283                    // after its first paragraph.
8284                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
8285                    body.push_str(rest.trim());
8286                    body.push('\n');
8287                }
8288            }
8289        }
8290    } else {
8291        let task = state.instruction.trim();
8292        let task = if task.is_empty() {
8293            "(empty task)"
8294        } else {
8295            task
8296        };
8297        body.push_str(&format!(
8298            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
8299            task.replace("</details>", "&lt;/details&gt;")
8300        ));
8301    }
8302
8303    body.push_str(&format!(
8304        "\n---\nmagi:run/{} magi:candidate-{}\n",
8305        state.id,
8306        winner.to_ascii_lowercase()
8307    ));
8308
8309    // Prompts are advisory; this is the enforced half of the confidentiality
8310    // rule, and it covers the verbatim task in <details> too.
8311    let id = crate::scrub::Identity::current();
8312    PrMessage {
8313        title: crate::scrub::scrub(&title, &id),
8314        body: crate::scrub::scrub(&body, &id),
8315    }
8316}
8317
8318/// The task with what the repository says about the existing work it names
8319/// appended, so an implementer knows what it started from and what it must
8320/// not redo. Unchanged when the task names nothing.
8321fn seeded_instruction(state: &RunState) -> String {
8322    match refs::describe(&state.seeds) {
8323        Some(facts) => format!(
8324            "{}\n\n# Existing work the task refers to\n\n{facts}\n\n\
8325             Candidates start from the unmerged branch named above, when there \
8326             is one, and carry any unmerged commit named by sha as a \
8327             cherry-pick. Check that this is what the task meant before \
8328             building on it.",
8329            state.instruction
8330        ),
8331        None => state.instruction.clone(),
8332    }
8333}
8334
8335/// Does the winner have no commits ahead of the base it would land on?
8336/// Any failure to find out reads as "not empty": the merge then behaves as it
8337/// always did rather than refusing on a guess.
8338async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
8339    let base = &state.base_branch;
8340    let mut against = base.clone();
8341    if mode == MergeMode::Pr {
8342        // A pull request lands on the remote's base, never the local branch
8343        // of the same name: if that cannot be read, "not empty" is the safe
8344        // answer.
8345        let remote = &state.config.merge.remote;
8346        let tracking = format!("{remote}/{base}");
8347        let fetched = git::fetch(repo, remote, base).await;
8348        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
8349            against = tracking;
8350        } else {
8351            return false;
8352        }
8353    }
8354    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
8355}
8356
8357/// Why nothing was opened for an empty winner, with what the task's own
8358/// references resolved to.
8359fn empty_candidate_detail(state: &RunState, base: &str) -> String {
8360    let mut detail = format!(
8361        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
8362         nothing to open a pull request for"
8363    );
8364    match refs::describe(&state.seeds) {
8365        Some(facts) => detail.push_str(&format!("\nReferences in the task:\n{facts}")),
8366        None => detail.push_str(
8367            "\nThe task names no existing branch or commit; if it means to land work \
8368             that lives elsewhere, name the branch (magi/<run>/<label>) or the sha.",
8369        ),
8370    }
8371    detail
8372}
8373
8374/// What the `Pr` merge does once it knows whether the branch already has an
8375/// open pull request.
8376#[derive(Debug, PartialEq, Eq)]
8377enum PrPlan {
8378    Create,
8379    Adopt { url: String, title: String },
8380    Stop(String),
8381}
8382
8383/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
8384/// a failed lookup -> stop with the real reason. Never guesses.
8385fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
8386    match found {
8387        Ok(land::OpenPr::None) => PrPlan::Create,
8388        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
8389        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
8390            "several open pull requests exist for this branch, not picking one: {}",
8391            urls.join(" ")
8392        )),
8393        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
8394    }
8395}
8396
8397/// `gh pr create`, returning the PR url.
8398async fn gh_pr_create(
8399    cwd: &Path,
8400    base: &str,
8401    head: &str,
8402    title: &str,
8403    body: &str,
8404) -> Result<String> {
8405    let out = tokio::process::Command::new("gh")
8406        .args([
8407            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
8408        ])
8409        .current_dir(cwd)
8410        .quiet()
8411        .stdin(std::process::Stdio::null())
8412        .output()
8413        .await
8414        .context("spawn gh")?;
8415    if out.status.success() {
8416        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
8417    } else {
8418        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
8419    }
8420}
8421
8422/// Tear a run's worktrees and branches down.
8423///
8424/// `home` is where the updated `run.json` is saved (via
8425/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
8426/// a housekeeping pass already has its own honest `home` handed to it, and
8427/// falling through to the global here would write back through whichever
8428/// directory some other process or test pinned into that `OnceLock` first,
8429/// not the one the caller actually resolved its `runs` and `state` from.
8430pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
8431    let repo = state.repo.clone();
8432    let root = state.worktree_root();
8433    let winner = state.tally.as_ref().map(|t| t.winner);
8434    let mut removed = Vec::new();
8435
8436    for i in 0..state.candidates.len() {
8437        let c = state.candidates[i].clone();
8438        let is_winner = Some(c.label) == winner;
8439        if is_winner && !drop_winner {
8440            continue;
8441        }
8442        if c.worktree.exists() {
8443            git::worktree_remove(&repo, &c.worktree).await.ok();
8444            removed.push(c.worktree.to_string_lossy().into_owned());
8445        }
8446        // A branch handed to a later run (and its pull request) is not this
8447        // run's to delete.
8448        let handed_over = state.released_branches.contains(&c.branch);
8449        if !handed_over && git::branch_exists(&repo, &c.branch).await.unwrap_or(false) {
8450            git::branch_delete(&repo, &c.branch).await.ok();
8451            removed.push(c.branch.clone());
8452        }
8453        state.candidates[i].folded = true;
8454    }
8455
8456    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
8457        let path = name.path();
8458        let keep = !drop_winner
8459            && winner.is_some_and(|w| {
8460                path.file_name()
8461                    .is_some_and(|n| n == format!("cand-{w}").as_str())
8462            });
8463        if keep {
8464            continue;
8465        }
8466        git::worktree_remove(&repo, &path).await.ok();
8467        removed.push(path.to_string_lossy().into_owned());
8468    }
8469
8470    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
8471    // judge worktrees, so once the loop above has cleared all of them out,
8472    // the parent is a bare directory nobody else was ever going to remove -
8473    // git only ever managed what was inside it. Left alone, one of these
8474    // accumulates per fully-folded run; the operator's own machine had 74.
8475    // `remove_if_empty` re-checks rather than assuming: a run whose winner
8476    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
8477    // so does anything a run never claimed that happens to share the bay.
8478    remove_if_empty(&root);
8479
8480    if state.enabled_worktree_config && drop_winner {
8481        // A release, not a raw disable: some sibling run in this repository
8482        // may still hold its own reference (see `git::acquire_worktree_config`),
8483        // and only the last release actually turns the setting back off.
8484        git::release_worktree_config(&repo).await.ok();
8485        state.enabled_worktree_config = false;
8486    }
8487    state.save_under(home)?;
8488    Ok(removed)
8489}
8490
8491/// Remove `dir` if it exists and has nothing in it.
8492///
8493/// Best-effort and silent by design: a directory that is not empty (a run
8494/// whose winner is still parked there, a stray file some other process left)
8495/// is exactly the case this must refuse, and a directory that is already gone
8496/// is not a failure worth reporting either. `std::fs::remove_dir` itself
8497/// already refuses a non-empty directory, so the emptiness check below is
8498/// belt, not suspenders - it is what keeps this from ever attempting the
8499/// removal in the case that matters, rather than trusting `remove_dir`'s
8500/// error path to have no side effects if it ever changed.
8501fn remove_if_empty(dir: &Path) {
8502    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
8503        std::fs::remove_dir(dir).ok();
8504    }
8505}
8506
8507/// Severity of the worst open finding in the last review round, for reporting.
8508pub fn worst_open(state: &RunState) -> Option<Severity> {
8509    state
8510        .reviews
8511        .last()?
8512        .reviews
8513        .iter()
8514        .flat_map(|r| r.findings.iter())
8515        .map(|f| f.severity)
8516        .max()
8517}
8518
8519#[cfg(test)]
8520mod tests {
8521    #[test]
8522    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
8523        let leaked = vec!["chore(deps): update a crate".to_owned()];
8524        let own = "fix(daemon): apply a chosen action";
8525        assert!(should_retitle("", own, &leaked));
8526        assert!(should_retitle(
8527            &format!("{REVIEW_PROMPT_OPENING} `x`"),
8528            own,
8529            &leaked
8530        ));
8531        assert!(should_retitle(
8532            "chore: land candidate A of run 1",
8533            own,
8534            &leaked
8535        ));
8536        assert!(should_retitle(
8537            "magi: candidate A (uncommitted work)",
8538            own,
8539            &leaked
8540        ));
8541        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
8542        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
8543        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
8544    }
8545
8546    #[test]
8547    fn pr_merge_plan_creates_adopts_or_stops() {
8548        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
8549        assert_eq!(
8550            pr_merge_plan(Ok(land::OpenPr::One {
8551                url: "u".into(),
8552                title: "t".into()
8553            })),
8554            PrPlan::Adopt {
8555                url: "u".into(),
8556                title: "t".into()
8557            }
8558        );
8559        let PrPlan::Stop(many) =
8560            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
8561        else {
8562            panic!("many must stop");
8563        };
8564        assert!(many.contains('a') && many.contains('b'));
8565        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
8566            panic!("a failed lookup must stop");
8567        };
8568        assert!(err.contains("bad token"));
8569    }
8570
8571    use super::*;
8572    use crate::run::GateStatus;
8573    use std::collections::BTreeMap;
8574    use std::time::Duration;
8575
8576    fn conductor() -> AgentSpec {
8577        AgentSpec {
8578            id: "conductor".to_owned(),
8579            kind: crate::config::AgentKind::Command,
8580            model: None,
8581            command: vec!["true".to_owned()],
8582            extra_args: Vec::new(),
8583            env: BTreeMap::new(),
8584            prompt_delivery: None,
8585        }
8586    }
8587
8588    fn spec(id: &str) -> AgentSpec {
8589        AgentSpec {
8590            id: id.to_owned(),
8591            kind: crate::config::AgentKind::Command,
8592            model: None,
8593            command: vec!["true".to_owned()],
8594            extra_args: Vec::new(),
8595            env: BTreeMap::new(),
8596            prompt_delivery: None,
8597        }
8598    }
8599
8600    fn ids(xs: &[&str]) -> BTreeSet<String> {
8601        xs.iter().map(|s| (*s).to_owned()).collect()
8602    }
8603
8604    #[test]
8605    fn pick_successor_skips_an_agent_another_seat_holds() {
8606        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
8607        let roster = [spec("a"), spec("b"), spec("c")];
8608        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
8609        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
8610    }
8611
8612    #[test]
8613    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
8614        // The other seat started on c but was handed to d; c is free again.
8615        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
8616        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
8617        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
8618        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
8619        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
8620    }
8621
8622    #[test]
8623    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
8624        let roster = [spec("a"), spec("b")];
8625        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
8626        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8627        let carried = ids(&["b"]);
8628        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
8629        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8630    }
8631
8632    #[test]
8633    fn pick_successor_returns_none_without_any_untried_successor() {
8634        let roster = [spec("a"), spec("b")];
8635        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
8636        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
8637        let carried = ids(&["a"]);
8638        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
8639    }
8640
8641    #[test]
8642    fn pick_successor_rescue_avoids_another_seats_occupant() {
8643        // b is a carried failure and free; a is held by the other seat.
8644        let roster = [spec("a"), spec("b"), spec("c")];
8645        let carried = ids(&["b", "c"]);
8646        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
8647        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8648    }
8649
8650    #[test]
8651    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
8652        let roster = [spec("a"), spec("b"), spec("c")];
8653        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
8654        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
8655    }
8656
8657    #[test]
8658    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
8659        let roster = [spec("a"), spec("b"), spec("c")];
8660        let failed = ids(&["a", "b", "c"]);
8661        // Rescue looks at the whole roster, once per id, then runs out.
8662        let mut tried = ids(&["b"]);
8663        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
8664        assert_eq!(first.id, "a");
8665        tried.insert(first.id.clone());
8666        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
8667        assert_eq!(second.id, "c");
8668        tried.insert(second.id.clone());
8669        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
8670    }
8671
8672    #[test]
8673    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
8674        let roster = [spec("a"), spec("b")];
8675        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
8676        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8677    }
8678
8679    #[test]
8680    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
8681        let roster = [spec("a"), spec("b"), spec("c")];
8682        let h = SeatHistory {
8683            failed: ids(&["a"]),
8684            last_ok: Some("b".to_owned()),
8685            last_fail: None,
8686        };
8687        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
8688        // A last answerer that left the roster, or later failed, is ignored.
8689        let gone = SeatHistory {
8690            last_ok: Some("zzz".to_owned()),
8691            ..h.clone()
8692        };
8693        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
8694        let failed = SeatHistory {
8695            failed: ids(&["a", "b"]),
8696            last_ok: Some("b".to_owned()),
8697            last_fail: None,
8698        };
8699        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
8700    }
8701
8702    #[test]
8703    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
8704        let first = SeatState::new("review-1", "alpha", 7);
8705        let next = handover_seat("review-1", "gamma", 7);
8706        assert_ne!(first.claude_session, next.claude_session);
8707    }
8708
8709    #[test]
8710    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
8711        let mut state = state_with_summary("x", "y");
8712        let a = handover_seat("review-1", "beta", state.next_seat_seed());
8713        let b = handover_seat("review-1", "beta", state.next_seat_seed());
8714        assert_ne!(a.claude_session, b.claude_session);
8715    }
8716
8717    #[test]
8718    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
8719        let roster = [spec("a"), spec("b")];
8720        let h = SeatHistory {
8721            failed: ids(&["a", "b"]),
8722            ..SeatHistory::default()
8723        };
8724        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
8725        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
8726        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
8727    }
8728
8729    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
8730    // fallback loop depends on to terminate: it must walk forward from the
8731    // seat's own position, never restart at the front of the roster, and it
8732    // must never hand back an id already tried, however many times that id
8733    // happens to appear.
8734
8735    #[test]
8736    fn failure_signature_ignores_numbers_and_paths() {
8737        assert_eq!(
8738            failure_signature("exited with Some(2) and no usable output"),
8739            failure_signature("exited with Some(137) and no usable output")
8740        );
8741        assert_eq!(
8742            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
8743            failure_signature("cannot open /var/x.txt: denied")
8744        );
8745        assert_ne!(failure_signature("boom"), failure_signature("bang"));
8746    }
8747
8748    #[test]
8749    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
8750        let other = FailClass::Other("x".into());
8751        assert!(should_hand_over(None, &FailClass::Quota));
8752        assert!(should_hand_over(Some(&other), &FailClass::Quota));
8753        assert!(should_hand_over(
8754            Some(&FailClass::Timeout),
8755            &FailClass::Timeout
8756        ));
8757        assert!(should_hand_over(None, &other));
8758        assert!(!should_hand_over(Some(&other), &other));
8759        assert!(should_hand_over(
8760            Some(&other),
8761            &FailClass::Other("y".into())
8762        ));
8763        // A quota or timeout in between ends the run of identical failures.
8764        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
8765        assert!(should_hand_over(Some(&FailClass::Quota), &other));
8766    }
8767
8768    #[test]
8769    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
8770        let a = SeatState::new("judge-1", "alpha", 7);
8771        let b = handover_seat("judge-1", "beta", 7);
8772        assert_ne!(a.claude_session, b.claude_session);
8773        assert_eq!(b.turns, 0);
8774    }
8775
8776    #[test]
8777    fn a_timeout_is_classified_apart_from_other_failures() {
8778        assert_eq!(
8779            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
8780            Some(FailClass::Timeout)
8781        );
8782        assert!(matches!(
8783            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
8784            Some(FailClass::Other(_))
8785        ));
8786    }
8787
8788    #[test]
8789    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
8790        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
8791        let tried = BTreeSet::from(["beta".to_owned()]);
8792        // beta sits at index 1; the next candidate is gamma, never alpha —
8793        // which is very likely a different candidate slot's own agent.
8794        let next = next_untried_in_roster(&roster, 1, &tried);
8795        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
8796    }
8797
8798    #[test]
8799    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
8800        let roster = vec![spec("alpha"), spec("beta")];
8801        let tried = BTreeSet::from(["beta".to_owned()]);
8802        // beta is the roster's last entry: nothing follows it, and alpha —
8803        // earlier in the roster, almost certainly a different candidate
8804        // slot's own agent — must not be reached by wrapping back to it.
8805        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
8806    }
8807
8808    #[test]
8809    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
8810        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
8811        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
8812        // beta (index 1) and gamma (index 2, the only entry after it) have
8813        // both been tried; alpha (index 0) never has, but it comes before
8814        // beta's own position, so there is nothing further for this seat.
8815        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
8816    }
8817
8818    #[test]
8819    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
8820        let roster = vec![spec("a"), spec("a"), spec("b")];
8821        let tried = BTreeSet::from(["a".to_owned()]);
8822        let next = next_untried_in_roster(&roster, 0, &tried);
8823        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8824    }
8825
8826    #[test]
8827    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
8828        let roster = vec![spec("a"), spec("b")];
8829        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
8830        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
8831    }
8832
8833    #[test]
8834    fn remove_if_empty_only_ever_takes_a_bare_directory() {
8835        let dir = tempfile::tempdir().unwrap();
8836        let bay = dir.path().join("ffff");
8837
8838        // Not there yet: nothing to do, nothing to panic on.
8839        remove_if_empty(&bay);
8840        assert!(!bay.exists());
8841
8842        // Something still inside - the winner's worktree, or a stray file -
8843        // keeps the directory standing.
8844        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
8845        remove_if_empty(&bay);
8846        assert!(bay.exists(), "non-empty directory must survive");
8847
8848        // Once the last entry is gone, so is the directory itself.
8849        std::fs::remove_dir(bay.join("cand-A")).unwrap();
8850        remove_if_empty(&bay);
8851        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
8852    }
8853
8854    // `round_is_clean` is the exact decision this task fixed: a round with a
8855    // seat that never answered must not read the same as a round every seat
8856    // actually reviewed. These are deterministic and process-free by design —
8857    // the equivalent end-to-end check (a real reviewer timing out under a
8858    // live graph run) is a genuine race against wall-clock contention, and a
8859    // spawn slow enough to blow even a generous budget under a loaded test
8860    // run must not turn this specific regression check flaky.
8861
8862    #[test]
8863    fn a_full_panel_that_found_nothing_is_clean() {
8864        assert!(round_is_clean(
8865            0,
8866            true,
8867            2,
8868            2,
8869            0,
8870            IncompleteReviewPolicy::Block
8871        ));
8872    }
8873
8874    #[test]
8875    fn a_missing_seat_is_never_clean_under_the_default_policy() {
8876        assert!(!round_is_clean(
8877            0,
8878            true,
8879            1,
8880            2,
8881            0,
8882            IncompleteReviewPolicy::Block
8883        ));
8884    }
8885
8886    #[test]
8887    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
8888        assert!(!round_is_clean(
8889            1,
8890            true,
8891            1,
8892            2,
8893            0,
8894            IncompleteReviewPolicy::Warn
8895        ));
8896    }
8897
8898    #[test]
8899    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
8900        assert!(round_is_clean(
8901            0,
8902            true,
8903            1,
8904            2,
8905            0,
8906            IncompleteReviewPolicy::Warn
8907        ));
8908    }
8909
8910    #[test]
8911    fn a_full_panel_with_an_open_finding_is_not_clean() {
8912        assert!(!round_is_clean(
8913            1,
8914            true,
8915            2,
8916            2,
8917            0,
8918            IncompleteReviewPolicy::Block
8919        ));
8920    }
8921
8922    #[test]
8923    fn a_full_panel_with_a_red_e2e_is_not_clean() {
8924        assert!(!round_is_clean(
8925            0,
8926            false,
8927            2,
8928            2,
8929            0,
8930            IncompleteReviewPolicy::Block
8931        ));
8932    }
8933
8934    // The stall this task closes: under the default `block` policy, a seat
8935    // missing only because it was rate limited must not force a wait for a
8936    // session limit that will not lift by the next round. `round_is_clean`
8937    // is where that quorum carve-out lives; the review loop around it never
8938    // changes what a reviewer's vote or a finding's severity means.
8939
8940    #[test]
8941    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
8942        // 1 of 2 answered, and the one missing was quota'd — the exact
8943        // "review-2 rate limited (quota)" shape from the field report.
8944        assert!(round_is_clean(
8945            0,
8946            true,
8947            1,
8948            2,
8949            1,
8950            IncompleteReviewPolicy::Block
8951        ));
8952    }
8953
8954    #[test]
8955    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
8956        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
8957        // not a quota loss (`quota_missing` stays 0) — worth another try.
8958        assert!(!round_is_clean(
8959            0,
8960            true,
8961            1,
8962            2,
8963            0,
8964            IncompleteReviewPolicy::Block
8965        ));
8966    }
8967
8968    #[test]
8969    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
8970        assert!(!round_is_clean(
8971            1,
8972            true,
8973            1,
8974            2,
8975            1,
8976            IncompleteReviewPolicy::Block
8977        ));
8978        assert!(!round_is_clean(
8979            0,
8980            false,
8981            1,
8982            2,
8983            1,
8984            IncompleteReviewPolicy::Block
8985        ));
8986    }
8987
8988    #[test]
8989    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
8990        // Every seat quota'd, nobody answered: there is no panel to decide
8991        // on, so this must fall through to the existing block-and-retry
8992        // fallback rather than call an unreviewed patch clean.
8993        assert!(!round_is_clean(
8994            0,
8995            true,
8996            0,
8997            2,
8998            2,
8999            IncompleteReviewPolicy::Block
9000        ));
9001    }
9002
9003    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
9004        CommandOutcome {
9005            command: "test".to_owned(),
9006            code,
9007            output_tail: String::new(),
9008            duration_ms: 0,
9009            resource_blocked,
9010        }
9011    }
9012
9013    #[test]
9014    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
9015        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
9016        assert!(
9017            !verify_inconclusive(&[outcome(Some(1), false)]),
9018            "an ordinary failure is still evidence about the patch"
9019        );
9020        assert!(verify_inconclusive(&[outcome(None, true)]));
9021        assert!(
9022            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
9023            "one inconclusive outcome taints the whole batch"
9024        );
9025        assert!(!verify_inconclusive(&[]));
9026    }
9027
9028    #[tokio::test]
9029    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
9030        // Alive for the first two checks, then dead - confirms the loop
9031        // actually re-polls rather than deciding once and sleeping out the
9032        // ceiling regardless.
9033        let calls = std::sync::atomic::AtomicUsize::new(0);
9034        let started = Instant::now();
9035        wait_for_pids_with(
9036            &[123],
9037            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
9038            Duration::from_millis(5),
9039            Duration::from_secs(5),
9040        )
9041        .await;
9042        assert!(
9043            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
9044            "must keep checking rather than deciding on the first answer"
9045        );
9046        assert!(
9047            started.elapsed() < Duration::from_secs(1),
9048            "must return the moment it is confirmed dead, not wait out the ceiling"
9049        );
9050    }
9051
9052    #[tokio::test]
9053    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
9054        let started = Instant::now();
9055        wait_for_pids_with(
9056            &[123],
9057            |_| true, // never reports dead
9058            Duration::from_millis(5),
9059            Duration::from_millis(30),
9060        )
9061        .await;
9062        let elapsed = started.elapsed();
9063        assert!(
9064            elapsed >= Duration::from_millis(30),
9065            "must not give up before its own ceiling: {elapsed:?}"
9066        );
9067        assert!(
9068            elapsed < Duration::from_secs(1),
9069            "must not wait past its own ceiling either: {elapsed:?}"
9070        );
9071    }
9072
9073    #[tokio::test]
9074    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
9075        let started = Instant::now();
9076        wait_for_pids_with(
9077            &[],
9078            |_| true,
9079            Duration::from_secs(5),
9080            Duration::from_secs(5),
9081        )
9082        .await;
9083        assert!(
9084            started.elapsed() < Duration::from_millis(200),
9085            "an empty pid list has nothing to confirm"
9086        );
9087    }
9088
9089    // `review_conclusion` is the exact decision the review hand-off task
9090    // fixed: a round budget spent (or a tree that stopped moving) must not
9091    // collapse into `Blocked` regardless of what verification actually
9092    // said. Deterministic and process-free for the same reason the
9093    // `round_is_clean` family above is.
9094    fn review_round(
9095        clean: bool,
9096        blocking: usize,
9097        answered: usize,
9098        expected: usize,
9099        progressed: bool,
9100        e2e_ok: bool,
9101    ) -> ReviewRound {
9102        ReviewRound {
9103            round: 1,
9104            head: "h".to_owned(),
9105            verified_head: None,
9106            verified_at: None,
9107            reviews: Vec::new(),
9108            e2e: vec![CommandOutcome {
9109                command: "test".to_owned(),
9110                code: Some(if e2e_ok { 0 } else { 1 }),
9111                output_tail: String::new(),
9112                duration_ms: 0,
9113                resource_blocked: false,
9114            }],
9115            verify_retried: false,
9116            e2e_deferred: false,
9117            e2e_defer_reason: None,
9118            fix: None,
9119            blocking,
9120            answered,
9121            expected,
9122            clean,
9123            progressed,
9124            vote_split: false,
9125            reconsideration: Vec::new(),
9126            verdict: None,
9127        }
9128    }
9129
9130    #[test]
9131    fn review_conclusion_is_none_when_nothing_has_run() {
9132        assert_eq!(review_conclusion(&[], 3), None);
9133    }
9134
9135    #[test]
9136    fn review_conclusion_is_none_while_rounds_remain() {
9137        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
9138        assert_eq!(review_conclusion(&rounds, 3), None);
9139    }
9140
9141    #[test]
9142    fn review_conclusion_is_gating_once_a_round_is_clean() {
9143        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
9144        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
9145    }
9146
9147    #[test]
9148    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
9149        let rounds = vec![
9150            review_round(false, 1, 2, 2, true, true),
9151            review_round(false, 1, 2, 2, true, true),
9152        ];
9153        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
9154    }
9155
9156    #[test]
9157    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
9158        let rounds = vec![
9159            review_round(false, 1, 2, 2, true, true),
9160            review_round(false, 1, 2, 2, true, false),
9161        ];
9162        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
9163    }
9164
9165    #[test]
9166    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
9167        // Magi never got a command to run against this round's own head — a
9168        // resource-blocked attempt, not a red one — so this must never
9169        // settle on `Blocked` the way a genuine e2e failure would. `None`
9170        // here is what tells `Runner::review_loop` to retry the check
9171        // itself rather than trust this cheap recomputation with a verdict
9172        // it cannot actually produce.
9173        let mut blocked = review_round(false, 1, 2, 2, true, false);
9174        blocked.e2e[0].resource_blocked = true;
9175        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
9176        assert_eq!(review_conclusion(&rounds, 2), None);
9177    }
9178
9179    #[test]
9180    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
9181        // Missing input, not a verified tree — never a hand-off candidate.
9182        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
9183        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
9184    }
9185
9186    #[test]
9187    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
9188        let rounds = vec![
9189            review_round(false, 1, 2, 2, false, true),
9190            review_round(false, 1, 2, 2, false, true),
9191        ];
9192        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
9193    }
9194
9195    fn secs(n: u64) -> Duration {
9196        Duration::from_secs(n)
9197    }
9198
9199    /// A throwaway repo with one commit on `main`, for tests that need `merge`
9200    /// to make real (and, if it runs at all, real*ly fail*) git calls.
9201    fn init_repo(dir: &Path) {
9202        let run = |args: &[&str]| {
9203            let out = std::process::Command::new("git")
9204                .args(args)
9205                .current_dir(dir)
9206                .quiet()
9207                .output()
9208                .expect("spawn git");
9209            assert!(
9210                out.status.success(),
9211                "git {args:?} failed: {}",
9212                String::from_utf8_lossy(&out.stderr)
9213            );
9214        };
9215        run(&["init", "-b", "main"]);
9216        run(&["config", "user.name", "magi test"]);
9217        run(&["config", "user.email", "magi@example.com"]);
9218        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
9219        run(&["add", "-A"]);
9220        run(&["commit", "-m", "init"]);
9221    }
9222
9223    // `settle_questions` is what closes the ghost the phone showed: a run's
9224    // seat asked something, the run then ended, and nothing was left to
9225    // abandon the question it left `open`. `HOME` is a process-wide
9226    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
9227    // first time it runs in the binary — every test below still reaches the
9228    // same directory whichever call won, and each gets its own run id from
9229    // `RunState::new`, so they never collide there.
9230    fn ask_test_home() {
9231        crate::run::pin_test_home();
9232    }
9233
9234    /// A minimal, git-free `Runner` at a given status — `settle_questions`
9235    /// reads nothing else off it.
9236    fn runner_at(status: RunStatus) -> Runner {
9237        let mut state = RunState::new(
9238            PathBuf::from("/nonexistent/repo"),
9239            "main".to_owned(),
9240            "deadbeef".to_owned(),
9241            "task".to_owned(),
9242            Config::default(),
9243        );
9244        state.status = status;
9245        Runner {
9246            state,
9247            roles: ResolvedRoles {
9248                implementers: Vec::new(),
9249                judges: Vec::new(),
9250                reviewers: Vec::new(),
9251                fixer: None,
9252                conductor: conductor(),
9253                implementer_roster: Vec::new(),
9254                judge_roster: Vec::new(),
9255                reviewer_roster: Vec::new(),
9256            },
9257            sem: Arc::new(Semaphore::new(1)),
9258            pause: Pause::new(),
9259            interrupt: Pause::new(),
9260        }
9261    }
9262
9263    /// `park_here` folding in the reason `Pause::park_because` recorded -
9264    /// this is what lets an operator reading a run's events tell an
9265    /// interrupt-driven park from an ordinary shutdown park.
9266    #[test]
9267    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
9268        crate::run::pin_test_home();
9269        let mut runner = runner_at(RunStatus::Implementing);
9270        let interrupt = Pause::new();
9271        runner.watch_interrupt(interrupt.clone());
9272
9273        interrupt.park_because("task a1b2 asked to run first");
9274
9275        assert!(runner.park_here().expect("park_here"));
9276        assert!(runner.state.parked);
9277        let last = runner.state.events.last().expect("a park event");
9278        assert_eq!(last.node, "park");
9279        assert!(
9280            last.message.contains("task a1b2 asked to run first"),
9281            "expected the interrupt reason in {:?}",
9282            last.message
9283        );
9284    }
9285
9286    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
9287    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
9288    /// cleared) must not make a *different* run - one only watching its own,
9289    /// unshared interrupt `Pause` - see itself as parked. If a future change
9290    /// ever collapsed these back into one handle, the interrupt scheduler
9291    /// would park every run for the rest of the daemon's life, not just the
9292    /// one it meant to interrupt.
9293    #[test]
9294    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
9295        crate::run::pin_test_home();
9296        let mut runner = runner_at(RunStatus::Implementing);
9297        let shutdown = Pause::new();
9298        runner.on_pause(shutdown.clone());
9299        let interrupt = Pause::new();
9300        runner.watch_interrupt(interrupt.clone());
9301
9302        // Nobody has asked for anything yet.
9303        assert!(!runner.park_here().expect("park_here"));
9304        assert!(!runner.state.parked);
9305
9306        // Only the interrupt handle fires; the shutdown handle stays clear.
9307        interrupt.park_because("test");
9308        assert!(!shutdown.parked());
9309        assert!(runner.park_here().expect("park_here"));
9310    }
9311
9312    /// The property every prior attempt at this feature failed to pin down:
9313    /// asking a run to park while one of its nodes has a real, in-flight
9314    /// async operation running (an agent call, in production) must not cut
9315    /// that operation short. `park_here` is only ever consulted *between*
9316    /// `execute`'s node calls - see its own doc - so nothing inside a node
9317    /// can observe a park request until the node itself returns. This proves
9318    /// that structurally, with real `tokio` concurrency and a channel
9319    /// handshake (never a sleep, which would only prove "usually", not
9320    /// "cannot"): the "node" below reports that it has genuinely started,
9321    /// and only then is the park requested; the node still has to be told to
9322    /// finish before `park_here` is ever called, exactly mirroring every
9323    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
9324    /// in `execute`.
9325    #[tokio::test]
9326    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
9327        crate::run::pin_test_home();
9328        let mut runner = runner_at(RunStatus::Implementing);
9329        let interrupt = Pause::new();
9330        runner.watch_interrupt(interrupt.clone());
9331
9332        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
9333        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
9334
9335        // Stands in for one node's in-flight agent call: it proves it has
9336        // genuinely started, then blocks - exactly as a spawned CLI process
9337        // does - until told to finish.
9338        let node = async move {
9339            started_tx.send(()).expect("send started");
9340            finish_rx.await.expect("recv finish");
9341            "node finished"
9342        };
9343
9344        let interrupter = async move {
9345            started_rx.await.expect("recv started");
9346            // The call is now genuinely in flight. Ask it to park.
9347            interrupt.park_because("higher-priority task waiting");
9348            // Nothing the node does can observe this yet - there is no
9349            // check inside it, by construction - so let the executor run
9350            // anything pending and then let the node finish on its own.
9351            tokio::task::yield_now().await;
9352            finish_tx.send(()).expect("send finish");
9353        };
9354
9355        let (node_result, ()) = tokio::join!(node, interrupter);
9356        assert_eq!(
9357            node_result, "node finished",
9358            "the in-flight call ran to completion"
9359        );
9360
9361        // Only now, at the boundary the real `execute` would check right
9362        // after this node, does the park take effect.
9363        assert!(runner.park_here().expect("park_here"));
9364        assert!(runner.state.parked);
9365    }
9366
9367    /// A run parked mid-competition carries every field it had accumulated
9368    /// through the exact same disk round-trip an ordinary resume uses -
9369    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
9370    /// Nothing about parking for an interrupt is a special case of that path;
9371    /// this is what proves it rather than assuming it.
9372    #[test]
9373    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
9374        crate::run::pin_test_home();
9375        let mut runner = runner_at(RunStatus::Judging);
9376        // `Runner::resume` re-resolves roles from the saved config, which
9377        // refuses an empty roster - give it the same minimal one `conductor`
9378        // itself uses.
9379        runner.state.config.agents = vec![conductor()];
9380        runner.state.candidates = vec![Candidate {
9381            index: 0,
9382            label: 'A',
9383            agent: "alpha".to_owned(),
9384            branch: "magi/x/A".to_owned(),
9385            worktree: PathBuf::from("/nonexistent/worktree"),
9386            summary: "did the thing".to_owned(),
9387            stat: "1 file changed".to_owned(),
9388            files: 1,
9389            commits: 1,
9390            empty: false,
9391            failed: None,
9392            verified_noop: None,
9393            duration_ms: 1234,
9394            folded: false,
9395        }];
9396        let run_id = runner.state.id.clone();
9397
9398        let interrupt = Pause::new();
9399        runner.watch_interrupt(interrupt.clone());
9400        interrupt.park_because("task c3d4 asked to run first");
9401        assert!(runner.park_here().expect("park_here"));
9402
9403        let resumed = Runner::resume(&run_id).expect("resume");
9404        assert_eq!(resumed.state.candidates.len(), 1);
9405        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
9406        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
9407        assert_eq!(resumed.state.status, runner.state.status);
9408        assert!(
9409            resumed.state.parked,
9410            "still parked until `execute` actually walks the graph again"
9411        );
9412        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
9413    }
9414
9415    /// A fresh open question on `run`, stored and handed back for assertions.
9416    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
9417        let mut q = ask::Question::new(
9418            run.to_owned(),
9419            "implement".to_owned(),
9420            "impl-A".to_owned(),
9421            "Which storage backend should the cache use?".to_owned(),
9422            String::new(),
9423            vec!["SQLite".to_owned(), "Redis".to_owned()],
9424        );
9425        store.put(&mut q).unwrap();
9426        q
9427    }
9428
9429    #[test]
9430    fn a_failed_runs_open_question_is_abandoned() {
9431        ask_test_home();
9432        let store = ask::Questions::open();
9433        let mut runner = runner_at(RunStatus::Failed);
9434        let run = runner.state.id.clone();
9435        let q = ask_open_question(&store, &run);
9436
9437        runner.settle_questions();
9438
9439        let back = store.get(&q.id).unwrap();
9440        assert!(
9441            !back.status.open(),
9442            "the seat that asked died with the run; nobody is left to read an answer"
9443        );
9444        assert!(
9445            back.detail.contains(&run) && back.detail.contains("failed"),
9446            "the reason names what the run became, not just that it is gone: {}",
9447            back.detail
9448        );
9449    }
9450
9451    #[test]
9452    fn a_merged_runs_open_question_is_abandoned_too() {
9453        ask_test_home();
9454        let store = ask::Questions::open();
9455        // A run that finishes cleanly still leaves nobody to read an answer -
9456        // this is not only a failure-path cleanup.
9457        for status in [RunStatus::Merged, RunStatus::Ready] {
9458            let mut runner = runner_at(status);
9459            let run = runner.state.id.clone();
9460            let q = ask_open_question(&store, &run);
9461
9462            runner.settle_questions();
9463
9464            let back = store.get(&q.id).unwrap();
9465            assert!(
9466                !back.status.open(),
9467                "{status:?} run's question must not outlive the run"
9468            );
9469        }
9470    }
9471
9472    #[test]
9473    fn a_still_resumable_runs_open_question_is_left_alone() {
9474        ask_test_home();
9475        let store = ask::Questions::open();
9476        // `Blocked` and `Stalled` can still be resumed — the candidates, the
9477        // review round and the seat sessions are all still on disk — so a
9478        // question asked mid-round may yet get a real answer from a real
9479        // resume. Sweeping it here would be exactly the failure mode this
9480        // whole feature exists to avoid on the other side.
9481        for status in [RunStatus::Blocked, RunStatus::Stalled] {
9482            let mut runner = runner_at(status);
9483            let run = runner.state.id.clone();
9484            let q = ask_open_question(&store, &run);
9485
9486            runner.settle_questions();
9487
9488            let back = store.get(&q.id).unwrap();
9489            assert!(
9490                back.status.open(),
9491                "{status:?} is still alive; the question must still be waiting"
9492            );
9493        }
9494    }
9495
9496    #[test]
9497    fn settle_questions_never_touches_an_already_answered_question() {
9498        ask_test_home();
9499        let store = ask::Questions::open();
9500        let mut runner = runner_at(RunStatus::Failed);
9501        let run = runner.state.id.clone();
9502        let mut q = ask_open_question(&store, &run);
9503        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
9504            .unwrap();
9505        store.put(&mut q).unwrap();
9506
9507        // Called twice, the way a crash-recovered daemon reclaim and the
9508        // graph's own cleanup both can for the same run — `abandon_for_run`
9509        // only ever touches what is still open, so this must be inert both
9510        // times, not merely the second.
9511        runner.settle_questions();
9512        runner.settle_questions();
9513
9514        let back = store.get(&q.id).unwrap();
9515        assert_eq!(
9516            back.status,
9517            ask::QuestionStatus::Answered,
9518            "a real answer is a decision on record, never overwritten by a sweep"
9519        );
9520    }
9521
9522    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
9523    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
9524    /// without merging, whose winner is still the operator's answer to read.
9525    /// Nothing previously called `fold_run` itself with a real `tally`, so
9526    /// this is the first test to pin down the one distinction the whole
9527    /// automatic-fold feature depends on: the winner's worktree and branch
9528    /// must survive, everything else sharing the run's worktree bay - a
9529    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
9530    /// second sweep treats every non-winner directory under the bay alike -
9531    /// must not.
9532    #[tokio::test]
9533    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
9534        crate::run::pin_test_home();
9535        let tmp = tempfile::tempdir().expect("tempdir");
9536        let repo = tmp.path().join("repo");
9537        std::fs::create_dir_all(&repo).unwrap();
9538        init_repo(&repo);
9539
9540        let mut config = Config::default();
9541        config.graph.worktree_root = Some(tmp.path().join("wt"));
9542
9543        let mut state = RunState::new(
9544            repo.clone(),
9545            "main".to_owned(),
9546            "deadbeef".to_owned(),
9547            "task".to_owned(),
9548            config,
9549        );
9550        let root = state.worktree_root();
9551        let wt_a = root.join("cand-A");
9552        let wt_b = root.join("cand-B");
9553        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
9554            .await
9555            .expect("worktree A");
9556        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
9557            .await
9558            .expect("worktree B");
9559
9560        state.candidates = vec![
9561            Candidate {
9562                index: 0,
9563                label: 'A',
9564                agent: "alpha".to_owned(),
9565                branch: "magi/x/A".to_owned(),
9566                worktree: wt_a.clone(),
9567                summary: String::new(),
9568                stat: String::new(),
9569                files: 0,
9570                commits: 0,
9571                empty: false,
9572                failed: None,
9573                verified_noop: None,
9574                duration_ms: 0,
9575                folded: false,
9576            },
9577            Candidate {
9578                index: 1,
9579                label: 'B',
9580                agent: "beta".to_owned(),
9581                branch: "magi/x/B".to_owned(),
9582                worktree: wt_b.clone(),
9583                summary: String::new(),
9584                stat: String::new(),
9585                files: 0,
9586                commits: 0,
9587                empty: false,
9588                failed: None,
9589                verified_noop: None,
9590                duration_ms: 0,
9591                folded: false,
9592            },
9593        ];
9594        state.tally = Some(Tally {
9595            first_choice: BTreeMap::from([('A', 1)]),
9596            borda: BTreeMap::new(),
9597            winner: 'A',
9598            rankings: 1,
9599            unanimous_initial: true,
9600            deliberated: false,
9601            changed_votes: 0,
9602            unanimous_final: true,
9603            tie_break: None,
9604            judges: 1,
9605            present: 1,
9606            quorum: 1,
9607            met_quorum: true,
9608            uncontested: None,
9609        });
9610        state.status = RunStatus::Ready;
9611
9612        fold_run(&mut state, false, &crate::run::home())
9613            .await
9614            .expect("fold_run");
9615
9616        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
9617        assert!(
9618            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
9619            "the unmerged winner's branch survives"
9620        );
9621        assert!(
9622            !state.candidates[0].folded,
9623            "the winner is not marked folded"
9624        );
9625
9626        assert!(!wt_b.exists(), "the loser's worktree is removed");
9627        assert!(
9628            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
9629            "the loser's branch is removed"
9630        );
9631        assert!(state.candidates[1].folded, "the loser is marked folded");
9632    }
9633
9634    /// A branch handed to a later run is that run's (and its pull request's):
9635    /// folding the run that released it must not delete it.
9636    #[tokio::test]
9637    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
9638        let tmp = tempfile::tempdir().expect("tempdir");
9639        let repo = tmp.path().join("repo");
9640        std::fs::create_dir_all(&repo).unwrap();
9641        init_repo(&repo);
9642        let home = tmp.path().join("home");
9643
9644        let mut config = Config::default();
9645        config.graph.worktree_root = Some(tmp.path().join("wt"));
9646        let mut state = RunState::new(
9647            repo.clone(),
9648            "main".to_owned(),
9649            "deadbeef".to_owned(),
9650            "task".to_owned(),
9651            config,
9652        );
9653        // The worktree is already gone (released); the branch survives.
9654        git::git(&repo, &["branch", "magi/x/A", "main"])
9655            .await
9656            .expect("branch");
9657        state.candidates = vec![Candidate {
9658            index: 0,
9659            label: 'A',
9660            agent: "alpha".to_owned(),
9661            branch: "magi/x/A".to_owned(),
9662            worktree: state.worktree_root().join("cand-A"),
9663            summary: String::new(),
9664            stat: String::new(),
9665            files: 0,
9666            commits: 0,
9667            empty: false,
9668            failed: None,
9669            verified_noop: None,
9670            duration_ms: 0,
9671            folded: true,
9672        }];
9673        state.released_to = Some("20260901-000000-new1".to_owned());
9674        state.released_branches = vec!["magi/x/A".to_owned()];
9675
9676        fold_run(&mut state, true, &home).await.expect("fold_run");
9677
9678        assert!(
9679            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
9680            "the handed-over branch survives a fold"
9681        );
9682    }
9683
9684    /// A winner with nothing ahead of the base is caught before `gh` is ever
9685    /// asked for a pull request, and the message carries what the task's
9686    /// references resolved to.
9687    #[tokio::test]
9688    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
9689        let tmp = tempfile::tempdir().expect("tempdir");
9690        let repo = tmp.path().join("repo");
9691        std::fs::create_dir_all(&repo).unwrap();
9692        init_repo(&repo);
9693        let run = |args: &[&str]| {
9694            let out = std::process::Command::new("git")
9695                .quiet()
9696                .args(args)
9697                .current_dir(&repo)
9698                .output()
9699                .expect("spawn git");
9700            assert!(out.status.success(), "git {args:?}");
9701        };
9702        run(&["branch", "magi/x/A"]);
9703        run(&["checkout", "-q", "-b", "magi/x/B"]);
9704        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
9705        run(&["add", "-A"]);
9706        run(&["commit", "-q", "-m", "work"]);
9707        run(&["checkout", "-q", "main"]);
9708
9709        // A pull request is compared against the remote's base, so the
9710        // fixture needs one. Before it exists nothing can be read, and the
9711        // answer must be "not empty".
9712        let probe = RunState::new(
9713            repo.clone(),
9714            "main".to_owned(),
9715            "deadbeef".to_owned(),
9716            "task".to_owned(),
9717            Config::default(),
9718        );
9719        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
9720        let bare = tmp.path().join("origin.git");
9721        let out = std::process::Command::new("git")
9722            .quiet()
9723            .args(["init", "-q", "--bare"])
9724            .arg(&bare)
9725            .output()
9726            .expect("spawn git");
9727        assert!(out.status.success(), "git init --bare");
9728        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
9729        run(&["push", "-q", "origin", "main"]);
9730
9731        let mut state = RunState::new(
9732            repo.clone(),
9733            "main".to_owned(),
9734            "deadbeef".to_owned(),
9735            "task".to_owned(),
9736            Config::default(),
9737        );
9738        state.seeds = vec![refs::Seed {
9739            token: "magi/27b2/A".to_owned(),
9740            kind: refs::SeedKind::Unresolved,
9741            sha: String::new(),
9742            branch: true,
9743            detail: "no branch or commit named magi/27b2/A".to_owned(),
9744        }];
9745
9746        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
9747        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
9748        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
9749        let detail = empty_candidate_detail(&state, "main");
9750        assert!(detail.starts_with("empty candidate"), "{detail}");
9751        assert!(detail.contains("magi/27b2/A"), "{detail}");
9752    }
9753
9754    /// `status == Ready` used to be read as "this is the harmless
9755    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
9756    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
9757    /// run's PR was closed without merging — and reentering `merge` with
9758    /// `mode` still `Pr` does not know the difference, so it pushed and
9759    /// opened a second pull request. `mode == Local` reproduces the same
9760    /// blind spot without a network call: reentry must not attempt another
9761    /// git merge once this node has already recorded an outcome.
9762    #[tokio::test]
9763    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
9764        let tmp = tempfile::tempdir().expect("tempdir");
9765        let repo = tmp.path().join("repo");
9766        std::fs::create_dir_all(&repo).unwrap();
9767        init_repo(&repo);
9768
9769        let mut config = Config::default();
9770        config.merge.mode = MergeMode::Local;
9771
9772        let mut state = RunState::new(
9773            repo.clone(),
9774            "main".to_owned(),
9775            "deadbeef".to_owned(),
9776            "task".to_owned(),
9777            config,
9778        );
9779        state.candidates = vec![Candidate {
9780            index: 0,
9781            label: 'A',
9782            agent: "alpha".to_owned(),
9783            branch: "does-not-exist".to_owned(),
9784            worktree: repo.clone(),
9785            summary: String::new(),
9786            stat: String::new(),
9787            files: 0,
9788            commits: 0,
9789            empty: false,
9790            failed: None,
9791            verified_noop: None,
9792            duration_ms: 0,
9793            folded: false,
9794        }];
9795        state.tally = Some(Tally {
9796            first_choice: BTreeMap::from([('A', 1)]),
9797            borda: BTreeMap::new(),
9798            winner: 'A',
9799            rankings: 1,
9800            unanimous_initial: true,
9801            deliberated: false,
9802            changed_votes: 0,
9803            unanimous_final: true,
9804            tie_break: None,
9805            judges: 0,
9806            present: 0,
9807            quorum: 0,
9808            met_quorum: true,
9809            uncontested: Some("only candidate A produced a change".to_owned()),
9810        });
9811        state.reviews = vec![ReviewRound {
9812            round: 1,
9813            head: "deadbeef".to_owned(),
9814            verified_head: None,
9815            verified_at: None,
9816            reviews: Vec::new(),
9817            e2e: Vec::new(),
9818            fix: None,
9819            blocking: 0,
9820            answered: 0,
9821            expected: 0,
9822            clean: true,
9823            verify_retried: false,
9824            e2e_deferred: false,
9825            e2e_defer_reason: None,
9826            progressed: false,
9827            vote_split: false,
9828            reconsideration: Vec::new(),
9829            verdict: None,
9830        }];
9831        state.gate = vec![CommandOutcome {
9832            command: "test".to_owned(),
9833            code: Some(0),
9834            output_tail: String::new(),
9835            duration_ms: 0,
9836            resource_blocked: false,
9837        }];
9838        state.gate_ran = true;
9839        // Reached its conclusion already — e.g. `land` closing the PR without
9840        // merging it, which (like the honest `MergeMode::None` path) leaves
9841        // `status` at `Ready`. The recorded outcome is what actually marks
9842        // this node done.
9843        state.status = RunStatus::Ready;
9844        state.merge = Some(MergeOutcome {
9845            mode: MergeMode::Local,
9846            ok: false,
9847            detail: "already concluded".to_owned(),
9848            empty: false,
9849        });
9850
9851        let mut runner = Runner {
9852            state,
9853            roles: ResolvedRoles {
9854                implementers: Vec::new(),
9855                judges: Vec::new(),
9856                reviewers: Vec::new(),
9857                fixer: None,
9858                conductor: conductor(),
9859                implementer_roster: Vec::new(),
9860                judge_roster: Vec::new(),
9861                reviewer_roster: Vec::new(),
9862            },
9863            sem: Arc::new(Semaphore::new(1)),
9864            pause: Pause::new(),
9865            interrupt: Pause::new(),
9866        };
9867
9868        runner.merge().await.expect("merge");
9869
9870        assert_eq!(
9871            runner.state.status,
9872            RunStatus::Ready,
9873            "a concluded run's status must not change on reentry"
9874        );
9875        assert_eq!(
9876            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
9877            Some("already concluded"),
9878            "merge must not run again once the node already recorded an outcome"
9879        );
9880    }
9881
9882    /// `gate` leaves `state.gate_ran` false both before it has ever run and
9883    /// when its last attempt was resource-blocked (the shared build cache
9884    /// could not be acquired or confirmed fresh in time - see
9885    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
9886    /// `Vec` this also leaves behind used to read as "nothing failed" and let
9887    /// a run merge a tree the gate never actually checked - exactly the case
9888    /// a contended cache produces on every retry until it clears. `merge`
9889    /// must refuse until `gate` has actually recorded an attempt.
9890    #[tokio::test]
9891    async fn merge_refuses_a_gate_that_has_not_actually_run() {
9892        let tmp = tempfile::tempdir().expect("tempdir");
9893        let repo = tmp.path().join("repo");
9894        std::fs::create_dir_all(&repo).unwrap();
9895        init_repo(&repo);
9896
9897        let mut config = Config::default();
9898        config.merge.mode = MergeMode::Local;
9899
9900        let mut state = RunState::new(
9901            repo.clone(),
9902            "main".to_owned(),
9903            "deadbeef".to_owned(),
9904            "task".to_owned(),
9905            config,
9906        );
9907        state.candidates = vec![Candidate {
9908            index: 0,
9909            label: 'A',
9910            agent: "alpha".to_owned(),
9911            branch: "does-not-exist".to_owned(),
9912            worktree: repo.clone(),
9913            summary: String::new(),
9914            stat: String::new(),
9915            files: 0,
9916            commits: 0,
9917            empty: false,
9918            failed: None,
9919            verified_noop: None,
9920            duration_ms: 0,
9921            folded: false,
9922        }];
9923        state.tally = Some(Tally {
9924            first_choice: BTreeMap::from([('A', 1)]),
9925            borda: BTreeMap::new(),
9926            winner: 'A',
9927            rankings: 1,
9928            unanimous_initial: true,
9929            deliberated: false,
9930            changed_votes: 0,
9931            unanimous_final: true,
9932            tie_break: None,
9933            judges: 0,
9934            present: 0,
9935            quorum: 0,
9936            met_quorum: true,
9937            uncontested: Some("only candidate A produced a change".to_owned()),
9938        });
9939        state.reviews = vec![ReviewRound {
9940            round: 1,
9941            head: "deadbeef".to_owned(),
9942            verified_head: None,
9943            verified_at: None,
9944            reviews: Vec::new(),
9945            e2e: Vec::new(),
9946            fix: None,
9947            blocking: 0,
9948            answered: 0,
9949            expected: 0,
9950            clean: true,
9951            verify_retried: false,
9952            e2e_deferred: false,
9953            e2e_defer_reason: None,
9954            progressed: false,
9955            vote_split: false,
9956            reconsideration: Vec::new(),
9957            verdict: None,
9958        }];
9959        // The point: `gate` has not recorded anything yet.
9960        state.gate = Vec::new();
9961        state.gate_ran = false;
9962        state.status = RunStatus::Gating;
9963
9964        let mut runner = Runner {
9965            state,
9966            roles: ResolvedRoles {
9967                implementers: Vec::new(),
9968                judges: Vec::new(),
9969                reviewers: Vec::new(),
9970                fixer: None,
9971                conductor: conductor(),
9972                implementer_roster: Vec::new(),
9973                judge_roster: Vec::new(),
9974                reviewer_roster: Vec::new(),
9975            },
9976            sem: Arc::new(Semaphore::new(1)),
9977            pause: Pause::new(),
9978            interrupt: Pause::new(),
9979        };
9980
9981        runner.merge().await.expect("merge");
9982
9983        assert!(
9984            runner.state.merge.is_none(),
9985            "an empty gate must never be read as a passing one: {:?}",
9986            runner.state.merge
9987        );
9988    }
9989
9990    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
9991    /// commands configured and `merge.mode` is `none` (a review-only run).
9992    /// `gate` must still record a real attempt — zero commands, vacuously
9993    /// passed — rather than leaving `state.gate` empty in a way `merge`
9994    /// cannot tell apart from "never ran"; otherwise the run reaches
9995    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
9996    #[tokio::test]
9997    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
9998        let tmp = tempfile::tempdir().expect("tempdir");
9999        let repo = tmp.path().join("repo");
10000        std::fs::create_dir_all(&repo).unwrap();
10001        init_repo(&repo);
10002
10003        // Default config: `verify.gate` empty, `merge.mode` is `none`.
10004        let config = Config::default();
10005
10006        let mut state = RunState::new(
10007            repo.clone(),
10008            "main".to_owned(),
10009            "deadbeef".to_owned(),
10010            "task".to_owned(),
10011            config,
10012        );
10013        state.candidates = vec![Candidate {
10014            index: 0,
10015            label: 'A',
10016            agent: "alpha".to_owned(),
10017            branch: "does-not-exist".to_owned(),
10018            worktree: repo.clone(),
10019            summary: String::new(),
10020            stat: String::new(),
10021            files: 0,
10022            commits: 0,
10023            empty: false,
10024            failed: None,
10025            verified_noop: None,
10026            duration_ms: 0,
10027            folded: false,
10028        }];
10029        state.tally = Some(Tally {
10030            first_choice: BTreeMap::from([('A', 1)]),
10031            borda: BTreeMap::new(),
10032            winner: 'A',
10033            rankings: 1,
10034            unanimous_initial: true,
10035            deliberated: false,
10036            changed_votes: 0,
10037            unanimous_final: true,
10038            tie_break: None,
10039            judges: 0,
10040            present: 0,
10041            quorum: 0,
10042            met_quorum: true,
10043            uncontested: Some("only candidate A produced a change".to_owned()),
10044        });
10045        state.reviews = vec![ReviewRound {
10046            round: 1,
10047            head: "deadbeef".to_owned(),
10048            verified_head: None,
10049            verified_at: None,
10050            reviews: Vec::new(),
10051            e2e: Vec::new(),
10052            fix: None,
10053            blocking: 0,
10054            answered: 0,
10055            expected: 0,
10056            clean: true,
10057            verify_retried: false,
10058            e2e_deferred: false,
10059            e2e_defer_reason: None,
10060            progressed: false,
10061            vote_split: false,
10062            reconsideration: Vec::new(),
10063            verdict: None,
10064        }];
10065
10066        let mut runner = Runner {
10067            state,
10068            roles: ResolvedRoles {
10069                implementers: Vec::new(),
10070                judges: Vec::new(),
10071                reviewers: Vec::new(),
10072                fixer: None,
10073                conductor: conductor(),
10074                implementer_roster: Vec::new(),
10075                judge_roster: Vec::new(),
10076                reviewer_roster: Vec::new(),
10077            },
10078            sem: Arc::new(Semaphore::new(1)),
10079            pause: Pause::new(),
10080            interrupt: Pause::new(),
10081        };
10082
10083        runner.gate().await.expect("gate");
10084        assert!(
10085            runner.state.gate_ran,
10086            "zero configured commands is still a real attempt, not an unrun gate"
10087        );
10088        assert!(runner.state.gate.is_empty());
10089        assert_eq!(runner.state.gate_status(), GateStatus::PassedWithNoCommands);
10090        assert_ne!(
10091            runner.state.status,
10092            RunStatus::Blocked,
10093            "a gate with nothing to check must not read as failed"
10094        );
10095
10096        runner.merge().await.expect("merge");
10097        assert_eq!(
10098            runner.state.status,
10099            RunStatus::Ready,
10100            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
10101        );
10102    }
10103
10104    /// `Config::cache_dir` is derived from `verify.e2e` as well as
10105    /// `verify.gate` (so the e2e leg and the final gate never build against
10106    /// different directories). With zero `verify.gate` commands but a
10107    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
10108    /// that lease before discovering it had nothing to run - so a repo with
10109    /// no gate commands could come back `resource_blocked` (and therefore
10110    /// still `gate_ran == false`) on nothing but an unrelated run holding the
10111    /// cache, exactly the contention this run's own zero commands could
10112    /// never have touched. `gate` must recognise there is nothing to check
10113    /// before it ever asks for the lease.
10114    #[tokio::test]
10115    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
10116        crate::run::pin_test_home();
10117        let home = crate::run::home();
10118
10119        let tmp = tempfile::tempdir().expect("tempdir");
10120        let repo = tmp.path().join("repo");
10121        std::fs::create_dir_all(&repo).unwrap();
10122        init_repo(&repo);
10123        // Unique to this test, so holding its lease cannot collide with
10124        // another test sharing the same process-wide `home`.
10125        let cache_dir = tmp.path().join("target");
10126
10127        let mut config = Config::default();
10128        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
10129        // `verify.gate` stays empty (the default). Bounded so a regression
10130        // that does start waiting fails the test in seconds, not hangs it.
10131        config.graph.timeout_verify = Some(2);
10132
10133        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10134        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10135            .expect("no io error acquiring directly")
10136        {
10137            crate::cache::AcquireOutcome::Acquired(g) => g,
10138            crate::cache::AcquireOutcome::Busy(b) => {
10139                panic!("expected the direct acquire to win the lease first: {b:?}")
10140            }
10141        };
10142
10143        let mut state = RunState::new(
10144            repo.clone(),
10145            "main".to_owned(),
10146            "deadbeef".to_owned(),
10147            "task".to_owned(),
10148            config,
10149        );
10150        state.candidates = vec![Candidate {
10151            index: 0,
10152            label: 'A',
10153            agent: "alpha".to_owned(),
10154            branch: "does-not-exist".to_owned(),
10155            worktree: repo.clone(),
10156            summary: String::new(),
10157            stat: String::new(),
10158            files: 0,
10159            commits: 0,
10160            empty: false,
10161            failed: None,
10162            verified_noop: None,
10163            duration_ms: 0,
10164            folded: false,
10165        }];
10166        state.tally = Some(Tally {
10167            first_choice: BTreeMap::from([('A', 1)]),
10168            borda: BTreeMap::new(),
10169            winner: 'A',
10170            rankings: 1,
10171            unanimous_initial: true,
10172            deliberated: false,
10173            changed_votes: 0,
10174            unanimous_final: true,
10175            tie_break: None,
10176            judges: 0,
10177            present: 0,
10178            quorum: 0,
10179            met_quorum: true,
10180            uncontested: Some("only candidate A produced a change".to_owned()),
10181        });
10182        state.reviews = vec![ReviewRound {
10183            round: 1,
10184            head: "deadbeef".to_owned(),
10185            verified_head: None,
10186            verified_at: None,
10187            reviews: Vec::new(),
10188            e2e: Vec::new(),
10189            fix: None,
10190            blocking: 0,
10191            answered: 0,
10192            expected: 0,
10193            clean: true,
10194            verify_retried: false,
10195            e2e_deferred: false,
10196            e2e_defer_reason: None,
10197            progressed: false,
10198            vote_split: false,
10199            reconsideration: Vec::new(),
10200            verdict: None,
10201        }];
10202
10203        let mut runner = Runner {
10204            state,
10205            roles: ResolvedRoles {
10206                implementers: Vec::new(),
10207                judges: Vec::new(),
10208                reviewers: Vec::new(),
10209                fixer: None,
10210                conductor: conductor(),
10211                implementer_roster: Vec::new(),
10212                judge_roster: Vec::new(),
10213                reviewer_roster: Vec::new(),
10214            },
10215            sem: Arc::new(Semaphore::new(1)),
10216            pause: Pause::new(),
10217            interrupt: Pause::new(),
10218        };
10219
10220        let started = std::time::Instant::now();
10221        runner.gate().await.expect("gate");
10222        assert!(
10223            started.elapsed() < Duration::from_secs(1),
10224            "a gate with nothing to run must never wait on a lease it never needed"
10225        );
10226        assert!(
10227            runner.state.gate_ran,
10228            "zero commands is still a real, immediate attempt"
10229        );
10230        assert!(runner.state.gate.is_empty());
10231        assert_ne!(
10232            runner.state.status,
10233            RunStatus::Blocked,
10234            "must not read as resource-blocked on a lease it never asked for"
10235        );
10236    }
10237
10238    /// The addendum's second gap: a `verify.gate` command running for real
10239    /// wall-clock time had nothing at all to show for it in `active` before
10240    /// `run_commands` learned to record it — a run could sit in `Gating` for
10241    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
10242    /// what was actually happening. Proven with a genuinely still-running
10243    /// command, not just a before/after check on the final state: a poller
10244    /// task reads the same `run.json` `gate()` is writing, the same way the
10245    /// phone or `magi show` would, while the shell command is still blocked
10246    /// on its own release marker.
10247    #[tokio::test]
10248    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
10249        crate::run::pin_test_home();
10250
10251        let tmp = tempfile::tempdir().expect("tempdir");
10252        let repo = tmp.path().join("repo");
10253        std::fs::create_dir_all(&repo).unwrap();
10254        init_repo(&repo);
10255
10256        let mut config = Config::default();
10257        config.verify.gate = vec![
10258            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
10259             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done"
10260                .to_owned(),
10261        ];
10262
10263        let mut state = RunState::new(
10264            repo.clone(),
10265            "main".to_owned(),
10266            "deadbeef".to_owned(),
10267            "task".to_owned(),
10268            config,
10269        );
10270        let run_id = state.id.clone();
10271        state.candidates = vec![Candidate {
10272            index: 0,
10273            label: 'A',
10274            agent: "alpha".to_owned(),
10275            branch: "does-not-exist".to_owned(),
10276            worktree: repo.clone(),
10277            summary: String::new(),
10278            stat: String::new(),
10279            files: 0,
10280            commits: 0,
10281            empty: false,
10282            failed: None,
10283            verified_noop: None,
10284            duration_ms: 0,
10285            folded: false,
10286        }];
10287        state.tally = Some(Tally {
10288            first_choice: BTreeMap::from([('A', 1)]),
10289            borda: BTreeMap::new(),
10290            winner: 'A',
10291            rankings: 1,
10292            unanimous_initial: true,
10293            deliberated: false,
10294            changed_votes: 0,
10295            unanimous_final: true,
10296            tie_break: None,
10297            judges: 0,
10298            present: 0,
10299            quorum: 0,
10300            met_quorum: true,
10301            uncontested: Some("only candidate A produced a change".to_owned()),
10302        });
10303        state.reviews = vec![ReviewRound {
10304            round: 1,
10305            head: "deadbeef".to_owned(),
10306            verified_head: None,
10307            verified_at: None,
10308            reviews: Vec::new(),
10309            e2e: Vec::new(),
10310            fix: None,
10311            blocking: 0,
10312            answered: 0,
10313            expected: 0,
10314            clean: true,
10315            verify_retried: false,
10316            e2e_deferred: false,
10317            e2e_defer_reason: None,
10318            progressed: false,
10319            vote_split: false,
10320            reconsideration: Vec::new(),
10321            verdict: None,
10322        }];
10323
10324        let mut runner = Runner {
10325            state,
10326            roles: ResolvedRoles {
10327                implementers: Vec::new(),
10328                judges: Vec::new(),
10329                reviewers: Vec::new(),
10330                fixer: None,
10331                conductor: conductor(),
10332                implementer_roster: Vec::new(),
10333                judge_roster: Vec::new(),
10334                reviewer_roster: Vec::new(),
10335            },
10336            sem: Arc::new(Semaphore::new(1)),
10337            pause: Pause::new(),
10338            interrupt: Pause::new(),
10339        };
10340
10341        let started_marker = repo.join("started.marker");
10342        let release_marker = repo.join("release.marker");
10343        let poller = tokio::spawn(async move {
10344            // Bounded so a regression that never records the task entry
10345            // fails this test in seconds instead of hanging the suite —
10346            // the same shape `a_park_requested_while_a_seat_is_mid_call_
10347            // does_not_cut_it_short` uses for the same reason.
10348            for _ in 0..100 {
10349                if started_marker.exists()
10350                    && let Ok(s) = crate::run::RunState::load(&run_id)
10351                    && let Some(a) = s.active.get("gate")
10352                {
10353                    std::fs::write(&release_marker, b"go").expect("release marker");
10354                    return Some(a.clone());
10355                }
10356                tokio::time::sleep(Duration::from_millis(50)).await;
10357            }
10358            None
10359        });
10360
10361        runner.gate().await.expect("gate");
10362        let captured = poller.await.expect("poller task");
10363        let captured = captured.expect(
10364            "the poller never saw a `gate` task entry in run.json while the command was \
10365             still blocked on its own release marker",
10366        );
10367
10368        assert_eq!(captured.task.as_deref(), Some("gate"));
10369        assert_eq!(captured.node, "gate");
10370        assert_eq!(captured.index, Some(1));
10371        assert_eq!(captured.total, Some(1));
10372        assert!(
10373            captured
10374                .command
10375                .as_deref()
10376                .is_some_and(|c| c.contains("started.marker")),
10377            "{captured:?}"
10378        );
10379
10380        assert!(
10381            runner.state.active.is_empty(),
10382            "the entry must be cleared once the command actually finished: {:?}",
10383            runner.state.active
10384        );
10385        assert!(runner.state.gate_ran);
10386        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
10387    }
10388
10389    /// The hand-off over a blocking finding a reviewer rejected on leaves a
10390    /// record for `land`; one with only a Minor, or no reject, leaves none.
10391    #[tokio::test]
10392    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
10393        use crate::verdict::{Finding, ReviewVote, Severity};
10394        crate::run::pin_test_home();
10395        let tmp = tempfile::tempdir().expect("tempdir");
10396        let repo = tmp.path().join("repo");
10397        std::fs::create_dir_all(&repo).unwrap();
10398        init_repo(&repo);
10399
10400        for (severity, vote, expect) in [
10401            (Severity::Major, ReviewVote::Reject, true),
10402            (Severity::Minor, ReviewVote::Reject, false),
10403            (Severity::Major, ReviewVote::Approve, false),
10404        ] {
10405            let mut round = review_round(false, 1, 1, 1, false, true);
10406            round.reviews = vec![ReviewRecord {
10407                reviewer: 1,
10408                agent: "alpha".to_owned(),
10409                summary: String::new(),
10410                findings: vec![Finding {
10411                    id: "R1-1-1".to_owned(),
10412                    severity,
10413                    file: None,
10414                    line: None,
10415                    title: "t".to_owned(),
10416                    detail: String::new(),
10417                }],
10418                vote: Some(vote),
10419                failed: None,
10420                duration_ms: 0,
10421                attempts: 0,
10422            }];
10423            let mut state = RunState::new(
10424                repo.clone(),
10425                "main".to_owned(),
10426                "deadbeef".to_owned(),
10427                "task".to_owned(),
10428                Config::default(),
10429            );
10430            state.reviews = vec![round];
10431            let mut runner = Runner {
10432                state,
10433                roles: ResolvedRoles {
10434                    implementers: Vec::new(),
10435                    judges: Vec::new(),
10436                    reviewers: Vec::new(),
10437                    fixer: None,
10438                    conductor: conductor(),
10439                    implementer_roster: Vec::new(),
10440                    judge_roster: Vec::new(),
10441                    reviewer_roster: Vec::new(),
10442                },
10443                sem: Arc::new(Semaphore::new(1)),
10444                pause: Pause::new(),
10445                interrupt: Pause::new(),
10446            };
10447            let shell = runner.state.config.shell();
10448            runner
10449                .stop_reviewing("round budget spent", &shell, &repo)
10450                .await
10451                .expect("stop_reviewing");
10452            assert_eq!(runner.state.status, RunStatus::Gating);
10453            assert_eq!(
10454                runner.state.contested_handoff.is_some(),
10455                expect,
10456                "{severity:?} + {vote:?}"
10457            );
10458        }
10459    }
10460
10461    /// The shape the incident this whole fix responds to actually had: the
10462    /// round budget spent, the last round's own e2e blocked on the shared
10463    /// build cache (held here by a live pid — this test process — exactly
10464    /// `cache`'s own unit tests' pattern for "another owner, still alive"
10465    /// without forking a process). `stop_reviewing` must retry it — not
10466    /// silently leave the round looking untouched (the catch-up-only half of
10467    /// the bug), and not read the contention as a red `e2e` and block the
10468    /// run on it (the other half). Called directly, the same way
10469    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
10470    /// above exercises `gate`, so this never needs a real cargo build to
10471    /// reach: the lease is never released, so `with_cache_lease` never gets
10472    /// past acquiring it into anything that would need a real workspace.
10473    #[tokio::test]
10474    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
10475        crate::run::pin_test_home();
10476        let home = crate::run::home();
10477
10478        let tmp = tempfile::tempdir().expect("tempdir");
10479        let repo = tmp.path().join("repo");
10480        std::fs::create_dir_all(&repo).unwrap();
10481        init_repo(&repo);
10482        let head = crate::git::rev_parse(&repo, "HEAD")
10483            .await
10484            .expect("rev-parse");
10485        // Unique to this test, so holding its lease cannot collide with
10486        // another test sharing the same process-wide `home`.
10487        let cache_dir = tmp.path().join("target");
10488
10489        let mut config = Config::default();
10490        config.verify.e2e = vec![format!(
10491            "CARGO_TARGET_DIR='{}' test -f README.md",
10492            cache_dir.display()
10493        )];
10494        config.graph.review_rounds = 1;
10495        // Bounded so a regression that does start waiting fails the test in
10496        // seconds, not hangs it.
10497        config.graph.timeout_verify = Some(2);
10498
10499        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10500        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10501            .expect("no io error acquiring directly")
10502        {
10503            crate::cache::AcquireOutcome::Acquired(g) => g,
10504            crate::cache::AcquireOutcome::Busy(b) => {
10505                panic!("expected the direct acquire to win the lease first: {b:?}")
10506            }
10507        };
10508
10509        let mut state = RunState::new(
10510            repo.clone(),
10511            "main".to_owned(),
10512            head.clone(),
10513            "task".to_owned(),
10514            config,
10515        );
10516        state.candidates = vec![Candidate {
10517            index: 0,
10518            label: 'A',
10519            agent: "alpha".to_owned(),
10520            branch: "does-not-exist".to_owned(),
10521            worktree: repo.clone(),
10522            summary: String::new(),
10523            stat: String::new(),
10524            files: 0,
10525            commits: 0,
10526            empty: false,
10527            failed: None,
10528            verified_noop: None,
10529            duration_ms: 0,
10530            folded: false,
10531        }];
10532        state.tally = Some(Tally {
10533            first_choice: BTreeMap::from([('A', 1)]),
10534            borda: BTreeMap::new(),
10535            winner: 'A',
10536            rankings: 1,
10537            unanimous_initial: true,
10538            deliberated: false,
10539            changed_votes: 0,
10540            unanimous_final: true,
10541            tie_break: None,
10542            judges: 0,
10543            present: 0,
10544            quorum: 0,
10545            met_quorum: true,
10546            uncontested: Some("only candidate A produced a change".to_owned()),
10547        });
10548        // The round budget's last round, deferred: `needs_catchup_run`'s
10549        // other trigger. `stop_reviewing`'s retry machinery must treat this
10550        // exactly like a resource-blocked attempt once it actually runs.
10551        state.reviews = vec![ReviewRound {
10552            round: 1,
10553            head: head.clone(),
10554            verified_head: None,
10555            verified_at: None,
10556            reviews: Vec::new(),
10557            e2e: Vec::new(),
10558            fix: None,
10559            blocking: 1,
10560            answered: 1,
10561            expected: 1,
10562            clean: false,
10563            verify_retried: false,
10564            e2e_deferred: true,
10565            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
10566            progressed: false,
10567            vote_split: false,
10568            reconsideration: Vec::new(),
10569            verdict: None,
10570        }];
10571
10572        let mut runner = Runner {
10573            state,
10574            roles: ResolvedRoles {
10575                implementers: Vec::new(),
10576                judges: Vec::new(),
10577                reviewers: Vec::new(),
10578                fixer: None,
10579                conductor: conductor(),
10580                implementer_roster: Vec::new(),
10581                judge_roster: Vec::new(),
10582                reviewer_roster: Vec::new(),
10583            },
10584            sem: Arc::new(Semaphore::new(1)),
10585            pause: Pause::new(),
10586            interrupt: Pause::new(),
10587        };
10588
10589        let shell = runner.state.config.shell();
10590        runner
10591            .stop_reviewing("round budget spent", &shell, &repo)
10592            .await
10593            .expect("stop_reviewing");
10594
10595        let last = runner.state.reviews.last().expect("round record");
10596        assert_eq!(
10597            last.e2e_status(),
10598            E2eStatus::ResourceBlocked,
10599            "the shared cache is still held; the attempt must read as blocked, not deferred or \
10600             failed: {last:?}"
10601        );
10602        assert_eq!(
10603            last.verified_head.as_deref(),
10604            Some(head.as_str()),
10605            "which commit this attempt targeted is known even though nothing finished checking \
10606             it"
10607        );
10608        let first_attempt_at = last
10609            .verified_at
10610            .expect("when this attempt ran is known too");
10611        assert_ne!(
10612            runner.state.status,
10613            RunStatus::Blocked,
10614            "contention is evidence about the machine, not the patch — it must not settle the \
10615             run as blocked: {:?}",
10616            runner.state.status
10617        );
10618        assert!(
10619            !runner
10620                .state
10621                .events
10622                .iter()
10623                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
10624            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
10625            runner.state.events
10626        );
10627
10628        // The cache is still held: a later reentry must retry the same
10629        // round's verification again — not leave it looking exactly as
10630        // untouched as the first blocked attempt, which is indistinguishable
10631        // from never having tried again at all.
10632        runner
10633            .stop_reviewing("round budget spent", &shell, &repo)
10634            .await
10635            .expect("stop_reviewing retry");
10636        assert_eq!(
10637            runner.state.reviews.len(),
10638            1,
10639            "no new round was started: {:?}",
10640            runner.state.reviews
10641        );
10642        let last = runner.state.reviews.last().expect("round record");
10643        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
10644        assert!(
10645            last.verified_at.expect("still known") > first_attempt_at,
10646            "a second reentry must be a fresh attempt, not a stale copy of the first"
10647        );
10648        assert_ne!(runner.state.status, RunStatus::Blocked);
10649
10650        held.release();
10651    }
10652
10653    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
10654    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
10655    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
10656    /// own top-of-function fast path (`review_conclusion`) correctly reads
10657    /// this shape as `None` rather than guessing `Blocked`, and the loop's
10658    /// own `for` range is empty once the round budget is spent, so
10659    /// `review_loop` must retry the check itself rather than silently doing
10660    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
10661    /// above exercises directly, but through `review_loop`'s own entry point
10662    /// this time, proving the wiring between the two rather than just the
10663    /// retry logic in isolation.
10664    #[tokio::test]
10665    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
10666        crate::run::pin_test_home();
10667        let home = crate::run::home();
10668
10669        let tmp = tempfile::tempdir().expect("tempdir");
10670        let repo = tmp.path().join("repo");
10671        std::fs::create_dir_all(&repo).unwrap();
10672        init_repo(&repo);
10673        let head = crate::git::rev_parse(&repo, "HEAD")
10674            .await
10675            .expect("rev-parse");
10676        let cache_dir = tmp.path().join("target");
10677
10678        let mut config = Config::default();
10679        config.verify.e2e = vec![format!(
10680            "CARGO_TARGET_DIR='{}' test -f README.md",
10681            cache_dir.display()
10682        )];
10683        config.graph.review_rounds = 1;
10684        config.graph.timeout_verify = Some(2);
10685
10686        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10687        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10688            .expect("no io error acquiring directly")
10689        {
10690            crate::cache::AcquireOutcome::Acquired(g) => g,
10691            crate::cache::AcquireOutcome::Busy(b) => {
10692                panic!("expected the direct acquire to win the lease first: {b:?}")
10693            }
10694        };
10695
10696        let mut state = RunState::new(
10697            repo.clone(),
10698            "main".to_owned(),
10699            head.clone(),
10700            "task".to_owned(),
10701            config,
10702        );
10703        state.candidates = vec![Candidate {
10704            index: 0,
10705            label: 'A',
10706            agent: "alpha".to_owned(),
10707            branch: "does-not-exist".to_owned(),
10708            worktree: repo.clone(),
10709            summary: String::new(),
10710            stat: String::new(),
10711            files: 0,
10712            commits: 0,
10713            empty: false,
10714            failed: None,
10715            verified_noop: None,
10716            duration_ms: 0,
10717            folded: false,
10718        }];
10719        state.tally = Some(Tally {
10720            first_choice: BTreeMap::from([('A', 1)]),
10721            borda: BTreeMap::new(),
10722            winner: 'A',
10723            rankings: 1,
10724            unanimous_initial: true,
10725            deliberated: false,
10726            changed_votes: 0,
10727            unanimous_final: true,
10728            tie_break: None,
10729            judges: 0,
10730            present: 0,
10731            quorum: 0,
10732            met_quorum: true,
10733            uncontested: Some("only candidate A produced a change".to_owned()),
10734        });
10735        // The exact shape a prior process's `stop_reviewing` would have left
10736        // on disk: the round budget's last round, a real attempt already
10737        // made and already resource-blocked.
10738        state.reviews = vec![ReviewRound {
10739            round: 1,
10740            head: head.clone(),
10741            verified_head: Some(head.clone()),
10742            verified_at: Some(jiff::Timestamp::now()),
10743            reviews: Vec::new(),
10744            e2e: vec![CommandOutcome {
10745                command: format!(
10746                    "CARGO_TARGET_DIR='{}' test -f README.md",
10747                    cache_dir.display()
10748                ),
10749                code: None,
10750                output_tail: "waiting for the shared build cache".to_owned(),
10751                duration_ms: 0,
10752                resource_blocked: true,
10753            }],
10754            fix: None,
10755            blocking: 1,
10756            answered: 1,
10757            expected: 1,
10758            clean: false,
10759            verify_retried: false,
10760            e2e_deferred: false,
10761            e2e_defer_reason: None,
10762            progressed: false,
10763            vote_split: false,
10764            reconsideration: Vec::new(),
10765            verdict: None,
10766        }];
10767
10768        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
10769        let mut runner = Runner {
10770            state,
10771            roles: ResolvedRoles {
10772                implementers: Vec::new(),
10773                judges: Vec::new(),
10774                reviewers: Vec::new(),
10775                fixer: None,
10776                conductor: conductor(),
10777                implementer_roster: Vec::new(),
10778                judge_roster: Vec::new(),
10779                reviewer_roster: Vec::new(),
10780            },
10781            sem: Arc::new(Semaphore::new(1)),
10782            pause: Pause::new(),
10783            interrupt: Pause::new(),
10784        };
10785
10786        // The lease is still held throughout, so this reentry's own retry is
10787        // also contended — proving `review_loop` actually tried again (not
10788        // that it happened to succeed) is what the timestamp comparison
10789        // below is for.
10790        runner.review_loop().await.expect("review_loop");
10791
10792        assert_eq!(
10793            runner.state.reviews.len(),
10794            1,
10795            "no new round was started on top of the unresolved one: {:?}",
10796            runner.state.reviews
10797        );
10798        let last = &runner.state.reviews[0];
10799        assert_eq!(
10800            last.e2e_status(),
10801            E2eStatus::ResourceBlocked,
10802            "still contended: {last:?}"
10803        );
10804        assert!(
10805            last.verified_at.expect("still known") > first_attempt_at,
10806            "review_loop must have actually retried the check, not left it exactly as found"
10807        );
10808        assert_ne!(
10809            runner.state.status,
10810            RunStatus::Blocked,
10811            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
10812            runner.state.status
10813        );
10814
10815        held.release();
10816    }
10817
10818    #[tokio::test]
10819    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
10820        crate::run::pin_test_home();
10821        let tmp = tempfile::tempdir().expect("tempdir");
10822        let repo = tmp.path().join("repo");
10823        std::fs::create_dir_all(&repo).unwrap();
10824        init_repo(&repo);
10825
10826        let mut config = Config::default();
10827        config.merge.mode = MergeMode::Pr;
10828        config.graph.land = true;
10829        config.graph.land_approval = false;
10830
10831        let mut state = RunState::new(
10832            repo.clone(),
10833            "main".to_owned(),
10834            "deadbeef".to_owned(),
10835            "task".to_owned(),
10836            config,
10837        );
10838        state.candidates = vec![Candidate {
10839            index: 0,
10840            label: 'A',
10841            agent: "alpha".to_owned(),
10842            branch: "does-not-exist".to_owned(),
10843            worktree: repo.clone(),
10844            summary: String::new(),
10845            stat: String::new(),
10846            files: 0,
10847            commits: 0,
10848            empty: false,
10849            failed: None,
10850            verified_noop: None,
10851            duration_ms: 0,
10852            folded: false,
10853        }];
10854        state.tally = Some(Tally {
10855            first_choice: BTreeMap::from([('A', 1)]),
10856            borda: BTreeMap::new(),
10857            winner: 'A',
10858            rankings: 1,
10859            unanimous_initial: true,
10860            deliberated: false,
10861            changed_votes: 0,
10862            unanimous_final: true,
10863            tie_break: None,
10864            judges: 0,
10865            present: 0,
10866            quorum: 0,
10867            met_quorum: true,
10868            uncontested: Some("only candidate A produced a change".to_owned()),
10869        });
10870        state.reviews = vec![ReviewRound {
10871            round: 1,
10872            head: "deadbeef".to_owned(),
10873            verified_head: None,
10874            verified_at: None,
10875            reviews: Vec::new(),
10876            e2e: Vec::new(),
10877            fix: None,
10878            blocking: 0,
10879            answered: 0,
10880            expected: 0,
10881            clean: true,
10882            verify_retried: false,
10883            e2e_deferred: false,
10884            e2e_defer_reason: None,
10885            progressed: false,
10886            vote_split: false,
10887            reconsideration: Vec::new(),
10888            verdict: None,
10889        }];
10890        state.gate = vec![CommandOutcome {
10891            command: "test".to_owned(),
10892            code: Some(0),
10893            output_tail: String::new(),
10894            duration_ms: 0,
10895            resource_blocked: false,
10896        }];
10897        state.gate_ran = true;
10898        // A first pass through `merge` already pushed and opened this pull
10899        // request; `status` is `Landing` because a previous call into `land`
10900        // parked or was interrupted before it reached a terminal outcome.
10901        state.status = RunStatus::Landing;
10902        state.merge = Some(MergeOutcome {
10903            mode: MergeMode::Pr,
10904            ok: true,
10905            detail: "https://example.invalid/x/y/pull/1".to_owned(),
10906            empty: false,
10907        });
10908
10909        // The Landing-resume shortcut calls `run_land` directly rather than
10910        // through `merge`, which is exactly the call site that used to skip
10911        // `settle_questions` - see the fixture below.
10912        ask_test_home();
10913        let store = ask::Questions::open();
10914        let q = ask_open_question(&store, &state.id);
10915
10916        let mut runner = Runner {
10917            state,
10918            roles: ResolvedRoles {
10919                implementers: Vec::new(),
10920                judges: Vec::new(),
10921                reviewers: Vec::new(),
10922                fixer: None,
10923                conductor: conductor(),
10924                implementer_roster: Vec::new(),
10925                judge_roster: Vec::new(),
10926                reviewer_roster: Vec::new(),
10927            },
10928            sem: Arc::new(Semaphore::new(1)),
10929            pause: Pause::new(),
10930            interrupt: Pause::new(),
10931        };
10932
10933        // `execute`, not `merge` directly: the Landing-resume shortcut lives
10934        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
10935        // exactly because `review_loop` would otherwise clobber the marker
10936        // first.
10937        runner.execute().await.expect("execute");
10938
10939        assert_eq!(
10940            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
10941            Some("https://example.invalid/x/y/pull/1"),
10942            "reentry must not push again or open a second pull request over the \
10943             one `land` is already watching"
10944        );
10945        assert_ne!(
10946            runner.state.status,
10947            RunStatus::Landing,
10948            "land could not actually reach the fake pull request, so it must \
10949             have given up rather than left the run silently parked forever"
10950        );
10951        // `land` could not reach the fake pull request, so it gave up into
10952        // `Blocked` - still resumable, so the question must not have been
10953        // swept just because this branch now also calls `settle_questions`.
10954        assert_eq!(runner.state.status, RunStatus::Blocked);
10955        assert!(
10956            store.get(&q.id).unwrap().status.open(),
10957            "Blocked is still alive; settle_questions must have been a no-op here"
10958        );
10959    }
10960
10961    fn state_with_round(round: ReviewRound) -> RunState {
10962        let mut s = RunState::new(
10963            PathBuf::from("/repo"),
10964            "main".to_owned(),
10965            "abc1234".to_owned(),
10966            "add retries".to_owned(),
10967            Config::default(),
10968        );
10969        s.reviews = vec![round];
10970        s
10971    }
10972
10973    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
10974        crate::verdict::Finding {
10975            id: id.to_owned(),
10976            severity,
10977            file: None,
10978            line: None,
10979            title: title.to_owned(),
10980            detail: String::new(),
10981        }
10982    }
10983
10984    #[test]
10985    fn pr_body_names_open_findings_and_declined_ones() {
10986        let round = ReviewRound {
10987            round: 2,
10988            head: "deadbee".to_owned(),
10989            verified_head: None,
10990            verified_at: None,
10991            reviews: vec![ReviewRecord {
10992                attempts: 0,
10993                reviewer: 1,
10994                agent: "alpha".to_owned(),
10995                summary: String::new(),
10996                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
10997                vote: None,
10998                failed: None,
10999                duration_ms: 0,
11000            }],
11001            e2e: vec![CommandOutcome {
11002                command: "cargo test".to_owned(),
11003                code: Some(0),
11004                output_tail: String::new(),
11005                duration_ms: 0,
11006                resource_blocked: false,
11007            }],
11008            verify_retried: false,
11009            e2e_deferred: false,
11010            e2e_defer_reason: None,
11011            fix: Some(FixRecord {
11012                agent: "alpha".to_owned(),
11013                addressed: Vec::new(),
11014                rejected: vec![crate::verdict::Rejection {
11015                    id: "R1-1-1".to_owned(),
11016                    why: "not reachable from any caller".to_owned(),
11017                }],
11018                notes: String::new(),
11019                committed: true,
11020                failed: None,
11021                duration_ms: 0,
11022                continuation: None,
11023            }),
11024            blocking: 0,
11025            answered: 1,
11026            expected: 1,
11027            clean: false,
11028            progressed: true,
11029            vote_split: false,
11030            reconsideration: Vec::new(),
11031            verdict: None,
11032        };
11033        let state = state_with_round(round);
11034        let body = pr_message(&state, 'A').body;
11035
11036        assert!(body.contains("add retries"), "the task must still be there");
11037        assert!(body.contains("R2-1-1"), "{body}");
11038        assert!(body.contains("unused import"), "{body}");
11039        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
11040        assert!(
11041            body.contains("not reachable from any caller"),
11042            "the reason it was declined: {body}"
11043        );
11044    }
11045
11046    #[test]
11047    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
11048        let round = ReviewRound {
11049            round: 1,
11050            head: "deadbee".to_owned(),
11051            verified_head: None,
11052            verified_at: None,
11053            reviews: vec![ReviewRecord {
11054                attempts: 0,
11055                reviewer: 1,
11056                agent: "alpha".to_owned(),
11057                summary: String::new(),
11058                findings: Vec::new(),
11059                vote: None,
11060                failed: None,
11061                duration_ms: 0,
11062            }],
11063            e2e: Vec::new(),
11064            verify_retried: false,
11065            e2e_deferred: false,
11066            e2e_defer_reason: None,
11067            fix: None,
11068            blocking: 0,
11069            answered: 1,
11070            expected: 1,
11071            clean: true,
11072            progressed: false,
11073            vote_split: false,
11074            reconsideration: Vec::new(),
11075            verdict: None,
11076        };
11077        let state = state_with_round(round);
11078        let body = pr_message(&state, 'A').body;
11079        assert!(!body.contains("Open review findings"), "{body}");
11080        assert!(!body.contains("Declined"), "{body}");
11081    }
11082
11083    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
11084        let mut state = RunState::new(
11085            PathBuf::from("/repo"),
11086            "main".to_owned(),
11087            "abc1234".to_owned(),
11088            instruction.to_owned(),
11089            Config::default(),
11090        );
11091        state.candidates.push(Candidate {
11092            index: 0,
11093            label: 'A',
11094            agent: "alpha".to_owned(),
11095            branch: "magi/x/A".to_owned(),
11096            worktree: PathBuf::from("/wt"),
11097            summary: summary.to_owned(),
11098            stat: String::new(),
11099            files: 1,
11100            commits: 1,
11101            empty: false,
11102            failed: None,
11103            verified_noop: None,
11104            folded: false,
11105            duration_ms: 0,
11106        });
11107        state
11108    }
11109
11110    fn review_state(subjects: &[&str]) -> RunState {
11111        let mut state = state_with_summary(
11112            "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",
11113            "",
11114        );
11115        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
11116        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
11117        state
11118    }
11119
11120    /// A branch rebased onto a main that moved past the recorded
11121    /// `base_commit` is titled from its own first commit, never main's.
11122    #[tokio::test]
11123    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
11124        ask_test_home();
11125        let tmp = tempfile::tempdir().unwrap();
11126        let repo = tmp.path().join("repo");
11127        std::fs::create_dir_all(&repo).unwrap();
11128        init_repo(&repo);
11129        let origin = tmp.path().join("origin.git");
11130        let g = |dir: &Path, args: &[&str]| {
11131            let out = std::process::Command::new("git")
11132                .args(args)
11133                .current_dir(dir)
11134                .quiet()
11135                .output()
11136                .expect("spawn git");
11137            assert!(
11138                out.status.success(),
11139                "git {args:?}: {}",
11140                String::from_utf8_lossy(&out.stderr)
11141            );
11142        };
11143        g(
11144            tmp.path(),
11145            &[
11146                "clone",
11147                "--bare",
11148                "-q",
11149                repo.to_str().unwrap(),
11150                origin.to_str().unwrap(),
11151            ],
11152        );
11153        g(
11154            &repo,
11155            &["remote", "add", "origin", origin.to_str().unwrap()],
11156        );
11157        let c1 = git::rev_parse(&repo, "main").await.unwrap();
11158
11159        // Main moves on; the branch is built on top of the new main.
11160        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
11161        g(&repo, &["add", "-A"]);
11162        g(
11163            &repo,
11164            &["commit", "-q", "-m", "chore(deps): update a crate"],
11165        );
11166        g(&repo, &["push", "-q", "origin", "main"]);
11167        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
11168        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
11169        g(&repo, &["add", "-A"]);
11170        g(
11171            &repo,
11172            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
11173        );
11174        g(&repo, &["checkout", "-q", "main"]);
11175
11176        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
11177        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
11178        // Without a readable tracking ref the recorded base's merge base is used.
11179        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
11180        assert_eq!(fallback, c1);
11181
11182        let mut state = review_state(&[
11183            "chore(deps): update a crate",
11184            "fix(daemon): apply a chosen action",
11185        ]);
11186        state.repo = repo.clone();
11187        state.base_branch = "main".to_owned();
11188        state.base_commit = c1;
11189        refresh_reviewed_commits(&mut state, "feat/own").await;
11190        assert_eq!(
11191            state.reviewed_commits,
11192            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
11193        );
11194        assert_eq!(
11195            review_title(&state).as_deref(),
11196            Some("fix(daemon): apply a chosen action")
11197        );
11198        assert_eq!(
11199            leaked_subjects(&state, "feat/own").await,
11200            Some(vec!["chore(deps): update a crate".to_owned()])
11201        );
11202        // A stale tracking ref is still used when the fetch fails, but the
11203        // leak list is withheld.
11204        state.config.merge.remote = "nowhere".to_owned();
11205        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
11206    }
11207
11208    #[test]
11209    fn pr_message_review_single_commit_uses_its_subject() {
11210        let state = review_state(&["feat(nats): per-role user"]);
11211        let m = pr_message(&state, 'A');
11212        assert_eq!(m.title, "feat(nats): per-role user");
11213        assert!(!m.body.contains("Review the work already"), "{}", m.body);
11214        assert!(m.body.contains("## Commits under review"), "{}", m.body);
11215    }
11216
11217    #[test]
11218    fn pr_message_review_multi_commit_takes_the_oldest() {
11219        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
11220        let m = pr_message(&state, 'A');
11221        assert_eq!(m.title, "feat: the change");
11222        for s in ["feat: the change", "fix: typo", "fix: again"] {
11223            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
11224        }
11225    }
11226
11227    #[test]
11228    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
11229        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
11230            let mut state = review_state(&[first, "fix: later fixup"]);
11231            state.candidates[0].branch = "機能/ログイン".to_owned();
11232            let m = pr_message(&state, 'A');
11233            assert!(
11234                m.title.starts_with("chore: land candidate A of run"),
11235                "{}",
11236                m.title
11237            );
11238        }
11239    }
11240
11241    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
11242        BranchFacts {
11243            commits: commits
11244                .iter()
11245                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
11246                .collect(),
11247            stat: stat.to_owned(),
11248        }
11249    }
11250
11251    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
11252        let mut r = review_round(true, 0, 1, 1, true, true);
11253        r.round = round;
11254        r.fix = notes.map(|n| FixRecord {
11255            agent: "fixer".to_owned(),
11256            addressed: Vec::new(),
11257            rejected: Vec::new(),
11258            notes: n.to_owned(),
11259            committed: true,
11260            failed: None,
11261            duration_ms: 0,
11262            continuation: None,
11263        });
11264        r
11265    }
11266
11267    #[test]
11268    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
11269        let state = review_state(&["ignored"]);
11270        let f = facts(
11271            &[
11272                (
11273                    "fix(login): resolve PATH on macOS",
11274                    "Login shells skip rc files.",
11275                ),
11276                ("fix: address review", ""),
11277            ],
11278            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
11279        );
11280        let m = pr_message_with(&state, 'A', Some(&f));
11281        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
11282        assert!(
11283            m.body
11284                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
11285            "{}",
11286            m.body
11287        );
11288        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
11289        assert!(m.body.contains("## Diff stat"), "{}", m.body);
11290        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
11291        for banned in [
11292            "Review the work already",
11293            "no task statement",
11294            "Original task",
11295        ] {
11296            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
11297        }
11298        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
11299    }
11300
11301    #[test]
11302    fn pr_message_review_truncates_a_huge_first_commit_body() {
11303        let state = review_state(&["ignored"]);
11304        let f = facts(
11305            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
11306            "s",
11307        );
11308        let m = pr_message_with(&state, 'A', Some(&f));
11309        assert!(m.body.len() < 30_000, "{}", m.body.len());
11310        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
11311        assert!(
11312            m.body.contains("- ... 1 more commit(s)"),
11313            "{}",
11314            m.body.len()
11315        );
11316        assert!(m.body.ends_with("magi:candidate-a\n"));
11317    }
11318
11319    #[test]
11320    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
11321        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
11322        assert_eq!(m.title, "feat: x");
11323        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
11324        assert!(!m.body.contains("Diff stat"), "{}", m.body);
11325        assert!(!m.body.contains("no task statement"), "{}", m.body);
11326    }
11327
11328    #[test]
11329    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
11330        let mut state = review_state(&["日本語の件名"]);
11331        state.candidates[0].branch = "fix/macos-login-path".to_owned();
11332        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
11333        state.candidates[0].branch = "機能/ログイン".to_owned();
11334        assert!(
11335            pr_message(&state, 'A')
11336                .title
11337                .starts_with("chore: land candidate A")
11338        );
11339    }
11340
11341    #[test]
11342    fn pr_message_review_fixes_survive_a_clean_final_round() {
11343        let mut state = review_state(&["feat: x"]);
11344        state.reviews = vec![
11345            round_with_notes(1, Some("handled the PATH case")),
11346            round_with_notes(2, None),
11347        ];
11348        let body = pr_message(&state, 'A').body;
11349        assert!(
11350            body.contains("## Review fixes\n\nhandled the PATH case\n"),
11351            "{body}"
11352        );
11353        assert!(!body.contains("### Round"), "{body}");
11354
11355        state.reviews = vec![
11356            round_with_notes(1, Some("first fix")),
11357            round_with_notes(2, Some("")),
11358            round_with_notes(3, Some("second fix")),
11359            round_with_notes(4, None),
11360        ];
11361        let body = pr_message(&state, 'A').body;
11362        assert!(body.contains("### Round 1\n\nfirst fix"), "{body}");
11363        assert!(body.contains("### Round 3\n\nsecond fix"), "{body}");
11364        assert!(!body.contains("### Round 2"), "{body}");
11365    }
11366
11367    #[test]
11368    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
11369        let state = state_with_summary(
11370            "add retries to the client",
11371            "TITLE: feat: retries\n\nDid it.",
11372        );
11373        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
11374        assert_eq!(m.title, "feat: retries");
11375        assert!(
11376            m.body.contains("<summary>Original task</summary>"),
11377            "{}",
11378            m.body
11379        );
11380        assert!(!m.body.contains("Commits under review"), "{}", m.body);
11381        assert!(
11382            m.body
11383                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
11384            "{}",
11385            m.body
11386        );
11387    }
11388
11389    #[test]
11390    fn pr_message_review_bounds_a_long_english_subject() {
11391        let long = format!("feat: {}", "word ".repeat(100));
11392        let m = pr_message(&review_state(&[&long]), 'A');
11393        assert!(m.title.starts_with("feat: word"), "{}", m.title);
11394        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11395    }
11396
11397    #[test]
11398    fn pr_message_implementation_run_is_unchanged_by_review_support() {
11399        let state = state_with_summary("add retries\n\ndetails", "- did some things");
11400        let m = pr_message(&state, 'A');
11401        assert_eq!(m.title, "add retries");
11402        assert!(m.body.contains("<summary>Original task</summary>"));
11403        assert!(!m.body.contains("Commits under review"));
11404        assert_eq!(landing_subject_source(&state), state.instruction);
11405    }
11406
11407    #[test]
11408    fn review_run_squash_subject_is_the_change_not_the_prompt() {
11409        let state = review_state(&["feat: the change", "fix: typo"]);
11410        let source = landing_subject_source(&state);
11411        assert_eq!(land::merge_subject("", &source), "feat: the change");
11412        assert_eq!(
11413            land::merge_subject("magi: candidate A (uncommitted work)", &source),
11414            "feat: the change"
11415        );
11416        // An operator's rename still wins.
11417        assert_eq!(
11418            land::merge_subject("feat: renamed by hand", &source),
11419            "feat: renamed by hand"
11420        );
11421        let blank = review_state(&["日本語"]);
11422        assert!(
11423            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
11424        );
11425    }
11426
11427    #[test]
11428    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
11429        let state = review_state(&["feat: the change"]);
11430        let source = landing_subject_source(&state);
11431        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
11432        assert_eq!(
11433            land::merge_subject(landing_title(&state, old), &source),
11434            "feat: the change"
11435        );
11436        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
11437        let task = state_with_summary("add retries", "");
11438        assert_eq!(landing_title(&task, old), old);
11439    }
11440
11441    #[test]
11442    fn pr_message_describes_the_change_not_the_task() {
11443        let state = state_with_summary(
11444            "今回やってほしいこと: results projector を直す",
11445            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
11446        );
11447        let m = pr_message(&state, 'A');
11448        assert_eq!(m.title, "fix(web): batch the runs list reads");
11449        assert!(
11450            m.body.starts_with("## Summary\n\n- reads run.json once"),
11451            "{}",
11452            m.body
11453        );
11454        assert!(!m.body.contains("TITLE:"), "{}", m.body);
11455        let task_at = m.body.find("今回やってほしいこと").unwrap();
11456        let details_at = m.body.find("<details>").unwrap();
11457        assert!(
11458            details_at < task_at,
11459            "the task lives inside <details>: {}",
11460            m.body
11461        );
11462        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
11463        assert!(m.body.contains("magi:candidate-a"));
11464    }
11465
11466    #[test]
11467    fn pr_message_falls_back_to_the_task_without_a_title_line() {
11468        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
11469        let m = pr_message(&state, 'A');
11470        assert_eq!(m.title, "add retries");
11471        assert!(
11472            m.body.contains("## Summary\n\n- did some things"),
11473            "{}",
11474            m.body
11475        );
11476
11477        let none = RunState::new(
11478            PathBuf::from("/repo"),
11479            "main".to_owned(),
11480            "abc1234".to_owned(),
11481            "add retries".to_owned(),
11482            Config::default(),
11483        );
11484        let m = pr_message(&none, 'A');
11485        assert_eq!(m.title, "add retries");
11486        assert!(!m.body.contains("## Summary"), "{}", m.body);
11487    }
11488
11489    #[test]
11490    fn pr_message_refuses_the_candidate_commit_subject() {
11491        for bad in [
11492            "TITLE: magi: candidate A (uncommitted work)",
11493            "TITLE: chore: stuff (uncommitted work)",
11494            "TITLE:   ",
11495        ] {
11496            let state = state_with_summary("add retries", bad);
11497            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
11498        }
11499    }
11500
11501    #[test]
11502    fn pr_message_bounds_a_very_long_task_and_title() {
11503        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
11504        let state = state_with_summary(&long, "- nothing");
11505        let m = pr_message(&state, 'A');
11506        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11507        assert!(!m.title.contains('\n'));
11508
11509        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
11510        let m = pr_message(&state, 'A');
11511        assert!(m.title.starts_with("feat: "));
11512        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11513        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
11514    }
11515
11516    fn long_title_of(instruction: &str) -> String {
11517        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
11518    }
11519
11520    #[test]
11521    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
11522        let first = "Make the landing path keep a readable title for long tasks";
11523        let line = format!(
11524            "{first}. {}",
11525            "And then keep going with more words ".repeat(20)
11526        );
11527        let t = long_title_of(&line);
11528        assert_eq!(t, first);
11529        assert!(!t.starts_with("chore: land"));
11530    }
11531
11532    #[test]
11533    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
11534        let line = "word ".repeat(200);
11535        let t = long_title_of(&line);
11536        assert!(t.ends_with("word..."), "{t}");
11537        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
11538    }
11539
11540    #[test]
11541    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
11542        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
11543            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
11544        }
11545    }
11546
11547    #[test]
11548    fn pr_message_title_limit_is_exact() {
11549        let at = "a".repeat(PR_TITLE_MAX);
11550        assert_eq!(long_title_of(&at), at);
11551        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
11552        assert!(over.ends_with("..."), "{over}");
11553        assert_eq!(over.chars().count(), PR_TITLE_MAX);
11554    }
11555
11556    #[test]
11557    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
11558        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
11559        let t = long_title_of(&line);
11560        assert!(t.ends_with("..."), "{t}");
11561        assert!(t.is_ascii(), "{t}");
11562    }
11563
11564    #[test]
11565    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
11566        let line = format!(
11567            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
11568            "plus more filler words ".repeat(20)
11569        );
11570        let t = long_title_of(&line);
11571        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
11572    }
11573
11574    #[test]
11575    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
11576        let line = format!("\n\n# {}", "title words ".repeat(40));
11577        let state = state_with_summary(&line, "- nothing");
11578        let m = pr_message(&state, 'A');
11579        assert!(m.title.starts_with("title words"), "{}", m.title);
11580        assert_eq!(
11581            land::merge_subject(&m.title, &landing_subject_source(&state)),
11582            m.title
11583        );
11584        // An operator's rename wins untouched.
11585        assert_eq!(
11586            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
11587            "feat: renamed by hand"
11588        );
11589    }
11590
11591    #[test]
11592    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
11593        // What magi itself writes stays English under any configured language,
11594        // so a future localisation of these headings fails here. (The agents'
11595        // own text is held to English by the prompt only; magi cannot check it.)
11596        let mut state = state_with_summary(
11597            "add retries",
11598            "TITLE: fix(web): batch reads\n- reads run.json once",
11599        );
11600        state.config.graph.language = "ja".to_owned();
11601        let m = pr_message(&state, 'A');
11602        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
11603
11604        // The task is the operator's own text: it goes in untouched, and the
11605        // fallback title (no summary) may be in its language too.
11606        let task = "今回やってほしいこと: results projector を直す";
11607        let mut state = state_with_summary(task, "- no title line");
11608        state.config.graph.language = "ja".to_owned();
11609        let m = pr_message(&state, 'A');
11610        assert_eq!(
11611            m.title,
11612            format!("chore: land candidate A of run {}", state.id)
11613        );
11614        assert!(
11615            m.body.contains(&format!(
11616                "<summary>Original task</summary>\n\n{task}\n\n</details>"
11617            )),
11618            "{}",
11619            m.body
11620        );
11621    }
11622
11623    #[test]
11624    fn pr_message_scrubs_home_paths_and_addresses() {
11625        let state = state_with_summary(
11626            "fix it in /Users/someone/src/x",
11627            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
11628        );
11629        let m = pr_message(&state, 'A');
11630        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
11631            assert!(!m.body.contains(leak), "{}", m.body);
11632        }
11633        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
11634    }
11635
11636    #[test]
11637    fn pr_message_survives_a_task_that_closes_details() {
11638        let state = state_with_summary("a </details> b", "TITLE: fix: x");
11639        let m = pr_message(&state, 'A');
11640        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
11641    }
11642
11643    #[test]
11644    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
11645        let cmd = manual_merge_command(
11646            MergeStyle::Squash,
11647            Path::new("/repo"),
11648            "b",
11649            "fix: \"quoted\" $(x) `y`\n\nbody",
11650        );
11651        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
11652    }
11653
11654    #[test]
11655    fn manual_merge_command_matches_the_configured_style() {
11656        let repo = Path::new("/repo");
11657        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
11658
11659        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
11660        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
11661
11662        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
11663        assert_eq!(
11664            squash,
11665            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
11666             \"Merge magi run 0832 (candidate A)\""
11667        );
11668
11669        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
11670        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
11671    }
11672
11673    #[test]
11674    fn a_nudge_gets_a_quarter_of_the_budget() {
11675        // The judge and implement budgets magi ships with.
11676        assert_eq!(retry_budget(secs(1200), true), secs(300));
11677        assert_eq!(retry_budget(secs(3600), true), secs(900));
11678    }
11679
11680    #[test]
11681    fn a_resent_prompt_keeps_the_whole_budget() {
11682        // The seat kept no context, so the retry is the original job again and
11683        // shortening it would only guarantee a second failure.
11684        assert_eq!(retry_budget(secs(1200), false), secs(1200));
11685        assert_eq!(retry_budget(secs(60), false), secs(60));
11686    }
11687
11688    #[test]
11689    fn the_floor_never_exceeds_the_original_budget() {
11690        // A short configured timeout must not be *raised* by the floor: the
11691        // operator asked for a bound, and a retry may not outlast the attempt
11692        // it is retrying.
11693        assert_eq!(retry_budget(secs(60), true), secs(60));
11694        assert_eq!(retry_budget(secs(480), true), secs(120));
11695        assert_eq!(retry_budget(secs(0), true), secs(0));
11696    }
11697
11698    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
11699        agent::CommandEvidence {
11700            id: "item1".to_owned(),
11701            description: "cargo test".to_owned(),
11702            exit_code,
11703            result_summary: String::new(),
11704            source: "codex".to_owned(),
11705        }
11706    }
11707
11708    #[test]
11709    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
11710        // No evidence is not the same fact as unconfirmed evidence: a
11711        // backend with no adapter, or a reply that ran no commands at all,
11712        // must not be misread as carrying a dangling job.
11713        assert!(!has_unconfirmed_command(&[]));
11714    }
11715
11716    #[test]
11717    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
11718        // Deliberately not a check on the exit code's *value*: a fixer
11719        // legitimately runs something that fails mid-iteration before it
11720        // succeeds, and that must never by itself reopen a valid report.
11721        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
11722        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
11723        assert!(!has_unconfirmed_command(&[
11724            evidence(Some(0)),
11725            evidence(Some(101))
11726        ]));
11727    }
11728
11729    #[test]
11730    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
11731        assert!(has_unconfirmed_command(&[
11732            evidence(Some(0)),
11733            evidence(None)
11734        ]));
11735    }
11736
11737    #[test]
11738    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
11739        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11740        assert_eq!(
11741            verified_noop_claim(true, &[], text).as_deref(),
11742            Some("already fixed by b32cfc4, on main.")
11743        );
11744    }
11745
11746    #[test]
11747    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
11748        // A timeout or a bad exit code reads as the ordinary loss it is,
11749        // whatever the reply's own prose claims.
11750        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11751        assert!(verified_noop_claim(false, &[], text).is_none());
11752    }
11753
11754    #[test]
11755    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
11756        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11757        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
11758        // A confirmed command alongside the marker is fine.
11759        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
11760    }
11761
11762    #[test]
11763    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
11764        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
11765    }
11766
11767    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
11768    /// pair, in order, labelled A, B, C, ...
11769    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
11770        runner.state.candidates = shape
11771            .iter()
11772            .enumerate()
11773            .map(|(i, &(empty, verified))| Candidate {
11774                index: i,
11775                label: (b'A' + i as u8) as char,
11776                agent: "sonnet".to_owned(),
11777                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
11778                worktree: PathBuf::from(format!("/wt/{i}")),
11779                summary: String::new(),
11780                stat: String::new(),
11781                files: 0,
11782                commits: 0,
11783                empty,
11784                failed: None,
11785                verified_noop: verified.map(str::to_owned),
11786                duration_ms: 0,
11787                folded: false,
11788            })
11789            .collect();
11790    }
11791
11792    #[test]
11793    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
11794        ask_test_home();
11795        let mut runner = runner_at(RunStatus::Implementing);
11796        set_candidates(
11797            &mut runner,
11798            &[
11799                (true, Some("already on main at b32cfc4")),
11800                (true, Some("same fix, see the existing test")),
11801            ],
11802        );
11803
11804        runner
11805            .after_implement()
11806            .expect("a verified no-op is not an error");
11807
11808        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
11809    }
11810
11811    #[test]
11812    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
11813        ask_test_home();
11814        let mut runner = runner_at(RunStatus::Implementing);
11815        // Candidate A declares a verified no-op; candidate B simply wrote
11816        // nothing and said nothing about why. One candidate's claim is not
11817        // the whole run's agreement.
11818        set_candidates(
11819            &mut runner,
11820            &[(true, Some("already on main at b32cfc4")), (true, None)],
11821        );
11822
11823        let err = runner
11824            .after_implement()
11825            .expect_err("an unverified empty candidate must still fail the run");
11826
11827        assert!(
11828            err.to_string().contains("no candidate produced a change"),
11829            "{err}"
11830        );
11831        assert_eq!(runner.state.status, RunStatus::Failed);
11832    }
11833
11834    #[test]
11835    fn after_implement_still_fails_an_ordinary_all_empty_run() {
11836        ask_test_home();
11837        let mut runner = runner_at(RunStatus::Implementing);
11838        set_candidates(&mut runner, &[(true, None), (true, None)]);
11839
11840        let err = runner
11841            .after_implement()
11842            .expect_err("no candidate declared anything; this is an ordinary failure");
11843
11844        assert!(
11845            err.to_string().contains("no candidate produced a change"),
11846            "{err}"
11847        );
11848        assert_eq!(runner.state.status, RunStatus::Failed);
11849    }
11850}