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::git;
39use crate::land;
40use crate::proc::Quiet as _;
41use crate::prompt::{
42    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
43};
44use crate::queue;
45use crate::refs;
46use crate::run::{
47    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
48    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord, Handover,
49    JobRecord, JobStatus, Judgement, MergeOutcome, OperatorFixFinding, OperatorFixOutcome,
50    OperatorFixRequest, Origin, QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState,
51    RunStatus, SeatHistory, Tally, VoteRecord, tail, write_artifact,
52};
53use crate::verdict::{
54    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
55    ReviewVote, Severity,
56};
57
58/// How much verification output is kept and fed back to the fixer.
59const OUTPUT_TAIL: usize = 8_000;
60
61/// Bytes of a failing command's output kept in an event, so the reason a run
62/// stopped is readable from the report without opening `run.json`.
63const EVENT_OUTPUT_TAIL: usize = 2_000;
64
65/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
66/// command's pid before releasing the build cache's lease.
67const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
68
69/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
70/// command's pid to actually exit before giving up and releasing anyway.
71///
72/// A timeout means the process was asked to die (`kill_on_drop`,
73/// `start_kill`), not that it already has — on Windows in particular that can
74/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
75/// the instant the command returns would let the very next acquirer (this
76/// run's own next round, another run's verification, the janitor's prune)
77/// start touching the same directory while it might still be writing to it,
78/// so this polls the actual pid — real confirmation, not a fixed guess —
79/// until it is gone or this ceiling is reached. It is still not full
80/// process-tree reaping: a grandchild the timed-out process spawned and that
81/// outlives it independently is invisible to a pid check, and continuing to
82/// observe and collect *that* stays a different piece of work with its own
83/// owner. Set generously because the common case returns early the moment
84/// the pid is confirmed gone, not because every timeout pays this in full.
85const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
86
87/// Consecutive review rounds with no tree progress (see
88/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
89/// instead of spending the rest of the round budget.
90///
91/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
92/// legitimately finds nothing left to change (its previous round's fix already
93/// covered it, and this round's reviewers re-raised only nits) looks the same
94/// as one that is spinning, for exactly one round. Two in a row is where the
95/// two stop being distinguishable, and a review round on this workload has
96/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
97/// third attempt at a tree that has not moved twice running is pure cost.
98/// This does not touch `review_rounds` itself, which stays the operator's
99/// call.
100pub(crate) const STAGNANT_LIMIT: usize = 2;
101
102/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
103/// a base that moved before giving up and leaving the run `Blocked` for a
104/// person.
105///
106/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
107/// that keeps moving faster than a run can catch it is not something more
108/// rebasing fixes, it is a person's call. Not the same *number as*
109/// `land_rounds` - this budget is spent before a pull request exists, land's
110/// after - but bounded for the identical reason, so it uses the same
111/// default. Counted across both call sites in [`Runner::finish_after_tally`]
112/// (once before review, once before the gate), because either one finding
113/// the base still moving is the same signal.
114const BASE_SYNC_ROUNDS: usize = 4;
115
116/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
117/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
118/// reply held no [`FixReport`].
119///
120/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
121/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
122/// "I'll pause here until the `cargo make check` background run reports
123/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
124/// No `FixReport` was ever collected from that seat, and the run moved on to
125/// the next review round regardless.
126///
127/// Bounded independently of `review_rounds` and `graph.retries`: this
128/// recovers one seat's missing report mid-round, not a new round of review or
129/// an ordinary parse retry, and must not itself become the unbounded wait the
130/// rest of this module exists to avoid.
131const MAX_FIX_CONTINUATIONS: usize = 2;
132
133/// One queued agent invocation.
134///
135/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
136/// CLI hung up on its own stream is asked again from the same job rather than
137/// rebuilt from scratch. See [`Runner::resume_undelivered`].
138#[derive(Clone)]
139struct SeatJob {
140    spec: AgentSpec,
141    seat: SeatState,
142    cwd: PathBuf,
143    prompt: String,
144    timeout: Duration,
145    allow_write: bool,
146    sessions: bool,
147    artifacts: PathBuf,
148    stem: String,
149    /// The prompt for a seat that has been handed to another roster agent
150    /// (a fresh session): everything the original seat would have
151    /// remembered. `None` when `prompt` already carries it, as the first
152    /// ranking and the implement prompt do. Never a resume-style prompt.
153    handover: Option<String>,
154}
155
156/// How the graph reads one agent invocation.
157///
158/// Quota is split out from an ordinary failure on purpose: a rate-limited call
159/// is known to fail again if retried now, so the retry loop must not spend an
160/// attempt on it. `Dropped` is split out for the opposite reason: unlike
161/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
162/// error JSON, never the agent's answer — a caller that matched only
163/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
164/// left to read that JSON as if it were usable output. `resume_undelivered`
165/// is the only caller that acts on it; everywhere else it is reported like an
166/// ordinary failure.
167enum AgentOutcome {
168    /// A usable output.
169    Ok(AgentOutput),
170    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
171    Quota(AgentOutput),
172    /// The CLI hung up on its own stream after billed work. See
173    /// [`agent::AgentOutput::work_undelivered`].
174    Dropped(AgentOutput),
175    /// Any other failure: a timeout, a bad exit code, an empty reply.
176    Failed(String),
177}
178
179/// A request to park the run at its next node boundary.
180///
181/// Cloning is how the request travels: the loop keeps one handle and hands a
182/// clone to each [`Runner`], and every clone points at the same flag. There
183/// is no channel because there is nothing to send - the only message is
184/// "park", it is idempotent, and a flag cannot be missed by a receiver that
185/// was not listening yet.
186///
187/// The boundary is what makes this cheap. Every node writes the run's state
188/// before the next one starts, and every node skips what is already recorded:
189/// `prep` returns early once candidates exist, `implement` asks only the seats
190/// with nothing on disk, `judge` returns early once judgements exist. So a
191/// parked run resumes into exactly the node it stopped before, and no agent
192/// work is thrown away. Killing the process mid-node, by contrast, loses
193/// whatever the seats in flight had not yet written - which for an implement
194/// wave is an hour of paid work.
195///
196/// A [`Runner`] watches two independent handles of this type - see
197/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
198/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
199/// clone covering the whole daemon's lifetime and is never asked to un-park,
200/// which is correct exactly because nothing is dispatched after it fires.
201/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
202/// that parks for an interrupted task must go on to run other tasks
203/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
204/// reusing the daemon-wide one.
205#[derive(Debug, Clone, Default)]
206pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<String>>>);
207
208impl Pause {
209    /// A pause nobody has asked for yet.
210    #[must_use]
211    pub fn new() -> Self {
212        Self::default()
213    }
214
215    /// Ask the run to park at its next node boundary. Idempotent.
216    pub fn park(&self) {
217        self.0.store(true, Ordering::SeqCst);
218    }
219
220    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
221    /// fold into the run's own `park` event - so an operator reading the run
222    /// later knows this was a deliberate interrupt rather than a shutdown or
223    /// a binary swap. The first reason recorded wins; a park already in
224    /// flight is not relabelled by a second, unrelated request.
225    pub fn park_because(&self, reason: impl Into<String>) {
226        let mut reason_guard = self
227            .1
228            .lock()
229            .unwrap_or_else(std::sync::PoisonError::into_inner);
230        if reason_guard.is_none() {
231            *reason_guard = Some(reason.into());
232        }
233        drop(reason_guard);
234        self.park();
235    }
236
237    /// Has a park been asked for?
238    #[must_use]
239    pub fn parked(&self) -> bool {
240        self.0.load(Ordering::SeqCst)
241    }
242
243    /// Why the park was asked for, when the caller used [`Pause::park_because`].
244    #[must_use]
245    pub fn reason(&self) -> Option<String> {
246        self.1
247            .lock()
248            .unwrap_or_else(std::sync::PoisonError::into_inner)
249            .clone()
250    }
251}
252
253/// Drives one run.
254pub struct Runner {
255    /// Run state; public so the CLI can report on it.
256    pub state: RunState,
257    roles: ResolvedRoles,
258    sem: Arc<Semaphore>,
259    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
260    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
261    /// this is never the same handle as `interrupt`.
262    pause: Pause,
263    /// Set when `magi serve`'s interrupt scheduler wants this specific run
264    /// parked at its next node boundary, to let a task marked
265    /// [`crate::queue::Task::interrupt`] run alone before this one carries
266    /// on. Unlike `pause`, a fresh, unshared handle per run - see
267    /// [`Runner::watch_interrupt`].
268    interrupt: Pause,
269}
270
271/// Where the branch's own commits start: its merge base with the base branch
272/// as the remote has it now, else with the recorded `base_commit`. A branch
273/// rebased onto a base that moved past `base_commit` would otherwise count
274/// the base's commits as its own under `base_commit..branch`.
275async fn review_base(
276    repo: &Path,
277    remote: &str,
278    base_branch: &str,
279    base_commit: &str,
280    branch: &str,
281) -> String {
282    review_base_checked(repo, remote, base_branch, base_commit, branch)
283        .await
284        .0
285}
286
287/// [`review_base`] plus whether the base was read from a freshly fetched
288/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
289/// never older than `base_commit`'s view of the base), but the answer is then
290/// not trusted to rewrite a pull request's title.
291async fn review_base_checked(
292    repo: &Path,
293    remote: &str,
294    base_branch: &str,
295    base_commit: &str,
296    branch: &str,
297) -> (String, bool) {
298    let tracking = format!("{remote}/{base_branch}");
299    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
300    if git::rev_exists(repo, &tracking).await
301        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
302        && !mb.is_empty()
303    {
304        return (mb, fresh);
305    }
306    let mb = git::merge_base(repo, base_commit, branch)
307        .await
308        .ok()
309        .filter(|mb| !mb.is_empty())
310        .unwrap_or_else(|| base_commit.to_owned());
311    (mb, false)
312}
313
314/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
315/// when git cannot say or finds nothing: a stale list is better than a wrong
316/// or empty one.
317pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
318    if !is_review_run(state) {
319        return;
320    }
321    let base = review_base(
322        &state.repo,
323        &state.config.merge.remote,
324        &state.base_branch,
325        &state.base_commit,
326        branch,
327    )
328    .await;
329    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
330        && !subjects.is_empty()
331        && state.reviewed_commits.as_ref() != Some(&subjects)
332    {
333        state.reviewed_commits = Some(subjects);
334        state.save().ok();
335    }
336}
337
338/// Subjects of the base's commits between the recorded start and the branch's
339/// merge base: what a stale `base_commit..branch` would have mistaken for the
340/// branch's own work.
341async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
342    let (base, trusted) = review_base_checked(
343        &state.repo,
344        &state.config.merge.remote,
345        &state.base_branch,
346        &state.base_commit,
347        branch,
348    )
349    .await;
350    if !trusted {
351        return None;
352    }
353    git::subjects(&state.repo, &state.base_commit, &base)
354        .await
355        .ok()
356}
357
358/// May an adopted pull request's title be replaced with `computed`? Only when
359/// it is empty, magi's own shape, or a base commit's subject that leaked in;
360/// a title a person wrote stays. Never when `computed` is itself a leak.
361fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
362    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
363    if is_leak(computed) {
364        return false;
365    }
366    let cur = current.trim();
367    cur.is_empty()
368        || cur.starts_with(REVIEW_PROMPT_OPENING)
369        || cur.starts_with("chore: land candidate")
370        || cur.starts_with("magi: candidate")
371        || is_leak(cur)
372}
373
374/// The commit a run branches from: the base branch as the remote has it.
375///
376/// Two failures this replaces. A run used to branch off `HEAD` and so refused
377/// to start on a dirty tree, which made `magi serve` decline every task for as
378/// long as the operator had work in progress - most of the time. Branching off
379/// the *local* base branch fixed that and introduced a worse one: `land` merges
380/// the winner on GitHub, nothing updates the local ref, and the next run
381/// branches off a base missing everything the previous runs landed. Two tasks
382/// in a row from a phone would have had the second silently re-implementing
383/// against stale code and opening a pull request that reverted the first.
384///
385/// Only refs move here - no checkout, no local branch, no merge - so it is safe
386/// with uncommitted work in the tree. A machine with no network still starts:
387/// the fetch may fail and the local tip is used with a warning, because
388/// refusing to run offline is a worse failure than running against a base the
389/// operator can see for themselves.
390///
391/// One function, called by both entry points. Two answers to "where does a run
392/// branch from" is the kind of drift nobody notices until a diff is wrong.
393/// Bring the local `branch` in line with `<remote>/<branch>` before a review
394/// checks it out.
395///
396/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
397/// anything other than plain `git push` from this checkout (a jj colocated
398/// workspace, another clone) moves only the remote-tracking ref - so the local
399/// one can be a stale placeholder. It moves only when local is behind the remote or is an
400/// empty placeholder that diverged from it; unpushed local work is kept, and a real
401/// divergence is refused rather than guessed at.
402async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
403    let tracking = format!("{remote}/{branch}");
404    let fetched = git::fetch(repo, remote, branch).await;
405    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
406    let local_exists = git::branch_exists(repo, branch).await?;
407    if !fresh {
408        if !local_exists {
409            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
410        }
411        tracing::warn!(
412            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
413        );
414        return Ok(());
415    }
416    let remote_sha = git::rev_parse(repo, &tracking).await?;
417    if !local_exists {
418        git::git(repo, &["branch", branch, &tracking]).await?;
419        return Ok(());
420    }
421    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
422    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
423        return Ok(());
424    }
425    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
426        // Diverged. `reconcile` settles it only when it can prove nothing is
427        // lost: a local tip that is the remote's change rebased is pushed over
428        // it (lease pinned to the tip read here), a tip whose every extra
429        // commit is empty is a placeholder the remote's work replaced, and
430        // anything else is two different changes - a question for a person.
431        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
432            .await?
433        {
434            crate::reconcile::Reconciliation::Pushed => {
435                tracing::warn!(
436                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
437                    short(&local_sha),
438                    short(&remote_sha)
439                );
440                return Ok(());
441            }
442            crate::reconcile::Reconciliation::Placeholder => {}
443            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
444        }
445    }
446    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
447    if !out.ok() {
448        bail!(
449            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
450            short(&local_sha),
451            short(&remote_sha),
452            out.stderr
453        );
454    }
455    tracing::warn!(
456        "local `{branch}` was stale: fast-forwarded {} -> {}",
457        short(&local_sha),
458        short(&remote_sha)
459    );
460    Ok(())
461}
462
463async fn resolve_base(repo: &Path, base_branch: &str, remote: &str) -> Result<String> {
464    let tracking = format!("{remote}/{base_branch}");
465    let fetched = git::fetch(repo, remote, base_branch).await;
466    if let Ok(out) = &fetched
467        && out.ok()
468        && git::rev_exists(repo, &tracking).await
469    {
470        return git::rev_parse(repo, &tracking).await;
471    }
472    let why = match &fetched {
473        Ok(out) if !out.ok() => out.stderr.lines().next().unwrap_or("").to_owned(),
474        Ok(_) => format!("{remote} has no {base_branch}"),
475        Err(e) => e.to_string(),
476    };
477    tracing::warn!(
478        "could not read {tracking} ({why}); branching off the local \
479         {base_branch} instead, which may be behind"
480    );
481    git::rev_parse(repo, base_branch).await.with_context(|| {
482        format!(
483            "cannot resolve `{base_branch}`; set [merge] base in magi.toml to a \
484             branch that exists"
485        )
486    })
487}
488
489/// Exclusive claim on one run's `magi fix` step, released on drop — including
490/// on an early return or a panic.
491///
492/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
493/// manual `magi fix` invocations against the same run are otherwise
494/// invisible to each other and would race to remove and recreate the same
495/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
496/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
497/// which is only ever reclaimed later, out of band, by
498/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
499/// `magi fix` invocation is not necessarily running under either of those, so
500/// nothing would ever sweep a lock a killed or crashed process left behind.
501/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
502/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
503/// lease use: an unreadable or unparsable pid, or a liveness query the
504/// platform cannot answer, reads as alive and the lock is left in place.
505struct FixClaim {
506    path: PathBuf,
507}
508
509impl FixClaim {
510    fn acquire(dir: &Path) -> Result<Self> {
511        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
512        let path = dir.join("fix.lock");
513        match Self::create(&path) {
514            Ok(claim) => Ok(claim),
515            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
516                if Self::reclaim_if_dead(&path) {
517                    Self::create(&path).with_context(|| format!("lock {}", path.display()))
518                } else {
519                    bail!(
520                        "another `magi fix` is already running for this run ({} exists)",
521                        path.display()
522                    )
523                }
524            }
525            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
526        }
527    }
528
529    fn create(path: &Path) -> std::io::Result<Self> {
530        let mut f = std::fs::OpenOptions::new()
531            .write(true)
532            .create_new(true)
533            .open(path)?;
534        use std::io::Write as _;
535        // Read back by `reclaim_if_dead` on a later, stuck invocation.
536        writeln!(f, "{}", std::process::id())?;
537        Ok(Self {
538            path: path.to_owned(),
539        })
540    }
541
542    /// True if the lock named a process confirmed dead, in which case it was
543    /// also removed. Never true on an unreadable file, an unparsable pid, or
544    /// a liveness query the platform cannot answer — see this type's own doc.
545    fn reclaim_if_dead(path: &Path) -> bool {
546        let dead = std::fs::read_to_string(path)
547            .ok()
548            .and_then(|body| body.trim().parse::<u32>().ok())
549            .is_some_and(|pid| !crate::proc::pid_alive(pid));
550        dead && std::fs::remove_file(path).is_ok()
551    }
552}
553
554impl Drop for FixClaim {
555    fn drop(&mut self) {
556        let _ = std::fs::remove_file(&self.path);
557    }
558}
559
560impl Runner {
561    /// Start a fresh run against `repo`.
562    pub async fn start(
563        repo: &Path,
564        instruction: String,
565        config: Config,
566        origin: Origin,
567    ) -> Result<Self> {
568        Self::start_naming(repo, instruction, "", config, origin).await
569    }
570
571    /// [`Runner::start`] for a queued task: `also_scan` (the task's title) is
572    /// searched for branch and commit references along with the instruction,
573    /// since a task may name the work it is about only in its title.
574    pub async fn start_naming(
575        repo: &Path,
576        instruction: String,
577        also_scan: &str,
578        config: Config,
579        origin: Origin,
580    ) -> Result<Self> {
581        let repo = git::toplevel(repo).await?;
582        let missing = agent::missing_programs(&config.agents);
583        if !missing.is_empty() {
584            bail!(
585                "these agent programs are not on PATH: {}. Fix the roster in \
586                 magi.toml or install them.",
587                missing.join(", ")
588            );
589        }
590        let base_branch = match config.merge.base.clone() {
591            Some(b) => b,
592            None => git::current_branch(&repo)
593                .await?
594                .context("HEAD is detached; set [merge] base in magi.toml")?,
595        };
596        let base_commit = resolve_base(&repo, &base_branch, &config.merge.remote).await?;
597        // Still worth saying out loud. The operator's uncommitted work is not
598        // part of this run, and someone watching a candidate fail to use a
599        // change they just made deserves to know why.
600        if !git::is_clean(&repo).await? {
601            tracing::warn!(
602                "{} has uncommitted changes; they are not part of this run, \
603                 which branches off {base_branch} ({})",
604                repo.display(),
605                &base_commit[..base_commit.len().min(8)]
606            );
607        }
608        let roles = config.resolve_roles()?;
609        let max_parallel = config.graph.max_parallel.max(1);
610        // A task that points at work already in the repository starts from
611        // it; what the repository says about each reference is recorded.
612        let seeds = refs::resolve(
613            &repo,
614            &base_commit,
615            &config.merge.remote,
616            &format!("{also_scan}\n{instruction}"),
617        )
618        .await;
619        refs::plan(&repo, &seeds).await?;
620        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
621        // Recorded before the first save, so a crash right after minting
622        // cannot leave a run with no origin. Legibility only: nothing reads it
623        // to decide anything.
624        state.origin = Some(origin);
625        for seed in &seeds {
626            state.event(
627                "seed",
628                refs::describe(std::slice::from_ref(seed)).unwrap_or_default(),
629            );
630        }
631        state.seeds = seeds;
632        state.event("start", format!("run {} created", state.id));
633        state.save()?;
634        Ok(Self {
635            state,
636            roles,
637            sem: Arc::new(Semaphore::new(max_parallel)),
638            pause: Pause::new(),
639            interrupt: Pause::new(),
640        })
641    }
642
643    /// Open a review-only run against work that already exists on `branch`.
644    ///
645    /// The expensive half of the graph is the implement wave — measured at
646    /// 111 and 134 internal tool-loop turns on this repository, against a
647    /// handful for a judge or a reviewer. The cheap half is worth running on
648    /// hand-written work too, and there was no way to reach it.
649    ///
650    /// No new state and no schema change are needed: a run with **one** viable
651    /// candidate and a tally already decided degrades `execute` to exactly
652    /// review → gate → merge, because `judge` skips a single-candidate field,
653    /// `deliberate` has fewer than two first choices to reconcile, `vote`
654    /// returns early, `tally` is already present and `fold_losers` has no
655    /// losers. Resuming such a run therefore does the right thing as well.
656    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
657        Self::review_taking_over(repo, branch, config, None, origin).await
658    }
659
660    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
661    /// at the same task still has `branch` checked out, its worktree is
662    /// released first if that is safe (see [`crate::handover`]), and the
663    /// review refuses with the reason if it is not. `None` is a hand-run
664    /// review: it has no earlier attempts, so only a worktree of a dead run
665    /// magi recorded itself can be released.
666    pub async fn review_taking_over(
667        repo: &Path,
668        branch: &str,
669        config: Config,
670        takeover: Option<crate::handover::Takeover>,
671        origin: Origin,
672    ) -> Result<Self> {
673        let repo = git::toplevel(repo).await?;
674        let missing = agent::missing_programs(&config.agents);
675        if !missing.is_empty() {
676            bail!(
677                "these agent programs are not on PATH: {}. Fix the roster in \
678                 magi.toml or install them.",
679                missing.join(", ")
680            );
681        }
682        let base_branch = match config.merge.base.clone() {
683            Some(b) => b,
684            None => git::current_branch(&repo)
685                .await?
686                .context("HEAD is detached; set [merge] base in magi.toml")?,
687        };
688        if base_branch == branch {
689            bail!("`{branch}` is the base branch; there is nothing to review against");
690        }
691        let base_commit = resolve_base(&repo, &base_branch, &config.merge.remote).await?;
692
693        let roles = config.resolve_roles()?;
694        let max_parallel = config.graph.max_parallel.max(1);
695        let mut state = RunState::new(
696            repo.clone(),
697            base_branch,
698            base_commit.clone(),
699            String::new(),
700            config,
701        );
702        state.origin = Some(origin);
703
704        // Released before anything else touches the branch: a stale local
705        // branch is moved with `git branch -f`, which git refuses while an
706        // earlier attempt's worktree still has it checked out. Everything
707        // after this point that can fail puts the old run back.
708        // A hand-run review has no task, hence no earlier attempts, but a
709        // worktree of a dead run magi made may still be released.
710        let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
711            earlier: Vec::new(),
712            home: crate::run::home(),
713            choice: None,
714        });
715        let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
716        if let Some(released) = &released {
717            state.event(
718                "release",
719                format!(
720                    "took `{branch}` over from run {}: its worktree was released: {}",
721                    crate::run::short_of(&released.old_id),
722                    released.audit
723                ),
724            );
725        }
726        // The owner's answer to an earlier divergence question is applied
727        // here: after the release (git will not move a checked-out branch)
728        // and before the sync that would otherwise ask again.
729        if let Some(choice) = takeover.choice.as_ref()
730            && let Err(e) =
731                crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
732                    .await
733        {
734            if let Some(released) = &released {
735                released.restore(&repo, branch).await;
736            }
737            return Err(e.context("applying the owner's answer about the diverged branch"));
738        }
739        let opened =
740            Self::open_review(&repo, branch, state, roles, max_parallel, base_commit).await;
741        if opened.is_err()
742            && let Some(released) = &released
743        {
744            released.restore(&repo, branch).await;
745        }
746        opened
747    }
748
749    /// The half of [`Runner::review_taking_over`] that can fail after an
750    /// earlier attempt's worktree was released.
751    async fn open_review(
752        repo: &Path,
753        branch: &str,
754        mut state: RunState,
755        roles: ResolvedRoles,
756        max_parallel: usize,
757        base_commit: String,
758    ) -> Result<Self> {
759        sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
760        // The commit subjects are the closest thing to a task statement that
761        // existing work carries, and the reviewers are told as much.
762        let start = review_base(
763            repo,
764            &state.config.merge.remote,
765            &state.base_branch,
766            &base_commit,
767            branch,
768        )
769        .await;
770        let log = git::log_oneline(repo, &start, branch)
771            .await
772            .unwrap_or_default();
773        let instruction = format!(
774            "Review the work already on branch `{branch}`. There is no task \
775             statement: what the change claims to do is whatever its commits \
776             say.\n\n{}",
777            if log.trim().is_empty() {
778                "(no commit messages)"
779            } else {
780                log.trim()
781            }
782        );
783        state.instruction = instruction;
784        state.reviewed_commits = Some(
785            git::subjects(repo, &start, branch)
786                .await
787                .unwrap_or_default(),
788        );
789
790        // An attached worktree, so the fixer's commits land on the branch under
791        // review rather than on a detached head nobody will look at again.
792        let worktree = state.worktree_root().join("under-review");
793        if let Some(parent) = worktree.parent() {
794            tokio::fs::create_dir_all(parent).await.ok();
795        }
796        let path = worktree.to_string_lossy().to_string();
797        git::git(repo, &["worktree", "add", &path, branch])
798            .await
799            .with_context(|| {
800                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
801            })?;
802
803        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
804            .await
805            .unwrap_or(0);
806        if commits == 0 {
807            git::worktree_remove(repo, &worktree).await.ok();
808            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
809        }
810        let files = git::changed_files(&worktree, &base_commit, "HEAD")
811            .await
812            .map(|f| f.len())
813            .unwrap_or(0);
814        if files == 0
815            && let (Ok(head_tree), Ok(base_tree)) = (
816                git::tree_of(&worktree, "HEAD").await,
817                git::tree_of(&worktree, &base_commit).await,
818            )
819            && head_tree == base_tree
820        {
821            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
822            git::worktree_remove(repo, &worktree).await.ok();
823            bail!(
824                "`{branch}` at {} has a tree identical to base {}; this usually means \
825                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
826                 against `{}/{branch}`) rather than an empty change",
827                short(&head),
828                short(&base_commit),
829                state.config.merge.remote
830            );
831        }
832        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
833            .await
834            .unwrap_or_default();
835
836        state.candidates.push(Candidate {
837            index: 0,
838            label: 'A',
839            // Not an agent id on purpose: nothing in the roster wrote this, and
840            // the stats tables must not credit anyone with a win for it.
841            agent: EXISTING_BRANCH.to_owned(),
842            branch: branch.to_owned(),
843            worktree,
844            summary: String::new(),
845            stat,
846            files,
847            commits,
848            empty: false,
849            failed: None,
850            verified_noop: None,
851            duration_ms: 0,
852            folded: false,
853        });
854        state.tally = Some(Tally {
855            first_choice: BTreeMap::from([('A', 0)]),
856            borda: BTreeMap::new(),
857            winner: 'A',
858            rankings: 0,
859            unanimous_initial: false,
860            deliberated: false,
861            changed_votes: 0,
862            unanimous_final: false,
863            tie_break: None,
864            // No panel sat, so no quorum applies. Zero judges is the correct
865            // number for work that never competed, and must not be reported as
866            // a collapsed panel.
867            judges: 0,
868            present: 0,
869            quorum: 0,
870            met_quorum: true,
871            uncontested: Some("review-only run: nothing competed".to_owned()),
872        });
873        state.status = RunStatus::Reviewing;
874        state.event(
875            "start",
876            format!(
877                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
878                state.id
879            ),
880        );
881        state.save()?;
882        Ok(Self {
883            state,
884            roles,
885            sem: Arc::new(Semaphore::new(max_parallel)),
886            pause: Pause::new(),
887            interrupt: Pause::new(),
888        })
889    }
890
891    /// Reopen an existing run.
892    pub fn resume(id: &str) -> Result<Self> {
893        let state = RunState::load(id)?;
894        if let Some(to) = &state.released_to {
895            bail!(
896                "run {} cannot be resumed: its worktree was released to run {}",
897                state.short(),
898                crate::run::short_of(to)
899            );
900        }
901        let roles = state.config.resolve_roles()?;
902        let max_parallel = state.config.graph.max_parallel.max(1);
903        Ok(Self {
904            state,
905            roles,
906            sem: Arc::new(Semaphore::new(max_parallel)),
907            pause: Pause::new(),
908            interrupt: Pause::new(),
909        })
910    }
911
912    /// Walk the graph to a terminal state, skipping nodes already recorded.
913    ///
914    /// Every way a run is driven - the queue loop, `magi run`, a resume from
915    /// the phone - ends here, so this is the one place a run that ended
916    /// Blocked / Stalled / Failed, or died with an error, is announced to the
917    /// notification centre. Best-effort: see [`crate::notices::raise`].
918    pub async fn execute(&mut self) -> Result<()> {
919        let result = self.execute_graph().await;
920        self.mark_driver_exited();
921        let ended = if result.is_err() {
922            Some(crate::notices::run_stopped(&self.state.id, &self.state))
923        } else {
924            crate::notices::run_ended(&self.state)
925        };
926        if let Some(notice) = ended {
927            crate::notices::raise(notice);
928        }
929        result
930    }
931
932    /// Record that this process no longer drives the run, so its pid (a
933    /// daemon's outlives the run) is not read as a live driver.
934    ///
935    /// Written onto the record as it is on disk, never this copy: another
936    /// process may have resumed the run (recording its own pid and clearing
937    /// the flag) or released its worktree since this copy was read, and
938    /// saving over that would mark a running driver dead. Only a record still
939    /// naming this process as the driver is touched.
940    fn mark_driver_exited(&mut self) {
941        self.state.driver_exited = true;
942        let pid = std::process::id();
943        let Ok(mut disk) = RunState::load(&self.state.id) else {
944            return;
945        };
946        if disk.released_to.is_some() || disk.driver_pid != Some(pid) || disk.driver_exited {
947            return;
948        }
949        disk.driver_exited = true;
950        if let Err(e) = disk.save() {
951            tracing::warn!("could not record that run {} stopped: {e:#}", self.state.id);
952        }
953    }
954
955    async fn execute_graph(&mut self) -> Result<()> {
956        // Moving again, so it is no longer parked. Set before the walk rather
957        // than in `resume`, so every way of re-entering the graph clears it
958        // and a card cannot claim a run is waiting to be resumed while the
959        // agents are already working.
960        self.state.parked = false;
961        // Any seat this state still lists as answering belongs to whatever
962        // process last drove this run — this one included, if it crashed
963        // mid-wave. Cleared and flushed immediately, before anything else
964        // runs, so a resume can never show a seat as live when nothing is
965        // asking it anything yet; the node that actually dispatches the next
966        // wave repopulates it.
967        self.state.clear_active();
968        // Recorded in the same spot, and flushed together with the clear
969        // above: this is the pid a reader checks (`RunState::liveness`) when
970        // no daemon claim exists to answer "is a process still driving this
971        // run" — a plain `magi run` / `magi review` typed into a terminal
972        // claims nothing there. Always overwritten, never only-if-absent, so
973        // a resumed run's stale pid from a previous, possibly-dead process
974        // can never survive into this one's own report. Unlike
975        // `clear_active`, this changes on every single `execute()` call, so
976        // the save below is now unconditional rather than only-if-cleared.
977        //
978        // `driver_started_at` is recorded in the same breath, from this same
979        // pid, so `liveness` can tell a live pid that is genuinely still us
980        // apart from one the OS has since handed to an unrelated process —
981        // see that field's own doc for why the pid alone is not enough.
982        // A resume that raced a takeover: the record on disk says the worktree
983        // was handed to a later run after this copy was read. Saving over it
984        // would erase that and drive a run with nothing to run in.
985        if let Ok(disk) = RunState::load(&self.state.id)
986            && let Some(to) = &disk.released_to
987        {
988            bail!(
989                "run {} cannot continue: its worktree was released to run {}",
990                self.state.short(),
991                crate::run::short_of(to)
992            );
993        }
994        let pid = std::process::id();
995        self.state.driver_pid = Some(pid);
996        self.state.driver_started_at = crate::proc::process_started_at(pid);
997        self.state.driver_exited = false;
998        self.state.save()?;
999        // A run that already lost its quorum never resumes into the verdict
1000        // machinery: `deliberate` and `vote` would otherwise clobber the
1001        // stalled marker back to Voting and the run would keep going past a
1002        // verdict that is no longer trustworthy. Everything already recorded is
1003        // kept, so the run stays resumable (or foldable) for a human to pick up.
1004        //
1005        // On --resume the run gets one chance to repair itself: the seats a
1006        // rate limit took out are re-asked. If their quota has since reset and
1007        // the quorum is restored, the run picks up and finishes; otherwise it
1008        // stays stale and still-resumable for a later retry. If it does not
1009        // recover, the returned status stays `Stalled` and nothing was
1010        // clobbered (the recovery only mutates entries for the lost seats).
1011        if self.state.status == RunStatus::Stalled {
1012            if self.recover_stall().await? {
1013                self.finish_after_tally().await?;
1014            } else {
1015                // Still below quorum: persist the marker and stay resumable.
1016                self.state.save()?;
1017            }
1018            return Ok(());
1019        }
1020        // A run parked inside `land` - watching CI, mid fix-round, or
1021        // waiting on the owner's merge approval - resumes directly into it,
1022        // never back through `prep`. Everything before `merge` already
1023        // concluded; that is the only way `status` reaches `Landing` in the
1024        // first place. Re-walking `review_loop` first would also be actively
1025        // wrong: its own status recomputation (see its doc) treats any
1026        // clean round as reason to set `status` to `Gating`, which would
1027        // clobber this marker before `merge` ever ran, and this run would
1028        // never find its way back into `land` at all.
1029        if self.state.status == RunStatus::Landing {
1030            self.run_land().await?;
1031            // `run_land` may have settled the run right here - CI came back
1032            // green and the PR merged, say - without ever passing back
1033            // through `merge`'s own trailing call. Whatever it left `status`
1034            // as is what this has to read.
1035            self.settle_questions();
1036            return Ok(());
1037        }
1038        self.prep().await?;
1039        if self.park_here()? {
1040            return Ok(());
1041        }
1042        self.advise().await?;
1043        if self.park_here()? {
1044            return Ok(());
1045        }
1046        self.implement().await?;
1047        if self.park_here()? {
1048            return Ok(());
1049        }
1050        // `after_implement` already saved the state and settled any open
1051        // questions when it set this; nothing later in the graph has
1052        // anything to judge.
1053        if self.state.status == RunStatus::VerifiedNoop {
1054            return Ok(());
1055        }
1056        self.judge().await?;
1057        if self.park_here()? {
1058            return Ok(());
1059        }
1060        self.deliberate().await?;
1061        if self.park_here()? {
1062            return Ok(());
1063        }
1064        self.vote().await?;
1065        if self.park_here()? {
1066            return Ok(());
1067        }
1068        self.tally()?;
1069        // A verdict that lost its quorum is not trustworthy: do not review,
1070        // gate, or merge on it. Everything already done is kept, so the run
1071        // stays resumable (or foldable); the human can replace the agent that
1072        // ran out of quota and pick it up.
1073        if self.state.status == RunStatus::Stalled {
1074            // Persist the stalled marker now — the normal end-of-execute save
1075            // below is below this early return, and without it a resumed run
1076            // would reload a pre-tally status and keep going.
1077            self.state.save()?;
1078            return Ok(());
1079        }
1080        self.finish_after_tally().await?;
1081        Ok(())
1082    }
1083
1084    /// Park here if asked to, recording it in the run's own timeline.
1085    ///
1086    /// Returns whether the caller should stop walking the graph. The state is
1087    /// saved either way by the node that just finished; this adds the event so
1088    /// the operator's card says why a run that is neither finished nor moving
1089    /// is sitting where it is.
1090    fn park_here(&mut self) -> Result<bool> {
1091        // Either handle asking is enough - see `Pause`'s own doc for why
1092        // they are never the same one. `interrupt` is checked second so a
1093        // reason it carries is preferred in the message below over a plain
1094        // shutdown park racing it at the same boundary.
1095        if !self.pause.parked() && !self.interrupt.parked() {
1096            return Ok(false);
1097        }
1098        let why = match self.interrupt.reason().or_else(|| self.pause.reason()) {
1099            Some(reason) => format!(
1100                "parked after `{}` ({reason}) — resume to carry on from here",
1101                self.state.status.as_str()
1102            ),
1103            None => format!(
1104                "parked after `{}` — resume to carry on from here",
1105                self.state.status.as_str()
1106            ),
1107        };
1108        self.state.event("park", why);
1109        self.state.parked = true;
1110        self.state.save()?;
1111        Ok(true)
1112    }
1113
1114    /// Hand the runner the pause `magi serve`'s own shutdown watches.
1115    pub fn on_pause(&mut self, pause: Pause) {
1116        self.pause = pause;
1117    }
1118
1119    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
1120    /// scheduler asking this one run - and no other - to park so a task
1121    /// marked [`crate::queue::Task::interrupt`] can run alone. See
1122    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
1123    /// handle.
1124    pub fn watch_interrupt(&mut self, pause: Pause) {
1125        self.interrupt = pause;
1126    }
1127
1128    /// Abandon this run's own open questions, once `status` has actually
1129    /// settled rather than merely paused.
1130    ///
1131    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
1132    /// either back up with the candidates, the review round and the seat
1133    /// sessions already on disk, so a question an implementer asked mid-round
1134    /// may still get a real answer read by a real resume. Only the statuses
1135    /// `resumable` excludes are actually final: the run merged, it reached
1136    /// `Ready` with nothing left to do, it failed outright with no
1137    /// established point to continue from, or every candidate agreed, with
1138    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
1139    /// every one of those the seat that asked is gone for good, exactly like
1140    /// the run being deleted under `magi run rm` - so the same cleanup
1141    /// applies, worded for what actually happened instead of "the run was
1142    /// deleted".
1143    ///
1144    /// Best-effort and silent on success: called from every place `status`
1145    /// can land on one of those three, including ones a resumed run revisits,
1146    /// so it must cost nothing when there was nothing open to begin with.
1147    fn settle_questions(&mut self) {
1148        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
1149            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
1150        }
1151    }
1152
1153    /// The tail of the graph after a trustworthy tally: fold losers, review,
1154    /// gate, merge, and persist.
1155    async fn finish_after_tally(&mut self) -> Result<()> {
1156        self.fold_losers().await?;
1157        // Before review starts, and again right before the gate: a run's
1158        // review rounds can themselves take long enough for the base to move
1159        // a second time, and the gate is the one node whose "green" gets
1160        // acted on.
1161        self.sync_to_base().await?;
1162        if self.state.status == RunStatus::AlreadyInBase {
1163            return Ok(());
1164        }
1165        self.review_loop().await?;
1166        self.sync_to_base().await?;
1167        if self.state.status == RunStatus::AlreadyInBase {
1168            return Ok(());
1169        }
1170        self.gate().await?;
1171        self.merge().await?;
1172        self.state.save()?;
1173        Ok(())
1174    }
1175
1176    // ---------------------------------------------------------------- prep
1177
1178    async fn prep(&mut self) -> Result<()> {
1179        if !self.state.candidates.is_empty() {
1180            return Ok(());
1181        }
1182        self.state.status = RunStatus::Prep;
1183        let repo = self.state.repo.clone();
1184        let base = self.state.base_commit.clone();
1185        let plan = refs::plan(&repo, &self.state.seeds).await?;
1186        let start = plan.start.clone().unwrap_or_else(|| base.clone());
1187        let root = self.state.worktree_root();
1188        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
1189
1190        // The hook is the write-time half of the blindness contract; the
1191        // presentation filter in `blind` is the half that cannot be bypassed.
1192        let hooks_dir = self.state.dir().join("hooks");
1193        if self.state.config.blind.commit_msg_hook {
1194            std::fs::create_dir_all(&hooks_dir)
1195                .with_context(|| format!("create {}", hooks_dir.display()))?;
1196            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
1197            let path = hooks_dir.join("commit-msg");
1198            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
1199            make_executable(&path)?;
1200            // Ref-counted rather than a plain idempotent set: with more than
1201            // one run able to be in flight in the same repository at once
1202            // (see `Config::daemon.max_concurrent_runs`), a bare "already
1203            // true?" check cannot tell "another run of mine still needs
1204            // this" from "nobody does", and the run that happens to finish
1205            // first would disable the hook out from under a sibling still
1206            // relying on it.
1207            git::acquire_worktree_config(&repo).await?;
1208            self.state.enabled_worktree_config = true;
1209        }
1210
1211        for (index, (spec, label)) in self
1212            .roles
1213            .implementers
1214            .clone()
1215            .into_iter()
1216            .zip(labels)
1217            .enumerate()
1218        {
1219            let branch = self.state.branch_for(label);
1220            let worktree = root.join(format!("cand-{label}"));
1221            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
1222            if self.state.config.blind.commit_msg_hook {
1223                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
1224            }
1225            git::local_exclude(&worktree, "/.magi/").await?;
1226            for pick in &plan.picks {
1227                if let Err(e) = git::cherry_pick(&worktree, pick).await {
1228                    self.state.status = RunStatus::Blocked;
1229                    self.state
1230                        .event("prep", format!("cannot apply referenced commit: {e}"));
1231                    self.state.save()?;
1232                    return Err(e);
1233                }
1234            }
1235            self.state.candidates.push(Candidate {
1236                index,
1237                label,
1238                agent: spec.id.clone(),
1239                branch,
1240                worktree,
1241                summary: String::new(),
1242                stat: String::new(),
1243                files: 0,
1244                commits: 0,
1245                empty: false,
1246                failed: None,
1247                verified_noop: None,
1248                duration_ms: 0,
1249                folded: false,
1250            });
1251        }
1252
1253        for j in 1..=self.roles.judges.len() {
1254            let wt = root.join(format!("judge-{j}"));
1255            if !wt.exists() {
1256                git::worktree_add_detached(&repo, &wt, &base).await?;
1257            }
1258        }
1259
1260        // Disposable, detached checkouts for the design-deliberation stage's
1261        // advisor seats — the same shape as the judges' above, at the same
1262        // base commit, since advisors also only ever read. Sized off the
1263        // configured count directly rather than a resolved roster: unlike
1264        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
1265        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
1266        // `prep` has no `ResolvedRoles` field to read a count from here.
1267        if self.state.config.graph.advise {
1268            for k in 1..=self.state.config.graph.advisors {
1269                let wt = root.join(format!("advisor-{k}"));
1270                if !wt.exists() {
1271                    git::worktree_add_detached(&repo, &wt, &base).await?;
1272                }
1273            }
1274        }
1275
1276        // A judge cannot tell it is looking at its own patch — the seats keep
1277        // separate conversations — but a panel that shares agents with the
1278        // field is less independent than it looks, and that is worth saying out
1279        // loud once per run rather than leaving it in the config.
1280        let authors: Vec<&str> = self
1281            .roles
1282            .implementers
1283            .iter()
1284            .map(|a| a.id.as_str())
1285            .collect();
1286        let overlap: Vec<String> = self
1287            .roles
1288            .judges
1289            .iter()
1290            .enumerate()
1291            .filter(|(_, j)| authors.contains(&j.id.as_str()))
1292            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
1293            .collect();
1294        if !overlap.is_empty() {
1295            let note = format!(
1296                "{} also authored a candidate; blind, but the panel is less \
1297                 independent than {} distinct agents would be",
1298                overlap.join(", "),
1299                self.roles.judges.len()
1300            );
1301            self.state.event("prep", note);
1302        }
1303
1304        self.state.event(
1305            "prep",
1306            format!(
1307                "{} candidates, {} judges, base {} ({})",
1308                self.state.candidates.len(),
1309                self.roles.judges.len(),
1310                &self.state.base_commit[..7.min(self.state.base_commit.len())],
1311                self.state.base_branch
1312            ),
1313        );
1314        self.state.status = RunStatus::Implementing;
1315        self.state.save()?;
1316        Ok(())
1317    }
1318
1319    // -------------------------------------------------------------- advise
1320
1321    /// The design-deliberation stage: independent, read-only advisor seats
1322    /// each sketch a design before any implementer touches the repository,
1323    /// and (when at least one produced a usable proposal) a synthesis seat
1324    /// blends them into a brief `implement` carries in every candidate's
1325    /// prompt.
1326    ///
1327    /// `[graph] advise` is the on/off switch, on by default; `[graph]
1328    /// advisors` is the proposal count. Everything here is best-effort and
1329    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
1330    /// that cannot reach quota, or a synthesis seat that produced nothing
1331    /// usable all leave `implement` exactly as it was before this stage
1332    /// existed — the task instruction alone — rather than failing the whole
1333    /// competition over an enrichment stage. Every outcome is still recorded
1334    /// as an event, so a run that got nothing from this stage says why.
1335    ///
1336    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
1337    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
1338    /// resumed run whose stage failed would re-run it, and re-spend the
1339    /// agent calls, on every reentry before `implement`.
1340    ///
1341    /// Also skipped once any candidate shows implementation progress — the
1342    /// exact predicate `implement` itself uses to decide a candidate is no
1343    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
1344    /// is not enough: a run created by an older binary that predates this
1345    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
1346    /// an already-`Implementing`-or-later run under this build would
1347    /// otherwise walk straight back through `prep` (a no-op once candidates
1348    /// exist) into this node and spawn every advisor seat against worktrees
1349    /// `prep` never recreated — after implementation has already started,
1350    /// which is exactly the invariant this stage exists to guarantee.
1351    async fn advise(&mut self) -> Result<()> {
1352        let implement_untouched = self
1353            .state
1354            .candidates
1355            .iter()
1356            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
1357        if !self.state.config.graph.advise || self.state.advise_attempted {
1358            return Ok(());
1359        }
1360        if !implement_untouched {
1361            self.state.event(
1362                "advise",
1363                "skipping the design-deliberation stage: at least one \
1364                 candidate already shows implementation progress, so this \
1365                 run is past the point the stage exists to run before"
1366                    .to_owned(),
1367            );
1368            self.state.advise_attempted = true;
1369            self.state.save()?;
1370            return Ok(());
1371        }
1372        let run_id = self.state.id.clone();
1373        let prompts = self.state.config.prompts.clone();
1374        let instruction = self.state.instruction.clone();
1375        let language = self.state.config.graph.language.clone();
1376        let root = self.state.worktree_root();
1377        let n = self.state.config.graph.advisors;
1378        let where_recorded = self.state.dir().join("run.json");
1379
1380        let seats = match self.state.config.advisors() {
1381            Ok(seats) if !seats.is_empty() => seats,
1382            Ok(_) => {
1383                self.state.event(
1384                    "advise",
1385                    format!(
1386                        "[graph] advisors is 0; skipping the design-deliberation \
1387                         stage and continuing without a synthesis brief (see {})",
1388                        where_recorded.display()
1389                    ),
1390                );
1391                self.state.advise_attempted = true;
1392                self.state.save()?;
1393                return Ok(());
1394            }
1395            Err(e) => {
1396                self.state.event(
1397                    "advise",
1398                    format!(
1399                        "could not resolve advisor seats ({e:#}); continuing \
1400                         without a design-deliberation brief (see {})",
1401                        where_recorded.display()
1402                    ),
1403                );
1404                self.state.advise_attempted = true;
1405                self.state.save()?;
1406                return Ok(());
1407            }
1408        };
1409
1410        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
1411        let artifacts = agent::artifacts_dir(&self.state.dir());
1412        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
1413
1414        let mut jobs = Vec::new();
1415        for (i, spec) in seats.iter().cloned().enumerate() {
1416            let seat_key = format!("advisor-{}", i + 1);
1417            let seat = self.seat(&seat_key, &spec.id);
1418            jobs.push(SeatJob {
1419                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
1420                spec,
1421                seat,
1422                cwd: worktrees[i % worktrees.len()].clone(),
1423                timeout,
1424                allow_write: false,
1425                sessions: false,
1426                artifacts: artifacts.clone(),
1427                stem: seat_key,
1428                handover: None,
1429            });
1430        }
1431
1432        self.state.event(
1433            "advise",
1434            format!(
1435                "{} advisor seat(s) sketching a design in parallel",
1436                jobs.len()
1437            ),
1438        );
1439        let mut quota_losses = Vec::new();
1440        let cache = self.state.config.cache_dir();
1441        let ctx = WaveCtx {
1442            carry_seats: false,
1443            run: &run_id,
1444            node: "advise",
1445            prompts: &prompts,
1446            cache: cache.as_deref(),
1447            round: None,
1448        };
1449        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
1450        let results = ask_json_wave::<Proposal>(
1451            jobs,
1452            Arc::clone(&self.sem),
1453            self.state.config.graph.retries,
1454            &advisor_roster,
1455            &ctx,
1456            &mut quota_losses,
1457            &mut self.state,
1458            &|p: &Proposal| p.validate(),
1459        )
1460        .await;
1461        self.state.quota.extend(quota_losses);
1462
1463        let mut records = Vec::with_capacity(results.len());
1464        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
1465            let agent_id = seat.agent.clone();
1466            self.state.seats.insert(seat.key.clone(), seat);
1467            match res {
1468                Ok((proposal, out)) => {
1469                    self.state
1470                        .event("advise", format!("advisor-{} proposed a design", i + 1));
1471                    records.push(advise::AdvisorRecord::proposed(
1472                        i + 1,
1473                        agent_id,
1474                        proposal,
1475                        out.duration_ms,
1476                    ));
1477                }
1478                Err(e) => {
1479                    self.state.event(
1480                        "advise",
1481                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
1482                    );
1483                    records.push(advise::AdvisorRecord::failed(
1484                        i + 1,
1485                        agent_id,
1486                        e.to_string(),
1487                    ));
1488                }
1489            }
1490        }
1491
1492        let mut advice = advise::Advice {
1493            records,
1494            synthesis: None,
1495        };
1496        if advice.proposals().is_empty() {
1497            self.state.event(
1498                "advise",
1499                "no advisor produced a usable proposal; continuing without a \
1500                 synthesis brief"
1501                    .to_owned(),
1502            );
1503        } else {
1504            match self
1505                .synthesize_brief(
1506                    &advice,
1507                    &instruction,
1508                    &language,
1509                    &worktrees[0],
1510                    &artifacts,
1511                    &run_id,
1512                    &prompts,
1513                    cache.as_deref(),
1514                )
1515                .await
1516            {
1517                Ok(Some(text)) => {
1518                    self.state.event(
1519                        "advise",
1520                        "synthesized a design brief for the implementer".to_owned(),
1521                    );
1522                    advice.synthesis = Some(text);
1523                }
1524                Ok(None) => {
1525                    self.state.event(
1526                        "advise",
1527                        "the synthesis seat produced nothing usable; continuing \
1528                         without a design brief"
1529                            .to_owned(),
1530                    );
1531                }
1532                Err(e) => {
1533                    self.state.event(
1534                        "advise",
1535                        format!("could not synthesize a design brief: {e:#}"),
1536                    );
1537                }
1538            }
1539        }
1540        advise::apply_reflection(&mut advice);
1541
1542        self.state.advice = Some(advice);
1543        self.state.advise_attempted = true;
1544        self.state.save()?;
1545        Ok(())
1546    }
1547
1548    /// The synthesis seat: reads every advisor's proposal and blends them
1549    /// into the design brief `advise` stores on [`RunState::advice`]. Split
1550    /// out of [`Runner::advise`] only for readability — it is not called
1551    /// anywhere else.
1552    ///
1553    /// Picked the same way [`crate::talk`]'s standing conversation and
1554    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
1555    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
1556    /// order (a claude seat, else the first runnable agent in roster order)
1557    /// used when that field is unset — see `[roles] synthesizer`'s own doc
1558    /// in [`crate::config`] for why a dedicated field exists here at all.
1559    #[allow(clippy::too_many_arguments)]
1560    async fn synthesize_brief(
1561        &mut self,
1562        advice: &advise::Advice,
1563        instruction: &str,
1564        language: &str,
1565        cwd: &Path,
1566        artifacts: &Path,
1567        run_id: &str,
1568        prompts: &Prompts,
1569        cache: Option<&Path>,
1570    ) -> Result<Option<String>> {
1571        let chain = agent::pick_chain(
1572            &self.state.config.agents,
1573            self.state.config.roles.synthesizer.as_ref(),
1574            &agent::installed,
1575            "synthesizer",
1576        )?;
1577        let proposals = advice.proposals();
1578        let mut prompt = prompt::with_overlay(
1579            prompt::synthesize_brief(instruction, &proposals, language),
1580            prompts.overlay("advise"),
1581        );
1582        if cache.is_some() {
1583            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
1584            // below — see `prompt::build_cache_note`'s doc for why telling a
1585            // read-only seat to build through the shared cache is exactly how
1586            // a sandbox's write refusal gets misread as a defect.
1587            prompt.push('\n');
1588            prompt.push_str(&prompt::build_cache_note("advise", false));
1589        }
1590        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
1591        // Each id is tried once, in order; a quota hit, error or unusable
1592        // answer moves to the next. The seat is single-turn (`sessions:
1593        // false`) and the prompt is the whole context, so a fallback agent
1594        // needs nothing carried over.
1595        let mut last = None;
1596        for (n, spec) in chain.iter().enumerate() {
1597            if n > 0 {
1598                self.state
1599                    .event("advise", format!("synthesis falling back to {}", spec.id));
1600            }
1601            let mut seat = self.seat("advise-synthesis", &spec.id);
1602            let outcome = agent::invoke(
1603                spec,
1604                &mut seat,
1605                &Invocation {
1606                    cwd,
1607                    prompt: &prompt,
1608                    timeout,
1609                    allow_write: false,
1610                    sessions: false,
1611                    artifacts,
1612                    stem: &if n == 0 {
1613                        "advise-synthesis".to_owned()
1614                    } else {
1615                        format!("advise-synthesis-{}", spec.id)
1616                    },
1617                    run: run_id,
1618                    node: "advise",
1619                    cache_dir: None,
1620                    attachments: &[],
1621                    writable: &[],
1622                },
1623            )
1624            .await;
1625            if outcome.is_ok() {
1626                self.state.seats.insert(seat.key.clone(), seat);
1627            }
1628            let advance = agent::chain_advances(&outcome);
1629            last = Some(outcome);
1630            if !advance {
1631                break;
1632            }
1633        }
1634        // Exhausted: the last attempt's result is what a single failed seat
1635        // would have produced.
1636        let out = last.expect("a chain holds at least one agent")?;
1637        if !out.usable() {
1638            return Ok(None);
1639        }
1640        let text =
1641            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
1642        Ok((!text.trim().is_empty()).then_some(text))
1643    }
1644
1645    // ----------------------------------------------------------- implement
1646
1647    async fn implement(&mut self) -> Result<()> {
1648        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
1649        // agent files with `magi task add` name the run that paid for it. The
1650        // prompt overlay is cloned alongside it because the waves borrow it
1651        // while `self` is mutably borrowed by the node's own bookkeeping.
1652        let run_id = self.state.id.clone();
1653        let prompts = self.state.config.prompts.clone();
1654        let todo: Vec<usize> = self
1655            .state
1656            .candidates
1657            .iter()
1658            .enumerate()
1659            .filter(|(_, c)| c.commits == 0 && c.failed.is_none() && !c.empty)
1660            .map(|(i, _)| i)
1661            .collect();
1662        if todo.is_empty() {
1663            return self.after_implement();
1664        }
1665        self.state.status = RunStatus::Implementing;
1666
1667        let language = self.state.config.graph.language.clone();
1668        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
1669        let sessions = self.state.config.graph.sessions;
1670        let artifacts = agent::artifacts_dir(&self.state.dir());
1671        // The design-deliberation stage's blended brief, when `advise` found
1672        // one — carried into every implementer's prompt the same way
1673        // regardless of which candidate it is.
1674        let brief = self
1675            .state
1676            .advice
1677            .as_ref()
1678            .and_then(|a| a.synthesis.as_deref())
1679            .map(str::to_owned);
1680        let attachments = self.state.attachments.clone();
1681
1682        let mut jobs = Vec::new();
1683        for &i in &todo {
1684            let (index, label, worktree) = {
1685                let c = &self.state.candidates[i];
1686                (c.index, c.label, c.worktree.clone())
1687            };
1688            let spec = self.roles.implementers[index].clone();
1689            let seat_key = format!("impl-{label}");
1690            let seat = self.seat(&seat_key, &spec.id);
1691            let instruction = seeded_instruction(&self.state);
1692            jobs.push(SeatJob {
1693                spec,
1694                seat,
1695                prompt: prompt::implement(
1696                    &instruction,
1697                    &worktree.to_string_lossy(),
1698                    &language,
1699                    brief.as_deref(),
1700                    &attachments,
1701                ),
1702                cwd: worktree,
1703                timeout,
1704                allow_write: true,
1705                sessions,
1706                artifacts: artifacts.clone(),
1707                stem: format!("impl-{label}"),
1708                handover: None,
1709            });
1710        }
1711
1712        self.state.event(
1713            "implement",
1714            format!("{} candidates in parallel", jobs.len()),
1715        );
1716        // Kept so a seat whose CLI hung up can be asked again from the same
1717        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
1718        // can update a seat's own entry once a fallback agent takes it over —
1719        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
1720        // whichever agent actually answered, not the one that quota'd out.
1721        let mut sent = jobs.clone();
1722        let cache = self.state.config.cache_dir();
1723        let ctx = WaveCtx {
1724            carry_seats: false,
1725            run: &run_id,
1726            node: "implement",
1727            prompts: &prompts,
1728            cache: cache.as_deref(),
1729            round: None,
1730        };
1731        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
1732        self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
1733            .await;
1734        self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
1735            .await;
1736        self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
1737            .await;
1738
1739        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
1740            let seat_key = seat.key.clone();
1741            // A quota fallback (`resume_seat_handovers`) may have handed this
1742            // seat to a different agent than the one `prep` recorded on the
1743            // candidate; the stats tables and any later fixer-defaults-to-
1744            // winner's-author lookup must credit whoever actually answered —
1745            // unless every fallback also quota'd out, in which case nobody
1746            // actually answered and crediting the last agent tried would
1747            // erase every earlier agent's own quota loss from the stats
1748            // tables instead of just this one seat's.
1749            let agent = seat.agent.clone();
1750            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
1751            self.state.seats.insert(seat.key.clone(), seat);
1752            let label = self.state.candidates[i].label;
1753            let worktree = self.state.candidates[i].worktree.clone();
1754            let base = self.state.base_commit.clone();
1755
1756            let (summary, duration, failed, verified_claim) = match out {
1757                AgentOutcome::Ok(o) => {
1758                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
1759                    let failed = (!o.usable()).then(|| {
1760                        if o.timed_out {
1761                            "agent timed out".to_owned()
1762                        } else {
1763                            format!("agent exited with {:?}", o.exit_code)
1764                        }
1765                    });
1766                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
1767                    (text, o.duration_ms, failed, verified_claim)
1768                }
1769                // Left un-resumed by `resume_undelivered` (a dirty tree
1770                // already rescues the work, or there was no session left to
1771                // resume into) — reported like the ordinary failure it is,
1772                // never as if `o.text` (the CLI's raw error JSON) were an
1773                // answer.
1774                AgentOutcome::Dropped(o) => {
1775                    let why = o
1776                        .dropped
1777                        .as_ref()
1778                        .map(|d| d.why.as_str())
1779                        .unwrap_or("the CLI ended the stream without delivering its answer");
1780                    (
1781                        String::new(),
1782                        o.duration_ms,
1783                        Some(format!("the CLI dropped the stream ({why})")),
1784                        None,
1785                    )
1786                }
1787                AgentOutcome::Quota(o) => {
1788                    self.state.quota.push(QuotaLoss {
1789                        seat: seat_key,
1790                        node: "implement".to_owned(),
1791                        at: Timestamp::now(),
1792                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
1793                    });
1794                    (
1795                        String::new(),
1796                        o.duration_ms,
1797                        Some("rate limited (quota); produced no change".to_owned()),
1798                        None,
1799                    )
1800                }
1801                AgentOutcome::Failed(e) => (String::new(), 0, Some(e), None),
1802            };
1803
1804            // Rescue anything the agent edited but never committed: an
1805            // uncommitted candidate would silently be an empty one.
1806            let rescued = match git::rescue_commit(
1807                &worktree,
1808                &format!("magi: candidate {label} (uncommitted work)"),
1809            )
1810            .await
1811            {
1812                Ok(r) => {
1813                    self.state.note_withheld("implement", &r.withheld);
1814                    r.committed
1815                }
1816                Err(_) => false,
1817            };
1818            let commits = git::commits_ahead(&worktree, &base, "HEAD")
1819                .await
1820                .unwrap_or(0);
1821            let patch = git::diff(&worktree, &base, "HEAD")
1822                .await
1823                .unwrap_or_default();
1824            let stat = git::diff_stat(&worktree, &base, "HEAD")
1825                .await
1826                .unwrap_or_default();
1827            let files = git::changed_files(&worktree, &base, "HEAD")
1828                .await
1829                .map(|f| f.len())
1830                .unwrap_or(0);
1831            write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
1832
1833            let c = &mut self.state.candidates[i];
1834            if !exhausted_the_fallback_chain {
1835                c.agent = agent;
1836            }
1837            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
1838            c.stat = stat;
1839            c.files = files;
1840            c.commits = commits;
1841            c.duration_ms = duration;
1842            c.empty = commits == 0 || patch.trim().is_empty();
1843            // An agent that failed but still produced a committed change stays
1844            // in the running: the patch is what gets judged, not the exit code.
1845            c.failed = match failed {
1846                Some(_) if c.empty => failed,
1847                _ => None,
1848            };
1849            // Only an empty candidate can be a verified no-op: a claim next
1850            // to a real patch is not what the marker is for, and `c.failed`
1851            // being `Some` here already implies `verified_claim` was never
1852            // set (see the guard above the match that produced it).
1853            c.verified_noop = if c.empty { verified_claim } else { None };
1854            let note = match (&c.failed, c.empty, &c.verified_noop, rescued) {
1855                (Some(e), _, _, _) => format!("candidate {label}: {e}"),
1856                (None, true, Some(_), _) => {
1857                    format!("candidate {label}: no change produced (agent-verified no-op)")
1858                }
1859                (None, true, None, _) => format!("candidate {label}: no change produced"),
1860                (None, false, _, true) => {
1861                    format!(
1862                        "candidate {label}: {files} files, {commits} commits (rescued an uncommitted tree)"
1863                    )
1864                }
1865                (None, false, _, false) => {
1866                    format!("candidate {label}: {files} files, {commits} commits")
1867                }
1868            };
1869            self.state.event("implement", note);
1870            self.state.save()?;
1871        }
1872
1873        self.after_implement()
1874    }
1875
1876    /// Ask again, once, for work a CLI did and then failed to hand over.
1877    ///
1878    /// [`agent::dropped_stream`] recognises the one shape observed: an error
1879    /// status with an empty response and a usage report showing output tokens,
1880    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
1881    /// seven minutes and 14,267 output tokens that arrived as an empty
1882    /// candidate, because `agy`'s own subscriber fell behind and hung up.
1883    ///
1884    /// Two conditions, and both matter:
1885    ///
1886    /// - **Only when the tree is untouched.** Often the agent has already
1887    ///   written its files and only the closing message was lost; the rescue
1888    ///   commit below picks that up and there is nothing to ask for. Re-asking
1889    ///   then would pay for a second implementation of work already on disk.
1890    /// - **Once.** A CLI that drops one stream can drop the next, and this
1891    ///   node is the most expensive in the graph.
1892    ///
1893    /// The re-ask is a resume, not a re-run: `has_context` is true because the
1894    /// dropped reply still carried its `conversation_id`, so the seat is asked
1895    /// to finish what it was doing rather than sent the whole task again. It
1896    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
1897    /// node's - for the same reason a re-ranked judge does: restating finished
1898    /// work is not the work.
1899    ///
1900    /// Unlike a quota this is worth retrying at all: a rate limit fails the
1901    /// same way until it resets, while an abandoned conversation is still
1902    /// there to be picked up.
1903    async fn resume_undelivered(
1904        &mut self,
1905        results: &mut [(usize, SeatState, AgentOutcome)],
1906        sent: &[SeatJob],
1907        prompts: &Prompts,
1908        run_id: &str,
1909    ) {
1910        for (wi, seat, out) in results.iter_mut() {
1911            let Some(dropped) = (match &*out {
1912                AgentOutcome::Dropped(o) => o.dropped.clone(),
1913                _ => None,
1914            }) else {
1915                continue;
1916            };
1917            let Some(job) = sent.get(*wi) else { continue };
1918            // Already on disk? Then only the closing message was lost.
1919            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
1920                self.state.event(
1921                    "implement",
1922                    format!(
1923                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
1924                         work is in the tree",
1925                        seat.key, dropped.output_tokens, dropped.why
1926                    ),
1927                );
1928                continue;
1929            }
1930            // The re-ask only makes sense as a resume: `resume_after_drop`
1931            // says nothing about the task, trusting the seat to still hold it.
1932            // Without a session to resume — sessions disabled, or this CLI's
1933            // drop shape happened not to carry a session id — that prompt
1934            // would open a brand-new conversation with no context at all,
1935            // which is worse than leaving this as the ordinary failure it
1936            // already is.
1937            if !has_context(&job.spec, seat, job.sessions) {
1938                self.state.event(
1939                    "implement",
1940                    format!(
1941                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
1942                         is no session left to resume",
1943                        seat.key, dropped.output_tokens, dropped.why
1944                    ),
1945                );
1946                continue;
1947            }
1948            self.state.event(
1949                "implement",
1950                format!(
1951                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
1952                     conversation",
1953                    seat.key, dropped.output_tokens, dropped.why
1954                ),
1955            );
1956            let mut retry = job.clone();
1957            retry.seat = seat.clone();
1958            retry.prompt = prompt::resume_after_drop(&dropped.why);
1959            retry.timeout = retry_budget(job.timeout, true);
1960            retry.stem = format!("{}-resume", job.stem);
1961            let cache = self.state.config.cache_dir();
1962            let ctx = WaveCtx {
1963                carry_seats: false,
1964                run: run_id,
1965                node: "implement",
1966                prompts,
1967                cache: cache.as_deref(),
1968                round: None,
1969            };
1970            let (resumed_seat, resumed) =
1971                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
1972            *seat = resumed_seat;
1973            *out = resumed;
1974        }
1975    }
1976
1977    /// Fall an implement seat through to the next untried agent in the
1978    /// implementer roster when it lost to quota — or, since the handover was
1979    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
1980    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
1981    /// quota path itself being unchanged — instead of leaving the
1982    /// seat's loss final the moment one agent's account runs dry.
1983    ///
1984    /// Solo runs (`graph.candidates = 1`, `daemon::apply_solo`'s forced shape)
1985    /// are the motivating case: `Config::resolve_roles`'s `implementers`
1986    /// truncates to the single slot rotation picked, so a solo task whose one
1987    /// implementer hits quota mid-run used to have nothing else to try. This
1988    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
1989    /// unrotated roster — which is the only place the *other* candidates in
1990    /// the machine's roster still exist once `implementers` has been cut down
1991    /// to size.
1992    ///
1993    /// Walks forward from just past the seat's own original position in the
1994    /// roster, never wrapping back to the front: a later candidate slot (say
1995    /// `beta`, the roster's second entry) must fall through to the *next*
1996    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
1997    /// almost certainly a different candidate's own agent already — and once
1998    /// the roster's tail is exhausted there is nothing left to fall through
1999    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
2000    /// whole [`AgentSpec`]: a roster with the same id named twice must not
2001    /// let this retry that id forever. The loop keeps falling through until
2002    /// an attempt lands something other than `Quota` or the roster's tail
2003    /// runs out of untried ids, at which point the seat is left exactly as
2004    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
2005    /// `QuotaLoss` recorded, the candidate failed/empty.
2006    ///
2007    /// `sent` is taken mutably and updated with the fallback agent's spec:
2008    /// `resume_unconfirmed_commands`, which runs after this and also reads
2009    /// `sent`, must see whichever agent actually ended up answering the seat
2010    /// — reading the stale, original spec there would check session
2011    /// eligibility against the wrong CLI and could hand a fallback agent's
2012    /// session id to the agent that just lost the seat to quota.
2013    ///
2014    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
2015    /// — `self.seat` only reuses state when the agent id is unchanged, so
2016    /// handing it a different id already gets this for free. Reusing the old
2017    /// seat would resume a different CLI's session as if it were a
2018    /// continuation of this one.
2019    ///
2020    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
2021    /// a quota loss cuts an agent off mid-turn, so anything already in the
2022    /// tree is unfinished work, not a completed candidate a re-ask would pay
2023    /// for twice. A dirty tree is rescued into a commit first (the same
2024    /// neutral-identity rescue `implement`'s own outcome loop gives every
2025    /// candidate) so the next agent starts clean.
2026    ///
2027    /// The new agent gets the implementer's full prompt and full
2028    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
2029    /// it has no session and no context, and is implementing the task from
2030    /// nothing, unlike a resumed drop which is only restating work already
2031    /// done.
2032    ///
2033    /// Every intermediate `Quota` this loop absorbs is folded into a plain
2034    /// `implement` event, never into `self.state.quota` — that is what
2035    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
2036    /// go unspent, and a seat that ultimately recovered on its second or
2037    /// third agent is not the stalled panel that check exists to catch. Only
2038    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
2039    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
2040    /// outcome loop already has — this helper never pushes to it itself.
2041    async fn resume_seat_handovers(
2042        &mut self,
2043        results: &mut [(usize, SeatState, AgentOutcome)],
2044        sent: &mut [SeatJob],
2045        prompts: &Prompts,
2046        run_id: &str,
2047    ) {
2048        let instruction = seeded_instruction(&self.state);
2049        let language = self.state.config.graph.language.clone();
2050        let brief = self
2051            .state
2052            .advice
2053            .as_ref()
2054            .and_then(|a| a.synthesis.as_deref())
2055            .map(str::to_owned);
2056        let attachments = self.state.attachments.clone();
2057        for (wi, seat, out) in results.iter_mut() {
2058            let Some(job) = sent.get_mut(*wi) else {
2059                continue;
2060            };
2061            // Where the seat's own original agent sits in the roster — the
2062            // fallback walk starts just past here, never at the front, so a
2063            // later candidate slot's quota loss does not fall back onto an
2064            // earlier slot's own agent.
2065            let start = self
2066                .roles
2067                .implementer_roster
2068                .iter()
2069                .position(|s| s.id == job.spec.id)
2070                .unwrap_or(0);
2071            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
2072            let mut fallback_attempt = 0usize;
2073            let mut prev: Option<FailClass> = None;
2074            while let Some(cur) = FailClass::of(&*out) {
2075                if !should_hand_over(prev.as_ref(), &cur) {
2076                    break;
2077                }
2078                let Some(next) =
2079                    next_untried_in_roster(&self.roles.implementer_roster, start, &tried).cloned()
2080                else {
2081                    break;
2082                };
2083                tried.insert(next.id.clone());
2084                fallback_attempt += 1;
2085
2086                if let Ok(r) = git::rescue_commit(
2087                    &job.cwd,
2088                    &format!(
2089                        "magi: candidate {} (uncommitted work before {} fallback)",
2090                        seat.key,
2091                        if cur == FailClass::Quota {
2092                            "quota"
2093                        } else {
2094                            "handover"
2095                        }
2096                    ),
2097                )
2098                .await
2099                {
2100                    self.state.note_withheld("implement", &r.withheld);
2101                }
2102
2103                record_handover(
2104                    &mut self.state,
2105                    "implement",
2106                    &seat.key,
2107                    &seat.agent,
2108                    &next.id,
2109                    &cur,
2110                    &fail_reason(&*out),
2111                );
2112                prev = Some(cur.clone());
2113
2114                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
2115                self.state.seats.insert(seat.key.clone(), new_seat.clone());
2116                // Kept in sync on `sent` itself, not just the local retry: a
2117                // later helper (`resume_unconfirmed_commands`) reads `sent`
2118                // after this one returns and must see whichever agent is now
2119                // occupying the seat, not the one that just quota'd out —
2120                // otherwise it would judge session/continuation eligibility
2121                // by the wrong CLI and could resend a fallback's session id
2122                // to the agent that lost it the seat in the first place.
2123                job.spec = next.clone();
2124                let mut retry = job.clone();
2125                retry.seat = new_seat;
2126                retry.prompt = prompt::implement(
2127                    &instruction,
2128                    &job.cwd.to_string_lossy(),
2129                    &language,
2130                    brief.as_deref(),
2131                    &attachments,
2132                );
2133                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
2134                let cache = self.state.config.cache_dir();
2135                let ctx = WaveCtx {
2136                    carry_seats: false,
2137                    run: run_id,
2138                    node: "implement",
2139                    prompts,
2140                    cache: cache.as_deref(),
2141                    round: None,
2142                };
2143                let (fallback_seat, fallback_out) = run_one(
2144                    retry,
2145                    Arc::clone(&self.sem),
2146                    &ctx,
2147                    &mut self.state,
2148                    fallback_attempt,
2149                )
2150                .await;
2151                *seat = fallback_seat;
2152                *out = fallback_out;
2153            }
2154        }
2155    }
2156
2157    /// Ask an implement seat's own CLI to confirm what it started, once, when
2158    /// its reply reported a command whose completion status it never
2159    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
2160    /// that does and does not mean.
2161    ///
2162    /// The completion contract this task asks for, extended to `implement`
2163    /// with the same signal `continue_fix_report` reads for the fixer,
2164    /// rather than a keyword search over the reply or a hard requirement on
2165    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
2166    /// a candidate's CLI turn ended cleanly while a test run it had started
2167    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
2168    /// named in it at all is untouched by this: `commands` is empty, so
2169    /// there is nothing to be unconfirmed.
2170    ///
2171    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
2172    /// this is not about recovering edits that might already be on disk, it
2173    /// is about a result the seat itself never vouched for, which resuming
2174    /// asks for regardless of what the tree already holds. Bounded to one
2175    /// attempt for the same reason `resume_undelivered` is — this is the
2176    /// most expensive node in the graph — and a seat that still cannot
2177    /// confirm on that attempt is left as whatever its (possibly still
2178    /// unconfirmed) reply says; this does not invent a new "failed" reason
2179    /// for a candidate that otherwise produced a real, committed change.
2180    async fn resume_unconfirmed_commands(
2181        &mut self,
2182        results: &mut [(usize, SeatState, AgentOutcome)],
2183        sent: &[SeatJob],
2184        prompts: &Prompts,
2185        run_id: &str,
2186    ) {
2187        for (wi, seat, out) in results.iter_mut() {
2188            let AgentOutcome::Ok(o) = &*out else {
2189                continue;
2190            };
2191            if !has_unconfirmed_command(&o.commands) {
2192                continue;
2193            }
2194            let Some(job) = sent.get(*wi) else { continue };
2195            if !has_context(&job.spec, seat, job.sessions) {
2196                self.state.event(
2197                    "implement",
2198                    format!(
2199                        "{}: the reply named a command whose own CLI never confirmed the exit \
2200                         status of, but there is no session left to resume",
2201                        seat.key
2202                    ),
2203                );
2204                continue;
2205            }
2206            self.state.event(
2207                "implement",
2208                format!(
2209                    "{}: the reply named a command whose own CLI never confirmed the exit \
2210                     status of; resuming the conversation",
2211                    seat.key
2212                ),
2213            );
2214            let mut retry = job.clone();
2215            retry.seat = seat.clone();
2216            retry.prompt = prompt::resume_incomplete(
2217                "a command in your last reply had no confirmed exit status",
2218            );
2219            retry.timeout = retry_budget(job.timeout, true);
2220            retry.stem = format!("{}-confirm", job.stem);
2221            let cache = self.state.config.cache_dir();
2222            let ctx = WaveCtx {
2223                carry_seats: false,
2224                run: run_id,
2225                node: "implement",
2226                prompts,
2227                cache: cache.as_deref(),
2228                round: None,
2229            };
2230            let (resumed_seat, resumed) =
2231                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
2232            *seat = resumed_seat;
2233            *out = resumed;
2234        }
2235    }
2236
2237    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
2238    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
2239    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
2240    /// that motivated this.
2241    ///
2242    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
2243    /// own nudge loop already covers for judge/review/vote seats, and not a
2244    /// dropped stream, which [`Runner::resume_undelivered`] covers for
2245    /// implement seats: here the CLI turn genuinely finished while the node's
2246    /// own work — the fixer's account of what it did — had not. Gated purely
2247    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
2248    /// reply, never on any wording in it, so a fixer whose valid, first-try
2249    /// `FixReport` happens to mention having waited on a background test is
2250    /// never resumed — the `Ok(report)` branch at the call site returns
2251    /// before this is ever invoked.
2252    ///
2253    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
2254    /// attempt ([`retry_budget`]), nothing attempted once the session is
2255    /// gone, and a quota hit ends the loop immediately rather than retrying a
2256    /// rate limit that fails the same way again.
2257    async fn continue_fix_report(
2258        &mut self,
2259        mut seat: SeatState,
2260        parse_err: String,
2261        job: &SeatJob,
2262        prompts: &Prompts,
2263        run_id: &str,
2264        round: usize,
2265    ) -> (
2266        SeatState,
2267        Option<FixReport>,
2268        Option<String>,
2269        ContinuationRecord,
2270    ) {
2271        let mut last_err = parse_err;
2272        let mut cumulative_wait_ms = 0u64;
2273        let mut attempts = 0usize;
2274        loop {
2275            if !has_context(&job.spec, &seat, job.sessions) {
2276                self.state.event(
2277                    "fix",
2278                    format!(
2279                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
2280                         session left to resume into"
2281                    ),
2282                );
2283                let outcome = if attempts == 0 {
2284                    ContinuationOutcome::NoSession
2285                } else {
2286                    ContinuationOutcome::Exhausted
2287                };
2288                return (
2289                    seat,
2290                    None,
2291                    Some(format!("unparsable fix report: {last_err}")),
2292                    ContinuationRecord {
2293                        attempts,
2294                        cumulative_wait_ms,
2295                        outcome,
2296                    },
2297                );
2298            }
2299            if attempts >= MAX_FIX_CONTINUATIONS {
2300                self.state.event(
2301                    "fix",
2302                    format!(
2303                        "round {round}: fixer's reply still had no adoption report after \
2304                         {attempts} continuation(s) ({last_err}); giving up"
2305                    ),
2306                );
2307                return (
2308                    seat,
2309                    None,
2310                    Some(format!(
2311                        "unparsable fix report after {attempts} continuation(s): {last_err}"
2312                    )),
2313                    ContinuationRecord {
2314                        attempts,
2315                        cumulative_wait_ms,
2316                        outcome: ContinuationOutcome::Exhausted,
2317                    },
2318                );
2319            }
2320            attempts += 1;
2321            self.state.event(
2322                "fix",
2323                format!(
2324                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
2325                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
2326                ),
2327            );
2328            let mut retry = job.clone();
2329            retry.seat = seat.clone();
2330            retry.prompt = prompt::resume_incomplete(&last_err);
2331            retry.timeout = retry_budget(job.timeout, true);
2332            retry.stem = format!("{}-continue{attempts}", job.stem);
2333            let cache = self.state.config.cache_dir();
2334            let ctx = WaveCtx {
2335                carry_seats: false,
2336                run: run_id,
2337                node: "fix",
2338                prompts,
2339                cache: cache.as_deref(),
2340                round: Some(round),
2341            };
2342            let (resumed_seat, resumed_out) = run_one(
2343                retry,
2344                Arc::clone(&self.sem),
2345                &ctx,
2346                &mut self.state,
2347                attempts,
2348            )
2349            .await;
2350            seat = resumed_seat;
2351            match resumed_out {
2352                AgentOutcome::Ok(o) => {
2353                    cumulative_wait_ms += o.duration_ms;
2354                    match verdict::extract_json::<FixReport>(&o.text) {
2355                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
2356                            self.state.event(
2357                                "fix",
2358                                format!(
2359                                    "round {round}: fixer's adoption report recovered after \
2360                                     {attempts} continuation(s)"
2361                                ),
2362                            );
2363                            return (
2364                                seat,
2365                                Some(report),
2366                                None,
2367                                ContinuationRecord {
2368                                    attempts,
2369                                    cumulative_wait_ms,
2370                                    outcome: ContinuationOutcome::Resumed,
2371                                },
2372                            );
2373                        }
2374                        // The report parsed, but this same reply's own
2375                        // CommandEvidence — the identical record `state.jobs`
2376                        // renders — names a command whose CLI never
2377                        // confirmed an exit status. Read together, that is
2378                        // not a resolved answer: keep nudging rather than
2379                        // accept a report standing next to a command the
2380                        // seat's own CLI cannot vouch for.
2381                        Ok(_) => {
2382                            last_err = "the reply parsed, but it reported a command whose own CLI \
2383                                 never confirmed an exit status"
2384                                .to_owned();
2385                        }
2386                        Err(e) => last_err = e.to_string(),
2387                    }
2388                }
2389                AgentOutcome::Quota(o) => {
2390                    cumulative_wait_ms += o.duration_ms;
2391                    self.state.quota.push(QuotaLoss {
2392                        seat: seat.key.clone(),
2393                        node: "fix".to_owned(),
2394                        at: Timestamp::now(),
2395                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
2396                    });
2397                    self.state.event(
2398                        "fix",
2399                        format!(
2400                            "round {round}: continuation rate limited (quota); not retrying now"
2401                        ),
2402                    );
2403                    return (
2404                        seat,
2405                        None,
2406                        Some("rate limited (quota) while recovering the fix report".to_owned()),
2407                        ContinuationRecord {
2408                            attempts,
2409                            cumulative_wait_ms,
2410                            outcome: ContinuationOutcome::QuotaLost,
2411                        },
2412                    );
2413                }
2414                AgentOutcome::Dropped(o) => {
2415                    cumulative_wait_ms += o.duration_ms;
2416                    let why = o
2417                        .dropped
2418                        .as_ref()
2419                        .map(|d| d.why.as_str())
2420                        .unwrap_or("the CLI ended the stream without delivering its answer");
2421                    last_err = format!("the CLI dropped the stream ({why})");
2422                }
2423                AgentOutcome::Failed(e) => last_err = e,
2424            }
2425        }
2426    }
2427
2428    fn after_implement(&mut self) -> Result<()> {
2429        // Scan every candidate patch once the set is complete.
2430        if self.state.leaks.is_empty() {
2431            let cfg = self.state.config.blind.clone();
2432            let mut leaks = Vec::new();
2433            for c in &self.state.candidates {
2434                let Some(patch) =
2435                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
2436                else {
2437                    continue;
2438                };
2439                leaks.extend(blind::scan(
2440                    &format!("candidate {} patch", c.label),
2441                    &patch,
2442                    &cfg.vendor_tokens,
2443                ));
2444            }
2445            if !leaks.is_empty() {
2446                let summary = leaks
2447                    .iter()
2448                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
2449                    .collect::<Vec<_>>()
2450                    .join(", ");
2451                match cfg.on_leak {
2452                    LeakPolicy::Fail => {
2453                        self.state.status = RunStatus::Failed;
2454                        self.state
2455                            .event("blind", format!("vendor text in a patch: {summary}"));
2456                        self.state.leaks = leaks;
2457                        self.state.save()?;
2458                        self.settle_questions();
2459                        bail!(
2460                            "blind.on_leak = \"fail\" and vendor text reached a \
2461                             judged patch: {summary}"
2462                        );
2463                    }
2464                    LeakPolicy::Redact => self.state.event(
2465                        "blind",
2466                        format!("redacting vendor text for judging: {summary}"),
2467                    ),
2468                    LeakPolicy::Warn => self.state.event(
2469                        "blind",
2470                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
2471                    ),
2472                }
2473                self.state.leaks = leaks;
2474            }
2475        }
2476
2477        if self.state.viable().is_empty() {
2478            if self.state.all_candidates_verified_noop() {
2479                // Every candidate agreed, with evidence the adoption guard
2480                // accepted, that nothing belongs in this worktree. That is
2481                // not the same fact as a candidate that simply failed to
2482                // write anything, and settling it as an ordinary `Failed`
2483                // (see `SCHEMA`'s doc for schema 10) is what let two of
2484                // task 391f's attempts burn a retry each re-discovering the
2485                // same already-landed fix. Terminal either way, so `judge`
2486                // must never run over an empty candidate set — unlike the
2487                // `Failed` branch below this returns `Ok`, not an error:
2488                // nothing here failed.
2489                self.state.status = RunStatus::VerifiedNoop;
2490                self.state.save()?;
2491                self.settle_questions();
2492                return Ok(());
2493            }
2494            self.state.status = RunStatus::Failed;
2495            self.state.save()?;
2496            self.settle_questions();
2497            bail!("no candidate produced a change; nothing to judge");
2498        }
2499        self.state.status = RunStatus::Judging;
2500        self.state.save()?;
2501        Ok(())
2502    }
2503
2504    // --------------------------------------------------------------- judge
2505
2506    async fn judge(&mut self) -> Result<()> {
2507        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2508        // agent files with `magi task add` name the run that paid for it. The
2509        // prompt overlay is cloned alongside it because the waves borrow it
2510        // while `self` is mutably borrowed by the node's own bookkeeping.
2511        let run_id = self.state.id.clone();
2512        let prompts = self.state.config.prompts.clone();
2513        if !self.state.judgements.is_empty() || self.state.judge_skipped {
2514            return Ok(());
2515        }
2516        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2517        if viable.len() == 1 {
2518            // Recorded so this is a one-time event: `judgements` stays empty
2519            // either way, which without this flag is indistinguishable from
2520            // "not yet judged" on the next reentry — and status is left
2521            // untouched, so a later node's conclusion (e.g. `Blocked` after
2522            // the review budget ran out) survives a resume instead of being
2523            // clobbered back to `Judging` by this node running again.
2524            self.state.judge_skipped = true;
2525            self.state.event(
2526                "judge",
2527                format!(
2528                    "only candidate {} produced a change; judging skipped",
2529                    viable[0].label
2530                ),
2531            );
2532            self.state.save()?;
2533            return Ok(());
2534        }
2535        self.state.status = RunStatus::Judging;
2536
2537        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
2538        let language = self.state.config.graph.language.clone();
2539        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2540        let sessions = self.state.config.graph.sessions;
2541        let artifacts = agent::artifacts_dir(&self.state.dir());
2542        let root = self.state.worktree_root();
2543        let base_short = short(&self.state.base_commit);
2544
2545        let mut jobs = Vec::new();
2546        let mut orders = Vec::new();
2547        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2548            let order = blind::presentation_order(viable.len(), j, self.state.seed);
2549            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
2550            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
2551            let seat_key = format!("judge-{}", j + 1);
2552            let seat = self.seat(&seat_key, &spec.id);
2553            jobs.push(SeatJob {
2554                prompt: prompt::judge(
2555                    &self.state.instruction,
2556                    &views,
2557                    self.roles.judges.len(),
2558                    &base_short,
2559                    &language,
2560                ),
2561                spec,
2562                seat,
2563                cwd: root.join(format!("judge-{}", j + 1)),
2564                timeout,
2565                allow_write: false,
2566                sessions,
2567                artifacts: artifacts.clone(),
2568                stem: format!("judge-{}", j + 1),
2569                handover: None,
2570            });
2571        }
2572
2573        self.state.event(
2574            "judge",
2575            format!(
2576                "{} judges ranking {} candidates blind",
2577                jobs.len(),
2578                viable.len()
2579            ),
2580        );
2581        let labels_for_check = labels.clone();
2582        let mut quota_losses = Vec::new();
2583        let cache = self.state.config.cache_dir();
2584        let ctx = WaveCtx {
2585            carry_seats: false,
2586            run: &run_id,
2587            node: "judge",
2588            prompts: &prompts,
2589            cache: cache.as_deref(),
2590            round: None,
2591        };
2592        let results = ask_json_wave::<Ranking>(
2593            jobs,
2594            Arc::clone(&self.sem),
2595            self.state.config.graph.retries,
2596            &self.roles.judge_roster,
2597            &ctx,
2598            &mut quota_losses,
2599            &mut self.state,
2600            &move |r: &Ranking| r.validate(&labels_for_check),
2601        )
2602        .await;
2603        self.state.quota.extend(quota_losses);
2604
2605        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
2606            let agent_id = seat.agent.clone();
2607            self.state.seats.insert(seat.key.clone(), seat);
2608            let mut record = Judgement {
2609                judge: j + 1,
2610                seat: format!("judge-{}", j + 1),
2611                agent: agent_id,
2612                ranking: Vec::new(),
2613                reasons: BTreeMap::new(),
2614                confidence: None,
2615                order: orders[j].clone(),
2616                failed: None,
2617                duration_ms: 0,
2618            };
2619            match res {
2620                Ok((ranking, out)) => {
2621                    record.ranking = ranking.normalized();
2622                    record.reasons = ranking.reasons;
2623                    record.confidence = ranking.confidence;
2624                    record.duration_ms = out.duration_ms;
2625                    self.state.event(
2626                        "judge",
2627                        format!(
2628                            "judge {} ranked {}",
2629                            j + 1,
2630                            record.ranking.iter().collect::<String>()
2631                        ),
2632                    );
2633                }
2634                Err(e) => {
2635                    record.failed = Some(e.to_string());
2636                    self.state
2637                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
2638                }
2639            }
2640            self.state.judgements.push(record);
2641            self.state.save()?;
2642        }
2643        Ok(())
2644    }
2645
2646    // ---------------------------------------------------------- deliberate
2647
2648    async fn deliberate(&mut self) -> Result<()> {
2649        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2650        // agent files with `magi task add` name the run that paid for it. The
2651        // prompt overlay is cloned alongside it because the waves borrow it
2652        // while `self` is mutably borrowed by the node's own bookkeeping.
2653        let run_id = self.state.id.clone();
2654        let prompts = self.state.config.prompts.clone();
2655        if !self.state.deliberation.is_empty() {
2656            return Ok(());
2657        }
2658        let tops: Vec<char> = self
2659            .state
2660            .judgements
2661            .iter()
2662            .filter_map(|j| j.ranking.first().copied())
2663            .collect();
2664        let rounds = self.state.config.graph.deliberate_rounds;
2665        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
2666            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
2667                self.state.event(
2668                    "deliberate",
2669                    format!("judges agreed on {} outright; no deliberation", tops[0]),
2670                );
2671            }
2672            self.state.status = RunStatus::Voting;
2673            self.state.save()?;
2674            return Ok(());
2675        }
2676
2677        self.state.status = RunStatus::Deliberating;
2678        self.state.event(
2679            "deliberate",
2680            format!(
2681                "split: first choices were {} — opening {rounds} round(s)",
2682                tops.iter().collect::<String>()
2683            ),
2684        );
2685
2686        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2687        let language = self.state.config.graph.language.clone();
2688        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2689        let sessions = self.state.config.graph.sessions;
2690        let artifacts = agent::artifacts_dir(&self.state.dir());
2691        let root = self.state.worktree_root();
2692        let base_short = short(&self.state.base_commit);
2693
2694        // Judges argue in sequence so that a turn can answer the one before it;
2695        // that is the difference between deliberation and three parallel
2696        // monologues.
2697        for round in 1..=rounds {
2698            let mut turns: Vec<DeliberationTurn> = Vec::new();
2699            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2700                if self.state.judgements[j].failed.is_some() {
2701                    continue;
2702                }
2703                let seat_key = format!("judge-{}", j + 1);
2704                let spec = self.occupant(&seat_key, spec);
2705                let mut seat = self.seat(&seat_key, &spec.id);
2706                let transcript = self.transcript(&turns, j);
2707                let build = |context: Option<&str>| {
2708                    prompt::deliberate(
2709                        &self.state.instruction,
2710                        context,
2711                        &transcript,
2712                        round,
2713                        rounds,
2714                        &language,
2715                    )
2716                };
2717                let block = self.candidate_block(&viable, &base_short);
2718                let full = build(Some(&block));
2719                let text = if has_context(&spec, &seat, sessions) {
2720                    build(None)
2721                } else {
2722                    full.clone()
2723                };
2724                let job = SeatJob {
2725                    spec,
2726                    seat: seat.clone(),
2727                    prompt: text,
2728                    cwd: root.join(format!("judge-{}", j + 1)),
2729                    timeout,
2730                    allow_write: false,
2731                    sessions,
2732                    artifacts: artifacts.clone(),
2733                    stem: format!("delib-{round}-judge-{}", j + 1),
2734                    handover: Some(full),
2735                };
2736                let cache = self.state.config.cache_dir();
2737                let ctx = WaveCtx {
2738                    carry_seats: false,
2739                    run: &run_id,
2740                    node: "deliberate",
2741                    prompts: &prompts,
2742                    cache: cache.as_deref(),
2743                    round: None,
2744                };
2745                // A turn is never nudged (`retries` 0): a failed seat is
2746                // handed to the next roster agent, which gets the full
2747                // context. An empty answer is a turn, not a failure.
2748                let mut losses = Vec::new();
2749                let mut results = ask_wave_with::<String>(
2750                    vec![job],
2751                    Arc::clone(&self.sem),
2752                    0,
2753                    &self.roles.judge_roster,
2754                    &ctx,
2755                    &mut losses,
2756                    &mut self.state,
2757                    &|text: &str| {
2758                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
2759                    },
2760                )
2761                .await;
2762                self.state.quota.extend(losses);
2763                let (updated, res, _) = results.pop().expect("one job in, one result out");
2764                seat = updated;
2765                let agent_id = seat.agent.clone();
2766                self.state.seats.insert(seat.key.clone(), seat);
2767                let body = match res {
2768                    Ok((body, _)) => body,
2769                    // Skip the seat; a CLI's raw error JSON is never read as
2770                    // this judge's position.
2771                    Err(e) => {
2772                        self.state
2773                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
2774                        continue;
2775                    }
2776                };
2777                let tentative = verdict::extract_json::<Position>(&body)
2778                    .ok()
2779                    .and_then(|p| p.tentative)
2780                    .and_then(|s| s.trim().chars().next())
2781                    .map(|c| c.to_ascii_uppercase());
2782                self.state.event(
2783                    "deliberate",
2784                    format!(
2785                        "round {round}: judge {} now favours {}",
2786                        j + 1,
2787                        tentative.map_or("—".to_owned(), |c| c.to_string())
2788                    ),
2789                );
2790                turns.push(DeliberationTurn {
2791                    judge: j + 1,
2792                    agent: agent_id,
2793                    body: blind::sanitize_prose(&body, &self.state.config.blind),
2794                    tentative,
2795                });
2796            }
2797            self.state
2798                .deliberation
2799                .push(DeliberationRound { round, turns });
2800            self.state.save()?;
2801        }
2802
2803        self.state.status = RunStatus::Voting;
2804        self.state.save()?;
2805        Ok(())
2806    }
2807
2808    // ---------------------------------------------------------------- vote
2809
2810    async fn vote(&mut self) -> Result<()> {
2811        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2812        // agent files with `magi task add` name the run that paid for it. The
2813        // prompt overlay is cloned alongside it because the waves borrow it
2814        // while `self` is mutably borrowed by the node's own bookkeeping.
2815        let run_id = self.state.id.clone();
2816        let prompts = self.state.config.prompts.clone();
2817        if !self.state.votes.is_empty() {
2818            return Ok(());
2819        }
2820        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
2821        if viable.len() == 1 {
2822            return Ok(());
2823        }
2824        self.state.status = RunStatus::Voting;
2825
2826        let language = self.state.config.graph.language.clone();
2827        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2828        let sessions = self.state.config.graph.sessions;
2829        let artifacts = agent::artifacts_dir(&self.state.dir());
2830        let root = self.state.worktree_root();
2831        let base_short = short(&self.state.base_commit);
2832        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2833
2834        let mut jobs = Vec::new();
2835        let mut seats_at = Vec::new();
2836        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2837            if self
2838                .state
2839                .judgements
2840                .get(j)
2841                .is_some_and(|r| r.failed.is_some())
2842            {
2843                continue;
2844            }
2845            let seat_key = format!("judge-{}", j + 1);
2846            let spec = self.occupant(&seat_key, spec);
2847            let seat = self.seat(&seat_key, &spec.id);
2848            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
2849            let text = if has_context(&spec, &seat, sessions) {
2850                prompt::final_vote(&viable, &language)
2851            } else {
2852                full.clone()
2853            };
2854            jobs.push(SeatJob {
2855                spec,
2856                seat,
2857                prompt: text,
2858                cwd: root.join(format!("judge-{}", j + 1)),
2859                timeout,
2860                allow_write: false,
2861                sessions,
2862                artifacts: artifacts.clone(),
2863                stem: format!("vote-judge-{}", j + 1),
2864                handover: Some(full),
2865            });
2866            seats_at.push(j);
2867        }
2868
2869        self.state.event(
2870            "vote",
2871            format!(
2872                "collecting {} final votes one by one, privately",
2873                jobs.len()
2874            ),
2875        );
2876        let allowed = viable.clone();
2877        let mut quota_losses = Vec::new();
2878        let cache = self.state.config.cache_dir();
2879        let ctx = WaveCtx {
2880            carry_seats: false,
2881            run: &run_id,
2882            node: "vote",
2883            prompts: &prompts,
2884            cache: cache.as_deref(),
2885            round: None,
2886        };
2887        let results = ask_json_wave::<FinalVote>(
2888            jobs,
2889            Arc::clone(&self.sem),
2890            self.state.config.graph.retries,
2891            &self.roles.judge_roster,
2892            &ctx,
2893            &mut quota_losses,
2894            &mut self.state,
2895            &move |v: &FinalVote| match v.label() {
2896                Some(c) if allowed.contains(&c) => Ok(()),
2897                other => bail!("vote {other:?} is not one of {allowed:?}"),
2898            },
2899        )
2900        .await;
2901        self.state.quota.extend(quota_losses);
2902
2903        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
2904            let agent_id = seat.agent.clone();
2905            self.state.seats.insert(seat.key.clone(), seat);
2906            let initial = self
2907                .state
2908                .judgements
2909                .get(j)
2910                .and_then(|r| r.ranking.first().copied());
2911            let mut record = VoteRecord {
2912                judge: j + 1,
2913                agent: agent_id,
2914                vote: None,
2915                reason: String::new(),
2916                changed: false,
2917            };
2918            match res {
2919                Ok((v, _)) => {
2920                    record.vote = v.label();
2921                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
2922                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
2923                    self.state.event(
2924                        "vote",
2925                        format!(
2926                            "judge {} voted {}{}",
2927                            j + 1,
2928                            record.vote.unwrap_or('?'),
2929                            if record.changed { " (changed)" } else { "" }
2930                        ),
2931                    );
2932                }
2933                Err(e) => {
2934                    self.state
2935                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
2936                }
2937            }
2938            self.state.votes.push(record);
2939            self.state.save()?;
2940        }
2941        Ok(())
2942    }
2943
2944    // --------------------------------------------------------------- tally
2945
2946    fn tally(&mut self) -> Result<()> {
2947        if self.state.tally.is_some() {
2948            return Ok(());
2949        }
2950        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
2951        let tops: Vec<char> = self
2952            .state
2953            .judgements
2954            .iter()
2955            .filter_map(|j| j.ranking.first().copied())
2956            .collect();
2957        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
2958
2959        // A judge whose private vote failed still counted once, in the initial
2960        // ranking; using it beats discarding a whole seat.
2961        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
2962        let mut cast: Vec<char> = Vec::new();
2963        for (i, j) in self.state.judgements.iter().enumerate() {
2964            let vote = self
2965                .state
2966                .votes
2967                .iter()
2968                .find(|v| v.judge == i + 1)
2969                .and_then(|v| v.vote)
2970                .or_else(|| j.ranking.first().copied());
2971            if let Some(v) = vote {
2972                *first_choice.entry(v).or_insert(0) += 1;
2973                cast.push(v);
2974            }
2975        }
2976
2977        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
2978        for j in &self.state.judgements {
2979            let n = j.ranking.len();
2980            for (pos, label) in j.ranking.iter().enumerate() {
2981                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
2982            }
2983        }
2984
2985        let best = first_choice.values().copied().max().unwrap_or(0);
2986        let mut leaders: Vec<char> = first_choice
2987            .iter()
2988            .filter(|(_, v)| **v == best)
2989            .map(|(k, _)| *k)
2990            .collect();
2991        let mut tie_break = None;
2992        if leaders.len() > 1 {
2993            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
2994            let borda_leaders: Vec<char> = leaders
2995                .iter()
2996                .copied()
2997                .filter(|l| borda[l] == top_borda)
2998                .collect();
2999            tie_break = Some(if borda_leaders.len() == 1 {
3000                format!(
3001                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
3002                    leaders.len()
3003                )
3004            } else {
3005                format!(
3006                    "{} way tie on both first-choice votes and Borda points, broken by label order",
3007                    leaders.len()
3008                )
3009            });
3010            leaders = borda_leaders;
3011            leaders.sort_unstable();
3012        }
3013        let winner = *leaders
3014            .first()
3015            .or(viable.first())
3016            .context("no candidate to declare a winner from")?;
3017
3018        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
3019        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
3020        let deliberated = !self.state.deliberation.is_empty();
3021
3022        // Whose verdict is this? A rate-limited seat is absent even if it
3023        // ranked before the limit hit, so presence is measured against the
3024        // recorded losses, not just "did a ranking ever appear".
3025        let quota_seats: std::collections::BTreeSet<&str> =
3026            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
3027        let mut present = 0usize;
3028        for (i, j) in self.state.judgements.iter().enumerate() {
3029            if quota_seats.contains(j.seat.as_str()) {
3030                continue;
3031            }
3032            let ranked = !j.ranking.is_empty() && j.failed.is_none();
3033            let voted = self
3034                .state
3035                .votes
3036                .iter()
3037                .any(|v| v.judge == i + 1 && v.vote.is_some());
3038            if ranked || voted {
3039                present += 1;
3040            }
3041        }
3042        // Strict majority of the configured panel. A bare majority is real
3043        // signal we can act on, while a minority verdict must never stand in
3044        // for a healthy one. A one-candidate run needs no panel at all, and
3045        // `judges` stays `0` rather than the roster size a panel that never
3046        // sat would otherwise be credited with.
3047        let needs_quorum = viable.len() > 1;
3048        let judges_total = if needs_quorum {
3049            self.roles.judges.len()
3050        } else {
3051            0
3052        };
3053        let quorum = if needs_quorum {
3054            judges_total / 2 + 1
3055        } else {
3056            0
3057        };
3058        let met_quorum = !needs_quorum || present >= quorum;
3059        let uncontested = (!needs_quorum).then(|| {
3060            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
3061        });
3062
3063        self.state.event(
3064            "tally",
3065            match &uncontested {
3066                Some(reason) => format!("winner {winner} — {reason}"),
3067                None => format!(
3068                    "winner {winner} — votes {} | initial {} | {} changed | \
3069                     {present}/{judges_total} judges{}",
3070                    first_choice
3071                        .iter()
3072                        .map(|(k, v)| format!("{k}:{v}"))
3073                        .collect::<Vec<_>>()
3074                        .join(" "),
3075                    if unanimous_initial {
3076                        "unanimous"
3077                    } else {
3078                        "split"
3079                    },
3080                    changed_votes,
3081                    if met_quorum {
3082                        String::new()
3083                    } else {
3084                        format!(" — below quorum ({quorum} required)")
3085                    },
3086                ),
3087            },
3088        );
3089        if !met_quorum {
3090            self.state.event(
3091                "stall",
3092                format!(
3093                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
3094                     the run stops here, resumable"
3095                ),
3096            );
3097        }
3098        self.state.tally = Some(Tally {
3099            first_choice,
3100            borda,
3101            winner,
3102            rankings: tops.len(),
3103            unanimous_initial,
3104            deliberated,
3105            changed_votes,
3106            unanimous_final,
3107            tie_break,
3108            judges: judges_total,
3109            present,
3110            quorum,
3111            met_quorum,
3112            uncontested,
3113        });
3114        self.state.status = if met_quorum {
3115            RunStatus::Reviewing
3116        } else {
3117            RunStatus::Stalled
3118        };
3119        self.state.save()?;
3120        Ok(())
3121    }
3122
3123    // ------------------------------------------------------------- recover
3124
3125    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
3126    /// resumed toward completion once the transient cause clears.
3127    ///
3128    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
3129    /// it toward the quorum, which is exactly the set of seats whose absence
3130    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
3131    /// not depend on which node happened to hit the limit), or an ordinary
3132    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
3133    /// seat is never disturbed.
3134    ///
3135    /// A seat that now answers with a usable ranking is "recovered": its
3136    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
3137    /// `tally` counts it present again), and its vote re-collected. A seat that
3138    /// still fails keeps its loss and stays absent.
3139    ///
3140    /// Returns `true` when the re-tally restores the quorum (the run may proceed
3141    /// to review/gate/merge), `false` when it is still below quorum (the run
3142    /// stays `Stalled`, still resumable for a later retry).
3143    #[allow(clippy::too_many_lines)]
3144    async fn recover_stall(&mut self) -> Result<bool> {
3145        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3146        // agent files with `magi task add` name the run that paid for it. The
3147        // prompt overlay is cloned alongside it because the waves borrow it
3148        // while `self` is mutably borrowed by the node's own bookkeeping.
3149        let run_id = self.state.id.clone();
3150        let prompts = self.state.config.prompts.clone();
3151        // Absent seats = quota-lost at any node, or failed outright. Mirroring
3152        // `tally`'s presence test (rather than the old quota-judge/vote filter)
3153        // is what keeps a non-quota collapse — or a quota loss recorded at the
3154        // deliberate node — from being a permanent dead-end on `--resume`.
3155        let quota_seats: BTreeSet<&str> =
3156            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
3157        let absent: Vec<String> = self
3158            .state
3159            .judgements
3160            .iter()
3161            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
3162            .map(|j| j.seat.clone())
3163            .collect();
3164        if absent.is_empty() {
3165            return Ok(false);
3166        }
3167        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
3168        if viable.len() <= 1 {
3169            return Ok(false);
3170        }
3171        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
3172        let language = self.state.config.graph.language.clone();
3173        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
3174        let sessions = self.state.config.graph.sessions;
3175        let artifacts = agent::artifacts_dir(&self.state.dir());
3176        let root = self.state.worktree_root();
3177        let base_short = short(&self.state.base_commit);
3178        let candidates: Vec<Candidate> = viable.clone();
3179
3180        // Map each absent seat key to its 0-based position in `roles.judges`.
3181        let mut positions: Vec<usize> = absent
3182            .iter()
3183            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
3184            .collect();
3185        if positions.is_empty() {
3186            return Ok(false);
3187        }
3188        positions.sort_unstable();
3189        positions.dedup();
3190
3191        // Re-rank the lost seats, one blind prompt each.
3192        let mut judge_jobs = Vec::new();
3193        for &j in &positions {
3194            let order = blind::presentation_order(viable.len(), j, self.state.seed);
3195            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
3196            let seat_key = format!("judge-{}", j + 1);
3197            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
3198            let seat = self.seat(&seat_key, &spec.id);
3199            judge_jobs.push(SeatJob {
3200                spec,
3201                seat,
3202                prompt: prompt::judge(
3203                    &self.state.instruction,
3204                    &views,
3205                    self.roles.judges.len(),
3206                    &base_short,
3207                    &language,
3208                ),
3209                cwd: root.join(seat_key),
3210                timeout,
3211                allow_write: false,
3212                sessions,
3213                artifacts: artifacts.clone(),
3214                stem: format!("judge-{}-recover", j + 1),
3215                handover: None,
3216            });
3217        }
3218
3219        let labels_for_check = labels.clone();
3220        let mut judge_losses = Vec::new();
3221        let retries = self.state.config.graph.retries;
3222        let cache = self.state.config.cache_dir();
3223        let ctx = WaveCtx {
3224            carry_seats: false,
3225            run: &run_id,
3226            node: "judge",
3227            prompts: &prompts,
3228            cache: cache.as_deref(),
3229            round: None,
3230        };
3231        let results = ask_json_wave::<Ranking>(
3232            judge_jobs,
3233            Arc::clone(&self.sem),
3234            retries,
3235            &self.roles.judge_roster,
3236            &ctx,
3237            &mut judge_losses,
3238            &mut self.state,
3239            &move |r: &Ranking| r.validate(&labels_for_check),
3240        )
3241        .await;
3242
3243        // Refresh the judgement of every seat that ranked again.
3244        let mut recovered: BTreeSet<usize> = BTreeSet::new();
3245        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
3246            let agent_id = seat.agent.clone();
3247            self.state.seats.insert(seat.key.clone(), seat);
3248            let record = &mut self.state.judgements[j];
3249            match res {
3250                Ok((ranking, out)) => {
3251                    record.agent = agent_id;
3252                    record.ranking = ranking.normalized();
3253                    record.reasons = ranking.reasons;
3254                    record.confidence = ranking.confidence;
3255                    record.failed = None;
3256                    record.duration_ms = out.duration_ms;
3257                    recovered.insert(j);
3258                    self.state.event(
3259                        "recover",
3260                        format!("judge {} ranked again after the limit", j + 1),
3261                    );
3262                }
3263                Err(e) => {
3264                    self.state
3265                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
3266                }
3267            }
3268        }
3269
3270        // Re-ask the votes of the seats that recovered a ranking.
3271        let mut vote_jobs = Vec::new();
3272        let mut vote_pos: Vec<usize> = Vec::new();
3273        for &j in &recovered {
3274            let seat_key = format!("judge-{}", j + 1);
3275            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
3276            let seat = self.seat(&seat_key, &spec.id);
3277            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
3278            let text = if has_context(&spec, &seat, sessions) {
3279                prompt::final_vote(&labels, &language)
3280            } else {
3281                full.clone()
3282            };
3283            vote_jobs.push(SeatJob {
3284                spec,
3285                seat,
3286                prompt: text,
3287                cwd: root.join(seat_key),
3288                timeout,
3289                allow_write: false,
3290                sessions,
3291                artifacts: artifacts.clone(),
3292                stem: format!("vote-judge-{}-recover", j + 1),
3293                handover: Some(full),
3294            });
3295            vote_pos.push(j);
3296        }
3297        let allowed = labels.clone();
3298        let mut vote_losses = Vec::new();
3299        let vote_retries = self.state.config.graph.retries;
3300        let vote_cache = self.state.config.cache_dir();
3301        let ctx = WaveCtx {
3302            carry_seats: false,
3303            run: &run_id,
3304            node: "vote",
3305            prompts: &prompts,
3306            cache: vote_cache.as_deref(),
3307            round: None,
3308        };
3309        let votes = ask_json_wave::<FinalVote>(
3310            vote_jobs,
3311            Arc::clone(&self.sem),
3312            vote_retries,
3313            &self.roles.judge_roster,
3314            &ctx,
3315            &mut vote_losses,
3316            &mut self.state,
3317            &move |v: &FinalVote| match v.label() {
3318                Some(c) if allowed.contains(&c) => Ok(()),
3319                other => bail!("vote {other:?} is not one of {allowed:?}"),
3320            },
3321        )
3322        .await;
3323        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
3324            let agent_id = seat.agent.clone();
3325            self.state.seats.insert(seat.key.clone(), seat);
3326            match res {
3327                Ok((v, _)) => {
3328                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
3329                        rec.vote = v.label();
3330                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
3331                    } else {
3332                        self.state.votes.push(VoteRecord {
3333                            judge: j + 1,
3334                            agent: agent_id,
3335                            vote: v.label(),
3336                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
3337                            changed: false,
3338                        });
3339                    }
3340                    self.state.event(
3341                        "recover",
3342                        format!("judge {} voted again after the limit", j + 1),
3343                    );
3344                }
3345                Err(e) => {
3346                    self.state
3347                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
3348                }
3349            }
3350        }
3351
3352        // A seat that ranked again is present even if its re-vote failed —
3353        // `tally` falls back to the initial ranking's first choice — so clear
3354        // its quota loss. Seats that still fail keep theirs and stay absent.
3355        let recovered_keys: BTreeSet<String> = recovered
3356            .iter()
3357            .map(|&j| format!("judge-{}", j + 1))
3358            .collect();
3359        self.state
3360            .quota
3361            .retain(|q| !recovered_keys.contains(&q.seat));
3362        // A seat that hit the limit again is a fresh loss, not the old one:
3363        // replace the stale entry so the history stays one-per-seat and the
3364        // daemon can tell this attempt's loss from a previous session's.
3365        for loss in judge_losses.into_iter().chain(vote_losses) {
3366            if recovered_keys.contains(&loss.seat) {
3367                continue;
3368            }
3369            self.state.quota.retain(|q| q.seat != loss.seat);
3370            self.state.quota.push(loss);
3371        }
3372
3373        // Recompute the verdict from the refreshed panel.
3374        self.state.tally = None;
3375        self.tally()?;
3376        Ok(self
3377            .state
3378            .tally
3379            .as_ref()
3380            .map(|t| t.met_quorum)
3381            .unwrap_or(false))
3382    }
3383
3384    // ----------------------------------------------------------------- fold
3385
3386    async fn fold_losers(&mut self) -> Result<()> {
3387        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
3388            return Ok(());
3389        };
3390        let repo = self.state.repo.clone();
3391        let mut folded = Vec::new();
3392        for i in 0..self.state.candidates.len() {
3393            let c = &self.state.candidates[i];
3394            if c.label == winner || c.folded {
3395                continue;
3396            }
3397            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
3398            git::worktree_remove(&repo, &wt).await.ok();
3399            git::branch_delete(&repo, &branch).await.ok();
3400            self.state.candidates[i].folded = true;
3401            folded.push(label.to_string());
3402        }
3403        // The judges are finished; their checkouts are pure cost from here.
3404        let root = self.state.worktree_root();
3405        for j in 1..=self.roles.judges.len() {
3406            let wt = root.join(format!("judge-{j}"));
3407            if wt.exists() {
3408                git::worktree_remove(&repo, &wt).await.ok();
3409            }
3410        }
3411        // The design-deliberation stage is finished by the time a tally
3412        // exists — same reasoning as the judges above.
3413        if self.state.config.graph.advise {
3414            for k in 1..=self.state.config.graph.advisors {
3415                let wt = root.join(format!("advisor-{k}"));
3416                if wt.exists() {
3417                    git::worktree_remove(&repo, &wt).await.ok();
3418                }
3419            }
3420        }
3421        if !folded.is_empty() {
3422            self.state
3423                .event("fold", format!("folded candidates {}", folded.join(", ")));
3424            self.state.save()?;
3425        }
3426        Ok(())
3427    }
3428
3429    // ------------------------------------------------------------ base sync
3430
3431    /// Land the winner's tree on the current tip of `<remote>/<base>` before
3432    /// anything verifies it.
3433    ///
3434    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
3435    /// read whatever is checked out in the winner's worktree. Left alone that
3436    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
3437    /// it when the run *branched* - and a run takes long enough that the base
3438    /// has usually moved by the time it gets here. A gate that ran there
3439    /// answers "green on the commit this run started from", not "green on
3440    /// what is about to land", and the difference showed up three times in
3441    /// one day as a green run whose merge would have reverted a file another
3442    /// pull request had already landed.
3443    ///
3444    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
3445    /// `land::Step::Rebase` calls, rather than a second implementation of the
3446    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
3447    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
3448    /// doc warns about ("two answers to a question nobody notices until a
3449    /// diff is wrong").
3450    ///
3451    /// A conflict is not the end of the road: the standing rebase is handed
3452    /// to the fixer seat, at most `graph.review_rounds` times, counted in
3453    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
3454    /// land). Once it finishes, review and the gate run as usual on the
3455    /// rebased tree, which is where a breakage the new base caused is caught
3456    /// by the ordinary gate-fix round. magi resolves nothing itself.
3457    ///
3458    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
3459    /// `state.base_sync.attempts`, is how many times the base is *rebased
3460    /// onto* (a base that keeps moving); `rebase_fixes` is how many times a
3461    /// *conflict* was given to a fixer. When the fixer cannot finish the
3462    /// rebase the branch is restored, `state.base_sync.conflict` is set with
3463    /// what was tried (rounds spent, paths still conflicted) and the branch
3464    /// and worktree stay exactly as they were - untouched, for a person to
3465    /// look at - which is also what makes re-entering this function
3466    /// afterwards a no-op instead of a second attempt at the same wall. A
3467    /// push failure ends the same way.
3468    async fn sync_to_base(&mut self) -> Result<()> {
3469        if self.state.status == RunStatus::AlreadyInBase {
3470            return Ok(());
3471        }
3472        let conflicted = self
3473            .state
3474            .base_sync
3475            .as_ref()
3476            .is_some_and(|s| s.conflict.is_some());
3477        let Some(winner) = self.state.winner().cloned() else {
3478            return Ok(());
3479        };
3480
3481        let repo = self.state.repo.clone();
3482        let remote = self.state.config.merge.remote.clone();
3483        let base_branch = self.state.base_branch.clone();
3484        let tracking = format!("{remote}/{base_branch}");
3485
3486        git::fetch(&repo, &remote, &base_branch).await.ok();
3487        // No network, or the remote never had this branch: `resolve_base`
3488        // already treats that as non-fatal at branch time, and a run that got
3489        // this far must not be blocked by it here either.
3490        let Ok(tip) = git::rev_parse(&repo, &tracking).await else {
3491            return Ok(());
3492        };
3493
3494        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3495        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
3496        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
3497
3498        // Before any rebase, and before a recorded conflict is honoured: a
3499        // branch whose change reached the base under other commit ids has
3500        // nothing to rebase and nothing to conflict with, and a run that
3501        // already stopped on that phantom conflict recovers here on resume.
3502        // `behind == 0` with head == tip is a branch the base has since taken
3503        // in whole, whether or not a conflict was ever recorded: the ancestry
3504        // proof must still run (`classify` ignores a head still on the start
3505        // commit).
3506        if (behind > 0 || conflicted || head == tip)
3507            && self
3508                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
3509                .await?
3510        {
3511            return Ok(());
3512        }
3513        if conflicted {
3514            return Ok(());
3515        }
3516
3517        if behind == 0 {
3518            // A fixer-finished rebase moves the branch ref before the
3519            // winner's worktree is told (`sync_to_head` below). A run that
3520            // died in between resumes here with `behind == 0` and a tree still
3521            // holding the pre-rebase files, which review and the gate would
3522            // then read. That state is exactly: HEAD moved off the tip the
3523            // rebase started from, yet the tree is still identical to that
3524            // tip. A tree with edits of its own differs from it, so nothing
3525            // is thrown away.
3526            if let Some(from) = self
3527                .state
3528                .rebase_fixes
3529                .iter()
3530                .rev()
3531                .find_map(|r| r.from.clone())
3532                && from != head
3533                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
3534                    .await
3535                    .is_ok_and(|o| o.ok())
3536            {
3537                git::sync_to_head(&winner.worktree).await?;
3538            }
3539            // An earlier attempt may have rebased the branch locally and died
3540            // before pushing it (only the fresh-rebase arm below pushes).
3541            // Publish it now, so the plain push at PR time is not refused as
3542            // a non-fast-forward. A run already holding a recorded conflict
3543            // never reaches here; that case is out of scope.
3544            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
3545            if let Some(why) = &conflict {
3546                self.state.status = RunStatus::Blocked;
3547                self.state.event("land", why.clone());
3548            }
3549            self.state.base_sync = Some(BaseSync {
3550                tip,
3551                behind: 0,
3552                attempts,
3553                conflict,
3554                already_in: None,
3555            });
3556            self.state.save()?;
3557            return Ok(());
3558        }
3559
3560        if attempts >= BASE_SYNC_ROUNDS {
3561            let why = format!(
3562                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
3563                 rebase(s); rebasing again would only race it",
3564                winner.branch
3565            );
3566            self.state.status = RunStatus::Blocked;
3567            self.state.base_sync = Some(BaseSync {
3568                tip,
3569                behind,
3570                attempts,
3571                conflict: Some(why.clone()),
3572                already_in: None,
3573            });
3574            self.state.event("land", why);
3575            self.state.save()?;
3576            return Ok(());
3577        }
3578
3579        self.state.event(
3580            "land",
3581            format!(
3582                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
3583                winner.branch
3584            ),
3585        );
3586        self.state.save()?;
3587
3588        // The remote's copy of the branch, read now and only if the fetch
3589        // really succeeded (a stale tracking ref must never pin a lease). It is
3590        // pushed over after a rebase only when it is a commit this branch
3591        // already contains, by ancestry or by patch (an earlier rebase of ours
3592        // that never reached the remote): anything else is somebody else's work.
3593        let branch_tracking = format!("{remote}/{}", winner.branch);
3594        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
3595        let remote_tip = if matches!(&fetched_branch, Ok(o) if o.ok()) {
3596            git::rev_parse(&repo, &branch_tracking).await.ok()
3597        } else {
3598            None
3599        };
3600        // A remote tip this branch does not contain is somebody else's work:
3601        // rebasing would leave a local tip that can never be pushed. Stop
3602        // before touching anything and say so.
3603        if let Some(theirs) = &remote_tip
3604            && !git::is_ancestor(&repo, theirs, &head).await
3605            && !crate::reconcile::origin_missing(&repo, &head, theirs)
3606                .await
3607                .is_ok_and(|missing| missing.is_empty())
3608        {
3609            let why = format!(
3610                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
3611                 them",
3612                short(theirs),
3613                winner.branch
3614            );
3615            self.state.status = RunStatus::Blocked;
3616            self.state.base_sync = Some(BaseSync {
3617                tip,
3618                behind,
3619                attempts,
3620                conflict: Some(why.clone()),
3621                already_in: None,
3622            });
3623            self.state.event("land", why);
3624            self.state.save()?;
3625            return Ok(());
3626        }
3627
3628        let scratch = self.state.dir().join("base-sync");
3629        let rebased = match crate::rebase::rebase_with_fixer(
3630            &mut self.state,
3631            &scratch,
3632            &winner.branch,
3633            &tracking,
3634        )
3635        .await
3636        {
3637            Ok(crate::rebase::Rebased::Applied) => Ok(None),
3638            Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
3639            Err(e) => Err(e),
3640        };
3641        let attempts = attempts + 1;
3642        match rebased {
3643            Ok(None) => {
3644                // The branch ref moved, but a worktree that already had it
3645                // checked out (the winner's) was not told; sync its index and
3646                // files before anything reads them.
3647                git::sync_to_head(&winner.worktree).await?;
3648                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
3649                let mut conflict = None;
3650                if let Some(pinned) = &remote_tip {
3651                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
3652                    match pushed {
3653                        Ok(o) if o.ok() => self.state.event(
3654                            "land",
3655                            format!("pushed rebased {} to {remote}", winner.branch),
3656                        ),
3657                        Ok(o) => {
3658                            conflict = Some(format!(
3659                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
3660                                winner.branch,
3661                                short(pinned),
3662                                o.stderr.chars().take(600).collect::<String>()
3663                            ));
3664                        }
3665                        Err(e) => {
3666                            conflict = Some(format!(
3667                                "rebased {} locally but could not push it: {e:#}",
3668                                winner.branch
3669                            ));
3670                        }
3671                    }
3672                }
3673                if let Some(why) = &conflict {
3674                    self.state.status = RunStatus::Blocked;
3675                    self.state.event("land", why.clone());
3676                }
3677                self.state.base_sync = Some(BaseSync {
3678                    tip: tip.clone(),
3679                    behind: 0,
3680                    attempts,
3681                    conflict,
3682                    already_in: None,
3683                });
3684                self.state
3685                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
3686            }
3687            Ok(Some(conflict)) => {
3688                let why = format!(
3689                    "{} conflicts with {tracking} and did not rebase: {}",
3690                    winner.branch,
3691                    conflict.chars().take(600).collect::<String>()
3692                );
3693                self.state.status = RunStatus::Blocked;
3694                self.state.base_sync = Some(BaseSync {
3695                    tip,
3696                    behind,
3697                    attempts,
3698                    conflict: Some(why.clone()),
3699                    already_in: None,
3700                });
3701                self.state.event("land", why);
3702            }
3703            Err(e) => {
3704                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
3705                self.state.status = RunStatus::Blocked;
3706                self.state.base_sync = Some(BaseSync {
3707                    tip,
3708                    behind,
3709                    attempts,
3710                    conflict: Some(why.clone()),
3711                    already_in: None,
3712                });
3713                self.state.event("land", why);
3714            }
3715        }
3716        self.state.save()?;
3717        Ok(())
3718    }
3719
3720    /// Push a branch an earlier attempt rebased locally but never published,
3721    /// pinned to the remote tip read right after a successful fetch. Returns
3722    /// the reason when the run must stop; `None` when there was nothing to do
3723    /// (no remote copy, the same tip, or a remote copy this branch already
3724    /// contains, which the PR-time push fast-forwards) or the push succeeded.
3725    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
3726        let repo = self.state.repo.clone();
3727        let remote = self.state.config.merge.remote.clone();
3728        let fetched = git::fetch(&repo, &remote, branch).await;
3729        if !matches!(&fetched, Ok(o) if o.ok()) {
3730            return None;
3731        }
3732        let branch_tracking = format!("{remote}/{branch}");
3733        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
3734        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
3735            return None;
3736        }
3737        if !crate::reconcile::origin_missing(&repo, head, &theirs)
3738            .await
3739            .is_ok_and(|missing| missing.is_empty())
3740        {
3741            return Some(format!(
3742                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
3743                 them",
3744                short(&theirs)
3745            ));
3746        }
3747        match git::push_pinned(&repo, &remote, branch, &theirs).await {
3748            Ok(o) if o.ok() => {
3749                self.state
3750                    .event("land", format!("pushed rebased {branch} to {remote}"));
3751                None
3752            }
3753            Ok(o) => Some(format!(
3754                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
3755                 someone may have pushed): {}",
3756                short(&theirs),
3757                o.stderr.chars().take(600).collect::<String>()
3758            )),
3759            Err(e) => Some(format!(
3760                "{branch} is rebased locally but could not be pushed: {e:#}"
3761            )),
3762        }
3763    }
3764
3765    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
3766    /// is already on `tip` under other commit ids ([`crate::already`]); returns
3767    /// whether it did.
3768    ///
3769    /// Checked only when the base is ahead of the branch. A failing check is
3770    /// "not proven" - the ordinary rebase path then decides - never a reason to
3771    /// stop the run.
3772    ///
3773    /// The remote copy of the branch is held to the same standard as the local
3774    /// one: if it carries a tip this worktree does not, that tip must itself be
3775    /// proven in the base, or nothing is settled (a pull request would
3776    /// otherwise be closed over commits nobody checked). The pull request is
3777    /// closed *before* the terminal status is saved; if that fails for a
3778    /// reason other than a refusal (no network, a `gh` error) the run is left
3779    /// `Blocked` with the reason as its conflict, which a resume retries -
3780    /// the same recovery a phantom conflict gets.
3781    async fn settle_already_in(
3782        &mut self,
3783        branch: &str,
3784        tip: &str,
3785        head: &str,
3786        attempts: usize,
3787        behind: usize,
3788    ) -> Result<bool> {
3789        let repo = self.state.repo.clone();
3790        let remote = self.state.config.merge.remote.clone();
3791        let start = self.state.base_commit.clone();
3792        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
3793            Ok(Some(e)) => e,
3794            Ok(None) => return Ok(false),
3795            Err(e) => {
3796                tracing::warn!("already-in-base check for {branch}: {e:#}");
3797                return Ok(false);
3798            }
3799        };
3800        let mut verified = vec![head.to_owned()];
3801        let fetched = git::fetch(&repo, &remote, branch).await;
3802        if matches!(&fetched, Ok(o) if o.ok())
3803            && let Ok(theirs) = git::rev_parse(&repo, &format!("{remote}/{branch}")).await
3804            && theirs != head
3805        {
3806            match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
3807                Ok(Some(_)) => verified.push(theirs),
3808                _ => return Ok(false),
3809            }
3810        }
3811        let base_branch = self.state.base_branch.clone();
3812        let message = format!(
3813            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
3814             land",
3815            evidence.names(),
3816            evidence.proof.as_str()
3817        );
3818        let closed =
3819            crate::land::close_superseded_pr(&mut self.state, branch, &evidence, &verified).await;
3820        match closed {
3821            Ok(Ok(url)) => self
3822                .state
3823                .event("land", format!("closed {url}: superseded on {base_branch}")),
3824            Ok(Err(why)) => self
3825                .state
3826                .event("land", format!("did not close a pull request: {why}")),
3827            Err(e) => {
3828                let why = format!(
3829                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
3830                     not be closed ({e:#}); resume to retry"
3831                );
3832                self.state.status = RunStatus::Blocked;
3833                self.state.base_sync = Some(BaseSync {
3834                    tip: tip.to_owned(),
3835                    behind,
3836                    attempts,
3837                    conflict: Some(why.clone()),
3838                    already_in: None,
3839                });
3840                self.state.event("land", why);
3841                self.state.save()?;
3842                return Ok(true);
3843            }
3844        }
3845        self.state.status = RunStatus::AlreadyInBase;
3846        self.state.base_sync = Some(BaseSync {
3847            tip: tip.to_owned(),
3848            behind,
3849            attempts,
3850            conflict: None,
3851            already_in: Some(evidence),
3852        });
3853        self.state.event("land", message);
3854        self.state.save()?;
3855        self.settle_questions();
3856        Ok(true)
3857    }
3858
3859    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
3860    /// last landed the winner on, once it has run, else the commit the run
3861    /// branched from.
3862    ///
3863    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
3864    /// and `vote` all happen before there is a winner to rebase, so they
3865    /// compare every candidate against the branch point on purpose, and a
3866    /// base that moves after they are already done cannot change an answer
3867    /// they already gave.
3868    fn landing_base(&self) -> String {
3869        self.state
3870            .base_sync
3871            .as_ref()
3872            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
3873    }
3874
3875    // ------------------------------------------------------- operator fix
3876
3877    /// Route specific, already-recorded review findings to a fixer for a
3878    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
3879    /// entry point.
3880    ///
3881    /// Distinct from `review_loop`'s own fix step in three ways: it never
3882    /// runs a reviewer wave, it never spends review-round budget, and what
3883    /// happened is recorded as an [`OperatorFixRequest`] appended to
3884    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
3885    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
3886    /// and vote must never be rewritten to look like a manufactured blocking
3887    /// verdict.
3888    ///
3889    /// Only meaningful once review has actually concluded: `Ready` (handed
3890    /// off with findings still open, or simply concluded clean while minor
3891    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
3892    /// gate failed). Everything else is refused: a run still in progress
3893    /// should simply be resumed, and a `Merged` run's branch has already
3894    /// landed — reopening *this* run's own record cannot change that, so the
3895    /// answer there is a fresh `magi review <branch>`.
3896    ///
3897    /// A real commit here re-verifies through a fresh, ordinary review-only
3898    /// run on the same branch ([`Self::review`]) rather than reopening this
3899    /// run's own `review_loop`: once any round in this run's history went
3900    /// clean, `review_conclusion` treats that as permanent by design (the
3901    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
3902    /// way to force one more genuine reviewer wave out of *this* run without
3903    /// either rewriting history or weakening that guarantee for every other
3904    /// caller. A review-only run costs nothing extra — no implementation, no
3905    /// judging, no vote — and exercises the exact same review → verify →
3906    /// gate → (human) merge path, unmodified.
3907    pub async fn fix_selected(
3908        &mut self,
3909        ids: &[String],
3910        reason: &str,
3911        allow_stale: bool,
3912    ) -> Result<()> {
3913        let reason = reason.trim();
3914        if reason.is_empty() {
3915            bail!("a fix request needs a reason — that is the operator's own record of why");
3916        }
3917        if ids.is_empty() {
3918            bail!("no finding id given");
3919        }
3920        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
3921            bail!(
3922                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
3923                 has already concluded — can be given a targeted fix. A run still \
3924                 in progress should simply be resumed; a `merged` run's branch has \
3925                 already landed, so its answer is a fresh `magi review <branch>`, \
3926                 not reopening this run's own record",
3927                self.state.id,
3928                self.state.status.as_str()
3929            );
3930        }
3931        let Some(winner) = self.state.winner().cloned() else {
3932            bail!("run {} has no winning candidate to fix", self.state.id);
3933        };
3934        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
3935            bail!(
3936                "branch `{}` no longer exists; this run cannot be extended",
3937                winner.branch
3938            );
3939        }
3940        let home = crate::run::home();
3941        if crate::daemon::is_working_on(&home, &self.state.id, Timestamp::now()) {
3942            bail!(
3943                "run {} is currently being worked on by another magi process",
3944                self.state.id
3945            );
3946        }
3947        // Held for the rest of this call, including the follow-up review
3948        // below: two `magi fix` invocations against the same run must not
3949        // both reach the worktree manipulation further down, which would
3950        // otherwise race to remove and recreate the same directory — see
3951        // [`FixClaim`]'s own doc.
3952        let _claim = FixClaim::acquire(&self.state.dir())?;
3953
3954        // Resolve every id before spending anything — an unknown id refuses
3955        // the whole request rather than silently dropping it — and dedup
3956        // while keeping the operator's own order.
3957        let mut seen = BTreeSet::new();
3958        let mut findings = Vec::new();
3959        let mut missing = Vec::new();
3960        for id in ids {
3961            if !seen.insert(id.clone()) {
3962                continue;
3963            }
3964            match self.state.finding(id) {
3965                Some((round, rec, f)) => findings.push(OperatorFixFinding {
3966                    id: f.id.clone(),
3967                    severity: f.severity,
3968                    reviewer_vote: rec.vote,
3969                    round: round.round,
3970                    round_head: round.head.clone(),
3971                    reviewer: rec.reviewer,
3972                    agent: rec.agent.clone(),
3973                    file: f.file.clone(),
3974                    line: f.line,
3975                    title: f.title.clone(),
3976                    detail: f.detail.clone(),
3977                    outcome: OperatorFixOutcome::Pending,
3978                }),
3979                None => missing.push(id.clone()),
3980            }
3981        }
3982        if !missing.is_empty() {
3983            bail!(
3984                "unknown finding id(s): {}; nothing was changed",
3985                missing.join(", ")
3986            );
3987        }
3988
3989        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
3990        let stale_details: Vec<(String, String)> = findings
3991            .iter()
3992            .filter(|f| f.round_head != head_at_request)
3993            .map(|f| (f.id.clone(), f.round_head.clone()))
3994            .collect();
3995        let stale = !stale_details.is_empty();
3996        if stale && !allow_stale {
3997            bail!(
3998                "the branch has moved since some finding(s) were raised — {} — now \
3999                 at {}; pass --allow-stale to fix anyway, or re-run review first",
4000                stale_details
4001                    .iter()
4002                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
4003                    .collect::<Vec<_>>()
4004                    .join(", "),
4005                short(&head_at_request)
4006            );
4007        }
4008
4009        let request = OperatorFixRequest {
4010            requested_at: Timestamp::now(),
4011            reason: reason.to_owned(),
4012            findings,
4013            head_at_request: head_at_request.clone(),
4014            allow_stale,
4015            stale,
4016            fix: None,
4017            result_head: None,
4018            follow_up_review_run: None,
4019        };
4020        self.state.event(
4021            "fix",
4022            format!(
4023                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
4024                request.findings.len(),
4025                request
4026                    .findings
4027                    .iter()
4028                    .map(|f| f.id.as_str())
4029                    .collect::<Vec<_>>()
4030                    .join(", "),
4031            ),
4032        );
4033        // Recorded now, before any worktree work or the fixer call itself —
4034        // and re-saved at each checkpoint below: a crash at any point after
4035        // this (mid fixer call, mid follow-up review) must not lose the fact
4036        // that this was requested, for which findings, and why. Everything
4037        // past this point reads and writes through `request_index` rather
4038        // than a local variable, since `request` itself is moved here.
4039        self.state.operator_fixes.push(request);
4040        self.state.save()?;
4041        let request_index = self.state.operator_fixes.len() - 1;
4042
4043        // A fresh, dedicated worktree for this one call, never the winner's
4044        // own worktree in place: that one may already be gone (folded away),
4045        // and reusing it in place would leave the branch checked out there
4046        // when the follow-up review below tries to check it out again. Freed
4047        // immediately after, either way — but only once confirmed clean:
4048        // `worktree_remove` is a `git worktree remove --force`, which would
4049        // otherwise discard uncommitted work left there by the operator or
4050        // another process before this had a chance to even look at it.
4051        if winner.worktree.exists() {
4052            // Lockfiles a rescue commit withheld stay untracked on purpose and
4053            // are already recorded; they are not the operator's work to protect.
4054            let dirty = git::git(
4055                &winner.worktree,
4056                &["status", "--porcelain", "--untracked-files=all"],
4057            )
4058            .await?;
4059            let only_withheld = dirty.lines().all(|l| {
4060                l.strip_prefix("?? ")
4061                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
4062            });
4063            if !only_withheld {
4064                bail!(
4065                    "`{}` has uncommitted changes; refusing to touch it — commit or \
4066                     discard them first",
4067                    winner.worktree.display()
4068                );
4069            }
4070            git::worktree_remove(&self.state.repo, &winner.worktree)
4071                .await
4072                .ok();
4073        }
4074        let fix_worktree = self.state.worktree_root().join("operator-fix");
4075        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
4076        git::git(
4077            &self.state.repo,
4078            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
4079        )
4080        .await
4081        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
4082        if !git::is_clean(&fix_worktree).await? {
4083            git::worktree_remove(&self.state.repo, &fix_worktree)
4084                .await
4085                .ok();
4086            bail!(
4087                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
4088                winner.branch
4089            );
4090        }
4091
4092        let run_id = self.state.id.clone();
4093        let prompts = self.state.config.prompts.clone();
4094        let language = self.state.config.graph.language.clone();
4095        let sessions = self.state.config.graph.sessions;
4096        let artifacts = agent::artifacts_dir(&self.state.dir());
4097        let (fix_spec, fix_seat_key) = match &self.roles.fixer {
4098            Some(f) if f.id != winner.agent => (f.clone(), "fix".to_owned()),
4099            _ => (
4100                self.state
4101                    .config
4102                    .agent(&winner.agent)
4103                    .cloned()
4104                    .unwrap_or_else(|_| self.roles.implementers[winner.index].clone()),
4105                format!("impl-{}", winner.label),
4106            ),
4107        };
4108        let seat = self.seat(&fix_seat_key, &fix_spec.id);
4109        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
4110            .findings
4111            .iter()
4112            .map(|f| Finding {
4113                id: f.id.clone(),
4114                severity: f.severity,
4115                file: f.file.clone(),
4116                line: f.line,
4117                title: f.title.clone(),
4118                detail: f.detail.clone(),
4119            })
4120            .collect();
4121        let job = SeatJob {
4122            prompt: prompt::operator_fix(
4123                &self.state.instruction,
4124                &finding_list,
4125                reason,
4126                &stale_details,
4127                &head_at_request,
4128                &language,
4129            ),
4130            spec: fix_spec.clone(),
4131            seat,
4132            cwd: fix_worktree.clone(),
4133            timeout: Duration::from_secs(self.state.config.graph.timeout_fix),
4134            allow_write: true,
4135            sessions,
4136            artifacts: artifacts.clone(),
4137            stem: "operator-fix".to_owned(),
4138            handover: None,
4139        };
4140        let cache = self.state.config.cache_dir();
4141        let ctx = WaveCtx {
4142            carry_seats: false,
4143            run: &run_id,
4144            node: "fix",
4145            prompts: &prompts,
4146            cache: cache.as_deref(),
4147            round: None,
4148        };
4149        let (seat, out) =
4150            run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
4151        let agent_id = seat.agent.clone();
4152
4153        let mut fix = FixRecord {
4154            agent: agent_id,
4155            addressed: Vec::new(),
4156            rejected: Vec::new(),
4157            notes: String::new(),
4158            committed: false,
4159            failed: None,
4160            duration_ms: 0,
4161            continuation: None,
4162        };
4163        let mut final_seat = seat.clone();
4164        match out {
4165            AgentOutcome::Ok(o) => {
4166                fix.duration_ms = o.duration_ms;
4167                let parsed = verdict::extract_json::<FixReport>(&o.text);
4168                let incomplete_reason = match &parsed {
4169                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
4170                        "the reply parsed, but it reported a command whose own CLI \
4171                         never confirmed an exit status"
4172                            .to_owned(),
4173                    ),
4174                    Ok(_) => None,
4175                    Err(e) => Some(e.to_string()),
4176                };
4177                match incomplete_reason {
4178                    None => {
4179                        let report = parsed.expect("checked Ok above");
4180                        fix.addressed = report.addressed;
4181                        fix.rejected = report.rejected;
4182                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
4183                    }
4184                    Some(reason) => {
4185                        let (resumed_seat, resolved, failure, cont) = self
4186                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
4187                            .await;
4188                        fix.duration_ms += cont.cumulative_wait_ms;
4189                        fix.continuation = Some(cont);
4190                        final_seat = resumed_seat;
4191                        match resolved {
4192                            Some(report) => {
4193                                fix.addressed = report.addressed;
4194                                fix.rejected = report.rejected;
4195                                fix.notes =
4196                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
4197                            }
4198                            None => fix.failed = failure,
4199                        }
4200                    }
4201                }
4202            }
4203            AgentOutcome::Dropped(o) => {
4204                fix.duration_ms = o.duration_ms;
4205                let why = o
4206                    .dropped
4207                    .as_ref()
4208                    .map(|d| d.why.as_str())
4209                    .unwrap_or("the CLI ended the stream without delivering its answer");
4210                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
4211            }
4212            AgentOutcome::Quota(o) => {
4213                self.state.quota.push(QuotaLoss {
4214                    seat: final_seat.key.clone(),
4215                    node: "fix".to_owned(),
4216                    at: Timestamp::now(),
4217                    reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
4218                });
4219                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
4220            }
4221            AgentOutcome::Failed(e) => fix.failed = Some(e),
4222        }
4223        if fix.continuation.is_none() {
4224            fix.continuation = Some(ContinuationRecord::not_needed());
4225        }
4226        self.state.seats.insert(final_seat.key.clone(), final_seat);
4227
4228        let rescue_message = format!(
4229            "magi: operator-selected fix ({}) (uncommitted work)",
4230            self.state.operator_fixes[request_index]
4231                .findings
4232                .iter()
4233                .map(|f| f.id.as_str())
4234                .collect::<Vec<_>>()
4235                .join(", ")
4236        );
4237        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
4238            self.state.note_withheld("fix", &r.withheld);
4239        }
4240        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
4241        fix.committed = after != head_at_request;
4242        git::worktree_remove(&self.state.repo, &fix_worktree)
4243            .await
4244            .ok();
4245
4246        self.state.event(
4247            "fix",
4248            match &fix.failed {
4249                Some(reason) => format!(
4250                    "operator fix: adoption report was lost ({reason}); {}",
4251                    if fix.committed {
4252                        "committed"
4253                    } else {
4254                        "NO new commit"
4255                    }
4256                ),
4257                None => format!(
4258                    "operator fix: {} addressed, {} rejected, {}",
4259                    fix.addressed.len(),
4260                    fix.rejected.len(),
4261                    if fix.committed {
4262                        "committed"
4263                    } else {
4264                        "NO new commit"
4265                    }
4266                ),
4267            },
4268        );
4269
4270        // Every selected finding gets an outcome — never left `Pending` once
4271        // the fixer's own turn is over. A report that never came back at all
4272        // marks every one of them `Unreported`, not silently "not addressed":
4273        // quota, a dropped stream, or an exhausted continuation are gaps in
4274        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
4275        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
4276        for f in &mut self.state.operator_fixes[request_index].findings {
4277            f.outcome = if fix.failed.is_some() {
4278                OperatorFixOutcome::Unreported
4279            } else if fix.addressed.contains(&f.id) {
4280                OperatorFixOutcome::Addressed
4281            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
4282                OperatorFixOutcome::Rejected { why: r.why.clone() }
4283            } else {
4284                OperatorFixOutcome::Unreported
4285            };
4286        }
4287
4288        let committed = fix.committed;
4289        if committed {
4290            self.state.operator_fixes[request_index].result_head = Some(after.clone());
4291        }
4292        self.state.operator_fixes[request_index].fix = Some(fix);
4293        // Saved again now that the fixer's own outcome is final, on top of
4294        // the save right after the request was first pushed above.
4295        self.state.save()?;
4296
4297        if committed {
4298            self.state.event(
4299                "fix",
4300                format!(
4301                    "operator fix committed {}; opening a follow-up review-only run",
4302                    short(&after)
4303                ),
4304            );
4305            // The operator asked for the fix, and the follow-up serves whatever
4306            // task the run it follows served.
4307            let origin =
4308                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
4309            match Self::review(
4310                &self.state.repo,
4311                &winner.branch,
4312                self.state.config.clone(),
4313                origin,
4314            )
4315            .await
4316            {
4317                Ok(mut follow_up) => {
4318                    follow_up.state.event(
4319                        "start",
4320                        format!(
4321                            "requested by an operator fix on run {} for finding(s) {}",
4322                            self.state.id,
4323                            self.state.operator_fixes[request_index]
4324                                .findings
4325                                .iter()
4326                                .map(|f| f.id.as_str())
4327                                .collect::<Vec<_>>()
4328                                .join(", "),
4329                        ),
4330                    );
4331                    follow_up.state.save()?;
4332                    let follow_up_id = follow_up.state.id.clone();
4333                    // The follow-up is a run like any other: it belongs to the
4334                    // task of the run it follows, or to one filed for it.
4335                    let adopted = crate::direct::adopt(
4336                        &follow_up.state,
4337                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
4338                    );
4339                    let executed = follow_up.execute().await;
4340                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
4341                    if let Some(a) = adopted {
4342                        a.finish(&follow_up.state, executed);
4343                    }
4344                    if let Some(e) = failure {
4345                        self.state.event(
4346                            "fix",
4347                            format!(
4348                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
4349                            ),
4350                        );
4351                    }
4352                    self.state.operator_fixes[request_index].follow_up_review_run =
4353                        Some(follow_up_id);
4354                }
4355                Err(e) => {
4356                    self.state.event(
4357                        "fix",
4358                        format!("committed the fix but could not open a follow-up review: {e:#}"),
4359                    );
4360                }
4361            }
4362            self.state.save()?;
4363        }
4364
4365        Ok(())
4366    }
4367
4368    // --------------------------------------------------------------- review
4369
4370    /// The agent and seat key that fix the winner's tree: the configured
4371    /// fixer, else the winner's own implementer seat, whose conversation
4372    /// continues now that the competition is over. Shared by the review loop
4373    /// and the gate-fix round so both talk to the same seat.
4374    fn fixer_spec(&self, winner: &Candidate) -> (AgentSpec, String) {
4375        match &self.roles.fixer {
4376            Some(f) if f.id != winner.agent => (f.clone(), "fix".to_owned()),
4377            _ => (
4378                self.state
4379                    .config
4380                    .agent(&winner.agent)
4381                    .cloned()
4382                    .unwrap_or_else(|_| self.roles.implementers[winner.index].clone()),
4383                format!("impl-{}", winner.label),
4384            ),
4385        }
4386    }
4387
4388    async fn review_loop(&mut self) -> Result<()> {
4389        // A base that would not rebase is a person's decision, not a review
4390        // round: nothing here would change the answer, and reviewers and a
4391        // fixer would be spending real budget on a tree that cannot land
4392        // regardless of what they find.
4393        if self
4394            .state
4395            .base_sync
4396            .as_ref()
4397            .is_some_and(|s| s.conflict.is_some())
4398        {
4399            return Ok(());
4400        }
4401        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4402        // agent files with `magi task add` name the run that paid for it. The
4403        // prompt overlay is cloned alongside it because the waves borrow it
4404        // while `self` is mutably borrowed by the node's own bookkeeping.
4405        let run_id = self.state.id.clone();
4406        let prompts = self.state.config.prompts.clone();
4407        let Some(winner) = self.state.winner().cloned() else {
4408            return Ok(());
4409        };
4410        let max_rounds = self.state.config.graph.review_rounds;
4411        // A clean round, an exhausted round budget, or a stalled tree (see
4412        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
4413        // they are recorded — recomputed here, not read off `status`, so a
4414        // reentry into a run that already stopped restates the identical
4415        // verdict instead of silently handing back whatever an earlier node
4416        // in this same walk clobbered `status` to (a solo-candidate
4417        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
4418        // below runs an empty range once the budget is spent, and would
4419        // otherwise fall through without touching `status` at all.
4420        if let Some(status) = review_conclusion(&self.state.reviews, max_rounds) {
4421            // A reentry after a crash between the last round's save and
4422            // `stop_reviewing` reaches the hand-off here, not there.
4423            if status == RunStatus::Gating {
4424                self.record_contested_handoff();
4425            }
4426            self.state.status = status;
4427            self.state.save()?;
4428            return Ok(());
4429        }
4430        self.state.status = RunStatus::Reviewing;
4431        // A last recorded round whose own verification never resolved
4432        // (`ResourceBlocked` — the shared build cache, not the patch) is
4433        // never a concluded round, whatever the round budget says: starting
4434        // a fresh round on top of it would spend a whole new reviewer wave
4435        // re-reading an unchanged patch instead of just retrying the one
4436        // check that actually needs it, and once the budget is spent the
4437        // loop below has nothing left to do at all (its range is empty).
4438        // Retry that check directly instead, exactly the same retry
4439        // `stop_reviewing` already does for its own catch-up case.
4440        if self
4441            .state
4442            .reviews
4443            .last()
4444            .is_some_and(|r| r.e2e_status() == E2eStatus::ResourceBlocked)
4445        {
4446            let shell = self.state.config.shell();
4447            return self
4448                .stop_reviewing(
4449                    "the last round's own verification never resolved",
4450                    &shell,
4451                    &winner.worktree,
4452                )
4453                .await;
4454        }
4455
4456        let repo = self.state.repo.clone();
4457        let root = self.state.worktree_root();
4458        let language = self.state.config.graph.language.clone();
4459        let sessions = self.state.config.graph.sessions;
4460        let artifacts = agent::artifacts_dir(&self.state.dir());
4461        let base = self.landing_base();
4462        let base_short = short(&base);
4463        let reviewers = self.roles.reviewers.clone();
4464        let shell = self.state.config.shell();
4465
4466        for round in (self.state.reviews.len() + 1)..=max_rounds {
4467            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4468            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
4469            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
4470            // The prior round's own record, already persisted — never a
4471            // hand-carried variable of just its failing output: that is
4472            // exactly what let a round's e2e result drift out of sync with
4473            // which commit it was actually about (see `SCHEMA`'s doc for
4474            // schema 8). Judged against `head`, the commit reviewers are
4475            // about to look at now, so the summary always reads as "an
4476            // earlier head" here — this round's own patch has not been
4477            // checked yet.
4478            let prev_verification = self
4479                .state
4480                .reviews
4481                .last()
4482                .and_then(|r| r.verification_summary(&head));
4483
4484            // Each reviewer gets its own detached checkout of exactly this
4485            // commit: nobody can perturb the winner's tree, and the fixer can
4486            // keep working without racing a reviewer.
4487            let mut jobs = Vec::new();
4488            for (r, spec) in reviewers.iter().cloned().enumerate() {
4489                let wt = root.join(format!("review-{}", r + 1));
4490                if wt.exists() {
4491                    git::reset_detached(&wt, &head).await?;
4492                } else {
4493                    git::worktree_add_detached(&repo, &wt, &head).await?;
4494                }
4495                let seat_key = format!("review-{}", r + 1);
4496                // The seat starts the round on whoever answered it last, not
4497                // on the agent the spec names, so a failure is not re-paid.
4498                let spec = pick_start_spec(
4499                    &self.roles.reviewer_roster,
4500                    spec,
4501                    self.state.seat_history.get(&seat_key),
4502                );
4503                let seat = self.seat(&seat_key, &spec.id);
4504                jobs.push(SeatJob {
4505                    prompt: prompt::review(&prompt::ReviewCtx {
4506                        instruction: &self.state.instruction,
4507                        branch: &winner.branch,
4508                        base_short: &base_short,
4509                        stat: &stat,
4510                        patch: &patch,
4511                        verification: prev_verification.as_ref(),
4512                        reviewers: reviewers.len(),
4513                        round,
4514                        rounds: max_rounds,
4515                        // A review-only run has no rankings, so nothing
4516                        // competed for this patch and the reviewer is told so.
4517                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
4518                        lens: Lens::for_seat(r),
4519                        language: &language,
4520                    }),
4521                    spec,
4522                    seat,
4523                    cwd: wt,
4524                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
4525                    allow_write: false,
4526                    sessions,
4527                    artifacts: artifacts.clone(),
4528                    stem: format!("review-{round}-{}", r + 1),
4529                    handover: None,
4530                });
4531            }
4532
4533            self.state.event(
4534                "review",
4535                format!(
4536                    "round {round}: {} reviewers on {}",
4537                    jobs.len(),
4538                    short(&head)
4539                ),
4540            );
4541            let mut quota_losses = Vec::new();
4542            let review_retries = self.state.config.graph.retries;
4543            let review_cache = self.state.config.cache_dir();
4544            let ctx = WaveCtx {
4545                carry_seats: true,
4546                run: &run_id,
4547                node: "review",
4548                prompts: &prompts,
4549                cache: review_cache.as_deref(),
4550                round: Some(round),
4551            };
4552            let results = ask_json_wave::<Review>(
4553                jobs,
4554                Arc::clone(&self.sem),
4555                review_retries,
4556                &self.roles.reviewer_roster,
4557                &ctx,
4558                &mut quota_losses,
4559                &mut self.state,
4560                &|_: &Review| Ok(()),
4561            )
4562            .await;
4563            // Counted before the move below: how many of *this* round's
4564            // reviewer seats were lost to their own rate limit, as opposed to
4565            // a crash, a timeout, or unparsable output — see `round_is_clean`.
4566            let round_quota_missing = quota_losses.len();
4567            self.state.quota.extend(quota_losses);
4568
4569            let mut records = Vec::new();
4570            let mut all_findings = Vec::new();
4571            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
4572                let agent_id = seat.agent.clone();
4573                self.state.seats.insert(seat.key.clone(), seat);
4574                let mut record = ReviewRecord {
4575                    reviewer: r + 1,
4576                    agent: agent_id,
4577                    summary: String::new(),
4578                    findings: Vec::new(),
4579                    vote: None,
4580                    failed: None,
4581                    duration_ms: 0,
4582                    // Set for both outcomes: `failed: Some(_)` with
4583                    // `attempts > 0` is a seat every retry still lost, not a
4584                    // recovered one — only `failed: None` with `attempts > 0`
4585                    // reads as "answered after a nudge" (see this field's own
4586                    // doc).
4587                    attempts,
4588                };
4589                match res {
4590                    Ok((review, out)) => {
4591                        // Sanitized here, at the point every other piece of
4592                        // agent prose in this file is (candidate summaries,
4593                        // deliberation turns, vote reasons): a reviewer's own
4594                        // words are the one thing about it that could name
4595                        // it, and reconsideration below broadcasts this same
4596                        // summary and these same findings to every other
4597                        // seat on the panel.
4598                        record.summary =
4599                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
4600                        record.vote = Some(review.vote);
4601                        record.duration_ms = out.duration_ms;
4602                        for (n, mut f) in review.findings.into_iter().enumerate() {
4603                            // ids are magi's, never the agent's: the fixer's
4604                            // adoption report is keyed by them.
4605                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
4606                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
4607                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
4608                            // `file` is agent-supplied prose too, never
4609                            // checked against the real tree — the same
4610                            // exposure `title`/`detail` above have, just in
4611                            // a field easy to forget because it looks like a
4612                            // path rather than free text.
4613                            f.file = f
4614                                .file
4615                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
4616                            all_findings.push(f.clone());
4617                            record.findings.push(f);
4618                        }
4619                        self.state.event(
4620                            "review",
4621                            format!(
4622                                "round {round}: reviewer {} voted {} with {} finding(s)",
4623                                r + 1,
4624                                review.vote.label(),
4625                                record.findings.len()
4626                            ),
4627                        );
4628                    }
4629                    Err(e) => {
4630                        record.failed = Some(e.to_string());
4631                        self.state.event(
4632                            "review",
4633                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
4634                        );
4635                    }
4636                }
4637                records.push(record);
4638            }
4639
4640            // Tally the round's votes and, if they split, spend the one
4641            // round of reconsideration the split -> deliberate -> revote
4642            // shape `judge`/`vote` use for the panel, sized down to what a
4643            // read-only review round can afford: one round, and a revote
4644            // rather than an argument, because the panel already wrote its
4645            // reasoning down as findings the first time around.
4646            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
4647            let vote_split =
4648                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
4649            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
4650            if vote_split {
4651                self.state.event(
4652                    "review",
4653                    format!(
4654                        "round {round}: votes split ({}) — one round of reconsideration",
4655                        initial_votes
4656                            .iter()
4657                            .map(|v| v.label())
4658                            .collect::<Vec<_>>()
4659                            .join(", ")
4660                    ),
4661                );
4662                // Seats read every seat's findings and votes, still numbered
4663                // and never named — the same anonymity `review` itself keeps.
4664                let panel: Vec<ReviewSeatReport<'_>> = records
4665                    .iter()
4666                    .filter_map(|r| {
4667                        r.vote.map(|vote| ReviewSeatReport {
4668                            reviewer: r.reviewer,
4669                            vote,
4670                            summary: &r.summary,
4671                            findings: &r.findings,
4672                        })
4673                    })
4674                    .collect();
4675
4676                let mut jobs = Vec::new();
4677                let mut seats_at = Vec::new();
4678                for (r, spec) in reviewers.iter().cloned().enumerate() {
4679                    // A seat with no initial vote has nothing to reconsider
4680                    // from and stays absent, the same as it stayed absent
4681                    // from `panel` above.
4682                    if records[r].vote.is_none() {
4683                        continue;
4684                    }
4685                    let wt = root.join(format!("review-{}", r + 1));
4686                    let seat_key = format!("review-{}", r + 1);
4687                    let spec = self.occupant(&seat_key, spec);
4688                    let seat = self.seat(&seat_key, &spec.id);
4689                    // A seat with no live session has already forgotten the
4690                    // initial review's prompt — restate the patch it is
4691                    // voting on, the same as `deliberate`/`vote` do for a
4692                    // judge in the same position.
4693                    // The panel already carries this seat's own review and
4694                    // vote, so restating the patch makes the prompt whole for
4695                    // a seat handed to another agent.
4696                    let build = |with_patch: bool| {
4697                        prompt::review_reconsider(&ReviewReconsiderCtx {
4698                            instruction: &self.state.instruction,
4699                            reviewer: r + 1,
4700                            lens: Lens::for_seat(r),
4701                            panel: &panel,
4702                            patch: with_patch.then_some(ReviewPatch {
4703                                branch: &winner.branch,
4704                                base_short: &base_short,
4705                                stat: &stat,
4706                                patch: &patch,
4707                            }),
4708                            round,
4709                            rounds: max_rounds,
4710                            language: &language,
4711                        })
4712                    };
4713                    let full = build(true);
4714                    let prompt = if has_context(&spec, &seat, sessions) {
4715                        build(false)
4716                    } else {
4717                        full.clone()
4718                    };
4719                    jobs.push(SeatJob {
4720                        prompt,
4721                        spec,
4722                        seat,
4723                        cwd: wt,
4724                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
4725                        allow_write: false,
4726                        sessions,
4727                        artifacts: artifacts.clone(),
4728                        stem: format!("review-{round}-reconsider-{}", r + 1),
4729                        handover: Some(full),
4730                    });
4731                    seats_at.push(r);
4732                }
4733
4734                let mut recon_quota_losses = Vec::new();
4735                let recon_cache = self.state.config.cache_dir();
4736                let recon_ctx = WaveCtx {
4737                    carry_seats: true,
4738                    run: &run_id,
4739                    node: "review",
4740                    prompts: &prompts,
4741                    cache: recon_cache.as_deref(),
4742                    round: Some(round),
4743                };
4744                let recon_results = ask_json_wave::<ReviewRevote>(
4745                    jobs,
4746                    Arc::clone(&self.sem),
4747                    review_retries,
4748                    &self.roles.reviewer_roster,
4749                    &recon_ctx,
4750                    &mut recon_quota_losses,
4751                    &mut self.state,
4752                    &|_: &ReviewRevote| Ok(()),
4753                )
4754                .await;
4755                self.state.quota.extend(recon_quota_losses);
4756
4757                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
4758                    let agent_id = seat.agent.clone();
4759                    self.state.seats.insert(seat.key.clone(), seat);
4760                    let mut rec = ReviewRevoteRecord {
4761                        reviewer: r + 1,
4762                        agent: agent_id,
4763                        vote: None,
4764                        reason: String::new(),
4765                        failed: None,
4766                    };
4767                    match res {
4768                        Ok((rv, _)) => {
4769                            rec.vote = Some(rv.vote);
4770                            rec.reason =
4771                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
4772                            self.state.event(
4773                                "review",
4774                                format!(
4775                                    "round {round}: reviewer {} revoted {}",
4776                                    r + 1,
4777                                    rv.vote.label()
4778                                ),
4779                            );
4780                        }
4781                        Err(e) => {
4782                            rec.failed = Some(e.to_string());
4783                            self.state.event(
4784                                "review",
4785                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
4786                            );
4787                        }
4788                    }
4789                    reconsideration.push(rec);
4790                }
4791            } else if initial_votes.len() > 1 {
4792                self.state.event(
4793                    "review",
4794                    format!(
4795                        "round {round}: votes agreed ({}) — no reconsideration",
4796                        initial_votes[0].label()
4797                    ),
4798                );
4799            }
4800
4801            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
4802            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
4803            // A round that already has a blocking finding and a round left to
4804            // try is going back to the fixer no matter what `verify.e2e`
4805            // says, so running it first only spends the loop's slowest step
4806            // (minutes, for a Rust repo's full test suite) on a head about
4807            // to be rewritten. Deferred, never skipped: `verify.e2e` still
4808            // runs once a round has no blocking findings left (see
4809            // `round_is_clean`, which a deferred — empty — `e2e` can never
4810            // satisfy since `blocking` is nonzero whenever this branch is
4811            // taken), and `stop_reviewing` forces a real run before it will
4812            // ever read a deferred round as green.
4813            let defer_e2e =
4814                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
4815            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
4816                let reason =
4817                    format!("{blocking} blocking finding(s) already required a fix this round");
4818                self.state.event(
4819                    "verify",
4820                    format!(
4821                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
4822                         {}); it will run once a round has none left",
4823                        short(&head)
4824                    ),
4825                );
4826                (Vec::new(), false, true, Some(reason))
4827            } else {
4828                let e2e_commands = self.state.config.verify.e2e.clone();
4829                let cache_dir = self.state.config.cache_dir();
4830                let context = format!("round {round}");
4831                let (e2e, verify_retried) = with_cache_lease(
4832                    &mut self.state,
4833                    cache_dir.as_deref(),
4834                    "e2e",
4835                    "e2e",
4836                    &winner.worktree,
4837                    &head,
4838                    verify_timeout,
4839                    &context,
4840                    |state, budget| {
4841                        let shell = shell.clone();
4842                        let e2e_commands = e2e_commands.clone();
4843                        let worktree = winner.worktree.clone();
4844                        let context = context.clone();
4845                        async move {
4846                            run_e2e_with_retry(
4847                                state,
4848                                &shell,
4849                                &e2e_commands,
4850                                &worktree,
4851                                budget,
4852                                &context,
4853                            )
4854                            .await
4855                        }
4856                    },
4857                )
4858                .await;
4859                (e2e, verify_retried, false, None)
4860            };
4861
4862            let expected = records.len();
4863            let answered = records.iter().filter(|r| r.failed.is_none()).count();
4864            let incomplete = answered < expected;
4865            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
4866            let policy = self.state.config.graph.incomplete_review;
4867            let clean = round_is_clean(
4868                blocking,
4869                e2e_ok,
4870                answered,
4871                expected,
4872                round_quota_missing,
4873                policy,
4874            );
4875
4876            let mut round_record = ReviewRound {
4877                round,
4878                head: head.clone(),
4879                verified_head: None,
4880                verified_at: None,
4881                reviews: records,
4882                e2e,
4883                verify_retried,
4884                e2e_deferred,
4885                e2e_defer_reason,
4886                fix: None,
4887                blocking,
4888                answered,
4889                expected,
4890                clean,
4891                progressed: false,
4892                vote_split,
4893                reconsideration,
4894                verdict: None,
4895            };
4896            // The final vote per seat is its revote where reconsideration
4897            // ran and answered, its initial vote otherwise — the same
4898            // fallback `tally` uses for a judge whose private vote failed.
4899            round_record.verdict = ReviewVote::worst(
4900                round_record
4901                    .final_votes()
4902                    .into_iter()
4903                    .map(|(_, _, vote)| vote),
4904            );
4905            // Which commit and when magi actually attempted to check —
4906            // known the moment a command was dispatched against `head`,
4907            // whether or not it finished: a resource-blocked attempt still
4908            // targeted a specific commit at a specific time, and leaving
4909            // that unrecorded is exactly what made `verification_summary`
4910            // report a fresh attempt as "commit unknown ... recorded before
4911            // this was tracked", indistinguishable from a genuinely old,
4912            // untracked record. Only a deferred or unconfigured round never
4913            // ran at all and has nothing to record — see
4914            // `ReviewRound::verified_head`'s own doc.
4915            if !matches!(
4916                round_record.e2e_status(),
4917                E2eStatus::Deferred | E2eStatus::NotConfigured
4918            ) {
4919                round_record.verified_head = Some(head.clone());
4920                round_record.verified_at = Some(Timestamp::now());
4921            }
4922            let this_round_verification = round_record.verification_summary(&head);
4923
4924            if incomplete {
4925                let missing: Vec<String> = round_record
4926                    .reviews
4927                    .iter()
4928                    .filter(|r| r.failed.is_some())
4929                    .map(|r| format!("review-{}", r.reviewer))
4930                    .collect();
4931                self.state.event(
4932                    "review",
4933                    format!(
4934                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
4935                        missing.join(", ")
4936                    ),
4937                );
4938            }
4939
4940            if clean {
4941                self.state.event(
4942                    "review",
4943                    if incomplete && policy == IncompleteReviewPolicy::Warn {
4944                        format!(
4945                            "round {round}: clean (warn policy, incomplete panel) — no \
4946                             blocking findings from the seats that answered, verification green"
4947                        )
4948                    } else if incomplete {
4949                        format!(
4950                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
4951                             quorum) — no blocking findings from the seats that answered, \
4952                             verification green",
4953                            expected - answered
4954                        )
4955                    } else {
4956                        format!("round {round}: clean — no blocking findings, verification green")
4957                    },
4958                );
4959                self.state.reviews.push(round_record);
4960                self.state.status = RunStatus::Gating;
4961                self.state.save()?;
4962                return Ok(());
4963            }
4964
4965            // Nothing was raised and verification passed, but not every seat
4966            // answered and `round_is_clean` still refused to call it clean —
4967            // either a seat is missing for a reason other than its own quota
4968            // (a crash, a timeout, unparsable output — worth another try), or
4969            // every seat that could have answered lost its quota and nobody
4970            // is left to decide on: re-review rather than send the fixer
4971            // after a round with nothing to fix.
4972            if incomplete && blocking == 0 && e2e_ok {
4973                self.state.reviews.push(round_record);
4974                self.state.save()?;
4975                if round == max_rounds {
4976                    self.state.status = RunStatus::Blocked;
4977                    self.state.event(
4978                        "review",
4979                        format!(
4980                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
4981                             refusing to call it clean",
4982                            expected - answered
4983                        ),
4984                    );
4985                    return Ok(());
4986                }
4987                continue;
4988            }
4989
4990            // Nothing for the fixer to act on (`blocking == 0`) and the only
4991            // reason this round is not clean is that magi itself never got
4992            // a command to run — the shared build cache, not the patch (see
4993            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
4994            // the fixer would invite a change to appease contention that has
4995            // nothing to do with the diff, and would leave this attempt
4996            // sitting in the next round's prompt as if it were about an
4997            // earlier, superseded commit rather than what it actually is:
4998            // the same head, still waiting to be checked. Wait for it the
4999            // same way the final round's own contention is already handled,
5000            // whatever round this happens to be.
5001            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
5002                self.state.reviews.push(round_record);
5003                return self
5004                    .stop_reviewing(
5005                        "the round's own verification could not run",
5006                        &shell,
5007                        &winner.worktree,
5008                    )
5009                    .await;
5010            }
5011
5012            if round == max_rounds {
5013                self.state.reviews.push(round_record);
5014                return self
5015                    .stop_reviewing(
5016                        &format!(
5017                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
5018                        ),
5019                        &shell,
5020                        &winner.worktree,
5021                    )
5022                    .await;
5023            }
5024
5025            // Fix. The winner's own implementer seat continues its conversation:
5026            // the competition is over, so context is pure benefit now.
5027            let (fix_spec, fix_seat_key) = self.fixer_spec(&winner);
5028            let seat = self.seat(&fix_seat_key, &fix_spec.id);
5029            let blocking_findings: Vec<_> = all_findings
5030                .iter()
5031                .filter(|f| f.severity.blocks())
5032                .cloned()
5033                .collect();
5034            let job = SeatJob {
5035                prompt: prompt::fix(
5036                    &self.state.instruction,
5037                    &blocking_findings,
5038                    this_round_verification.as_ref(),
5039                    round,
5040                    max_rounds,
5041                    &language,
5042                ),
5043                spec: fix_spec.clone(),
5044                seat,
5045                cwd: winner.worktree.clone(),
5046                timeout: Duration::from_secs(self.state.config.graph.timeout_fix),
5047                allow_write: true,
5048                sessions,
5049                artifacts: artifacts.clone(),
5050                stem: format!("fix-{round}"),
5051                handover: None,
5052            };
5053            let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5054            let cache = self.state.config.cache_dir();
5055            let ctx = WaveCtx {
5056                carry_seats: false,
5057                run: &run_id,
5058                node: "fix",
5059                prompts: &prompts,
5060                cache: cache.as_deref(),
5061                round: Some(round),
5062            };
5063            let (seat, out) =
5064                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
5065            let agent_id = seat.agent.clone();
5066
5067            let mut fix = FixRecord {
5068                agent: agent_id,
5069                addressed: Vec::new(),
5070                rejected: Vec::new(),
5071                notes: String::new(),
5072                committed: false,
5073                failed: None,
5074                duration_ms: 0,
5075                continuation: None,
5076            };
5077            let mut continuation = ContinuationRecord::not_needed();
5078            let mut final_seat = seat.clone();
5079            match out {
5080                AgentOutcome::Ok(o) => {
5081                    fix.duration_ms = o.duration_ms;
5082                    let parsed = verdict::extract_json::<FixReport>(&o.text);
5083                    // A parsed report standing next to a command this same
5084                    // reply's own CLI never confirmed the exit status of is
5085                    // not a resolved answer — the identical `CommandEvidence`
5086                    // `state.jobs` renders, read here instead of only on
5087                    // display, per the completion judgment and the shown
5088                    // record needing to agree.
5089                    let incomplete_reason = match &parsed {
5090                        Ok(_) if has_unconfirmed_command(&o.commands) => Some(
5091                            "the reply parsed, but it reported a command whose own CLI never \
5092                             confirmed an exit status"
5093                                .to_owned(),
5094                        ),
5095                        Ok(_) => None,
5096                        Err(e) => Some(e.to_string()),
5097                    };
5098                    match incomplete_reason {
5099                        None => {
5100                            let report = parsed.expect("checked Ok above");
5101                            fix.addressed = report.addressed;
5102                            fix.rejected = report.rejected;
5103                            fix.notes =
5104                                blind::sanitize_prose(&report.notes, &self.state.config.blind);
5105                        }
5106                        Some(reason) => {
5107                            let (resumed_seat, resolved, failure, cont) = self
5108                                .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
5109                                .await;
5110                            fix.duration_ms += cont.cumulative_wait_ms;
5111                            continuation = cont;
5112                            final_seat = resumed_seat;
5113                            match resolved {
5114                                Some(report) => {
5115                                    fix.addressed = report.addressed;
5116                                    fix.rejected = report.rejected;
5117                                    fix.notes = blind::sanitize_prose(
5118                                        &report.notes,
5119                                        &self.state.config.blind,
5120                                    );
5121                                }
5122                                None => fix.failed = failure,
5123                            }
5124                        }
5125                    }
5126                }
5127                // The CLI's raw error JSON is not a fix report to parse.
5128                AgentOutcome::Dropped(o) => {
5129                    fix.duration_ms = o.duration_ms;
5130                    let why = o
5131                        .dropped
5132                        .as_ref()
5133                        .map(|d| d.why.as_str())
5134                        .unwrap_or("the CLI ended the stream without delivering its answer");
5135                    fix.failed = Some(format!("the CLI dropped the stream ({why})"));
5136                }
5137                AgentOutcome::Quota(o) => {
5138                    self.state.quota.push(QuotaLoss {
5139                        seat: final_seat.key.clone(),
5140                        node: "fix".to_owned(),
5141                        at: Timestamp::now(),
5142                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
5143                    });
5144                    fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
5145                }
5146                AgentOutcome::Failed(e) => fix.failed = Some(e),
5147            }
5148            fix.continuation = Some(continuation);
5149            self.state.seats.insert(final_seat.key.clone(), final_seat);
5150            if let Ok(r) = git::rescue_commit(
5151                &winner.worktree,
5152                &format!("magi: review round {round} fixes (uncommitted work)"),
5153            )
5154            .await
5155            {
5156                self.state.note_withheld("fix", &r.withheld);
5157            }
5158            let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5159            fix.committed = after != before;
5160            // Judged by what `git` says moved against base, never by the
5161            // fixer's own `addressed`/`rejected` count — see
5162            // `ReviewRound::progressed`. Propagated with `?`, the same as the
5163            // `patch` snapshot above: swallowing this error would default
5164            // `diff_after` to empty, which almost always differs from a
5165            // non-empty `patch` and reads as "progressed" — exactly backwards
5166            // for a `git` failure the stagnation check cannot see through.
5167            let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
5168            let progressed = diff_after != patch;
5169            let commit_note = if fix.committed {
5170                "committed"
5171            } else {
5172                "NO new commit"
5173            };
5174            let tree_note = if progressed {
5175                "changed vs base"
5176            } else {
5177                "unchanged vs base"
5178            };
5179            self.state.event(
5180                "fix",
5181                match &fix.failed {
5182                    // Distinct on purpose from "0 addressed, 0 rejected": the
5183                    // fixer's own diff still landed (blocking counts do keep
5184                    // falling round over round), only its adoption report did
5185                    // not come back, so this must never read like every
5186                    // finding was reviewed and declined.
5187                    Some(reason) => {
5188                        format!(
5189                            "round {round}: fixer's adoption report was lost ({reason}); \
5190                             {commit_note}, tree {tree_note}"
5191                        )
5192                    }
5193                    None => format!(
5194                        "round {round}: {} addressed, {} rejected, {commit_note}, tree \
5195                         {tree_note}{}",
5196                        fix.addressed.len(),
5197                        fix.rejected.len(),
5198                        if continuation.outcome == ContinuationOutcome::Resumed {
5199                            format!(
5200                                " (adoption report recovered after {} continuation(s))",
5201                                continuation.attempts
5202                            )
5203                        } else {
5204                            String::new()
5205                        },
5206                    ),
5207                },
5208            );
5209            round_record.fix = Some(fix);
5210            round_record.progressed = progressed;
5211            self.state.reviews.push(round_record);
5212            self.state.save()?;
5213
5214            // The fixer's own report never came back this round, even after
5215            // `continue_fix_report`'s own budget was spent on it — not an
5216            // ordinary "no report" (dropped stream, quota, plain failure),
5217            // which already reads that way and is left to the existing round
5218            // budget. Stopping here, rather than opening another round, is
5219            // what keeps a next reviewer/fixer wave from ever being
5220            // dispatched onto `winner.worktree` while whatever the seat's
5221            // last call may still have running there is unaccounted for: no
5222            // process liveness check exists (and none is being added — see
5223            // AGENTS.md/this task's own scope), so the only way to honour
5224            // "nothing starts before a valid report returns" is to not start
5225            // anything further on this worktree from this run at all.
5226            if matches!(
5227                continuation.outcome,
5228                ContinuationOutcome::Exhausted
5229                    | ContinuationOutcome::QuotaLost
5230                    | ContinuationOutcome::NoSession
5231            ) {
5232                return self
5233                    .stop_reviewing(
5234                        "the fixer's adoption report never came back, even after resuming its \
5235                         own seat; refusing to start another round against the same worktree \
5236                         while that is unresolved",
5237                        &shell,
5238                        &winner.worktree,
5239                    )
5240                    .await;
5241            }
5242
5243            let streak = self
5244                .state
5245                .reviews
5246                .iter()
5247                .rev()
5248                .take_while(|r| !r.progressed)
5249                .count();
5250            if streak >= STAGNANT_LIMIT {
5251                return self
5252                    .stop_reviewing(
5253                        &format!(
5254                            "the tree has not moved against base for {streak} round(s) in a row"
5255                        ),
5256                        &shell,
5257                        &winner.worktree,
5258                    )
5259                    .await;
5260            }
5261        }
5262        Ok(())
5263    }
5264
5265    /// Decide, from the last recorded round's own verification, whether
5266    /// stopping the review loop is a hand-off or a genuine block.
5267    ///
5268    /// Called once the loop has given up trying — the round budget is spent,
5269    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
5270    /// findings still open, never while a round is still clean or the
5271    /// incomplete-panel case handled inline above. Gate and e2e are facts
5272    /// about the tree; a lingering review finding is an opinion, and this
5273    /// workload's own `magi stats` puts reviewer precision low enough
5274    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
5275    /// must not by itself stand between a green, verified change and the
5276    /// human who decides what to do with it. A red e2e is not an opinion, so
5277    /// that case still blocks, with the failing command and a tail of its
5278    /// output recorded here rather than left in `run.json` for someone to go
5279    /// find.
5280    ///
5281    /// A round that deferred its own e2e (see [`Config::graph`]'s
5282    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
5283    /// only because nothing ran, and treating an empty list as a passing one
5284    /// here is exactly the "deferred painted green" bug this function exists
5285    /// to not have. When the last round's own verification never resolved —
5286    /// deferred on purpose, or a real attempt the shared build cache blocked
5287    /// — this makes (or retries) the real run, on the actual worktree this
5288    /// loop is about to stop touching, before deciding anything. A
5289    /// resource-blocked attempt is likewise never read as either green or
5290    /// red: it is evidence about the machine, not the patch (see
5291    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
5292    /// blocked cache leaves this call without deciding rather than guessing
5293    /// — the caller retries on a later reentry.
5294    /// Record, once, that the review loop handed off over a blocking finding
5295    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
5296    /// `land` asks the owner even with `land_approval` off. Called from every
5297    /// path that concludes `Gating`; a reentry keeps the first record.
5298    fn record_contested_handoff(&mut self) {
5299        if self.state.contested_handoff.is_some() {
5300            return;
5301        }
5302        let Some(contested) = self
5303            .state
5304            .reviews
5305            .last()
5306            .and_then(ReviewRound::contested_handoff)
5307        else {
5308            return;
5309        };
5310        self.state.event(
5311            "review",
5312            format!(
5313                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
5314                 wait for the owner's approval",
5315                contested.findings.len(),
5316                contested.rejecters.len()
5317            ),
5318        );
5319        self.state.contested_handoff = Some(contested);
5320    }
5321
5322    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
5323        let round_idx = self.state.reviews.len() - 1;
5324        // A deferred round and a resource-blocked one are the same shape
5325        // here: neither has a real result yet, and both get one more
5326        // attempt. Read off `e2e_status` — the single source for this —
5327        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
5328        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
5329        // still retries instead of being read as a settled result the
5330        // instant it stops being empty.
5331        let needs_catchup_run = matches!(
5332            self.state.reviews[round_idx].e2e_status(),
5333            E2eStatus::Deferred | E2eStatus::ResourceBlocked
5334        );
5335        if needs_catchup_run {
5336            let round = self.state.reviews[round_idx].round;
5337            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5338            let commands = self.state.config.verify.e2e.clone();
5339            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
5340            let cache_dir = self.state.config.cache_dir();
5341            let context = format!(
5342                "round {round}: verification unresolved, catching up before the final decision"
5343            );
5344            let (outcomes, verify_retried) = with_cache_lease(
5345                &mut self.state,
5346                cache_dir.as_deref(),
5347                "e2e",
5348                "e2e",
5349                worktree,
5350                &attempted_head,
5351                timeout,
5352                &context,
5353                |state, budget| {
5354                    let shell = shell.to_vec();
5355                    let commands = commands.clone();
5356                    let context = context.clone();
5357                    async move {
5358                        run_e2e_with_retry(state, &shell, &commands, worktree, budget, &context)
5359                            .await
5360                    }
5361                },
5362            )
5363            .await;
5364            let last = &mut self.state.reviews[round_idx];
5365            last.e2e = outcomes;
5366            last.verify_retried = verify_retried;
5367            // Always the commit and time this attempt actually targeted,
5368            // whether or not it happens to equal the reviewed `head` and
5369            // whether or not a command finished — see
5370            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
5371            // attempt is recorded too, so a later reader sees "attempted
5372            // again at T2" rather than silence.
5373            last.verified_head = Some(attempted_head);
5374            last.verified_at = Some(Timestamp::now());
5375            if verify_inconclusive(&last.e2e) {
5376                // Still not a real result: `e2e_deferred` is left exactly
5377                // as it was, so `needs_catchup_run` above reads
5378                // `ResourceBlocked` (via `e2e_status`, which checks
5379                // `resource_blocked` before `e2e_deferred`) and retries
5380                // again on the next reentry, rather than recording
5381                // contention as a red e2e and blocking the run on it.
5382                self.state.save()?;
5383                return Ok(());
5384            }
5385            last.e2e_deferred = false;
5386        }
5387        let last = &self.state.reviews[round_idx];
5388        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
5389
5390        match last.e2e_status() {
5391            E2eStatus::Failed => {
5392                let red: Vec<String> = last
5393                    .e2e
5394                    .iter()
5395                    .filter(|o| !o.ok())
5396                    .map(|o| {
5397                        format!(
5398                            "`{}` -> {:?}\n{}",
5399                            o.command,
5400                            o.code,
5401                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
5402                        )
5403                    })
5404                    .collect();
5405                self.state
5406                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
5407                self.state.status = RunStatus::Blocked;
5408            }
5409            // `needs_catchup_run` above already retried once this call; if
5410            // it is still blocked, this is magi's own admission it could
5411            // not get a command to run, never a verdict on the patch — the
5412            // run is left exactly where a later reentry can retry again.
5413            E2eStatus::ResourceBlocked => {
5414                self.state.event(
5415                    "review",
5416                    format!(
5417                        "{why}; e2e could not run (shared build cache unavailable); not \
5418                         deciding yet"
5419                    ),
5420                );
5421            }
5422            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
5423                self.state.event(
5424                    "review",
5425                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
5426                );
5427                self.record_contested_handoff();
5428                self.state.status = RunStatus::Gating;
5429            }
5430        }
5431        self.state.save()?;
5432        Ok(())
5433    }
5434
5435    // ----------------------------------------------------------------- gate
5436
5437    async fn gate(&mut self) -> Result<()> {
5438        // Judged by the review record itself, not by `status`: a solo
5439        // candidate's `judge`/`deliberate` skip rewrites `status` on every
5440        // reentry (see `judge`), and trusting it here is exactly how a run
5441        // that exhausted its review budget got gated and merged a second
5442        // time around. `review_conclusion` recomputes the review loop's own
5443        // verdict from the round records themselves — `Gating` for a clean
5444        // round or a hand-off (see `stop_reviewing`), anything else means the
5445        // loop is still going or genuinely blocked.
5446        // A base the winner could not be replayed onto is a decision, not a
5447        // round: there is no landing tree to gate. Read as its own record for
5448        // the same reason the review verdict is.
5449        if self.state.status == RunStatus::Failed
5450            || self
5451                .state
5452                .base_sync
5453                .as_ref()
5454                .is_some_and(|s| s.conflict.is_some())
5455            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
5456                != Some(RunStatus::Gating)
5457        {
5458            return Ok(());
5459        }
5460        if self.state.gate_ran {
5461            // `review_loop` derives its conclusion from the clean review
5462            // record on every reentry and therefore puts a completed run back
5463            // in `Gating`. A recorded gate is a stronger, terminal fact:
5464            // retain its original command output (or lack of any, for a repo
5465            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
5466            // doc) and restore `Blocked` on a real failure rather than
5467            // pretending the command is still running or running it a second
5468            // time. `gate_ran == false` remains the only shape — unattempted,
5469            // or a resource-blocked retry — that may still need to execute a
5470            // command.
5471            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
5472                self.state.status = RunStatus::Blocked;
5473                self.state.save()?;
5474            }
5475            return Ok(());
5476        }
5477        let Some(winner) = self.state.winner().cloned() else {
5478            return Ok(());
5479        };
5480        self.state.status = RunStatus::Gating;
5481        let mut outcomes = self.run_gate(&winner).await?;
5482        loop {
5483            // A resource-blocked outcome means the gate command never actually
5484            // ran - the shared build cache could not be acquired or confirmed
5485            // fresh in time - which is evidence about the machine, not about
5486            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
5487            // Recording it as a red gate would mark a run `Blocked` on nothing
5488            // but contention magi has already logged; leaving `self.state.gate`
5489            // empty and `self.state.gate_ran` false instead keeps the shape
5490            // this function already treats as "still needs to run" (see the
5491            // early-return above), so the next call retries the command
5492            // rather than concluding anything.
5493            if verify_inconclusive(&outcomes) {
5494                self.state.save()?;
5495                return Ok(());
5496            }
5497            if outcomes.iter().all(CommandOutcome::ok) {
5498                break;
5499            }
5500            match self.gate_fix_round(&winner, &outcomes).await? {
5501                GateFix::Retry => outcomes = self.run_gate(&winner).await?,
5502                GateFix::Stop => break,
5503                GateFix::Defer => {
5504                    self.state.save()?;
5505                    return Ok(());
5506                }
5507            }
5508        }
5509        let passed = outcomes.iter().all(CommandOutcome::ok);
5510        self.state.gate = outcomes;
5511        self.state.gate_ran = true;
5512        if !passed {
5513            self.state.status = RunStatus::Blocked;
5514            let spent = self.state.gate_fixes.len();
5515            self.state.event(
5516                "gate",
5517                if spent == 0 {
5518                    "gate failed; not merging".to_owned()
5519                } else {
5520                    format!("gate failed after {spent} gate-fix round(s); not merging")
5521                },
5522            );
5523        }
5524        self.state.save()?;
5525        Ok(())
5526    }
5527
5528    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
5529    /// changed into one commit. Reached only from [`Self::run_gate`], i.e.
5530    /// after review is clean and never on a candidate awaiting judging.
5531    ///
5532    /// Never fails the run: a non-zero exit or timeout is a warning and a
5533    /// recorded outcome, and the gate remains the single arbiter. Nothing
5534    /// configured means nothing happens - no event, no commit. `commit_all`
5535    /// commits any leftover change under the neutral identity and returns
5536    /// `false` when the tree is clean, so no empty commit is ever made.
5537    async fn run_pre_gate(&mut self, winner: &Candidate) {
5538        let commands = self.state.config.verify.pre_gate.clone();
5539        if commands.is_empty() {
5540            return;
5541        }
5542        let shell = self.state.config.shell();
5543        let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5544        let (outcomes, _) = run_commands(
5545            &mut self.state,
5546            "pre_gate",
5547            "pre_gate",
5548            0,
5549            &shell,
5550            &commands,
5551            &winner.worktree,
5552            timeout,
5553        )
5554        .await;
5555        for o in &outcomes {
5556            if !o.ok() {
5557                tracing::warn!(
5558                    "pre_gate `{}` failed ({:?}); the gate decides",
5559                    o.command,
5560                    o.code
5561                );
5562            }
5563            self.state.event(
5564                "pre_gate",
5565                format!(
5566                    "`{}` -> {}",
5567                    o.command,
5568                    if o.ok() {
5569                        "pass".to_owned()
5570                    } else {
5571                        format!(
5572                            "FAIL ({:?})\n{}",
5573                            o.code,
5574                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
5575                        )
5576                    }
5577                ),
5578            );
5579        }
5580        self.state.pre_gate = outcomes;
5581        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
5582            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
5583                Ok(head) => {
5584                    self.state
5585                        .event("pre_gate", format!("committed mechanical fixes ({head})"));
5586                    self.state.pre_gate_commit = Some(head);
5587                }
5588                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
5589            },
5590            Ok(false) => {}
5591            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
5592        }
5593        if let Err(e) = self.state.save() {
5594            tracing::warn!("could not persist the pre_gate record: {e:#}");
5595        }
5596    }
5597
5598    /// Run `verify.gate` once against the winner's current tree, logging one
5599    /// event per command. Empty when nothing is configured.
5600    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
5601        self.run_pre_gate(winner).await;
5602        let shell = self.state.config.shell();
5603        let gate_commands = self.state.config.verify.gate.clone();
5604        // Zero commands has nothing to run and nothing that could touch the
5605        // shared build cache, so it never needs a lease: `Config::cache_dir`
5606        // is derived from `verify.e2e` too, so a repo with no `verify.gate`
5607        // commands but a `CARGO_TARGET_DIR`-using `verify.e2e` would
5608        // otherwise queue behind an unrelated run's lease and come back
5609        // resource-blocked - `gate_ran` would stay false on nothing but
5610        // cache contention, for a step that had nothing to check in the
5611        // first place.
5612        let outcomes = if gate_commands.is_empty() {
5613            Vec::new()
5614        } else {
5615            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5616            let cache_dir = self.state.config.cache_dir();
5617            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5618            let (outcomes, _) = with_cache_lease(
5619                &mut self.state,
5620                cache_dir.as_deref(),
5621                "gate",
5622                "gate",
5623                &winner.worktree,
5624                &head,
5625                timeout,
5626                "final gate",
5627                |state, budget| {
5628                    let shell = shell.clone();
5629                    let gate_commands = gate_commands.clone();
5630                    let worktree = winner.worktree.clone();
5631                    async move {
5632                        let (outcomes, timed_out_pids) = run_commands(
5633                            state,
5634                            "gate",
5635                            "gate",
5636                            0,
5637                            &shell,
5638                            &gate_commands,
5639                            &worktree,
5640                            budget,
5641                        )
5642                        .await;
5643                        (outcomes, false, timed_out_pids)
5644                    }
5645                },
5646            )
5647            .await;
5648            outcomes
5649        };
5650        if outcomes.is_empty() {
5651            // Nothing configured to check — distinct from every other
5652            // silence in this run's event log, since an empty `gate` alone
5653            // no longer says whether the gate ran at all (see
5654            // `RunState::gate_ran`'s own doc).
5655            self.state.event(
5656                "gate",
5657                "no gate commands configured; nothing to check, passing",
5658            );
5659        }
5660        for o in &outcomes {
5661            self.state.event(
5662                "gate",
5663                format!(
5664                    "`{}` -> {}",
5665                    o.command,
5666                    if o.ok() {
5667                        "pass".to_owned()
5668                    } else {
5669                        format!(
5670                            "FAIL ({:?})\n{}",
5671                            o.code,
5672                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
5673                        )
5674                    }
5675                ),
5676            );
5677        }
5678        Ok(outcomes)
5679    }
5680
5681    /// One bounded fix round for a failing gate.
5682    ///
5683    /// The fixer is told the failure came from the gate itself, not from a
5684    /// reviewer, and is shown the failed commands, their exit codes and a tail
5685    /// of their output - whatever `[verify].gate` holds, nothing here knows
5686    /// what those commands run. Only a normal non-zero exit that printed
5687    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
5688    /// command or a full disk says nothing about the code, and a fixer sent
5689    /// after it can only appease the machine. The round is judged by what git
5690    /// says moved, never by the fixer's own report, and `verify.e2e` runs
5691    /// again before the gate does, so a fix cannot trade a green gate for a
5692    /// red e2e unnoticed.
5693    async fn gate_fix_round(
5694        &mut self,
5695        winner: &Candidate,
5696        outcomes: &[CommandOutcome],
5697    ) -> Result<GateFix> {
5698        let cap = self.state.config.graph.gate_fix_rounds;
5699        let spent = self.state.gate_fixes.len();
5700        if spent >= cap {
5701            if cap > 0 {
5702                self.state.event(
5703                    "gate",
5704                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
5705                );
5706            }
5707            return Ok(GateFix::Stop);
5708        }
5709        if !gate_fixable(outcomes) {
5710            self.state.event(
5711                "gate",
5712                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
5713                 command or similar); not spending a fix round on it",
5714            );
5715            return Ok(GateFix::Stop);
5716        }
5717        let min_free = self.state.config.disk.min_free_bytes;
5718        if min_free > 0 {
5719            match crate::disk::free_bytes(&winner.worktree) {
5720                Ok(free) if crate::disk::enough_space(free, min_free) => {}
5721                Ok(free) => {
5722                    self.state.event(
5723                        "gate",
5724                        format!(
5725                            "only {free} bytes free ({min_free} required by `[disk] \
5726                             min_free_bytes`); not spending a fix round on a failure the disk \
5727                             may explain"
5728                        ),
5729                    );
5730                    return Ok(GateFix::Stop);
5731                }
5732                Err(e) => {
5733                    self.state.event(
5734                        "gate",
5735                        format!("free disk space could not be measured ({e:#}); no fix round"),
5736                    );
5737                    return Ok(GateFix::Stop);
5738                }
5739            }
5740        }
5741
5742        let attempt = spent + 1;
5743        let run_id = self.state.id.clone();
5744        let prompts = self.state.config.prompts.clone();
5745        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
5746        let base = self.landing_base();
5747        let (fix_spec, fix_seat_key) = self.fixer_spec(winner);
5748        let seat = self.seat(&fix_seat_key, &fix_spec.id);
5749        let job = SeatJob {
5750            prompt: prompt::gate_fix(
5751                &self.state.instruction,
5752                &failed,
5753                attempt,
5754                cap,
5755                &self.state.config.graph.language,
5756            ),
5757            spec: fix_spec,
5758            seat,
5759            cwd: winner.worktree.clone(),
5760            timeout: Duration::from_secs(self.state.config.graph.timeout_fix),
5761            allow_write: true,
5762            sessions: self.state.config.graph.sessions,
5763            artifacts: agent::artifacts_dir(&self.state.dir()),
5764            stem: format!("gate-fix-{attempt}"),
5765            handover: None,
5766        };
5767        self.state.event(
5768            "gate",
5769            format!("gate failed; gate-fix round {attempt} of {cap}"),
5770        );
5771        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5772        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
5773        let cache = self.state.config.cache_dir();
5774        let ctx = WaveCtx {
5775            carry_seats: false,
5776            run: &run_id,
5777            node: "gate-fix",
5778            prompts: &prompts,
5779            cache: cache.as_deref(),
5780            round: None,
5781        };
5782        let (seat, out) = run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
5783        let mut record = GateFixRecord {
5784            agent: seat.agent.clone(),
5785            failed,
5786            notes: String::new(),
5787            committed: false,
5788            error: None,
5789        };
5790        match out {
5791            AgentOutcome::Ok(o) => {
5792                // A missing report is not a failed fix: the round is judged
5793                // by the tree below, and the report only carries prose.
5794                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
5795                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
5796                }
5797            }
5798            AgentOutcome::Dropped(_) => {
5799                record.error = Some("the CLI dropped the stream".to_owned());
5800            }
5801            AgentOutcome::Quota(o) => {
5802                self.state.quota.push(QuotaLoss {
5803                    seat: seat.key.clone(),
5804                    node: "gate-fix".to_owned(),
5805                    at: Timestamp::now(),
5806                    reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
5807                });
5808                record.error = Some("rate limited (quota); fixer could not run".to_owned());
5809            }
5810            AgentOutcome::Failed(e) => record.error = Some(e),
5811        }
5812        self.state.seats.insert(seat.key.clone(), seat);
5813        if let Ok(r) = git::rescue_commit(
5814            &winner.worktree,
5815            &format!("magi: gate fix {attempt} (uncommitted work)"),
5816        )
5817        .await
5818        {
5819            self.state.note_withheld("gate-fix", &r.withheld);
5820        }
5821        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5822        record.committed = after != before;
5823        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
5824        let note = record.error.clone();
5825        self.state.gate_fixes.push(record);
5826        self.state.save()?;
5827        if !changed {
5828            self.state.event(
5829                "gate",
5830                match note {
5831                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
5832                    None => format!("gate-fix round {attempt}: the tree did not change"),
5833                },
5834            );
5835            return Ok(GateFix::Stop);
5836        }
5837        self.state.event(
5838            "gate",
5839            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
5840        );
5841
5842        let commands = self.state.config.verify.e2e.clone();
5843        if !commands.is_empty() {
5844            let shell = self.state.config.shell();
5845            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
5846            let cache_dir = self.state.config.cache_dir();
5847            let context = format!("gate-fix round {attempt}");
5848            let (e2e, _) = with_cache_lease(
5849                &mut self.state,
5850                cache_dir.as_deref(),
5851                "e2e",
5852                "e2e",
5853                &winner.worktree,
5854                &after,
5855                timeout,
5856                &context,
5857                |state, budget| {
5858                    let shell = shell.clone();
5859                    let commands = commands.clone();
5860                    let context = context.clone();
5861                    let worktree = winner.worktree.clone();
5862                    async move {
5863                        run_e2e_with_retry(state, &shell, &commands, &worktree, budget, &context)
5864                            .await
5865                    }
5866                },
5867            )
5868            .await;
5869            if verify_inconclusive(&e2e) {
5870                return Ok(GateFix::Defer);
5871            }
5872            if e2e.iter().any(|o| !o.ok()) {
5873                self.state.event(
5874                    "gate",
5875                    format!("gate-fix round {attempt}: verify.e2e failed after the fix"),
5876                );
5877                return Ok(GateFix::Stop);
5878            }
5879        }
5880        Ok(GateFix::Retry)
5881    }
5882
5883    // ---------------------------------------------------------------- merge
5884
5885    async fn merge(&mut self) -> Result<()> {
5886        // Same reasoning as `gate`: ask the review and gate records directly
5887        // rather than `status`, which a solo-candidate `judge`/`deliberate`
5888        // skip can rewrite on reentry to something that no longer says
5889        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
5890        // so a hand-off (open findings, green verification) reaches merge
5891        // exactly like a genuinely clean round does.
5892        //
5893        // A run resumed mid-`land` never reaches here at all: `execute`
5894        // recognises `RunStatus::Landing` before it even calls `prep`, and
5895        // routes straight to `run_land` instead. That has to happen a level
5896        // up from this function, not with a check in here, because
5897        // `review_loop`'s own status recomputation (see its doc) runs
5898        // *before* `merge` on every reentry and would otherwise overwrite
5899        // the `Landing` marker with `Gating` before this node ever saw it.
5900        if self
5901            .state
5902            .base_sync
5903            .as_ref()
5904            .is_some_and(|s| s.conflict.is_some())
5905            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
5906                != Some(RunStatus::Gating)
5907            // `gate_ran == false` is not "passed" - `gate` leaves it false
5908            // both before it has ever run and when its last attempt was
5909            // resource-blocked (see `Runner::gate`'s own doc), and neither is
5910            // permission to merge on nothing but the review record. Only a
5911            // gate that actually ran - zero commands configured and
5912            // vacuously passed, or one or more that all exited 0 - may
5913            // proceed; `RunState::gate_status` is the single place that
5914            // reading is computed.
5915            || !self.state.gate_status().ok()
5916        {
5917            return Ok(());
5918        }
5919        // This node's own record, not `status`: `status == Ready` is not
5920        // unique to the harmless `MergeMode::None` path this line was
5921        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
5922        // run's PR was closed without merging — and on that run `mode` is
5923        // still `Pr`, so a reentry that fell through here would push and
5924        // open a second pull request. `self.state.merge` is set exactly once
5925        // this node (or `land`) has already produced a verdict, under every
5926        // mode, which is what "already done" actually means here.
5927        if self.state.merge.is_some() {
5928            return Ok(());
5929        }
5930        let Some(winner) = self.state.winner().cloned() else {
5931            return Ok(());
5932        };
5933        let repo = self.state.repo.clone();
5934        let base = self.state.base_branch.clone();
5935        let mode = self.state.config.merge.mode;
5936        let style = self.state.config.merge.style;
5937        let facts = if is_review_run(&self.state) {
5938            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
5939            let start = review_base(
5940                &repo,
5941                &self.state.config.merge.remote,
5942                &base,
5943                &self.state.base_commit,
5944                &winner.branch,
5945            )
5946            .await;
5947            branch_facts(&repo, &start, &winner.branch).await
5948        } else {
5949            None
5950        };
5951        // `None` when the base could not be freshly read: then an adopted
5952        // pull request's title is left alone.
5953        let leaked = if is_review_run(&self.state) {
5954            leaked_subjects(&self.state, &winner.branch).await
5955        } else {
5956            Some(Vec::new())
5957        };
5958        let pr = pr_message_with(&self.state, winner.label, facts.as_ref());
5959        let message = pr.commit_message();
5960
5961        let outcome = match mode {
5962            MergeMode::None => MergeOutcome {
5963                mode,
5964                ok: true,
5965                detail: manual_merge_command(style, &repo, &winner.branch, &message),
5966                empty: false,
5967            },
5968            MergeMode::Pr | MergeMode::Local
5969                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
5970            {
5971                MergeOutcome {
5972                    mode,
5973                    ok: false,
5974                    detail: empty_candidate_detail(&self.state, &base),
5975                    empty: true,
5976                }
5977            }
5978            MergeMode::Local => {
5979                let on = git::current_branch(&repo).await?;
5980                if on.as_deref() != Some(base.as_str()) {
5981                    MergeOutcome {
5982                        mode,
5983                        ok: false,
5984                        detail: format!(
5985                            "{} has {} checked out, not the base branch {base}",
5986                            repo.display(),
5987                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
5988                        ),
5989                        empty: false,
5990                    }
5991                } else if !git::is_clean(&repo).await? {
5992                    MergeOutcome {
5993                        mode,
5994                        ok: false,
5995                        detail: format!("{} is dirty; refusing to merge", repo.display()),
5996                        empty: false,
5997                    }
5998                } else {
5999                    let out = match style {
6000                        MergeStyle::Merge => {
6001                            git::merge_no_ff(&repo, &winner.branch, &message).await?
6002                        }
6003                        MergeStyle::Squash => {
6004                            git::merge_squash(&repo, &winner.branch, &message).await?
6005                        }
6006                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
6007                    };
6008                    MergeOutcome {
6009                        mode,
6010                        ok: out.ok(),
6011                        detail: if out.ok() { out.stdout } else { out.stderr },
6012                        empty: false,
6013                    }
6014                }
6015            }
6016            MergeMode::Pr => {
6017                let remote = self.state.config.merge.remote.clone();
6018                let pushed = git::push(&winner.worktree, &remote, &winner.branch).await?;
6019                if !pushed.ok() {
6020                    MergeOutcome {
6021                        mode,
6022                        ok: false,
6023                        detail: pushed.stderr,
6024                        empty: false,
6025                    }
6026                } else {
6027                    // A retry or resume of a run whose branch already has an
6028                    // open pull request adopts it rather than failing on a
6029                    // duplicate. Only this winner branch into this base:
6030                    // `branch_for` derives the name from the run id, so a
6031                    // different run's pull request never matches.
6032                    let found = land::find_open_pr(&winner.worktree, &winner.branch, &base).await;
6033                    let out = match pr_merge_plan(found) {
6034                        PrPlan::Create => {
6035                            gh_pr_create(
6036                                &winner.worktree,
6037                                &base,
6038                                &winner.branch,
6039                                &pr.title,
6040                                &pr.body,
6041                            )
6042                            .await
6043                        }
6044                        PrPlan::Adopt { url, title } => {
6045                            self.state
6046                                .event("merge", format!("Pr: adopted open pull request {url}"));
6047                            if title != pr.title
6048                                && (!is_review_run(&self.state)
6049                                    || leaked
6050                                        .as_deref()
6051                                        .is_some_and(|l| should_retitle(&title, &pr.title, l)))
6052                                && let Err(e) =
6053                                    land::set_pr_title(&winner.worktree, &url, &pr.title).await
6054                            {
6055                                tracing::warn!("could not refresh title of {url}: {e:#}");
6056                                self.state
6057                                    .event("merge", format!("Pr: title refresh failed: {e:#}"));
6058                            }
6059                            Ok(url)
6060                        }
6061                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
6062                    };
6063                    match out {
6064                        Ok(url) => MergeOutcome {
6065                            mode,
6066                            ok: true,
6067                            detail: url,
6068                            empty: false,
6069                        },
6070                        Err(e) => MergeOutcome {
6071                            mode,
6072                            ok: false,
6073                            detail: e.to_string(),
6074                            empty: false,
6075                        },
6076                    }
6077                }
6078            }
6079        };
6080
6081        self.state.status = match (mode, outcome.ok) {
6082            (MergeMode::None, _) => RunStatus::Ready,
6083            (_, true) => RunStatus::Merged,
6084            (_, false) => RunStatus::Blocked,
6085        };
6086        self.state.event(
6087            "merge",
6088            format!(
6089                "{:?}: {}",
6090                mode,
6091                outcome.detail.lines().next().unwrap_or("")
6092            ),
6093        );
6094        self.state.merge = Some(outcome);
6095        self.state.save()?;
6096
6097        // The PR is open and the run would historically stop here, leaving the
6098        // operator to watch checks, feed review comments back to a fixer, and
6099        // merge. That was done by hand six times in one session before this
6100        // existed. Opt-in, because merging is the one irreversible thing magi
6101        // can do to a repository.
6102        if self.state.config.graph.land
6103            && mode == MergeMode::Pr
6104            && self.state.status == RunStatus::Merged
6105        {
6106            self.run_land().await?;
6107        }
6108        // `run_land` may have left `status` at `Landing` - still waiting on
6109        // CI or the owner's approval, not actually settled - so this has to
6110        // read whatever `status` ended up as here, not the `Merged` this
6111        // function set a few lines up.
6112        self.settle_questions();
6113        Ok(())
6114    }
6115
6116    /// Enter `land`.
6117    ///
6118    /// Shared between a fresh run's first pass through [`Runner::merge`] and
6119    /// a resumed run's re-entry. `land::land` itself is what serialises the
6120    /// two git-mutating moments inside the loop — the rebase push and
6121    /// `gh pr merge` — per repository (see its own doc); nothing here needs
6122    /// to hold a lock across the whole call, and doing so would serialise
6123    /// this run's CI wait against a *different* run's land-approval resume
6124    /// in the same repository, which is exactly the "must not wait on
6125    /// another task" property the daemon's slot-freeing exists to give.
6126    async fn run_land(&mut self) -> Result<()> {
6127        let url = self
6128            .state
6129            .merge
6130            .as_ref()
6131            .map(|m| m.detail.clone())
6132            .unwrap_or_default();
6133        let url = url.lines().next().unwrap_or("").trim().to_owned();
6134        if !url.starts_with("http") {
6135            return Ok(());
6136        }
6137        // A land failure is not a lost run: the work is on a branch and the
6138        // pull request is open, which is exactly where a human takes over.
6139        match land::land(&mut self.state, &url).await {
6140            Ok(pr) if self.state.parked => {
6141                // `land` already saved the parked marker; nothing here
6142                // overrides `status` back to a terminal value while an
6143                // approval is still outstanding.
6144                let _ = pr;
6145            }
6146            Ok(pr) => {
6147                self.state.status = match pr.state {
6148                    land::PrLifecycle::Merged => RunStatus::Merged,
6149                    _ => RunStatus::Blocked,
6150                };
6151                // Downstream of a confirmed merge only - see
6152                // `bump::should_release_bump`'s own doc for why this one
6153                // check covers all three of `land`'s success paths.
6154                // Best-effort: the run already landed, so a failure here
6155                // (the decision call, `gh`, `cargo`) is recorded and never
6156                // turns a landed run into a failed one.
6157                if bump::should_release_bump(self.state.status)
6158                    && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
6159                {
6160                    // The event is the run's own record. Not-eligible cases
6161                    // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
6162                    // `Err` is a bump that was tried and failed:
6163                    // `after_merge` itself raises the operator notice for
6164                    // that, whether or not a release PR exists yet.
6165                    self.state
6166                        .event("bump", format!("release bump skipped: {e:#}"));
6167                }
6168                // Independent of the bump, and best-effort in the same way:
6169                // findings the merge left open become follow-up tasks.
6170                if self.state.status == RunStatus::Merged {
6171                    crate::followup::after_merge(&mut self.state, &pr.url).await;
6172                }
6173                self.state.save()?;
6174            }
6175            Err(e) => {
6176                self.state.status = RunStatus::Blocked;
6177                self.state.event("land", format!("gave up: {e}"));
6178                self.state.save()?;
6179            }
6180        }
6181        Ok(())
6182    }
6183
6184    // -------------------------------------------------------------- helpers
6185
6186    /// Fetch or create a seat, keeping its conversation across nodes.
6187    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
6188        if let Some(existing) = self.state.seats.get(key)
6189            && existing.agent == agent
6190        {
6191            return existing.clone();
6192        }
6193        // A seat that changes agent mints its session id from the agent too,
6194        // like a handover: the old agent's uuid is already taken by the CLI.
6195        let fresh = if self.state.seats.contains_key(key) {
6196            handover_seat(key, agent, self.state.next_seat_seed())
6197        } else {
6198            SeatState::new(key, agent, self.state.seed)
6199        };
6200        self.state.seats.insert(key.to_owned(), fresh.clone());
6201        fresh
6202    }
6203
6204    /// The agent now holding seat `key`: `spec`, unless a handover moved the
6205    /// seat to another roster agent, in which case that agent. Nodes that
6206    /// continue a seat's conversation (deliberation, the votes, a reviewer's
6207    /// reconsideration) must keep talking to whoever answered it, not slip
6208    /// back to the agent that failed it.
6209    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
6210        match self.state.seats.get(key) {
6211            Some(s) if s.agent != spec.id => {
6212                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
6213            }
6214            _ => spec,
6215        }
6216    }
6217
6218    /// A candidate rendered for judging, with the leak policy applied.
6219    fn view(&self, c: &Candidate) -> CandidateView {
6220        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
6221            .unwrap_or_default();
6222        let (patch, _) = blind::sanitize_patch(
6223            &format!("candidate {} patch", c.label),
6224            &raw,
6225            &self.state.config.blind,
6226        );
6227        CandidateView {
6228            label: c.label,
6229            branch: c.branch.clone(),
6230            summary: c.summary.clone(),
6231            stat: c.stat.clone(),
6232            patch,
6233        }
6234    }
6235
6236    /// The full candidate set as prompt text, for seats with no live session.
6237    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
6238        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
6239        prompt::judge(
6240            "(see above)",
6241            &views,
6242            self.roles.judges.len(),
6243            base_short,
6244            "en",
6245        )
6246    }
6247
6248    /// The final-vote prompt with everything a seat that has no session of its
6249    /// own needs: the candidates, the seat's own ranking and reasons, and the
6250    /// anonymised deliberation it took part in (only when there was one, so a
6251    /// handed-over seat never sees more than the seat it replaces did). The
6252    /// `Final vote` heading stays first.
6253    fn vote_prompt_full(
6254        &self,
6255        j: usize,
6256        labels: &[char],
6257        language: &str,
6258        candidates: &[Candidate],
6259        base_short: &str,
6260    ) -> String {
6261        let mut text = format!(
6262            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
6263            prompt::final_vote(labels, language),
6264            self.state.instruction,
6265            self.candidate_block(candidates, base_short)
6266        );
6267        if let Some(own) = self
6268            .state
6269            .judgements
6270            .get(j)
6271            .filter(|r| !r.ranking.is_empty())
6272        {
6273            let reasons = own
6274                .reasons
6275                .iter()
6276                .map(|(k, v)| format!("- {k}: {v}"))
6277                .collect::<Vec<_>>()
6278                .join("\n");
6279            text.push_str(&format!(
6280                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
6281                own.ranking.iter().collect::<String>(),
6282                if reasons.is_empty() {
6283                    ""
6284                } else {
6285                    ", because:\n"
6286                }
6287            ));
6288        }
6289        if !self.state.deliberation.is_empty() {
6290            text.push_str("\n# What was argued before this vote\n");
6291            for t in self.transcript(&[], j) {
6292                text.push_str(&format!(
6293                    "\n## {}{}\n\n{}\n",
6294                    t.who,
6295                    if t.is_self { " (you)" } else { "" },
6296                    t.body.trim()
6297                ));
6298            }
6299        }
6300        text
6301    }
6302
6303    /// Anonymised transcript for judge `self_idx`.
6304    ///
6305    /// The initial rankings are always the opening statements. Seeding them
6306    /// only when no turn had been taken yet meant every judge after the first
6307    /// argued against a single voice instead of against the actual split — the
6308    /// disagreement is the information, so it is always on the table.
6309    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
6310        let mut turns = Vec::new();
6311        for j in &self.state.judgements {
6312            if j.ranking.is_empty() {
6313                continue;
6314            }
6315            let reasons = j
6316                .reasons
6317                .iter()
6318                .map(|(k, v)| format!("- {k}: {v}"))
6319                .collect::<Vec<_>>()
6320                .join("\n");
6321            turns.push(Turn {
6322                who: format!("Judge {} (opening ranking)", j.judge),
6323                is_self: j.judge == self_idx + 1,
6324                body: format!(
6325                    "Ranked {}{}{reasons}",
6326                    j.ranking.iter().collect::<String>(),
6327                    if reasons.is_empty() {
6328                        ""
6329                    } else {
6330                        ", because:\n"
6331                    }
6332                ),
6333            });
6334        }
6335        for t in self
6336            .state
6337            .deliberation
6338            .iter()
6339            .flat_map(|r| r.turns.iter())
6340            .chain(current)
6341        {
6342            turns.push(Turn {
6343                who: format!("Judge {}", t.judge),
6344                is_self: t.judge == self_idx + 1,
6345                body: t.body.clone(),
6346            });
6347        }
6348        turns
6349    }
6350}
6351
6352/// Does this seat still hold the context a follow-up prompt would rely on?
6353fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
6354    agent::has_session(spec.kind, seat, sessions)
6355}
6356
6357/// The next entry in `roster` after `start`, never wrapping back to the
6358/// front, whose id is not in `tried` yet.
6359///
6360/// Starts one past `start` rather than at the front of `roster`: `start` is
6361/// the seat's own original position, and a seat whose candidate slot already
6362/// sits on the roster's second entry must fall through to the third next, not
6363/// restart at the first — which is very likely a different candidate's own
6364/// agent already. Never wraps back past `start`, for the same reason: an
6365/// entry earlier in the roster than the seat's own position is almost
6366/// certainly some *other* candidate slot's own agent, and once the tail of
6367/// the roster is exhausted there are no more untried agents for *this* seat
6368/// to fall through to — the caller's fallback chain ends there, exactly as
6369/// "no further untried agents remain in the list for that seat" asks for.
6370///
6371/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
6372/// the same id twice (an operator's `roles.implementers` typo, or a
6373/// `[[agents]]` list reused across roles) must not let
6374/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
6375/// over `roster` either finds an untried id or runs out, so this always
6376/// terminates regardless of duplicates.
6377fn next_untried_in_roster<'a>(
6378    roster: &'a [AgentSpec],
6379    start: usize,
6380    tried: &BTreeSet<String>,
6381) -> Option<&'a AgentSpec> {
6382    roster
6383        .get(start + 1..)?
6384        .iter()
6385        .find(|s| !tried.contains(&s.id))
6386}
6387
6388/// The next agent for a seat that carries its failure history across rounds
6389/// (the review loop). `round_tried` is this round's own bound and starts
6390/// empty every round; `carried_failed` only decides priority.
6391///
6392/// First: an id walking forward from `start`, never wrapping, that is neither
6393/// tried this round nor failed in an earlier one. Only when that is exhausted
6394/// does it rescue: the first roster id (in roster order, so this one *does*
6395/// look before `start`) not yet tried this round, which is by then a carried
6396/// failure. Each id is rescued at most once per round, so it cannot loop.
6397fn next_for_seat<'a>(
6398    roster: &'a [AgentSpec],
6399    start: usize,
6400    round_tried: &BTreeSet<String>,
6401    carried_failed: &BTreeSet<String>,
6402) -> Option<&'a AgentSpec> {
6403    roster
6404        .get(start + 1..)?
6405        .iter()
6406        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
6407        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
6408}
6409
6410/// Where a reviewer seat starts a round: the agent that last answered it when
6411/// it is still on the roster and not marked failed, else the spec's own agent
6412/// unless it failed, else the next roster agent that has not failed, else the
6413/// spec's own agent again (the whole roster failed). Ids no longer on the
6414/// roster are ignored. An empty roster has no handover, so the spec stands.
6415fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
6416    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
6417        return spec;
6418    };
6419    let ok = |id: &str| !h.failed.contains(id);
6420    if let Some(last) = h.last_ok.as_deref()
6421        && ok(last)
6422        && let Some(s) = roster.iter().find(|s| s.id == last)
6423    {
6424        return s.clone();
6425    }
6426    if ok(&spec.id) {
6427        return spec;
6428    }
6429    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
6430    roster
6431        .get(from + 1..)
6432        .into_iter()
6433        .flatten()
6434        .chain(roster.iter())
6435        .find(|s| ok(&s.id))
6436        .cloned()
6437        .unwrap_or(spec)
6438}
6439
6440/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
6441/// seed so a CLI that mints its session id up front (`--session-id`) never
6442/// reuses the uuid the previous agent already opened under the same seat key.
6443fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
6444    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
6445}
6446
6447/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
6448/// so the classifier below and the code that builds the message cannot drift.
6449const TIMED_OUT: &str = "timed out";
6450
6451impl FailClass {
6452    /// `None` for an answer; otherwise how the turn failed.
6453    fn of(out: &AgentOutcome) -> Option<Self> {
6454        match out {
6455            AgentOutcome::Ok(_) => None,
6456            AgentOutcome::Quota(_) => Some(Self::Quota),
6457            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
6458            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
6459            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
6460        }
6461    }
6462
6463    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
6464    fn stem_word(&self) -> &'static str {
6465        match self {
6466            Self::Quota => "quota",
6467            _ => "handover",
6468        }
6469    }
6470}
6471
6472/// The message's first line with its variable parts removed — digit runs and
6473/// path-like tokens — so "exited with Some(2)" and "exited with Some(7)" read
6474/// as one kind of failure.
6475fn failure_signature(msg: &str) -> String {
6476    let line = msg.lines().next().unwrap_or("").trim().to_lowercase();
6477    let mut out = Vec::new();
6478    for word in line.split_whitespace() {
6479        if word.contains('/') || word.contains('\\') {
6480            out.push("<path>".to_owned());
6481            continue;
6482        }
6483        let mut w = String::new();
6484        let mut in_digits = false;
6485        for c in word.chars() {
6486            if c.is_ascii_digit() {
6487                if !in_digits {
6488                    w.push('#');
6489                }
6490                in_digits = true;
6491            } else {
6492                in_digits = false;
6493                w.push(c);
6494            }
6495        }
6496        out.push(w);
6497    }
6498    out.join(" ").chars().take(120).collect()
6499}
6500
6501/// Whether a seat that just failed with `cur` may go to the next roster agent.
6502/// A quota or a timeout always may. Any other failure may not when the agent
6503/// before it failed the same way: an error the prompt causes would otherwise
6504/// walk the whole roster. `prev` is the class of the immediately preceding
6505/// agent's failure, so a quota or timeout in between breaks the run of
6506/// identical failures by itself.
6507fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
6508    match cur {
6509        FailClass::Quota | FailClass::Timeout => true,
6510        FailClass::Other(_) => prev != Some(cur),
6511    }
6512}
6513
6514/// A short human reason for a failed outcome, for the handover record.
6515fn fail_reason(out: &AgentOutcome) -> String {
6516    match out {
6517        AgentOutcome::Ok(_) => String::new(),
6518        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
6519        AgentOutcome::Dropped(o) => format!(
6520            "the CLI dropped the stream ({})",
6521            o.dropped
6522                .as_ref()
6523                .map(|d| d.why.as_str())
6524                .unwrap_or("it ended without delivering its answer")
6525        ),
6526        AgentOutcome::Failed(e) => e.lines().next().unwrap_or("").chars().take(160).collect(),
6527    }
6528}
6529
6530/// Note one handover in the run: the structured record and, in the timeline,
6531/// the sentence a person reads. A quota keeps the wording it always had.
6532fn record_handover(
6533    state: &mut RunState,
6534    node: &str,
6535    seat: &str,
6536    from: &str,
6537    to: &str,
6538    class: &FailClass,
6539    reason: &str,
6540) {
6541    let message = if *class == FailClass::Quota {
6542        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
6543    } else {
6544        format!("{seat}: handed over {from} -> {to} ({reason})")
6545    };
6546    state.event(node, message);
6547    state.handovers.push(Handover {
6548        at: Timestamp::now(),
6549        node: node.to_owned(),
6550        seat: seat.to_owned(),
6551        from: from.to_owned(),
6552        to: to.to_owned(),
6553        reason: reason.to_owned(),
6554    });
6555}
6556
6557/// Did this reply report running a command whose own CLI never confirmed an
6558/// exit status?
6559///
6560/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
6561/// command *finished* (see that type's own doc), so this can only be `true`
6562/// for a command whose completion event carried no readable exit code — not
6563/// for one that simply is not mentioned at all. That is the one signal this
6564/// crate can read, from the same record `state.jobs` renders, about a reply
6565/// standing next to work its own CLI cannot vouch for finishing; it is
6566/// deliberately not a check on the exit code's *value* (a fixer legitimately
6567/// runs a command that fails mid-iteration before it succeeds) and not a
6568/// guess at a command still running in the background (which emits no event
6569/// at all, and so leaves no evidence here to find).
6570fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
6571    commands.iter().any(|c| c.exit_code.is_none())
6572}
6573
6574/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
6575/// trusted as a verified no-op — the adoption guard's own text-level half.
6576///
6577/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
6578/// timed out): a marker only earns the benefit of the doubt from a turn the
6579/// CLI itself vouches for finishing properly, the same house style
6580/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
6581/// *fix* report to for `commands`. A candidate that timed out, exited
6582/// non-zero, or left a command unconfirmed is read as the ordinary loss it
6583/// is, whatever prose it wrote — this returns `None` before it ever looks at
6584/// `text`. The remaining guards (the tree really is empty, the evidence is
6585/// non-empty) are the caller's: this only reads what the reply *claimed*.
6586fn verified_noop_claim(
6587    usable: bool,
6588    commands: &[agent::CommandEvidence],
6589    text: &str,
6590) -> Option<String> {
6591    (usable && !has_unconfirmed_command(commands))
6592        .then(|| verdict::verified_noop(text))
6593        .flatten()
6594}
6595
6596fn short(commit: &str) -> String {
6597    commit.chars().take(7).collect()
6598}
6599
6600fn make_executable(path: &Path) -> Result<()> {
6601    #[cfg(unix)]
6602    {
6603        use std::os::unix::fs::PermissionsExt as _;
6604        let mut perms = std::fs::metadata(path)?.permissions();
6605        perms.set_mode(0o755);
6606        std::fs::set_permissions(path, perms)?;
6607    }
6608    #[cfg(not(unix))]
6609    {
6610        let _ = path;
6611    }
6612    Ok(())
6613}
6614
6615/// What every seat in one batch shares: where the answers are attributed, the
6616/// prompt overlay they inherit, and the build cache they are told to use.
6617///
6618/// A struct rather than four more parameters: `wave` also needs the run's
6619/// state (to record who is answering right now) and the attempt number, and
6620/// eight positional arguments is both unreadable and a clippy error.
6621struct WaveCtx<'a> {
6622    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
6623    /// paid for it.
6624    run: &'a str,
6625    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
6626    node: &'a str,
6627    prompts: &'a Prompts,
6628    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
6629    cache: Option<&'a Path>,
6630    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
6631    /// `JobRecord::round`. `None` for every other node.
6632    round: Option<usize>,
6633    /// Carry each seat's failed-agent history across waves (the review loop
6634    /// only): start-of-round priority and handover choice read
6635    /// [`RunState::seat_history`], and every answer or failure writes it.
6636    carry_seats: bool,
6637}
6638
6639/// Run one job, honouring the parallelism budget.
6640async fn run_one(
6641    job: SeatJob,
6642    sem: Arc<Semaphore>,
6643    ctx: &WaveCtx<'_>,
6644    state: &mut RunState,
6645    attempt: usize,
6646) -> (SeatState, AgentOutcome) {
6647    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
6648        .await
6649        .pop()
6650        .expect("one job in, one result out");
6651    (seat, out)
6652}
6653
6654/// Run every job concurrently, capped by the semaphore, preserving order.
6655///
6656/// Every seat in the batch is recorded into [`RunState::active`] before the
6657/// wave starts and cleared as each answer lands, so the run's own record says
6658/// who is still being waited on rather than only who finished.
6659async fn wave(
6660    jobs: Vec<SeatJob>,
6661    sem: Arc<Semaphore>,
6662    ctx: &WaveCtx<'_>,
6663    state: &mut RunState,
6664    attempt: usize,
6665) -> Vec<(usize, SeatState, AgentOutcome)> {
6666    let WaveCtx {
6667        run,
6668        node,
6669        prompts,
6670        cache,
6671        round,
6672        carry_seats: _,
6673    } = *ctx;
6674    for job in &jobs {
6675        state.seat_started(node, &job.seat.key, job.timeout, attempt);
6676    }
6677    if let Err(e) = state.save() {
6678        // A failed persist of "who is answering right now" must not abort the
6679        // wave: the seats are already being asked, and the alternative is
6680        // losing the answers to save a status line nobody may even be
6681        // watching.
6682        tracing::warn!("could not persist in-progress seats: {e:#}");
6683    }
6684    // Hold the shared build cache's lease for the whole batch, not per job:
6685    // several candidates (an implement wave) or a fixer legitimately share
6686    // one cache concurrently within this run, and that stays untouched — a
6687    // single lease taken once for the whole wave and released once it is
6688    // done is what stops a *different* borrower (another run's own wave, its
6689    // e2e/gate, a human's `magi review`) from interleaving a build into the
6690    // same directory while this one is in flight. Best-effort, not
6691    // all-or-nothing: a wave that cannot get the lease within its own
6692    // longest job's budget still runs — an hour of paid implementer calls is
6693    // not thrown away over cache contention — but every write-allowed seat
6694    // then goes without `CARGO_TARGET_DIR` for this wave too (see the filter
6695    // below), the same fallback a read-only seat always gets, rather than
6696    // building into a directory this run was never granted. The identity
6697    // record is still invalidated below either way, so the next tracked
6698    // caller (`e2e`/`gate`) never trusts a match it cannot vouch for.
6699    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
6700    let wait_started = Instant::now();
6701    let cache_guard = if let Some(cache_dir) = cache {
6702        if jobs_had_a_writer {
6703            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
6704            let budget = jobs
6705                .iter()
6706                .map(|j| j.timeout)
6707                .max()
6708                .unwrap_or(Duration::from_secs(60));
6709            acquire_cache_lease(state, cache_dir, &owner, budget, node)
6710                .await
6711                .ok()
6712        } else {
6713            None
6714        }
6715    } else {
6716        None
6717    };
6718    // Carved out of each job's own budget, not added on top of it: a seat
6719    // that waited behind the lease must not also get its full timeout
6720    // afterward, or a run contended on the cache could double the time it
6721    // spends per wave. `saturating_sub` floors at zero rather than
6722    // wrapping - a job whose whole budget was spent waiting starts with
6723    // none left, which is the honest number, not a free minimum.
6724    let waited_for_lease = wait_started.elapsed();
6725    let mut set = tokio::task::JoinSet::new();
6726    let overlay = prompts.overlay(node);
6727    for (i, mut job) in jobs.into_iter().enumerate() {
6728        job.timeout = job.timeout.saturating_sub(waited_for_lease);
6729        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
6730        if cache.is_some() {
6731            job.prompt.push('\n');
6732            job.prompt
6733                .push_str(&prompt::build_cache_note(node, job.allow_write));
6734        }
6735        let sem = Arc::clone(&sem);
6736        let run = run.to_owned();
6737        let node = node.to_owned();
6738        // Only implementers were told about the task's attachments, so only
6739        // their seats get the directory widened for reading.
6740        let attachments = if node == "implement" {
6741            state.attachments.clone()
6742        } else {
6743            Vec::new()
6744        };
6745        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
6746        // `prompt::build_cache_note`'s doc for why setting it anyway is
6747        // exactly how a sandboxed reviewer's write refusal got reported as a
6748        // defect in the patch, not a property of its own seat. And a
6749        // write-allowed one is handed it only when the lease above was
6750        // actually acquired: a wave that could not get it (`cache_guard` is
6751        // `None`, see its own comment) must not send seats to build into a
6752        // directory this run does not hold - that is the exact concurrent,
6753        // unmanaged-write race this module exists to prevent, not something
6754        // "proceeding anyway" is allowed to reintroduce.
6755        let cache = cache
6756            .filter(|_| job.allow_write && cache_guard.is_some())
6757            .map(Path::to_path_buf);
6758        set.spawn(async move {
6759            let _permit = sem.acquire().await;
6760            let mut seat = job.seat;
6761            let out = agent::invoke(
6762                &job.spec,
6763                &mut seat,
6764                &Invocation {
6765                    cwd: &job.cwd,
6766                    prompt: &job.prompt,
6767                    timeout: job.timeout,
6768                    allow_write: job.allow_write,
6769                    sessions: job.sessions,
6770                    artifacts: &job.artifacts,
6771                    stem: &job.stem,
6772                    run: &run,
6773                    node: &node,
6774                    cache_dir: cache.as_deref(),
6775                    attachments: &attachments,
6776                    writable: &[],
6777                },
6778            )
6779            .await;
6780            let out = match out {
6781                Ok(o) if o.usable() => AgentOutcome::Ok(o),
6782                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
6783                // Billed work the CLI failed to hand over is not an ordinary
6784                // failure, but its text is the CLI's raw error JSON, not an
6785                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
6786                // read it as one by forgetting to check. `usable()` is always
6787                // false here (dropped implies an empty response), so this has
6788                // to be checked before the catch-all `Failed` below or the
6789                // one shape this exists for is lost with the rest.
6790                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
6791                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
6792                Ok(o) => AgentOutcome::Failed(format!(
6793                    "exited with {:?} and no usable output",
6794                    o.exit_code
6795                )),
6796                Err(e) => AgentOutcome::Failed(e.to_string()),
6797            };
6798            (i, seat, out)
6799        });
6800    }
6801    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
6802    while let Some(joined) = set.join_next().await {
6803        let (i, seat, out) = match joined {
6804            Ok(v) => v,
6805            // No seat to clear: a panicked task never reported which one it
6806            // was. The defensive sweep below this loop is what stops that
6807            // seat's `active` entry from surviving forever.
6808            Err(e) => {
6809                tracing::error!("agent task panicked: {e}");
6810                continue;
6811            }
6812        };
6813        state.seat_finished(&seat.key);
6814        record_jobs(state, node, round, &seat.key, &out);
6815        if let Err(e) = state.save() {
6816            tracing::warn!("could not persist a seat's completion: {e:#}");
6817        }
6818        if collected.len() <= i {
6819            collected.resize_with(i + 1, || None);
6820        }
6821        collected[i] = Some((i, seat, out));
6822    }
6823    // Belt-and-braces for the panic branch above: every seat this exact batch
6824    // started shares this `(node, attempt)` pair, and every seat that finished
6825    // normally already cleared itself, so anything left tagged with it here
6826    // can only be a panicked task's leftover. Cleared unconditionally rather
6827    // than left to read as still answering forever.
6828    if state
6829        .active
6830        .values()
6831        .any(|a| a.node == node && a.attempt == attempt)
6832    {
6833        state
6834            .active
6835            .retain(|_, a| !(a.node == node && a.attempt == attempt));
6836        if let Err(e) = state.save() {
6837            tracing::warn!("could not persist the end of a wave: {e:#}");
6838        }
6839    }
6840    // Whether or not the lease above was actually held, several worktrees
6841    // may just have built into the cache with nothing here able to name one
6842    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
6843    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
6844    // clean it might not have strictly needed; trusting a stale match would
6845    // cost it a wrong answer.
6846    if let Some(cache_dir) = cache
6847        && jobs_had_a_writer
6848    {
6849        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
6850    }
6851    if let Some(guard) = cache_guard {
6852        guard.release();
6853    }
6854    collected.into_iter().flatten().collect()
6855}
6856
6857/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
6858/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
6859/// this is data collection, not the fix-specific completion contract in
6860/// [`Runner::continue_fix_report`], and applies regardless of which node
6861/// asked.
6862///
6863/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
6864/// evidence from; `Failed` does not, and correctly contributes nothing — a
6865/// timeout or crash is not itself evidence about a command the seat may have
6866/// started.
6867fn record_jobs(
6868    state: &mut RunState,
6869    node: &str,
6870    round: Option<usize>,
6871    seat: &str,
6872    out: &AgentOutcome,
6873) {
6874    let commands: &[agent::CommandEvidence] = match out {
6875        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
6876        AgentOutcome::Failed(_) => &[],
6877    };
6878    let checked_at = Timestamp::now();
6879    for c in commands {
6880        state.jobs.push(JobRecord {
6881            node: node.to_owned(),
6882            round,
6883            seat: seat.to_owned(),
6884            id: c.id.clone(),
6885            description: c.description.clone(),
6886            checked_at,
6887            status: match c.exit_code {
6888                Some(0) => JobStatus::Completed,
6889                Some(_) => JobStatus::Failed,
6890                None => JobStatus::Unknown,
6891            },
6892            exit_code: c.exit_code,
6893            result_summary: c.result_summary.clone(),
6894            source: c.source.clone(),
6895        });
6896    }
6897}
6898
6899/// Is a review round clean, given how many reviewer seats answered against
6900/// how many the round expected?
6901///
6902/// A seat that never answered (timeout, crash, unparsable output) is not a
6903/// seat that read the patch and found nothing — treating it as such is
6904/// exactly the bug this function exists to close. Under the default `block`
6905/// policy a missing seat can never be clean; `warn` still requires the seats
6906/// that *did* answer to have found nothing blocking and verification to be
6907/// green.
6908///
6909/// `quota_missing` narrows that `block` default for exactly one cause of
6910/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
6911/// a session limit lifts by the very next round buys nothing — the seat is
6912/// asked again with the same quota — so once every missing seat is accounted
6913/// for by a quota loss (and at least one seat *did* answer, so a decision has
6914/// something to rest on) the round is decided on the panel that could answer,
6915/// same as `warn` would. A panel that lost every seat to quota is not
6916/// decided here: `answered == 0` falls through to the existing `block`
6917/// fallback so a fully collapsed panel still waits rather than landing on no
6918/// review at all.
6919fn round_is_clean(
6920    blocking: usize,
6921    e2e_ok: bool,
6922    answered: usize,
6923    expected: usize,
6924    quota_missing: usize,
6925    policy: IncompleteReviewPolicy,
6926) -> bool {
6927    if blocking != 0 || !e2e_ok {
6928        return false;
6929    }
6930    if answered == expected || policy == IncompleteReviewPolicy::Warn {
6931        return true;
6932    }
6933    answered > 0 && expected - answered <= quota_missing
6934}
6935
6936/// The review loop's own conclusion, derived entirely from its persisted
6937/// round records and the round budget that produced them — never from
6938/// `status`, so a reentry (or `gate`/`merge` reading it independently)
6939/// recomputes the identical answer regardless of what an earlier node in the
6940/// same walk, or a previous walk, did to `status`.
6941///
6942/// `None` while more rounds remain to try, including when review never ran
6943/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
6944/// gone clean, or the budget is spent, or the tree has stopped moving (see
6945/// [`STAGNANT_LIMIT`]), the answer is one of two things:
6946///
6947/// - An incomplete panel that raised nothing is missing input, not a
6948///   verified tree — never a hand-off candidate, whatever verification said
6949///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
6950/// - Otherwise, green e2e on the last round hands off (see
6951///   [`Runner::stop_reviewing`]); red e2e blocks.
6952///
6953/// A last round whose own verification is still `ResourceBlocked` — magi
6954/// itself never got a command to run, not evidence the patch is broken —
6955/// is neither: this returns `None` for it too, the same as "more rounds
6956/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
6957/// handling of that shape) instead of this cheap recomputation guessing a
6958/// verdict a real attempt never produced.
6959fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
6960    if max_rounds == 0 || reviews.iter().any(|r| r.clean) {
6961        return Some(RunStatus::Gating);
6962    }
6963    let last = reviews.last()?;
6964    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
6965    if reviews.len() < max_rounds && !stagnant {
6966        return None;
6967    }
6968    if last.incomplete() && last.blocking == 0 {
6969        return Some(RunStatus::Blocked);
6970    }
6971    if last.e2e_status() == E2eStatus::ResourceBlocked {
6972        return None;
6973    }
6974    Some(if last.e2e.iter().all(CommandOutcome::ok) {
6975        RunStatus::Gating
6976    } else {
6977        RunStatus::Blocked
6978    })
6979}
6980
6981/// How long a re-ask may take, given the budget the first attempt had.
6982///
6983/// A `nudged` retry is a request to restate an answer the seat has already
6984/// worked out: it carries no new work, so it does not deserve the original
6985/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
6986/// 133 seconds while a third sat for over ten minutes on a resumed session
6987/// holding 410 KB of prior output - and because the retry had inherited the
6988/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
6989/// judging round whose other seats were long finished.
6990///
6991/// A quarter of the budget, with a floor so that a deliberately short timeout
6992/// does not collapse to nothing. A retry that re-sends the whole prompt
6993/// (because the seat kept no context) is the original job again, and keeps the
6994/// original budget.
6995fn retry_budget(full: Duration, nudged: bool) -> Duration {
6996    if nudged {
6997        (full / 4).max(Duration::from_secs(120)).min(full)
6998    } else {
6999        full
7000    }
7001}
7002
7003/// Run a wave and parse each reply, re-asking the seats whose reply was
7004/// unusable.
7005///
7006/// The re-ask is a nudge rather than the whole prompt again when the seat still
7007/// holds its conversation, which is the difference between a cheap retry and
7008/// paying for the entire candidate set twice.
7009///
7010/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
7011/// successor in `roster` is handed to it instead of being re-asked: the
7012/// handover is the retry. A seat with no successor left (a single-agent
7013/// roster, the roster's tail) is nudged as before, up to `retries` times. So
7014/// the asks to one seat in one node number at most
7015/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
7016/// is asked once (a dropped stream is nudged first), and only the last agent
7017/// of the chain gets the `retries` same-agent nudges. Each roster agent is
7018/// tried at most once per seat, walking forward from the seat's own position and never wrapping
7019/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
7020/// other failure stops the chain when the previous agent failed the same way
7021/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
7022/// [`has_context`] is false and the job's own full prompt and full budget are
7023/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
7024/// intermediate ones are not losses) and is returned as a failure like any
7025/// other absent seat — the caller decides whether the panel still has a
7026/// quorum. An empty `roster` disables handover: failures are nudged as they
7027/// always were, and a quota is simply lost. A reply that fails to parse or
7028/// validate is the prompt's doing and is only ever nudged, never handed over.
7029///
7030/// The returned [`SeatState`] names the agent that answered (or tried last).
7031#[allow(clippy::too_many_arguments)]
7032async fn ask_json_wave<T>(
7033    jobs: Vec<SeatJob>,
7034    sem: Arc<Semaphore>,
7035    retries: usize,
7036    roster: &[AgentSpec],
7037    ctx: &WaveCtx<'_>,
7038    losses: &mut Vec<QuotaLoss>,
7039    state: &mut RunState,
7040    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
7041) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
7042where
7043    T: serde::de::DeserializeOwned + Send + 'static,
7044{
7045    ask_wave_with(
7046        jobs,
7047        sem,
7048        retries,
7049        roster,
7050        ctx,
7051        losses,
7052        state,
7053        &|text: &str| {
7054            let v = verdict::extract_json::<T>(text)?;
7055            validate(&v)?;
7056            Ok(v)
7057        },
7058    )
7059    .await
7060}
7061
7062/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
7063/// a node whose answer is prose (deliberation) shares the same handover,
7064/// failure classification, quota bookkeeping and bounds instead of a copy.
7065///
7066/// A seat handed to another roster agent is sent the job's `handover` prompt
7067/// (when it has one) rather than `prompt`: the new agent has no session, so a
7068/// resume-style prompt would be incomplete. That holds for the handover ask
7069/// and for every nudge to that agent whose `has_context` is false.
7070#[allow(clippy::too_many_arguments)]
7071async fn ask_wave_with<T>(
7072    jobs: Vec<SeatJob>,
7073    sem: Arc<Semaphore>,
7074    retries: usize,
7075    roster: &[AgentSpec],
7076    ctx: &WaveCtx<'_>,
7077    losses: &mut Vec<QuotaLoss>,
7078    state: &mut RunState,
7079    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
7080) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
7081where
7082    T: Send + 'static,
7083{
7084    let n = jobs.len();
7085    let originals: Vec<SeatJob> = jobs;
7086    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
7087    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
7088    // Nudges each seat's *current* agent has taken — 0 for a first-ask
7089    // answer, N once it has gone through N nudges. Read back once this
7090    // returns, so a caller building a history record (`ReviewRecord`) can
7091    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
7092    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
7093    // field's own doc.
7094    let mut nudges: Vec<usize> = vec![0; n];
7095    // The agent now occupying each seat, the ids it has already been through,
7096    // where in the roster the walk began, the class of the last failure, and
7097    // the stem word of a handover not yet asked (full prompt, full budget).
7098    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
7099    let mut tried: Vec<BTreeSet<String>> = specs
7100        .iter()
7101        .map(|s| BTreeSet::from([s.id.clone()]))
7102        .collect();
7103    let starts: Vec<usize> = specs
7104        .iter()
7105        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
7106        .collect();
7107    let carry = ctx.carry_seats && !roster.is_empty();
7108    // Carried across rounds: ids that failed the seat earlier, and how the
7109    // last failure went (so a repeat of it is not handed over again).
7110    let carried: Vec<BTreeSet<String>> = originals
7111        .iter()
7112        .map(|j| {
7113            state
7114                .seat_history
7115                .get(&j.seat.key)
7116                .filter(|_| carry)
7117                .map(|h| h.failed.clone())
7118                .unwrap_or_default()
7119        })
7120        .collect();
7121    let mut prev: Vec<Option<FailClass>> = originals
7122        .iter()
7123        .map(|j| {
7124            state
7125                .seat_history
7126                .get(&j.seat.key)
7127                .filter(|_| carry)
7128                .and_then(|h| h.last_fail.clone())
7129        })
7130        .collect();
7131    let next_agent = |i: usize, tried: &BTreeSet<String>| -> Option<AgentSpec> {
7132        if carry {
7133            next_for_seat(roster, starts[i], tried, &carried[i]).cloned()
7134        } else {
7135            next_untried_in_roster(roster, starts[i], tried).cloned()
7136        }
7137    };
7138    let mut fresh: Vec<Option<String>> = vec![None; n];
7139    let mut last_quota: Vec<Option<Option<String>>> = vec![None; n];
7140    let mut pending: Vec<usize> = (0..n).collect();
7141
7142    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
7143    // asks: an agent with a successor is asked once and handed over, and only
7144    // a seat with no successor spends `retries` nudges on the same agent. This
7145    // only guarantees the loop's own termination whatever those say.
7146    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
7147    for round in 0..max_rounds {
7148        if pending.is_empty() {
7149            break;
7150        }
7151        let mut batch = Vec::with_capacity(pending.len());
7152        let mut renudged: Vec<&str> = Vec::new();
7153        for &i in &pending {
7154            let src = &originals[i];
7155            // A seat now held by another agent than the job named has no
7156            // session of its own: it gets the full-context prompt whenever
7157            // it is asked in full (the handover ask, a nudge it cannot
7158            // resume).
7159            let full: &str = match &src.handover {
7160                Some(h) if specs[i].id != src.spec.id => h,
7161                _ => &src.prompt,
7162            };
7163            // The prompt and the budget are one decision: a nudge restates
7164            // finished work, a re-sent prompt redoes it.
7165            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
7166                (
7167                    full.to_owned(),
7168                    src.timeout,
7169                    format!("{}-{word}-{}", src.stem, specs[i].id),
7170                )
7171            } else if nudges[i] == 0 {
7172                (full.to_owned(), src.timeout, src.stem.clone())
7173            } else {
7174                renudged.push(src.seat.key.as_str());
7175                let why = done[i]
7176                    .as_ref()
7177                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
7178                    .unwrap_or_else(|| "no parsable answer".to_owned());
7179                let nudge = prompt::nudge(&why);
7180                let nudged = has_context(&specs[i], &seats[i], src.sessions);
7181                let prompt = if nudged {
7182                    nudge
7183                } else {
7184                    format!("{full}\n\n---\n\n{nudge}")
7185                };
7186                (
7187                    prompt,
7188                    retry_budget(src.timeout, nudged),
7189                    format!("{}-retry{}", src.stem, nudges[i]),
7190                )
7191            };
7192            batch.push(SeatJob {
7193                spec: specs[i].clone(),
7194                seat: seats[i].clone(),
7195                cwd: src.cwd.clone(),
7196                prompt,
7197                timeout,
7198                allow_write: src.allow_write,
7199                sessions: src.sessions,
7200                artifacts: src.artifacts.clone(),
7201                stem,
7202                handover: None,
7203            });
7204        }
7205
7206        if !renudged.is_empty() {
7207            state.event(
7208                ctx.node,
7209                format!("retry {round}: re-asking {}", renudged.join(", ")),
7210            );
7211        }
7212        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
7213        let mut still = Vec::new();
7214        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
7215            seats[i] = seat;
7216            let class = FailClass::of(&out);
7217            // A dropped stream is nudged first (the conversation is still
7218            // there to pick up); only a seat whose nudges are spent hands over.
7219            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
7220                && nudges[i] < retries
7221                && !roster.is_empty();
7222            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
7223                let next = should_hand_over(prev[i].as_ref(), &cur)
7224                    .then(|| next_agent(i, &tried[i]))
7225                    .flatten();
7226                if carry {
7227                    let h = state
7228                        .seat_history
7229                        .entry(originals[i].seat.key.clone())
7230                        .or_default();
7231                    h.failed.insert(specs[i].id.clone());
7232                    h.last_fail = Some(cur.clone());
7233                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
7234                        h.last_ok = None;
7235                    }
7236                    // Saved before the next agent is asked, so a restart in
7237                    // between does not forget who failed.
7238                    if let Err(e) = state.save() {
7239                        tracing::warn!("could not persist a seat's failure history: {e:#}");
7240                    }
7241                }
7242                if let Some(next) = next {
7243                    record_handover(
7244                        state,
7245                        ctx.node,
7246                        &originals[i].seat.key,
7247                        &specs[i].id,
7248                        &next.id,
7249                        &cur,
7250                        &fail_reason(&out),
7251                    );
7252                    tried[i].insert(next.id.clone());
7253                    prev[i] = Some(cur.clone());
7254                    seats[i] =
7255                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
7256                    specs[i] = next;
7257                    fresh[i] = Some(cur.stem_word().to_owned());
7258                    nudges[i] = 0;
7259                    done[i] = Some(Err(anyhow::anyhow!(
7260                        "handed over after: {}",
7261                        fail_reason(&out)
7262                    )));
7263                    still.push(i);
7264                    continue;
7265                }
7266            }
7267            if carry
7268                && !nudge_first
7269                && let Some(cur) = class.clone()
7270            {
7271                // The chain ended here (no successor, or a repeated failure).
7272                let h = state
7273                    .seat_history
7274                    .entry(originals[i].seat.key.clone())
7275                    .or_default();
7276                h.failed.insert(specs[i].id.clone());
7277                h.last_fail = Some(cur);
7278            }
7279            let parsed = match out {
7280                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
7281                AgentOutcome::Quota(o) => {
7282                    last_quota[i] = Some(o.quota.as_ref().and_then(|q| q.reset.clone()));
7283                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
7284                }
7285                // Not a parseable answer: the nudge loop re-asks it, which is
7286                // exactly what a dropped stream needs. Just don't hand its raw
7287                // error JSON to `extract_json`.
7288                AgentOutcome::Dropped(o) => {
7289                    let why = o
7290                        .dropped
7291                        .as_ref()
7292                        .map(|d| d.why.as_str())
7293                        .unwrap_or("the CLI ended the stream without delivering its answer");
7294                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
7295                }
7296                AgentOutcome::Failed(e) => Err(anyhow::anyhow!(e)),
7297            };
7298            let quota = class == Some(FailClass::Quota);
7299            let failed = parsed.is_err();
7300            done[i] = Some(parsed);
7301            if carry && !failed {
7302                let h = state
7303                    .seat_history
7304                    .entry(originals[i].seat.key.clone())
7305                    .or_default();
7306                h.failed.remove(&specs[i].id);
7307                h.last_ok = Some(specs[i].id.clone());
7308                h.last_fail = None;
7309            }
7310            // Do not re-ask a rate-limited seat (quota) — a retry is known to
7311            // fail the same way; and never re-ask a seat that already parsed.
7312            // A failed agent that still has a successor is not re-asked
7313            // either: the handover was its remedy and has just been refused
7314            // (the chain stops on a repeated failure class). A seat with no
7315            // successor left (a single-agent roster, the roster's tail, or an
7316            // empty roster) keeps the same-agent nudge, bounded by `retries`.
7317            let agent_failure = class.is_some()
7318                && !nudge_first
7319                && !roster.is_empty()
7320                && next_agent(i, &tried[i]).is_some();
7321            if failed && !quota && !agent_failure && nudges[i] < retries {
7322                nudges[i] += 1;
7323                still.push(i);
7324            }
7325        }
7326        pending = still;
7327    }
7328
7329    // One loss per seat whose chain ended on a quota: the intermediate ones
7330    // were absorbed by a handover and are not losses.
7331    for (i, q) in last_quota.into_iter().enumerate() {
7332        if let Some(reset) = q {
7333            losses.push(QuotaLoss {
7334                seat: originals[i].seat.key.clone(),
7335                node: ctx.node.to_owned(),
7336                at: Timestamp::now(),
7337                reset,
7338            });
7339        }
7340    }
7341
7342    seats
7343        .into_iter()
7344        .zip(done)
7345        .zip(nudges)
7346        .map(|((seat, res), attempts)| {
7347            (
7348                seat,
7349                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
7350                attempts,
7351            )
7352        })
7353        .collect()
7354}
7355
7356/// Acquire the shared build cache's lease, waiting out contention within
7357/// `budget` (never past it — see AGENTS.md's build-cache section on why an
7358/// unbounded wait is never acceptable).
7359///
7360/// A first, non-blocking check happens before ever waiting; if it finds the
7361/// lease busy, that fact is logged as a `verify` event *and* flushed with
7362/// [`RunState::save`] immediately — not only once the wait finally succeeds
7363/// or gives up — so a `magi show` run by a different process while this one
7364/// is still waiting reads a `run.json` that says so, rather than whatever it
7365/// looked like before the wait started. The same applies to the terminal
7366/// failure: logged and saved before this returns `Err`, so a caller that
7367/// could not get the lease at all still leaves a legible record of why.
7368async fn acquire_cache_lease(
7369    state: &mut RunState,
7370    cache_dir: &Path,
7371    owner: &crate::cache::Owner,
7372    budget: Duration,
7373    context: &str,
7374) -> Result<crate::cache::Guard> {
7375    let home = crate::run::home();
7376    let started = Instant::now();
7377    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
7378        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(g),
7379        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
7380        Err(e) => {
7381            state.event(
7382                "verify",
7383                format!("{context}: could not check the shared build cache: {e:#}"),
7384            );
7385            if let Err(e2) = state.save() {
7386                tracing::warn!("could not persist a cache-check failure: {e2:#}");
7387            }
7388            return Err(e);
7389        }
7390    };
7391    state.event(
7392        "verify",
7393        format!(
7394            "{context}: waiting for the shared build cache at {} ({})",
7395            cache_dir.display(),
7396            busy.describe()
7397        ),
7398    );
7399    if let Err(e) = state.save() {
7400        tracing::warn!("could not persist a cache wait: {e:#}");
7401    }
7402    let remaining = budget.saturating_sub(started.elapsed());
7403    match crate::cache::wait_for(&home, cache_dir, owner, remaining, Duration::from_secs(5)).await {
7404        Ok(g) => Ok(g),
7405        Err(e) => {
7406            state.event("verify", format!("{context}: {e:#}"));
7407            if let Err(e2) = state.save() {
7408                tracing::warn!("could not persist a cache wait timeout: {e2:#}");
7409            }
7410            Err(e)
7411        }
7412    }
7413}
7414
7415/// Run `body` — a verify command batch — while holding the shared build
7416/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
7417/// never interleave with another borrower's build against the same
7418/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
7419/// timeout, or a human's own `magi review`. See the `cache` module doc for
7420/// why this matters more than Cargo's own per-target locking covers — two
7421/// *different* worktrees building the same package name/version into one
7422/// cache directory is a staleness bug, not a lock contention one.
7423///
7424/// The wait for the lease is carved out of `budget`, never on top of it —
7425/// `body` is handed whatever is left, so a caller's own node timeout is the
7426/// only clock involved, exactly what AGENTS.md's build-cache section asks
7427/// for ("never an unbounded wait"). When `cache_dir` is `None` — no shared
7428/// cache configured at all — this is a pass-through: `body` runs with the
7429/// full budget and nothing is leased.
7430///
7431/// A lease that cannot be acquired within `budget` is reported as a single
7432/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
7433/// verification — the same shape a spawn failure already takes in
7434/// [`run_commands`], so a caller need not special-case it.
7435#[allow(clippy::too_many_arguments)]
7436async fn with_cache_lease<'s, F, Fut>(
7437    state: &'s mut RunState,
7438    cache_dir: Option<&Path>,
7439    node: &str,
7440    seat: &str,
7441    worktree: &Path,
7442    head: &str,
7443    budget: Duration,
7444    context: &str,
7445    body: F,
7446) -> (Vec<CommandOutcome>, bool)
7447where
7448    F: FnOnce(&'s mut RunState, Duration) -> Fut,
7449    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
7450{
7451    let Some(cache_dir) = cache_dir else {
7452        let (outcomes, retried, _timed_out_pids) = body(state, budget).await;
7453        return (outcomes, retried);
7454    };
7455    let home = crate::run::home();
7456    let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
7457    let started = Instant::now();
7458    let guard = match acquire_cache_lease(state, cache_dir, &owner, budget, context).await {
7459        Ok(g) => g,
7460        Err(e) => {
7461            return (
7462                vec![CommandOutcome {
7463                    command: "(waiting for the shared build cache)".to_owned(),
7464                    code: None,
7465                    output_tail: e.to_string(),
7466                    duration_ms: started.elapsed().as_millis() as u64,
7467                    resource_blocked: true,
7468                }],
7469                false,
7470            );
7471        }
7472    };
7473    let identity = crate::cache::Identity::new(worktree, head);
7474    if let Err(e) = crate::cache::ensure_fresh(&home, cache_dir, &identity) {
7475        // A failed freshness check means this process cannot vouch for what
7476        // is sitting in the cache right now - on Windows this is exactly the
7477        // "a stale test executable is still locked, `cargo clean -p` cannot
7478        // remove it" case the evidence log records. Running verify anyway
7479        // and reporting whatever it says would let a result nobody can trust
7480        // stand for the tree it claims to have checked; fail the step
7481        // instead of the patch.
7482        state.event(
7483            "verify",
7484            format!(
7485                "{context}: could not confirm the shared build cache matches {} at {}: {e:#}",
7486                worktree.display(),
7487                short(head)
7488            ),
7489        );
7490        guard.release();
7491        return (
7492            vec![CommandOutcome {
7493                command: "(confirming the shared build cache is fresh)".to_owned(),
7494                code: None,
7495                output_tail: e.to_string(),
7496                duration_ms: started.elapsed().as_millis() as u64,
7497                resource_blocked: true,
7498            }],
7499            false,
7500        );
7501    }
7502    let remaining = budget.saturating_sub(started.elapsed());
7503    let (outcomes, retried, timed_out_pids) = body(state, remaining).await;
7504    // A timed-out command's process was only *asked* to die (`kill_on_drop`,
7505    // `start_kill`); confirm it actually has before handing the directory to
7506    // the next acquirer. See `wait_for_timed_out_children_to_die`'s own doc
7507    // for what this can and cannot see.
7508    if !timed_out_pids.is_empty() {
7509        wait_for_timed_out_children_to_die(&timed_out_pids).await;
7510    }
7511    guard.release();
7512    (outcomes, retried)
7513}
7514
7515/// Poll `pids` — commands [`run_commands`] reports as still running when its
7516/// own timeout elapsed — until every one is confirmed gone, or
7517/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
7518///
7519/// Real confirmation where confirmation is possible, not a substitute for
7520/// full process-tree observation: a grandchild the timed-out process spawned
7521/// and that survives independently of it is invisible to a pid check the
7522/// same way it always was, and continuing to observe and collect *that*
7523/// stays a different piece of work with its own owner. This only narrows a
7524/// fixed blind wait into an actual check of the pids this process does know
7525/// about.
7526async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
7527    wait_for_pids_with(
7528        pids,
7529        crate::proc::pid_alive,
7530        LEASE_RELEASE_POLL,
7531        LEASE_RELEASE_MAX_WAIT,
7532    )
7533    .await;
7534}
7535
7536/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
7537/// interval and ceiling supplied by the caller, so the polling *logic* -
7538/// returns as soon as every pid reports dead, gives up at the ceiling
7539/// otherwise - is testable on millisecond durations without asking the real
7540/// OS about a pid at all.
7541async fn wait_for_pids_with<F: Fn(u32) -> bool>(
7542    pids: &[u32],
7543    alive: F,
7544    poll: Duration,
7545    max_wait: Duration,
7546) {
7547    let deadline = Instant::now() + max_wait;
7548    loop {
7549        if pids.iter().all(|&pid| !alive(pid)) {
7550            return;
7551        }
7552        if Instant::now() >= deadline {
7553            return;
7554        }
7555        tokio::time::sleep(poll).await;
7556    }
7557}
7558
7559/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
7560/// admission that it could not even get a verify command to run, as opposed
7561/// to evidence the command actually produced? A caller that would otherwise
7562/// read a resource-blocked outcome as a red command must check this first:
7563/// see [`Runner::gate`], which retries rather than records `Blocked` when
7564/// this is true.
7565fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
7566    outcomes.iter().any(|o| o.resource_blocked)
7567}
7568
7569/// What [`Runner::gate_fix_round`] decided.
7570enum GateFix {
7571    /// The tree changed and `verify.e2e` is still green: run the gate again.
7572    Retry,
7573    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
7574    /// last failure stands and the run ends blocked.
7575    Stop,
7576    /// `verify.e2e` could not run after the fix (magi's own contention):
7577    /// decide nothing now, a later reentry retries.
7578    Defer,
7579}
7580
7581/// Is every red command in `outcomes` an ordinary failure the code could
7582/// explain: it ran, exited non-zero, and said something?
7583///
7584/// A timeout, a spawn failure and a killed process all leave `code` `None`;
7585/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
7586/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
7587/// what the command is stays the gate's business.
7588fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
7589    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
7590    red.peek().is_some()
7591        && red.all(|o| {
7592            !o.resource_blocked
7593                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
7594                && !o.output_tail.trim().is_empty()
7595        })
7596}
7597
7598/// Describe one verify command's outcome for the event log, distinguishing a
7599/// build/link failure — the toolchain never produced a binary to run — from
7600/// an actual test failure, since only the latter is a verdict on the patch.
7601fn e2e_outcome_label(o: &CommandOutcome) -> String {
7602    if o.ok() {
7603        return "pass".to_owned();
7604    }
7605    let reason = if o.build_failed() {
7606        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
7607    } else {
7608        format!("FAIL ({:?})", o.code)
7609    };
7610    format!("{reason}\n{}", tail(&o.output_tail, EVENT_OUTPUT_TAIL))
7611}
7612
7613/// Run `verify.e2e`, retrying once if the first attempt could not build or
7614/// link — a build/link failure is frequently a race against a shared
7615/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
7616/// `verify` event per command, tagged with `context` (normally `"round N"`)
7617/// so the two call sites that need this — the ordinary per-round leg in
7618/// `review_loop`, and the deferred catch-up run `stop_reviewing` makes before
7619/// it will ever call a round green — read identically in the event log.
7620async fn run_e2e_with_retry(
7621    state: &mut RunState,
7622    shell: &[String],
7623    commands: &[String],
7624    worktree: &Path,
7625    timeout: Duration,
7626    context: &str,
7627) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
7628    let (mut e2e, mut timed_out_pids) = run_commands(
7629        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
7630    )
7631    .await;
7632    for o in &e2e {
7633        state.event(
7634            "verify",
7635            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
7636        );
7637    }
7638    // A build/link failure is not a verdict on the patch — it is frequently a
7639    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
7640    // one retry before letting a red like that decide the round.
7641    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
7642    if verify_retried {
7643        state.event(
7644            "verify",
7645            format!(
7646                "{context}: verify could not build/link, not a test result — retrying once \
7647                 before concluding"
7648            ),
7649        );
7650        let retried = run_commands(
7651            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
7652        )
7653        .await;
7654        e2e = retried.0;
7655        // Both attempts' timeouts matter, not just the last one: the first
7656        // attempt's descendants may still be alive alongside the retry's.
7657        timed_out_pids.extend(retried.1);
7658        for o in &e2e {
7659            state.event(
7660                "verify",
7661                format!(
7662                    "{context}: retry `{}` -> {}",
7663                    o.command,
7664                    e2e_outcome_label(o)
7665                ),
7666            );
7667        }
7668    }
7669    (e2e, verify_retried, timed_out_pids)
7670}
7671
7672/// Run configured shell commands in `cwd`, in order. The second element is
7673/// the pid of every command that hit `timeout` and was still running when
7674/// this stopped waiting on it (best-effort: `None` when the platform did not
7675/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
7676/// that releases a shared resource afterward needs to know.
7677///
7678/// Records `task` into [`RunState::active`] at every command boundary
7679/// (`RunState::task_command`) and clears it once the whole list has run
7680/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
7681/// for minutes with no seat and no output of its own to show for it (see
7682/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
7683/// apart from "not yet run" without this), and this is the only place that
7684/// knows which command is running right now and how many are left. Three
7685/// saves per command — start, not per second — matching the same "only at a
7686/// boundary" rule [`wave`] already follows for seats.
7687#[allow(clippy::too_many_arguments)]
7688async fn run_commands(
7689    state: &mut RunState,
7690    node: &str,
7691    task: &str,
7692    attempt: usize,
7693    shell: &[String],
7694    commands: &[String],
7695    cwd: &Path,
7696    timeout: Duration,
7697) -> (Vec<CommandOutcome>, Vec<u32>) {
7698    if commands.is_empty() {
7699        // Nothing to mark as running and nothing to clear — an empty list
7700        // means "not configured", and touching `active` (or the disk) over
7701        // that would be a write for every round of a repo with no
7702        // `verify.e2e` / `verify.gate` commands at all.
7703        return (Vec::new(), Vec::new());
7704    }
7705    let mut out = Vec::new();
7706    let mut timed_out_pids = Vec::new();
7707    let total = commands.len();
7708    for (idx, command) in commands.iter().enumerate() {
7709        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
7710        if let Err(e) = state.save() {
7711            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
7712        }
7713        let started = Instant::now();
7714        let mut cmd = tokio::process::Command::new(&shell[0]);
7715        cmd.quiet();
7716        cmd.args(&shell[1..])
7717            .arg(command)
7718            .current_dir(cwd)
7719            .stdin(std::process::Stdio::null())
7720            .stdout(std::process::Stdio::piped())
7721            .stderr(std::process::Stdio::piped())
7722            .kill_on_drop(true);
7723        let spawned = cmd.spawn();
7724        let (code, body) = match spawned {
7725            Ok(child) => {
7726                // Captured before the child is consumed below: `kill_on_drop`
7727                // only *asks* the process to die when the timeout branch
7728                // drops it, and the pid is the only way anyone downstream can
7729                // later check whether that request actually took.
7730                let pid = child.id();
7731                match tokio::time::timeout(timeout, child.wait_with_output()).await {
7732                    Ok(Ok(o)) => {
7733                        let mut body = String::from_utf8_lossy(&o.stdout).into_owned();
7734                        body.push_str(&String::from_utf8_lossy(&o.stderr));
7735                        (o.status.code(), body)
7736                    }
7737                    Ok(Err(e)) => (None, format!("failed to run: {e}")),
7738                    Err(_) => {
7739                        if let Some(pid) = pid {
7740                            timed_out_pids.push(pid);
7741                        }
7742                        (None, format!("timed out after {}s", timeout.as_secs()))
7743                    }
7744                }
7745            }
7746            Err(e) => (None, format!("failed to spawn `{}`: {e}", shell[0])),
7747        };
7748        out.push(CommandOutcome {
7749            command: command.clone(),
7750            code,
7751            output_tail: tail(&body, OUTPUT_TAIL),
7752            duration_ms: started.elapsed().as_millis() as u64,
7753            resource_blocked: false,
7754        });
7755    }
7756    state.task_finished(task);
7757    if let Err(e) = state.save() {
7758        tracing::warn!("could not persist the end of {task}: {e:#}");
7759    }
7760    (out, timed_out_pids)
7761}
7762
7763/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
7764/// section (`report::run`) and in the `merge` event this node records — for
7765/// the operator to run by hand.
7766///
7767/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
7768/// branch whose ruleset forbids merge commits (GitHub's "must not contain
7769/// merge commits", or "require linear history") rejects the push a `--no-ff`
7770/// merge would produce, which is exactly the guidance this function replaces.
7771/// `message`'s first line becomes the squash commit's subject, matching the
7772/// note `report::run` prints alongside this command — see that function for
7773/// why an explicit subject is not optional there.
7774fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
7775    let repo = repo.display();
7776    match style {
7777        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
7778        MergeStyle::Squash => {
7779            // The subject sits inside double quotes, and a title an agent
7780            // wrote may carry the characters that break out of them.
7781            let subject = message
7782                .lines()
7783                .next()
7784                .unwrap_or(branch)
7785                .replace(['\\', '"', '$', '`'], "");
7786            format!(
7787                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
7788            )
7789        }
7790        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
7791    }
7792}
7793
7794/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
7795/// under the hood, rejects a `title` over 256 characters and the whole
7796/// command fails — no PR at all, for a run whose body was otherwise fine
7797/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
7798/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
7799/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
7800/// this bound. It is a margin, not a guarantee — a title packed
7801/// with multi-unit characters could still in principle land close to the
7802/// edge, but a real task title's occasional emoji or accented letter fits
7803/// comfortably inside it.
7804const PR_TITLE_MAX: usize = 240;
7805
7806/// A pull request title from the opening line of `text`, or `None` when that
7807/// line is not English (GitHub text is) or has no letters.
7808///
7809/// A line within `max` is kept as is. A longer one is cut at the end of its
7810/// first sentence when that falls inside `max`, else at a word boundary with a
7811/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
7812/// make every merely-truncated title look non-English). The language check
7813/// runs on the kept text before any mark is added, so only what GitHub will
7814/// show is judged: an English opening followed by non-ASCII far past the cut
7815/// still passes.
7816fn english_title(text: &str, max: usize) -> Option<String> {
7817    let line = queue::first_line(text)?;
7818    let chars: Vec<char> = line.chars().collect();
7819    let (kept, mark) = if chars.len() <= max {
7820        (line.to_owned(), "")
7821    } else if let Some(end) = sentence_end(&chars, max) {
7822        (chars[..end].iter().collect::<String>(), "")
7823    } else {
7824        let room = max.saturating_sub(3);
7825        // Cut at the last space inside the room; when the char just past the
7826        // room is a space the room already ends on a word.
7827        let cut = if chars[room].is_whitespace() {
7828            room
7829        } else {
7830            chars[..room]
7831                .iter()
7832                .rposition(|c| c.is_whitespace())
7833                .unwrap_or(room)
7834        };
7835        let head: String = chars[..cut].iter().collect();
7836        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
7837        (head.to_owned(), "...")
7838    };
7839    if kept.is_empty() || !kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic()) {
7840        return None;
7841    }
7842    Some(format!("{kept}{mark}"))
7843}
7844
7845/// The char length of the first sentence of `chars` when it ends within `max`
7846/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
7847/// abbreviations so `e.g. foo` does not end a title early.
7848fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
7849    const MIN: usize = 20;
7850    for i in MIN..max.min(chars.len()) {
7851        if !matches!(chars[i], '.' | '!' | '?') {
7852            continue;
7853        }
7854        let Some(&next) = chars.get(i + 1) else {
7855            continue;
7856        };
7857        if !next.is_whitespace() {
7858            continue;
7859        }
7860        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
7861        if after.is_some_and(|c| c.is_ascii_lowercase()) {
7862            continue;
7863        }
7864        let word: String = chars[..i]
7865            .iter()
7866            .rev()
7867            .take_while(|c| !c.is_whitespace())
7868            .collect::<Vec<_>>()
7869            .into_iter()
7870            .rev()
7871            .collect();
7872        let word = word.to_ascii_lowercase();
7873        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
7874            continue;
7875        }
7876        let end = chars[..i]
7877            .iter()
7878            .rposition(|c| !c.is_whitespace())
7879            .map_or(i, |p| p + 1);
7880        return Some(end);
7881    }
7882    None
7883}
7884
7885/// What `merge = "pr"` (and the merge commit of the other modes) says about a
7886/// change: a title and a body describing what was *implemented*, not the task
7887/// that asked for it. A task reads as a request; a reader of the merged
7888/// history wants the change.
7889struct PrMessage {
7890    title: String,
7891    body: String,
7892}
7893
7894impl PrMessage {
7895    /// Title, blank line, body. The first line is the squash/merge commit
7896    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
7897    /// has to stay one sensible line.
7898    fn commit_message(&self) -> String {
7899        format!("{}\n\n{}", self.title, self.body)
7900    }
7901}
7902
7903/// The text after a leading `TITLE:` (any case) on `line`.
7904fn title_marker(line: &str) -> Option<&str> {
7905    let line = line.trim();
7906    let head = line.get(..6)?;
7907    head.eq_ignore_ascii_case("title:")
7908        .then(|| line[6..].trim())
7909}
7910
7911/// The implementer's own one-line title: the `TITLE:` line the implement
7912/// prompt asks for at the top of its SUMMARY. Candidate commits are all
7913/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
7914/// source, and a title that says as much is refused here too.
7915fn summary_title(summary: &str) -> Option<String> {
7916    let first = summary.lines().find(|l| !l.trim().is_empty())?;
7917    let raw = title_marker(first)?;
7918    if raw.is_empty() {
7919        return None;
7920    }
7921    let title = queue::title_from(raw, PR_TITLE_MAX);
7922    let lower = title.to_ascii_lowercase();
7923    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
7924        return None;
7925    }
7926    Some(title)
7927}
7928
7929/// How `open_review`'s instruction begins; see [`landing_title`].
7930const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
7931
7932/// Marker `open_review` gives a candidate that nothing in the roster wrote.
7933const EXISTING_BRANCH: &str = "(existing branch)";
7934
7935/// Does this run review work that already existed, rather than implement a
7936/// task? Runs recorded before `reviewed_commits` existed carry only the
7937/// candidate marker.
7938fn is_review_run(state: &RunState) -> bool {
7939    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
7940}
7941
7942/// The title of a review-only run: the subject of the oldest commit under
7943/// review. Later commits are usually fixups, and `instruction` is the review
7944/// prompt, which says nothing about the change. GitHub text is English, so a
7945/// non-ASCII or blank subject yields `None` and the caller's neutral title.
7946fn review_title(state: &RunState) -> Option<String> {
7947    english_subject(state.reviewed_commits.as_ref()?.first()?)
7948}
7949
7950/// `raw` as a pull request title, or `None` when it is blank, not English
7951/// (GitHub text is), or one of magi's own candidate commit subjects.
7952fn english_subject(raw: &str) -> Option<String> {
7953    let raw = raw.trim();
7954    if raw.is_empty() || !raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic()) {
7955        return None;
7956    }
7957    let title = queue::title_from(raw, PR_TITLE_MAX);
7958    let lower = title.to_ascii_lowercase();
7959    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
7960        return None;
7961    }
7962    Some(title)
7963}
7964
7965/// What a review-only run's branch says about itself, read at the moment the
7966/// pull request is opened.
7967#[derive(Debug, Clone, PartialEq, Eq)]
7968struct BranchFacts {
7969    /// `(subject, body)` of each commit, oldest first.
7970    commits: Vec<(String, String)>,
7971    /// Trimmed `git diff --stat`.
7972    stat: String,
7973}
7974
7975/// Longest diff stat shown: this many file lines plus the summary line.
7976const STAT_FILE_LINES: usize = 25;
7977/// Cap on the commit list, well inside GitHub's 65536-character body limit.
7978const COMMITS_MAX_CHARS: usize = 20_000;
7979
7980/// Read the commits and diff stat of `base..branch`. `None` when git cannot
7981/// say or finds nothing, so the caller falls back to what the run recorded.
7982async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
7983    let commits = git::commit_log(repo, base, branch).await.ok()?;
7984    if commits.is_empty() {
7985        return None;
7986    }
7987    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
7988    let lines: Vec<&str> = stat.lines().collect();
7989    let stat = if lines.len() > STAT_FILE_LINES + 1 {
7990        let omitted = lines.len() - 1 - STAT_FILE_LINES;
7991        let more = format!(" ... {omitted} more file(s)");
7992        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
7993        kept.push(&more);
7994        kept.push(lines[lines.len() - 1]);
7995        kept.join("\n")
7996    } else {
7997        lines.join("\n")
7998    };
7999    Some(BranchFacts { commits, stat })
8000}
8001
8002/// Defang what would break the surrounding markdown: a closing `</details>`
8003/// and a code fence.
8004fn markdown_safe(text: &str) -> String {
8005    text.replace("</details>", "&lt;/details&gt;")
8006        .replace("\x60\x60\x60", "~~~")
8007}
8008
8009fn neutral_title(state: &RunState, winner: char) -> String {
8010    format!(
8011        "chore: land candidate {} of run {}",
8012        winner.to_ascii_uppercase(),
8013        state.id
8014    )
8015}
8016
8017/// The pull request title to hand to `land::merge_subject`. A review-only run
8018/// opened by an earlier build titled its pull request with the review prompt;
8019/// that title is dropped (empty, so the fallback applies) rather than landed.
8020/// Any other title, including an operator's rename, passes through untouched,
8021/// and so does every title of a run that implements a task.
8022pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
8023    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
8024        ""
8025    } else {
8026        pr_title
8027    }
8028}
8029
8030/// What the squash subject falls back to when the pull request title is empty
8031/// or candidate-shaped: for a review-only run the derived title, never the
8032/// review prompt held in `instruction`.
8033pub fn landing_subject_source(state: &RunState) -> String {
8034    if is_review_run(state) {
8035        let winner = state.candidates.first().map_or('A', |c| c.label);
8036        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
8037    }
8038    state.instruction.clone()
8039}
8040
8041/// `summary` without its `TITLE:` line, which the pull request title already
8042/// carries.
8043fn summary_without_title(summary: &str) -> String {
8044    let mut lines = summary.trim().lines().peekable();
8045    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
8046        lines.next();
8047    }
8048    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
8049}
8050
8051/// The pull request title and body for the winning candidate.
8052///
8053/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
8054/// the task's own opening line via [`queue::title_from`] when there is none.
8055/// `state.instruction` can open with blank lines (`task_text` only rejects a
8056/// body that is blank *entirely*), which `title_from` skips.
8057///
8058/// Body: the implementer's summary and the fixer's notes, then — when the
8059/// winning review round was not clean — the findings still open and whatever
8060/// the fixer declined, so `merge = "pr"` hands the reader the same material
8061/// `magi show` does. The task follows inside a collapsed block, and the
8062/// footer repeats the run and candidate as plain tags for a reader holding
8063/// only the merged commit or the PR body.
8064#[cfg(test)]
8065fn pr_message(state: &RunState, winner: char) -> PrMessage {
8066    pr_message_with(state, winner, None)
8067}
8068
8069/// [`pr_message`] with what the branch of a review-only run says about itself.
8070/// `facts` is ignored for a run that implements a task.
8071fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
8072    let summary = state
8073        .candidates
8074        .iter()
8075        .find(|c| c.label == winner)
8076        .map(|c| c.summary.as_str())
8077        .unwrap_or_default();
8078    // The fallback is the operator's own words and may not be English; GitHub
8079    // text always is, so a non-English task gets a neutral title instead.
8080    let review = is_review_run(state);
8081    let title = if review {
8082        facts
8083            .and_then(|f| english_subject(&f.commits.first()?.0))
8084            .or_else(|| review_title(state))
8085            .or_else(|| {
8086                state
8087                    .candidates
8088                    .iter()
8089                    .find(|c| c.label == winner)
8090                    .filter(|c| !c.branch.starts_with("magi/"))
8091                    .and_then(|c| english_subject(&c.branch))
8092            })
8093            .unwrap_or_else(|| neutral_title(state, winner))
8094    } else {
8095        summary_title(summary).unwrap_or_else(|| {
8096            english_title(&state.instruction, PR_TITLE_MAX)
8097                .unwrap_or_else(|| neutral_title(state, winner))
8098        })
8099    };
8100
8101    let mut body = String::new();
8102    let what = summary_without_title(summary);
8103    if !what.is_empty() {
8104        body.push_str("## Summary\n\n");
8105        body.push_str(&what);
8106        body.push_str("\n\n");
8107    }
8108
8109    // The last round is usually a clean verification pass with no fix of its
8110    // own, so every round's notes are read, not just the final one's.
8111    let notes: Vec<(usize, &str)> = state
8112        .reviews
8113        .iter()
8114        .filter_map(|r| {
8115            let n = r.fix.as_ref()?.notes.trim();
8116            (!n.is_empty()).then_some((r.round, n))
8117        })
8118        .collect();
8119    if !notes.is_empty() {
8120        body.push_str("## Review fixes\n\n");
8121        if let [(_, only)] = notes.as_slice() {
8122            body.push_str(only);
8123            body.push_str("\n\n");
8124        } else {
8125            for (round, n) in &notes {
8126                body.push_str(&format!("### Round {round}\n\n{n}\n\n"));
8127            }
8128        }
8129    }
8130    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
8131
8132    let open = state.open_findings();
8133    if !open.is_empty() {
8134        body.push_str("## Open review findings\n\n");
8135        for f in &open {
8136            body.push_str(&format!("- `{}` [{:?}] {}\n", f.id, f.severity, f.title));
8137        }
8138        body.push('\n');
8139    }
8140
8141    if let Some(fix) = fix
8142        && !fix.rejected.is_empty()
8143    {
8144        body.push_str("## Declined by the fixer\n\n");
8145        for r in &fix.rejected {
8146            body.push_str(&format!("- `{}`: {}\n", r.id, r.why));
8147        }
8148        body.push('\n');
8149    }
8150
8151    if review {
8152        // The review prompt is not the task; list what the branch carries.
8153        body.push_str("## Commits under review\n\n");
8154        if let Some(facts) = facts {
8155            let mut left = COMMITS_MAX_CHARS;
8156            for (i, (subject, text)) in facts.commits.iter().enumerate() {
8157                let mut entry = format!("- {}\n", markdown_safe(subject));
8158                for l in markdown_safe(text).lines() {
8159                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
8160                }
8161                if left == 0 {
8162                    body.push_str(&format!(
8163                        "- ... {} more commit(s)\n",
8164                        facts.commits.len() - i
8165                    ));
8166                    break;
8167                }
8168                if entry.len() > left {
8169                    // Even the first commit is cut: one huge body must not
8170                    // push the whole description past GitHub's limit.
8171                    let mut end = left;
8172                    while !entry.is_char_boundary(end) {
8173                        end -= 1;
8174                    }
8175                    entry.truncate(end);
8176                    entry.push_str("\n  ... (truncated)\n");
8177                    left = 0;
8178                } else {
8179                    left -= entry.len();
8180                }
8181                body.push_str(&entry);
8182            }
8183            if !facts.stat.trim().is_empty() {
8184                body.push_str(&format!(
8185                    "\n## Diff stat\n\n```\n{}\n```\n",
8186                    markdown_safe(facts.stat.trim())
8187                ));
8188            }
8189        } else {
8190            match &state.reviewed_commits {
8191                Some(subjects) => {
8192                    for s in subjects {
8193                        body.push_str(&format!("- {}\n", s.trim()));
8194                    }
8195                }
8196                None => {
8197                    // An older run kept only the prompt, with the commit list
8198                    // after its first paragraph.
8199                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
8200                    body.push_str(rest.trim());
8201                    body.push('\n');
8202                }
8203            }
8204        }
8205    } else {
8206        let task = state.instruction.trim();
8207        let task = if task.is_empty() {
8208            "(empty task)"
8209        } else {
8210            task
8211        };
8212        body.push_str(&format!(
8213            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
8214            task.replace("</details>", "&lt;/details&gt;")
8215        ));
8216    }
8217
8218    body.push_str(&format!(
8219        "\n---\nmagi:run/{} magi:candidate-{}\n",
8220        state.id,
8221        winner.to_ascii_lowercase()
8222    ));
8223
8224    // Prompts are advisory; this is the enforced half of the confidentiality
8225    // rule, and it covers the verbatim task in <details> too.
8226    let id = crate::scrub::Identity::current();
8227    PrMessage {
8228        title: crate::scrub::scrub(&title, &id),
8229        body: crate::scrub::scrub(&body, &id),
8230    }
8231}
8232
8233/// The task with what the repository says about the existing work it names
8234/// appended, so an implementer knows what it started from and what it must
8235/// not redo. Unchanged when the task names nothing.
8236fn seeded_instruction(state: &RunState) -> String {
8237    match refs::describe(&state.seeds) {
8238        Some(facts) => format!(
8239            "{}\n\n# Existing work the task refers to\n\n{facts}\n\n\
8240             Candidates start from the unmerged branch named above, when there \
8241             is one, and carry any unmerged commit named by sha as a \
8242             cherry-pick. Check that this is what the task meant before \
8243             building on it.",
8244            state.instruction
8245        ),
8246        None => state.instruction.clone(),
8247    }
8248}
8249
8250/// Does the winner have no commits ahead of the base it would land on?
8251/// Any failure to find out reads as "not empty": the merge then behaves as it
8252/// always did rather than refusing on a guess.
8253async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
8254    let base = &state.base_branch;
8255    let mut against = base.clone();
8256    if mode == MergeMode::Pr {
8257        let remote = &state.config.merge.remote;
8258        let tracking = format!("{remote}/{base}");
8259        let fetched = git::fetch(repo, remote, base).await;
8260        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
8261            against = tracking;
8262        }
8263    }
8264    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
8265}
8266
8267/// Why nothing was opened for an empty winner, with what the task's own
8268/// references resolved to.
8269fn empty_candidate_detail(state: &RunState, base: &str) -> String {
8270    let mut detail = format!(
8271        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
8272         nothing to open a pull request for"
8273    );
8274    match refs::describe(&state.seeds) {
8275        Some(facts) => detail.push_str(&format!("\nReferences in the task:\n{facts}")),
8276        None => detail.push_str(
8277            "\nThe task names no existing branch or commit; if it means to land work \
8278             that lives elsewhere, name the branch (magi/<run>/<label>) or the sha.",
8279        ),
8280    }
8281    detail
8282}
8283
8284/// What the `Pr` merge does once it knows whether the branch already has an
8285/// open pull request.
8286#[derive(Debug, PartialEq, Eq)]
8287enum PrPlan {
8288    Create,
8289    Adopt { url: String, title: String },
8290    Stop(String),
8291}
8292
8293/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
8294/// a failed lookup -> stop with the real reason. Never guesses.
8295fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
8296    match found {
8297        Ok(land::OpenPr::None) => PrPlan::Create,
8298        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
8299        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
8300            "several open pull requests exist for this branch, not picking one: {}",
8301            urls.join(" ")
8302        )),
8303        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
8304    }
8305}
8306
8307/// `gh pr create`, returning the PR url.
8308async fn gh_pr_create(
8309    cwd: &Path,
8310    base: &str,
8311    head: &str,
8312    title: &str,
8313    body: &str,
8314) -> Result<String> {
8315    let out = tokio::process::Command::new("gh")
8316        .args([
8317            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
8318        ])
8319        .current_dir(cwd)
8320        .quiet()
8321        .stdin(std::process::Stdio::null())
8322        .output()
8323        .await
8324        .context("spawn gh")?;
8325    if out.status.success() {
8326        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
8327    } else {
8328        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
8329    }
8330}
8331
8332/// Tear a run's worktrees and branches down.
8333///
8334/// `home` is where the updated `run.json` is saved (via
8335/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
8336/// a housekeeping pass already has its own honest `home` handed to it, and
8337/// falling through to the global here would write back through whichever
8338/// directory some other process or test pinned into that `OnceLock` first,
8339/// not the one the caller actually resolved its `runs` and `state` from.
8340pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
8341    let repo = state.repo.clone();
8342    let root = state.worktree_root();
8343    let winner = state.tally.as_ref().map(|t| t.winner);
8344    let mut removed = Vec::new();
8345
8346    for i in 0..state.candidates.len() {
8347        let c = state.candidates[i].clone();
8348        let is_winner = Some(c.label) == winner;
8349        if is_winner && !drop_winner {
8350            continue;
8351        }
8352        if c.worktree.exists() {
8353            git::worktree_remove(&repo, &c.worktree).await.ok();
8354            removed.push(c.worktree.to_string_lossy().into_owned());
8355        }
8356        // A branch handed to a later run (and its pull request) is not this
8357        // run's to delete.
8358        let handed_over = state.released_branches.contains(&c.branch);
8359        if !handed_over && git::branch_exists(&repo, &c.branch).await.unwrap_or(false) {
8360            git::branch_delete(&repo, &c.branch).await.ok();
8361            removed.push(c.branch.clone());
8362        }
8363        state.candidates[i].folded = true;
8364    }
8365
8366    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
8367        let path = name.path();
8368        let keep = !drop_winner
8369            && winner.is_some_and(|w| {
8370                path.file_name()
8371                    .is_some_and(|n| n == format!("cand-{w}").as_str())
8372            });
8373        if keep {
8374            continue;
8375        }
8376        git::worktree_remove(&repo, &path).await.ok();
8377        removed.push(path.to_string_lossy().into_owned());
8378    }
8379
8380    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
8381    // judge worktrees, so once the loop above has cleared all of them out,
8382    // the parent is a bare directory nobody else was ever going to remove -
8383    // git only ever managed what was inside it. Left alone, one of these
8384    // accumulates per fully-folded run; the operator's own machine had 74.
8385    // `remove_if_empty` re-checks rather than assuming: a run whose winner
8386    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
8387    // so does anything a run never claimed that happens to share the bay.
8388    remove_if_empty(&root);
8389
8390    if state.enabled_worktree_config && drop_winner {
8391        // A release, not a raw disable: some sibling run in this repository
8392        // may still hold its own reference (see `git::acquire_worktree_config`),
8393        // and only the last release actually turns the setting back off.
8394        git::release_worktree_config(&repo).await.ok();
8395        state.enabled_worktree_config = false;
8396    }
8397    state.save_under(home)?;
8398    Ok(removed)
8399}
8400
8401/// Remove `dir` if it exists and has nothing in it.
8402///
8403/// Best-effort and silent by design: a directory that is not empty (a run
8404/// whose winner is still parked there, a stray file some other process left)
8405/// is exactly the case this must refuse, and a directory that is already gone
8406/// is not a failure worth reporting either. `std::fs::remove_dir` itself
8407/// already refuses a non-empty directory, so the emptiness check below is
8408/// belt, not suspenders - it is what keeps this from ever attempting the
8409/// removal in the case that matters, rather than trusting `remove_dir`'s
8410/// error path to have no side effects if it ever changed.
8411fn remove_if_empty(dir: &Path) {
8412    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
8413        std::fs::remove_dir(dir).ok();
8414    }
8415}
8416
8417/// Severity of the worst open finding in the last review round, for reporting.
8418pub fn worst_open(state: &RunState) -> Option<Severity> {
8419    state
8420        .reviews
8421        .last()?
8422        .reviews
8423        .iter()
8424        .flat_map(|r| r.findings.iter())
8425        .map(|f| f.severity)
8426        .max()
8427}
8428
8429#[cfg(test)]
8430mod tests {
8431    #[test]
8432    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
8433        let leaked = vec!["chore(deps): update a crate".to_owned()];
8434        let own = "fix(daemon): apply a chosen action";
8435        assert!(should_retitle("", own, &leaked));
8436        assert!(should_retitle(
8437            &format!("{REVIEW_PROMPT_OPENING} `x`"),
8438            own,
8439            &leaked
8440        ));
8441        assert!(should_retitle(
8442            "chore: land candidate A of run 1",
8443            own,
8444            &leaked
8445        ));
8446        assert!(should_retitle(
8447            "magi: candidate A (uncommitted work)",
8448            own,
8449            &leaked
8450        ));
8451        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
8452        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
8453        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
8454    }
8455
8456    #[test]
8457    fn pr_merge_plan_creates_adopts_or_stops() {
8458        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
8459        assert_eq!(
8460            pr_merge_plan(Ok(land::OpenPr::One {
8461                url: "u".into(),
8462                title: "t".into()
8463            })),
8464            PrPlan::Adopt {
8465                url: "u".into(),
8466                title: "t".into()
8467            }
8468        );
8469        let PrPlan::Stop(many) =
8470            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
8471        else {
8472            panic!("many must stop");
8473        };
8474        assert!(many.contains('a') && many.contains('b'));
8475        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
8476            panic!("a failed lookup must stop");
8477        };
8478        assert!(err.contains("bad token"));
8479    }
8480
8481    use super::*;
8482    use crate::run::GateStatus;
8483    use std::collections::BTreeMap;
8484    use std::time::Duration;
8485
8486    fn conductor() -> AgentSpec {
8487        AgentSpec {
8488            id: "conductor".to_owned(),
8489            kind: crate::config::AgentKind::Command,
8490            model: None,
8491            command: vec!["true".to_owned()],
8492            extra_args: Vec::new(),
8493            env: BTreeMap::new(),
8494            prompt_delivery: None,
8495        }
8496    }
8497
8498    fn spec(id: &str) -> AgentSpec {
8499        AgentSpec {
8500            id: id.to_owned(),
8501            kind: crate::config::AgentKind::Command,
8502            model: None,
8503            command: vec!["true".to_owned()],
8504            extra_args: Vec::new(),
8505            env: BTreeMap::new(),
8506            prompt_delivery: None,
8507        }
8508    }
8509
8510    fn ids(xs: &[&str]) -> BTreeSet<String> {
8511        xs.iter().map(|s| (*s).to_owned()).collect()
8512    }
8513
8514    #[test]
8515    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
8516        let roster = [spec("a"), spec("b"), spec("c")];
8517        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
8518        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
8519    }
8520
8521    #[test]
8522    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
8523        let roster = [spec("a"), spec("b"), spec("c")];
8524        let failed = ids(&["a", "b", "c"]);
8525        // Rescue looks at the whole roster, once per id, then runs out.
8526        let mut tried = ids(&["b"]);
8527        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
8528        assert_eq!(first.id, "a");
8529        tried.insert(first.id.clone());
8530        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
8531        assert_eq!(second.id, "c");
8532        tried.insert(second.id.clone());
8533        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
8534    }
8535
8536    #[test]
8537    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
8538        let roster = [spec("a"), spec("b")];
8539        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
8540        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8541    }
8542
8543    #[test]
8544    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
8545        let roster = [spec("a"), spec("b"), spec("c")];
8546        let h = SeatHistory {
8547            failed: ids(&["a"]),
8548            last_ok: Some("b".to_owned()),
8549            last_fail: None,
8550        };
8551        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
8552        // A last answerer that left the roster, or later failed, is ignored.
8553        let gone = SeatHistory {
8554            last_ok: Some("zzz".to_owned()),
8555            ..h.clone()
8556        };
8557        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
8558        let failed = SeatHistory {
8559            failed: ids(&["a", "b"]),
8560            last_ok: Some("b".to_owned()),
8561            last_fail: None,
8562        };
8563        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
8564    }
8565
8566    #[test]
8567    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
8568        let first = SeatState::new("review-1", "alpha", 7);
8569        let next = handover_seat("review-1", "gamma", 7);
8570        assert_ne!(first.claude_session, next.claude_session);
8571    }
8572
8573    #[test]
8574    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
8575        let mut state = state_with_summary("x", "y");
8576        let a = handover_seat("review-1", "beta", state.next_seat_seed());
8577        let b = handover_seat("review-1", "beta", state.next_seat_seed());
8578        assert_ne!(a.claude_session, b.claude_session);
8579    }
8580
8581    #[test]
8582    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
8583        let roster = [spec("a"), spec("b")];
8584        let h = SeatHistory {
8585            failed: ids(&["a", "b"]),
8586            ..SeatHistory::default()
8587        };
8588        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
8589        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
8590        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
8591    }
8592
8593    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
8594    // fallback loop depends on to terminate: it must walk forward from the
8595    // seat's own position, never restart at the front of the roster, and it
8596    // must never hand back an id already tried, however many times that id
8597    // happens to appear.
8598
8599    #[test]
8600    fn failure_signature_ignores_numbers_and_paths() {
8601        assert_eq!(
8602            failure_signature("exited with Some(2) and no usable output"),
8603            failure_signature("exited with Some(137) and no usable output")
8604        );
8605        assert_eq!(
8606            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
8607            failure_signature("cannot open /var/x.txt: denied")
8608        );
8609        assert_ne!(failure_signature("boom"), failure_signature("bang"));
8610    }
8611
8612    #[test]
8613    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
8614        let other = FailClass::Other("x".into());
8615        assert!(should_hand_over(None, &FailClass::Quota));
8616        assert!(should_hand_over(Some(&other), &FailClass::Quota));
8617        assert!(should_hand_over(
8618            Some(&FailClass::Timeout),
8619            &FailClass::Timeout
8620        ));
8621        assert!(should_hand_over(None, &other));
8622        assert!(!should_hand_over(Some(&other), &other));
8623        assert!(should_hand_over(
8624            Some(&other),
8625            &FailClass::Other("y".into())
8626        ));
8627        // A quota or timeout in between ends the run of identical failures.
8628        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
8629        assert!(should_hand_over(Some(&FailClass::Quota), &other));
8630    }
8631
8632    #[test]
8633    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
8634        let a = SeatState::new("judge-1", "alpha", 7);
8635        let b = handover_seat("judge-1", "beta", 7);
8636        assert_ne!(a.claude_session, b.claude_session);
8637        assert_eq!(b.turns, 0);
8638    }
8639
8640    #[test]
8641    fn a_timeout_is_classified_apart_from_other_failures() {
8642        assert_eq!(
8643            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
8644            Some(FailClass::Timeout)
8645        );
8646        assert!(matches!(
8647            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
8648            Some(FailClass::Other(_))
8649        ));
8650    }
8651
8652    #[test]
8653    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
8654        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
8655        let tried = BTreeSet::from(["beta".to_owned()]);
8656        // beta sits at index 1; the next candidate is gamma, never alpha —
8657        // which is very likely a different candidate slot's own agent.
8658        let next = next_untried_in_roster(&roster, 1, &tried);
8659        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
8660    }
8661
8662    #[test]
8663    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
8664        let roster = vec![spec("alpha"), spec("beta")];
8665        let tried = BTreeSet::from(["beta".to_owned()]);
8666        // beta is the roster's last entry: nothing follows it, and alpha —
8667        // earlier in the roster, almost certainly a different candidate
8668        // slot's own agent — must not be reached by wrapping back to it.
8669        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
8670    }
8671
8672    #[test]
8673    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
8674        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
8675        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
8676        // beta (index 1) and gamma (index 2, the only entry after it) have
8677        // both been tried; alpha (index 0) never has, but it comes before
8678        // beta's own position, so there is nothing further for this seat.
8679        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
8680    }
8681
8682    #[test]
8683    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
8684        let roster = vec![spec("a"), spec("a"), spec("b")];
8685        let tried = BTreeSet::from(["a".to_owned()]);
8686        let next = next_untried_in_roster(&roster, 0, &tried);
8687        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
8688    }
8689
8690    #[test]
8691    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
8692        let roster = vec![spec("a"), spec("b")];
8693        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
8694        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
8695    }
8696
8697    #[test]
8698    fn remove_if_empty_only_ever_takes_a_bare_directory() {
8699        let dir = tempfile::tempdir().unwrap();
8700        let bay = dir.path().join("ffff");
8701
8702        // Not there yet: nothing to do, nothing to panic on.
8703        remove_if_empty(&bay);
8704        assert!(!bay.exists());
8705
8706        // Something still inside - the winner's worktree, or a stray file -
8707        // keeps the directory standing.
8708        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
8709        remove_if_empty(&bay);
8710        assert!(bay.exists(), "non-empty directory must survive");
8711
8712        // Once the last entry is gone, so is the directory itself.
8713        std::fs::remove_dir(bay.join("cand-A")).unwrap();
8714        remove_if_empty(&bay);
8715        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
8716    }
8717
8718    // `round_is_clean` is the exact decision this task fixed: a round with a
8719    // seat that never answered must not read the same as a round every seat
8720    // actually reviewed. These are deterministic and process-free by design —
8721    // the equivalent end-to-end check (a real reviewer timing out under a
8722    // live graph run) is a genuine race against wall-clock contention, and a
8723    // spawn slow enough to blow even a generous budget under a loaded test
8724    // run must not turn this specific regression check flaky.
8725
8726    #[test]
8727    fn a_full_panel_that_found_nothing_is_clean() {
8728        assert!(round_is_clean(
8729            0,
8730            true,
8731            2,
8732            2,
8733            0,
8734            IncompleteReviewPolicy::Block
8735        ));
8736    }
8737
8738    #[test]
8739    fn a_missing_seat_is_never_clean_under_the_default_policy() {
8740        assert!(!round_is_clean(
8741            0,
8742            true,
8743            1,
8744            2,
8745            0,
8746            IncompleteReviewPolicy::Block
8747        ));
8748    }
8749
8750    #[test]
8751    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
8752        assert!(!round_is_clean(
8753            1,
8754            true,
8755            1,
8756            2,
8757            0,
8758            IncompleteReviewPolicy::Warn
8759        ));
8760    }
8761
8762    #[test]
8763    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
8764        assert!(round_is_clean(
8765            0,
8766            true,
8767            1,
8768            2,
8769            0,
8770            IncompleteReviewPolicy::Warn
8771        ));
8772    }
8773
8774    #[test]
8775    fn a_full_panel_with_an_open_finding_is_not_clean() {
8776        assert!(!round_is_clean(
8777            1,
8778            true,
8779            2,
8780            2,
8781            0,
8782            IncompleteReviewPolicy::Block
8783        ));
8784    }
8785
8786    #[test]
8787    fn a_full_panel_with_a_red_e2e_is_not_clean() {
8788        assert!(!round_is_clean(
8789            0,
8790            false,
8791            2,
8792            2,
8793            0,
8794            IncompleteReviewPolicy::Block
8795        ));
8796    }
8797
8798    // The stall this task closes: under the default `block` policy, a seat
8799    // missing only because it was rate limited must not force a wait for a
8800    // session limit that will not lift by the next round. `round_is_clean`
8801    // is where that quorum carve-out lives; the review loop around it never
8802    // changes what a reviewer's vote or a finding's severity means.
8803
8804    #[test]
8805    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
8806        // 1 of 2 answered, and the one missing was quota'd — the exact
8807        // "review-2 rate limited (quota)" shape from the field report.
8808        assert!(round_is_clean(
8809            0,
8810            true,
8811            1,
8812            2,
8813            1,
8814            IncompleteReviewPolicy::Block
8815        ));
8816    }
8817
8818    #[test]
8819    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
8820        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
8821        // not a quota loss (`quota_missing` stays 0) — worth another try.
8822        assert!(!round_is_clean(
8823            0,
8824            true,
8825            1,
8826            2,
8827            0,
8828            IncompleteReviewPolicy::Block
8829        ));
8830    }
8831
8832    #[test]
8833    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
8834        assert!(!round_is_clean(
8835            1,
8836            true,
8837            1,
8838            2,
8839            1,
8840            IncompleteReviewPolicy::Block
8841        ));
8842        assert!(!round_is_clean(
8843            0,
8844            false,
8845            1,
8846            2,
8847            1,
8848            IncompleteReviewPolicy::Block
8849        ));
8850    }
8851
8852    #[test]
8853    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
8854        // Every seat quota'd, nobody answered: there is no panel to decide
8855        // on, so this must fall through to the existing block-and-retry
8856        // fallback rather than call an unreviewed patch clean.
8857        assert!(!round_is_clean(
8858            0,
8859            true,
8860            0,
8861            2,
8862            2,
8863            IncompleteReviewPolicy::Block
8864        ));
8865    }
8866
8867    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
8868        CommandOutcome {
8869            command: "test".to_owned(),
8870            code,
8871            output_tail: String::new(),
8872            duration_ms: 0,
8873            resource_blocked,
8874        }
8875    }
8876
8877    #[test]
8878    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
8879        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
8880        assert!(
8881            !verify_inconclusive(&[outcome(Some(1), false)]),
8882            "an ordinary failure is still evidence about the patch"
8883        );
8884        assert!(verify_inconclusive(&[outcome(None, true)]));
8885        assert!(
8886            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
8887            "one inconclusive outcome taints the whole batch"
8888        );
8889        assert!(!verify_inconclusive(&[]));
8890    }
8891
8892    #[tokio::test]
8893    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
8894        // Alive for the first two checks, then dead - confirms the loop
8895        // actually re-polls rather than deciding once and sleeping out the
8896        // ceiling regardless.
8897        let calls = std::sync::atomic::AtomicUsize::new(0);
8898        let started = Instant::now();
8899        wait_for_pids_with(
8900            &[123],
8901            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
8902            Duration::from_millis(5),
8903            Duration::from_secs(5),
8904        )
8905        .await;
8906        assert!(
8907            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
8908            "must keep checking rather than deciding on the first answer"
8909        );
8910        assert!(
8911            started.elapsed() < Duration::from_secs(1),
8912            "must return the moment it is confirmed dead, not wait out the ceiling"
8913        );
8914    }
8915
8916    #[tokio::test]
8917    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
8918        let started = Instant::now();
8919        wait_for_pids_with(
8920            &[123],
8921            |_| true, // never reports dead
8922            Duration::from_millis(5),
8923            Duration::from_millis(30),
8924        )
8925        .await;
8926        let elapsed = started.elapsed();
8927        assert!(
8928            elapsed >= Duration::from_millis(30),
8929            "must not give up before its own ceiling: {elapsed:?}"
8930        );
8931        assert!(
8932            elapsed < Duration::from_secs(1),
8933            "must not wait past its own ceiling either: {elapsed:?}"
8934        );
8935    }
8936
8937    #[tokio::test]
8938    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
8939        let started = Instant::now();
8940        wait_for_pids_with(
8941            &[],
8942            |_| true,
8943            Duration::from_secs(5),
8944            Duration::from_secs(5),
8945        )
8946        .await;
8947        assert!(
8948            started.elapsed() < Duration::from_millis(200),
8949            "an empty pid list has nothing to confirm"
8950        );
8951    }
8952
8953    // `review_conclusion` is the exact decision the review hand-off task
8954    // fixed: a round budget spent (or a tree that stopped moving) must not
8955    // collapse into `Blocked` regardless of what verification actually
8956    // said. Deterministic and process-free for the same reason the
8957    // `round_is_clean` family above is.
8958    fn review_round(
8959        clean: bool,
8960        blocking: usize,
8961        answered: usize,
8962        expected: usize,
8963        progressed: bool,
8964        e2e_ok: bool,
8965    ) -> ReviewRound {
8966        ReviewRound {
8967            round: 1,
8968            head: "h".to_owned(),
8969            verified_head: None,
8970            verified_at: None,
8971            reviews: Vec::new(),
8972            e2e: vec![CommandOutcome {
8973                command: "test".to_owned(),
8974                code: Some(if e2e_ok { 0 } else { 1 }),
8975                output_tail: String::new(),
8976                duration_ms: 0,
8977                resource_blocked: false,
8978            }],
8979            verify_retried: false,
8980            e2e_deferred: false,
8981            e2e_defer_reason: None,
8982            fix: None,
8983            blocking,
8984            answered,
8985            expected,
8986            clean,
8987            progressed,
8988            vote_split: false,
8989            reconsideration: Vec::new(),
8990            verdict: None,
8991        }
8992    }
8993
8994    #[test]
8995    fn review_conclusion_is_none_when_nothing_has_run() {
8996        assert_eq!(review_conclusion(&[], 3), None);
8997    }
8998
8999    #[test]
9000    fn review_conclusion_is_none_while_rounds_remain() {
9001        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
9002        assert_eq!(review_conclusion(&rounds, 3), None);
9003    }
9004
9005    #[test]
9006    fn review_conclusion_is_gating_once_a_round_is_clean() {
9007        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
9008        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
9009    }
9010
9011    #[test]
9012    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
9013        let rounds = vec![
9014            review_round(false, 1, 2, 2, true, true),
9015            review_round(false, 1, 2, 2, true, true),
9016        ];
9017        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
9018    }
9019
9020    #[test]
9021    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
9022        let rounds = vec![
9023            review_round(false, 1, 2, 2, true, true),
9024            review_round(false, 1, 2, 2, true, false),
9025        ];
9026        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
9027    }
9028
9029    #[test]
9030    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
9031        // Magi never got a command to run against this round's own head — a
9032        // resource-blocked attempt, not a red one — so this must never
9033        // settle on `Blocked` the way a genuine e2e failure would. `None`
9034        // here is what tells `Runner::review_loop` to retry the check
9035        // itself rather than trust this cheap recomputation with a verdict
9036        // it cannot actually produce.
9037        let mut blocked = review_round(false, 1, 2, 2, true, false);
9038        blocked.e2e[0].resource_blocked = true;
9039        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
9040        assert_eq!(review_conclusion(&rounds, 2), None);
9041    }
9042
9043    #[test]
9044    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
9045        // Missing input, not a verified tree — never a hand-off candidate.
9046        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
9047        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
9048    }
9049
9050    #[test]
9051    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
9052        let rounds = vec![
9053            review_round(false, 1, 2, 2, false, true),
9054            review_round(false, 1, 2, 2, false, true),
9055        ];
9056        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
9057    }
9058
9059    fn secs(n: u64) -> Duration {
9060        Duration::from_secs(n)
9061    }
9062
9063    /// A throwaway repo with one commit on `main`, for tests that need `merge`
9064    /// to make real (and, if it runs at all, real*ly fail*) git calls.
9065    fn init_repo(dir: &Path) {
9066        let run = |args: &[&str]| {
9067            let out = std::process::Command::new("git")
9068                .args(args)
9069                .current_dir(dir)
9070                .quiet()
9071                .output()
9072                .expect("spawn git");
9073            assert!(
9074                out.status.success(),
9075                "git {args:?} failed: {}",
9076                String::from_utf8_lossy(&out.stderr)
9077            );
9078        };
9079        run(&["init", "-b", "main"]);
9080        run(&["config", "user.name", "magi test"]);
9081        run(&["config", "user.email", "magi@example.com"]);
9082        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
9083        run(&["add", "-A"]);
9084        run(&["commit", "-m", "init"]);
9085    }
9086
9087    // `settle_questions` is what closes the ghost the phone showed: a run's
9088    // seat asked something, the run then ended, and nothing was left to
9089    // abandon the question it left `open`. `HOME` is a process-wide
9090    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
9091    // first time it runs in the binary — every test below still reaches the
9092    // same directory whichever call won, and each gets its own run id from
9093    // `RunState::new`, so they never collide there.
9094    fn ask_test_home() {
9095        crate::run::pin_test_home();
9096    }
9097
9098    /// A minimal, git-free `Runner` at a given status — `settle_questions`
9099    /// reads nothing else off it.
9100    fn runner_at(status: RunStatus) -> Runner {
9101        let mut state = RunState::new(
9102            PathBuf::from("/nonexistent/repo"),
9103            "main".to_owned(),
9104            "deadbeef".to_owned(),
9105            "task".to_owned(),
9106            Config::default(),
9107        );
9108        state.status = status;
9109        Runner {
9110            state,
9111            roles: ResolvedRoles {
9112                implementers: Vec::new(),
9113                judges: Vec::new(),
9114                reviewers: Vec::new(),
9115                fixer: None,
9116                conductor: conductor(),
9117                implementer_roster: Vec::new(),
9118                judge_roster: Vec::new(),
9119                reviewer_roster: Vec::new(),
9120            },
9121            sem: Arc::new(Semaphore::new(1)),
9122            pause: Pause::new(),
9123            interrupt: Pause::new(),
9124        }
9125    }
9126
9127    /// `park_here` folding in the reason `Pause::park_because` recorded -
9128    /// this is what lets an operator reading a run's events tell an
9129    /// interrupt-driven park from an ordinary shutdown park.
9130    #[test]
9131    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
9132        crate::run::pin_test_home();
9133        let mut runner = runner_at(RunStatus::Implementing);
9134        let interrupt = Pause::new();
9135        runner.watch_interrupt(interrupt.clone());
9136
9137        interrupt.park_because("task a1b2 asked to run first");
9138
9139        assert!(runner.park_here().expect("park_here"));
9140        assert!(runner.state.parked);
9141        let last = runner.state.events.last().expect("a park event");
9142        assert_eq!(last.node, "park");
9143        assert!(
9144            last.message.contains("task a1b2 asked to run first"),
9145            "expected the interrupt reason in {:?}",
9146            last.message
9147        );
9148    }
9149
9150    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
9151    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
9152    /// cleared) must not make a *different* run - one only watching its own,
9153    /// unshared interrupt `Pause` - see itself as parked. If a future change
9154    /// ever collapsed these back into one handle, the interrupt scheduler
9155    /// would park every run for the rest of the daemon's life, not just the
9156    /// one it meant to interrupt.
9157    #[test]
9158    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
9159        crate::run::pin_test_home();
9160        let mut runner = runner_at(RunStatus::Implementing);
9161        let shutdown = Pause::new();
9162        runner.on_pause(shutdown.clone());
9163        let interrupt = Pause::new();
9164        runner.watch_interrupt(interrupt.clone());
9165
9166        // Nobody has asked for anything yet.
9167        assert!(!runner.park_here().expect("park_here"));
9168        assert!(!runner.state.parked);
9169
9170        // Only the interrupt handle fires; the shutdown handle stays clear.
9171        interrupt.park_because("test");
9172        assert!(!shutdown.parked());
9173        assert!(runner.park_here().expect("park_here"));
9174    }
9175
9176    /// The property every prior attempt at this feature failed to pin down:
9177    /// asking a run to park while one of its nodes has a real, in-flight
9178    /// async operation running (an agent call, in production) must not cut
9179    /// that operation short. `park_here` is only ever consulted *between*
9180    /// `execute`'s node calls - see its own doc - so nothing inside a node
9181    /// can observe a park request until the node itself returns. This proves
9182    /// that structurally, with real `tokio` concurrency and a channel
9183    /// handshake (never a sleep, which would only prove "usually", not
9184    /// "cannot"): the "node" below reports that it has genuinely started,
9185    /// and only then is the park requested; the node still has to be told to
9186    /// finish before `park_here` is ever called, exactly mirroring every
9187    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
9188    /// in `execute`.
9189    #[tokio::test]
9190    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
9191        crate::run::pin_test_home();
9192        let mut runner = runner_at(RunStatus::Implementing);
9193        let interrupt = Pause::new();
9194        runner.watch_interrupt(interrupt.clone());
9195
9196        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
9197        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
9198
9199        // Stands in for one node's in-flight agent call: it proves it has
9200        // genuinely started, then blocks - exactly as a spawned CLI process
9201        // does - until told to finish.
9202        let node = async move {
9203            started_tx.send(()).expect("send started");
9204            finish_rx.await.expect("recv finish");
9205            "node finished"
9206        };
9207
9208        let interrupter = async move {
9209            started_rx.await.expect("recv started");
9210            // The call is now genuinely in flight. Ask it to park.
9211            interrupt.park_because("higher-priority task waiting");
9212            // Nothing the node does can observe this yet - there is no
9213            // check inside it, by construction - so let the executor run
9214            // anything pending and then let the node finish on its own.
9215            tokio::task::yield_now().await;
9216            finish_tx.send(()).expect("send finish");
9217        };
9218
9219        let (node_result, ()) = tokio::join!(node, interrupter);
9220        assert_eq!(
9221            node_result, "node finished",
9222            "the in-flight call ran to completion"
9223        );
9224
9225        // Only now, at the boundary the real `execute` would check right
9226        // after this node, does the park take effect.
9227        assert!(runner.park_here().expect("park_here"));
9228        assert!(runner.state.parked);
9229    }
9230
9231    /// A run parked mid-competition carries every field it had accumulated
9232    /// through the exact same disk round-trip an ordinary resume uses -
9233    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
9234    /// Nothing about parking for an interrupt is a special case of that path;
9235    /// this is what proves it rather than assuming it.
9236    #[test]
9237    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
9238        crate::run::pin_test_home();
9239        let mut runner = runner_at(RunStatus::Judging);
9240        // `Runner::resume` re-resolves roles from the saved config, which
9241        // refuses an empty roster - give it the same minimal one `conductor`
9242        // itself uses.
9243        runner.state.config.agents = vec![conductor()];
9244        runner.state.candidates = vec![Candidate {
9245            index: 0,
9246            label: 'A',
9247            agent: "alpha".to_owned(),
9248            branch: "magi/x/A".to_owned(),
9249            worktree: PathBuf::from("/nonexistent/worktree"),
9250            summary: "did the thing".to_owned(),
9251            stat: "1 file changed".to_owned(),
9252            files: 1,
9253            commits: 1,
9254            empty: false,
9255            failed: None,
9256            verified_noop: None,
9257            duration_ms: 1234,
9258            folded: false,
9259        }];
9260        let run_id = runner.state.id.clone();
9261
9262        let interrupt = Pause::new();
9263        runner.watch_interrupt(interrupt.clone());
9264        interrupt.park_because("task c3d4 asked to run first");
9265        assert!(runner.park_here().expect("park_here"));
9266
9267        let resumed = Runner::resume(&run_id).expect("resume");
9268        assert_eq!(resumed.state.candidates.len(), 1);
9269        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
9270        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
9271        assert_eq!(resumed.state.status, runner.state.status);
9272        assert!(
9273            resumed.state.parked,
9274            "still parked until `execute` actually walks the graph again"
9275        );
9276        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
9277    }
9278
9279    /// A fresh open question on `run`, stored and handed back for assertions.
9280    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
9281        let mut q = ask::Question::new(
9282            run.to_owned(),
9283            "implement".to_owned(),
9284            "impl-A".to_owned(),
9285            "Which storage backend should the cache use?".to_owned(),
9286            String::new(),
9287            vec!["SQLite".to_owned(), "Redis".to_owned()],
9288        );
9289        store.put(&mut q).unwrap();
9290        q
9291    }
9292
9293    #[test]
9294    fn a_failed_runs_open_question_is_abandoned() {
9295        ask_test_home();
9296        let store = ask::Questions::open();
9297        let mut runner = runner_at(RunStatus::Failed);
9298        let run = runner.state.id.clone();
9299        let q = ask_open_question(&store, &run);
9300
9301        runner.settle_questions();
9302
9303        let back = store.get(&q.id).unwrap();
9304        assert!(
9305            !back.status.open(),
9306            "the seat that asked died with the run; nobody is left to read an answer"
9307        );
9308        assert!(
9309            back.detail.contains(&run) && back.detail.contains("failed"),
9310            "the reason names what the run became, not just that it is gone: {}",
9311            back.detail
9312        );
9313    }
9314
9315    #[test]
9316    fn a_merged_runs_open_question_is_abandoned_too() {
9317        ask_test_home();
9318        let store = ask::Questions::open();
9319        // A run that finishes cleanly still leaves nobody to read an answer -
9320        // this is not only a failure-path cleanup.
9321        for status in [RunStatus::Merged, RunStatus::Ready] {
9322            let mut runner = runner_at(status);
9323            let run = runner.state.id.clone();
9324            let q = ask_open_question(&store, &run);
9325
9326            runner.settle_questions();
9327
9328            let back = store.get(&q.id).unwrap();
9329            assert!(
9330                !back.status.open(),
9331                "{status:?} run's question must not outlive the run"
9332            );
9333        }
9334    }
9335
9336    #[test]
9337    fn a_still_resumable_runs_open_question_is_left_alone() {
9338        ask_test_home();
9339        let store = ask::Questions::open();
9340        // `Blocked` and `Stalled` can still be resumed — the candidates, the
9341        // review round and the seat sessions are all still on disk — so a
9342        // question asked mid-round may yet get a real answer from a real
9343        // resume. Sweeping it here would be exactly the failure mode this
9344        // whole feature exists to avoid on the other side.
9345        for status in [RunStatus::Blocked, RunStatus::Stalled] {
9346            let mut runner = runner_at(status);
9347            let run = runner.state.id.clone();
9348            let q = ask_open_question(&store, &run);
9349
9350            runner.settle_questions();
9351
9352            let back = store.get(&q.id).unwrap();
9353            assert!(
9354                back.status.open(),
9355                "{status:?} is still alive; the question must still be waiting"
9356            );
9357        }
9358    }
9359
9360    #[test]
9361    fn settle_questions_never_touches_an_already_answered_question() {
9362        ask_test_home();
9363        let store = ask::Questions::open();
9364        let mut runner = runner_at(RunStatus::Failed);
9365        let run = runner.state.id.clone();
9366        let mut q = ask_open_question(&store, &run);
9367        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
9368            .unwrap();
9369        store.put(&mut q).unwrap();
9370
9371        // Called twice, the way a crash-recovered daemon reclaim and the
9372        // graph's own cleanup both can for the same run — `abandon_for_run`
9373        // only ever touches what is still open, so this must be inert both
9374        // times, not merely the second.
9375        runner.settle_questions();
9376        runner.settle_questions();
9377
9378        let back = store.get(&q.id).unwrap();
9379        assert_eq!(
9380            back.status,
9381            ask::QuestionStatus::Answered,
9382            "a real answer is a decision on record, never overwritten by a sweep"
9383        );
9384    }
9385
9386    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
9387    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
9388    /// without merging, whose winner is still the operator's answer to read.
9389    /// Nothing previously called `fold_run` itself with a real `tally`, so
9390    /// this is the first test to pin down the one distinction the whole
9391    /// automatic-fold feature depends on: the winner's worktree and branch
9392    /// must survive, everything else sharing the run's worktree bay - a
9393    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
9394    /// second sweep treats every non-winner directory under the bay alike -
9395    /// must not.
9396    #[tokio::test]
9397    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
9398        crate::run::pin_test_home();
9399        let tmp = tempfile::tempdir().expect("tempdir");
9400        let repo = tmp.path().join("repo");
9401        std::fs::create_dir_all(&repo).unwrap();
9402        init_repo(&repo);
9403
9404        let mut config = Config::default();
9405        config.graph.worktree_root = Some(tmp.path().join("wt"));
9406
9407        let mut state = RunState::new(
9408            repo.clone(),
9409            "main".to_owned(),
9410            "deadbeef".to_owned(),
9411            "task".to_owned(),
9412            config,
9413        );
9414        let root = state.worktree_root();
9415        let wt_a = root.join("cand-A");
9416        let wt_b = root.join("cand-B");
9417        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
9418            .await
9419            .expect("worktree A");
9420        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
9421            .await
9422            .expect("worktree B");
9423
9424        state.candidates = vec![
9425            Candidate {
9426                index: 0,
9427                label: 'A',
9428                agent: "alpha".to_owned(),
9429                branch: "magi/x/A".to_owned(),
9430                worktree: wt_a.clone(),
9431                summary: String::new(),
9432                stat: String::new(),
9433                files: 0,
9434                commits: 0,
9435                empty: false,
9436                failed: None,
9437                verified_noop: None,
9438                duration_ms: 0,
9439                folded: false,
9440            },
9441            Candidate {
9442                index: 1,
9443                label: 'B',
9444                agent: "beta".to_owned(),
9445                branch: "magi/x/B".to_owned(),
9446                worktree: wt_b.clone(),
9447                summary: String::new(),
9448                stat: String::new(),
9449                files: 0,
9450                commits: 0,
9451                empty: false,
9452                failed: None,
9453                verified_noop: None,
9454                duration_ms: 0,
9455                folded: false,
9456            },
9457        ];
9458        state.tally = Some(Tally {
9459            first_choice: BTreeMap::from([('A', 1)]),
9460            borda: BTreeMap::new(),
9461            winner: 'A',
9462            rankings: 1,
9463            unanimous_initial: true,
9464            deliberated: false,
9465            changed_votes: 0,
9466            unanimous_final: true,
9467            tie_break: None,
9468            judges: 1,
9469            present: 1,
9470            quorum: 1,
9471            met_quorum: true,
9472            uncontested: None,
9473        });
9474        state.status = RunStatus::Ready;
9475
9476        fold_run(&mut state, false, &crate::run::home())
9477            .await
9478            .expect("fold_run");
9479
9480        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
9481        assert!(
9482            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
9483            "the unmerged winner's branch survives"
9484        );
9485        assert!(
9486            !state.candidates[0].folded,
9487            "the winner is not marked folded"
9488        );
9489
9490        assert!(!wt_b.exists(), "the loser's worktree is removed");
9491        assert!(
9492            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
9493            "the loser's branch is removed"
9494        );
9495        assert!(state.candidates[1].folded, "the loser is marked folded");
9496    }
9497
9498    /// A branch handed to a later run is that run's (and its pull request's):
9499    /// folding the run that released it must not delete it.
9500    #[tokio::test]
9501    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
9502        let tmp = tempfile::tempdir().expect("tempdir");
9503        let repo = tmp.path().join("repo");
9504        std::fs::create_dir_all(&repo).unwrap();
9505        init_repo(&repo);
9506        let home = tmp.path().join("home");
9507
9508        let mut config = Config::default();
9509        config.graph.worktree_root = Some(tmp.path().join("wt"));
9510        let mut state = RunState::new(
9511            repo.clone(),
9512            "main".to_owned(),
9513            "deadbeef".to_owned(),
9514            "task".to_owned(),
9515            config,
9516        );
9517        // The worktree is already gone (released); the branch survives.
9518        git::git(&repo, &["branch", "magi/x/A", "main"])
9519            .await
9520            .expect("branch");
9521        state.candidates = vec![Candidate {
9522            index: 0,
9523            label: 'A',
9524            agent: "alpha".to_owned(),
9525            branch: "magi/x/A".to_owned(),
9526            worktree: state.worktree_root().join("cand-A"),
9527            summary: String::new(),
9528            stat: String::new(),
9529            files: 0,
9530            commits: 0,
9531            empty: false,
9532            failed: None,
9533            verified_noop: None,
9534            duration_ms: 0,
9535            folded: true,
9536        }];
9537        state.released_to = Some("20260901-000000-new1".to_owned());
9538        state.released_branches = vec!["magi/x/A".to_owned()];
9539
9540        fold_run(&mut state, true, &home).await.expect("fold_run");
9541
9542        assert!(
9543            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
9544            "the handed-over branch survives a fold"
9545        );
9546    }
9547
9548    /// A winner with nothing ahead of the base is caught before `gh` is ever
9549    /// asked for a pull request, and the message carries what the task's
9550    /// references resolved to.
9551    #[tokio::test]
9552    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
9553        let tmp = tempfile::tempdir().expect("tempdir");
9554        let repo = tmp.path().join("repo");
9555        std::fs::create_dir_all(&repo).unwrap();
9556        init_repo(&repo);
9557        let run = |args: &[&str]| {
9558            let out = std::process::Command::new("git")
9559                .quiet()
9560                .args(args)
9561                .current_dir(&repo)
9562                .output()
9563                .expect("spawn git");
9564            assert!(out.status.success(), "git {args:?}");
9565        };
9566        run(&["branch", "magi/x/A"]);
9567        run(&["checkout", "-q", "-b", "magi/x/B"]);
9568        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
9569        run(&["add", "-A"]);
9570        run(&["commit", "-q", "-m", "work"]);
9571        run(&["checkout", "-q", "main"]);
9572
9573        let mut state = RunState::new(
9574            repo.clone(),
9575            "main".to_owned(),
9576            "deadbeef".to_owned(),
9577            "task".to_owned(),
9578            Config::default(),
9579        );
9580        state.seeds = vec![refs::Seed {
9581            token: "magi/27b2/A".to_owned(),
9582            kind: refs::SeedKind::Unresolved,
9583            sha: String::new(),
9584            branch: true,
9585            detail: "no branch or commit named magi/27b2/A".to_owned(),
9586        }];
9587
9588        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
9589        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
9590        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
9591        let detail = empty_candidate_detail(&state, "main");
9592        assert!(detail.starts_with("empty candidate"), "{detail}");
9593        assert!(detail.contains("magi/27b2/A"), "{detail}");
9594    }
9595
9596    /// `status == Ready` used to be read as "this is the harmless
9597    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
9598    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
9599    /// run's PR was closed without merging — and reentering `merge` with
9600    /// `mode` still `Pr` does not know the difference, so it pushed and
9601    /// opened a second pull request. `mode == Local` reproduces the same
9602    /// blind spot without a network call: reentry must not attempt another
9603    /// git merge once this node has already recorded an outcome.
9604    #[tokio::test]
9605    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
9606        let tmp = tempfile::tempdir().expect("tempdir");
9607        let repo = tmp.path().join("repo");
9608        std::fs::create_dir_all(&repo).unwrap();
9609        init_repo(&repo);
9610
9611        let mut config = Config::default();
9612        config.merge.mode = MergeMode::Local;
9613
9614        let mut state = RunState::new(
9615            repo.clone(),
9616            "main".to_owned(),
9617            "deadbeef".to_owned(),
9618            "task".to_owned(),
9619            config,
9620        );
9621        state.candidates = vec![Candidate {
9622            index: 0,
9623            label: 'A',
9624            agent: "alpha".to_owned(),
9625            branch: "does-not-exist".to_owned(),
9626            worktree: repo.clone(),
9627            summary: String::new(),
9628            stat: String::new(),
9629            files: 0,
9630            commits: 0,
9631            empty: false,
9632            failed: None,
9633            verified_noop: None,
9634            duration_ms: 0,
9635            folded: false,
9636        }];
9637        state.tally = Some(Tally {
9638            first_choice: BTreeMap::from([('A', 1)]),
9639            borda: BTreeMap::new(),
9640            winner: 'A',
9641            rankings: 1,
9642            unanimous_initial: true,
9643            deliberated: false,
9644            changed_votes: 0,
9645            unanimous_final: true,
9646            tie_break: None,
9647            judges: 0,
9648            present: 0,
9649            quorum: 0,
9650            met_quorum: true,
9651            uncontested: Some("only candidate A produced a change".to_owned()),
9652        });
9653        state.reviews = vec![ReviewRound {
9654            round: 1,
9655            head: "deadbeef".to_owned(),
9656            verified_head: None,
9657            verified_at: None,
9658            reviews: Vec::new(),
9659            e2e: Vec::new(),
9660            fix: None,
9661            blocking: 0,
9662            answered: 0,
9663            expected: 0,
9664            clean: true,
9665            verify_retried: false,
9666            e2e_deferred: false,
9667            e2e_defer_reason: None,
9668            progressed: false,
9669            vote_split: false,
9670            reconsideration: Vec::new(),
9671            verdict: None,
9672        }];
9673        state.gate = vec![CommandOutcome {
9674            command: "test".to_owned(),
9675            code: Some(0),
9676            output_tail: String::new(),
9677            duration_ms: 0,
9678            resource_blocked: false,
9679        }];
9680        state.gate_ran = true;
9681        // Reached its conclusion already — e.g. `land` closing the PR without
9682        // merging it, which (like the honest `MergeMode::None` path) leaves
9683        // `status` at `Ready`. The recorded outcome is what actually marks
9684        // this node done.
9685        state.status = RunStatus::Ready;
9686        state.merge = Some(MergeOutcome {
9687            mode: MergeMode::Local,
9688            ok: false,
9689            detail: "already concluded".to_owned(),
9690            empty: false,
9691        });
9692
9693        let mut runner = Runner {
9694            state,
9695            roles: ResolvedRoles {
9696                implementers: Vec::new(),
9697                judges: Vec::new(),
9698                reviewers: Vec::new(),
9699                fixer: None,
9700                conductor: conductor(),
9701                implementer_roster: Vec::new(),
9702                judge_roster: Vec::new(),
9703                reviewer_roster: Vec::new(),
9704            },
9705            sem: Arc::new(Semaphore::new(1)),
9706            pause: Pause::new(),
9707            interrupt: Pause::new(),
9708        };
9709
9710        runner.merge().await.expect("merge");
9711
9712        assert_eq!(
9713            runner.state.status,
9714            RunStatus::Ready,
9715            "a concluded run's status must not change on reentry"
9716        );
9717        assert_eq!(
9718            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
9719            Some("already concluded"),
9720            "merge must not run again once the node already recorded an outcome"
9721        );
9722    }
9723
9724    /// `gate` leaves `state.gate_ran` false both before it has ever run and
9725    /// when its last attempt was resource-blocked (the shared build cache
9726    /// could not be acquired or confirmed fresh in time - see
9727    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
9728    /// `Vec` this also leaves behind used to read as "nothing failed" and let
9729    /// a run merge a tree the gate never actually checked - exactly the case
9730    /// a contended cache produces on every retry until it clears. `merge`
9731    /// must refuse until `gate` has actually recorded an attempt.
9732    #[tokio::test]
9733    async fn merge_refuses_a_gate_that_has_not_actually_run() {
9734        let tmp = tempfile::tempdir().expect("tempdir");
9735        let repo = tmp.path().join("repo");
9736        std::fs::create_dir_all(&repo).unwrap();
9737        init_repo(&repo);
9738
9739        let mut config = Config::default();
9740        config.merge.mode = MergeMode::Local;
9741
9742        let mut state = RunState::new(
9743            repo.clone(),
9744            "main".to_owned(),
9745            "deadbeef".to_owned(),
9746            "task".to_owned(),
9747            config,
9748        );
9749        state.candidates = vec![Candidate {
9750            index: 0,
9751            label: 'A',
9752            agent: "alpha".to_owned(),
9753            branch: "does-not-exist".to_owned(),
9754            worktree: repo.clone(),
9755            summary: String::new(),
9756            stat: String::new(),
9757            files: 0,
9758            commits: 0,
9759            empty: false,
9760            failed: None,
9761            verified_noop: None,
9762            duration_ms: 0,
9763            folded: false,
9764        }];
9765        state.tally = Some(Tally {
9766            first_choice: BTreeMap::from([('A', 1)]),
9767            borda: BTreeMap::new(),
9768            winner: 'A',
9769            rankings: 1,
9770            unanimous_initial: true,
9771            deliberated: false,
9772            changed_votes: 0,
9773            unanimous_final: true,
9774            tie_break: None,
9775            judges: 0,
9776            present: 0,
9777            quorum: 0,
9778            met_quorum: true,
9779            uncontested: Some("only candidate A produced a change".to_owned()),
9780        });
9781        state.reviews = vec![ReviewRound {
9782            round: 1,
9783            head: "deadbeef".to_owned(),
9784            verified_head: None,
9785            verified_at: None,
9786            reviews: Vec::new(),
9787            e2e: Vec::new(),
9788            fix: None,
9789            blocking: 0,
9790            answered: 0,
9791            expected: 0,
9792            clean: true,
9793            verify_retried: false,
9794            e2e_deferred: false,
9795            e2e_defer_reason: None,
9796            progressed: false,
9797            vote_split: false,
9798            reconsideration: Vec::new(),
9799            verdict: None,
9800        }];
9801        // The point: `gate` has not recorded anything yet.
9802        state.gate = Vec::new();
9803        state.gate_ran = false;
9804        state.status = RunStatus::Gating;
9805
9806        let mut runner = Runner {
9807            state,
9808            roles: ResolvedRoles {
9809                implementers: Vec::new(),
9810                judges: Vec::new(),
9811                reviewers: Vec::new(),
9812                fixer: None,
9813                conductor: conductor(),
9814                implementer_roster: Vec::new(),
9815                judge_roster: Vec::new(),
9816                reviewer_roster: Vec::new(),
9817            },
9818            sem: Arc::new(Semaphore::new(1)),
9819            pause: Pause::new(),
9820            interrupt: Pause::new(),
9821        };
9822
9823        runner.merge().await.expect("merge");
9824
9825        assert!(
9826            runner.state.merge.is_none(),
9827            "an empty gate must never be read as a passing one: {:?}",
9828            runner.state.merge
9829        );
9830    }
9831
9832    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
9833    /// commands configured and `merge.mode` is `none` (a review-only run).
9834    /// `gate` must still record a real attempt — zero commands, vacuously
9835    /// passed — rather than leaving `state.gate` empty in a way `merge`
9836    /// cannot tell apart from "never ran"; otherwise the run reaches
9837    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
9838    #[tokio::test]
9839    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
9840        let tmp = tempfile::tempdir().expect("tempdir");
9841        let repo = tmp.path().join("repo");
9842        std::fs::create_dir_all(&repo).unwrap();
9843        init_repo(&repo);
9844
9845        // Default config: `verify.gate` empty, `merge.mode` is `none`.
9846        let config = Config::default();
9847
9848        let mut state = RunState::new(
9849            repo.clone(),
9850            "main".to_owned(),
9851            "deadbeef".to_owned(),
9852            "task".to_owned(),
9853            config,
9854        );
9855        state.candidates = vec![Candidate {
9856            index: 0,
9857            label: 'A',
9858            agent: "alpha".to_owned(),
9859            branch: "does-not-exist".to_owned(),
9860            worktree: repo.clone(),
9861            summary: String::new(),
9862            stat: String::new(),
9863            files: 0,
9864            commits: 0,
9865            empty: false,
9866            failed: None,
9867            verified_noop: None,
9868            duration_ms: 0,
9869            folded: false,
9870        }];
9871        state.tally = Some(Tally {
9872            first_choice: BTreeMap::from([('A', 1)]),
9873            borda: BTreeMap::new(),
9874            winner: 'A',
9875            rankings: 1,
9876            unanimous_initial: true,
9877            deliberated: false,
9878            changed_votes: 0,
9879            unanimous_final: true,
9880            tie_break: None,
9881            judges: 0,
9882            present: 0,
9883            quorum: 0,
9884            met_quorum: true,
9885            uncontested: Some("only candidate A produced a change".to_owned()),
9886        });
9887        state.reviews = vec![ReviewRound {
9888            round: 1,
9889            head: "deadbeef".to_owned(),
9890            verified_head: None,
9891            verified_at: None,
9892            reviews: Vec::new(),
9893            e2e: Vec::new(),
9894            fix: None,
9895            blocking: 0,
9896            answered: 0,
9897            expected: 0,
9898            clean: true,
9899            verify_retried: false,
9900            e2e_deferred: false,
9901            e2e_defer_reason: None,
9902            progressed: false,
9903            vote_split: false,
9904            reconsideration: Vec::new(),
9905            verdict: None,
9906        }];
9907
9908        let mut runner = Runner {
9909            state,
9910            roles: ResolvedRoles {
9911                implementers: Vec::new(),
9912                judges: Vec::new(),
9913                reviewers: Vec::new(),
9914                fixer: None,
9915                conductor: conductor(),
9916                implementer_roster: Vec::new(),
9917                judge_roster: Vec::new(),
9918                reviewer_roster: Vec::new(),
9919            },
9920            sem: Arc::new(Semaphore::new(1)),
9921            pause: Pause::new(),
9922            interrupt: Pause::new(),
9923        };
9924
9925        runner.gate().await.expect("gate");
9926        assert!(
9927            runner.state.gate_ran,
9928            "zero configured commands is still a real attempt, not an unrun gate"
9929        );
9930        assert!(runner.state.gate.is_empty());
9931        assert_eq!(runner.state.gate_status(), GateStatus::PassedWithNoCommands);
9932        assert_ne!(
9933            runner.state.status,
9934            RunStatus::Blocked,
9935            "a gate with nothing to check must not read as failed"
9936        );
9937
9938        runner.merge().await.expect("merge");
9939        assert_eq!(
9940            runner.state.status,
9941            RunStatus::Ready,
9942            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
9943        );
9944    }
9945
9946    /// `Config::cache_dir` is derived from `verify.e2e` as well as
9947    /// `verify.gate` (so the e2e leg and the final gate never build against
9948    /// different directories). With zero `verify.gate` commands but a
9949    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
9950    /// that lease before discovering it had nothing to run - so a repo with
9951    /// no gate commands could come back `resource_blocked` (and therefore
9952    /// still `gate_ran == false`) on nothing but an unrelated run holding the
9953    /// cache, exactly the contention this run's own zero commands could
9954    /// never have touched. `gate` must recognise there is nothing to check
9955    /// before it ever asks for the lease.
9956    #[tokio::test]
9957    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
9958        crate::run::pin_test_home();
9959        let home = crate::run::home();
9960
9961        let tmp = tempfile::tempdir().expect("tempdir");
9962        let repo = tmp.path().join("repo");
9963        std::fs::create_dir_all(&repo).unwrap();
9964        init_repo(&repo);
9965        // Unique to this test, so holding its lease cannot collide with
9966        // another test sharing the same process-wide `home`.
9967        let cache_dir = tmp.path().join("target");
9968
9969        let mut config = Config::default();
9970        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
9971        // `verify.gate` stays empty (the default). Bounded so a regression
9972        // that does start waiting fails the test in seconds, not hangs it.
9973        config.graph.timeout_verify = Some(2);
9974
9975        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
9976        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
9977            .expect("no io error acquiring directly")
9978        {
9979            crate::cache::AcquireOutcome::Acquired(g) => g,
9980            crate::cache::AcquireOutcome::Busy(b) => {
9981                panic!("expected the direct acquire to win the lease first: {b:?}")
9982            }
9983        };
9984
9985        let mut state = RunState::new(
9986            repo.clone(),
9987            "main".to_owned(),
9988            "deadbeef".to_owned(),
9989            "task".to_owned(),
9990            config,
9991        );
9992        state.candidates = vec![Candidate {
9993            index: 0,
9994            label: 'A',
9995            agent: "alpha".to_owned(),
9996            branch: "does-not-exist".to_owned(),
9997            worktree: repo.clone(),
9998            summary: String::new(),
9999            stat: String::new(),
10000            files: 0,
10001            commits: 0,
10002            empty: false,
10003            failed: None,
10004            verified_noop: None,
10005            duration_ms: 0,
10006            folded: false,
10007        }];
10008        state.tally = Some(Tally {
10009            first_choice: BTreeMap::from([('A', 1)]),
10010            borda: BTreeMap::new(),
10011            winner: 'A',
10012            rankings: 1,
10013            unanimous_initial: true,
10014            deliberated: false,
10015            changed_votes: 0,
10016            unanimous_final: true,
10017            tie_break: None,
10018            judges: 0,
10019            present: 0,
10020            quorum: 0,
10021            met_quorum: true,
10022            uncontested: Some("only candidate A produced a change".to_owned()),
10023        });
10024        state.reviews = vec![ReviewRound {
10025            round: 1,
10026            head: "deadbeef".to_owned(),
10027            verified_head: None,
10028            verified_at: None,
10029            reviews: Vec::new(),
10030            e2e: Vec::new(),
10031            fix: None,
10032            blocking: 0,
10033            answered: 0,
10034            expected: 0,
10035            clean: true,
10036            verify_retried: false,
10037            e2e_deferred: false,
10038            e2e_defer_reason: None,
10039            progressed: false,
10040            vote_split: false,
10041            reconsideration: Vec::new(),
10042            verdict: None,
10043        }];
10044
10045        let mut runner = Runner {
10046            state,
10047            roles: ResolvedRoles {
10048                implementers: Vec::new(),
10049                judges: Vec::new(),
10050                reviewers: Vec::new(),
10051                fixer: None,
10052                conductor: conductor(),
10053                implementer_roster: Vec::new(),
10054                judge_roster: Vec::new(),
10055                reviewer_roster: Vec::new(),
10056            },
10057            sem: Arc::new(Semaphore::new(1)),
10058            pause: Pause::new(),
10059            interrupt: Pause::new(),
10060        };
10061
10062        let started = std::time::Instant::now();
10063        runner.gate().await.expect("gate");
10064        assert!(
10065            started.elapsed() < Duration::from_secs(1),
10066            "a gate with nothing to run must never wait on a lease it never needed"
10067        );
10068        assert!(
10069            runner.state.gate_ran,
10070            "zero commands is still a real, immediate attempt"
10071        );
10072        assert!(runner.state.gate.is_empty());
10073        assert_ne!(
10074            runner.state.status,
10075            RunStatus::Blocked,
10076            "must not read as resource-blocked on a lease it never asked for"
10077        );
10078    }
10079
10080    /// The addendum's second gap: a `verify.gate` command running for real
10081    /// wall-clock time had nothing at all to show for it in `active` before
10082    /// `run_commands` learned to record it — a run could sit in `Gating` for
10083    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
10084    /// what was actually happening. Proven with a genuinely still-running
10085    /// command, not just a before/after check on the final state: a poller
10086    /// task reads the same `run.json` `gate()` is writing, the same way the
10087    /// phone or `magi show` would, while the shell command is still blocked
10088    /// on its own release marker.
10089    #[tokio::test]
10090    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
10091        crate::run::pin_test_home();
10092
10093        let tmp = tempfile::tempdir().expect("tempdir");
10094        let repo = tmp.path().join("repo");
10095        std::fs::create_dir_all(&repo).unwrap();
10096        init_repo(&repo);
10097
10098        let mut config = Config::default();
10099        config.verify.gate = vec![
10100            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
10101             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done"
10102                .to_owned(),
10103        ];
10104
10105        let mut state = RunState::new(
10106            repo.clone(),
10107            "main".to_owned(),
10108            "deadbeef".to_owned(),
10109            "task".to_owned(),
10110            config,
10111        );
10112        let run_id = state.id.clone();
10113        state.candidates = vec![Candidate {
10114            index: 0,
10115            label: 'A',
10116            agent: "alpha".to_owned(),
10117            branch: "does-not-exist".to_owned(),
10118            worktree: repo.clone(),
10119            summary: String::new(),
10120            stat: String::new(),
10121            files: 0,
10122            commits: 0,
10123            empty: false,
10124            failed: None,
10125            verified_noop: None,
10126            duration_ms: 0,
10127            folded: false,
10128        }];
10129        state.tally = Some(Tally {
10130            first_choice: BTreeMap::from([('A', 1)]),
10131            borda: BTreeMap::new(),
10132            winner: 'A',
10133            rankings: 1,
10134            unanimous_initial: true,
10135            deliberated: false,
10136            changed_votes: 0,
10137            unanimous_final: true,
10138            tie_break: None,
10139            judges: 0,
10140            present: 0,
10141            quorum: 0,
10142            met_quorum: true,
10143            uncontested: Some("only candidate A produced a change".to_owned()),
10144        });
10145        state.reviews = vec![ReviewRound {
10146            round: 1,
10147            head: "deadbeef".to_owned(),
10148            verified_head: None,
10149            verified_at: None,
10150            reviews: Vec::new(),
10151            e2e: Vec::new(),
10152            fix: None,
10153            blocking: 0,
10154            answered: 0,
10155            expected: 0,
10156            clean: true,
10157            verify_retried: false,
10158            e2e_deferred: false,
10159            e2e_defer_reason: None,
10160            progressed: false,
10161            vote_split: false,
10162            reconsideration: Vec::new(),
10163            verdict: None,
10164        }];
10165
10166        let mut runner = Runner {
10167            state,
10168            roles: ResolvedRoles {
10169                implementers: Vec::new(),
10170                judges: Vec::new(),
10171                reviewers: Vec::new(),
10172                fixer: None,
10173                conductor: conductor(),
10174                implementer_roster: Vec::new(),
10175                judge_roster: Vec::new(),
10176                reviewer_roster: Vec::new(),
10177            },
10178            sem: Arc::new(Semaphore::new(1)),
10179            pause: Pause::new(),
10180            interrupt: Pause::new(),
10181        };
10182
10183        let started_marker = repo.join("started.marker");
10184        let release_marker = repo.join("release.marker");
10185        let poller = tokio::spawn(async move {
10186            // Bounded so a regression that never records the task entry
10187            // fails this test in seconds instead of hanging the suite —
10188            // the same shape `a_park_requested_while_a_seat_is_mid_call_
10189            // does_not_cut_it_short` uses for the same reason.
10190            for _ in 0..100 {
10191                if started_marker.exists()
10192                    && let Ok(s) = crate::run::RunState::load(&run_id)
10193                    && let Some(a) = s.active.get("gate")
10194                {
10195                    std::fs::write(&release_marker, b"go").expect("release marker");
10196                    return Some(a.clone());
10197                }
10198                tokio::time::sleep(Duration::from_millis(50)).await;
10199            }
10200            None
10201        });
10202
10203        runner.gate().await.expect("gate");
10204        let captured = poller.await.expect("poller task");
10205        let captured = captured.expect(
10206            "the poller never saw a `gate` task entry in run.json while the command was \
10207             still blocked on its own release marker",
10208        );
10209
10210        assert_eq!(captured.task.as_deref(), Some("gate"));
10211        assert_eq!(captured.node, "gate");
10212        assert_eq!(captured.index, Some(1));
10213        assert_eq!(captured.total, Some(1));
10214        assert!(
10215            captured
10216                .command
10217                .as_deref()
10218                .is_some_and(|c| c.contains("started.marker")),
10219            "{captured:?}"
10220        );
10221
10222        assert!(
10223            runner.state.active.is_empty(),
10224            "the entry must be cleared once the command actually finished: {:?}",
10225            runner.state.active
10226        );
10227        assert!(runner.state.gate_ran);
10228        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
10229    }
10230
10231    /// The hand-off over a blocking finding a reviewer rejected on leaves a
10232    /// record for `land`; one with only a Minor, or no reject, leaves none.
10233    #[tokio::test]
10234    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
10235        use crate::verdict::{Finding, ReviewVote, Severity};
10236        crate::run::pin_test_home();
10237        let tmp = tempfile::tempdir().expect("tempdir");
10238        let repo = tmp.path().join("repo");
10239        std::fs::create_dir_all(&repo).unwrap();
10240        init_repo(&repo);
10241
10242        for (severity, vote, expect) in [
10243            (Severity::Major, ReviewVote::Reject, true),
10244            (Severity::Minor, ReviewVote::Reject, false),
10245            (Severity::Major, ReviewVote::Approve, false),
10246        ] {
10247            let mut round = review_round(false, 1, 1, 1, false, true);
10248            round.reviews = vec![ReviewRecord {
10249                reviewer: 1,
10250                agent: "alpha".to_owned(),
10251                summary: String::new(),
10252                findings: vec![Finding {
10253                    id: "R1-1-1".to_owned(),
10254                    severity,
10255                    file: None,
10256                    line: None,
10257                    title: "t".to_owned(),
10258                    detail: String::new(),
10259                }],
10260                vote: Some(vote),
10261                failed: None,
10262                duration_ms: 0,
10263                attempts: 0,
10264            }];
10265            let mut state = RunState::new(
10266                repo.clone(),
10267                "main".to_owned(),
10268                "deadbeef".to_owned(),
10269                "task".to_owned(),
10270                Config::default(),
10271            );
10272            state.reviews = vec![round];
10273            let mut runner = Runner {
10274                state,
10275                roles: ResolvedRoles {
10276                    implementers: Vec::new(),
10277                    judges: Vec::new(),
10278                    reviewers: Vec::new(),
10279                    fixer: None,
10280                    conductor: conductor(),
10281                    implementer_roster: Vec::new(),
10282                    judge_roster: Vec::new(),
10283                    reviewer_roster: Vec::new(),
10284                },
10285                sem: Arc::new(Semaphore::new(1)),
10286                pause: Pause::new(),
10287                interrupt: Pause::new(),
10288            };
10289            let shell = runner.state.config.shell();
10290            runner
10291                .stop_reviewing("round budget spent", &shell, &repo)
10292                .await
10293                .expect("stop_reviewing");
10294            assert_eq!(runner.state.status, RunStatus::Gating);
10295            assert_eq!(
10296                runner.state.contested_handoff.is_some(),
10297                expect,
10298                "{severity:?} + {vote:?}"
10299            );
10300        }
10301    }
10302
10303    /// The shape the incident this whole fix responds to actually had: the
10304    /// round budget spent, the last round's own e2e blocked on the shared
10305    /// build cache (held here by a live pid — this test process — exactly
10306    /// `cache`'s own unit tests' pattern for "another owner, still alive"
10307    /// without forking a process). `stop_reviewing` must retry it — not
10308    /// silently leave the round looking untouched (the catch-up-only half of
10309    /// the bug), and not read the contention as a red `e2e` and block the
10310    /// run on it (the other half). Called directly, the same way
10311    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
10312    /// above exercises `gate`, so this never needs a real cargo build to
10313    /// reach: the lease is never released, so `with_cache_lease` never gets
10314    /// past acquiring it into anything that would need a real workspace.
10315    #[tokio::test]
10316    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
10317        crate::run::pin_test_home();
10318        let home = crate::run::home();
10319
10320        let tmp = tempfile::tempdir().expect("tempdir");
10321        let repo = tmp.path().join("repo");
10322        std::fs::create_dir_all(&repo).unwrap();
10323        init_repo(&repo);
10324        let head = crate::git::rev_parse(&repo, "HEAD")
10325            .await
10326            .expect("rev-parse");
10327        // Unique to this test, so holding its lease cannot collide with
10328        // another test sharing the same process-wide `home`.
10329        let cache_dir = tmp.path().join("target");
10330
10331        let mut config = Config::default();
10332        config.verify.e2e = vec![format!(
10333            "CARGO_TARGET_DIR='{}' test -f README.md",
10334            cache_dir.display()
10335        )];
10336        config.graph.review_rounds = 1;
10337        // Bounded so a regression that does start waiting fails the test in
10338        // seconds, not hangs it.
10339        config.graph.timeout_verify = Some(2);
10340
10341        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10342        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10343            .expect("no io error acquiring directly")
10344        {
10345            crate::cache::AcquireOutcome::Acquired(g) => g,
10346            crate::cache::AcquireOutcome::Busy(b) => {
10347                panic!("expected the direct acquire to win the lease first: {b:?}")
10348            }
10349        };
10350
10351        let mut state = RunState::new(
10352            repo.clone(),
10353            "main".to_owned(),
10354            head.clone(),
10355            "task".to_owned(),
10356            config,
10357        );
10358        state.candidates = vec![Candidate {
10359            index: 0,
10360            label: 'A',
10361            agent: "alpha".to_owned(),
10362            branch: "does-not-exist".to_owned(),
10363            worktree: repo.clone(),
10364            summary: String::new(),
10365            stat: String::new(),
10366            files: 0,
10367            commits: 0,
10368            empty: false,
10369            failed: None,
10370            verified_noop: None,
10371            duration_ms: 0,
10372            folded: false,
10373        }];
10374        state.tally = Some(Tally {
10375            first_choice: BTreeMap::from([('A', 1)]),
10376            borda: BTreeMap::new(),
10377            winner: 'A',
10378            rankings: 1,
10379            unanimous_initial: true,
10380            deliberated: false,
10381            changed_votes: 0,
10382            unanimous_final: true,
10383            tie_break: None,
10384            judges: 0,
10385            present: 0,
10386            quorum: 0,
10387            met_quorum: true,
10388            uncontested: Some("only candidate A produced a change".to_owned()),
10389        });
10390        // The round budget's last round, deferred: `needs_catchup_run`'s
10391        // other trigger. `stop_reviewing`'s retry machinery must treat this
10392        // exactly like a resource-blocked attempt once it actually runs.
10393        state.reviews = vec![ReviewRound {
10394            round: 1,
10395            head: head.clone(),
10396            verified_head: None,
10397            verified_at: None,
10398            reviews: Vec::new(),
10399            e2e: Vec::new(),
10400            fix: None,
10401            blocking: 1,
10402            answered: 1,
10403            expected: 1,
10404            clean: false,
10405            verify_retried: false,
10406            e2e_deferred: true,
10407            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
10408            progressed: false,
10409            vote_split: false,
10410            reconsideration: Vec::new(),
10411            verdict: None,
10412        }];
10413
10414        let mut runner = Runner {
10415            state,
10416            roles: ResolvedRoles {
10417                implementers: Vec::new(),
10418                judges: Vec::new(),
10419                reviewers: Vec::new(),
10420                fixer: None,
10421                conductor: conductor(),
10422                implementer_roster: Vec::new(),
10423                judge_roster: Vec::new(),
10424                reviewer_roster: Vec::new(),
10425            },
10426            sem: Arc::new(Semaphore::new(1)),
10427            pause: Pause::new(),
10428            interrupt: Pause::new(),
10429        };
10430
10431        let shell = runner.state.config.shell();
10432        runner
10433            .stop_reviewing("round budget spent", &shell, &repo)
10434            .await
10435            .expect("stop_reviewing");
10436
10437        let last = runner.state.reviews.last().expect("round record");
10438        assert_eq!(
10439            last.e2e_status(),
10440            E2eStatus::ResourceBlocked,
10441            "the shared cache is still held; the attempt must read as blocked, not deferred or \
10442             failed: {last:?}"
10443        );
10444        assert_eq!(
10445            last.verified_head.as_deref(),
10446            Some(head.as_str()),
10447            "which commit this attempt targeted is known even though nothing finished checking \
10448             it"
10449        );
10450        let first_attempt_at = last
10451            .verified_at
10452            .expect("when this attempt ran is known too");
10453        assert_ne!(
10454            runner.state.status,
10455            RunStatus::Blocked,
10456            "contention is evidence about the machine, not the patch — it must not settle the \
10457             run as blocked: {:?}",
10458            runner.state.status
10459        );
10460        assert!(
10461            !runner
10462                .state
10463                .events
10464                .iter()
10465                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
10466            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
10467            runner.state.events
10468        );
10469
10470        // The cache is still held: a later reentry must retry the same
10471        // round's verification again — not leave it looking exactly as
10472        // untouched as the first blocked attempt, which is indistinguishable
10473        // from never having tried again at all.
10474        runner
10475            .stop_reviewing("round budget spent", &shell, &repo)
10476            .await
10477            .expect("stop_reviewing retry");
10478        assert_eq!(
10479            runner.state.reviews.len(),
10480            1,
10481            "no new round was started: {:?}",
10482            runner.state.reviews
10483        );
10484        let last = runner.state.reviews.last().expect("round record");
10485        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
10486        assert!(
10487            last.verified_at.expect("still known") > first_attempt_at,
10488            "a second reentry must be a fresh attempt, not a stale copy of the first"
10489        );
10490        assert_ne!(runner.state.status, RunStatus::Blocked);
10491
10492        held.release();
10493    }
10494
10495    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
10496    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
10497    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
10498    /// own top-of-function fast path (`review_conclusion`) correctly reads
10499    /// this shape as `None` rather than guessing `Blocked`, and the loop's
10500    /// own `for` range is empty once the round budget is spent, so
10501    /// `review_loop` must retry the check itself rather than silently doing
10502    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
10503    /// above exercises directly, but through `review_loop`'s own entry point
10504    /// this time, proving the wiring between the two rather than just the
10505    /// retry logic in isolation.
10506    #[tokio::test]
10507    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
10508        crate::run::pin_test_home();
10509        let home = crate::run::home();
10510
10511        let tmp = tempfile::tempdir().expect("tempdir");
10512        let repo = tmp.path().join("repo");
10513        std::fs::create_dir_all(&repo).unwrap();
10514        init_repo(&repo);
10515        let head = crate::git::rev_parse(&repo, "HEAD")
10516            .await
10517            .expect("rev-parse");
10518        let cache_dir = tmp.path().join("target");
10519
10520        let mut config = Config::default();
10521        config.verify.e2e = vec![format!(
10522            "CARGO_TARGET_DIR='{}' test -f README.md",
10523            cache_dir.display()
10524        )];
10525        config.graph.review_rounds = 1;
10526        config.graph.timeout_verify = Some(2);
10527
10528        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
10529        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
10530            .expect("no io error acquiring directly")
10531        {
10532            crate::cache::AcquireOutcome::Acquired(g) => g,
10533            crate::cache::AcquireOutcome::Busy(b) => {
10534                panic!("expected the direct acquire to win the lease first: {b:?}")
10535            }
10536        };
10537
10538        let mut state = RunState::new(
10539            repo.clone(),
10540            "main".to_owned(),
10541            head.clone(),
10542            "task".to_owned(),
10543            config,
10544        );
10545        state.candidates = vec![Candidate {
10546            index: 0,
10547            label: 'A',
10548            agent: "alpha".to_owned(),
10549            branch: "does-not-exist".to_owned(),
10550            worktree: repo.clone(),
10551            summary: String::new(),
10552            stat: String::new(),
10553            files: 0,
10554            commits: 0,
10555            empty: false,
10556            failed: None,
10557            verified_noop: None,
10558            duration_ms: 0,
10559            folded: false,
10560        }];
10561        state.tally = Some(Tally {
10562            first_choice: BTreeMap::from([('A', 1)]),
10563            borda: BTreeMap::new(),
10564            winner: 'A',
10565            rankings: 1,
10566            unanimous_initial: true,
10567            deliberated: false,
10568            changed_votes: 0,
10569            unanimous_final: true,
10570            tie_break: None,
10571            judges: 0,
10572            present: 0,
10573            quorum: 0,
10574            met_quorum: true,
10575            uncontested: Some("only candidate A produced a change".to_owned()),
10576        });
10577        // The exact shape a prior process's `stop_reviewing` would have left
10578        // on disk: the round budget's last round, a real attempt already
10579        // made and already resource-blocked.
10580        state.reviews = vec![ReviewRound {
10581            round: 1,
10582            head: head.clone(),
10583            verified_head: Some(head.clone()),
10584            verified_at: Some(jiff::Timestamp::now()),
10585            reviews: Vec::new(),
10586            e2e: vec![CommandOutcome {
10587                command: format!(
10588                    "CARGO_TARGET_DIR='{}' test -f README.md",
10589                    cache_dir.display()
10590                ),
10591                code: None,
10592                output_tail: "waiting for the shared build cache".to_owned(),
10593                duration_ms: 0,
10594                resource_blocked: true,
10595            }],
10596            fix: None,
10597            blocking: 1,
10598            answered: 1,
10599            expected: 1,
10600            clean: false,
10601            verify_retried: false,
10602            e2e_deferred: false,
10603            e2e_defer_reason: None,
10604            progressed: false,
10605            vote_split: false,
10606            reconsideration: Vec::new(),
10607            verdict: None,
10608        }];
10609
10610        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
10611        let mut runner = Runner {
10612            state,
10613            roles: ResolvedRoles {
10614                implementers: Vec::new(),
10615                judges: Vec::new(),
10616                reviewers: Vec::new(),
10617                fixer: None,
10618                conductor: conductor(),
10619                implementer_roster: Vec::new(),
10620                judge_roster: Vec::new(),
10621                reviewer_roster: Vec::new(),
10622            },
10623            sem: Arc::new(Semaphore::new(1)),
10624            pause: Pause::new(),
10625            interrupt: Pause::new(),
10626        };
10627
10628        // The lease is still held throughout, so this reentry's own retry is
10629        // also contended — proving `review_loop` actually tried again (not
10630        // that it happened to succeed) is what the timestamp comparison
10631        // below is for.
10632        runner.review_loop().await.expect("review_loop");
10633
10634        assert_eq!(
10635            runner.state.reviews.len(),
10636            1,
10637            "no new round was started on top of the unresolved one: {:?}",
10638            runner.state.reviews
10639        );
10640        let last = &runner.state.reviews[0];
10641        assert_eq!(
10642            last.e2e_status(),
10643            E2eStatus::ResourceBlocked,
10644            "still contended: {last:?}"
10645        );
10646        assert!(
10647            last.verified_at.expect("still known") > first_attempt_at,
10648            "review_loop must have actually retried the check, not left it exactly as found"
10649        );
10650        assert_ne!(
10651            runner.state.status,
10652            RunStatus::Blocked,
10653            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
10654            runner.state.status
10655        );
10656
10657        held.release();
10658    }
10659
10660    #[tokio::test]
10661    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
10662        crate::run::pin_test_home();
10663        let tmp = tempfile::tempdir().expect("tempdir");
10664        let repo = tmp.path().join("repo");
10665        std::fs::create_dir_all(&repo).unwrap();
10666        init_repo(&repo);
10667
10668        let mut config = Config::default();
10669        config.merge.mode = MergeMode::Pr;
10670        config.graph.land = true;
10671        config.graph.land_approval = false;
10672
10673        let mut state = RunState::new(
10674            repo.clone(),
10675            "main".to_owned(),
10676            "deadbeef".to_owned(),
10677            "task".to_owned(),
10678            config,
10679        );
10680        state.candidates = vec![Candidate {
10681            index: 0,
10682            label: 'A',
10683            agent: "alpha".to_owned(),
10684            branch: "does-not-exist".to_owned(),
10685            worktree: repo.clone(),
10686            summary: String::new(),
10687            stat: String::new(),
10688            files: 0,
10689            commits: 0,
10690            empty: false,
10691            failed: None,
10692            verified_noop: None,
10693            duration_ms: 0,
10694            folded: false,
10695        }];
10696        state.tally = Some(Tally {
10697            first_choice: BTreeMap::from([('A', 1)]),
10698            borda: BTreeMap::new(),
10699            winner: 'A',
10700            rankings: 1,
10701            unanimous_initial: true,
10702            deliberated: false,
10703            changed_votes: 0,
10704            unanimous_final: true,
10705            tie_break: None,
10706            judges: 0,
10707            present: 0,
10708            quorum: 0,
10709            met_quorum: true,
10710            uncontested: Some("only candidate A produced a change".to_owned()),
10711        });
10712        state.reviews = vec![ReviewRound {
10713            round: 1,
10714            head: "deadbeef".to_owned(),
10715            verified_head: None,
10716            verified_at: None,
10717            reviews: Vec::new(),
10718            e2e: Vec::new(),
10719            fix: None,
10720            blocking: 0,
10721            answered: 0,
10722            expected: 0,
10723            clean: true,
10724            verify_retried: false,
10725            e2e_deferred: false,
10726            e2e_defer_reason: None,
10727            progressed: false,
10728            vote_split: false,
10729            reconsideration: Vec::new(),
10730            verdict: None,
10731        }];
10732        state.gate = vec![CommandOutcome {
10733            command: "test".to_owned(),
10734            code: Some(0),
10735            output_tail: String::new(),
10736            duration_ms: 0,
10737            resource_blocked: false,
10738        }];
10739        state.gate_ran = true;
10740        // A first pass through `merge` already pushed and opened this pull
10741        // request; `status` is `Landing` because a previous call into `land`
10742        // parked or was interrupted before it reached a terminal outcome.
10743        state.status = RunStatus::Landing;
10744        state.merge = Some(MergeOutcome {
10745            mode: MergeMode::Pr,
10746            ok: true,
10747            detail: "https://example.invalid/x/y/pull/1".to_owned(),
10748            empty: false,
10749        });
10750
10751        // The Landing-resume shortcut calls `run_land` directly rather than
10752        // through `merge`, which is exactly the call site that used to skip
10753        // `settle_questions` - see the fixture below.
10754        ask_test_home();
10755        let store = ask::Questions::open();
10756        let q = ask_open_question(&store, &state.id);
10757
10758        let mut runner = Runner {
10759            state,
10760            roles: ResolvedRoles {
10761                implementers: Vec::new(),
10762                judges: Vec::new(),
10763                reviewers: Vec::new(),
10764                fixer: None,
10765                conductor: conductor(),
10766                implementer_roster: Vec::new(),
10767                judge_roster: Vec::new(),
10768                reviewer_roster: Vec::new(),
10769            },
10770            sem: Arc::new(Semaphore::new(1)),
10771            pause: Pause::new(),
10772            interrupt: Pause::new(),
10773        };
10774
10775        // `execute`, not `merge` directly: the Landing-resume shortcut lives
10776        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
10777        // exactly because `review_loop` would otherwise clobber the marker
10778        // first.
10779        runner.execute().await.expect("execute");
10780
10781        assert_eq!(
10782            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
10783            Some("https://example.invalid/x/y/pull/1"),
10784            "reentry must not push again or open a second pull request over the \
10785             one `land` is already watching"
10786        );
10787        assert_ne!(
10788            runner.state.status,
10789            RunStatus::Landing,
10790            "land could not actually reach the fake pull request, so it must \
10791             have given up rather than left the run silently parked forever"
10792        );
10793        // `land` could not reach the fake pull request, so it gave up into
10794        // `Blocked` - still resumable, so the question must not have been
10795        // swept just because this branch now also calls `settle_questions`.
10796        assert_eq!(runner.state.status, RunStatus::Blocked);
10797        assert!(
10798            store.get(&q.id).unwrap().status.open(),
10799            "Blocked is still alive; settle_questions must have been a no-op here"
10800        );
10801    }
10802
10803    fn state_with_round(round: ReviewRound) -> RunState {
10804        let mut s = RunState::new(
10805            PathBuf::from("/repo"),
10806            "main".to_owned(),
10807            "abc1234".to_owned(),
10808            "add retries".to_owned(),
10809            Config::default(),
10810        );
10811        s.reviews = vec![round];
10812        s
10813    }
10814
10815    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
10816        crate::verdict::Finding {
10817            id: id.to_owned(),
10818            severity,
10819            file: None,
10820            line: None,
10821            title: title.to_owned(),
10822            detail: String::new(),
10823        }
10824    }
10825
10826    #[test]
10827    fn pr_body_names_open_findings_and_declined_ones() {
10828        let round = ReviewRound {
10829            round: 2,
10830            head: "deadbee".to_owned(),
10831            verified_head: None,
10832            verified_at: None,
10833            reviews: vec![ReviewRecord {
10834                attempts: 0,
10835                reviewer: 1,
10836                agent: "alpha".to_owned(),
10837                summary: String::new(),
10838                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
10839                vote: None,
10840                failed: None,
10841                duration_ms: 0,
10842            }],
10843            e2e: vec![CommandOutcome {
10844                command: "cargo test".to_owned(),
10845                code: Some(0),
10846                output_tail: String::new(),
10847                duration_ms: 0,
10848                resource_blocked: false,
10849            }],
10850            verify_retried: false,
10851            e2e_deferred: false,
10852            e2e_defer_reason: None,
10853            fix: Some(FixRecord {
10854                agent: "alpha".to_owned(),
10855                addressed: Vec::new(),
10856                rejected: vec![crate::verdict::Rejection {
10857                    id: "R1-1-1".to_owned(),
10858                    why: "not reachable from any caller".to_owned(),
10859                }],
10860                notes: String::new(),
10861                committed: true,
10862                failed: None,
10863                duration_ms: 0,
10864                continuation: None,
10865            }),
10866            blocking: 0,
10867            answered: 1,
10868            expected: 1,
10869            clean: false,
10870            progressed: true,
10871            vote_split: false,
10872            reconsideration: Vec::new(),
10873            verdict: None,
10874        };
10875        let state = state_with_round(round);
10876        let body = pr_message(&state, 'A').body;
10877
10878        assert!(body.contains("add retries"), "the task must still be there");
10879        assert!(body.contains("R2-1-1"), "{body}");
10880        assert!(body.contains("unused import"), "{body}");
10881        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
10882        assert!(
10883            body.contains("not reachable from any caller"),
10884            "the reason it was declined: {body}"
10885        );
10886    }
10887
10888    #[test]
10889    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
10890        let round = ReviewRound {
10891            round: 1,
10892            head: "deadbee".to_owned(),
10893            verified_head: None,
10894            verified_at: None,
10895            reviews: vec![ReviewRecord {
10896                attempts: 0,
10897                reviewer: 1,
10898                agent: "alpha".to_owned(),
10899                summary: String::new(),
10900                findings: Vec::new(),
10901                vote: None,
10902                failed: None,
10903                duration_ms: 0,
10904            }],
10905            e2e: Vec::new(),
10906            verify_retried: false,
10907            e2e_deferred: false,
10908            e2e_defer_reason: None,
10909            fix: None,
10910            blocking: 0,
10911            answered: 1,
10912            expected: 1,
10913            clean: true,
10914            progressed: false,
10915            vote_split: false,
10916            reconsideration: Vec::new(),
10917            verdict: None,
10918        };
10919        let state = state_with_round(round);
10920        let body = pr_message(&state, 'A').body;
10921        assert!(!body.contains("Open review findings"), "{body}");
10922        assert!(!body.contains("Declined"), "{body}");
10923    }
10924
10925    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
10926        let mut state = RunState::new(
10927            PathBuf::from("/repo"),
10928            "main".to_owned(),
10929            "abc1234".to_owned(),
10930            instruction.to_owned(),
10931            Config::default(),
10932        );
10933        state.candidates.push(Candidate {
10934            index: 0,
10935            label: 'A',
10936            agent: "alpha".to_owned(),
10937            branch: "magi/x/A".to_owned(),
10938            worktree: PathBuf::from("/wt"),
10939            summary: summary.to_owned(),
10940            stat: String::new(),
10941            files: 1,
10942            commits: 1,
10943            empty: false,
10944            failed: None,
10945            verified_noop: None,
10946            folded: false,
10947            duration_ms: 0,
10948        });
10949        state
10950    }
10951
10952    fn review_state(subjects: &[&str]) -> RunState {
10953        let mut state = state_with_summary(
10954            "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",
10955            "",
10956        );
10957        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
10958        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
10959        state
10960    }
10961
10962    /// A branch rebased onto a main that moved past the recorded
10963    /// `base_commit` is titled from its own first commit, never main's.
10964    #[tokio::test]
10965    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
10966        ask_test_home();
10967        let tmp = tempfile::tempdir().unwrap();
10968        let repo = tmp.path().join("repo");
10969        std::fs::create_dir_all(&repo).unwrap();
10970        init_repo(&repo);
10971        let origin = tmp.path().join("origin.git");
10972        let g = |dir: &Path, args: &[&str]| {
10973            let out = std::process::Command::new("git")
10974                .args(args)
10975                .current_dir(dir)
10976                .quiet()
10977                .output()
10978                .expect("spawn git");
10979            assert!(
10980                out.status.success(),
10981                "git {args:?}: {}",
10982                String::from_utf8_lossy(&out.stderr)
10983            );
10984        };
10985        g(
10986            tmp.path(),
10987            &[
10988                "clone",
10989                "--bare",
10990                "-q",
10991                repo.to_str().unwrap(),
10992                origin.to_str().unwrap(),
10993            ],
10994        );
10995        g(
10996            &repo,
10997            &["remote", "add", "origin", origin.to_str().unwrap()],
10998        );
10999        let c1 = git::rev_parse(&repo, "main").await.unwrap();
11000
11001        // Main moves on; the branch is built on top of the new main.
11002        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
11003        g(&repo, &["add", "-A"]);
11004        g(
11005            &repo,
11006            &["commit", "-q", "-m", "chore(deps): update a crate"],
11007        );
11008        g(&repo, &["push", "-q", "origin", "main"]);
11009        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
11010        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
11011        g(&repo, &["add", "-A"]);
11012        g(
11013            &repo,
11014            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
11015        );
11016        g(&repo, &["checkout", "-q", "main"]);
11017
11018        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
11019        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
11020        // Without a readable tracking ref the recorded base's merge base is used.
11021        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
11022        assert_eq!(fallback, c1);
11023
11024        let mut state = review_state(&[
11025            "chore(deps): update a crate",
11026            "fix(daemon): apply a chosen action",
11027        ]);
11028        state.repo = repo.clone();
11029        state.base_branch = "main".to_owned();
11030        state.base_commit = c1;
11031        refresh_reviewed_commits(&mut state, "feat/own").await;
11032        assert_eq!(
11033            state.reviewed_commits,
11034            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
11035        );
11036        assert_eq!(
11037            review_title(&state).as_deref(),
11038            Some("fix(daemon): apply a chosen action")
11039        );
11040        assert_eq!(
11041            leaked_subjects(&state, "feat/own").await,
11042            Some(vec!["chore(deps): update a crate".to_owned()])
11043        );
11044        // A stale tracking ref is still used when the fetch fails, but the
11045        // leak list is withheld.
11046        state.config.merge.remote = "nowhere".to_owned();
11047        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
11048    }
11049
11050    #[test]
11051    fn pr_message_review_single_commit_uses_its_subject() {
11052        let state = review_state(&["feat(nats): per-role user"]);
11053        let m = pr_message(&state, 'A');
11054        assert_eq!(m.title, "feat(nats): per-role user");
11055        assert!(!m.body.contains("Review the work already"), "{}", m.body);
11056        assert!(m.body.contains("## Commits under review"), "{}", m.body);
11057    }
11058
11059    #[test]
11060    fn pr_message_review_multi_commit_takes_the_oldest() {
11061        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
11062        let m = pr_message(&state, 'A');
11063        assert_eq!(m.title, "feat: the change");
11064        for s in ["feat: the change", "fix: typo", "fix: again"] {
11065            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
11066        }
11067    }
11068
11069    #[test]
11070    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
11071        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
11072            let mut state = review_state(&[first, "fix: later fixup"]);
11073            state.candidates[0].branch = "機能/ログイン".to_owned();
11074            let m = pr_message(&state, 'A');
11075            assert!(
11076                m.title.starts_with("chore: land candidate A of run"),
11077                "{}",
11078                m.title
11079            );
11080        }
11081    }
11082
11083    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
11084        BranchFacts {
11085            commits: commits
11086                .iter()
11087                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
11088                .collect(),
11089            stat: stat.to_owned(),
11090        }
11091    }
11092
11093    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
11094        let mut r = review_round(true, 0, 1, 1, true, true);
11095        r.round = round;
11096        r.fix = notes.map(|n| FixRecord {
11097            agent: "fixer".to_owned(),
11098            addressed: Vec::new(),
11099            rejected: Vec::new(),
11100            notes: n.to_owned(),
11101            committed: true,
11102            failed: None,
11103            duration_ms: 0,
11104            continuation: None,
11105        });
11106        r
11107    }
11108
11109    #[test]
11110    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
11111        let state = review_state(&["ignored"]);
11112        let f = facts(
11113            &[
11114                (
11115                    "fix(login): resolve PATH on macOS",
11116                    "Login shells skip rc files.",
11117                ),
11118                ("fix: address review", ""),
11119            ],
11120            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
11121        );
11122        let m = pr_message_with(&state, 'A', Some(&f));
11123        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
11124        assert!(
11125            m.body
11126                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
11127            "{}",
11128            m.body
11129        );
11130        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
11131        assert!(m.body.contains("## Diff stat"), "{}", m.body);
11132        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
11133        for banned in [
11134            "Review the work already",
11135            "no task statement",
11136            "Original task",
11137        ] {
11138            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
11139        }
11140        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
11141    }
11142
11143    #[test]
11144    fn pr_message_review_truncates_a_huge_first_commit_body() {
11145        let state = review_state(&["ignored"]);
11146        let f = facts(
11147            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
11148            "s",
11149        );
11150        let m = pr_message_with(&state, 'A', Some(&f));
11151        assert!(m.body.len() < 30_000, "{}", m.body.len());
11152        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
11153        assert!(
11154            m.body.contains("- ... 1 more commit(s)"),
11155            "{}",
11156            m.body.len()
11157        );
11158        assert!(m.body.ends_with("magi:candidate-a\n"));
11159    }
11160
11161    #[test]
11162    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
11163        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
11164        assert_eq!(m.title, "feat: x");
11165        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
11166        assert!(!m.body.contains("Diff stat"), "{}", m.body);
11167        assert!(!m.body.contains("no task statement"), "{}", m.body);
11168    }
11169
11170    #[test]
11171    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
11172        let mut state = review_state(&["日本語の件名"]);
11173        state.candidates[0].branch = "fix/macos-login-path".to_owned();
11174        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
11175        state.candidates[0].branch = "機能/ログイン".to_owned();
11176        assert!(
11177            pr_message(&state, 'A')
11178                .title
11179                .starts_with("chore: land candidate A")
11180        );
11181    }
11182
11183    #[test]
11184    fn pr_message_review_fixes_survive_a_clean_final_round() {
11185        let mut state = review_state(&["feat: x"]);
11186        state.reviews = vec![
11187            round_with_notes(1, Some("handled the PATH case")),
11188            round_with_notes(2, None),
11189        ];
11190        let body = pr_message(&state, 'A').body;
11191        assert!(
11192            body.contains("## Review fixes\n\nhandled the PATH case\n"),
11193            "{body}"
11194        );
11195        assert!(!body.contains("### Round"), "{body}");
11196
11197        state.reviews = vec![
11198            round_with_notes(1, Some("first fix")),
11199            round_with_notes(2, Some("")),
11200            round_with_notes(3, Some("second fix")),
11201            round_with_notes(4, None),
11202        ];
11203        let body = pr_message(&state, 'A').body;
11204        assert!(body.contains("### Round 1\n\nfirst fix"), "{body}");
11205        assert!(body.contains("### Round 3\n\nsecond fix"), "{body}");
11206        assert!(!body.contains("### Round 2"), "{body}");
11207    }
11208
11209    #[test]
11210    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
11211        let state = state_with_summary(
11212            "add retries to the client",
11213            "TITLE: feat: retries\n\nDid it.",
11214        );
11215        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
11216        assert_eq!(m.title, "feat: retries");
11217        assert!(
11218            m.body.contains("<summary>Original task</summary>"),
11219            "{}",
11220            m.body
11221        );
11222        assert!(!m.body.contains("Commits under review"), "{}", m.body);
11223        assert!(
11224            m.body
11225                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
11226            "{}",
11227            m.body
11228        );
11229    }
11230
11231    #[test]
11232    fn pr_message_review_bounds_a_long_english_subject() {
11233        let long = format!("feat: {}", "word ".repeat(100));
11234        let m = pr_message(&review_state(&[&long]), 'A');
11235        assert!(m.title.starts_with("feat: word"), "{}", m.title);
11236        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11237    }
11238
11239    #[test]
11240    fn pr_message_implementation_run_is_unchanged_by_review_support() {
11241        let state = state_with_summary("add retries\n\ndetails", "- did some things");
11242        let m = pr_message(&state, 'A');
11243        assert_eq!(m.title, "add retries");
11244        assert!(m.body.contains("<summary>Original task</summary>"));
11245        assert!(!m.body.contains("Commits under review"));
11246        assert_eq!(landing_subject_source(&state), state.instruction);
11247    }
11248
11249    #[test]
11250    fn review_run_squash_subject_is_the_change_not_the_prompt() {
11251        let state = review_state(&["feat: the change", "fix: typo"]);
11252        let source = landing_subject_source(&state);
11253        assert_eq!(land::merge_subject("", &source), "feat: the change");
11254        assert_eq!(
11255            land::merge_subject("magi: candidate A (uncommitted work)", &source),
11256            "feat: the change"
11257        );
11258        // An operator's rename still wins.
11259        assert_eq!(
11260            land::merge_subject("feat: renamed by hand", &source),
11261            "feat: renamed by hand"
11262        );
11263        let blank = review_state(&["日本語"]);
11264        assert!(
11265            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
11266        );
11267    }
11268
11269    #[test]
11270    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
11271        let state = review_state(&["feat: the change"]);
11272        let source = landing_subject_source(&state);
11273        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
11274        assert_eq!(
11275            land::merge_subject(landing_title(&state, old), &source),
11276            "feat: the change"
11277        );
11278        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
11279        let task = state_with_summary("add retries", "");
11280        assert_eq!(landing_title(&task, old), old);
11281    }
11282
11283    #[test]
11284    fn pr_message_describes_the_change_not_the_task() {
11285        let state = state_with_summary(
11286            "今回やってほしいこと: results projector を直す",
11287            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
11288        );
11289        let m = pr_message(&state, 'A');
11290        assert_eq!(m.title, "fix(web): batch the runs list reads");
11291        assert!(
11292            m.body.starts_with("## Summary\n\n- reads run.json once"),
11293            "{}",
11294            m.body
11295        );
11296        assert!(!m.body.contains("TITLE:"), "{}", m.body);
11297        let task_at = m.body.find("今回やってほしいこと").unwrap();
11298        let details_at = m.body.find("<details>").unwrap();
11299        assert!(
11300            details_at < task_at,
11301            "the task lives inside <details>: {}",
11302            m.body
11303        );
11304        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
11305        assert!(m.body.contains("magi:candidate-a"));
11306    }
11307
11308    #[test]
11309    fn pr_message_falls_back_to_the_task_without_a_title_line() {
11310        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
11311        let m = pr_message(&state, 'A');
11312        assert_eq!(m.title, "add retries");
11313        assert!(
11314            m.body.contains("## Summary\n\n- did some things"),
11315            "{}",
11316            m.body
11317        );
11318
11319        let none = RunState::new(
11320            PathBuf::from("/repo"),
11321            "main".to_owned(),
11322            "abc1234".to_owned(),
11323            "add retries".to_owned(),
11324            Config::default(),
11325        );
11326        let m = pr_message(&none, 'A');
11327        assert_eq!(m.title, "add retries");
11328        assert!(!m.body.contains("## Summary"), "{}", m.body);
11329    }
11330
11331    #[test]
11332    fn pr_message_refuses_the_candidate_commit_subject() {
11333        for bad in [
11334            "TITLE: magi: candidate A (uncommitted work)",
11335            "TITLE: chore: stuff (uncommitted work)",
11336            "TITLE:   ",
11337        ] {
11338            let state = state_with_summary("add retries", bad);
11339            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
11340        }
11341    }
11342
11343    #[test]
11344    fn pr_message_bounds_a_very_long_task_and_title() {
11345        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
11346        let state = state_with_summary(&long, "- nothing");
11347        let m = pr_message(&state, 'A');
11348        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11349        assert!(!m.title.contains('\n'));
11350
11351        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
11352        let m = pr_message(&state, 'A');
11353        assert!(m.title.starts_with("feat: "));
11354        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
11355        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
11356    }
11357
11358    fn long_title_of(instruction: &str) -> String {
11359        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
11360    }
11361
11362    #[test]
11363    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
11364        let first = "Make the landing path keep a readable title for long tasks";
11365        let line = format!(
11366            "{first}. {}",
11367            "And then keep going with more words ".repeat(20)
11368        );
11369        let t = long_title_of(&line);
11370        assert_eq!(t, first);
11371        assert!(!t.starts_with("chore: land"));
11372    }
11373
11374    #[test]
11375    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
11376        let line = "word ".repeat(200);
11377        let t = long_title_of(&line);
11378        assert!(t.ends_with("word..."), "{t}");
11379        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
11380    }
11381
11382    #[test]
11383    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
11384        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
11385            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
11386        }
11387    }
11388
11389    #[test]
11390    fn pr_message_title_limit_is_exact() {
11391        let at = "a".repeat(PR_TITLE_MAX);
11392        assert_eq!(long_title_of(&at), at);
11393        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
11394        assert!(over.ends_with("..."), "{over}");
11395        assert_eq!(over.chars().count(), PR_TITLE_MAX);
11396    }
11397
11398    #[test]
11399    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
11400        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
11401        let t = long_title_of(&line);
11402        assert!(t.ends_with("..."), "{t}");
11403        assert!(t.is_ascii(), "{t}");
11404    }
11405
11406    #[test]
11407    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
11408        let line = format!(
11409            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
11410            "plus more filler words ".repeat(20)
11411        );
11412        let t = long_title_of(&line);
11413        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
11414    }
11415
11416    #[test]
11417    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
11418        let line = format!("\n\n# {}", "title words ".repeat(40));
11419        let state = state_with_summary(&line, "- nothing");
11420        let m = pr_message(&state, 'A');
11421        assert!(m.title.starts_with("title words"), "{}", m.title);
11422        assert_eq!(
11423            land::merge_subject(&m.title, &landing_subject_source(&state)),
11424            m.title
11425        );
11426        // An operator's rename wins untouched.
11427        assert_eq!(
11428            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
11429            "feat: renamed by hand"
11430        );
11431    }
11432
11433    #[test]
11434    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
11435        // What magi itself writes stays English under any configured language,
11436        // so a future localisation of these headings fails here. (The agents'
11437        // own text is held to English by the prompt only; magi cannot check it.)
11438        let mut state = state_with_summary(
11439            "add retries",
11440            "TITLE: fix(web): batch reads\n- reads run.json once",
11441        );
11442        state.config.graph.language = "ja".to_owned();
11443        let m = pr_message(&state, 'A');
11444        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
11445
11446        // The task is the operator's own text: it goes in untouched, and the
11447        // fallback title (no summary) may be in its language too.
11448        let task = "今回やってほしいこと: results projector を直す";
11449        let mut state = state_with_summary(task, "- no title line");
11450        state.config.graph.language = "ja".to_owned();
11451        let m = pr_message(&state, 'A');
11452        assert_eq!(
11453            m.title,
11454            format!("chore: land candidate A of run {}", state.id)
11455        );
11456        assert!(
11457            m.body.contains(&format!(
11458                "<summary>Original task</summary>\n\n{task}\n\n</details>"
11459            )),
11460            "{}",
11461            m.body
11462        );
11463    }
11464
11465    #[test]
11466    fn pr_message_scrubs_home_paths_and_addresses() {
11467        let state = state_with_summary(
11468            "fix it in /Users/someone/src/x",
11469            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
11470        );
11471        let m = pr_message(&state, 'A');
11472        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
11473            assert!(!m.body.contains(leak), "{}", m.body);
11474        }
11475        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
11476    }
11477
11478    #[test]
11479    fn pr_message_survives_a_task_that_closes_details() {
11480        let state = state_with_summary("a </details> b", "TITLE: fix: x");
11481        let m = pr_message(&state, 'A');
11482        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
11483    }
11484
11485    #[test]
11486    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
11487        let cmd = manual_merge_command(
11488            MergeStyle::Squash,
11489            Path::new("/repo"),
11490            "b",
11491            "fix: \"quoted\" $(x) `y`\n\nbody",
11492        );
11493        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
11494    }
11495
11496    #[test]
11497    fn manual_merge_command_matches_the_configured_style() {
11498        let repo = Path::new("/repo");
11499        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
11500
11501        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
11502        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
11503
11504        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
11505        assert_eq!(
11506            squash,
11507            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
11508             \"Merge magi run 0832 (candidate A)\""
11509        );
11510
11511        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
11512        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
11513    }
11514
11515    #[test]
11516    fn a_nudge_gets_a_quarter_of_the_budget() {
11517        // The judge and implement budgets magi ships with.
11518        assert_eq!(retry_budget(secs(1200), true), secs(300));
11519        assert_eq!(retry_budget(secs(3600), true), secs(900));
11520    }
11521
11522    #[test]
11523    fn a_resent_prompt_keeps_the_whole_budget() {
11524        // The seat kept no context, so the retry is the original job again and
11525        // shortening it would only guarantee a second failure.
11526        assert_eq!(retry_budget(secs(1200), false), secs(1200));
11527        assert_eq!(retry_budget(secs(60), false), secs(60));
11528    }
11529
11530    #[test]
11531    fn the_floor_never_exceeds_the_original_budget() {
11532        // A short configured timeout must not be *raised* by the floor: the
11533        // operator asked for a bound, and a retry may not outlast the attempt
11534        // it is retrying.
11535        assert_eq!(retry_budget(secs(60), true), secs(60));
11536        assert_eq!(retry_budget(secs(480), true), secs(120));
11537        assert_eq!(retry_budget(secs(0), true), secs(0));
11538    }
11539
11540    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
11541        agent::CommandEvidence {
11542            id: "item1".to_owned(),
11543            description: "cargo test".to_owned(),
11544            exit_code,
11545            result_summary: String::new(),
11546            source: "codex".to_owned(),
11547        }
11548    }
11549
11550    #[test]
11551    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
11552        // No evidence is not the same fact as unconfirmed evidence: a
11553        // backend with no adapter, or a reply that ran no commands at all,
11554        // must not be misread as carrying a dangling job.
11555        assert!(!has_unconfirmed_command(&[]));
11556    }
11557
11558    #[test]
11559    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
11560        // Deliberately not a check on the exit code's *value*: a fixer
11561        // legitimately runs something that fails mid-iteration before it
11562        // succeeds, and that must never by itself reopen a valid report.
11563        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
11564        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
11565        assert!(!has_unconfirmed_command(&[
11566            evidence(Some(0)),
11567            evidence(Some(101))
11568        ]));
11569    }
11570
11571    #[test]
11572    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
11573        assert!(has_unconfirmed_command(&[
11574            evidence(Some(0)),
11575            evidence(None)
11576        ]));
11577    }
11578
11579    #[test]
11580    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
11581        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11582        assert_eq!(
11583            verified_noop_claim(true, &[], text).as_deref(),
11584            Some("already fixed by b32cfc4, on main.")
11585        );
11586    }
11587
11588    #[test]
11589    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
11590        // A timeout or a bad exit code reads as the ordinary loss it is,
11591        // whatever the reply's own prose claims.
11592        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11593        assert!(verified_noop_claim(false, &[], text).is_none());
11594    }
11595
11596    #[test]
11597    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
11598        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
11599        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
11600        // A confirmed command alongside the marker is fine.
11601        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
11602    }
11603
11604    #[test]
11605    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
11606        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
11607    }
11608
11609    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
11610    /// pair, in order, labelled A, B, C, ...
11611    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
11612        runner.state.candidates = shape
11613            .iter()
11614            .enumerate()
11615            .map(|(i, &(empty, verified))| Candidate {
11616                index: i,
11617                label: (b'A' + i as u8) as char,
11618                agent: "sonnet".to_owned(),
11619                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
11620                worktree: PathBuf::from(format!("/wt/{i}")),
11621                summary: String::new(),
11622                stat: String::new(),
11623                files: 0,
11624                commits: 0,
11625                empty,
11626                failed: None,
11627                verified_noop: verified.map(str::to_owned),
11628                duration_ms: 0,
11629                folded: false,
11630            })
11631            .collect();
11632    }
11633
11634    #[test]
11635    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
11636        ask_test_home();
11637        let mut runner = runner_at(RunStatus::Implementing);
11638        set_candidates(
11639            &mut runner,
11640            &[
11641                (true, Some("already on main at b32cfc4")),
11642                (true, Some("same fix, see the existing test")),
11643            ],
11644        );
11645
11646        runner
11647            .after_implement()
11648            .expect("a verified no-op is not an error");
11649
11650        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
11651    }
11652
11653    #[test]
11654    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
11655        ask_test_home();
11656        let mut runner = runner_at(RunStatus::Implementing);
11657        // Candidate A declares a verified no-op; candidate B simply wrote
11658        // nothing and said nothing about why. One candidate's claim is not
11659        // the whole run's agreement.
11660        set_candidates(
11661            &mut runner,
11662            &[(true, Some("already on main at b32cfc4")), (true, None)],
11663        );
11664
11665        let err = runner
11666            .after_implement()
11667            .expect_err("an unverified empty candidate must still fail the run");
11668
11669        assert!(
11670            err.to_string().contains("no candidate produced a change"),
11671            "{err}"
11672        );
11673        assert_eq!(runner.state.status, RunStatus::Failed);
11674    }
11675
11676    #[test]
11677    fn after_implement_still_fails_an_ordinary_all_empty_run() {
11678        ask_test_home();
11679        let mut runner = runner_at(RunStatus::Implementing);
11680        set_candidates(&mut runner, &[(true, None), (true, None)]);
11681
11682        let err = runner
11683            .after_implement()
11684            .expect_err("no candidate declared anything; this is an ordinary failure");
11685
11686        assert!(
11687            err.to_string().contains("no candidate produced a change"),
11688            "{err}"
11689        );
11690        assert_eq!(runner.state.status, RunStatus::Failed);
11691    }
11692}