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::run::{
46    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
47    DeliberationRound, DeliberationTurn, E2eStatus, FixRecord, JobRecord, JobStatus, Judgement,
48    MergeOutcome, OperatorFixFinding, OperatorFixOutcome, OperatorFixRequest, QuotaLoss,
49    ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState, RunStatus, Tally, VoteRecord, tail,
50    write_artifact,
51};
52use crate::verdict::{
53    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
54    ReviewVote, Severity,
55};
56
57/// How much verification output is kept and fed back to the fixer.
58const OUTPUT_TAIL: usize = 8_000;
59
60/// Bytes of a failing command's output kept in an event, so the reason a run
61/// stopped is readable from the report without opening `run.json`.
62const EVENT_OUTPUT_TAIL: usize = 2_000;
63
64/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
65/// command's pid before releasing the build cache's lease.
66const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
67
68/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
69/// command's pid to actually exit before giving up and releasing anyway.
70///
71/// A timeout means the process was asked to die (`kill_on_drop`,
72/// `start_kill`), not that it already has — on Windows in particular that can
73/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
74/// the instant the command returns would let the very next acquirer (this
75/// run's own next round, another run's verification, the janitor's prune)
76/// start touching the same directory while it might still be writing to it,
77/// so this polls the actual pid — real confirmation, not a fixed guess —
78/// until it is gone or this ceiling is reached. It is still not full
79/// process-tree reaping: a grandchild the timed-out process spawned and that
80/// outlives it independently is invisible to a pid check, and continuing to
81/// observe and collect *that* stays a different piece of work with its own
82/// owner. Set generously because the common case returns early the moment
83/// the pid is confirmed gone, not because every timeout pays this in full.
84const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
85
86/// Consecutive review rounds with no tree progress (see
87/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
88/// instead of spending the rest of the round budget.
89///
90/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
91/// legitimately finds nothing left to change (its previous round's fix already
92/// covered it, and this round's reviewers re-raised only nits) looks the same
93/// as one that is spinning, for exactly one round. Two in a row is where the
94/// two stop being distinguishable, and a review round on this workload has
95/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
96/// third attempt at a tree that has not moved twice running is pure cost.
97/// This does not touch `review_rounds` itself, which stays the operator's
98/// call.
99pub(crate) const STAGNANT_LIMIT: usize = 2;
100
101/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
102/// a base that moved before giving up and leaving the run `Blocked` for a
103/// person.
104///
105/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
106/// that keeps moving faster than a run can catch it is not something more
107/// rebasing fixes, it is a person's call. Not the same *number as*
108/// `land_rounds` - this budget is spent before a pull request exists, land's
109/// after - but bounded for the identical reason, so it uses the same
110/// default. Counted across both call sites in [`Runner::finish_after_tally`]
111/// (once before review, once before the gate), because either one finding
112/// the base still moving is the same signal.
113const BASE_SYNC_ROUNDS: usize = 4;
114
115/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
116/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
117/// reply held no [`FixReport`].
118///
119/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
120/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
121/// "I'll pause here until the `cargo make check` background run reports
122/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
123/// No `FixReport` was ever collected from that seat, and the run moved on to
124/// the next review round regardless.
125///
126/// Bounded independently of `review_rounds` and `graph.retries`: this
127/// recovers one seat's missing report mid-round, not a new round of review or
128/// an ordinary parse retry, and must not itself become the unbounded wait the
129/// rest of this module exists to avoid.
130const MAX_FIX_CONTINUATIONS: usize = 2;
131
132/// One queued agent invocation.
133///
134/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
135/// CLI hung up on its own stream is asked again from the same job rather than
136/// rebuilt from scratch. See [`Runner::resume_undelivered`].
137#[derive(Clone)]
138struct SeatJob {
139    spec: AgentSpec,
140    seat: SeatState,
141    cwd: PathBuf,
142    prompt: String,
143    timeout: Duration,
144    allow_write: bool,
145    sessions: bool,
146    artifacts: PathBuf,
147    stem: String,
148}
149
150/// How the graph reads one agent invocation.
151///
152/// Quota is split out from an ordinary failure on purpose: a rate-limited call
153/// is known to fail again if retried now, so the retry loop must not spend an
154/// attempt on it. `Dropped` is split out for the opposite reason: unlike
155/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
156/// error JSON, never the agent's answer — a caller that matched only
157/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
158/// left to read that JSON as if it were usable output. `resume_undelivered`
159/// is the only caller that acts on it; everywhere else it is reported like an
160/// ordinary failure.
161enum AgentOutcome {
162    /// A usable output.
163    Ok(AgentOutput),
164    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
165    Quota(AgentOutput),
166    /// The CLI hung up on its own stream after billed work. See
167    /// [`agent::AgentOutput::work_undelivered`].
168    Dropped(AgentOutput),
169    /// Any other failure: a timeout, a bad exit code, an empty reply.
170    Failed(String),
171}
172
173/// A request to park the run at its next node boundary.
174///
175/// Cloning is how the request travels: the loop keeps one handle and hands a
176/// clone to each [`Runner`], and every clone points at the same flag. There
177/// is no channel because there is nothing to send - the only message is
178/// "park", it is idempotent, and a flag cannot be missed by a receiver that
179/// was not listening yet.
180///
181/// The boundary is what makes this cheap. Every node writes the run's state
182/// before the next one starts, and every node skips what is already recorded:
183/// `prep` returns early once candidates exist, `implement` asks only the seats
184/// with nothing on disk, `judge` returns early once judgements exist. So a
185/// parked run resumes into exactly the node it stopped before, and no agent
186/// work is thrown away. Killing the process mid-node, by contrast, loses
187/// whatever the seats in flight had not yet written - which for an implement
188/// wave is an hour of paid work.
189///
190/// A [`Runner`] watches two independent handles of this type - see
191/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
192/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
193/// clone covering the whole daemon's lifetime and is never asked to un-park,
194/// which is correct exactly because nothing is dispatched after it fires.
195/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
196/// that parks for an interrupted task must go on to run other tasks
197/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
198/// reusing the daemon-wide one.
199#[derive(Debug, Clone, Default)]
200pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<String>>>);
201
202impl Pause {
203    /// A pause nobody has asked for yet.
204    #[must_use]
205    pub fn new() -> Self {
206        Self::default()
207    }
208
209    /// Ask the run to park at its next node boundary. Idempotent.
210    pub fn park(&self) {
211        self.0.store(true, Ordering::SeqCst);
212    }
213
214    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
215    /// fold into the run's own `park` event - so an operator reading the run
216    /// later knows this was a deliberate interrupt rather than a shutdown or
217    /// a binary swap. The first reason recorded wins; a park already in
218    /// flight is not relabelled by a second, unrelated request.
219    pub fn park_because(&self, reason: impl Into<String>) {
220        let mut reason_guard = self
221            .1
222            .lock()
223            .unwrap_or_else(std::sync::PoisonError::into_inner);
224        if reason_guard.is_none() {
225            *reason_guard = Some(reason.into());
226        }
227        drop(reason_guard);
228        self.park();
229    }
230
231    /// Has a park been asked for?
232    #[must_use]
233    pub fn parked(&self) -> bool {
234        self.0.load(Ordering::SeqCst)
235    }
236
237    /// Why the park was asked for, when the caller used [`Pause::park_because`].
238    #[must_use]
239    pub fn reason(&self) -> Option<String> {
240        self.1
241            .lock()
242            .unwrap_or_else(std::sync::PoisonError::into_inner)
243            .clone()
244    }
245}
246
247/// Drives one run.
248pub struct Runner {
249    /// Run state; public so the CLI can report on it.
250    pub state: RunState,
251    roles: ResolvedRoles,
252    sem: Arc<Semaphore>,
253    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
254    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
255    /// this is never the same handle as `interrupt`.
256    pause: Pause,
257    /// Set when `magi serve`'s interrupt scheduler wants this specific run
258    /// parked at its next node boundary, to let a task marked
259    /// [`crate::queue::Task::interrupt`] run alone before this one carries
260    /// on. Unlike `pause`, a fresh, unshared handle per run - see
261    /// [`Runner::watch_interrupt`].
262    interrupt: Pause,
263}
264
265/// The commit a run branches from: the base branch as the remote has it.
266///
267/// Two failures this replaces. A run used to branch off `HEAD` and so refused
268/// to start on a dirty tree, which made `magi serve` decline every task for as
269/// long as the operator had work in progress - most of the time. Branching off
270/// the *local* base branch fixed that and introduced a worse one: `land` merges
271/// the winner on GitHub, nothing updates the local ref, and the next run
272/// branches off a base missing everything the previous runs landed. Two tasks
273/// in a row from a phone would have had the second silently re-implementing
274/// against stale code and opening a pull request that reverted the first.
275///
276/// Only refs move here - no checkout, no local branch, no merge - so it is safe
277/// with uncommitted work in the tree. A machine with no network still starts:
278/// the fetch may fail and the local tip is used with a warning, because
279/// refusing to run offline is a worse failure than running against a base the
280/// operator can see for themselves.
281///
282/// One function, called by both entry points. Two answers to "where does a run
283/// branch from" is the kind of drift nobody notices until a diff is wrong.
284async fn resolve_base(repo: &Path, base_branch: &str, remote: &str) -> Result<String> {
285    let tracking = format!("{remote}/{base_branch}");
286    let fetched = git::fetch(repo, remote, base_branch).await;
287    if let Ok(out) = &fetched
288        && out.ok()
289        && git::rev_exists(repo, &tracking).await
290    {
291        return git::rev_parse(repo, &tracking).await;
292    }
293    let why = match &fetched {
294        Ok(out) if !out.ok() => out.stderr.lines().next().unwrap_or("").to_owned(),
295        Ok(_) => format!("{remote} has no {base_branch}"),
296        Err(e) => e.to_string(),
297    };
298    tracing::warn!(
299        "could not read {tracking} ({why}); branching off the local \
300         {base_branch} instead, which may be behind"
301    );
302    git::rev_parse(repo, base_branch).await.with_context(|| {
303        format!(
304            "cannot resolve `{base_branch}`; set [merge] base in magi.toml to a \
305             branch that exists"
306        )
307    })
308}
309
310/// Exclusive claim on one run's `magi fix` step, released on drop — including
311/// on an early return or a panic.
312///
313/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
314/// manual `magi fix` invocations against the same run are otherwise
315/// invisible to each other and would race to remove and recreate the same
316/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
317/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
318/// which is only ever reclaimed later, out of band, by
319/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
320/// `magi fix` invocation is not necessarily running under either of those, so
321/// nothing would ever sweep a lock a killed or crashed process left behind.
322/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
323/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
324/// lease use: an unreadable or unparsable pid, or a liveness query the
325/// platform cannot answer, reads as alive and the lock is left in place.
326struct FixClaim {
327    path: PathBuf,
328}
329
330impl FixClaim {
331    fn acquire(dir: &Path) -> Result<Self> {
332        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
333        let path = dir.join("fix.lock");
334        match Self::create(&path) {
335            Ok(claim) => Ok(claim),
336            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
337                if Self::reclaim_if_dead(&path) {
338                    Self::create(&path).with_context(|| format!("lock {}", path.display()))
339                } else {
340                    bail!(
341                        "another `magi fix` is already running for this run ({} exists)",
342                        path.display()
343                    )
344                }
345            }
346            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
347        }
348    }
349
350    fn create(path: &Path) -> std::io::Result<Self> {
351        let mut f = std::fs::OpenOptions::new()
352            .write(true)
353            .create_new(true)
354            .open(path)?;
355        use std::io::Write as _;
356        // Read back by `reclaim_if_dead` on a later, stuck invocation.
357        writeln!(f, "{}", std::process::id())?;
358        Ok(Self {
359            path: path.to_owned(),
360        })
361    }
362
363    /// True if the lock named a process confirmed dead, in which case it was
364    /// also removed. Never true on an unreadable file, an unparsable pid, or
365    /// a liveness query the platform cannot answer — see this type's own doc.
366    fn reclaim_if_dead(path: &Path) -> bool {
367        let dead = std::fs::read_to_string(path)
368            .ok()
369            .and_then(|body| body.trim().parse::<u32>().ok())
370            .is_some_and(|pid| !crate::proc::pid_alive(pid));
371        dead && std::fs::remove_file(path).is_ok()
372    }
373}
374
375impl Drop for FixClaim {
376    fn drop(&mut self) {
377        let _ = std::fs::remove_file(&self.path);
378    }
379}
380
381impl Runner {
382    /// Start a fresh run against `repo`.
383    pub async fn start(repo: &Path, instruction: String, config: Config) -> Result<Self> {
384        let repo = git::toplevel(repo).await?;
385        let missing = agent::missing_programs(&config.agents);
386        if !missing.is_empty() {
387            bail!(
388                "these agent programs are not on PATH: {}. Fix the roster in \
389                 magi.toml or install them.",
390                missing.join(", ")
391            );
392        }
393        let base_branch = match config.merge.base.clone() {
394            Some(b) => b,
395            None => git::current_branch(&repo)
396                .await?
397                .context("HEAD is detached; set [merge] base in magi.toml")?,
398        };
399        let base_commit = resolve_base(&repo, &base_branch, &config.merge.remote).await?;
400        // Still worth saying out loud. The operator's uncommitted work is not
401        // part of this run, and someone watching a candidate fail to use a
402        // change they just made deserves to know why.
403        if !git::is_clean(&repo).await? {
404            tracing::warn!(
405                "{} has uncommitted changes; they are not part of this run, \
406                 which branches off {base_branch} ({})",
407                repo.display(),
408                &base_commit[..base_commit.len().min(8)]
409            );
410        }
411        let roles = config.resolve_roles()?;
412        let max_parallel = config.graph.max_parallel.max(1);
413        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
414        state.event("start", format!("run {} created", state.id));
415        state.save()?;
416        Ok(Self {
417            state,
418            roles,
419            sem: Arc::new(Semaphore::new(max_parallel)),
420            pause: Pause::new(),
421            interrupt: Pause::new(),
422        })
423    }
424
425    /// Open a review-only run against work that already exists on `branch`.
426    ///
427    /// The expensive half of the graph is the implement wave — measured at
428    /// 111 and 134 internal tool-loop turns on this repository, against a
429    /// handful for a judge or a reviewer. The cheap half is worth running on
430    /// hand-written work too, and there was no way to reach it.
431    ///
432    /// No new state and no schema change are needed: a run with **one** viable
433    /// candidate and a tally already decided degrades `execute` to exactly
434    /// review → gate → merge, because `judge` skips a single-candidate field,
435    /// `deliberate` has fewer than two first choices to reconcile, `vote`
436    /// returns early, `tally` is already present and `fold_losers` has no
437    /// losers. Resuming such a run therefore does the right thing as well.
438    pub async fn review(repo: &Path, branch: &str, config: Config) -> Result<Self> {
439        let repo = git::toplevel(repo).await?;
440        let missing = agent::missing_programs(&config.agents);
441        if !missing.is_empty() {
442            bail!(
443                "these agent programs are not on PATH: {}. Fix the roster in \
444                 magi.toml or install them.",
445                missing.join(", ")
446            );
447        }
448        if !git::branch_exists(&repo, branch).await? {
449            bail!("no branch `{branch}` in {}", repo.display());
450        }
451        let base_branch = match config.merge.base.clone() {
452            Some(b) => b,
453            None => git::current_branch(&repo)
454                .await?
455                .context("HEAD is detached; set [merge] base in magi.toml")?,
456        };
457        if base_branch == branch {
458            bail!("`{branch}` is the base branch; there is nothing to review against");
459        }
460        let base_commit = resolve_base(&repo, &base_branch, &config.merge.remote).await?;
461
462        let roles = config.resolve_roles()?;
463        let max_parallel = config.graph.max_parallel.max(1);
464        // The commit subjects are the closest thing to a task statement that
465        // existing work carries, and the reviewers are told as much.
466        let log = git::log_oneline(&repo, &base_commit, branch)
467            .await
468            .unwrap_or_default();
469        let instruction = format!(
470            "Review the work already on branch `{branch}`. There is no task \
471             statement: what the change claims to do is whatever its commits \
472             say.\n\n{}",
473            if log.trim().is_empty() {
474                "(no commit messages)"
475            } else {
476                log.trim()
477            }
478        );
479        let mut state = RunState::new(
480            repo.clone(),
481            base_branch,
482            base_commit.clone(),
483            instruction,
484            config,
485        );
486
487        // An attached worktree, so the fixer's commits land on the branch under
488        // review rather than on a detached head nobody will look at again.
489        let worktree = state.worktree_root().join("under-review");
490        if let Some(parent) = worktree.parent() {
491            tokio::fs::create_dir_all(parent).await.ok();
492        }
493        let path = worktree.to_string_lossy().to_string();
494        git::git(&repo, &["worktree", "add", &path, branch])
495            .await
496            .with_context(|| {
497                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
498            })?;
499
500        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
501            .await
502            .unwrap_or(0);
503        if commits == 0 {
504            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
505        }
506        let files = git::changed_files(&worktree, &base_commit, "HEAD")
507            .await
508            .map(|f| f.len())
509            .unwrap_or(0);
510        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
511            .await
512            .unwrap_or_default();
513
514        state.candidates.push(Candidate {
515            index: 0,
516            label: 'A',
517            // Not an agent id on purpose: nothing in the roster wrote this, and
518            // the stats tables must not credit anyone with a win for it.
519            agent: "(existing branch)".to_owned(),
520            branch: branch.to_owned(),
521            worktree,
522            summary: String::new(),
523            stat,
524            files,
525            commits,
526            empty: false,
527            failed: None,
528            verified_noop: None,
529            duration_ms: 0,
530            folded: false,
531        });
532        state.tally = Some(Tally {
533            first_choice: BTreeMap::from([('A', 0)]),
534            borda: BTreeMap::new(),
535            winner: 'A',
536            rankings: 0,
537            unanimous_initial: false,
538            deliberated: false,
539            changed_votes: 0,
540            unanimous_final: false,
541            tie_break: None,
542            // No panel sat, so no quorum applies. Zero judges is the correct
543            // number for work that never competed, and must not be reported as
544            // a collapsed panel.
545            judges: 0,
546            present: 0,
547            quorum: 0,
548            met_quorum: true,
549            uncontested: Some("review-only run: nothing competed".to_owned()),
550        });
551        state.status = RunStatus::Reviewing;
552        state.event(
553            "start",
554            format!(
555                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
556                state.id
557            ),
558        );
559        state.save()?;
560        Ok(Self {
561            state,
562            roles,
563            sem: Arc::new(Semaphore::new(max_parallel)),
564            pause: Pause::new(),
565            interrupt: Pause::new(),
566        })
567    }
568
569    /// Reopen an existing run.
570    pub fn resume(id: &str) -> Result<Self> {
571        let state = RunState::load(id)?;
572        let roles = state.config.resolve_roles()?;
573        let max_parallel = state.config.graph.max_parallel.max(1);
574        Ok(Self {
575            state,
576            roles,
577            sem: Arc::new(Semaphore::new(max_parallel)),
578            pause: Pause::new(),
579            interrupt: Pause::new(),
580        })
581    }
582
583    /// Walk the graph to a terminal state, skipping nodes already recorded.
584    pub async fn execute(&mut self) -> Result<()> {
585        // Moving again, so it is no longer parked. Set before the walk rather
586        // than in `resume`, so every way of re-entering the graph clears it
587        // and a card cannot claim a run is waiting to be resumed while the
588        // agents are already working.
589        self.state.parked = false;
590        // Any seat this state still lists as answering belongs to whatever
591        // process last drove this run — this one included, if it crashed
592        // mid-wave. Cleared and flushed immediately, before anything else
593        // runs, so a resume can never show a seat as live when nothing is
594        // asking it anything yet; the node that actually dispatches the next
595        // wave repopulates it.
596        self.state.clear_active();
597        // Recorded in the same spot, and flushed together with the clear
598        // above: this is the pid a reader checks (`RunState::liveness`) when
599        // no daemon claim exists to answer "is a process still driving this
600        // run" — a plain `magi run` / `magi review` typed into a terminal
601        // claims nothing there. Always overwritten, never only-if-absent, so
602        // a resumed run's stale pid from a previous, possibly-dead process
603        // can never survive into this one's own report. Unlike
604        // `clear_active`, this changes on every single `execute()` call, so
605        // the save below is now unconditional rather than only-if-cleared.
606        //
607        // `driver_started_at` is recorded in the same breath, from this same
608        // pid, so `liveness` can tell a live pid that is genuinely still us
609        // apart from one the OS has since handed to an unrelated process —
610        // see that field's own doc for why the pid alone is not enough.
611        let pid = std::process::id();
612        self.state.driver_pid = Some(pid);
613        self.state.driver_started_at = crate::proc::process_started_at(pid);
614        self.state.save()?;
615        // A run that already lost its quorum never resumes into the verdict
616        // machinery: `deliberate` and `vote` would otherwise clobber the
617        // stalled marker back to Voting and the run would keep going past a
618        // verdict that is no longer trustworthy. Everything already recorded is
619        // kept, so the run stays resumable (or foldable) for a human to pick up.
620        //
621        // On --resume the run gets one chance to repair itself: the seats a
622        // rate limit took out are re-asked. If their quota has since reset and
623        // the quorum is restored, the run picks up and finishes; otherwise it
624        // stays stale and still-resumable for a later retry. If it does not
625        // recover, the returned status stays `Stalled` and nothing was
626        // clobbered (the recovery only mutates entries for the lost seats).
627        if self.state.status == RunStatus::Stalled {
628            if self.recover_stall().await? {
629                self.finish_after_tally().await?;
630            } else {
631                // Still below quorum: persist the marker and stay resumable.
632                self.state.save()?;
633            }
634            return Ok(());
635        }
636        // A run parked inside `land` - watching CI, mid fix-round, or
637        // waiting on the owner's merge approval - resumes directly into it,
638        // never back through `prep`. Everything before `merge` already
639        // concluded; that is the only way `status` reaches `Landing` in the
640        // first place. Re-walking `review_loop` first would also be actively
641        // wrong: its own status recomputation (see its doc) treats any
642        // clean round as reason to set `status` to `Gating`, which would
643        // clobber this marker before `merge` ever ran, and this run would
644        // never find its way back into `land` at all.
645        if self.state.status == RunStatus::Landing {
646            self.run_land().await?;
647            // `run_land` may have settled the run right here - CI came back
648            // green and the PR merged, say - without ever passing back
649            // through `merge`'s own trailing call. Whatever it left `status`
650            // as is what this has to read.
651            self.settle_questions();
652            return Ok(());
653        }
654        self.prep().await?;
655        if self.park_here()? {
656            return Ok(());
657        }
658        self.advise().await?;
659        if self.park_here()? {
660            return Ok(());
661        }
662        self.implement().await?;
663        if self.park_here()? {
664            return Ok(());
665        }
666        // `after_implement` already saved the state and settled any open
667        // questions when it set this; nothing later in the graph has
668        // anything to judge.
669        if self.state.status == RunStatus::VerifiedNoop {
670            return Ok(());
671        }
672        self.judge().await?;
673        if self.park_here()? {
674            return Ok(());
675        }
676        self.deliberate().await?;
677        if self.park_here()? {
678            return Ok(());
679        }
680        self.vote().await?;
681        if self.park_here()? {
682            return Ok(());
683        }
684        self.tally()?;
685        // A verdict that lost its quorum is not trustworthy: do not review,
686        // gate, or merge on it. Everything already done is kept, so the run
687        // stays resumable (or foldable); the human can replace the agent that
688        // ran out of quota and pick it up.
689        if self.state.status == RunStatus::Stalled {
690            // Persist the stalled marker now — the normal end-of-execute save
691            // below is below this early return, and without it a resumed run
692            // would reload a pre-tally status and keep going.
693            self.state.save()?;
694            return Ok(());
695        }
696        self.finish_after_tally().await?;
697        Ok(())
698    }
699
700    /// Park here if asked to, recording it in the run's own timeline.
701    ///
702    /// Returns whether the caller should stop walking the graph. The state is
703    /// saved either way by the node that just finished; this adds the event so
704    /// the operator's card says why a run that is neither finished nor moving
705    /// is sitting where it is.
706    fn park_here(&mut self) -> Result<bool> {
707        // Either handle asking is enough - see `Pause`'s own doc for why
708        // they are never the same one. `interrupt` is checked second so a
709        // reason it carries is preferred in the message below over a plain
710        // shutdown park racing it at the same boundary.
711        if !self.pause.parked() && !self.interrupt.parked() {
712            return Ok(false);
713        }
714        let why = match self.interrupt.reason().or_else(|| self.pause.reason()) {
715            Some(reason) => format!(
716                "parked after `{}` ({reason}) — resume to carry on from here",
717                self.state.status.as_str()
718            ),
719            None => format!(
720                "parked after `{}` — resume to carry on from here",
721                self.state.status.as_str()
722            ),
723        };
724        self.state.event("park", why);
725        self.state.parked = true;
726        self.state.save()?;
727        Ok(true)
728    }
729
730    /// Hand the runner the pause `magi serve`'s own shutdown watches.
731    pub fn on_pause(&mut self, pause: Pause) {
732        self.pause = pause;
733    }
734
735    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
736    /// scheduler asking this one run - and no other - to park so a task
737    /// marked [`crate::queue::Task::interrupt`] can run alone. See
738    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
739    /// handle.
740    pub fn watch_interrupt(&mut self, pause: Pause) {
741        self.interrupt = pause;
742    }
743
744    /// Abandon this run's own open questions, once `status` has actually
745    /// settled rather than merely paused.
746    ///
747    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
748    /// either back up with the candidates, the review round and the seat
749    /// sessions already on disk, so a question an implementer asked mid-round
750    /// may still get a real answer read by a real resume. Only the statuses
751    /// `resumable` excludes are actually final: the run merged, it reached
752    /// `Ready` with nothing left to do, it failed outright with no
753    /// established point to continue from, or every candidate agreed, with
754    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
755    /// every one of those the seat that asked is gone for good, exactly like
756    /// the run being deleted under `magi run rm` - so the same cleanup
757    /// applies, worded for what actually happened instead of "the run was
758    /// deleted".
759    ///
760    /// Best-effort and silent on success: called from every place `status`
761    /// can land on one of those three, including ones a resumed run revisits,
762    /// so it must cost nothing when there was nothing open to begin with.
763    fn settle_questions(&mut self) {
764        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
765            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
766        }
767    }
768
769    /// The tail of the graph after a trustworthy tally: fold losers, review,
770    /// gate, merge, and persist.
771    async fn finish_after_tally(&mut self) -> Result<()> {
772        self.fold_losers().await?;
773        // Before review starts, and again right before the gate: a run's
774        // review rounds can themselves take long enough for the base to move
775        // a second time, and the gate is the one node whose "green" gets
776        // acted on.
777        self.sync_to_base().await?;
778        self.review_loop().await?;
779        self.sync_to_base().await?;
780        self.gate().await?;
781        self.merge().await?;
782        self.state.save()?;
783        Ok(())
784    }
785
786    // ---------------------------------------------------------------- prep
787
788    async fn prep(&mut self) -> Result<()> {
789        if !self.state.candidates.is_empty() {
790            return Ok(());
791        }
792        self.state.status = RunStatus::Prep;
793        let repo = self.state.repo.clone();
794        let base = self.state.base_commit.clone();
795        let root = self.state.worktree_root();
796        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
797
798        // The hook is the write-time half of the blindness contract; the
799        // presentation filter in `blind` is the half that cannot be bypassed.
800        let hooks_dir = self.state.dir().join("hooks");
801        if self.state.config.blind.commit_msg_hook {
802            std::fs::create_dir_all(&hooks_dir)
803                .with_context(|| format!("create {}", hooks_dir.display()))?;
804            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
805            let path = hooks_dir.join("commit-msg");
806            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
807            make_executable(&path)?;
808            // Ref-counted rather than a plain idempotent set: with more than
809            // one run able to be in flight in the same repository at once
810            // (see `Config::daemon.max_concurrent_runs`), a bare "already
811            // true?" check cannot tell "another run of mine still needs
812            // this" from "nobody does", and the run that happens to finish
813            // first would disable the hook out from under a sibling still
814            // relying on it.
815            git::acquire_worktree_config(&repo).await?;
816            self.state.enabled_worktree_config = true;
817        }
818
819        for (index, (spec, label)) in self
820            .roles
821            .implementers
822            .clone()
823            .into_iter()
824            .zip(labels)
825            .enumerate()
826        {
827            let branch = self.state.branch_for(label);
828            let worktree = root.join(format!("cand-{label}"));
829            git::worktree_add_branch(&repo, &worktree, &branch, &base).await?;
830            if self.state.config.blind.commit_msg_hook {
831                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
832            }
833            git::local_exclude(&worktree, "/.magi/").await?;
834            self.state.candidates.push(Candidate {
835                index,
836                label,
837                agent: spec.id.clone(),
838                branch,
839                worktree,
840                summary: String::new(),
841                stat: String::new(),
842                files: 0,
843                commits: 0,
844                empty: false,
845                failed: None,
846                verified_noop: None,
847                duration_ms: 0,
848                folded: false,
849            });
850        }
851
852        for j in 1..=self.roles.judges.len() {
853            let wt = root.join(format!("judge-{j}"));
854            if !wt.exists() {
855                git::worktree_add_detached(&repo, &wt, &base).await?;
856            }
857        }
858
859        // Disposable, detached checkouts for the design-deliberation stage's
860        // advisor seats — the same shape as the judges' above, at the same
861        // base commit, since advisors also only ever read. Sized off the
862        // configured count directly rather than a resolved roster: unlike
863        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
864        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
865        // `prep` has no `ResolvedRoles` field to read a count from here.
866        if self.state.config.graph.advise {
867            for k in 1..=self.state.config.graph.advisors {
868                let wt = root.join(format!("advisor-{k}"));
869                if !wt.exists() {
870                    git::worktree_add_detached(&repo, &wt, &base).await?;
871                }
872            }
873        }
874
875        // A judge cannot tell it is looking at its own patch — the seats keep
876        // separate conversations — but a panel that shares agents with the
877        // field is less independent than it looks, and that is worth saying out
878        // loud once per run rather than leaving it in the config.
879        let authors: Vec<&str> = self
880            .roles
881            .implementers
882            .iter()
883            .map(|a| a.id.as_str())
884            .collect();
885        let overlap: Vec<String> = self
886            .roles
887            .judges
888            .iter()
889            .enumerate()
890            .filter(|(_, j)| authors.contains(&j.id.as_str()))
891            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
892            .collect();
893        if !overlap.is_empty() {
894            let note = format!(
895                "{} also authored a candidate; blind, but the panel is less \
896                 independent than {} distinct agents would be",
897                overlap.join(", "),
898                self.roles.judges.len()
899            );
900            self.state.event("prep", note);
901        }
902
903        self.state.event(
904            "prep",
905            format!(
906                "{} candidates, {} judges, base {} ({})",
907                self.state.candidates.len(),
908                self.roles.judges.len(),
909                &self.state.base_commit[..7.min(self.state.base_commit.len())],
910                self.state.base_branch
911            ),
912        );
913        self.state.status = RunStatus::Implementing;
914        self.state.save()?;
915        Ok(())
916    }
917
918    // -------------------------------------------------------------- advise
919
920    /// The design-deliberation stage: independent, read-only advisor seats
921    /// each sketch a design before any implementer touches the repository,
922    /// and (when at least one produced a usable proposal) a synthesis seat
923    /// blends them into a brief `implement` carries in every candidate's
924    /// prompt.
925    ///
926    /// `[graph] advise` is the on/off switch, on by default; `[graph]
927    /// advisors` is the proposal count. Everything here is best-effort and
928    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
929    /// that cannot reach quota, or a synthesis seat that produced nothing
930    /// usable all leave `implement` exactly as it was before this stage
931    /// existed — the task instruction alone — rather than failing the whole
932    /// competition over an enrichment stage. Every outcome is still recorded
933    /// as an event, so a run that got nothing from this stage says why.
934    ///
935    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
936    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
937    /// resumed run whose stage failed would re-run it, and re-spend the
938    /// agent calls, on every reentry before `implement`.
939    ///
940    /// Also skipped once any candidate shows implementation progress — the
941    /// exact predicate `implement` itself uses to decide a candidate is no
942    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
943    /// is not enough: a run created by an older binary that predates this
944    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
945    /// an already-`Implementing`-or-later run under this build would
946    /// otherwise walk straight back through `prep` (a no-op once candidates
947    /// exist) into this node and spawn every advisor seat against worktrees
948    /// `prep` never recreated — after implementation has already started,
949    /// which is exactly the invariant this stage exists to guarantee.
950    async fn advise(&mut self) -> Result<()> {
951        let implement_untouched = self
952            .state
953            .candidates
954            .iter()
955            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
956        if !self.state.config.graph.advise || self.state.advise_attempted {
957            return Ok(());
958        }
959        if !implement_untouched {
960            self.state.event(
961                "advise",
962                "skipping the design-deliberation stage: at least one \
963                 candidate already shows implementation progress, so this \
964                 run is past the point the stage exists to run before"
965                    .to_owned(),
966            );
967            self.state.advise_attempted = true;
968            self.state.save()?;
969            return Ok(());
970        }
971        let run_id = self.state.id.clone();
972        let prompts = self.state.config.prompts.clone();
973        let instruction = self.state.instruction.clone();
974        let language = self.state.config.graph.language.clone();
975        let root = self.state.worktree_root();
976        let n = self.state.config.graph.advisors;
977        let where_recorded = self.state.dir().join("run.json");
978
979        let seats = match self.state.config.advisors() {
980            Ok(seats) if !seats.is_empty() => seats,
981            Ok(_) => {
982                self.state.event(
983                    "advise",
984                    format!(
985                        "[graph] advisors is 0; skipping the design-deliberation \
986                         stage and continuing without a synthesis brief (see {})",
987                        where_recorded.display()
988                    ),
989                );
990                self.state.advise_attempted = true;
991                self.state.save()?;
992                return Ok(());
993            }
994            Err(e) => {
995                self.state.event(
996                    "advise",
997                    format!(
998                        "could not resolve advisor seats ({e:#}); continuing \
999                         without a design-deliberation brief (see {})",
1000                        where_recorded.display()
1001                    ),
1002                );
1003                self.state.advise_attempted = true;
1004                self.state.save()?;
1005                return Ok(());
1006            }
1007        };
1008
1009        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
1010        let artifacts = agent::artifacts_dir(&self.state.dir());
1011        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
1012
1013        let mut jobs = Vec::new();
1014        for (i, spec) in seats.iter().cloned().enumerate() {
1015            let seat_key = format!("advisor-{}", i + 1);
1016            let seat = self.seat(&seat_key, &spec.id);
1017            jobs.push(SeatJob {
1018                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
1019                spec,
1020                seat,
1021                cwd: worktrees[i % worktrees.len()].clone(),
1022                timeout,
1023                allow_write: false,
1024                sessions: false,
1025                artifacts: artifacts.clone(),
1026                stem: seat_key,
1027            });
1028        }
1029
1030        self.state.event(
1031            "advise",
1032            format!(
1033                "{} advisor seat(s) sketching a design in parallel",
1034                jobs.len()
1035            ),
1036        );
1037        let mut quota_losses = Vec::new();
1038        let cache = self.state.config.cache_dir();
1039        let ctx = WaveCtx {
1040            run: &run_id,
1041            node: "advise",
1042            prompts: &prompts,
1043            cache: cache.as_deref(),
1044            round: None,
1045        };
1046        let results = ask_json_wave::<Proposal>(
1047            jobs,
1048            Arc::clone(&self.sem),
1049            self.state.config.graph.retries,
1050            &ctx,
1051            &mut quota_losses,
1052            &mut self.state,
1053            &|p: &Proposal| p.validate(),
1054        )
1055        .await;
1056        self.state.quota.extend(quota_losses);
1057
1058        let mut records = Vec::with_capacity(results.len());
1059        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
1060            let agent_id = seat.agent.clone();
1061            self.state.seats.insert(seat.key.clone(), seat);
1062            match res {
1063                Ok((proposal, out)) => {
1064                    self.state
1065                        .event("advise", format!("advisor-{} proposed a design", i + 1));
1066                    records.push(advise::AdvisorRecord::proposed(
1067                        i + 1,
1068                        agent_id,
1069                        proposal,
1070                        out.duration_ms,
1071                    ));
1072                }
1073                Err(e) => {
1074                    self.state.event(
1075                        "advise",
1076                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
1077                    );
1078                    records.push(advise::AdvisorRecord::failed(
1079                        i + 1,
1080                        agent_id,
1081                        e.to_string(),
1082                    ));
1083                }
1084            }
1085        }
1086
1087        let mut advice = advise::Advice {
1088            records,
1089            synthesis: None,
1090        };
1091        if advice.proposals().is_empty() {
1092            self.state.event(
1093                "advise",
1094                "no advisor produced a usable proposal; continuing without a \
1095                 synthesis brief"
1096                    .to_owned(),
1097            );
1098        } else {
1099            match self
1100                .synthesize_brief(
1101                    &advice,
1102                    &instruction,
1103                    &language,
1104                    &worktrees[0],
1105                    &artifacts,
1106                    &run_id,
1107                    &prompts,
1108                    cache.as_deref(),
1109                )
1110                .await
1111            {
1112                Ok(Some(text)) => {
1113                    self.state.event(
1114                        "advise",
1115                        "synthesized a design brief for the implementer".to_owned(),
1116                    );
1117                    advice.synthesis = Some(text);
1118                }
1119                Ok(None) => {
1120                    self.state.event(
1121                        "advise",
1122                        "the synthesis seat produced nothing usable; continuing \
1123                         without a design brief"
1124                            .to_owned(),
1125                    );
1126                }
1127                Err(e) => {
1128                    self.state.event(
1129                        "advise",
1130                        format!("could not synthesize a design brief: {e:#}"),
1131                    );
1132                }
1133            }
1134        }
1135        advise::apply_reflection(&mut advice);
1136
1137        self.state.advice = Some(advice);
1138        self.state.advise_attempted = true;
1139        self.state.save()?;
1140        Ok(())
1141    }
1142
1143    /// The synthesis seat: reads every advisor's proposal and blends them
1144    /// into the design brief `advise` stores on [`RunState::advice`]. Split
1145    /// out of [`Runner::advise`] only for readability — it is not called
1146    /// anywhere else.
1147    ///
1148    /// Picked the same way [`crate::talk`]'s standing conversation and
1149    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
1150    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
1151    /// order (a claude seat, else the first runnable agent in roster order)
1152    /// used when that field is unset — see `[roles] synthesizer`'s own doc
1153    /// in [`crate::config`] for why a dedicated field exists here at all.
1154    #[allow(clippy::too_many_arguments)]
1155    async fn synthesize_brief(
1156        &mut self,
1157        advice: &advise::Advice,
1158        instruction: &str,
1159        language: &str,
1160        cwd: &Path,
1161        artifacts: &Path,
1162        run_id: &str,
1163        prompts: &Prompts,
1164        cache: Option<&Path>,
1165    ) -> Result<Option<String>> {
1166        let want = self.state.config.roles.synthesizer.as_deref();
1167        let spec = agent::pick(&self.state.config.agents, want, &agent::installed)?;
1168        let mut seat = self.seat("advise-synthesis", &spec.id);
1169        let proposals = advice.proposals();
1170        let mut prompt = prompt::with_overlay(
1171            prompt::synthesize_brief(instruction, &proposals, language),
1172            prompts.overlay("advise"),
1173        );
1174        if cache.is_some() {
1175            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
1176            // below — see `prompt::build_cache_note`'s doc for why telling a
1177            // read-only seat to build through the shared cache is exactly how
1178            // a sandbox's write refusal gets misread as a defect.
1179            prompt.push('\n');
1180            prompt.push_str(&prompt::build_cache_note("advise", false));
1181        }
1182        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
1183        let out = agent::invoke(
1184            &spec,
1185            &mut seat,
1186            &Invocation {
1187                cwd,
1188                prompt: &prompt,
1189                timeout,
1190                allow_write: false,
1191                sessions: false,
1192                artifacts,
1193                stem: "advise-synthesis",
1194                run: run_id,
1195                node: "advise",
1196                cache_dir: None,
1197                attachments: &[],
1198            },
1199        )
1200        .await?;
1201        self.state.seats.insert(seat.key.clone(), seat);
1202        if !out.usable() {
1203            return Ok(None);
1204        }
1205        let text =
1206            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
1207        Ok((!text.trim().is_empty()).then_some(text))
1208    }
1209
1210    // ----------------------------------------------------------- implement
1211
1212    async fn implement(&mut self) -> Result<()> {
1213        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
1214        // agent files with `magi task add` name the run that paid for it. The
1215        // prompt overlay is cloned alongside it because the waves borrow it
1216        // while `self` is mutably borrowed by the node's own bookkeeping.
1217        let run_id = self.state.id.clone();
1218        let prompts = self.state.config.prompts.clone();
1219        let todo: Vec<usize> = self
1220            .state
1221            .candidates
1222            .iter()
1223            .enumerate()
1224            .filter(|(_, c)| c.commits == 0 && c.failed.is_none() && !c.empty)
1225            .map(|(i, _)| i)
1226            .collect();
1227        if todo.is_empty() {
1228            return self.after_implement();
1229        }
1230        self.state.status = RunStatus::Implementing;
1231
1232        let language = self.state.config.graph.language.clone();
1233        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
1234        let sessions = self.state.config.graph.sessions;
1235        let artifacts = agent::artifacts_dir(&self.state.dir());
1236        // The design-deliberation stage's blended brief, when `advise` found
1237        // one — carried into every implementer's prompt the same way
1238        // regardless of which candidate it is.
1239        let brief = self
1240            .state
1241            .advice
1242            .as_ref()
1243            .and_then(|a| a.synthesis.as_deref())
1244            .map(str::to_owned);
1245
1246        let mut jobs = Vec::new();
1247        for &i in &todo {
1248            let (index, label, worktree) = {
1249                let c = &self.state.candidates[i];
1250                (c.index, c.label, c.worktree.clone())
1251            };
1252            let spec = self.roles.implementers[index].clone();
1253            let seat_key = format!("impl-{label}");
1254            let seat = self.seat(&seat_key, &spec.id);
1255            let instruction = self.state.instruction.clone();
1256            jobs.push(SeatJob {
1257                spec,
1258                seat,
1259                prompt: prompt::implement(
1260                    &instruction,
1261                    &worktree.to_string_lossy(),
1262                    &language,
1263                    brief.as_deref(),
1264                ),
1265                cwd: worktree,
1266                timeout,
1267                allow_write: true,
1268                sessions,
1269                artifacts: artifacts.clone(),
1270                stem: format!("impl-{label}"),
1271            });
1272        }
1273
1274        self.state.event(
1275            "implement",
1276            format!("{} candidates in parallel", jobs.len()),
1277        );
1278        // Kept so a seat whose CLI hung up can be asked again from the same
1279        // job: `wave` consumes what it is given. Mutable so `resume_quota_losses`
1280        // can update a seat's own entry once a fallback agent takes it over —
1281        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
1282        // whichever agent actually answered, not the one that quota'd out.
1283        let mut sent = jobs.clone();
1284        let cache = self.state.config.cache_dir();
1285        let ctx = WaveCtx {
1286            run: &run_id,
1287            node: "implement",
1288            prompts: &prompts,
1289            cache: cache.as_deref(),
1290            round: None,
1291        };
1292        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
1293        self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
1294            .await;
1295        self.resume_quota_losses(&mut results, &mut sent, &prompts, &run_id)
1296            .await;
1297        self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
1298            .await;
1299
1300        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
1301            let seat_key = seat.key.clone();
1302            // A quota fallback (`resume_quota_losses`) may have handed this
1303            // seat to a different agent than the one `prep` recorded on the
1304            // candidate; the stats tables and any later fixer-defaults-to-
1305            // winner's-author lookup must credit whoever actually answered —
1306            // unless every fallback also quota'd out, in which case nobody
1307            // actually answered and crediting the last agent tried would
1308            // erase every earlier agent's own quota loss from the stats
1309            // tables instead of just this one seat's.
1310            let agent = seat.agent.clone();
1311            let exhausted_the_fallback_chain = matches!(&out, AgentOutcome::Quota(_));
1312            self.state.seats.insert(seat.key.clone(), seat);
1313            let label = self.state.candidates[i].label;
1314            let worktree = self.state.candidates[i].worktree.clone();
1315            let base = self.state.base_commit.clone();
1316
1317            let (summary, duration, failed, verified_claim) = match out {
1318                AgentOutcome::Ok(o) => {
1319                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
1320                    let failed = (!o.usable()).then(|| {
1321                        if o.timed_out {
1322                            "agent timed out".to_owned()
1323                        } else {
1324                            format!("agent exited with {:?}", o.exit_code)
1325                        }
1326                    });
1327                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
1328                    (text, o.duration_ms, failed, verified_claim)
1329                }
1330                // Left un-resumed by `resume_undelivered` (a dirty tree
1331                // already rescues the work, or there was no session left to
1332                // resume into) — reported like the ordinary failure it is,
1333                // never as if `o.text` (the CLI's raw error JSON) were an
1334                // answer.
1335                AgentOutcome::Dropped(o) => {
1336                    let why = o
1337                        .dropped
1338                        .as_ref()
1339                        .map(|d| d.why.as_str())
1340                        .unwrap_or("the CLI ended the stream without delivering its answer");
1341                    (
1342                        String::new(),
1343                        o.duration_ms,
1344                        Some(format!("the CLI dropped the stream ({why})")),
1345                        None,
1346                    )
1347                }
1348                AgentOutcome::Quota(o) => {
1349                    self.state.quota.push(QuotaLoss {
1350                        seat: seat_key,
1351                        node: "implement".to_owned(),
1352                        at: Timestamp::now(),
1353                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
1354                    });
1355                    (
1356                        String::new(),
1357                        o.duration_ms,
1358                        Some("rate limited (quota); produced no change".to_owned()),
1359                        None,
1360                    )
1361                }
1362                AgentOutcome::Failed(e) => (String::new(), 0, Some(e), None),
1363            };
1364
1365            // Rescue anything the agent edited but never committed: an
1366            // uncommitted candidate would silently be an empty one.
1367            let rescued = git::commit_all(
1368                &worktree,
1369                &format!("magi: candidate {label} (uncommitted work)"),
1370            )
1371            .await
1372            .unwrap_or(false);
1373            let commits = git::commits_ahead(&worktree, &base, "HEAD")
1374                .await
1375                .unwrap_or(0);
1376            let patch = git::diff(&worktree, &base, "HEAD")
1377                .await
1378                .unwrap_or_default();
1379            let stat = git::diff_stat(&worktree, &base, "HEAD")
1380                .await
1381                .unwrap_or_default();
1382            let files = git::changed_files(&worktree, &base, "HEAD")
1383                .await
1384                .map(|f| f.len())
1385                .unwrap_or(0);
1386            write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
1387
1388            let c = &mut self.state.candidates[i];
1389            if !exhausted_the_fallback_chain {
1390                c.agent = agent;
1391            }
1392            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
1393            c.stat = stat;
1394            c.files = files;
1395            c.commits = commits;
1396            c.duration_ms = duration;
1397            c.empty = commits == 0 || patch.trim().is_empty();
1398            // An agent that failed but still produced a committed change stays
1399            // in the running: the patch is what gets judged, not the exit code.
1400            c.failed = match failed {
1401                Some(_) if c.empty => failed,
1402                _ => None,
1403            };
1404            // Only an empty candidate can be a verified no-op: a claim next
1405            // to a real patch is not what the marker is for, and `c.failed`
1406            // being `Some` here already implies `verified_claim` was never
1407            // set (see the guard above the match that produced it).
1408            c.verified_noop = if c.empty { verified_claim } else { None };
1409            let note = match (&c.failed, c.empty, &c.verified_noop, rescued) {
1410                (Some(e), _, _, _) => format!("candidate {label}: {e}"),
1411                (None, true, Some(_), _) => {
1412                    format!("candidate {label}: no change produced (agent-verified no-op)")
1413                }
1414                (None, true, None, _) => format!("candidate {label}: no change produced"),
1415                (None, false, _, true) => {
1416                    format!(
1417                        "candidate {label}: {files} files, {commits} commits (rescued an uncommitted tree)"
1418                    )
1419                }
1420                (None, false, _, false) => {
1421                    format!("candidate {label}: {files} files, {commits} commits")
1422                }
1423            };
1424            self.state.event("implement", note);
1425            self.state.save()?;
1426        }
1427
1428        self.after_implement()
1429    }
1430
1431    /// Ask again, once, for work a CLI did and then failed to hand over.
1432    ///
1433    /// [`agent::dropped_stream`] recognises the one shape observed: an error
1434    /// status with an empty response and a usage report showing output tokens,
1435    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
1436    /// seven minutes and 14,267 output tokens that arrived as an empty
1437    /// candidate, because `agy`'s own subscriber fell behind and hung up.
1438    ///
1439    /// Two conditions, and both matter:
1440    ///
1441    /// - **Only when the tree is untouched.** Often the agent has already
1442    ///   written its files and only the closing message was lost; the rescue
1443    ///   commit below picks that up and there is nothing to ask for. Re-asking
1444    ///   then would pay for a second implementation of work already on disk.
1445    /// - **Once.** A CLI that drops one stream can drop the next, and this
1446    ///   node is the most expensive in the graph.
1447    ///
1448    /// The re-ask is a resume, not a re-run: `has_context` is true because the
1449    /// dropped reply still carried its `conversation_id`, so the seat is asked
1450    /// to finish what it was doing rather than sent the whole task again. It
1451    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
1452    /// node's - for the same reason a re-ranked judge does: restating finished
1453    /// work is not the work.
1454    ///
1455    /// Unlike a quota this is worth retrying at all: a rate limit fails the
1456    /// same way until it resets, while an abandoned conversation is still
1457    /// there to be picked up.
1458    async fn resume_undelivered(
1459        &mut self,
1460        results: &mut [(usize, SeatState, AgentOutcome)],
1461        sent: &[SeatJob],
1462        prompts: &Prompts,
1463        run_id: &str,
1464    ) {
1465        for (wi, seat, out) in results.iter_mut() {
1466            let Some(dropped) = (match &*out {
1467                AgentOutcome::Dropped(o) => o.dropped.clone(),
1468                _ => None,
1469            }) else {
1470                continue;
1471            };
1472            let Some(job) = sent.get(*wi) else { continue };
1473            // Already on disk? Then only the closing message was lost.
1474            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
1475                self.state.event(
1476                    "implement",
1477                    format!(
1478                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
1479                         work is in the tree",
1480                        seat.key, dropped.output_tokens, dropped.why
1481                    ),
1482                );
1483                continue;
1484            }
1485            // The re-ask only makes sense as a resume: `resume_after_drop`
1486            // says nothing about the task, trusting the seat to still hold it.
1487            // Without a session to resume — sessions disabled, or this CLI's
1488            // drop shape happened not to carry a session id — that prompt
1489            // would open a brand-new conversation with no context at all,
1490            // which is worse than leaving this as the ordinary failure it
1491            // already is.
1492            if !has_context(&job.spec, seat, job.sessions) {
1493                self.state.event(
1494                    "implement",
1495                    format!(
1496                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
1497                         is no session left to resume",
1498                        seat.key, dropped.output_tokens, dropped.why
1499                    ),
1500                );
1501                continue;
1502            }
1503            self.state.event(
1504                "implement",
1505                format!(
1506                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
1507                     conversation",
1508                    seat.key, dropped.output_tokens, dropped.why
1509                ),
1510            );
1511            let mut retry = job.clone();
1512            retry.seat = seat.clone();
1513            retry.prompt = prompt::resume_after_drop(&dropped.why);
1514            retry.timeout = retry_budget(job.timeout, true);
1515            retry.stem = format!("{}-resume", job.stem);
1516            let cache = self.state.config.cache_dir();
1517            let ctx = WaveCtx {
1518                run: run_id,
1519                node: "implement",
1520                prompts,
1521                cache: cache.as_deref(),
1522                round: None,
1523            };
1524            let (resumed_seat, resumed) =
1525                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
1526            *seat = resumed_seat;
1527            *out = resumed;
1528        }
1529    }
1530
1531    /// Fall an implement seat through to the next untried agent in the
1532    /// implementer roster when it lost to quota, instead of leaving the
1533    /// seat's loss final the moment one agent's account runs dry.
1534    ///
1535    /// Solo runs (`graph.candidates = 1`, `daemon::apply_solo`'s forced shape)
1536    /// are the motivating case: `Config::resolve_roles`'s `implementers`
1537    /// truncates to the single slot rotation picked, so a solo task whose one
1538    /// implementer hits quota mid-run used to have nothing else to try. This
1539    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
1540    /// unrotated roster — which is the only place the *other* candidates in
1541    /// the machine's roster still exist once `implementers` has been cut down
1542    /// to size.
1543    ///
1544    /// Walks forward from just past the seat's own original position in the
1545    /// roster, never wrapping back to the front: a later candidate slot (say
1546    /// `beta`, the roster's second entry) must fall through to the *next*
1547    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
1548    /// almost certainly a different candidate's own agent already — and once
1549    /// the roster's tail is exhausted there is nothing left to fall through
1550    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
1551    /// whole [`AgentSpec`]: a roster with the same id named twice must not
1552    /// let this retry that id forever. The loop keeps falling through until
1553    /// an attempt lands something other than `Quota` or the roster's tail
1554    /// runs out of untried ids, at which point the seat is left exactly as
1555    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
1556    /// `QuotaLoss` recorded, the candidate failed/empty.
1557    ///
1558    /// `sent` is taken mutably and updated with the fallback agent's spec:
1559    /// `resume_unconfirmed_commands`, which runs after this and also reads
1560    /// `sent`, must see whichever agent actually ended up answering the seat
1561    /// — reading the stale, original spec there would check session
1562    /// eligibility against the wrong CLI and could hand a fallback agent's
1563    /// session id to the agent that just lost the seat to quota.
1564    ///
1565    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
1566    /// — `self.seat` only reuses state when the agent id is unchanged, so
1567    /// handing it a different id already gets this for free. Reusing the old
1568    /// seat would resume a different CLI's session as if it were a
1569    /// continuation of this one.
1570    ///
1571    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
1572    /// a quota loss cuts an agent off mid-turn, so anything already in the
1573    /// tree is unfinished work, not a completed candidate a re-ask would pay
1574    /// for twice. A dirty tree is rescued into a commit first (the same
1575    /// neutral-identity rescue `implement`'s own outcome loop gives every
1576    /// candidate) so the next agent starts clean.
1577    ///
1578    /// The new agent gets the implementer's full prompt and full
1579    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
1580    /// it has no session and no context, and is implementing the task from
1581    /// nothing, unlike a resumed drop which is only restating work already
1582    /// done.
1583    ///
1584    /// Every intermediate `Quota` this loop absorbs is folded into a plain
1585    /// `implement` event, never into `self.state.quota` — that is what
1586    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
1587    /// go unspent, and a seat that ultimately recovered on its second or
1588    /// third agent is not the stalled panel that check exists to catch. Only
1589    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
1590    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
1591    /// outcome loop already has — this helper never pushes to it itself.
1592    async fn resume_quota_losses(
1593        &mut self,
1594        results: &mut [(usize, SeatState, AgentOutcome)],
1595        sent: &mut [SeatJob],
1596        prompts: &Prompts,
1597        run_id: &str,
1598    ) {
1599        let instruction = self.state.instruction.clone();
1600        let language = self.state.config.graph.language.clone();
1601        let brief = self
1602            .state
1603            .advice
1604            .as_ref()
1605            .and_then(|a| a.synthesis.as_deref())
1606            .map(str::to_owned);
1607        for (wi, seat, out) in results.iter_mut() {
1608            let Some(job) = sent.get_mut(*wi) else {
1609                continue;
1610            };
1611            // Where the seat's own original agent sits in the roster — the
1612            // fallback walk starts just past here, never at the front, so a
1613            // later candidate slot's quota loss does not fall back onto an
1614            // earlier slot's own agent.
1615            let start = self
1616                .roles
1617                .implementer_roster
1618                .iter()
1619                .position(|s| s.id == job.spec.id)
1620                .unwrap_or(0);
1621            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
1622            let mut fallback_attempt = 0usize;
1623            while matches!(&*out, AgentOutcome::Quota(_)) {
1624                let Some(next) =
1625                    next_untried_implementer(&self.roles.implementer_roster, start, &tried)
1626                        .cloned()
1627                else {
1628                    break;
1629                };
1630                tried.insert(next.id.clone());
1631                fallback_attempt += 1;
1632
1633                git::commit_all(
1634                    &job.cwd,
1635                    &format!(
1636                        "magi: candidate {} (uncommitted work before quota fallback)",
1637                        seat.key
1638                    ),
1639                )
1640                .await
1641                .ok();
1642
1643                self.state.event(
1644                    "implement",
1645                    format!(
1646                        "{}: rate limited (quota) on {}; retrying with {}",
1647                        seat.key, seat.agent, next.id
1648                    ),
1649                );
1650
1651                let new_seat = self.seat(&seat.key, &next.id);
1652                // Kept in sync on `sent` itself, not just the local retry: a
1653                // later helper (`resume_unconfirmed_commands`) reads `sent`
1654                // after this one returns and must see whichever agent is now
1655                // occupying the seat, not the one that just quota'd out —
1656                // otherwise it would judge session/continuation eligibility
1657                // by the wrong CLI and could resend a fallback's session id
1658                // to the agent that lost it the seat in the first place.
1659                job.spec = next.clone();
1660                let mut retry = job.clone();
1661                retry.seat = new_seat;
1662                retry.prompt = prompt::implement(
1663                    &instruction,
1664                    &job.cwd.to_string_lossy(),
1665                    &language,
1666                    brief.as_deref(),
1667                );
1668                retry.stem = format!("{}-quota-{}", job.stem, next.id);
1669                let cache = self.state.config.cache_dir();
1670                let ctx = WaveCtx {
1671                    run: run_id,
1672                    node: "implement",
1673                    prompts,
1674                    cache: cache.as_deref(),
1675                    round: None,
1676                };
1677                let (fallback_seat, fallback_out) = run_one(
1678                    retry,
1679                    Arc::clone(&self.sem),
1680                    &ctx,
1681                    &mut self.state,
1682                    fallback_attempt,
1683                )
1684                .await;
1685                *seat = fallback_seat;
1686                *out = fallback_out;
1687            }
1688        }
1689    }
1690
1691    /// Ask an implement seat's own CLI to confirm what it started, once, when
1692    /// its reply reported a command whose completion status it never
1693    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
1694    /// that does and does not mean.
1695    ///
1696    /// The completion contract this task asks for, extended to `implement`
1697    /// with the same signal `continue_fix_report` reads for the fixer,
1698    /// rather than a keyword search over the reply or a hard requirement on
1699    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
1700    /// a candidate's CLI turn ended cleanly while a test run it had started
1701    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
1702    /// named in it at all is untouched by this: `commands` is empty, so
1703    /// there is nothing to be unconfirmed.
1704    ///
1705    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
1706    /// this is not about recovering edits that might already be on disk, it
1707    /// is about a result the seat itself never vouched for, which resuming
1708    /// asks for regardless of what the tree already holds. Bounded to one
1709    /// attempt for the same reason `resume_undelivered` is — this is the
1710    /// most expensive node in the graph — and a seat that still cannot
1711    /// confirm on that attempt is left as whatever its (possibly still
1712    /// unconfirmed) reply says; this does not invent a new "failed" reason
1713    /// for a candidate that otherwise produced a real, committed change.
1714    async fn resume_unconfirmed_commands(
1715        &mut self,
1716        results: &mut [(usize, SeatState, AgentOutcome)],
1717        sent: &[SeatJob],
1718        prompts: &Prompts,
1719        run_id: &str,
1720    ) {
1721        for (wi, seat, out) in results.iter_mut() {
1722            let AgentOutcome::Ok(o) = &*out else {
1723                continue;
1724            };
1725            if !has_unconfirmed_command(&o.commands) {
1726                continue;
1727            }
1728            let Some(job) = sent.get(*wi) else { continue };
1729            if !has_context(&job.spec, seat, job.sessions) {
1730                self.state.event(
1731                    "implement",
1732                    format!(
1733                        "{}: the reply named a command whose own CLI never confirmed the exit \
1734                         status of, but there is no session left to resume",
1735                        seat.key
1736                    ),
1737                );
1738                continue;
1739            }
1740            self.state.event(
1741                "implement",
1742                format!(
1743                    "{}: the reply named a command whose own CLI never confirmed the exit \
1744                     status of; resuming the conversation",
1745                    seat.key
1746                ),
1747            );
1748            let mut retry = job.clone();
1749            retry.seat = seat.clone();
1750            retry.prompt = prompt::resume_incomplete(
1751                "a command in your last reply had no confirmed exit status",
1752            );
1753            retry.timeout = retry_budget(job.timeout, true);
1754            retry.stem = format!("{}-confirm", job.stem);
1755            let cache = self.state.config.cache_dir();
1756            let ctx = WaveCtx {
1757                run: run_id,
1758                node: "implement",
1759                prompts,
1760                cache: cache.as_deref(),
1761                round: None,
1762            };
1763            let (resumed_seat, resumed) =
1764                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
1765            *seat = resumed_seat;
1766            *out = resumed;
1767        }
1768    }
1769
1770    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
1771    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
1772    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
1773    /// that motivated this.
1774    ///
1775    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
1776    /// own nudge loop already covers for judge/review/vote seats, and not a
1777    /// dropped stream, which [`Runner::resume_undelivered`] covers for
1778    /// implement seats: here the CLI turn genuinely finished while the node's
1779    /// own work — the fixer's account of what it did — had not. Gated purely
1780    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
1781    /// reply, never on any wording in it, so a fixer whose valid, first-try
1782    /// `FixReport` happens to mention having waited on a background test is
1783    /// never resumed — the `Ok(report)` branch at the call site returns
1784    /// before this is ever invoked.
1785    ///
1786    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
1787    /// attempt ([`retry_budget`]), nothing attempted once the session is
1788    /// gone, and a quota hit ends the loop immediately rather than retrying a
1789    /// rate limit that fails the same way again.
1790    async fn continue_fix_report(
1791        &mut self,
1792        mut seat: SeatState,
1793        parse_err: String,
1794        job: &SeatJob,
1795        prompts: &Prompts,
1796        run_id: &str,
1797        round: usize,
1798    ) -> (
1799        SeatState,
1800        Option<FixReport>,
1801        Option<String>,
1802        ContinuationRecord,
1803    ) {
1804        let mut last_err = parse_err;
1805        let mut cumulative_wait_ms = 0u64;
1806        let mut attempts = 0usize;
1807        loop {
1808            if !has_context(&job.spec, &seat, job.sessions) {
1809                self.state.event(
1810                    "fix",
1811                    format!(
1812                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
1813                         session left to resume into"
1814                    ),
1815                );
1816                let outcome = if attempts == 0 {
1817                    ContinuationOutcome::NoSession
1818                } else {
1819                    ContinuationOutcome::Exhausted
1820                };
1821                return (
1822                    seat,
1823                    None,
1824                    Some(format!("unparsable fix report: {last_err}")),
1825                    ContinuationRecord {
1826                        attempts,
1827                        cumulative_wait_ms,
1828                        outcome,
1829                    },
1830                );
1831            }
1832            if attempts >= MAX_FIX_CONTINUATIONS {
1833                self.state.event(
1834                    "fix",
1835                    format!(
1836                        "round {round}: fixer's reply still had no adoption report after \
1837                         {attempts} continuation(s) ({last_err}); giving up"
1838                    ),
1839                );
1840                return (
1841                    seat,
1842                    None,
1843                    Some(format!(
1844                        "unparsable fix report after {attempts} continuation(s): {last_err}"
1845                    )),
1846                    ContinuationRecord {
1847                        attempts,
1848                        cumulative_wait_ms,
1849                        outcome: ContinuationOutcome::Exhausted,
1850                    },
1851                );
1852            }
1853            attempts += 1;
1854            self.state.event(
1855                "fix",
1856                format!(
1857                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
1858                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
1859                ),
1860            );
1861            let mut retry = job.clone();
1862            retry.seat = seat.clone();
1863            retry.prompt = prompt::resume_incomplete(&last_err);
1864            retry.timeout = retry_budget(job.timeout, true);
1865            retry.stem = format!("{}-continue{attempts}", job.stem);
1866            let cache = self.state.config.cache_dir();
1867            let ctx = WaveCtx {
1868                run: run_id,
1869                node: "fix",
1870                prompts,
1871                cache: cache.as_deref(),
1872                round: Some(round),
1873            };
1874            let (resumed_seat, resumed_out) = run_one(
1875                retry,
1876                Arc::clone(&self.sem),
1877                &ctx,
1878                &mut self.state,
1879                attempts,
1880            )
1881            .await;
1882            seat = resumed_seat;
1883            match resumed_out {
1884                AgentOutcome::Ok(o) => {
1885                    cumulative_wait_ms += o.duration_ms;
1886                    match verdict::extract_json::<FixReport>(&o.text) {
1887                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
1888                            self.state.event(
1889                                "fix",
1890                                format!(
1891                                    "round {round}: fixer's adoption report recovered after \
1892                                     {attempts} continuation(s)"
1893                                ),
1894                            );
1895                            return (
1896                                seat,
1897                                Some(report),
1898                                None,
1899                                ContinuationRecord {
1900                                    attempts,
1901                                    cumulative_wait_ms,
1902                                    outcome: ContinuationOutcome::Resumed,
1903                                },
1904                            );
1905                        }
1906                        // The report parsed, but this same reply's own
1907                        // CommandEvidence — the identical record `state.jobs`
1908                        // renders — names a command whose CLI never
1909                        // confirmed an exit status. Read together, that is
1910                        // not a resolved answer: keep nudging rather than
1911                        // accept a report standing next to a command the
1912                        // seat's own CLI cannot vouch for.
1913                        Ok(_) => {
1914                            last_err = "the reply parsed, but it reported a command whose own CLI \
1915                                 never confirmed an exit status"
1916                                .to_owned();
1917                        }
1918                        Err(e) => last_err = e.to_string(),
1919                    }
1920                }
1921                AgentOutcome::Quota(o) => {
1922                    cumulative_wait_ms += o.duration_ms;
1923                    self.state.quota.push(QuotaLoss {
1924                        seat: seat.key.clone(),
1925                        node: "fix".to_owned(),
1926                        at: Timestamp::now(),
1927                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
1928                    });
1929                    self.state.event(
1930                        "fix",
1931                        format!(
1932                            "round {round}: continuation rate limited (quota); not retrying now"
1933                        ),
1934                    );
1935                    return (
1936                        seat,
1937                        None,
1938                        Some("rate limited (quota) while recovering the fix report".to_owned()),
1939                        ContinuationRecord {
1940                            attempts,
1941                            cumulative_wait_ms,
1942                            outcome: ContinuationOutcome::QuotaLost,
1943                        },
1944                    );
1945                }
1946                AgentOutcome::Dropped(o) => {
1947                    cumulative_wait_ms += o.duration_ms;
1948                    let why = o
1949                        .dropped
1950                        .as_ref()
1951                        .map(|d| d.why.as_str())
1952                        .unwrap_or("the CLI ended the stream without delivering its answer");
1953                    last_err = format!("the CLI dropped the stream ({why})");
1954                }
1955                AgentOutcome::Failed(e) => last_err = e,
1956            }
1957        }
1958    }
1959
1960    fn after_implement(&mut self) -> Result<()> {
1961        // Scan every candidate patch once the set is complete.
1962        if self.state.leaks.is_empty() {
1963            let cfg = self.state.config.blind.clone();
1964            let mut leaks = Vec::new();
1965            for c in &self.state.candidates {
1966                let Some(patch) =
1967                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
1968                else {
1969                    continue;
1970                };
1971                leaks.extend(blind::scan(
1972                    &format!("candidate {} patch", c.label),
1973                    &patch,
1974                    &cfg.vendor_tokens,
1975                ));
1976            }
1977            if !leaks.is_empty() {
1978                let summary = leaks
1979                    .iter()
1980                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
1981                    .collect::<Vec<_>>()
1982                    .join(", ");
1983                match cfg.on_leak {
1984                    LeakPolicy::Fail => {
1985                        self.state.status = RunStatus::Failed;
1986                        self.state
1987                            .event("blind", format!("vendor text in a patch: {summary}"));
1988                        self.state.leaks = leaks;
1989                        self.state.save()?;
1990                        self.settle_questions();
1991                        bail!(
1992                            "blind.on_leak = \"fail\" and vendor text reached a \
1993                             judged patch: {summary}"
1994                        );
1995                    }
1996                    LeakPolicy::Redact => self.state.event(
1997                        "blind",
1998                        format!("redacting vendor text for judging: {summary}"),
1999                    ),
2000                    LeakPolicy::Warn => self.state.event(
2001                        "blind",
2002                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
2003                    ),
2004                }
2005                self.state.leaks = leaks;
2006            }
2007        }
2008
2009        if self.state.viable().is_empty() {
2010            if self.state.all_candidates_verified_noop() {
2011                // Every candidate agreed, with evidence the adoption guard
2012                // accepted, that nothing belongs in this worktree. That is
2013                // not the same fact as a candidate that simply failed to
2014                // write anything, and settling it as an ordinary `Failed`
2015                // (see `SCHEMA`'s doc for schema 10) is what let two of
2016                // task 391f's attempts burn a retry each re-discovering the
2017                // same already-landed fix. Terminal either way, so `judge`
2018                // must never run over an empty candidate set — unlike the
2019                // `Failed` branch below this returns `Ok`, not an error:
2020                // nothing here failed.
2021                self.state.status = RunStatus::VerifiedNoop;
2022                self.state.save()?;
2023                self.settle_questions();
2024                return Ok(());
2025            }
2026            self.state.status = RunStatus::Failed;
2027            self.state.save()?;
2028            self.settle_questions();
2029            bail!("no candidate produced a change; nothing to judge");
2030        }
2031        self.state.status = RunStatus::Judging;
2032        self.state.save()?;
2033        Ok(())
2034    }
2035
2036    // --------------------------------------------------------------- judge
2037
2038    async fn judge(&mut self) -> Result<()> {
2039        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2040        // agent files with `magi task add` name the run that paid for it. The
2041        // prompt overlay is cloned alongside it because the waves borrow it
2042        // while `self` is mutably borrowed by the node's own bookkeeping.
2043        let run_id = self.state.id.clone();
2044        let prompts = self.state.config.prompts.clone();
2045        if !self.state.judgements.is_empty() || self.state.judge_skipped {
2046            return Ok(());
2047        }
2048        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2049        if viable.len() == 1 {
2050            // Recorded so this is a one-time event: `judgements` stays empty
2051            // either way, which without this flag is indistinguishable from
2052            // "not yet judged" on the next reentry — and status is left
2053            // untouched, so a later node's conclusion (e.g. `Blocked` after
2054            // the review budget ran out) survives a resume instead of being
2055            // clobbered back to `Judging` by this node running again.
2056            self.state.judge_skipped = true;
2057            self.state.event(
2058                "judge",
2059                format!(
2060                    "only candidate {} produced a change; judging skipped",
2061                    viable[0].label
2062                ),
2063            );
2064            self.state.save()?;
2065            return Ok(());
2066        }
2067        self.state.status = RunStatus::Judging;
2068
2069        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
2070        let language = self.state.config.graph.language.clone();
2071        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2072        let sessions = self.state.config.graph.sessions;
2073        let artifacts = agent::artifacts_dir(&self.state.dir());
2074        let root = self.state.worktree_root();
2075        let base_short = short(&self.state.base_commit);
2076
2077        let mut jobs = Vec::new();
2078        let mut orders = Vec::new();
2079        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2080            let order = blind::presentation_order(viable.len(), j, self.state.seed);
2081            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
2082            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
2083            let seat_key = format!("judge-{}", j + 1);
2084            let seat = self.seat(&seat_key, &spec.id);
2085            jobs.push(SeatJob {
2086                prompt: prompt::judge(
2087                    &self.state.instruction,
2088                    &views,
2089                    self.roles.judges.len(),
2090                    &base_short,
2091                    &language,
2092                ),
2093                spec,
2094                seat,
2095                cwd: root.join(format!("judge-{}", j + 1)),
2096                timeout,
2097                allow_write: false,
2098                sessions,
2099                artifacts: artifacts.clone(),
2100                stem: format!("judge-{}", j + 1),
2101            });
2102        }
2103
2104        self.state.event(
2105            "judge",
2106            format!(
2107                "{} judges ranking {} candidates blind",
2108                jobs.len(),
2109                viable.len()
2110            ),
2111        );
2112        let labels_for_check = labels.clone();
2113        let mut quota_losses = Vec::new();
2114        let cache = self.state.config.cache_dir();
2115        let ctx = WaveCtx {
2116            run: &run_id,
2117            node: "judge",
2118            prompts: &prompts,
2119            cache: cache.as_deref(),
2120            round: None,
2121        };
2122        let results = ask_json_wave::<Ranking>(
2123            jobs,
2124            Arc::clone(&self.sem),
2125            self.state.config.graph.retries,
2126            &ctx,
2127            &mut quota_losses,
2128            &mut self.state,
2129            &move |r: &Ranking| r.validate(&labels_for_check),
2130        )
2131        .await;
2132        self.state.quota.extend(quota_losses);
2133
2134        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
2135            let agent_id = seat.agent.clone();
2136            self.state.seats.insert(seat.key.clone(), seat);
2137            let mut record = Judgement {
2138                judge: j + 1,
2139                seat: format!("judge-{}", j + 1),
2140                agent: agent_id,
2141                ranking: Vec::new(),
2142                reasons: BTreeMap::new(),
2143                confidence: None,
2144                order: orders[j].clone(),
2145                failed: None,
2146                duration_ms: 0,
2147            };
2148            match res {
2149                Ok((ranking, out)) => {
2150                    record.ranking = ranking.normalized();
2151                    record.reasons = ranking.reasons;
2152                    record.confidence = ranking.confidence;
2153                    record.duration_ms = out.duration_ms;
2154                    self.state.event(
2155                        "judge",
2156                        format!(
2157                            "judge {} ranked {}",
2158                            j + 1,
2159                            record.ranking.iter().collect::<String>()
2160                        ),
2161                    );
2162                }
2163                Err(e) => {
2164                    record.failed = Some(e.to_string());
2165                    self.state
2166                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
2167                }
2168            }
2169            self.state.judgements.push(record);
2170            self.state.save()?;
2171        }
2172        Ok(())
2173    }
2174
2175    // ---------------------------------------------------------- deliberate
2176
2177    async fn deliberate(&mut self) -> Result<()> {
2178        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2179        // agent files with `magi task add` name the run that paid for it. The
2180        // prompt overlay is cloned alongside it because the waves borrow it
2181        // while `self` is mutably borrowed by the node's own bookkeeping.
2182        let run_id = self.state.id.clone();
2183        let prompts = self.state.config.prompts.clone();
2184        if !self.state.deliberation.is_empty() {
2185            return Ok(());
2186        }
2187        let tops: Vec<char> = self
2188            .state
2189            .judgements
2190            .iter()
2191            .filter_map(|j| j.ranking.first().copied())
2192            .collect();
2193        let rounds = self.state.config.graph.deliberate_rounds;
2194        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
2195            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
2196                self.state.event(
2197                    "deliberate",
2198                    format!("judges agreed on {} outright; no deliberation", tops[0]),
2199                );
2200            }
2201            self.state.status = RunStatus::Voting;
2202            self.state.save()?;
2203            return Ok(());
2204        }
2205
2206        self.state.status = RunStatus::Deliberating;
2207        self.state.event(
2208            "deliberate",
2209            format!(
2210                "split: first choices were {} — opening {rounds} round(s)",
2211                tops.iter().collect::<String>()
2212            ),
2213        );
2214
2215        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2216        let language = self.state.config.graph.language.clone();
2217        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2218        let sessions = self.state.config.graph.sessions;
2219        let artifacts = agent::artifacts_dir(&self.state.dir());
2220        let root = self.state.worktree_root();
2221        let base_short = short(&self.state.base_commit);
2222
2223        // Judges argue in sequence so that a turn can answer the one before it;
2224        // that is the difference between deliberation and three parallel
2225        // monologues.
2226        for round in 1..=rounds {
2227            let mut turns: Vec<DeliberationTurn> = Vec::new();
2228            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2229                if self.state.judgements[j].failed.is_some() {
2230                    continue;
2231                }
2232                let seat_key = format!("judge-{}", j + 1);
2233                let mut seat = self.seat(&seat_key, &spec.id);
2234                let transcript = self.transcript(&turns, j);
2235                let context = if has_context(&spec, &seat, sessions) {
2236                    None
2237                } else {
2238                    Some(self.candidate_block(&viable, &base_short))
2239                };
2240                let text = prompt::deliberate(
2241                    &self.state.instruction,
2242                    context.as_deref(),
2243                    &transcript,
2244                    round,
2245                    rounds,
2246                    &language,
2247                );
2248                let job = SeatJob {
2249                    spec,
2250                    seat: seat.clone(),
2251                    prompt: text,
2252                    cwd: root.join(format!("judge-{}", j + 1)),
2253                    timeout,
2254                    allow_write: false,
2255                    sessions,
2256                    artifacts: artifacts.clone(),
2257                    stem: format!("delib-{round}-judge-{}", j + 1),
2258                };
2259                let cache = self.state.config.cache_dir();
2260                let ctx = WaveCtx {
2261                    run: &run_id,
2262                    node: "deliberate",
2263                    prompts: &prompts,
2264                    cache: cache.as_deref(),
2265                    round: None,
2266                };
2267                let (updated, out) =
2268                    run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
2269                seat = updated;
2270                let agent_id = seat.agent.clone();
2271                let seat_key = seat.key.clone();
2272                self.state.seats.insert(seat.key.clone(), seat);
2273                let body = match out {
2274                    AgentOutcome::Ok(o) => verdict::section(&o.text, "position").unwrap_or(o.text),
2275                    // Never read the CLI's raw error JSON as this judge's
2276                    // position — skip the seat instead, the same as any other
2277                    // failed turn.
2278                    AgentOutcome::Dropped(o) => {
2279                        let why =
2280                            o.dropped.as_ref().map(|d| d.why.as_str()).unwrap_or(
2281                                "the CLI ended the stream without delivering its answer",
2282                            );
2283                        self.state.event(
2284                            "deliberate",
2285                            format!(
2286                                "judge {} skipped: the CLI dropped the stream ({why})",
2287                                j + 1
2288                            ),
2289                        );
2290                        continue;
2291                    }
2292                    AgentOutcome::Quota(o) => {
2293                        self.state.quota.push(QuotaLoss {
2294                            seat: seat_key,
2295                            node: "deliberate".to_owned(),
2296                            at: Timestamp::now(),
2297                            reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
2298                        });
2299                        self.state.event(
2300                            "deliberate",
2301                            format!("judge {} skipped: rate limited (quota)", j + 1),
2302                        );
2303                        continue;
2304                    }
2305                    AgentOutcome::Failed(e) => {
2306                        self.state
2307                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
2308                        continue;
2309                    }
2310                };
2311                let tentative = verdict::extract_json::<Position>(&body)
2312                    .ok()
2313                    .and_then(|p| p.tentative)
2314                    .and_then(|s| s.trim().chars().next())
2315                    .map(|c| c.to_ascii_uppercase());
2316                self.state.event(
2317                    "deliberate",
2318                    format!(
2319                        "round {round}: judge {} now favours {}",
2320                        j + 1,
2321                        tentative.map_or("—".to_owned(), |c| c.to_string())
2322                    ),
2323                );
2324                turns.push(DeliberationTurn {
2325                    judge: j + 1,
2326                    agent: agent_id,
2327                    body: blind::sanitize_prose(&body, &self.state.config.blind),
2328                    tentative,
2329                });
2330            }
2331            self.state
2332                .deliberation
2333                .push(DeliberationRound { round, turns });
2334            self.state.save()?;
2335        }
2336
2337        self.state.status = RunStatus::Voting;
2338        self.state.save()?;
2339        Ok(())
2340    }
2341
2342    // ---------------------------------------------------------------- vote
2343
2344    async fn vote(&mut self) -> Result<()> {
2345        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2346        // agent files with `magi task add` name the run that paid for it. The
2347        // prompt overlay is cloned alongside it because the waves borrow it
2348        // while `self` is mutably borrowed by the node's own bookkeeping.
2349        let run_id = self.state.id.clone();
2350        let prompts = self.state.config.prompts.clone();
2351        if !self.state.votes.is_empty() {
2352            return Ok(());
2353        }
2354        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
2355        if viable.len() == 1 {
2356            return Ok(());
2357        }
2358        self.state.status = RunStatus::Voting;
2359
2360        let language = self.state.config.graph.language.clone();
2361        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2362        let sessions = self.state.config.graph.sessions;
2363        let artifacts = agent::artifacts_dir(&self.state.dir());
2364        let root = self.state.worktree_root();
2365        let base_short = short(&self.state.base_commit);
2366        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2367
2368        let mut jobs = Vec::new();
2369        let mut seats_at = Vec::new();
2370        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
2371            if self
2372                .state
2373                .judgements
2374                .get(j)
2375                .is_some_and(|r| r.failed.is_some())
2376            {
2377                continue;
2378            }
2379            let seat_key = format!("judge-{}", j + 1);
2380            let seat = self.seat(&seat_key, &spec.id);
2381            let mut text = prompt::final_vote(&viable, &language);
2382            if !has_context(&spec, &seat, sessions) {
2383                text = format!(
2384                    "{}\n\n# Candidates\n\n{}",
2385                    text,
2386                    self.candidate_block(&candidates, &base_short)
2387                );
2388            }
2389            jobs.push(SeatJob {
2390                spec,
2391                seat,
2392                prompt: text,
2393                cwd: root.join(format!("judge-{}", j + 1)),
2394                timeout,
2395                allow_write: false,
2396                sessions,
2397                artifacts: artifacts.clone(),
2398                stem: format!("vote-judge-{}", j + 1),
2399            });
2400            seats_at.push(j);
2401        }
2402
2403        self.state.event(
2404            "vote",
2405            format!(
2406                "collecting {} final votes one by one, privately",
2407                jobs.len()
2408            ),
2409        );
2410        let allowed = viable.clone();
2411        let mut quota_losses = Vec::new();
2412        let cache = self.state.config.cache_dir();
2413        let ctx = WaveCtx {
2414            run: &run_id,
2415            node: "vote",
2416            prompts: &prompts,
2417            cache: cache.as_deref(),
2418            round: None,
2419        };
2420        let results = ask_json_wave::<FinalVote>(
2421            jobs,
2422            Arc::clone(&self.sem),
2423            self.state.config.graph.retries,
2424            &ctx,
2425            &mut quota_losses,
2426            &mut self.state,
2427            &move |v: &FinalVote| match v.label() {
2428                Some(c) if allowed.contains(&c) => Ok(()),
2429                other => bail!("vote {other:?} is not one of {allowed:?}"),
2430            },
2431        )
2432        .await;
2433        self.state.quota.extend(quota_losses);
2434
2435        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
2436            let agent_id = seat.agent.clone();
2437            self.state.seats.insert(seat.key.clone(), seat);
2438            let initial = self
2439                .state
2440                .judgements
2441                .get(j)
2442                .and_then(|r| r.ranking.first().copied());
2443            let mut record = VoteRecord {
2444                judge: j + 1,
2445                agent: agent_id,
2446                vote: None,
2447                reason: String::new(),
2448                changed: false,
2449            };
2450            match res {
2451                Ok((v, _)) => {
2452                    record.vote = v.label();
2453                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
2454                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
2455                    self.state.event(
2456                        "vote",
2457                        format!(
2458                            "judge {} voted {}{}",
2459                            j + 1,
2460                            record.vote.unwrap_or('?'),
2461                            if record.changed { " (changed)" } else { "" }
2462                        ),
2463                    );
2464                }
2465                Err(e) => {
2466                    self.state
2467                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
2468                }
2469            }
2470            self.state.votes.push(record);
2471            self.state.save()?;
2472        }
2473        Ok(())
2474    }
2475
2476    // --------------------------------------------------------------- tally
2477
2478    fn tally(&mut self) -> Result<()> {
2479        if self.state.tally.is_some() {
2480            return Ok(());
2481        }
2482        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
2483        let tops: Vec<char> = self
2484            .state
2485            .judgements
2486            .iter()
2487            .filter_map(|j| j.ranking.first().copied())
2488            .collect();
2489        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
2490
2491        // A judge whose private vote failed still counted once, in the initial
2492        // ranking; using it beats discarding a whole seat.
2493        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
2494        let mut cast: Vec<char> = Vec::new();
2495        for (i, j) in self.state.judgements.iter().enumerate() {
2496            let vote = self
2497                .state
2498                .votes
2499                .iter()
2500                .find(|v| v.judge == i + 1)
2501                .and_then(|v| v.vote)
2502                .or_else(|| j.ranking.first().copied());
2503            if let Some(v) = vote {
2504                *first_choice.entry(v).or_insert(0) += 1;
2505                cast.push(v);
2506            }
2507        }
2508
2509        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
2510        for j in &self.state.judgements {
2511            let n = j.ranking.len();
2512            for (pos, label) in j.ranking.iter().enumerate() {
2513                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
2514            }
2515        }
2516
2517        let best = first_choice.values().copied().max().unwrap_or(0);
2518        let mut leaders: Vec<char> = first_choice
2519            .iter()
2520            .filter(|(_, v)| **v == best)
2521            .map(|(k, _)| *k)
2522            .collect();
2523        let mut tie_break = None;
2524        if leaders.len() > 1 {
2525            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
2526            let borda_leaders: Vec<char> = leaders
2527                .iter()
2528                .copied()
2529                .filter(|l| borda[l] == top_borda)
2530                .collect();
2531            tie_break = Some(if borda_leaders.len() == 1 {
2532                format!(
2533                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
2534                    leaders.len()
2535                )
2536            } else {
2537                format!(
2538                    "{} way tie on both first-choice votes and Borda points, broken by label order",
2539                    leaders.len()
2540                )
2541            });
2542            leaders = borda_leaders;
2543            leaders.sort_unstable();
2544        }
2545        let winner = *leaders
2546            .first()
2547            .or(viable.first())
2548            .context("no candidate to declare a winner from")?;
2549
2550        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
2551        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
2552        let deliberated = !self.state.deliberation.is_empty();
2553
2554        // Whose verdict is this? A rate-limited seat is absent even if it
2555        // ranked before the limit hit, so presence is measured against the
2556        // recorded losses, not just "did a ranking ever appear".
2557        let quota_seats: std::collections::BTreeSet<&str> =
2558            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
2559        let mut present = 0usize;
2560        for (i, j) in self.state.judgements.iter().enumerate() {
2561            if quota_seats.contains(j.seat.as_str()) {
2562                continue;
2563            }
2564            let ranked = !j.ranking.is_empty() && j.failed.is_none();
2565            let voted = self
2566                .state
2567                .votes
2568                .iter()
2569                .any(|v| v.judge == i + 1 && v.vote.is_some());
2570            if ranked || voted {
2571                present += 1;
2572            }
2573        }
2574        // Strict majority of the configured panel. A bare majority is real
2575        // signal we can act on, while a minority verdict must never stand in
2576        // for a healthy one. A one-candidate run needs no panel at all, and
2577        // `judges` stays `0` rather than the roster size a panel that never
2578        // sat would otherwise be credited with.
2579        let needs_quorum = viable.len() > 1;
2580        let judges_total = if needs_quorum {
2581            self.roles.judges.len()
2582        } else {
2583            0
2584        };
2585        let quorum = if needs_quorum {
2586            judges_total / 2 + 1
2587        } else {
2588            0
2589        };
2590        let met_quorum = !needs_quorum || present >= quorum;
2591        let uncontested = (!needs_quorum).then(|| {
2592            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
2593        });
2594
2595        self.state.event(
2596            "tally",
2597            match &uncontested {
2598                Some(reason) => format!("winner {winner} — {reason}"),
2599                None => format!(
2600                    "winner {winner} — votes {} | initial {} | {} changed | \
2601                     {present}/{judges_total} judges{}",
2602                    first_choice
2603                        .iter()
2604                        .map(|(k, v)| format!("{k}:{v}"))
2605                        .collect::<Vec<_>>()
2606                        .join(" "),
2607                    if unanimous_initial {
2608                        "unanimous"
2609                    } else {
2610                        "split"
2611                    },
2612                    changed_votes,
2613                    if met_quorum {
2614                        String::new()
2615                    } else {
2616                        format!(" — below quorum ({quorum} required)")
2617                    },
2618                ),
2619            },
2620        );
2621        if !met_quorum {
2622            self.state.event(
2623                "stall",
2624                format!(
2625                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
2626                     the run stops here, resumable"
2627                ),
2628            );
2629        }
2630        self.state.tally = Some(Tally {
2631            first_choice,
2632            borda,
2633            winner,
2634            rankings: tops.len(),
2635            unanimous_initial,
2636            deliberated,
2637            changed_votes,
2638            unanimous_final,
2639            tie_break,
2640            judges: judges_total,
2641            present,
2642            quorum,
2643            met_quorum,
2644            uncontested,
2645        });
2646        self.state.status = if met_quorum {
2647            RunStatus::Reviewing
2648        } else {
2649            RunStatus::Stalled
2650        };
2651        self.state.save()?;
2652        Ok(())
2653    }
2654
2655    // ------------------------------------------------------------- recover
2656
2657    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
2658    /// resumed toward completion once the transient cause clears.
2659    ///
2660    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
2661    /// it toward the quorum, which is exactly the set of seats whose absence
2662    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
2663    /// not depend on which node happened to hit the limit), or an ordinary
2664    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
2665    /// seat is never disturbed.
2666    ///
2667    /// A seat that now answers with a usable ranking is "recovered": its
2668    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
2669    /// `tally` counts it present again), and its vote re-collected. A seat that
2670    /// still fails keeps its loss and stays absent.
2671    ///
2672    /// Returns `true` when the re-tally restores the quorum (the run may proceed
2673    /// to review/gate/merge), `false` when it is still below quorum (the run
2674    /// stays `Stalled`, still resumable for a later retry).
2675    #[allow(clippy::too_many_lines)]
2676    async fn recover_stall(&mut self) -> Result<bool> {
2677        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
2678        // agent files with `magi task add` name the run that paid for it. The
2679        // prompt overlay is cloned alongside it because the waves borrow it
2680        // while `self` is mutably borrowed by the node's own bookkeeping.
2681        let run_id = self.state.id.clone();
2682        let prompts = self.state.config.prompts.clone();
2683        // Absent seats = quota-lost at any node, or failed outright. Mirroring
2684        // `tally`'s presence test (rather than the old quota-judge/vote filter)
2685        // is what keeps a non-quota collapse — or a quota loss recorded at the
2686        // deliberate node — from being a permanent dead-end on `--resume`.
2687        let quota_seats: BTreeSet<&str> =
2688            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
2689        let absent: Vec<String> = self
2690            .state
2691            .judgements
2692            .iter()
2693            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
2694            .map(|j| j.seat.clone())
2695            .collect();
2696        if absent.is_empty() {
2697            return Ok(false);
2698        }
2699        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
2700        if viable.len() <= 1 {
2701            return Ok(false);
2702        }
2703        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
2704        let language = self.state.config.graph.language.clone();
2705        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
2706        let sessions = self.state.config.graph.sessions;
2707        let artifacts = agent::artifacts_dir(&self.state.dir());
2708        let root = self.state.worktree_root();
2709        let base_short = short(&self.state.base_commit);
2710        let candidates: Vec<Candidate> = viable.clone();
2711
2712        // Map each absent seat key to its 0-based position in `roles.judges`.
2713        let mut positions: Vec<usize> = absent
2714            .iter()
2715            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
2716            .collect();
2717        if positions.is_empty() {
2718            return Ok(false);
2719        }
2720        positions.sort_unstable();
2721        positions.dedup();
2722
2723        // Re-rank the lost seats, one blind prompt each.
2724        let mut judge_jobs = Vec::new();
2725        for &j in &positions {
2726            let order = blind::presentation_order(viable.len(), j, self.state.seed);
2727            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
2728            let seat_key = format!("judge-{}", j + 1);
2729            let spec = self.roles.judges[j].clone();
2730            let seat = self.seat(&seat_key, &spec.id);
2731            judge_jobs.push(SeatJob {
2732                spec,
2733                seat,
2734                prompt: prompt::judge(
2735                    &self.state.instruction,
2736                    &views,
2737                    self.roles.judges.len(),
2738                    &base_short,
2739                    &language,
2740                ),
2741                cwd: root.join(seat_key),
2742                timeout,
2743                allow_write: false,
2744                sessions,
2745                artifacts: artifacts.clone(),
2746                stem: format!("judge-{}-recover", j + 1),
2747            });
2748        }
2749
2750        let labels_for_check = labels.clone();
2751        let mut judge_losses = Vec::new();
2752        let retries = self.state.config.graph.retries;
2753        let cache = self.state.config.cache_dir();
2754        let ctx = WaveCtx {
2755            run: &run_id,
2756            node: "judge",
2757            prompts: &prompts,
2758            cache: cache.as_deref(),
2759            round: None,
2760        };
2761        let results = ask_json_wave::<Ranking>(
2762            judge_jobs,
2763            Arc::clone(&self.sem),
2764            retries,
2765            &ctx,
2766            &mut judge_losses,
2767            &mut self.state,
2768            &move |r: &Ranking| r.validate(&labels_for_check),
2769        )
2770        .await;
2771
2772        // Refresh the judgement of every seat that ranked again.
2773        let mut recovered: BTreeSet<usize> = BTreeSet::new();
2774        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
2775            self.state.seats.insert(seat.key.clone(), seat);
2776            let record = &mut self.state.judgements[j];
2777            match res {
2778                Ok((ranking, out)) => {
2779                    record.ranking = ranking.normalized();
2780                    record.reasons = ranking.reasons;
2781                    record.confidence = ranking.confidence;
2782                    record.failed = None;
2783                    record.duration_ms = out.duration_ms;
2784                    recovered.insert(j);
2785                    self.state.event(
2786                        "recover",
2787                        format!("judge {} ranked again after the limit", j + 1),
2788                    );
2789                }
2790                Err(e) => {
2791                    self.state
2792                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
2793                }
2794            }
2795        }
2796
2797        // Re-ask the votes of the seats that recovered a ranking.
2798        let mut vote_jobs = Vec::new();
2799        let mut vote_pos: Vec<usize> = Vec::new();
2800        for &j in &recovered {
2801            let seat_key = format!("judge-{}", j + 1);
2802            let spec = self.roles.judges[j].clone();
2803            let seat = self.seat(&seat_key, &spec.id);
2804            let mut text = prompt::final_vote(&labels, &language);
2805            if !has_context(&spec, &seat, sessions) {
2806                text = format!(
2807                    "{}\n\n# Candidates\n\n{}",
2808                    text,
2809                    self.candidate_block(&candidates, &base_short)
2810                );
2811            }
2812            vote_jobs.push(SeatJob {
2813                spec,
2814                seat,
2815                prompt: text,
2816                cwd: root.join(seat_key),
2817                timeout,
2818                allow_write: false,
2819                sessions,
2820                artifacts: artifacts.clone(),
2821                stem: format!("vote-judge-{}-recover", j + 1),
2822            });
2823            vote_pos.push(j);
2824        }
2825        let allowed = labels.clone();
2826        let mut vote_losses = Vec::new();
2827        let vote_retries = self.state.config.graph.retries;
2828        let vote_cache = self.state.config.cache_dir();
2829        let ctx = WaveCtx {
2830            run: &run_id,
2831            node: "vote",
2832            prompts: &prompts,
2833            cache: vote_cache.as_deref(),
2834            round: None,
2835        };
2836        let votes = ask_json_wave::<FinalVote>(
2837            vote_jobs,
2838            Arc::clone(&self.sem),
2839            vote_retries,
2840            &ctx,
2841            &mut vote_losses,
2842            &mut self.state,
2843            &move |v: &FinalVote| match v.label() {
2844                Some(c) if allowed.contains(&c) => Ok(()),
2845                other => bail!("vote {other:?} is not one of {allowed:?}"),
2846            },
2847        )
2848        .await;
2849        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
2850            let agent_id = seat.agent.clone();
2851            self.state.seats.insert(seat.key.clone(), seat);
2852            match res {
2853                Ok((v, _)) => {
2854                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
2855                        rec.vote = v.label();
2856                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
2857                    } else {
2858                        self.state.votes.push(VoteRecord {
2859                            judge: j + 1,
2860                            agent: agent_id,
2861                            vote: v.label(),
2862                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
2863                            changed: false,
2864                        });
2865                    }
2866                    self.state.event(
2867                        "recover",
2868                        format!("judge {} voted again after the limit", j + 1),
2869                    );
2870                }
2871                Err(e) => {
2872                    self.state
2873                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
2874                }
2875            }
2876        }
2877
2878        // A seat that ranked again is present even if its re-vote failed —
2879        // `tally` falls back to the initial ranking's first choice — so clear
2880        // its quota loss. Seats that still fail keep theirs and stay absent.
2881        if !recovered.is_empty() {
2882            let recovered_keys: BTreeSet<String> = recovered
2883                .iter()
2884                .map(|&j| format!("judge-{}", j + 1))
2885                .collect();
2886            self.state
2887                .quota
2888                .retain(|q| !recovered_keys.contains(&q.seat));
2889        }
2890
2891        // Recompute the verdict from the refreshed panel.
2892        self.state.tally = None;
2893        self.tally()?;
2894        Ok(self
2895            .state
2896            .tally
2897            .as_ref()
2898            .map(|t| t.met_quorum)
2899            .unwrap_or(false))
2900    }
2901
2902    // ----------------------------------------------------------------- fold
2903
2904    async fn fold_losers(&mut self) -> Result<()> {
2905        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
2906            return Ok(());
2907        };
2908        let repo = self.state.repo.clone();
2909        let mut folded = Vec::new();
2910        for i in 0..self.state.candidates.len() {
2911            let c = &self.state.candidates[i];
2912            if c.label == winner || c.folded {
2913                continue;
2914            }
2915            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
2916            git::worktree_remove(&repo, &wt).await.ok();
2917            git::branch_delete(&repo, &branch).await.ok();
2918            self.state.candidates[i].folded = true;
2919            folded.push(label.to_string());
2920        }
2921        // The judges are finished; their checkouts are pure cost from here.
2922        let root = self.state.worktree_root();
2923        for j in 1..=self.roles.judges.len() {
2924            let wt = root.join(format!("judge-{j}"));
2925            if wt.exists() {
2926                git::worktree_remove(&repo, &wt).await.ok();
2927            }
2928        }
2929        // The design-deliberation stage is finished by the time a tally
2930        // exists — same reasoning as the judges above.
2931        if self.state.config.graph.advise {
2932            for k in 1..=self.state.config.graph.advisors {
2933                let wt = root.join(format!("advisor-{k}"));
2934                if wt.exists() {
2935                    git::worktree_remove(&repo, &wt).await.ok();
2936                }
2937            }
2938        }
2939        if !folded.is_empty() {
2940            self.state
2941                .event("fold", format!("folded candidates {}", folded.join(", ")));
2942            self.state.save()?;
2943        }
2944        Ok(())
2945    }
2946
2947    // ------------------------------------------------------------ base sync
2948
2949    /// Land the winner's tree on the current tip of `<remote>/<base>` before
2950    /// anything verifies it.
2951    ///
2952    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
2953    /// read whatever is checked out in the winner's worktree. Left alone that
2954    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
2955    /// it when the run *branched* - and a run takes long enough that the base
2956    /// has usually moved by the time it gets here. A gate that ran there
2957    /// answers "green on the commit this run started from", not "green on
2958    /// what is about to land", and the difference showed up three times in
2959    /// one day as a green run whose merge would have reverted a file another
2960    /// pull request had already landed.
2961    ///
2962    /// Reuses [`git::rebase_branch_in_temp`] rather than a second
2963    /// implementation of the same idea: `land::Step::Rebase` already worked
2964    /// out the rules - throwaway worktree, conflict stops and reports rather
2965    /// than feeding a fixer, nothing runs in the primary tree - and a second
2966    /// rebase path is exactly the kind of drift `resolve_base`'s own doc
2967    /// warns about ("two answers to a question nobody notices until a diff is
2968    /// wrong").
2969    ///
2970    /// Bounded by [`BASE_SYNC_ROUNDS`], counted in `state.base_sync.attempts`
2971    /// so it survives a park/resume. A conflict or a push failure sets
2972    /// `state.base_sync.conflict` and leaves the branch and worktree exactly
2973    /// as they were - untouched, for a person to look at - which is also what
2974    /// makes re-entering this function afterwards a no-op instead of a second
2975    /// attempt at the same wall.
2976    async fn sync_to_base(&mut self) -> Result<()> {
2977        if self
2978            .state
2979            .base_sync
2980            .as_ref()
2981            .is_some_and(|s| s.conflict.is_some())
2982        {
2983            return Ok(());
2984        }
2985        let Some(winner) = self.state.winner().cloned() else {
2986            return Ok(());
2987        };
2988
2989        let repo = self.state.repo.clone();
2990        let remote = self.state.config.merge.remote.clone();
2991        let base_branch = self.state.base_branch.clone();
2992        let tracking = format!("{remote}/{base_branch}");
2993
2994        git::fetch(&repo, &remote, &base_branch).await.ok();
2995        // No network, or the remote never had this branch: `resolve_base`
2996        // already treats that as non-fatal at branch time, and a run that got
2997        // this far must not be blocked by it here either.
2998        let Ok(tip) = git::rev_parse(&repo, &tracking).await else {
2999            return Ok(());
3000        };
3001
3002        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3003        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
3004        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
3005
3006        if behind == 0 {
3007            self.state.base_sync = Some(BaseSync {
3008                tip,
3009                behind: 0,
3010                attempts,
3011                conflict: None,
3012            });
3013            self.state.save()?;
3014            return Ok(());
3015        }
3016
3017        if attempts >= BASE_SYNC_ROUNDS {
3018            let why = format!(
3019                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
3020                 rebase(s); rebasing again would only race it",
3021                winner.branch
3022            );
3023            self.state.status = RunStatus::Blocked;
3024            self.state.base_sync = Some(BaseSync {
3025                tip,
3026                behind,
3027                attempts,
3028                conflict: Some(why.clone()),
3029            });
3030            self.state.event("land", why);
3031            self.state.save()?;
3032            return Ok(());
3033        }
3034
3035        self.state.event(
3036            "land",
3037            format!(
3038                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
3039                winner.branch
3040            ),
3041        );
3042        self.state.save()?;
3043
3044        let scratch = self.state.dir().join("base-sync");
3045        let rebased = git::rebase_branch_in_temp(&repo, &scratch, &winner.branch, &tracking).await;
3046        let attempts = attempts + 1;
3047        match rebased {
3048            Ok(None) => {
3049                // The branch ref moved, but a worktree that already had it
3050                // checked out (the winner's) was not told; sync its index and
3051                // files before anything reads them.
3052                git::sync_to_head(&winner.worktree).await?;
3053                self.state.base_sync = Some(BaseSync {
3054                    tip: tip.clone(),
3055                    behind: 0,
3056                    attempts,
3057                    conflict: None,
3058                });
3059                self.state
3060                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
3061            }
3062            Ok(Some(conflict)) => {
3063                let why = format!(
3064                    "{} conflicts with {tracking} and did not rebase: {}",
3065                    winner.branch,
3066                    conflict.chars().take(600).collect::<String>()
3067                );
3068                self.state.status = RunStatus::Blocked;
3069                self.state.base_sync = Some(BaseSync {
3070                    tip,
3071                    behind,
3072                    attempts,
3073                    conflict: Some(why.clone()),
3074                });
3075                self.state.event("land", why);
3076            }
3077            Err(e) => {
3078                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
3079                self.state.status = RunStatus::Blocked;
3080                self.state.base_sync = Some(BaseSync {
3081                    tip,
3082                    behind,
3083                    attempts,
3084                    conflict: Some(why.clone()),
3085                });
3086                self.state.event("land", why);
3087            }
3088        }
3089        self.state.save()?;
3090        Ok(())
3091    }
3092
3093    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
3094    /// last landed the winner on, once it has run, else the commit the run
3095    /// branched from.
3096    ///
3097    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
3098    /// and `vote` all happen before there is a winner to rebase, so they
3099    /// compare every candidate against the branch point on purpose, and a
3100    /// base that moves after they are already done cannot change an answer
3101    /// they already gave.
3102    fn landing_base(&self) -> String {
3103        self.state
3104            .base_sync
3105            .as_ref()
3106            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
3107    }
3108
3109    // ------------------------------------------------------- operator fix
3110
3111    /// Route specific, already-recorded review findings to a fixer for a
3112    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
3113    /// entry point.
3114    ///
3115    /// Distinct from `review_loop`'s own fix step in three ways: it never
3116    /// runs a reviewer wave, it never spends review-round budget, and what
3117    /// happened is recorded as an [`OperatorFixRequest`] appended to
3118    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
3119    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
3120    /// and vote must never be rewritten to look like a manufactured blocking
3121    /// verdict.
3122    ///
3123    /// Only meaningful once review has actually concluded: `Ready` (handed
3124    /// off with findings still open, or simply concluded clean while minor
3125    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
3126    /// gate failed). Everything else is refused: a run still in progress
3127    /// should simply be resumed, and a `Merged` run's branch has already
3128    /// landed — reopening *this* run's own record cannot change that, so the
3129    /// answer there is a fresh `magi review <branch>`.
3130    ///
3131    /// A real commit here re-verifies through a fresh, ordinary review-only
3132    /// run on the same branch ([`Self::review`]) rather than reopening this
3133    /// run's own `review_loop`: once any round in this run's history went
3134    /// clean, `review_conclusion` treats that as permanent by design (the
3135    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
3136    /// way to force one more genuine reviewer wave out of *this* run without
3137    /// either rewriting history or weakening that guarantee for every other
3138    /// caller. A review-only run costs nothing extra — no implementation, no
3139    /// judging, no vote — and exercises the exact same review → verify →
3140    /// gate → (human) merge path, unmodified.
3141    pub async fn fix_selected(
3142        &mut self,
3143        ids: &[String],
3144        reason: &str,
3145        allow_stale: bool,
3146    ) -> Result<()> {
3147        let reason = reason.trim();
3148        if reason.is_empty() {
3149            bail!("a fix request needs a reason — that is the operator's own record of why");
3150        }
3151        if ids.is_empty() {
3152            bail!("no finding id given");
3153        }
3154        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
3155            bail!(
3156                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
3157                 has already concluded — can be given a targeted fix. A run still \
3158                 in progress should simply be resumed; a `merged` run's branch has \
3159                 already landed, so its answer is a fresh `magi review <branch>`, \
3160                 not reopening this run's own record",
3161                self.state.id,
3162                self.state.status.as_str()
3163            );
3164        }
3165        let Some(winner) = self.state.winner().cloned() else {
3166            bail!("run {} has no winning candidate to fix", self.state.id);
3167        };
3168        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
3169            bail!(
3170                "branch `{}` no longer exists; this run cannot be extended",
3171                winner.branch
3172            );
3173        }
3174        let home = crate::run::home();
3175        if crate::daemon::is_working_on(&home, &self.state.id, Timestamp::now()) {
3176            bail!(
3177                "run {} is currently being worked on by another magi process",
3178                self.state.id
3179            );
3180        }
3181        // Held for the rest of this call, including the follow-up review
3182        // below: two `magi fix` invocations against the same run must not
3183        // both reach the worktree manipulation further down, which would
3184        // otherwise race to remove and recreate the same directory — see
3185        // [`FixClaim`]'s own doc.
3186        let _claim = FixClaim::acquire(&self.state.dir())?;
3187
3188        // Resolve every id before spending anything — an unknown id refuses
3189        // the whole request rather than silently dropping it — and dedup
3190        // while keeping the operator's own order.
3191        let mut seen = BTreeSet::new();
3192        let mut findings = Vec::new();
3193        let mut missing = Vec::new();
3194        for id in ids {
3195            if !seen.insert(id.clone()) {
3196                continue;
3197            }
3198            match self.state.finding(id) {
3199                Some((round, rec, f)) => findings.push(OperatorFixFinding {
3200                    id: f.id.clone(),
3201                    severity: f.severity,
3202                    reviewer_vote: rec.vote,
3203                    round: round.round,
3204                    round_head: round.head.clone(),
3205                    reviewer: rec.reviewer,
3206                    agent: rec.agent.clone(),
3207                    file: f.file.clone(),
3208                    line: f.line,
3209                    title: f.title.clone(),
3210                    detail: f.detail.clone(),
3211                    outcome: OperatorFixOutcome::Pending,
3212                }),
3213                None => missing.push(id.clone()),
3214            }
3215        }
3216        if !missing.is_empty() {
3217            bail!(
3218                "unknown finding id(s): {}; nothing was changed",
3219                missing.join(", ")
3220            );
3221        }
3222
3223        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
3224        let stale_details: Vec<(String, String)> = findings
3225            .iter()
3226            .filter(|f| f.round_head != head_at_request)
3227            .map(|f| (f.id.clone(), f.round_head.clone()))
3228            .collect();
3229        let stale = !stale_details.is_empty();
3230        if stale && !allow_stale {
3231            bail!(
3232                "the branch has moved since some finding(s) were raised — {} — now \
3233                 at {}; pass --allow-stale to fix anyway, or re-run review first",
3234                stale_details
3235                    .iter()
3236                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
3237                    .collect::<Vec<_>>()
3238                    .join(", "),
3239                short(&head_at_request)
3240            );
3241        }
3242
3243        let request = OperatorFixRequest {
3244            requested_at: Timestamp::now(),
3245            reason: reason.to_owned(),
3246            findings,
3247            head_at_request: head_at_request.clone(),
3248            allow_stale,
3249            stale,
3250            fix: None,
3251            result_head: None,
3252            follow_up_review_run: None,
3253        };
3254        self.state.event(
3255            "fix",
3256            format!(
3257                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
3258                request.findings.len(),
3259                request
3260                    .findings
3261                    .iter()
3262                    .map(|f| f.id.as_str())
3263                    .collect::<Vec<_>>()
3264                    .join(", "),
3265            ),
3266        );
3267        // Recorded now, before any worktree work or the fixer call itself —
3268        // and re-saved at each checkpoint below: a crash at any point after
3269        // this (mid fixer call, mid follow-up review) must not lose the fact
3270        // that this was requested, for which findings, and why. Everything
3271        // past this point reads and writes through `request_index` rather
3272        // than a local variable, since `request` itself is moved here.
3273        self.state.operator_fixes.push(request);
3274        self.state.save()?;
3275        let request_index = self.state.operator_fixes.len() - 1;
3276
3277        // A fresh, dedicated worktree for this one call, never the winner's
3278        // own worktree in place: that one may already be gone (folded away),
3279        // and reusing it in place would leave the branch checked out there
3280        // when the follow-up review below tries to check it out again. Freed
3281        // immediately after, either way — but only once confirmed clean:
3282        // `worktree_remove` is a `git worktree remove --force`, which would
3283        // otherwise discard uncommitted work left there by the operator or
3284        // another process before this had a chance to even look at it.
3285        if winner.worktree.exists() {
3286            if !git::is_clean(&winner.worktree).await? {
3287                bail!(
3288                    "`{}` has uncommitted changes; refusing to touch it — commit or \
3289                     discard them first",
3290                    winner.worktree.display()
3291                );
3292            }
3293            git::worktree_remove(&self.state.repo, &winner.worktree)
3294                .await
3295                .ok();
3296        }
3297        let fix_worktree = self.state.worktree_root().join("operator-fix");
3298        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
3299        git::git(
3300            &self.state.repo,
3301            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
3302        )
3303        .await
3304        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
3305        if !git::is_clean(&fix_worktree).await? {
3306            git::worktree_remove(&self.state.repo, &fix_worktree)
3307                .await
3308                .ok();
3309            bail!(
3310                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
3311                winner.branch
3312            );
3313        }
3314
3315        let run_id = self.state.id.clone();
3316        let prompts = self.state.config.prompts.clone();
3317        let language = self.state.config.graph.language.clone();
3318        let sessions = self.state.config.graph.sessions;
3319        let artifacts = agent::artifacts_dir(&self.state.dir());
3320        let (fix_spec, fix_seat_key) = match &self.roles.fixer {
3321            Some(f) if f.id != winner.agent => (f.clone(), "fix".to_owned()),
3322            _ => (
3323                self.state
3324                    .config
3325                    .agent(&winner.agent)
3326                    .cloned()
3327                    .unwrap_or_else(|_| self.roles.implementers[winner.index].clone()),
3328                format!("impl-{}", winner.label),
3329            ),
3330        };
3331        let seat = self.seat(&fix_seat_key, &fix_spec.id);
3332        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
3333            .findings
3334            .iter()
3335            .map(|f| Finding {
3336                id: f.id.clone(),
3337                severity: f.severity,
3338                file: f.file.clone(),
3339                line: f.line,
3340                title: f.title.clone(),
3341                detail: f.detail.clone(),
3342            })
3343            .collect();
3344        let job = SeatJob {
3345            prompt: prompt::operator_fix(
3346                &self.state.instruction,
3347                &finding_list,
3348                reason,
3349                &stale_details,
3350                &head_at_request,
3351                &language,
3352            ),
3353            spec: fix_spec.clone(),
3354            seat,
3355            cwd: fix_worktree.clone(),
3356            timeout: Duration::from_secs(self.state.config.graph.timeout_fix),
3357            allow_write: true,
3358            sessions,
3359            artifacts: artifacts.clone(),
3360            stem: "operator-fix".to_owned(),
3361        };
3362        let cache = self.state.config.cache_dir();
3363        let ctx = WaveCtx {
3364            run: &run_id,
3365            node: "fix",
3366            prompts: &prompts,
3367            cache: cache.as_deref(),
3368            round: None,
3369        };
3370        let (seat, out) =
3371            run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3372        let agent_id = seat.agent.clone();
3373
3374        let mut fix = FixRecord {
3375            agent: agent_id,
3376            addressed: Vec::new(),
3377            rejected: Vec::new(),
3378            notes: String::new(),
3379            committed: false,
3380            failed: None,
3381            duration_ms: 0,
3382            continuation: None,
3383        };
3384        let mut final_seat = seat.clone();
3385        match out {
3386            AgentOutcome::Ok(o) => {
3387                fix.duration_ms = o.duration_ms;
3388                let parsed = verdict::extract_json::<FixReport>(&o.text);
3389                let incomplete_reason = match &parsed {
3390                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
3391                        "the reply parsed, but it reported a command whose own CLI \
3392                         never confirmed an exit status"
3393                            .to_owned(),
3394                    ),
3395                    Ok(_) => None,
3396                    Err(e) => Some(e.to_string()),
3397                };
3398                match incomplete_reason {
3399                    None => {
3400                        let report = parsed.expect("checked Ok above");
3401                        fix.addressed = report.addressed;
3402                        fix.rejected = report.rejected;
3403                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
3404                    }
3405                    Some(reason) => {
3406                        let (resumed_seat, resolved, failure, cont) = self
3407                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
3408                            .await;
3409                        fix.duration_ms += cont.cumulative_wait_ms;
3410                        fix.continuation = Some(cont);
3411                        final_seat = resumed_seat;
3412                        match resolved {
3413                            Some(report) => {
3414                                fix.addressed = report.addressed;
3415                                fix.rejected = report.rejected;
3416                                fix.notes =
3417                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
3418                            }
3419                            None => fix.failed = failure,
3420                        }
3421                    }
3422                }
3423            }
3424            AgentOutcome::Dropped(o) => {
3425                fix.duration_ms = o.duration_ms;
3426                let why = o
3427                    .dropped
3428                    .as_ref()
3429                    .map(|d| d.why.as_str())
3430                    .unwrap_or("the CLI ended the stream without delivering its answer");
3431                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
3432            }
3433            AgentOutcome::Quota(o) => {
3434                self.state.quota.push(QuotaLoss {
3435                    seat: final_seat.key.clone(),
3436                    node: "fix".to_owned(),
3437                    at: Timestamp::now(),
3438                    reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
3439                });
3440                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
3441            }
3442            AgentOutcome::Failed(e) => fix.failed = Some(e),
3443        }
3444        if fix.continuation.is_none() {
3445            fix.continuation = Some(ContinuationRecord::not_needed());
3446        }
3447        self.state.seats.insert(final_seat.key.clone(), final_seat);
3448
3449        git::commit_all(
3450            &fix_worktree,
3451            &format!(
3452                "magi: operator-selected fix ({}) (uncommitted work)",
3453                self.state.operator_fixes[request_index]
3454                    .findings
3455                    .iter()
3456                    .map(|f| f.id.as_str())
3457                    .collect::<Vec<_>>()
3458                    .join(", ")
3459            ),
3460        )
3461        .await
3462        .ok();
3463        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
3464        fix.committed = after != head_at_request;
3465        git::worktree_remove(&self.state.repo, &fix_worktree)
3466            .await
3467            .ok();
3468
3469        self.state.event(
3470            "fix",
3471            match &fix.failed {
3472                Some(reason) => format!(
3473                    "operator fix: adoption report was lost ({reason}); {}",
3474                    if fix.committed {
3475                        "committed"
3476                    } else {
3477                        "NO new commit"
3478                    }
3479                ),
3480                None => format!(
3481                    "operator fix: {} addressed, {} rejected, {}",
3482                    fix.addressed.len(),
3483                    fix.rejected.len(),
3484                    if fix.committed {
3485                        "committed"
3486                    } else {
3487                        "NO new commit"
3488                    }
3489                ),
3490            },
3491        );
3492
3493        // Every selected finding gets an outcome — never left `Pending` once
3494        // the fixer's own turn is over. A report that never came back at all
3495        // marks every one of them `Unreported`, not silently "not addressed":
3496        // quota, a dropped stream, or an exhausted continuation are gaps in
3497        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
3498        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
3499        for f in &mut self.state.operator_fixes[request_index].findings {
3500            f.outcome = if fix.failed.is_some() {
3501                OperatorFixOutcome::Unreported
3502            } else if fix.addressed.contains(&f.id) {
3503                OperatorFixOutcome::Addressed
3504            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
3505                OperatorFixOutcome::Rejected { why: r.why.clone() }
3506            } else {
3507                OperatorFixOutcome::Unreported
3508            };
3509        }
3510
3511        let committed = fix.committed;
3512        if committed {
3513            self.state.operator_fixes[request_index].result_head = Some(after.clone());
3514        }
3515        self.state.operator_fixes[request_index].fix = Some(fix);
3516        // Saved again now that the fixer's own outcome is final, on top of
3517        // the save right after the request was first pushed above.
3518        self.state.save()?;
3519
3520        if committed {
3521            self.state.event(
3522                "fix",
3523                format!(
3524                    "operator fix committed {}; opening a follow-up review-only run",
3525                    short(&after)
3526                ),
3527            );
3528            match Self::review(&self.state.repo, &winner.branch, self.state.config.clone()).await {
3529                Ok(mut follow_up) => {
3530                    follow_up.state.event(
3531                        "start",
3532                        format!(
3533                            "requested by an operator fix on run {} for finding(s) {}",
3534                            self.state.id,
3535                            self.state.operator_fixes[request_index]
3536                                .findings
3537                                .iter()
3538                                .map(|f| f.id.as_str())
3539                                .collect::<Vec<_>>()
3540                                .join(", "),
3541                        ),
3542                    );
3543                    follow_up.state.save()?;
3544                    let follow_up_id = follow_up.state.id.clone();
3545                    if let Err(e) = follow_up.execute().await {
3546                        self.state.event(
3547                            "fix",
3548                            format!(
3549                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
3550                            ),
3551                        );
3552                    }
3553                    self.state.operator_fixes[request_index].follow_up_review_run =
3554                        Some(follow_up_id);
3555                }
3556                Err(e) => {
3557                    self.state.event(
3558                        "fix",
3559                        format!("committed the fix but could not open a follow-up review: {e:#}"),
3560                    );
3561                }
3562            }
3563            self.state.save()?;
3564        }
3565
3566        Ok(())
3567    }
3568
3569    // --------------------------------------------------------------- review
3570
3571    async fn review_loop(&mut self) -> Result<()> {
3572        // A base that would not rebase is a person's decision, not a review
3573        // round: nothing here would change the answer, and reviewers and a
3574        // fixer would be spending real budget on a tree that cannot land
3575        // regardless of what they find.
3576        if self
3577            .state
3578            .base_sync
3579            .as_ref()
3580            .is_some_and(|s| s.conflict.is_some())
3581        {
3582            return Ok(());
3583        }
3584        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3585        // agent files with `magi task add` name the run that paid for it. The
3586        // prompt overlay is cloned alongside it because the waves borrow it
3587        // while `self` is mutably borrowed by the node's own bookkeeping.
3588        let run_id = self.state.id.clone();
3589        let prompts = self.state.config.prompts.clone();
3590        let Some(winner) = self.state.winner().cloned() else {
3591            return Ok(());
3592        };
3593        let max_rounds = self.state.config.graph.review_rounds;
3594        // A clean round, an exhausted round budget, or a stalled tree (see
3595        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
3596        // they are recorded — recomputed here, not read off `status`, so a
3597        // reentry into a run that already stopped restates the identical
3598        // verdict instead of silently handing back whatever an earlier node
3599        // in this same walk clobbered `status` to (a solo-candidate
3600        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
3601        // below runs an empty range once the budget is spent, and would
3602        // otherwise fall through without touching `status` at all.
3603        if let Some(status) = review_conclusion(&self.state.reviews, max_rounds) {
3604            self.state.status = status;
3605            self.state.save()?;
3606            return Ok(());
3607        }
3608        self.state.status = RunStatus::Reviewing;
3609        // A last recorded round whose own verification never resolved
3610        // (`ResourceBlocked` — the shared build cache, not the patch) is
3611        // never a concluded round, whatever the round budget says: starting
3612        // a fresh round on top of it would spend a whole new reviewer wave
3613        // re-reading an unchanged patch instead of just retrying the one
3614        // check that actually needs it, and once the budget is spent the
3615        // loop below has nothing left to do at all (its range is empty).
3616        // Retry that check directly instead, exactly the same retry
3617        // `stop_reviewing` already does for its own catch-up case.
3618        if self
3619            .state
3620            .reviews
3621            .last()
3622            .is_some_and(|r| r.e2e_status() == E2eStatus::ResourceBlocked)
3623        {
3624            let shell = self.state.config.shell();
3625            return self
3626                .stop_reviewing(
3627                    "the last round's own verification never resolved",
3628                    &shell,
3629                    &winner.worktree,
3630                )
3631                .await;
3632        }
3633
3634        let repo = self.state.repo.clone();
3635        let root = self.state.worktree_root();
3636        let language = self.state.config.graph.language.clone();
3637        let sessions = self.state.config.graph.sessions;
3638        let artifacts = agent::artifacts_dir(&self.state.dir());
3639        let base = self.landing_base();
3640        let base_short = short(&base);
3641        let reviewers = self.roles.reviewers.clone();
3642        let shell = self.state.config.shell();
3643
3644        for round in (self.state.reviews.len() + 1)..=max_rounds {
3645            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3646            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
3647            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
3648            // The prior round's own record, already persisted — never a
3649            // hand-carried variable of just its failing output: that is
3650            // exactly what let a round's e2e result drift out of sync with
3651            // which commit it was actually about (see `SCHEMA`'s doc for
3652            // schema 8). Judged against `head`, the commit reviewers are
3653            // about to look at now, so the summary always reads as "an
3654            // earlier head" here — this round's own patch has not been
3655            // checked yet.
3656            let prev_verification = self
3657                .state
3658                .reviews
3659                .last()
3660                .and_then(|r| r.verification_summary(&head));
3661
3662            // Each reviewer gets its own detached checkout of exactly this
3663            // commit: nobody can perturb the winner's tree, and the fixer can
3664            // keep working without racing a reviewer.
3665            let mut jobs = Vec::new();
3666            for (r, spec) in reviewers.iter().cloned().enumerate() {
3667                let wt = root.join(format!("review-{}", r + 1));
3668                if wt.exists() {
3669                    git::reset_detached(&wt, &head).await?;
3670                } else {
3671                    git::worktree_add_detached(&repo, &wt, &head).await?;
3672                }
3673                let seat_key = format!("review-{}", r + 1);
3674                let seat = self.seat(&seat_key, &spec.id);
3675                jobs.push(SeatJob {
3676                    prompt: prompt::review(&prompt::ReviewCtx {
3677                        instruction: &self.state.instruction,
3678                        branch: &winner.branch,
3679                        base_short: &base_short,
3680                        stat: &stat,
3681                        patch: &patch,
3682                        verification: prev_verification.as_ref(),
3683                        reviewers: reviewers.len(),
3684                        round,
3685                        rounds: max_rounds,
3686                        // A review-only run has no rankings, so nothing
3687                        // competed for this patch and the reviewer is told so.
3688                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
3689                        lens: Lens::for_seat(r),
3690                        language: &language,
3691                    }),
3692                    spec,
3693                    seat,
3694                    cwd: wt,
3695                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
3696                    allow_write: false,
3697                    sessions,
3698                    artifacts: artifacts.clone(),
3699                    stem: format!("review-{round}-{}", r + 1),
3700                });
3701            }
3702
3703            self.state.event(
3704                "review",
3705                format!(
3706                    "round {round}: {} reviewers on {}",
3707                    jobs.len(),
3708                    short(&head)
3709                ),
3710            );
3711            let mut quota_losses = Vec::new();
3712            let review_retries = self.state.config.graph.retries;
3713            let review_cache = self.state.config.cache_dir();
3714            let ctx = WaveCtx {
3715                run: &run_id,
3716                node: "review",
3717                prompts: &prompts,
3718                cache: review_cache.as_deref(),
3719                round: Some(round),
3720            };
3721            let results = ask_json_wave::<Review>(
3722                jobs,
3723                Arc::clone(&self.sem),
3724                review_retries,
3725                &ctx,
3726                &mut quota_losses,
3727                &mut self.state,
3728                &|_: &Review| Ok(()),
3729            )
3730            .await;
3731            // Counted before the move below: how many of *this* round's
3732            // reviewer seats were lost to their own rate limit, as opposed to
3733            // a crash, a timeout, or unparsable output — see `round_is_clean`.
3734            let round_quota_missing = quota_losses.len();
3735            self.state.quota.extend(quota_losses);
3736
3737            let mut records = Vec::new();
3738            let mut all_findings = Vec::new();
3739            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
3740                let agent_id = seat.agent.clone();
3741                self.state.seats.insert(seat.key.clone(), seat);
3742                let mut record = ReviewRecord {
3743                    reviewer: r + 1,
3744                    agent: agent_id,
3745                    summary: String::new(),
3746                    findings: Vec::new(),
3747                    vote: None,
3748                    failed: None,
3749                    duration_ms: 0,
3750                    // Set for both outcomes: `failed: Some(_)` with
3751                    // `attempts > 0` is a seat every retry still lost, not a
3752                    // recovered one — only `failed: None` with `attempts > 0`
3753                    // reads as "answered after a nudge" (see this field's own
3754                    // doc).
3755                    attempts,
3756                };
3757                match res {
3758                    Ok((review, out)) => {
3759                        // Sanitized here, at the point every other piece of
3760                        // agent prose in this file is (candidate summaries,
3761                        // deliberation turns, vote reasons): a reviewer's own
3762                        // words are the one thing about it that could name
3763                        // it, and reconsideration below broadcasts this same
3764                        // summary and these same findings to every other
3765                        // seat on the panel.
3766                        record.summary =
3767                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
3768                        record.vote = Some(review.vote);
3769                        record.duration_ms = out.duration_ms;
3770                        for (n, mut f) in review.findings.into_iter().enumerate() {
3771                            // ids are magi's, never the agent's: the fixer's
3772                            // adoption report is keyed by them.
3773                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
3774                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
3775                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
3776                            // `file` is agent-supplied prose too, never
3777                            // checked against the real tree — the same
3778                            // exposure `title`/`detail` above have, just in
3779                            // a field easy to forget because it looks like a
3780                            // path rather than free text.
3781                            f.file = f
3782                                .file
3783                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
3784                            all_findings.push(f.clone());
3785                            record.findings.push(f);
3786                        }
3787                        self.state.event(
3788                            "review",
3789                            format!(
3790                                "round {round}: reviewer {} voted {} with {} finding(s)",
3791                                r + 1,
3792                                review.vote.label(),
3793                                record.findings.len()
3794                            ),
3795                        );
3796                    }
3797                    Err(e) => {
3798                        record.failed = Some(e.to_string());
3799                        self.state.event(
3800                            "review",
3801                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
3802                        );
3803                    }
3804                }
3805                records.push(record);
3806            }
3807
3808            // Tally the round's votes and, if they split, spend the one
3809            // round of reconsideration the split -> deliberate -> revote
3810            // shape `judge`/`vote` use for the panel, sized down to what a
3811            // read-only review round can afford: one round, and a revote
3812            // rather than an argument, because the panel already wrote its
3813            // reasoning down as findings the first time around.
3814            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
3815            let vote_split =
3816                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
3817            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
3818            if vote_split {
3819                self.state.event(
3820                    "review",
3821                    format!(
3822                        "round {round}: votes split ({}) — one round of reconsideration",
3823                        initial_votes
3824                            .iter()
3825                            .map(|v| v.label())
3826                            .collect::<Vec<_>>()
3827                            .join(", ")
3828                    ),
3829                );
3830                // Seats read every seat's findings and votes, still numbered
3831                // and never named — the same anonymity `review` itself keeps.
3832                let panel: Vec<ReviewSeatReport<'_>> = records
3833                    .iter()
3834                    .filter_map(|r| {
3835                        r.vote.map(|vote| ReviewSeatReport {
3836                            reviewer: r.reviewer,
3837                            vote,
3838                            summary: &r.summary,
3839                            findings: &r.findings,
3840                        })
3841                    })
3842                    .collect();
3843
3844                let mut jobs = Vec::new();
3845                let mut seats_at = Vec::new();
3846                for (r, spec) in reviewers.iter().cloned().enumerate() {
3847                    // A seat with no initial vote has nothing to reconsider
3848                    // from and stays absent, the same as it stayed absent
3849                    // from `panel` above.
3850                    if records[r].vote.is_none() {
3851                        continue;
3852                    }
3853                    let wt = root.join(format!("review-{}", r + 1));
3854                    let seat_key = format!("review-{}", r + 1);
3855                    let seat = self.seat(&seat_key, &spec.id);
3856                    // A seat with no live session has already forgotten the
3857                    // initial review's prompt — restate the patch it is
3858                    // voting on, the same as `deliberate`/`vote` do for a
3859                    // judge in the same position.
3860                    let patch_ctx = if has_context(&spec, &seat, sessions) {
3861                        None
3862                    } else {
3863                        Some(ReviewPatch {
3864                            branch: &winner.branch,
3865                            base_short: &base_short,
3866                            stat: &stat,
3867                            patch: &patch,
3868                        })
3869                    };
3870                    let prompt = prompt::review_reconsider(&ReviewReconsiderCtx {
3871                        instruction: &self.state.instruction,
3872                        reviewer: r + 1,
3873                        lens: Lens::for_seat(r),
3874                        panel: &panel,
3875                        patch: patch_ctx,
3876                        round,
3877                        rounds: max_rounds,
3878                        language: &language,
3879                    });
3880                    jobs.push(SeatJob {
3881                        prompt,
3882                        spec,
3883                        seat,
3884                        cwd: wt,
3885                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
3886                        allow_write: false,
3887                        sessions,
3888                        artifacts: artifacts.clone(),
3889                        stem: format!("review-{round}-reconsider-{}", r + 1),
3890                    });
3891                    seats_at.push(r);
3892                }
3893
3894                let mut recon_quota_losses = Vec::new();
3895                let recon_cache = self.state.config.cache_dir();
3896                let recon_ctx = WaveCtx {
3897                    run: &run_id,
3898                    node: "review",
3899                    prompts: &prompts,
3900                    cache: recon_cache.as_deref(),
3901                    round: Some(round),
3902                };
3903                let recon_results = ask_json_wave::<ReviewRevote>(
3904                    jobs,
3905                    Arc::clone(&self.sem),
3906                    review_retries,
3907                    &recon_ctx,
3908                    &mut recon_quota_losses,
3909                    &mut self.state,
3910                    &|_: &ReviewRevote| Ok(()),
3911                )
3912                .await;
3913                self.state.quota.extend(recon_quota_losses);
3914
3915                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
3916                    let agent_id = seat.agent.clone();
3917                    self.state.seats.insert(seat.key.clone(), seat);
3918                    let mut rec = ReviewRevoteRecord {
3919                        reviewer: r + 1,
3920                        agent: agent_id,
3921                        vote: None,
3922                        reason: String::new(),
3923                        failed: None,
3924                    };
3925                    match res {
3926                        Ok((rv, _)) => {
3927                            rec.vote = Some(rv.vote);
3928                            rec.reason =
3929                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
3930                            self.state.event(
3931                                "review",
3932                                format!(
3933                                    "round {round}: reviewer {} revoted {}",
3934                                    r + 1,
3935                                    rv.vote.label()
3936                                ),
3937                            );
3938                        }
3939                        Err(e) => {
3940                            rec.failed = Some(e.to_string());
3941                            self.state.event(
3942                                "review",
3943                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
3944                            );
3945                        }
3946                    }
3947                    reconsideration.push(rec);
3948                }
3949            } else if initial_votes.len() > 1 {
3950                self.state.event(
3951                    "review",
3952                    format!(
3953                        "round {round}: votes agreed ({}) — no reconsideration",
3954                        initial_votes[0].label()
3955                    ),
3956                );
3957            }
3958
3959            // The final vote per seat is its revote where reconsideration
3960            // ran and answered, its initial vote otherwise — the same
3961            // fallback `tally` uses for a judge whose private vote failed.
3962            let final_votes: Vec<ReviewVote> = records
3963                .iter()
3964                .filter_map(|r| {
3965                    reconsideration
3966                        .iter()
3967                        .find(|rv| rv.reviewer == r.reviewer)
3968                        .and_then(|rv| rv.vote)
3969                        .or(r.vote)
3970                })
3971                .collect();
3972            let round_verdict = ReviewVote::worst(final_votes);
3973
3974            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
3975            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
3976            // A round that already has a blocking finding and a round left to
3977            // try is going back to the fixer no matter what `verify.e2e`
3978            // says, so running it first only spends the loop's slowest step
3979            // (minutes, for a Rust repo's full test suite) on a head about
3980            // to be rewritten. Deferred, never skipped: `verify.e2e` still
3981            // runs once a round has no blocking findings left (see
3982            // `round_is_clean`, which a deferred — empty — `e2e` can never
3983            // satisfy since `blocking` is nonzero whenever this branch is
3984            // taken), and `stop_reviewing` forces a real run before it will
3985            // ever read a deferred round as green.
3986            let defer_e2e =
3987                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
3988            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
3989                let reason =
3990                    format!("{blocking} blocking finding(s) already required a fix this round");
3991                self.state.event(
3992                    "verify",
3993                    format!(
3994                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
3995                         {}); it will run once a round has none left",
3996                        short(&head)
3997                    ),
3998                );
3999                (Vec::new(), false, true, Some(reason))
4000            } else {
4001                let e2e_commands = self.state.config.verify.e2e.clone();
4002                let cache_dir = self.state.config.cache_dir();
4003                let context = format!("round {round}");
4004                let (e2e, verify_retried) = with_cache_lease(
4005                    &mut self.state,
4006                    cache_dir.as_deref(),
4007                    "e2e",
4008                    "e2e",
4009                    &winner.worktree,
4010                    &head,
4011                    verify_timeout,
4012                    &context,
4013                    |state, budget| {
4014                        let shell = shell.clone();
4015                        let e2e_commands = e2e_commands.clone();
4016                        let worktree = winner.worktree.clone();
4017                        let context = context.clone();
4018                        async move {
4019                            run_e2e_with_retry(
4020                                state,
4021                                &shell,
4022                                &e2e_commands,
4023                                &worktree,
4024                                budget,
4025                                &context,
4026                            )
4027                            .await
4028                        }
4029                    },
4030                )
4031                .await;
4032                (e2e, verify_retried, false, None)
4033            };
4034
4035            let expected = records.len();
4036            let answered = records.iter().filter(|r| r.failed.is_none()).count();
4037            let incomplete = answered < expected;
4038            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
4039            let policy = self.state.config.graph.incomplete_review;
4040            let clean = round_is_clean(
4041                blocking,
4042                e2e_ok,
4043                answered,
4044                expected,
4045                round_quota_missing,
4046                policy,
4047            );
4048
4049            let mut round_record = ReviewRound {
4050                round,
4051                head: head.clone(),
4052                verified_head: None,
4053                verified_at: None,
4054                reviews: records,
4055                e2e,
4056                verify_retried,
4057                e2e_deferred,
4058                e2e_defer_reason,
4059                fix: None,
4060                blocking,
4061                answered,
4062                expected,
4063                clean,
4064                progressed: false,
4065                vote_split,
4066                reconsideration,
4067                verdict: round_verdict,
4068            };
4069            // Which commit and when magi actually attempted to check —
4070            // known the moment a command was dispatched against `head`,
4071            // whether or not it finished: a resource-blocked attempt still
4072            // targeted a specific commit at a specific time, and leaving
4073            // that unrecorded is exactly what made `verification_summary`
4074            // report a fresh attempt as "commit unknown ... recorded before
4075            // this was tracked", indistinguishable from a genuinely old,
4076            // untracked record. Only a deferred or unconfigured round never
4077            // ran at all and has nothing to record — see
4078            // `ReviewRound::verified_head`'s own doc.
4079            if !matches!(
4080                round_record.e2e_status(),
4081                E2eStatus::Deferred | E2eStatus::NotConfigured
4082            ) {
4083                round_record.verified_head = Some(head.clone());
4084                round_record.verified_at = Some(Timestamp::now());
4085            }
4086            let this_round_verification = round_record.verification_summary(&head);
4087
4088            if incomplete {
4089                let missing: Vec<String> = round_record
4090                    .reviews
4091                    .iter()
4092                    .filter(|r| r.failed.is_some())
4093                    .map(|r| format!("review-{}", r.reviewer))
4094                    .collect();
4095                self.state.event(
4096                    "review",
4097                    format!(
4098                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
4099                        missing.join(", ")
4100                    ),
4101                );
4102            }
4103
4104            if clean {
4105                self.state.event(
4106                    "review",
4107                    if incomplete && policy == IncompleteReviewPolicy::Warn {
4108                        format!(
4109                            "round {round}: clean (warn policy, incomplete panel) — no \
4110                             blocking findings from the seats that answered, verification green"
4111                        )
4112                    } else if incomplete {
4113                        format!(
4114                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
4115                             quorum) — no blocking findings from the seats that answered, \
4116                             verification green",
4117                            expected - answered
4118                        )
4119                    } else {
4120                        format!("round {round}: clean — no blocking findings, verification green")
4121                    },
4122                );
4123                self.state.reviews.push(round_record);
4124                self.state.status = RunStatus::Gating;
4125                self.state.save()?;
4126                return Ok(());
4127            }
4128
4129            // Nothing was raised and verification passed, but not every seat
4130            // answered and `round_is_clean` still refused to call it clean —
4131            // either a seat is missing for a reason other than its own quota
4132            // (a crash, a timeout, unparsable output — worth another try), or
4133            // every seat that could have answered lost its quota and nobody
4134            // is left to decide on: re-review rather than send the fixer
4135            // after a round with nothing to fix.
4136            if incomplete && blocking == 0 && e2e_ok {
4137                self.state.reviews.push(round_record);
4138                self.state.save()?;
4139                if round == max_rounds {
4140                    self.state.status = RunStatus::Blocked;
4141                    self.state.event(
4142                        "review",
4143                        format!(
4144                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
4145                             refusing to call it clean",
4146                            expected - answered
4147                        ),
4148                    );
4149                    return Ok(());
4150                }
4151                continue;
4152            }
4153
4154            // Nothing for the fixer to act on (`blocking == 0`) and the only
4155            // reason this round is not clean is that magi itself never got
4156            // a command to run — the shared build cache, not the patch (see
4157            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
4158            // the fixer would invite a change to appease contention that has
4159            // nothing to do with the diff, and would leave this attempt
4160            // sitting in the next round's prompt as if it were about an
4161            // earlier, superseded commit rather than what it actually is:
4162            // the same head, still waiting to be checked. Wait for it the
4163            // same way the final round's own contention is already handled,
4164            // whatever round this happens to be.
4165            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
4166                self.state.reviews.push(round_record);
4167                return self
4168                    .stop_reviewing(
4169                        "the round's own verification could not run",
4170                        &shell,
4171                        &winner.worktree,
4172                    )
4173                    .await;
4174            }
4175
4176            if round == max_rounds {
4177                self.state.reviews.push(round_record);
4178                return self
4179                    .stop_reviewing(
4180                        &format!(
4181                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
4182                        ),
4183                        &shell,
4184                        &winner.worktree,
4185                    )
4186                    .await;
4187            }
4188
4189            // Fix. The winner's own implementer seat continues its conversation:
4190            // the competition is over, so context is pure benefit now.
4191            let (fix_spec, fix_seat_key) = match &self.roles.fixer {
4192                Some(f) if f.id != winner.agent => (f.clone(), "fix".to_owned()),
4193                _ => (
4194                    self.state
4195                        .config
4196                        .agent(&winner.agent)
4197                        .cloned()
4198                        .unwrap_or_else(|_| self.roles.implementers[winner.index].clone()),
4199                    format!("impl-{}", winner.label),
4200                ),
4201            };
4202            let seat = self.seat(&fix_seat_key, &fix_spec.id);
4203            let blocking_findings: Vec<_> = all_findings
4204                .iter()
4205                .filter(|f| f.severity.blocks())
4206                .cloned()
4207                .collect();
4208            let job = SeatJob {
4209                prompt: prompt::fix(
4210                    &self.state.instruction,
4211                    &blocking_findings,
4212                    this_round_verification.as_ref(),
4213                    round,
4214                    max_rounds,
4215                    &language,
4216                ),
4217                spec: fix_spec.clone(),
4218                seat,
4219                cwd: winner.worktree.clone(),
4220                timeout: Duration::from_secs(self.state.config.graph.timeout_fix),
4221                allow_write: true,
4222                sessions,
4223                artifacts: artifacts.clone(),
4224                stem: format!("fix-{round}"),
4225            };
4226            let before = git::rev_parse(&winner.worktree, "HEAD").await?;
4227            let cache = self.state.config.cache_dir();
4228            let ctx = WaveCtx {
4229                run: &run_id,
4230                node: "fix",
4231                prompts: &prompts,
4232                cache: cache.as_deref(),
4233                round: Some(round),
4234            };
4235            let (seat, out) =
4236                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
4237            let agent_id = seat.agent.clone();
4238
4239            let mut fix = FixRecord {
4240                agent: agent_id,
4241                addressed: Vec::new(),
4242                rejected: Vec::new(),
4243                notes: String::new(),
4244                committed: false,
4245                failed: None,
4246                duration_ms: 0,
4247                continuation: None,
4248            };
4249            let mut continuation = ContinuationRecord::not_needed();
4250            let mut final_seat = seat.clone();
4251            match out {
4252                AgentOutcome::Ok(o) => {
4253                    fix.duration_ms = o.duration_ms;
4254                    let parsed = verdict::extract_json::<FixReport>(&o.text);
4255                    // A parsed report standing next to a command this same
4256                    // reply's own CLI never confirmed the exit status of is
4257                    // not a resolved answer — the identical `CommandEvidence`
4258                    // `state.jobs` renders, read here instead of only on
4259                    // display, per the completion judgment and the shown
4260                    // record needing to agree.
4261                    let incomplete_reason = match &parsed {
4262                        Ok(_) if has_unconfirmed_command(&o.commands) => Some(
4263                            "the reply parsed, but it reported a command whose own CLI never \
4264                             confirmed an exit status"
4265                                .to_owned(),
4266                        ),
4267                        Ok(_) => None,
4268                        Err(e) => Some(e.to_string()),
4269                    };
4270                    match incomplete_reason {
4271                        None => {
4272                            let report = parsed.expect("checked Ok above");
4273                            fix.addressed = report.addressed;
4274                            fix.rejected = report.rejected;
4275                            fix.notes =
4276                                blind::sanitize_prose(&report.notes, &self.state.config.blind);
4277                        }
4278                        Some(reason) => {
4279                            let (resumed_seat, resolved, failure, cont) = self
4280                                .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
4281                                .await;
4282                            fix.duration_ms += cont.cumulative_wait_ms;
4283                            continuation = cont;
4284                            final_seat = resumed_seat;
4285                            match resolved {
4286                                Some(report) => {
4287                                    fix.addressed = report.addressed;
4288                                    fix.rejected = report.rejected;
4289                                    fix.notes = blind::sanitize_prose(
4290                                        &report.notes,
4291                                        &self.state.config.blind,
4292                                    );
4293                                }
4294                                None => fix.failed = failure,
4295                            }
4296                        }
4297                    }
4298                }
4299                // The CLI's raw error JSON is not a fix report to parse.
4300                AgentOutcome::Dropped(o) => {
4301                    fix.duration_ms = o.duration_ms;
4302                    let why = o
4303                        .dropped
4304                        .as_ref()
4305                        .map(|d| d.why.as_str())
4306                        .unwrap_or("the CLI ended the stream without delivering its answer");
4307                    fix.failed = Some(format!("the CLI dropped the stream ({why})"));
4308                }
4309                AgentOutcome::Quota(o) => {
4310                    self.state.quota.push(QuotaLoss {
4311                        seat: final_seat.key.clone(),
4312                        node: "fix".to_owned(),
4313                        at: Timestamp::now(),
4314                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
4315                    });
4316                    fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
4317                }
4318                AgentOutcome::Failed(e) => fix.failed = Some(e),
4319            }
4320            fix.continuation = Some(continuation);
4321            self.state.seats.insert(final_seat.key.clone(), final_seat);
4322            git::commit_all(
4323                &winner.worktree,
4324                &format!("magi: review round {round} fixes (uncommitted work)"),
4325            )
4326            .await
4327            .ok();
4328            let after = git::rev_parse(&winner.worktree, "HEAD").await?;
4329            fix.committed = after != before;
4330            // Judged by what `git` says moved against base, never by the
4331            // fixer's own `addressed`/`rejected` count — see
4332            // `ReviewRound::progressed`. Propagated with `?`, the same as the
4333            // `patch` snapshot above: swallowing this error would default
4334            // `diff_after` to empty, which almost always differs from a
4335            // non-empty `patch` and reads as "progressed" — exactly backwards
4336            // for a `git` failure the stagnation check cannot see through.
4337            let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
4338            let progressed = diff_after != patch;
4339            let commit_note = if fix.committed {
4340                "committed"
4341            } else {
4342                "NO new commit"
4343            };
4344            let tree_note = if progressed {
4345                "changed vs base"
4346            } else {
4347                "unchanged vs base"
4348            };
4349            self.state.event(
4350                "fix",
4351                match &fix.failed {
4352                    // Distinct on purpose from "0 addressed, 0 rejected": the
4353                    // fixer's own diff still landed (blocking counts do keep
4354                    // falling round over round), only its adoption report did
4355                    // not come back, so this must never read like every
4356                    // finding was reviewed and declined.
4357                    Some(reason) => {
4358                        format!(
4359                            "round {round}: fixer's adoption report was lost ({reason}); \
4360                             {commit_note}, tree {tree_note}"
4361                        )
4362                    }
4363                    None => format!(
4364                        "round {round}: {} addressed, {} rejected, {commit_note}, tree \
4365                         {tree_note}{}",
4366                        fix.addressed.len(),
4367                        fix.rejected.len(),
4368                        if continuation.outcome == ContinuationOutcome::Resumed {
4369                            format!(
4370                                " (adoption report recovered after {} continuation(s))",
4371                                continuation.attempts
4372                            )
4373                        } else {
4374                            String::new()
4375                        },
4376                    ),
4377                },
4378            );
4379            round_record.fix = Some(fix);
4380            round_record.progressed = progressed;
4381            self.state.reviews.push(round_record);
4382            self.state.save()?;
4383
4384            // The fixer's own report never came back this round, even after
4385            // `continue_fix_report`'s own budget was spent on it — not an
4386            // ordinary "no report" (dropped stream, quota, plain failure),
4387            // which already reads that way and is left to the existing round
4388            // budget. Stopping here, rather than opening another round, is
4389            // what keeps a next reviewer/fixer wave from ever being
4390            // dispatched onto `winner.worktree` while whatever the seat's
4391            // last call may still have running there is unaccounted for: no
4392            // process liveness check exists (and none is being added — see
4393            // AGENTS.md/this task's own scope), so the only way to honour
4394            // "nothing starts before a valid report returns" is to not start
4395            // anything further on this worktree from this run at all.
4396            if matches!(
4397                continuation.outcome,
4398                ContinuationOutcome::Exhausted
4399                    | ContinuationOutcome::QuotaLost
4400                    | ContinuationOutcome::NoSession
4401            ) {
4402                return self
4403                    .stop_reviewing(
4404                        "the fixer's adoption report never came back, even after resuming its \
4405                         own seat; refusing to start another round against the same worktree \
4406                         while that is unresolved",
4407                        &shell,
4408                        &winner.worktree,
4409                    )
4410                    .await;
4411            }
4412
4413            let streak = self
4414                .state
4415                .reviews
4416                .iter()
4417                .rev()
4418                .take_while(|r| !r.progressed)
4419                .count();
4420            if streak >= STAGNANT_LIMIT {
4421                return self
4422                    .stop_reviewing(
4423                        &format!(
4424                            "the tree has not moved against base for {streak} round(s) in a row"
4425                        ),
4426                        &shell,
4427                        &winner.worktree,
4428                    )
4429                    .await;
4430            }
4431        }
4432        Ok(())
4433    }
4434
4435    /// Decide, from the last recorded round's own verification, whether
4436    /// stopping the review loop is a hand-off or a genuine block.
4437    ///
4438    /// Called once the loop has given up trying — the round budget is spent,
4439    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
4440    /// findings still open, never while a round is still clean or the
4441    /// incomplete-panel case handled inline above. Gate and e2e are facts
4442    /// about the tree; a lingering review finding is an opinion, and this
4443    /// workload's own `magi stats` puts reviewer precision low enough
4444    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
4445    /// must not by itself stand between a green, verified change and the
4446    /// human who decides what to do with it. A red e2e is not an opinion, so
4447    /// that case still blocks, with the failing command and a tail of its
4448    /// output recorded here rather than left in `run.json` for someone to go
4449    /// find.
4450    ///
4451    /// A round that deferred its own e2e (see [`Config::graph`]'s
4452    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
4453    /// only because nothing ran, and treating an empty list as a passing one
4454    /// here is exactly the "deferred painted green" bug this function exists
4455    /// to not have. When the last round's own verification never resolved —
4456    /// deferred on purpose, or a real attempt the shared build cache blocked
4457    /// — this makes (or retries) the real run, on the actual worktree this
4458    /// loop is about to stop touching, before deciding anything. A
4459    /// resource-blocked attempt is likewise never read as either green or
4460    /// red: it is evidence about the machine, not the patch (see
4461    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
4462    /// blocked cache leaves this call without deciding rather than guessing
4463    /// — the caller retries on a later reentry.
4464    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
4465        let round_idx = self.state.reviews.len() - 1;
4466        // A deferred round and a resource-blocked one are the same shape
4467        // here: neither has a real result yet, and both get one more
4468        // attempt. Read off `e2e_status` — the single source for this —
4469        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
4470        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
4471        // still retries instead of being read as a settled result the
4472        // instant it stops being empty.
4473        let needs_catchup_run = matches!(
4474            self.state.reviews[round_idx].e2e_status(),
4475            E2eStatus::Deferred | E2eStatus::ResourceBlocked
4476        );
4477        if needs_catchup_run {
4478            let round = self.state.reviews[round_idx].round;
4479            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
4480            let commands = self.state.config.verify.e2e.clone();
4481            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
4482            let cache_dir = self.state.config.cache_dir();
4483            let context = format!(
4484                "round {round}: verification unresolved, catching up before the final decision"
4485            );
4486            let (outcomes, verify_retried) = with_cache_lease(
4487                &mut self.state,
4488                cache_dir.as_deref(),
4489                "e2e",
4490                "e2e",
4491                worktree,
4492                &attempted_head,
4493                timeout,
4494                &context,
4495                |state, budget| {
4496                    let shell = shell.to_vec();
4497                    let commands = commands.clone();
4498                    let context = context.clone();
4499                    async move {
4500                        run_e2e_with_retry(state, &shell, &commands, worktree, budget, &context)
4501                            .await
4502                    }
4503                },
4504            )
4505            .await;
4506            let last = &mut self.state.reviews[round_idx];
4507            last.e2e = outcomes;
4508            last.verify_retried = verify_retried;
4509            // Always the commit and time this attempt actually targeted,
4510            // whether or not it happens to equal the reviewed `head` and
4511            // whether or not a command finished — see
4512            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
4513            // attempt is recorded too, so a later reader sees "attempted
4514            // again at T2" rather than silence.
4515            last.verified_head = Some(attempted_head);
4516            last.verified_at = Some(Timestamp::now());
4517            if verify_inconclusive(&last.e2e) {
4518                // Still not a real result: `e2e_deferred` is left exactly
4519                // as it was, so `needs_catchup_run` above reads
4520                // `ResourceBlocked` (via `e2e_status`, which checks
4521                // `resource_blocked` before `e2e_deferred`) and retries
4522                // again on the next reentry, rather than recording
4523                // contention as a red e2e and blocking the run on it.
4524                self.state.save()?;
4525                return Ok(());
4526            }
4527            last.e2e_deferred = false;
4528        }
4529        let last = &self.state.reviews[round_idx];
4530        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
4531
4532        match last.e2e_status() {
4533            E2eStatus::Failed => {
4534                let red: Vec<String> = last
4535                    .e2e
4536                    .iter()
4537                    .filter(|o| !o.ok())
4538                    .map(|o| {
4539                        format!(
4540                            "`{}` -> {:?}\n{}",
4541                            o.command,
4542                            o.code,
4543                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
4544                        )
4545                    })
4546                    .collect();
4547                self.state
4548                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
4549                self.state.status = RunStatus::Blocked;
4550            }
4551            // `needs_catchup_run` above already retried once this call; if
4552            // it is still blocked, this is magi's own admission it could
4553            // not get a command to run, never a verdict on the patch — the
4554            // run is left exactly where a later reentry can retry again.
4555            E2eStatus::ResourceBlocked => {
4556                self.state.event(
4557                    "review",
4558                    format!(
4559                        "{why}; e2e could not run (shared build cache unavailable); not \
4560                         deciding yet"
4561                    ),
4562                );
4563            }
4564            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
4565                self.state.event(
4566                    "review",
4567                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
4568                );
4569                self.state.status = RunStatus::Gating;
4570            }
4571        }
4572        self.state.save()?;
4573        Ok(())
4574    }
4575
4576    // ----------------------------------------------------------------- gate
4577
4578    async fn gate(&mut self) -> Result<()> {
4579        // Judged by the review record itself, not by `status`: a solo
4580        // candidate's `judge`/`deliberate` skip rewrites `status` on every
4581        // reentry (see `judge`), and trusting it here is exactly how a run
4582        // that exhausted its review budget got gated and merged a second
4583        // time around. `review_conclusion` recomputes the review loop's own
4584        // verdict from the round records themselves — `Gating` for a clean
4585        // round or a hand-off (see `stop_reviewing`), anything else means the
4586        // loop is still going or genuinely blocked.
4587        // A base the winner could not be replayed onto is a decision, not a
4588        // round: there is no landing tree to gate. Read as its own record for
4589        // the same reason the review verdict is.
4590        if self.state.status == RunStatus::Failed
4591            || self
4592                .state
4593                .base_sync
4594                .as_ref()
4595                .is_some_and(|s| s.conflict.is_some())
4596            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
4597                != Some(RunStatus::Gating)
4598        {
4599            return Ok(());
4600        }
4601        if self.state.gate_ran {
4602            // `review_loop` derives its conclusion from the clean review
4603            // record on every reentry and therefore puts a completed run back
4604            // in `Gating`. A recorded gate is a stronger, terminal fact:
4605            // retain its original command output (or lack of any, for a repo
4606            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
4607            // doc) and restore `Blocked` on a real failure rather than
4608            // pretending the command is still running or running it a second
4609            // time. `gate_ran == false` remains the only shape — unattempted,
4610            // or a resource-blocked retry — that may still need to execute a
4611            // command.
4612            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
4613                self.state.status = RunStatus::Blocked;
4614                self.state.save()?;
4615            }
4616            return Ok(());
4617        }
4618        let Some(winner) = self.state.winner().cloned() else {
4619            return Ok(());
4620        };
4621        self.state.status = RunStatus::Gating;
4622        let shell = self.state.config.shell();
4623        let gate_commands = self.state.config.verify.gate.clone();
4624        // Zero commands has nothing to run and nothing that could touch the
4625        // shared build cache, so it never needs a lease: `Config::cache_dir`
4626        // is derived from `verify.e2e` too, so a repo with no `verify.gate`
4627        // commands but a `CARGO_TARGET_DIR`-using `verify.e2e` would
4628        // otherwise queue behind an unrelated run's lease and come back
4629        // resource-blocked - `gate_ran` would stay false on nothing but
4630        // cache contention, for a step that had nothing to check in the
4631        // first place.
4632        let outcomes = if gate_commands.is_empty() {
4633            Vec::new()
4634        } else {
4635            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
4636            let cache_dir = self.state.config.cache_dir();
4637            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
4638            let (outcomes, _) = with_cache_lease(
4639                &mut self.state,
4640                cache_dir.as_deref(),
4641                "gate",
4642                "gate",
4643                &winner.worktree,
4644                &head,
4645                timeout,
4646                "final gate",
4647                |state, budget| {
4648                    let shell = shell.clone();
4649                    let gate_commands = gate_commands.clone();
4650                    let worktree = winner.worktree.clone();
4651                    async move {
4652                        let (outcomes, timed_out_pids) = run_commands(
4653                            state,
4654                            "gate",
4655                            "gate",
4656                            0,
4657                            &shell,
4658                            &gate_commands,
4659                            &worktree,
4660                            budget,
4661                        )
4662                        .await;
4663                        (outcomes, false, timed_out_pids)
4664                    }
4665                },
4666            )
4667            .await;
4668            outcomes
4669        };
4670        if outcomes.is_empty() {
4671            // Nothing configured to check — distinct from every other
4672            // silence in this run's event log, since an empty `gate` alone
4673            // no longer says whether the gate ran at all (see
4674            // `RunState::gate_ran`'s own doc).
4675            self.state.event(
4676                "gate",
4677                "no gate commands configured; nothing to check, passing",
4678            );
4679        }
4680        for o in &outcomes {
4681            self.state.event(
4682                "gate",
4683                format!(
4684                    "`{}` -> {}",
4685                    o.command,
4686                    if o.ok() {
4687                        "pass".to_owned()
4688                    } else {
4689                        format!(
4690                            "FAIL ({:?})\n{}",
4691                            o.code,
4692                            tail(&o.output_tail, EVENT_OUTPUT_TAIL)
4693                        )
4694                    }
4695                ),
4696            );
4697        }
4698        // A resource-blocked outcome means the gate command never actually
4699        // ran - the shared build cache could not be acquired or confirmed
4700        // fresh in time - which is evidence about the machine, not about the
4701        // tree (see `CommandOutcome::resource_blocked`'s own doc). Recording
4702        // it as a red gate would mark a run `Blocked` on nothing but
4703        // contention magi has already logged above; leaving `self.state.gate`
4704        // empty and `self.state.gate_ran` false instead keeps the shape this
4705        // function already treats as "still needs to run" (see the
4706        // early-return above), so the next call retries the command rather
4707        // than concluding anything.
4708        if verify_inconclusive(&outcomes) {
4709            self.state.save()?;
4710            return Ok(());
4711        }
4712        let passed = outcomes.iter().all(CommandOutcome::ok);
4713        self.state.gate = outcomes;
4714        self.state.gate_ran = true;
4715        if !passed {
4716            self.state.status = RunStatus::Blocked;
4717            self.state.event("gate", "gate failed; not merging");
4718        }
4719        self.state.save()?;
4720        Ok(())
4721    }
4722
4723    // ---------------------------------------------------------------- merge
4724
4725    async fn merge(&mut self) -> Result<()> {
4726        // Same reasoning as `gate`: ask the review and gate records directly
4727        // rather than `status`, which a solo-candidate `judge`/`deliberate`
4728        // skip can rewrite on reentry to something that no longer says
4729        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
4730        // so a hand-off (open findings, green verification) reaches merge
4731        // exactly like a genuinely clean round does.
4732        //
4733        // A run resumed mid-`land` never reaches here at all: `execute`
4734        // recognises `RunStatus::Landing` before it even calls `prep`, and
4735        // routes straight to `run_land` instead. That has to happen a level
4736        // up from this function, not with a check in here, because
4737        // `review_loop`'s own status recomputation (see its doc) runs
4738        // *before* `merge` on every reentry and would otherwise overwrite
4739        // the `Landing` marker with `Gating` before this node ever saw it.
4740        if self
4741            .state
4742            .base_sync
4743            .as_ref()
4744            .is_some_and(|s| s.conflict.is_some())
4745            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
4746                != Some(RunStatus::Gating)
4747            // `gate_ran == false` is not "passed" - `gate` leaves it false
4748            // both before it has ever run and when its last attempt was
4749            // resource-blocked (see `Runner::gate`'s own doc), and neither is
4750            // permission to merge on nothing but the review record. Only a
4751            // gate that actually ran - zero commands configured and
4752            // vacuously passed, or one or more that all exited 0 - may
4753            // proceed; `RunState::gate_status` is the single place that
4754            // reading is computed.
4755            || !self.state.gate_status().ok()
4756        {
4757            return Ok(());
4758        }
4759        // This node's own record, not `status`: `status == Ready` is not
4760        // unique to the harmless `MergeMode::None` path this line was
4761        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
4762        // run's PR was closed without merging — and on that run `mode` is
4763        // still `Pr`, so a reentry that fell through here would push and
4764        // open a second pull request. `self.state.merge` is set exactly once
4765        // this node (or `land`) has already produced a verdict, under every
4766        // mode, which is what "already done" actually means here.
4767        if self.state.merge.is_some() {
4768            return Ok(());
4769        }
4770        let Some(winner) = self.state.winner().cloned() else {
4771            return Ok(());
4772        };
4773        let repo = self.state.repo.clone();
4774        let base = self.state.base_branch.clone();
4775        let mode = self.state.config.merge.mode;
4776        let style = self.state.config.merge.style;
4777        let message = pr_body(&self.state, winner.label);
4778
4779        let outcome = match mode {
4780            MergeMode::None => MergeOutcome {
4781                mode,
4782                ok: true,
4783                detail: manual_merge_command(style, &repo, &winner.branch, &message),
4784            },
4785            MergeMode::Local => {
4786                let on = git::current_branch(&repo).await?;
4787                if on.as_deref() != Some(base.as_str()) {
4788                    MergeOutcome {
4789                        mode,
4790                        ok: false,
4791                        detail: format!(
4792                            "{} has {} checked out, not the base branch {base}",
4793                            repo.display(),
4794                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
4795                        ),
4796                    }
4797                } else if !git::is_clean(&repo).await? {
4798                    MergeOutcome {
4799                        mode,
4800                        ok: false,
4801                        detail: format!("{} is dirty; refusing to merge", repo.display()),
4802                    }
4803                } else {
4804                    let out = match style {
4805                        MergeStyle::Merge => {
4806                            git::merge_no_ff(&repo, &winner.branch, &message).await?
4807                        }
4808                        MergeStyle::Squash => {
4809                            git::merge_squash(&repo, &winner.branch, &message).await?
4810                        }
4811                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
4812                    };
4813                    MergeOutcome {
4814                        mode,
4815                        ok: out.ok(),
4816                        detail: if out.ok() { out.stdout } else { out.stderr },
4817                    }
4818                }
4819            }
4820            MergeMode::Pr => {
4821                let remote = self.state.config.merge.remote.clone();
4822                let pushed = git::push(&winner.worktree, &remote, &winner.branch).await?;
4823                if !pushed.ok() {
4824                    MergeOutcome {
4825                        mode,
4826                        ok: false,
4827                        detail: pushed.stderr,
4828                    }
4829                } else {
4830                    let out = gh_pr_create(&winner.worktree, &base, &winner.branch, &message).await;
4831                    match out {
4832                        Ok(url) => MergeOutcome {
4833                            mode,
4834                            ok: true,
4835                            detail: url,
4836                        },
4837                        Err(e) => MergeOutcome {
4838                            mode,
4839                            ok: false,
4840                            detail: e.to_string(),
4841                        },
4842                    }
4843                }
4844            }
4845        };
4846
4847        self.state.status = match (mode, outcome.ok) {
4848            (MergeMode::None, _) => RunStatus::Ready,
4849            (_, true) => RunStatus::Merged,
4850            (_, false) => RunStatus::Blocked,
4851        };
4852        self.state.event(
4853            "merge",
4854            format!(
4855                "{:?}: {}",
4856                mode,
4857                outcome.detail.lines().next().unwrap_or("")
4858            ),
4859        );
4860        self.state.merge = Some(outcome);
4861        self.state.save()?;
4862
4863        // The PR is open and the run would historically stop here, leaving the
4864        // operator to watch checks, feed review comments back to a fixer, and
4865        // merge. That was done by hand six times in one session before this
4866        // existed. Opt-in, because merging is the one irreversible thing magi
4867        // can do to a repository.
4868        if self.state.config.graph.land
4869            && mode == MergeMode::Pr
4870            && self.state.status == RunStatus::Merged
4871        {
4872            self.run_land().await?;
4873        }
4874        // `run_land` may have left `status` at `Landing` - still waiting on
4875        // CI or the owner's approval, not actually settled - so this has to
4876        // read whatever `status` ended up as here, not the `Merged` this
4877        // function set a few lines up.
4878        self.settle_questions();
4879        Ok(())
4880    }
4881
4882    /// Enter `land`.
4883    ///
4884    /// Shared between a fresh run's first pass through [`Runner::merge`] and
4885    /// a resumed run's re-entry. `land::land` itself is what serialises the
4886    /// two git-mutating moments inside the loop — the rebase push and
4887    /// `gh pr merge` — per repository (see its own doc); nothing here needs
4888    /// to hold a lock across the whole call, and doing so would serialise
4889    /// this run's CI wait against a *different* run's land-approval resume
4890    /// in the same repository, which is exactly the "must not wait on
4891    /// another task" property the daemon's slot-freeing exists to give.
4892    async fn run_land(&mut self) -> Result<()> {
4893        let url = self
4894            .state
4895            .merge
4896            .as_ref()
4897            .map(|m| m.detail.clone())
4898            .unwrap_or_default();
4899        let url = url.lines().next().unwrap_or("").trim().to_owned();
4900        if !url.starts_with("http") {
4901            return Ok(());
4902        }
4903        // A land failure is not a lost run: the work is on a branch and the
4904        // pull request is open, which is exactly where a human takes over.
4905        match land::land(&mut self.state, &url).await {
4906            Ok(pr) if self.state.parked => {
4907                // `land` already saved the parked marker; nothing here
4908                // overrides `status` back to a terminal value while an
4909                // approval is still outstanding.
4910                let _ = pr;
4911            }
4912            Ok(pr) => {
4913                self.state.status = match pr.state {
4914                    land::PrLifecycle::Merged => RunStatus::Merged,
4915                    _ => RunStatus::Blocked,
4916                };
4917                // Downstream of a confirmed merge only - see
4918                // `bump::should_release_bump`'s own doc for why this one
4919                // check covers all three of `land`'s success paths.
4920                // Best-effort: the run already landed, so a failure here
4921                // (the decision call, `gh`, `cargo`) is recorded and never
4922                // turns a landed run into a failed one.
4923                if bump::should_release_bump(self.state.status)
4924                    && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
4925                {
4926                    self.state
4927                        .event("bump", format!("release bump skipped: {e:#}"));
4928                }
4929                self.state.save()?;
4930            }
4931            Err(e) => {
4932                self.state.status = RunStatus::Blocked;
4933                self.state.event("land", format!("gave up: {e}"));
4934                self.state.save()?;
4935            }
4936        }
4937        Ok(())
4938    }
4939
4940    // -------------------------------------------------------------- helpers
4941
4942    /// Fetch or create a seat, keeping its conversation across nodes.
4943    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
4944        if let Some(existing) = self.state.seats.get(key)
4945            && existing.agent == agent
4946        {
4947            return existing.clone();
4948        }
4949        let fresh = SeatState::new(key, agent, self.state.seed);
4950        self.state.seats.insert(key.to_owned(), fresh.clone());
4951        fresh
4952    }
4953
4954    /// A candidate rendered for judging, with the leak policy applied.
4955    fn view(&self, c: &Candidate) -> CandidateView {
4956        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4957            .unwrap_or_default();
4958        let (patch, _) = blind::sanitize_patch(
4959            &format!("candidate {} patch", c.label),
4960            &raw,
4961            &self.state.config.blind,
4962        );
4963        CandidateView {
4964            label: c.label,
4965            branch: c.branch.clone(),
4966            summary: c.summary.clone(),
4967            stat: c.stat.clone(),
4968            patch,
4969        }
4970    }
4971
4972    /// The full candidate set as prompt text, for seats with no live session.
4973    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
4974        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
4975        prompt::judge(
4976            "(see above)",
4977            &views,
4978            self.roles.judges.len(),
4979            base_short,
4980            "en",
4981        )
4982    }
4983
4984    /// Anonymised transcript for judge `self_idx`.
4985    ///
4986    /// The initial rankings are always the opening statements. Seeding them
4987    /// only when no turn had been taken yet meant every judge after the first
4988    /// argued against a single voice instead of against the actual split — the
4989    /// disagreement is the information, so it is always on the table.
4990    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
4991        let mut turns = Vec::new();
4992        for j in &self.state.judgements {
4993            if j.ranking.is_empty() {
4994                continue;
4995            }
4996            let reasons = j
4997                .reasons
4998                .iter()
4999                .map(|(k, v)| format!("- {k}: {v}"))
5000                .collect::<Vec<_>>()
5001                .join("\n");
5002            turns.push(Turn {
5003                who: format!("Judge {} (opening ranking)", j.judge),
5004                is_self: j.judge == self_idx + 1,
5005                body: format!(
5006                    "Ranked {}{}{reasons}",
5007                    j.ranking.iter().collect::<String>(),
5008                    if reasons.is_empty() {
5009                        ""
5010                    } else {
5011                        ", because:\n"
5012                    }
5013                ),
5014            });
5015        }
5016        for t in self
5017            .state
5018            .deliberation
5019            .iter()
5020            .flat_map(|r| r.turns.iter())
5021            .chain(current)
5022        {
5023            turns.push(Turn {
5024                who: format!("Judge {}", t.judge),
5025                is_self: t.judge == self_idx + 1,
5026                body: t.body.clone(),
5027            });
5028        }
5029        turns
5030    }
5031}
5032
5033/// Does this seat still hold the context a follow-up prompt would rely on?
5034fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
5035    agent::has_session(spec.kind, seat, sessions)
5036}
5037
5038/// The next entry in `roster` after `start`, never wrapping back to the
5039/// front, whose id is not in `tried` yet.
5040///
5041/// Starts one past `start` rather than at the front of `roster`: `start` is
5042/// the seat's own original position, and a seat whose candidate slot already
5043/// sits on the roster's second entry must fall through to the third next, not
5044/// restart at the first — which is very likely a different candidate's own
5045/// agent already. Never wraps back past `start`, for the same reason: an
5046/// entry earlier in the roster than the seat's own position is almost
5047/// certainly some *other* candidate slot's own agent, and once the tail of
5048/// the roster is exhausted there are no more untried agents for *this* seat
5049/// to fall through to — the caller's fallback chain ends there, exactly as
5050/// "no further untried agents remain in the list for that seat" asks for.
5051///
5052/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
5053/// the same id twice (an operator's `roles.implementers` typo, or a
5054/// `[[agents]]` list reused across roles) must not let
5055/// [`Runner::resume_quota_losses`] retry that id forever — one forward pass
5056/// over `roster` either finds an untried id or runs out, so this always
5057/// terminates regardless of duplicates.
5058fn next_untried_implementer<'a>(
5059    roster: &'a [AgentSpec],
5060    start: usize,
5061    tried: &BTreeSet<String>,
5062) -> Option<&'a AgentSpec> {
5063    roster
5064        .get(start + 1..)?
5065        .iter()
5066        .find(|s| !tried.contains(&s.id))
5067}
5068
5069/// Did this reply report running a command whose own CLI never confirmed an
5070/// exit status?
5071///
5072/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
5073/// command *finished* (see that type's own doc), so this can only be `true`
5074/// for a command whose completion event carried no readable exit code — not
5075/// for one that simply is not mentioned at all. That is the one signal this
5076/// crate can read, from the same record `state.jobs` renders, about a reply
5077/// standing next to work its own CLI cannot vouch for finishing; it is
5078/// deliberately not a check on the exit code's *value* (a fixer legitimately
5079/// runs a command that fails mid-iteration before it succeeds) and not a
5080/// guess at a command still running in the background (which emits no event
5081/// at all, and so leaves no evidence here to find).
5082fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
5083    commands.iter().any(|c| c.exit_code.is_none())
5084}
5085
5086/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
5087/// trusted as a verified no-op — the adoption guard's own text-level half.
5088///
5089/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
5090/// timed out): a marker only earns the benefit of the doubt from a turn the
5091/// CLI itself vouches for finishing properly, the same house style
5092/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
5093/// *fix* report to for `commands`. A candidate that timed out, exited
5094/// non-zero, or left a command unconfirmed is read as the ordinary loss it
5095/// is, whatever prose it wrote — this returns `None` before it ever looks at
5096/// `text`. The remaining guards (the tree really is empty, the evidence is
5097/// non-empty) are the caller's: this only reads what the reply *claimed*.
5098fn verified_noop_claim(
5099    usable: bool,
5100    commands: &[agent::CommandEvidence],
5101    text: &str,
5102) -> Option<String> {
5103    (usable && !has_unconfirmed_command(commands))
5104        .then(|| verdict::verified_noop(text))
5105        .flatten()
5106}
5107
5108fn short(commit: &str) -> String {
5109    commit.chars().take(7).collect()
5110}
5111
5112fn make_executable(path: &Path) -> Result<()> {
5113    #[cfg(unix)]
5114    {
5115        use std::os::unix::fs::PermissionsExt as _;
5116        let mut perms = std::fs::metadata(path)?.permissions();
5117        perms.set_mode(0o755);
5118        std::fs::set_permissions(path, perms)?;
5119    }
5120    #[cfg(not(unix))]
5121    {
5122        let _ = path;
5123    }
5124    Ok(())
5125}
5126
5127/// What every seat in one batch shares: where the answers are attributed, the
5128/// prompt overlay they inherit, and the build cache they are told to use.
5129///
5130/// A struct rather than four more parameters: `wave` also needs the run's
5131/// state (to record who is answering right now) and the attempt number, and
5132/// eight positional arguments is both unreadable and a clippy error.
5133struct WaveCtx<'a> {
5134    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
5135    /// paid for it.
5136    run: &'a str,
5137    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
5138    node: &'a str,
5139    prompts: &'a Prompts,
5140    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
5141    cache: Option<&'a Path>,
5142    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
5143    /// `JobRecord::round`. `None` for every other node.
5144    round: Option<usize>,
5145}
5146
5147/// Run one job, honouring the parallelism budget.
5148async fn run_one(
5149    job: SeatJob,
5150    sem: Arc<Semaphore>,
5151    ctx: &WaveCtx<'_>,
5152    state: &mut RunState,
5153    attempt: usize,
5154) -> (SeatState, AgentOutcome) {
5155    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
5156        .await
5157        .pop()
5158        .expect("one job in, one result out");
5159    (seat, out)
5160}
5161
5162/// Run every job concurrently, capped by the semaphore, preserving order.
5163///
5164/// Every seat in the batch is recorded into [`RunState::active`] before the
5165/// wave starts and cleared as each answer lands, so the run's own record says
5166/// who is still being waited on rather than only who finished.
5167async fn wave(
5168    jobs: Vec<SeatJob>,
5169    sem: Arc<Semaphore>,
5170    ctx: &WaveCtx<'_>,
5171    state: &mut RunState,
5172    attempt: usize,
5173) -> Vec<(usize, SeatState, AgentOutcome)> {
5174    let WaveCtx {
5175        run,
5176        node,
5177        prompts,
5178        cache,
5179        round,
5180    } = *ctx;
5181    for job in &jobs {
5182        state.seat_started(node, &job.seat.key, job.timeout, attempt);
5183    }
5184    if let Err(e) = state.save() {
5185        // A failed persist of "who is answering right now" must not abort the
5186        // wave: the seats are already being asked, and the alternative is
5187        // losing the answers to save a status line nobody may even be
5188        // watching.
5189        tracing::warn!("could not persist in-progress seats: {e:#}");
5190    }
5191    // Hold the shared build cache's lease for the whole batch, not per job:
5192    // several candidates (an implement wave) or a fixer legitimately share
5193    // one cache concurrently within this run, and that stays untouched — a
5194    // single lease taken once for the whole wave and released once it is
5195    // done is what stops a *different* borrower (another run's own wave, its
5196    // e2e/gate, a human's `magi review`) from interleaving a build into the
5197    // same directory while this one is in flight. Best-effort, not
5198    // all-or-nothing: a wave that cannot get the lease within its own
5199    // longest job's budget still runs — an hour of paid implementer calls is
5200    // not thrown away over cache contention — but every write-allowed seat
5201    // then goes without `CARGO_TARGET_DIR` for this wave too (see the filter
5202    // below), the same fallback a read-only seat always gets, rather than
5203    // building into a directory this run was never granted. The identity
5204    // record is still invalidated below either way, so the next tracked
5205    // caller (`e2e`/`gate`) never trusts a match it cannot vouch for.
5206    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
5207    let wait_started = Instant::now();
5208    let cache_guard = if let Some(cache_dir) = cache {
5209        if jobs_had_a_writer {
5210            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
5211            let budget = jobs
5212                .iter()
5213                .map(|j| j.timeout)
5214                .max()
5215                .unwrap_or(Duration::from_secs(60));
5216            acquire_cache_lease(state, cache_dir, &owner, budget, node)
5217                .await
5218                .ok()
5219        } else {
5220            None
5221        }
5222    } else {
5223        None
5224    };
5225    // Carved out of each job's own budget, not added on top of it: a seat
5226    // that waited behind the lease must not also get its full timeout
5227    // afterward, or a run contended on the cache could double the time it
5228    // spends per wave. `saturating_sub` floors at zero rather than
5229    // wrapping - a job whose whole budget was spent waiting starts with
5230    // none left, which is the honest number, not a free minimum.
5231    let waited_for_lease = wait_started.elapsed();
5232    let mut set = tokio::task::JoinSet::new();
5233    let overlay = prompts.overlay(node);
5234    for (i, mut job) in jobs.into_iter().enumerate() {
5235        job.timeout = job.timeout.saturating_sub(waited_for_lease);
5236        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
5237        if cache.is_some() {
5238            job.prompt.push('\n');
5239            job.prompt
5240                .push_str(&prompt::build_cache_note(node, job.allow_write));
5241        }
5242        let sem = Arc::clone(&sem);
5243        let run = run.to_owned();
5244        let node = node.to_owned();
5245        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
5246        // `prompt::build_cache_note`'s doc for why setting it anyway is
5247        // exactly how a sandboxed reviewer's write refusal got reported as a
5248        // defect in the patch, not a property of its own seat. And a
5249        // write-allowed one is handed it only when the lease above was
5250        // actually acquired: a wave that could not get it (`cache_guard` is
5251        // `None`, see its own comment) must not send seats to build into a
5252        // directory this run does not hold - that is the exact concurrent,
5253        // unmanaged-write race this module exists to prevent, not something
5254        // "proceeding anyway" is allowed to reintroduce.
5255        let cache = cache
5256            .filter(|_| job.allow_write && cache_guard.is_some())
5257            .map(Path::to_path_buf);
5258        set.spawn(async move {
5259            let _permit = sem.acquire().await;
5260            let mut seat = job.seat;
5261            let out = agent::invoke(
5262                &job.spec,
5263                &mut seat,
5264                &Invocation {
5265                    cwd: &job.cwd,
5266                    prompt: &job.prompt,
5267                    timeout: job.timeout,
5268                    allow_write: job.allow_write,
5269                    sessions: job.sessions,
5270                    artifacts: &job.artifacts,
5271                    stem: &job.stem,
5272                    run: &run,
5273                    node: &node,
5274                    cache_dir: cache.as_deref(),
5275                    attachments: &[],
5276                },
5277            )
5278            .await;
5279            let out = match out {
5280                Ok(o) if o.usable() => AgentOutcome::Ok(o),
5281                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
5282                // Billed work the CLI failed to hand over is not an ordinary
5283                // failure, but its text is the CLI's raw error JSON, not an
5284                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
5285                // read it as one by forgetting to check. `usable()` is always
5286                // false here (dropped implies an empty response), so this has
5287                // to be checked before the catch-all `Failed` below or the
5288                // one shape this exists for is lost with the rest.
5289                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
5290                Ok(o) if o.timed_out => AgentOutcome::Failed("timed out".to_owned()),
5291                Ok(o) => AgentOutcome::Failed(format!(
5292                    "exited with {:?} and no usable output",
5293                    o.exit_code
5294                )),
5295                Err(e) => AgentOutcome::Failed(e.to_string()),
5296            };
5297            (i, seat, out)
5298        });
5299    }
5300    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
5301    while let Some(joined) = set.join_next().await {
5302        let (i, seat, out) = match joined {
5303            Ok(v) => v,
5304            // No seat to clear: a panicked task never reported which one it
5305            // was. The defensive sweep below this loop is what stops that
5306            // seat's `active` entry from surviving forever.
5307            Err(e) => {
5308                tracing::error!("agent task panicked: {e}");
5309                continue;
5310            }
5311        };
5312        state.seat_finished(&seat.key);
5313        record_jobs(state, node, round, &seat.key, &out);
5314        if let Err(e) = state.save() {
5315            tracing::warn!("could not persist a seat's completion: {e:#}");
5316        }
5317        if collected.len() <= i {
5318            collected.resize_with(i + 1, || None);
5319        }
5320        collected[i] = Some((i, seat, out));
5321    }
5322    // Belt-and-braces for the panic branch above: every seat this exact batch
5323    // started shares this `(node, attempt)` pair, and every seat that finished
5324    // normally already cleared itself, so anything left tagged with it here
5325    // can only be a panicked task's leftover. Cleared unconditionally rather
5326    // than left to read as still answering forever.
5327    if state
5328        .active
5329        .values()
5330        .any(|a| a.node == node && a.attempt == attempt)
5331    {
5332        state
5333            .active
5334            .retain(|_, a| !(a.node == node && a.attempt == attempt));
5335        if let Err(e) = state.save() {
5336            tracing::warn!("could not persist the end of a wave: {e:#}");
5337        }
5338    }
5339    // Whether or not the lease above was actually held, several worktrees
5340    // may just have built into the cache with nothing here able to name one
5341    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
5342    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
5343    // clean it might not have strictly needed; trusting a stale match would
5344    // cost it a wrong answer.
5345    if let Some(cache_dir) = cache
5346        && jobs_had_a_writer
5347    {
5348        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
5349    }
5350    if let Some(guard) = cache_guard {
5351        guard.release();
5352    }
5353    collected.into_iter().flatten().collect()
5354}
5355
5356/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
5357/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
5358/// this is data collection, not the fix-specific completion contract in
5359/// [`Runner::continue_fix_report`], and applies regardless of which node
5360/// asked.
5361///
5362/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
5363/// evidence from; `Failed` does not, and correctly contributes nothing — a
5364/// timeout or crash is not itself evidence about a command the seat may have
5365/// started.
5366fn record_jobs(
5367    state: &mut RunState,
5368    node: &str,
5369    round: Option<usize>,
5370    seat: &str,
5371    out: &AgentOutcome,
5372) {
5373    let commands: &[agent::CommandEvidence] = match out {
5374        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
5375        AgentOutcome::Failed(_) => &[],
5376    };
5377    let checked_at = Timestamp::now();
5378    for c in commands {
5379        state.jobs.push(JobRecord {
5380            node: node.to_owned(),
5381            round,
5382            seat: seat.to_owned(),
5383            id: c.id.clone(),
5384            description: c.description.clone(),
5385            checked_at,
5386            status: match c.exit_code {
5387                Some(0) => JobStatus::Completed,
5388                Some(_) => JobStatus::Failed,
5389                None => JobStatus::Unknown,
5390            },
5391            exit_code: c.exit_code,
5392            result_summary: c.result_summary.clone(),
5393            source: c.source.clone(),
5394        });
5395    }
5396}
5397
5398/// Is a review round clean, given how many reviewer seats answered against
5399/// how many the round expected?
5400///
5401/// A seat that never answered (timeout, crash, unparsable output) is not a
5402/// seat that read the patch and found nothing — treating it as such is
5403/// exactly the bug this function exists to close. Under the default `block`
5404/// policy a missing seat can never be clean; `warn` still requires the seats
5405/// that *did* answer to have found nothing blocking and verification to be
5406/// green.
5407///
5408/// `quota_missing` narrows that `block` default for exactly one cause of
5409/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
5410/// a session limit lifts by the very next round buys nothing — the seat is
5411/// asked again with the same quota — so once every missing seat is accounted
5412/// for by a quota loss (and at least one seat *did* answer, so a decision has
5413/// something to rest on) the round is decided on the panel that could answer,
5414/// same as `warn` would. A panel that lost every seat to quota is not
5415/// decided here: `answered == 0` falls through to the existing `block`
5416/// fallback so a fully collapsed panel still waits rather than landing on no
5417/// review at all.
5418fn round_is_clean(
5419    blocking: usize,
5420    e2e_ok: bool,
5421    answered: usize,
5422    expected: usize,
5423    quota_missing: usize,
5424    policy: IncompleteReviewPolicy,
5425) -> bool {
5426    if blocking != 0 || !e2e_ok {
5427        return false;
5428    }
5429    if answered == expected || policy == IncompleteReviewPolicy::Warn {
5430        return true;
5431    }
5432    answered > 0 && expected - answered <= quota_missing
5433}
5434
5435/// The review loop's own conclusion, derived entirely from its persisted
5436/// round records and the round budget that produced them — never from
5437/// `status`, so a reentry (or `gate`/`merge` reading it independently)
5438/// recomputes the identical answer regardless of what an earlier node in the
5439/// same walk, or a previous walk, did to `status`.
5440///
5441/// `None` while more rounds remain to try, including when review never ran
5442/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
5443/// gone clean, or the budget is spent, or the tree has stopped moving (see
5444/// [`STAGNANT_LIMIT`]), the answer is one of two things:
5445///
5446/// - An incomplete panel that raised nothing is missing input, not a
5447///   verified tree — never a hand-off candidate, whatever verification said
5448///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
5449/// - Otherwise, green e2e on the last round hands off (see
5450///   [`Runner::stop_reviewing`]); red e2e blocks.
5451///
5452/// A last round whose own verification is still `ResourceBlocked` — magi
5453/// itself never got a command to run, not evidence the patch is broken —
5454/// is neither: this returns `None` for it too, the same as "more rounds
5455/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
5456/// handling of that shape) instead of this cheap recomputation guessing a
5457/// verdict a real attempt never produced.
5458fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
5459    if max_rounds == 0 || reviews.iter().any(|r| r.clean) {
5460        return Some(RunStatus::Gating);
5461    }
5462    let last = reviews.last()?;
5463    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
5464    if reviews.len() < max_rounds && !stagnant {
5465        return None;
5466    }
5467    if last.incomplete() && last.blocking == 0 {
5468        return Some(RunStatus::Blocked);
5469    }
5470    if last.e2e_status() == E2eStatus::ResourceBlocked {
5471        return None;
5472    }
5473    Some(if last.e2e.iter().all(CommandOutcome::ok) {
5474        RunStatus::Gating
5475    } else {
5476        RunStatus::Blocked
5477    })
5478}
5479
5480/// How long a re-ask may take, given the budget the first attempt had.
5481///
5482/// A `nudged` retry is a request to restate an answer the seat has already
5483/// worked out: it carries no new work, so it does not deserve the original
5484/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
5485/// 133 seconds while a third sat for over ten minutes on a resumed session
5486/// holding 410 KB of prior output - and because the retry had inherited the
5487/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
5488/// judging round whose other seats were long finished.
5489///
5490/// A quarter of the budget, with a floor so that a deliberately short timeout
5491/// does not collapse to nothing. A retry that re-sends the whole prompt
5492/// (because the seat kept no context) is the original job again, and keeps the
5493/// original budget.
5494fn retry_budget(full: Duration, nudged: bool) -> Duration {
5495    if nudged {
5496        (full / 4).max(Duration::from_secs(120)).min(full)
5497    } else {
5498        full
5499    }
5500}
5501
5502/// Run a wave and parse each reply, re-asking the seats whose reply was
5503/// unusable.
5504///
5505/// The re-ask is a nudge rather than the whole prompt again when the seat still
5506/// holds its conversation, which is the difference between a cheap retry and
5507/// paying for the entire candidate set twice.
5508///
5509/// A seat that hits a rate limit is **not** re-asked: the same call will fail
5510/// the same way until the limit resets, so spending a retry attempt on it is
5511/// pure waste. Its loss is recorded in `losses` and it is returned as a failure
5512/// like any other absent seat — the caller decides whether the panel still has
5513/// a quorum.
5514#[allow(clippy::too_many_arguments)]
5515async fn ask_json_wave<T>(
5516    jobs: Vec<SeatJob>,
5517    sem: Arc<Semaphore>,
5518    retries: usize,
5519    ctx: &WaveCtx<'_>,
5520    losses: &mut Vec<QuotaLoss>,
5521    state: &mut RunState,
5522    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
5523) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
5524where
5525    T: serde::de::DeserializeOwned + Send + 'static,
5526{
5527    let n = jobs.len();
5528    let originals: Vec<SeatJob> = jobs;
5529    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
5530    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
5531    // Which attempt each seat's `done[i]` reflects — 0 for a first-ask
5532    // answer, N once it has gone through N nudges. Read back once this
5533    // returns, so a caller building a history record (`ReviewRecord`) can
5534    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
5535    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
5536    // field's own doc.
5537    let mut attempts_used: Vec<usize> = vec![0; n];
5538    let mut pending: Vec<usize> = (0..n).collect();
5539
5540    for attempt in 0..=retries {
5541        if pending.is_empty() {
5542            break;
5543        }
5544        let mut batch = Vec::with_capacity(pending.len());
5545        for &i in &pending {
5546            let src = &originals[i];
5547            // The prompt and the budget are one decision: a nudge restates
5548            // finished work, a re-sent prompt redoes it.
5549            let (prompt, timeout) = if attempt == 0 {
5550                (src.prompt.clone(), src.timeout)
5551            } else {
5552                let why = done[i]
5553                    .as_ref()
5554                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
5555                    .unwrap_or_else(|| "no parsable answer".to_owned());
5556                let nudge = prompt::nudge(&why);
5557                let nudged = has_context(&src.spec, &seats[i], src.sessions);
5558                let prompt = if nudged {
5559                    nudge
5560                } else {
5561                    format!("{}\n\n---\n\n{}", src.prompt, nudge)
5562                };
5563                (prompt, retry_budget(src.timeout, nudged))
5564            };
5565            batch.push(SeatJob {
5566                spec: src.spec.clone(),
5567                seat: seats[i].clone(),
5568                cwd: src.cwd.clone(),
5569                prompt,
5570                timeout,
5571                allow_write: src.allow_write,
5572                sessions: src.sessions,
5573                artifacts: src.artifacts.clone(),
5574                stem: if attempt == 0 {
5575                    src.stem.clone()
5576                } else {
5577                    format!("{}-retry{attempt}", src.stem)
5578                },
5579            });
5580        }
5581
5582        if attempt > 0 {
5583            let seats_out: Vec<&str> = pending
5584                .iter()
5585                .map(|&i| originals[i].seat.key.as_str())
5586                .collect();
5587            state.event(
5588                ctx.node,
5589                format!("retry {attempt}: re-asking {}", seats_out.join(", ")),
5590            );
5591        }
5592        let results = wave(batch, Arc::clone(&sem), ctx, state, attempt).await;
5593        let mut still = Vec::new();
5594        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
5595            seats[i] = seat;
5596            let (parsed, quota) = match out {
5597                AgentOutcome::Ok(o) => (
5598                    match verdict::extract_json::<T>(&o.text) {
5599                        Ok(v) => match validate(&v) {
5600                            Ok(()) => Ok((v, o)),
5601                            Err(e) => Err(e),
5602                        },
5603                        Err(e) => Err(e),
5604                    },
5605                    false,
5606                ),
5607                AgentOutcome::Quota(o) => {
5608                    losses.push(QuotaLoss {
5609                        seat: originals[i].seat.key.clone(),
5610                        node: ctx.node.to_owned(),
5611                        at: Timestamp::now(),
5612                        reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
5613                    });
5614                    (
5615                        Err(anyhow::anyhow!("rate limited (quota); not retrying now")),
5616                        true,
5617                    )
5618                }
5619                // Not a parseable answer, but also not worth a special-cased
5620                // retry here: the nudge loop above already re-asks anything
5621                // that fails to parse, which is exactly what a dropped stream
5622                // needs. Just don't hand its raw error JSON to `extract_json`.
5623                AgentOutcome::Dropped(o) => {
5624                    let why = o
5625                        .dropped
5626                        .as_ref()
5627                        .map(|d| d.why.as_str())
5628                        .unwrap_or("the CLI ended the stream without delivering its answer");
5629                    (
5630                        Err(anyhow::anyhow!("the CLI dropped the stream ({why})")),
5631                        false,
5632                    )
5633                }
5634                AgentOutcome::Failed(e) => (Err(anyhow::anyhow!(e)), false),
5635            };
5636            let failed = parsed.is_err();
5637            done[i] = Some(parsed);
5638            attempts_used[i] = attempt;
5639            // Do not re-ask a rate-limited seat (quota) — a retry is known to
5640            // fail the same way; and never re-ask a seat that already parsed.
5641            if failed && !quota {
5642                still.push(i);
5643            }
5644        }
5645        pending = still;
5646    }
5647
5648    seats
5649        .into_iter()
5650        .zip(done)
5651        .zip(attempts_used)
5652        .map(|((seat, res), attempts)| {
5653            (
5654                seat,
5655                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
5656                attempts,
5657            )
5658        })
5659        .collect()
5660}
5661
5662/// Acquire the shared build cache's lease, waiting out contention within
5663/// `budget` (never past it — see AGENTS.md's build-cache section on why an
5664/// unbounded wait is never acceptable).
5665///
5666/// A first, non-blocking check happens before ever waiting; if it finds the
5667/// lease busy, that fact is logged as a `verify` event *and* flushed with
5668/// [`RunState::save`] immediately — not only once the wait finally succeeds
5669/// or gives up — so a `magi show` run by a different process while this one
5670/// is still waiting reads a `run.json` that says so, rather than whatever it
5671/// looked like before the wait started. The same applies to the terminal
5672/// failure: logged and saved before this returns `Err`, so a caller that
5673/// could not get the lease at all still leaves a legible record of why.
5674async fn acquire_cache_lease(
5675    state: &mut RunState,
5676    cache_dir: &Path,
5677    owner: &crate::cache::Owner,
5678    budget: Duration,
5679    context: &str,
5680) -> Result<crate::cache::Guard> {
5681    let home = crate::run::home();
5682    let started = Instant::now();
5683    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
5684        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(g),
5685        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
5686        Err(e) => {
5687            state.event(
5688                "verify",
5689                format!("{context}: could not check the shared build cache: {e:#}"),
5690            );
5691            if let Err(e2) = state.save() {
5692                tracing::warn!("could not persist a cache-check failure: {e2:#}");
5693            }
5694            return Err(e);
5695        }
5696    };
5697    state.event(
5698        "verify",
5699        format!(
5700            "{context}: waiting for the shared build cache at {} ({})",
5701            cache_dir.display(),
5702            busy.describe()
5703        ),
5704    );
5705    if let Err(e) = state.save() {
5706        tracing::warn!("could not persist a cache wait: {e:#}");
5707    }
5708    let remaining = budget.saturating_sub(started.elapsed());
5709    match crate::cache::wait_for(&home, cache_dir, owner, remaining, Duration::from_secs(5)).await {
5710        Ok(g) => Ok(g),
5711        Err(e) => {
5712            state.event("verify", format!("{context}: {e:#}"));
5713            if let Err(e2) = state.save() {
5714                tracing::warn!("could not persist a cache wait timeout: {e2:#}");
5715            }
5716            Err(e)
5717        }
5718    }
5719}
5720
5721/// Run `body` — a verify command batch — while holding the shared build
5722/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
5723/// never interleave with another borrower's build against the same
5724/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
5725/// timeout, or a human's own `magi review`. See the `cache` module doc for
5726/// why this matters more than Cargo's own per-target locking covers — two
5727/// *different* worktrees building the same package name/version into one
5728/// cache directory is a staleness bug, not a lock contention one.
5729///
5730/// The wait for the lease is carved out of `budget`, never on top of it —
5731/// `body` is handed whatever is left, so a caller's own node timeout is the
5732/// only clock involved, exactly what AGENTS.md's build-cache section asks
5733/// for ("never an unbounded wait"). When `cache_dir` is `None` — no shared
5734/// cache configured at all — this is a pass-through: `body` runs with the
5735/// full budget and nothing is leased.
5736///
5737/// A lease that cannot be acquired within `budget` is reported as a single
5738/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
5739/// verification — the same shape a spawn failure already takes in
5740/// [`run_commands`], so a caller need not special-case it.
5741#[allow(clippy::too_many_arguments)]
5742async fn with_cache_lease<'s, F, Fut>(
5743    state: &'s mut RunState,
5744    cache_dir: Option<&Path>,
5745    node: &str,
5746    seat: &str,
5747    worktree: &Path,
5748    head: &str,
5749    budget: Duration,
5750    context: &str,
5751    body: F,
5752) -> (Vec<CommandOutcome>, bool)
5753where
5754    F: FnOnce(&'s mut RunState, Duration) -> Fut,
5755    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
5756{
5757    let Some(cache_dir) = cache_dir else {
5758        let (outcomes, retried, _timed_out_pids) = body(state, budget).await;
5759        return (outcomes, retried);
5760    };
5761    let home = crate::run::home();
5762    let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
5763    let started = Instant::now();
5764    let guard = match acquire_cache_lease(state, cache_dir, &owner, budget, context).await {
5765        Ok(g) => g,
5766        Err(e) => {
5767            return (
5768                vec![CommandOutcome {
5769                    command: "(waiting for the shared build cache)".to_owned(),
5770                    code: None,
5771                    output_tail: e.to_string(),
5772                    duration_ms: started.elapsed().as_millis() as u64,
5773                    resource_blocked: true,
5774                }],
5775                false,
5776            );
5777        }
5778    };
5779    let identity = crate::cache::Identity::new(worktree, head);
5780    if let Err(e) = crate::cache::ensure_fresh(&home, cache_dir, &identity) {
5781        // A failed freshness check means this process cannot vouch for what
5782        // is sitting in the cache right now - on Windows this is exactly the
5783        // "a stale test executable is still locked, `cargo clean -p` cannot
5784        // remove it" case the evidence log records. Running verify anyway
5785        // and reporting whatever it says would let a result nobody can trust
5786        // stand for the tree it claims to have checked; fail the step
5787        // instead of the patch.
5788        state.event(
5789            "verify",
5790            format!(
5791                "{context}: could not confirm the shared build cache matches {} at {}: {e:#}",
5792                worktree.display(),
5793                short(head)
5794            ),
5795        );
5796        guard.release();
5797        return (
5798            vec![CommandOutcome {
5799                command: "(confirming the shared build cache is fresh)".to_owned(),
5800                code: None,
5801                output_tail: e.to_string(),
5802                duration_ms: started.elapsed().as_millis() as u64,
5803                resource_blocked: true,
5804            }],
5805            false,
5806        );
5807    }
5808    let remaining = budget.saturating_sub(started.elapsed());
5809    let (outcomes, retried, timed_out_pids) = body(state, remaining).await;
5810    // A timed-out command's process was only *asked* to die (`kill_on_drop`,
5811    // `start_kill`); confirm it actually has before handing the directory to
5812    // the next acquirer. See `wait_for_timed_out_children_to_die`'s own doc
5813    // for what this can and cannot see.
5814    if !timed_out_pids.is_empty() {
5815        wait_for_timed_out_children_to_die(&timed_out_pids).await;
5816    }
5817    guard.release();
5818    (outcomes, retried)
5819}
5820
5821/// Poll `pids` — commands [`run_commands`] reports as still running when its
5822/// own timeout elapsed — until every one is confirmed gone, or
5823/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
5824///
5825/// Real confirmation where confirmation is possible, not a substitute for
5826/// full process-tree observation: a grandchild the timed-out process spawned
5827/// and that survives independently of it is invisible to a pid check the
5828/// same way it always was, and continuing to observe and collect *that*
5829/// stays a different piece of work with its own owner. This only narrows a
5830/// fixed blind wait into an actual check of the pids this process does know
5831/// about.
5832async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
5833    wait_for_pids_with(
5834        pids,
5835        crate::proc::pid_alive,
5836        LEASE_RELEASE_POLL,
5837        LEASE_RELEASE_MAX_WAIT,
5838    )
5839    .await;
5840}
5841
5842/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
5843/// interval and ceiling supplied by the caller, so the polling *logic* -
5844/// returns as soon as every pid reports dead, gives up at the ceiling
5845/// otherwise - is testable on millisecond durations without asking the real
5846/// OS about a pid at all.
5847async fn wait_for_pids_with<F: Fn(u32) -> bool>(
5848    pids: &[u32],
5849    alive: F,
5850    poll: Duration,
5851    max_wait: Duration,
5852) {
5853    let deadline = Instant::now() + max_wait;
5854    loop {
5855        if pids.iter().all(|&pid| !alive(pid)) {
5856            return;
5857        }
5858        if Instant::now() >= deadline {
5859            return;
5860        }
5861        tokio::time::sleep(poll).await;
5862    }
5863}
5864
5865/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
5866/// admission that it could not even get a verify command to run, as opposed
5867/// to evidence the command actually produced? A caller that would otherwise
5868/// read a resource-blocked outcome as a red command must check this first:
5869/// see [`Runner::gate`], which retries rather than records `Blocked` when
5870/// this is true.
5871fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
5872    outcomes.iter().any(|o| o.resource_blocked)
5873}
5874
5875/// Describe one verify command's outcome for the event log, distinguishing a
5876/// build/link failure — the toolchain never produced a binary to run — from
5877/// an actual test failure, since only the latter is a verdict on the patch.
5878fn e2e_outcome_label(o: &CommandOutcome) -> String {
5879    if o.ok() {
5880        return "pass".to_owned();
5881    }
5882    let reason = if o.build_failed() {
5883        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
5884    } else {
5885        format!("FAIL ({:?})", o.code)
5886    };
5887    format!("{reason}\n{}", tail(&o.output_tail, EVENT_OUTPUT_TAIL))
5888}
5889
5890/// Run `verify.e2e`, retrying once if the first attempt could not build or
5891/// link — a build/link failure is frequently a race against a shared
5892/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
5893/// `verify` event per command, tagged with `context` (normally `"round N"`)
5894/// so the two call sites that need this — the ordinary per-round leg in
5895/// `review_loop`, and the deferred catch-up run `stop_reviewing` makes before
5896/// it will ever call a round green — read identically in the event log.
5897async fn run_e2e_with_retry(
5898    state: &mut RunState,
5899    shell: &[String],
5900    commands: &[String],
5901    worktree: &Path,
5902    timeout: Duration,
5903    context: &str,
5904) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
5905    let (mut e2e, mut timed_out_pids) = run_commands(
5906        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
5907    )
5908    .await;
5909    for o in &e2e {
5910        state.event(
5911            "verify",
5912            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
5913        );
5914    }
5915    // A build/link failure is not a verdict on the patch — it is frequently a
5916    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
5917    // one retry before letting a red like that decide the round.
5918    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
5919    if verify_retried {
5920        state.event(
5921            "verify",
5922            format!(
5923                "{context}: verify could not build/link, not a test result — retrying once \
5924                 before concluding"
5925            ),
5926        );
5927        let retried = run_commands(
5928            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
5929        )
5930        .await;
5931        e2e = retried.0;
5932        // Both attempts' timeouts matter, not just the last one: the first
5933        // attempt's descendants may still be alive alongside the retry's.
5934        timed_out_pids.extend(retried.1);
5935        for o in &e2e {
5936            state.event(
5937                "verify",
5938                format!(
5939                    "{context}: retry `{}` -> {}",
5940                    o.command,
5941                    e2e_outcome_label(o)
5942                ),
5943            );
5944        }
5945    }
5946    (e2e, verify_retried, timed_out_pids)
5947}
5948
5949/// Run configured shell commands in `cwd`, in order. The second element is
5950/// the pid of every command that hit `timeout` and was still running when
5951/// this stopped waiting on it (best-effort: `None` when the platform did not
5952/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
5953/// that releases a shared resource afterward needs to know.
5954///
5955/// Records `task` into [`RunState::active`] at every command boundary
5956/// (`RunState::task_command`) and clears it once the whole list has run
5957/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
5958/// for minutes with no seat and no output of its own to show for it (see
5959/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
5960/// apart from "not yet run" without this), and this is the only place that
5961/// knows which command is running right now and how many are left. Three
5962/// saves per command — start, not per second — matching the same "only at a
5963/// boundary" rule [`wave`] already follows for seats.
5964#[allow(clippy::too_many_arguments)]
5965async fn run_commands(
5966    state: &mut RunState,
5967    node: &str,
5968    task: &str,
5969    attempt: usize,
5970    shell: &[String],
5971    commands: &[String],
5972    cwd: &Path,
5973    timeout: Duration,
5974) -> (Vec<CommandOutcome>, Vec<u32>) {
5975    if commands.is_empty() {
5976        // Nothing to mark as running and nothing to clear — an empty list
5977        // means "not configured", and touching `active` (or the disk) over
5978        // that would be a write for every round of a repo with no
5979        // `verify.e2e` / `verify.gate` commands at all.
5980        return (Vec::new(), Vec::new());
5981    }
5982    let mut out = Vec::new();
5983    let mut timed_out_pids = Vec::new();
5984    let total = commands.len();
5985    for (idx, command) in commands.iter().enumerate() {
5986        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
5987        if let Err(e) = state.save() {
5988            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
5989        }
5990        let started = Instant::now();
5991        let mut cmd = tokio::process::Command::new(&shell[0]);
5992        cmd.quiet();
5993        cmd.args(&shell[1..])
5994            .arg(command)
5995            .current_dir(cwd)
5996            .stdin(std::process::Stdio::null())
5997            .stdout(std::process::Stdio::piped())
5998            .stderr(std::process::Stdio::piped())
5999            .kill_on_drop(true);
6000        let spawned = cmd.spawn();
6001        let (code, body) = match spawned {
6002            Ok(child) => {
6003                // Captured before the child is consumed below: `kill_on_drop`
6004                // only *asks* the process to die when the timeout branch
6005                // drops it, and the pid is the only way anyone downstream can
6006                // later check whether that request actually took.
6007                let pid = child.id();
6008                match tokio::time::timeout(timeout, child.wait_with_output()).await {
6009                    Ok(Ok(o)) => {
6010                        let mut body = String::from_utf8_lossy(&o.stdout).into_owned();
6011                        body.push_str(&String::from_utf8_lossy(&o.stderr));
6012                        (o.status.code(), body)
6013                    }
6014                    Ok(Err(e)) => (None, format!("failed to run: {e}")),
6015                    Err(_) => {
6016                        if let Some(pid) = pid {
6017                            timed_out_pids.push(pid);
6018                        }
6019                        (None, format!("timed out after {}s", timeout.as_secs()))
6020                    }
6021                }
6022            }
6023            Err(e) => (None, format!("failed to spawn `{}`: {e}", shell[0])),
6024        };
6025        out.push(CommandOutcome {
6026            command: command.clone(),
6027            code,
6028            output_tail: tail(&body, OUTPUT_TAIL),
6029            duration_ms: started.elapsed().as_millis() as u64,
6030            resource_blocked: false,
6031        });
6032    }
6033    state.task_finished(task);
6034    if let Err(e) = state.save() {
6035        tracing::warn!("could not persist the end of {task}: {e:#}");
6036    }
6037    (out, timed_out_pids)
6038}
6039
6040/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
6041/// section (`report::run`) and in the `merge` event this node records — for
6042/// the operator to run by hand.
6043///
6044/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
6045/// branch whose ruleset forbids merge commits (GitHub's "must not contain
6046/// merge commits", or "require linear history") rejects the push a `--no-ff`
6047/// merge would produce, which is exactly the guidance this function replaces.
6048/// `message`'s first line becomes the squash commit's subject, matching the
6049/// note `report::run` prints alongside this command — see that function for
6050/// why an explicit subject is not optional there.
6051fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
6052    let repo = repo.display();
6053    match style {
6054        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
6055        MergeStyle::Squash => {
6056            let subject = message.lines().next().unwrap_or(branch);
6057            format!(
6058                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
6059            )
6060        }
6061        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
6062    }
6063}
6064
6065/// The merge commit / pull request body: the task, and — when the winning
6066/// review round was not clean — the findings still open and whatever the
6067/// fixer declined, so `merge = "pr"` hands the reader the same material
6068/// `magi show` does rather than a pull request that reads clean while
6069/// `run.json` disagrees.
6070///
6071/// The first line doubles as the squash/merge commit subject
6072/// (`manual_merge_command`), which takes it via `message.lines().next()`
6073/// verbatim — so it has to be the task's own opening line, not run/candidate
6074/// bookkeeping. The pull request title (`gh_pr_create`) starts from the same
6075/// line but is further reshaped and truncated by `pr_title` to stay inside
6076/// GitHub's limit; see that function for why. "Merge magi run ec12 (candidate
6077/// B)" told a reader nothing about what landed once the run id had scrolled
6078/// off the PR list. That bookkeeping still needs to be findable, just not
6079/// from the title: the branch name already carries it
6080/// (`RunState::branch_for`), and the footer below repeats it as plain tags
6081/// for a reader holding only the merged commit or the PR body.
6082///
6083/// `state.instruction` can open with blank lines — a `--file` task is passed
6084/// through verbatim (`task_text` only rejects a body that is blank
6085/// *entirely*) — and `.lines().next()` on those reads back as `Some("")`, not
6086/// `None`. `trim_start` drops exactly those leading blank lines so the first
6087/// line is the task's real opening line, and the empty-after-trim case (a
6088/// whitespace-only instruction) falls back the same way `queue::title_from`
6089/// does for the same situation.
6090fn pr_body(state: &RunState, winner: char) -> String {
6091    let instruction = state.instruction.trim_start();
6092    let mut message = if instruction.is_empty() {
6093        "(empty task)".to_owned()
6094    } else {
6095        instruction.to_owned()
6096    };
6097
6098    let open = state.open_findings();
6099    if !open.is_empty() {
6100        message.push_str("\n\n## Open review findings\n\n");
6101        for f in &open {
6102            message.push_str(&format!("- `{}` [{:?}] {}\n", f.id, f.severity, f.title));
6103        }
6104    }
6105
6106    if let Some(fix) = state.reviews.last().and_then(|r| r.fix.as_ref())
6107        && !fix.rejected.is_empty()
6108    {
6109        message.push_str("\n## Declined by the fixer\n\n");
6110        for r in &fix.rejected {
6111            message.push_str(&format!("- `{}`: {}\n", r.id, r.why));
6112        }
6113    }
6114
6115    message.push_str(&format!(
6116        "\n\n---\nmagi:run/{} magi:candidate-{}\n",
6117        state.id,
6118        winner.to_ascii_lowercase()
6119    ));
6120
6121    message
6122}
6123
6124/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
6125/// under the hood, rejects a `title` over 256 characters and the whole
6126/// command fails — no PR at all, for a run whose body was otherwise fine
6127/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
6128/// that limit: `title_from` counts `chars()` (Unicode scalars), which is not
6129/// always how GitHub counts, plus one character for the trailing ellipsis
6130/// `title_from` may add. It is a margin, not a guarantee — a title packed
6131/// with multi-unit characters could still in principle land close to the
6132/// edge, but a real task title's occasional emoji or accented letter fits
6133/// comfortably inside it.
6134const PR_TITLE_MAX: usize = 240;
6135
6136/// The pull request title: the PR body's first line, reshaped and truncated
6137/// by [`queue::title_from`] the same way `magi show`'s task list titles are,
6138/// so it stays inside GitHub's limit on `--title` (see [`PR_TITLE_MAX`]).
6139fn pr_title(body: &str) -> String {
6140    queue::title_from(body, PR_TITLE_MAX)
6141}
6142
6143/// `gh pr create`, returning the PR url.
6144async fn gh_pr_create(cwd: &Path, base: &str, head: &str, body: &str) -> Result<String> {
6145    let title = pr_title(body);
6146    let out = tokio::process::Command::new("gh")
6147        .args([
6148            "pr", "create", "--base", base, "--head", head, "--title", &title, "--body", body,
6149        ])
6150        .current_dir(cwd)
6151        .quiet()
6152        .stdin(std::process::Stdio::null())
6153        .output()
6154        .await
6155        .context("spawn gh")?;
6156    if out.status.success() {
6157        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
6158    } else {
6159        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
6160    }
6161}
6162
6163/// Tear a run's worktrees and branches down.
6164///
6165/// `home` is where the updated `run.json` is saved (via
6166/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
6167/// a housekeeping pass already has its own honest `home` handed to it, and
6168/// falling through to the global here would write back through whichever
6169/// directory some other process or test pinned into that `OnceLock` first,
6170/// not the one the caller actually resolved its `runs` and `state` from.
6171pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
6172    let repo = state.repo.clone();
6173    let root = state.worktree_root();
6174    let winner = state.tally.as_ref().map(|t| t.winner);
6175    let mut removed = Vec::new();
6176
6177    for i in 0..state.candidates.len() {
6178        let c = state.candidates[i].clone();
6179        let is_winner = Some(c.label) == winner;
6180        if is_winner && !drop_winner {
6181            continue;
6182        }
6183        if c.worktree.exists() {
6184            git::worktree_remove(&repo, &c.worktree).await.ok();
6185            removed.push(c.worktree.to_string_lossy().into_owned());
6186        }
6187        if git::branch_exists(&repo, &c.branch).await.unwrap_or(false) {
6188            git::branch_delete(&repo, &c.branch).await.ok();
6189            removed.push(c.branch.clone());
6190        }
6191        state.candidates[i].folded = true;
6192    }
6193
6194    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
6195        let path = name.path();
6196        let keep = !drop_winner
6197            && winner.is_some_and(|w| {
6198                path.file_name()
6199                    .is_some_and(|n| n == format!("cand-{w}").as_str())
6200            });
6201        if keep {
6202            continue;
6203        }
6204        git::worktree_remove(&repo, &path).await.ok();
6205        removed.push(path.to_string_lossy().into_owned());
6206    }
6207
6208    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
6209    // judge worktrees, so once the loop above has cleared all of them out,
6210    // the parent is a bare directory nobody else was ever going to remove -
6211    // git only ever managed what was inside it. Left alone, one of these
6212    // accumulates per fully-folded run; the operator's own machine had 74.
6213    // `remove_if_empty` re-checks rather than assuming: a run whose winner
6214    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
6215    // so does anything a run never claimed that happens to share the bay.
6216    remove_if_empty(&root);
6217
6218    if state.enabled_worktree_config && drop_winner {
6219        // A release, not a raw disable: some sibling run in this repository
6220        // may still hold its own reference (see `git::acquire_worktree_config`),
6221        // and only the last release actually turns the setting back off.
6222        git::release_worktree_config(&repo).await.ok();
6223        state.enabled_worktree_config = false;
6224    }
6225    state.save_under(home)?;
6226    Ok(removed)
6227}
6228
6229/// Remove `dir` if it exists and has nothing in it.
6230///
6231/// Best-effort and silent by design: a directory that is not empty (a run
6232/// whose winner is still parked there, a stray file some other process left)
6233/// is exactly the case this must refuse, and a directory that is already gone
6234/// is not a failure worth reporting either. `std::fs::remove_dir` itself
6235/// already refuses a non-empty directory, so the emptiness check below is
6236/// belt, not suspenders - it is what keeps this from ever attempting the
6237/// removal in the case that matters, rather than trusting `remove_dir`'s
6238/// error path to have no side effects if it ever changed.
6239fn remove_if_empty(dir: &Path) {
6240    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
6241        std::fs::remove_dir(dir).ok();
6242    }
6243}
6244
6245/// Severity of the worst open finding in the last review round, for reporting.
6246pub fn worst_open(state: &RunState) -> Option<Severity> {
6247    state
6248        .reviews
6249        .last()?
6250        .reviews
6251        .iter()
6252        .flat_map(|r| r.findings.iter())
6253        .map(|f| f.severity)
6254        .max()
6255}
6256
6257#[cfg(test)]
6258mod tests {
6259    use super::*;
6260    use crate::run::GateStatus;
6261    use std::collections::BTreeMap;
6262    use std::time::Duration;
6263
6264    fn conductor() -> AgentSpec {
6265        AgentSpec {
6266            id: "conductor".to_owned(),
6267            kind: crate::config::AgentKind::Command,
6268            model: None,
6269            command: vec!["true".to_owned()],
6270            extra_args: Vec::new(),
6271            env: BTreeMap::new(),
6272            prompt_delivery: None,
6273        }
6274    }
6275
6276    fn spec(id: &str) -> AgentSpec {
6277        AgentSpec {
6278            id: id.to_owned(),
6279            kind: crate::config::AgentKind::Command,
6280            model: None,
6281            command: vec!["true".to_owned()],
6282            extra_args: Vec::new(),
6283            env: BTreeMap::new(),
6284            prompt_delivery: None,
6285        }
6286    }
6287
6288    // `next_untried_implementer` is the property `resume_quota_losses`'s own
6289    // fallback loop depends on to terminate: it must walk forward from the
6290    // seat's own position, never restart at the front of the roster, and it
6291    // must never hand back an id already tried, however many times that id
6292    // happens to appear.
6293
6294    #[test]
6295    fn next_untried_implementer_walks_forward_from_the_seats_own_position() {
6296        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
6297        let tried = BTreeSet::from(["beta".to_owned()]);
6298        // beta sits at index 1; the next candidate is gamma, never alpha —
6299        // which is very likely a different candidate slot's own agent.
6300        let next = next_untried_implementer(&roster, 1, &tried);
6301        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
6302    }
6303
6304    #[test]
6305    fn next_untried_implementer_does_not_wrap_back_past_its_own_start() {
6306        let roster = vec![spec("alpha"), spec("beta")];
6307        let tried = BTreeSet::from(["beta".to_owned()]);
6308        // beta is the roster's last entry: nothing follows it, and alpha —
6309        // earlier in the roster, almost certainly a different candidate
6310        // slot's own agent — must not be reached by wrapping back to it.
6311        assert!(next_untried_implementer(&roster, 1, &tried).is_none());
6312    }
6313
6314    #[test]
6315    fn next_untried_implementer_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
6316        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
6317        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
6318        // beta (index 1) and gamma (index 2, the only entry after it) have
6319        // both been tried; alpha (index 0) never has, but it comes before
6320        // beta's own position, so there is nothing further for this seat.
6321        assert!(next_untried_implementer(&roster, 1, &tried).is_none());
6322    }
6323
6324    #[test]
6325    fn next_untried_implementer_skips_ids_already_tried_even_when_duplicated() {
6326        let roster = vec![spec("a"), spec("a"), spec("b")];
6327        let tried = BTreeSet::from(["a".to_owned()]);
6328        let next = next_untried_implementer(&roster, 0, &tried);
6329        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
6330    }
6331
6332    #[test]
6333    fn next_untried_implementer_returns_none_once_every_id_is_tried() {
6334        let roster = vec![spec("a"), spec("b")];
6335        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
6336        assert!(next_untried_implementer(&roster, 0, &tried).is_none());
6337    }
6338
6339    #[test]
6340    fn remove_if_empty_only_ever_takes_a_bare_directory() {
6341        let dir = tempfile::tempdir().unwrap();
6342        let bay = dir.path().join("ffff");
6343
6344        // Not there yet: nothing to do, nothing to panic on.
6345        remove_if_empty(&bay);
6346        assert!(!bay.exists());
6347
6348        // Something still inside - the winner's worktree, or a stray file -
6349        // keeps the directory standing.
6350        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
6351        remove_if_empty(&bay);
6352        assert!(bay.exists(), "non-empty directory must survive");
6353
6354        // Once the last entry is gone, so is the directory itself.
6355        std::fs::remove_dir(bay.join("cand-A")).unwrap();
6356        remove_if_empty(&bay);
6357        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
6358    }
6359
6360    // `round_is_clean` is the exact decision this task fixed: a round with a
6361    // seat that never answered must not read the same as a round every seat
6362    // actually reviewed. These are deterministic and process-free by design —
6363    // the equivalent end-to-end check (a real reviewer timing out under a
6364    // live graph run) is a genuine race against wall-clock contention, and a
6365    // spawn slow enough to blow even a generous budget under a loaded test
6366    // run must not turn this specific regression check flaky.
6367
6368    #[test]
6369    fn a_full_panel_that_found_nothing_is_clean() {
6370        assert!(round_is_clean(
6371            0,
6372            true,
6373            2,
6374            2,
6375            0,
6376            IncompleteReviewPolicy::Block
6377        ));
6378    }
6379
6380    #[test]
6381    fn a_missing_seat_is_never_clean_under_the_default_policy() {
6382        assert!(!round_is_clean(
6383            0,
6384            true,
6385            1,
6386            2,
6387            0,
6388            IncompleteReviewPolicy::Block
6389        ));
6390    }
6391
6392    #[test]
6393    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
6394        assert!(!round_is_clean(
6395            1,
6396            true,
6397            1,
6398            2,
6399            0,
6400            IncompleteReviewPolicy::Warn
6401        ));
6402    }
6403
6404    #[test]
6405    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
6406        assert!(round_is_clean(
6407            0,
6408            true,
6409            1,
6410            2,
6411            0,
6412            IncompleteReviewPolicy::Warn
6413        ));
6414    }
6415
6416    #[test]
6417    fn a_full_panel_with_an_open_finding_is_not_clean() {
6418        assert!(!round_is_clean(
6419            1,
6420            true,
6421            2,
6422            2,
6423            0,
6424            IncompleteReviewPolicy::Block
6425        ));
6426    }
6427
6428    #[test]
6429    fn a_full_panel_with_a_red_e2e_is_not_clean() {
6430        assert!(!round_is_clean(
6431            0,
6432            false,
6433            2,
6434            2,
6435            0,
6436            IncompleteReviewPolicy::Block
6437        ));
6438    }
6439
6440    // The stall this task closes: under the default `block` policy, a seat
6441    // missing only because it was rate limited must not force a wait for a
6442    // session limit that will not lift by the next round. `round_is_clean`
6443    // is where that quorum carve-out lives; the review loop around it never
6444    // changes what a reviewer's vote or a finding's severity means.
6445
6446    #[test]
6447    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
6448        // 1 of 2 answered, and the one missing was quota'd — the exact
6449        // "review-2 rate limited (quota)" shape from the field report.
6450        assert!(round_is_clean(
6451            0,
6452            true,
6453            1,
6454            2,
6455            1,
6456            IncompleteReviewPolicy::Block
6457        ));
6458    }
6459
6460    #[test]
6461    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
6462        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
6463        // not a quota loss (`quota_missing` stays 0) — worth another try.
6464        assert!(!round_is_clean(
6465            0,
6466            true,
6467            1,
6468            2,
6469            0,
6470            IncompleteReviewPolicy::Block
6471        ));
6472    }
6473
6474    #[test]
6475    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
6476        assert!(!round_is_clean(
6477            1,
6478            true,
6479            1,
6480            2,
6481            1,
6482            IncompleteReviewPolicy::Block
6483        ));
6484        assert!(!round_is_clean(
6485            0,
6486            false,
6487            1,
6488            2,
6489            1,
6490            IncompleteReviewPolicy::Block
6491        ));
6492    }
6493
6494    #[test]
6495    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
6496        // Every seat quota'd, nobody answered: there is no panel to decide
6497        // on, so this must fall through to the existing block-and-retry
6498        // fallback rather than call an unreviewed patch clean.
6499        assert!(!round_is_clean(
6500            0,
6501            true,
6502            0,
6503            2,
6504            2,
6505            IncompleteReviewPolicy::Block
6506        ));
6507    }
6508
6509    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
6510        CommandOutcome {
6511            command: "test".to_owned(),
6512            code,
6513            output_tail: String::new(),
6514            duration_ms: 0,
6515            resource_blocked,
6516        }
6517    }
6518
6519    #[test]
6520    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
6521        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
6522        assert!(
6523            !verify_inconclusive(&[outcome(Some(1), false)]),
6524            "an ordinary failure is still evidence about the patch"
6525        );
6526        assert!(verify_inconclusive(&[outcome(None, true)]));
6527        assert!(
6528            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
6529            "one inconclusive outcome taints the whole batch"
6530        );
6531        assert!(!verify_inconclusive(&[]));
6532    }
6533
6534    #[tokio::test]
6535    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
6536        // Alive for the first two checks, then dead - confirms the loop
6537        // actually re-polls rather than deciding once and sleeping out the
6538        // ceiling regardless.
6539        let calls = std::sync::atomic::AtomicUsize::new(0);
6540        let started = Instant::now();
6541        wait_for_pids_with(
6542            &[123],
6543            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
6544            Duration::from_millis(5),
6545            Duration::from_secs(5),
6546        )
6547        .await;
6548        assert!(
6549            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
6550            "must keep checking rather than deciding on the first answer"
6551        );
6552        assert!(
6553            started.elapsed() < Duration::from_secs(1),
6554            "must return the moment it is confirmed dead, not wait out the ceiling"
6555        );
6556    }
6557
6558    #[tokio::test]
6559    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
6560        let started = Instant::now();
6561        wait_for_pids_with(
6562            &[123],
6563            |_| true, // never reports dead
6564            Duration::from_millis(5),
6565            Duration::from_millis(30),
6566        )
6567        .await;
6568        let elapsed = started.elapsed();
6569        assert!(
6570            elapsed >= Duration::from_millis(30),
6571            "must not give up before its own ceiling: {elapsed:?}"
6572        );
6573        assert!(
6574            elapsed < Duration::from_secs(1),
6575            "must not wait past its own ceiling either: {elapsed:?}"
6576        );
6577    }
6578
6579    #[tokio::test]
6580    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
6581        let started = Instant::now();
6582        wait_for_pids_with(
6583            &[],
6584            |_| true,
6585            Duration::from_secs(5),
6586            Duration::from_secs(5),
6587        )
6588        .await;
6589        assert!(
6590            started.elapsed() < Duration::from_millis(200),
6591            "an empty pid list has nothing to confirm"
6592        );
6593    }
6594
6595    // `review_conclusion` is the exact decision the review hand-off task
6596    // fixed: a round budget spent (or a tree that stopped moving) must not
6597    // collapse into `Blocked` regardless of what verification actually
6598    // said. Deterministic and process-free for the same reason the
6599    // `round_is_clean` family above is.
6600    fn review_round(
6601        clean: bool,
6602        blocking: usize,
6603        answered: usize,
6604        expected: usize,
6605        progressed: bool,
6606        e2e_ok: bool,
6607    ) -> ReviewRound {
6608        ReviewRound {
6609            round: 1,
6610            head: "h".to_owned(),
6611            verified_head: None,
6612            verified_at: None,
6613            reviews: Vec::new(),
6614            e2e: vec![CommandOutcome {
6615                command: "test".to_owned(),
6616                code: Some(if e2e_ok { 0 } else { 1 }),
6617                output_tail: String::new(),
6618                duration_ms: 0,
6619                resource_blocked: false,
6620            }],
6621            verify_retried: false,
6622            e2e_deferred: false,
6623            e2e_defer_reason: None,
6624            fix: None,
6625            blocking,
6626            answered,
6627            expected,
6628            clean,
6629            progressed,
6630            vote_split: false,
6631            reconsideration: Vec::new(),
6632            verdict: None,
6633        }
6634    }
6635
6636    #[test]
6637    fn review_conclusion_is_none_when_nothing_has_run() {
6638        assert_eq!(review_conclusion(&[], 3), None);
6639    }
6640
6641    #[test]
6642    fn review_conclusion_is_none_while_rounds_remain() {
6643        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
6644        assert_eq!(review_conclusion(&rounds, 3), None);
6645    }
6646
6647    #[test]
6648    fn review_conclusion_is_gating_once_a_round_is_clean() {
6649        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
6650        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
6651    }
6652
6653    #[test]
6654    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
6655        let rounds = vec![
6656            review_round(false, 1, 2, 2, true, true),
6657            review_round(false, 1, 2, 2, true, true),
6658        ];
6659        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
6660    }
6661
6662    #[test]
6663    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
6664        let rounds = vec![
6665            review_round(false, 1, 2, 2, true, true),
6666            review_round(false, 1, 2, 2, true, false),
6667        ];
6668        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
6669    }
6670
6671    #[test]
6672    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
6673        // Magi never got a command to run against this round's own head — a
6674        // resource-blocked attempt, not a red one — so this must never
6675        // settle on `Blocked` the way a genuine e2e failure would. `None`
6676        // here is what tells `Runner::review_loop` to retry the check
6677        // itself rather than trust this cheap recomputation with a verdict
6678        // it cannot actually produce.
6679        let mut blocked = review_round(false, 1, 2, 2, true, false);
6680        blocked.e2e[0].resource_blocked = true;
6681        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
6682        assert_eq!(review_conclusion(&rounds, 2), None);
6683    }
6684
6685    #[test]
6686    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
6687        // Missing input, not a verified tree — never a hand-off candidate.
6688        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
6689        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
6690    }
6691
6692    #[test]
6693    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
6694        let rounds = vec![
6695            review_round(false, 1, 2, 2, false, true),
6696            review_round(false, 1, 2, 2, false, true),
6697        ];
6698        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
6699    }
6700
6701    fn secs(n: u64) -> Duration {
6702        Duration::from_secs(n)
6703    }
6704
6705    /// A throwaway repo with one commit on `main`, for tests that need `merge`
6706    /// to make real (and, if it runs at all, real*ly fail*) git calls.
6707    fn init_repo(dir: &Path) {
6708        let run = |args: &[&str]| {
6709            let out = std::process::Command::new("git")
6710                .args(args)
6711                .current_dir(dir)
6712                .quiet()
6713                .output()
6714                .expect("spawn git");
6715            assert!(
6716                out.status.success(),
6717                "git {args:?} failed: {}",
6718                String::from_utf8_lossy(&out.stderr)
6719            );
6720        };
6721        run(&["init", "-b", "main"]);
6722        run(&["config", "user.name", "magi test"]);
6723        run(&["config", "user.email", "magi@example.com"]);
6724        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
6725        run(&["add", "-A"]);
6726        run(&["commit", "-m", "init"]);
6727    }
6728
6729    // `settle_questions` is what closes the ghost the phone showed: a run's
6730    // seat asked something, the run then ended, and nothing was left to
6731    // abandon the question it left `open`. `HOME` is a process-wide
6732    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
6733    // first time it runs in the binary — every test below still reaches the
6734    // same directory whichever call won, and each gets its own run id from
6735    // `RunState::new`, so they never collide there.
6736    fn ask_test_home() {
6737        crate::run::set_home(std::env::temp_dir().join("magi-graph-ask-tests-home"));
6738    }
6739
6740    /// A minimal, git-free `Runner` at a given status — `settle_questions`
6741    /// reads nothing else off it.
6742    fn runner_at(status: RunStatus) -> Runner {
6743        let mut state = RunState::new(
6744            PathBuf::from("/nonexistent/repo"),
6745            "main".to_owned(),
6746            "deadbeef".to_owned(),
6747            "task".to_owned(),
6748            Config::default(),
6749        );
6750        state.status = status;
6751        Runner {
6752            state,
6753            roles: ResolvedRoles {
6754                implementers: Vec::new(),
6755                judges: Vec::new(),
6756                reviewers: Vec::new(),
6757                fixer: None,
6758                conductor: conductor(),
6759                implementer_roster: Vec::new(),
6760            },
6761            sem: Arc::new(Semaphore::new(1)),
6762            pause: Pause::new(),
6763            interrupt: Pause::new(),
6764        }
6765    }
6766
6767    /// `park_here` folding in the reason `Pause::park_because` recorded -
6768    /// this is what lets an operator reading a run's events tell an
6769    /// interrupt-driven park from an ordinary shutdown park.
6770    #[test]
6771    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
6772        crate::run::set_home(std::env::temp_dir().join("magi-graph-interrupt-tests-home"));
6773        let mut runner = runner_at(RunStatus::Implementing);
6774        let interrupt = Pause::new();
6775        runner.watch_interrupt(interrupt.clone());
6776
6777        interrupt.park_because("task a1b2 asked to run first");
6778
6779        assert!(runner.park_here().expect("park_here"));
6780        assert!(runner.state.parked);
6781        let last = runner.state.events.last().expect("a park event");
6782        assert_eq!(last.node, "park");
6783        assert!(
6784            last.message.contains("task a1b2 asked to run first"),
6785            "expected the interrupt reason in {:?}",
6786            last.message
6787        );
6788    }
6789
6790    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
6791    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
6792    /// cleared) must not make a *different* run - one only watching its own,
6793    /// unshared interrupt `Pause` - see itself as parked. If a future change
6794    /// ever collapsed these back into one handle, the interrupt scheduler
6795    /// would park every run for the rest of the daemon's life, not just the
6796    /// one it meant to interrupt.
6797    #[test]
6798    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
6799        crate::run::set_home(std::env::temp_dir().join("magi-graph-interrupt-tests-home"));
6800        let mut runner = runner_at(RunStatus::Implementing);
6801        let shutdown = Pause::new();
6802        runner.on_pause(shutdown.clone());
6803        let interrupt = Pause::new();
6804        runner.watch_interrupt(interrupt.clone());
6805
6806        // Nobody has asked for anything yet.
6807        assert!(!runner.park_here().expect("park_here"));
6808        assert!(!runner.state.parked);
6809
6810        // Only the interrupt handle fires; the shutdown handle stays clear.
6811        interrupt.park_because("test");
6812        assert!(!shutdown.parked());
6813        assert!(runner.park_here().expect("park_here"));
6814    }
6815
6816    /// The property every prior attempt at this feature failed to pin down:
6817    /// asking a run to park while one of its nodes has a real, in-flight
6818    /// async operation running (an agent call, in production) must not cut
6819    /// that operation short. `park_here` is only ever consulted *between*
6820    /// `execute`'s node calls - see its own doc - so nothing inside a node
6821    /// can observe a park request until the node itself returns. This proves
6822    /// that structurally, with real `tokio` concurrency and a channel
6823    /// handshake (never a sleep, which would only prove "usually", not
6824    /// "cannot"): the "node" below reports that it has genuinely started,
6825    /// and only then is the park requested; the node still has to be told to
6826    /// finish before `park_here` is ever called, exactly mirroring every
6827    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
6828    /// in `execute`.
6829    #[tokio::test]
6830    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
6831        crate::run::set_home(std::env::temp_dir().join("magi-graph-interrupt-tests-home"));
6832        let mut runner = runner_at(RunStatus::Implementing);
6833        let interrupt = Pause::new();
6834        runner.watch_interrupt(interrupt.clone());
6835
6836        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
6837        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
6838
6839        // Stands in for one node's in-flight agent call: it proves it has
6840        // genuinely started, then blocks - exactly as a spawned CLI process
6841        // does - until told to finish.
6842        let node = async move {
6843            started_tx.send(()).expect("send started");
6844            finish_rx.await.expect("recv finish");
6845            "node finished"
6846        };
6847
6848        let interrupter = async move {
6849            started_rx.await.expect("recv started");
6850            // The call is now genuinely in flight. Ask it to park.
6851            interrupt.park_because("higher-priority task waiting");
6852            // Nothing the node does can observe this yet - there is no
6853            // check inside it, by construction - so let the executor run
6854            // anything pending and then let the node finish on its own.
6855            tokio::task::yield_now().await;
6856            finish_tx.send(()).expect("send finish");
6857        };
6858
6859        let (node_result, ()) = tokio::join!(node, interrupter);
6860        assert_eq!(
6861            node_result, "node finished",
6862            "the in-flight call ran to completion"
6863        );
6864
6865        // Only now, at the boundary the real `execute` would check right
6866        // after this node, does the park take effect.
6867        assert!(runner.park_here().expect("park_here"));
6868        assert!(runner.state.parked);
6869    }
6870
6871    /// A run parked mid-competition carries every field it had accumulated
6872    /// through the exact same disk round-trip an ordinary resume uses -
6873    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
6874    /// Nothing about parking for an interrupt is a special case of that path;
6875    /// this is what proves it rather than assuming it.
6876    #[test]
6877    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
6878        crate::run::set_home(std::env::temp_dir().join("magi-graph-interrupt-tests-home"));
6879        let mut runner = runner_at(RunStatus::Judging);
6880        // `Runner::resume` re-resolves roles from the saved config, which
6881        // refuses an empty roster - give it the same minimal one `conductor`
6882        // itself uses.
6883        runner.state.config.agents = vec![conductor()];
6884        runner.state.candidates = vec![Candidate {
6885            index: 0,
6886            label: 'A',
6887            agent: "alpha".to_owned(),
6888            branch: "magi/x/A".to_owned(),
6889            worktree: PathBuf::from("/nonexistent/worktree"),
6890            summary: "did the thing".to_owned(),
6891            stat: "1 file changed".to_owned(),
6892            files: 1,
6893            commits: 1,
6894            empty: false,
6895            failed: None,
6896            verified_noop: None,
6897            duration_ms: 1234,
6898            folded: false,
6899        }];
6900        let run_id = runner.state.id.clone();
6901
6902        let interrupt = Pause::new();
6903        runner.watch_interrupt(interrupt.clone());
6904        interrupt.park_because("task c3d4 asked to run first");
6905        assert!(runner.park_here().expect("park_here"));
6906
6907        let resumed = Runner::resume(&run_id).expect("resume");
6908        assert_eq!(resumed.state.candidates.len(), 1);
6909        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
6910        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
6911        assert_eq!(resumed.state.status, runner.state.status);
6912        assert!(
6913            resumed.state.parked,
6914            "still parked until `execute` actually walks the graph again"
6915        );
6916        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
6917    }
6918
6919    /// A fresh open question on `run`, stored and handed back for assertions.
6920    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
6921        let mut q = ask::Question::new(
6922            run.to_owned(),
6923            "implement".to_owned(),
6924            "impl-A".to_owned(),
6925            "Which storage backend should the cache use?".to_owned(),
6926            String::new(),
6927            vec!["SQLite".to_owned(), "Redis".to_owned()],
6928        );
6929        store.put(&mut q).unwrap();
6930        q
6931    }
6932
6933    #[test]
6934    fn a_failed_runs_open_question_is_abandoned() {
6935        ask_test_home();
6936        let store = ask::Questions::open();
6937        let mut runner = runner_at(RunStatus::Failed);
6938        let run = runner.state.id.clone();
6939        let q = ask_open_question(&store, &run);
6940
6941        runner.settle_questions();
6942
6943        let back = store.get(&q.id).unwrap();
6944        assert!(
6945            !back.status.open(),
6946            "the seat that asked died with the run; nobody is left to read an answer"
6947        );
6948        assert!(
6949            back.detail.contains(&run) && back.detail.contains("failed"),
6950            "the reason names what the run became, not just that it is gone: {}",
6951            back.detail
6952        );
6953    }
6954
6955    #[test]
6956    fn a_merged_runs_open_question_is_abandoned_too() {
6957        ask_test_home();
6958        let store = ask::Questions::open();
6959        // A run that finishes cleanly still leaves nobody to read an answer -
6960        // this is not only a failure-path cleanup.
6961        for status in [RunStatus::Merged, RunStatus::Ready] {
6962            let mut runner = runner_at(status);
6963            let run = runner.state.id.clone();
6964            let q = ask_open_question(&store, &run);
6965
6966            runner.settle_questions();
6967
6968            let back = store.get(&q.id).unwrap();
6969            assert!(
6970                !back.status.open(),
6971                "{status:?} run's question must not outlive the run"
6972            );
6973        }
6974    }
6975
6976    #[test]
6977    fn a_still_resumable_runs_open_question_is_left_alone() {
6978        ask_test_home();
6979        let store = ask::Questions::open();
6980        // `Blocked` and `Stalled` can still be resumed — the candidates, the
6981        // review round and the seat sessions are all still on disk — so a
6982        // question asked mid-round may yet get a real answer from a real
6983        // resume. Sweeping it here would be exactly the failure mode this
6984        // whole feature exists to avoid on the other side.
6985        for status in [RunStatus::Blocked, RunStatus::Stalled] {
6986            let mut runner = runner_at(status);
6987            let run = runner.state.id.clone();
6988            let q = ask_open_question(&store, &run);
6989
6990            runner.settle_questions();
6991
6992            let back = store.get(&q.id).unwrap();
6993            assert!(
6994                back.status.open(),
6995                "{status:?} is still alive; the question must still be waiting"
6996            );
6997        }
6998    }
6999
7000    #[test]
7001    fn settle_questions_never_touches_an_already_answered_question() {
7002        ask_test_home();
7003        let store = ask::Questions::open();
7004        let mut runner = runner_at(RunStatus::Failed);
7005        let run = runner.state.id.clone();
7006        let mut q = ask_open_question(&store, &run);
7007        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
7008            .unwrap();
7009        store.put(&mut q).unwrap();
7010
7011        // Called twice, the way a crash-recovered daemon reclaim and the
7012        // graph's own cleanup both can for the same run — `abandon_for_run`
7013        // only ever touches what is still open, so this must be inert both
7014        // times, not merely the second.
7015        runner.settle_questions();
7016        runner.settle_questions();
7017
7018        let back = store.get(&q.id).unwrap();
7019        assert_eq!(
7020            back.status,
7021            ask::QuestionStatus::Answered,
7022            "a real answer is a decision on record, never overwritten by a sweep"
7023        );
7024    }
7025
7026    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
7027    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
7028    /// without merging, whose winner is still the operator's answer to read.
7029    /// Nothing previously called `fold_run` itself with a real `tally`, so
7030    /// this is the first test to pin down the one distinction the whole
7031    /// automatic-fold feature depends on: the winner's worktree and branch
7032    /// must survive, everything else sharing the run's worktree bay - a
7033    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
7034    /// second sweep treats every non-winner directory under the bay alike -
7035    /// must not.
7036    #[tokio::test]
7037    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
7038        crate::run::set_home(std::env::temp_dir().join("magi-graph-fold-run-tests-home"));
7039        let tmp = tempfile::tempdir().expect("tempdir");
7040        let repo = tmp.path().join("repo");
7041        std::fs::create_dir_all(&repo).unwrap();
7042        init_repo(&repo);
7043
7044        let mut config = Config::default();
7045        config.graph.worktree_root = Some(tmp.path().join("wt"));
7046
7047        let mut state = RunState::new(
7048            repo.clone(),
7049            "main".to_owned(),
7050            "deadbeef".to_owned(),
7051            "task".to_owned(),
7052            config,
7053        );
7054        let root = state.worktree_root();
7055        let wt_a = root.join("cand-A");
7056        let wt_b = root.join("cand-B");
7057        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
7058            .await
7059            .expect("worktree A");
7060        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
7061            .await
7062            .expect("worktree B");
7063
7064        state.candidates = vec![
7065            Candidate {
7066                index: 0,
7067                label: 'A',
7068                agent: "alpha".to_owned(),
7069                branch: "magi/x/A".to_owned(),
7070                worktree: wt_a.clone(),
7071                summary: String::new(),
7072                stat: String::new(),
7073                files: 0,
7074                commits: 0,
7075                empty: false,
7076                failed: None,
7077                verified_noop: None,
7078                duration_ms: 0,
7079                folded: false,
7080            },
7081            Candidate {
7082                index: 1,
7083                label: 'B',
7084                agent: "beta".to_owned(),
7085                branch: "magi/x/B".to_owned(),
7086                worktree: wt_b.clone(),
7087                summary: String::new(),
7088                stat: String::new(),
7089                files: 0,
7090                commits: 0,
7091                empty: false,
7092                failed: None,
7093                verified_noop: None,
7094                duration_ms: 0,
7095                folded: false,
7096            },
7097        ];
7098        state.tally = Some(Tally {
7099            first_choice: BTreeMap::from([('A', 1)]),
7100            borda: BTreeMap::new(),
7101            winner: 'A',
7102            rankings: 1,
7103            unanimous_initial: true,
7104            deliberated: false,
7105            changed_votes: 0,
7106            unanimous_final: true,
7107            tie_break: None,
7108            judges: 1,
7109            present: 1,
7110            quorum: 1,
7111            met_quorum: true,
7112            uncontested: None,
7113        });
7114        state.status = RunStatus::Ready;
7115
7116        fold_run(&mut state, false, &crate::run::home())
7117            .await
7118            .expect("fold_run");
7119
7120        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
7121        assert!(
7122            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
7123            "the unmerged winner's branch survives"
7124        );
7125        assert!(
7126            !state.candidates[0].folded,
7127            "the winner is not marked folded"
7128        );
7129
7130        assert!(!wt_b.exists(), "the loser's worktree is removed");
7131        assert!(
7132            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
7133            "the loser's branch is removed"
7134        );
7135        assert!(state.candidates[1].folded, "the loser is marked folded");
7136    }
7137
7138    /// `status == Ready` used to be read as "this is the harmless
7139    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
7140    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
7141    /// run's PR was closed without merging — and reentering `merge` with
7142    /// `mode` still `Pr` does not know the difference, so it pushed and
7143    /// opened a second pull request. `mode == Local` reproduces the same
7144    /// blind spot without a network call: reentry must not attempt another
7145    /// git merge once this node has already recorded an outcome.
7146    #[tokio::test]
7147    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
7148        let tmp = tempfile::tempdir().expect("tempdir");
7149        let repo = tmp.path().join("repo");
7150        std::fs::create_dir_all(&repo).unwrap();
7151        init_repo(&repo);
7152
7153        let mut config = Config::default();
7154        config.merge.mode = MergeMode::Local;
7155
7156        let mut state = RunState::new(
7157            repo.clone(),
7158            "main".to_owned(),
7159            "deadbeef".to_owned(),
7160            "task".to_owned(),
7161            config,
7162        );
7163        state.candidates = vec![Candidate {
7164            index: 0,
7165            label: 'A',
7166            agent: "alpha".to_owned(),
7167            branch: "does-not-exist".to_owned(),
7168            worktree: repo.clone(),
7169            summary: String::new(),
7170            stat: String::new(),
7171            files: 0,
7172            commits: 0,
7173            empty: false,
7174            failed: None,
7175            verified_noop: None,
7176            duration_ms: 0,
7177            folded: false,
7178        }];
7179        state.tally = Some(Tally {
7180            first_choice: BTreeMap::from([('A', 1)]),
7181            borda: BTreeMap::new(),
7182            winner: 'A',
7183            rankings: 1,
7184            unanimous_initial: true,
7185            deliberated: false,
7186            changed_votes: 0,
7187            unanimous_final: true,
7188            tie_break: None,
7189            judges: 0,
7190            present: 0,
7191            quorum: 0,
7192            met_quorum: true,
7193            uncontested: Some("only candidate A produced a change".to_owned()),
7194        });
7195        state.reviews = vec![ReviewRound {
7196            round: 1,
7197            head: "deadbeef".to_owned(),
7198            verified_head: None,
7199            verified_at: None,
7200            reviews: Vec::new(),
7201            e2e: Vec::new(),
7202            fix: None,
7203            blocking: 0,
7204            answered: 0,
7205            expected: 0,
7206            clean: true,
7207            verify_retried: false,
7208            e2e_deferred: false,
7209            e2e_defer_reason: None,
7210            progressed: false,
7211            vote_split: false,
7212            reconsideration: Vec::new(),
7213            verdict: None,
7214        }];
7215        state.gate = vec![CommandOutcome {
7216            command: "test".to_owned(),
7217            code: Some(0),
7218            output_tail: String::new(),
7219            duration_ms: 0,
7220            resource_blocked: false,
7221        }];
7222        state.gate_ran = true;
7223        // Reached its conclusion already — e.g. `land` closing the PR without
7224        // merging it, which (like the honest `MergeMode::None` path) leaves
7225        // `status` at `Ready`. The recorded outcome is what actually marks
7226        // this node done.
7227        state.status = RunStatus::Ready;
7228        state.merge = Some(MergeOutcome {
7229            mode: MergeMode::Local,
7230            ok: false,
7231            detail: "already concluded".to_owned(),
7232        });
7233
7234        let mut runner = Runner {
7235            state,
7236            roles: ResolvedRoles {
7237                implementers: Vec::new(),
7238                judges: Vec::new(),
7239                reviewers: Vec::new(),
7240                fixer: None,
7241                conductor: conductor(),
7242                implementer_roster: Vec::new(),
7243            },
7244            sem: Arc::new(Semaphore::new(1)),
7245            pause: Pause::new(),
7246            interrupt: Pause::new(),
7247        };
7248
7249        runner.merge().await.expect("merge");
7250
7251        assert_eq!(
7252            runner.state.status,
7253            RunStatus::Ready,
7254            "a concluded run's status must not change on reentry"
7255        );
7256        assert_eq!(
7257            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
7258            Some("already concluded"),
7259            "merge must not run again once the node already recorded an outcome"
7260        );
7261    }
7262
7263    /// `gate` leaves `state.gate_ran` false both before it has ever run and
7264    /// when its last attempt was resource-blocked (the shared build cache
7265    /// could not be acquired or confirmed fresh in time - see
7266    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
7267    /// `Vec` this also leaves behind used to read as "nothing failed" and let
7268    /// a run merge a tree the gate never actually checked - exactly the case
7269    /// a contended cache produces on every retry until it clears. `merge`
7270    /// must refuse until `gate` has actually recorded an attempt.
7271    #[tokio::test]
7272    async fn merge_refuses_a_gate_that_has_not_actually_run() {
7273        let tmp = tempfile::tempdir().expect("tempdir");
7274        let repo = tmp.path().join("repo");
7275        std::fs::create_dir_all(&repo).unwrap();
7276        init_repo(&repo);
7277
7278        let mut config = Config::default();
7279        config.merge.mode = MergeMode::Local;
7280
7281        let mut state = RunState::new(
7282            repo.clone(),
7283            "main".to_owned(),
7284            "deadbeef".to_owned(),
7285            "task".to_owned(),
7286            config,
7287        );
7288        state.candidates = vec![Candidate {
7289            index: 0,
7290            label: 'A',
7291            agent: "alpha".to_owned(),
7292            branch: "does-not-exist".to_owned(),
7293            worktree: repo.clone(),
7294            summary: String::new(),
7295            stat: String::new(),
7296            files: 0,
7297            commits: 0,
7298            empty: false,
7299            failed: None,
7300            verified_noop: None,
7301            duration_ms: 0,
7302            folded: false,
7303        }];
7304        state.tally = Some(Tally {
7305            first_choice: BTreeMap::from([('A', 1)]),
7306            borda: BTreeMap::new(),
7307            winner: 'A',
7308            rankings: 1,
7309            unanimous_initial: true,
7310            deliberated: false,
7311            changed_votes: 0,
7312            unanimous_final: true,
7313            tie_break: None,
7314            judges: 0,
7315            present: 0,
7316            quorum: 0,
7317            met_quorum: true,
7318            uncontested: Some("only candidate A produced a change".to_owned()),
7319        });
7320        state.reviews = vec![ReviewRound {
7321            round: 1,
7322            head: "deadbeef".to_owned(),
7323            verified_head: None,
7324            verified_at: None,
7325            reviews: Vec::new(),
7326            e2e: Vec::new(),
7327            fix: None,
7328            blocking: 0,
7329            answered: 0,
7330            expected: 0,
7331            clean: true,
7332            verify_retried: false,
7333            e2e_deferred: false,
7334            e2e_defer_reason: None,
7335            progressed: false,
7336            vote_split: false,
7337            reconsideration: Vec::new(),
7338            verdict: None,
7339        }];
7340        // The point: `gate` has not recorded anything yet.
7341        state.gate = Vec::new();
7342        state.gate_ran = false;
7343        state.status = RunStatus::Gating;
7344
7345        let mut runner = Runner {
7346            state,
7347            roles: ResolvedRoles {
7348                implementers: Vec::new(),
7349                judges: Vec::new(),
7350                reviewers: Vec::new(),
7351                fixer: None,
7352                conductor: conductor(),
7353                implementer_roster: Vec::new(),
7354            },
7355            sem: Arc::new(Semaphore::new(1)),
7356            pause: Pause::new(),
7357            interrupt: Pause::new(),
7358        };
7359
7360        runner.merge().await.expect("merge");
7361
7362        assert!(
7363            runner.state.merge.is_none(),
7364            "an empty gate must never be read as a passing one: {:?}",
7365            runner.state.merge
7366        );
7367    }
7368
7369    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
7370    /// commands configured and `merge.mode` is `none` (a review-only run).
7371    /// `gate` must still record a real attempt — zero commands, vacuously
7372    /// passed — rather than leaving `state.gate` empty in a way `merge`
7373    /// cannot tell apart from "never ran"; otherwise the run reaches
7374    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
7375    #[tokio::test]
7376    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
7377        let tmp = tempfile::tempdir().expect("tempdir");
7378        let repo = tmp.path().join("repo");
7379        std::fs::create_dir_all(&repo).unwrap();
7380        init_repo(&repo);
7381
7382        // Default config: `verify.gate` empty, `merge.mode` is `none`.
7383        let config = Config::default();
7384
7385        let mut state = RunState::new(
7386            repo.clone(),
7387            "main".to_owned(),
7388            "deadbeef".to_owned(),
7389            "task".to_owned(),
7390            config,
7391        );
7392        state.candidates = vec![Candidate {
7393            index: 0,
7394            label: 'A',
7395            agent: "alpha".to_owned(),
7396            branch: "does-not-exist".to_owned(),
7397            worktree: repo.clone(),
7398            summary: String::new(),
7399            stat: String::new(),
7400            files: 0,
7401            commits: 0,
7402            empty: false,
7403            failed: None,
7404            verified_noop: None,
7405            duration_ms: 0,
7406            folded: false,
7407        }];
7408        state.tally = Some(Tally {
7409            first_choice: BTreeMap::from([('A', 1)]),
7410            borda: BTreeMap::new(),
7411            winner: 'A',
7412            rankings: 1,
7413            unanimous_initial: true,
7414            deliberated: false,
7415            changed_votes: 0,
7416            unanimous_final: true,
7417            tie_break: None,
7418            judges: 0,
7419            present: 0,
7420            quorum: 0,
7421            met_quorum: true,
7422            uncontested: Some("only candidate A produced a change".to_owned()),
7423        });
7424        state.reviews = vec![ReviewRound {
7425            round: 1,
7426            head: "deadbeef".to_owned(),
7427            verified_head: None,
7428            verified_at: None,
7429            reviews: Vec::new(),
7430            e2e: Vec::new(),
7431            fix: None,
7432            blocking: 0,
7433            answered: 0,
7434            expected: 0,
7435            clean: true,
7436            verify_retried: false,
7437            e2e_deferred: false,
7438            e2e_defer_reason: None,
7439            progressed: false,
7440            vote_split: false,
7441            reconsideration: Vec::new(),
7442            verdict: None,
7443        }];
7444
7445        let mut runner = Runner {
7446            state,
7447            roles: ResolvedRoles {
7448                implementers: Vec::new(),
7449                judges: Vec::new(),
7450                reviewers: Vec::new(),
7451                fixer: None,
7452                conductor: conductor(),
7453                implementer_roster: Vec::new(),
7454            },
7455            sem: Arc::new(Semaphore::new(1)),
7456            pause: Pause::new(),
7457            interrupt: Pause::new(),
7458        };
7459
7460        runner.gate().await.expect("gate");
7461        assert!(
7462            runner.state.gate_ran,
7463            "zero configured commands is still a real attempt, not an unrun gate"
7464        );
7465        assert!(runner.state.gate.is_empty());
7466        assert_eq!(runner.state.gate_status(), GateStatus::PassedWithNoCommands);
7467        assert_ne!(
7468            runner.state.status,
7469            RunStatus::Blocked,
7470            "a gate with nothing to check must not read as failed"
7471        );
7472
7473        runner.merge().await.expect("merge");
7474        assert_eq!(
7475            runner.state.status,
7476            RunStatus::Ready,
7477            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
7478        );
7479    }
7480
7481    /// `Config::cache_dir` is derived from `verify.e2e` as well as
7482    /// `verify.gate` (so the e2e leg and the final gate never build against
7483    /// different directories). With zero `verify.gate` commands but a
7484    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
7485    /// that lease before discovering it had nothing to run - so a repo with
7486    /// no gate commands could come back `resource_blocked` (and therefore
7487    /// still `gate_ran == false`) on nothing but an unrelated run holding the
7488    /// cache, exactly the contention this run's own zero commands could
7489    /// never have touched. `gate` must recognise there is nothing to check
7490    /// before it ever asks for the lease.
7491    #[tokio::test]
7492    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
7493        crate::run::set_home(std::env::temp_dir().join("magi-graph-test-home"));
7494        let home = crate::run::home();
7495
7496        let tmp = tempfile::tempdir().expect("tempdir");
7497        let repo = tmp.path().join("repo");
7498        std::fs::create_dir_all(&repo).unwrap();
7499        init_repo(&repo);
7500        // Unique to this test, so holding its lease cannot collide with
7501        // another test sharing the same process-wide `home`.
7502        let cache_dir = tmp.path().join("target");
7503
7504        let mut config = Config::default();
7505        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
7506        // `verify.gate` stays empty (the default). Bounded so a regression
7507        // that does start waiting fails the test in seconds, not hangs it.
7508        config.graph.timeout_verify = Some(2);
7509
7510        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
7511        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
7512            .expect("no io error acquiring directly")
7513        {
7514            crate::cache::AcquireOutcome::Acquired(g) => g,
7515            crate::cache::AcquireOutcome::Busy(b) => {
7516                panic!("expected the direct acquire to win the lease first: {b:?}")
7517            }
7518        };
7519
7520        let mut state = RunState::new(
7521            repo.clone(),
7522            "main".to_owned(),
7523            "deadbeef".to_owned(),
7524            "task".to_owned(),
7525            config,
7526        );
7527        state.candidates = vec![Candidate {
7528            index: 0,
7529            label: 'A',
7530            agent: "alpha".to_owned(),
7531            branch: "does-not-exist".to_owned(),
7532            worktree: repo.clone(),
7533            summary: String::new(),
7534            stat: String::new(),
7535            files: 0,
7536            commits: 0,
7537            empty: false,
7538            failed: None,
7539            verified_noop: None,
7540            duration_ms: 0,
7541            folded: false,
7542        }];
7543        state.tally = Some(Tally {
7544            first_choice: BTreeMap::from([('A', 1)]),
7545            borda: BTreeMap::new(),
7546            winner: 'A',
7547            rankings: 1,
7548            unanimous_initial: true,
7549            deliberated: false,
7550            changed_votes: 0,
7551            unanimous_final: true,
7552            tie_break: None,
7553            judges: 0,
7554            present: 0,
7555            quorum: 0,
7556            met_quorum: true,
7557            uncontested: Some("only candidate A produced a change".to_owned()),
7558        });
7559        state.reviews = vec![ReviewRound {
7560            round: 1,
7561            head: "deadbeef".to_owned(),
7562            verified_head: None,
7563            verified_at: None,
7564            reviews: Vec::new(),
7565            e2e: Vec::new(),
7566            fix: None,
7567            blocking: 0,
7568            answered: 0,
7569            expected: 0,
7570            clean: true,
7571            verify_retried: false,
7572            e2e_deferred: false,
7573            e2e_defer_reason: None,
7574            progressed: false,
7575            vote_split: false,
7576            reconsideration: Vec::new(),
7577            verdict: None,
7578        }];
7579
7580        let mut runner = Runner {
7581            state,
7582            roles: ResolvedRoles {
7583                implementers: Vec::new(),
7584                judges: Vec::new(),
7585                reviewers: Vec::new(),
7586                fixer: None,
7587                conductor: conductor(),
7588                implementer_roster: Vec::new(),
7589            },
7590            sem: Arc::new(Semaphore::new(1)),
7591            pause: Pause::new(),
7592            interrupt: Pause::new(),
7593        };
7594
7595        let started = std::time::Instant::now();
7596        runner.gate().await.expect("gate");
7597        assert!(
7598            started.elapsed() < Duration::from_secs(1),
7599            "a gate with nothing to run must never wait on a lease it never needed"
7600        );
7601        assert!(
7602            runner.state.gate_ran,
7603            "zero commands is still a real, immediate attempt"
7604        );
7605        assert!(runner.state.gate.is_empty());
7606        assert_ne!(
7607            runner.state.status,
7608            RunStatus::Blocked,
7609            "must not read as resource-blocked on a lease it never asked for"
7610        );
7611    }
7612
7613    /// The addendum's second gap: a `verify.gate` command running for real
7614    /// wall-clock time had nothing at all to show for it in `active` before
7615    /// `run_commands` learned to record it — a run could sit in `Gating` for
7616    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
7617    /// what was actually happening. Proven with a genuinely still-running
7618    /// command, not just a before/after check on the final state: a poller
7619    /// task reads the same `run.json` `gate()` is writing, the same way the
7620    /// phone or `magi show` would, while the shell command is still blocked
7621    /// on its own release marker.
7622    #[tokio::test]
7623    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
7624        crate::run::set_home(std::env::temp_dir().join("magi-graph-test-home"));
7625
7626        let tmp = tempfile::tempdir().expect("tempdir");
7627        let repo = tmp.path().join("repo");
7628        std::fs::create_dir_all(&repo).unwrap();
7629        init_repo(&repo);
7630
7631        let mut config = Config::default();
7632        config.verify.gate = vec![
7633            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
7634             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done"
7635                .to_owned(),
7636        ];
7637
7638        let mut state = RunState::new(
7639            repo.clone(),
7640            "main".to_owned(),
7641            "deadbeef".to_owned(),
7642            "task".to_owned(),
7643            config,
7644        );
7645        let run_id = state.id.clone();
7646        state.candidates = vec![Candidate {
7647            index: 0,
7648            label: 'A',
7649            agent: "alpha".to_owned(),
7650            branch: "does-not-exist".to_owned(),
7651            worktree: repo.clone(),
7652            summary: String::new(),
7653            stat: String::new(),
7654            files: 0,
7655            commits: 0,
7656            empty: false,
7657            failed: None,
7658            verified_noop: None,
7659            duration_ms: 0,
7660            folded: false,
7661        }];
7662        state.tally = Some(Tally {
7663            first_choice: BTreeMap::from([('A', 1)]),
7664            borda: BTreeMap::new(),
7665            winner: 'A',
7666            rankings: 1,
7667            unanimous_initial: true,
7668            deliberated: false,
7669            changed_votes: 0,
7670            unanimous_final: true,
7671            tie_break: None,
7672            judges: 0,
7673            present: 0,
7674            quorum: 0,
7675            met_quorum: true,
7676            uncontested: Some("only candidate A produced a change".to_owned()),
7677        });
7678        state.reviews = vec![ReviewRound {
7679            round: 1,
7680            head: "deadbeef".to_owned(),
7681            verified_head: None,
7682            verified_at: None,
7683            reviews: Vec::new(),
7684            e2e: Vec::new(),
7685            fix: None,
7686            blocking: 0,
7687            answered: 0,
7688            expected: 0,
7689            clean: true,
7690            verify_retried: false,
7691            e2e_deferred: false,
7692            e2e_defer_reason: None,
7693            progressed: false,
7694            vote_split: false,
7695            reconsideration: Vec::new(),
7696            verdict: None,
7697        }];
7698
7699        let mut runner = Runner {
7700            state,
7701            roles: ResolvedRoles {
7702                implementers: Vec::new(),
7703                judges: Vec::new(),
7704                reviewers: Vec::new(),
7705                fixer: None,
7706                conductor: conductor(),
7707                implementer_roster: Vec::new(),
7708            },
7709            sem: Arc::new(Semaphore::new(1)),
7710            pause: Pause::new(),
7711            interrupt: Pause::new(),
7712        };
7713
7714        let started_marker = repo.join("started.marker");
7715        let release_marker = repo.join("release.marker");
7716        let poller = tokio::spawn(async move {
7717            // Bounded so a regression that never records the task entry
7718            // fails this test in seconds instead of hanging the suite —
7719            // the same shape `a_park_requested_while_a_seat_is_mid_call_
7720            // does_not_cut_it_short` uses for the same reason.
7721            for _ in 0..100 {
7722                if started_marker.exists()
7723                    && let Ok(s) = crate::run::RunState::load(&run_id)
7724                    && let Some(a) = s.active.get("gate")
7725                {
7726                    std::fs::write(&release_marker, b"go").expect("release marker");
7727                    return Some(a.clone());
7728                }
7729                tokio::time::sleep(Duration::from_millis(50)).await;
7730            }
7731            None
7732        });
7733
7734        runner.gate().await.expect("gate");
7735        let captured = poller.await.expect("poller task");
7736        let captured = captured.expect(
7737            "the poller never saw a `gate` task entry in run.json while the command was \
7738             still blocked on its own release marker",
7739        );
7740
7741        assert_eq!(captured.task.as_deref(), Some("gate"));
7742        assert_eq!(captured.node, "gate");
7743        assert_eq!(captured.index, Some(1));
7744        assert_eq!(captured.total, Some(1));
7745        assert!(
7746            captured
7747                .command
7748                .as_deref()
7749                .is_some_and(|c| c.contains("started.marker")),
7750            "{captured:?}"
7751        );
7752
7753        assert!(
7754            runner.state.active.is_empty(),
7755            "the entry must be cleared once the command actually finished: {:?}",
7756            runner.state.active
7757        );
7758        assert!(runner.state.gate_ran);
7759        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
7760    }
7761
7762    /// The shape the incident this whole fix responds to actually had: the
7763    /// round budget spent, the last round's own e2e blocked on the shared
7764    /// build cache (held here by a live pid — this test process — exactly
7765    /// `cache`'s own unit tests' pattern for "another owner, still alive"
7766    /// without forking a process). `stop_reviewing` must retry it — not
7767    /// silently leave the round looking untouched (the catch-up-only half of
7768    /// the bug), and not read the contention as a red `e2e` and block the
7769    /// run on it (the other half). Called directly, the same way
7770    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
7771    /// above exercises `gate`, so this never needs a real cargo build to
7772    /// reach: the lease is never released, so `with_cache_lease` never gets
7773    /// past acquiring it into anything that would need a real workspace.
7774    #[tokio::test]
7775    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
7776        crate::run::set_home(std::env::temp_dir().join("magi-graph-test-home"));
7777        let home = crate::run::home();
7778
7779        let tmp = tempfile::tempdir().expect("tempdir");
7780        let repo = tmp.path().join("repo");
7781        std::fs::create_dir_all(&repo).unwrap();
7782        init_repo(&repo);
7783        let head = crate::git::rev_parse(&repo, "HEAD")
7784            .await
7785            .expect("rev-parse");
7786        // Unique to this test, so holding its lease cannot collide with
7787        // another test sharing the same process-wide `home`.
7788        let cache_dir = tmp.path().join("target");
7789
7790        let mut config = Config::default();
7791        config.verify.e2e = vec![format!(
7792            "CARGO_TARGET_DIR='{}' test -f README.md",
7793            cache_dir.display()
7794        )];
7795        config.graph.review_rounds = 1;
7796        // Bounded so a regression that does start waiting fails the test in
7797        // seconds, not hangs it.
7798        config.graph.timeout_verify = Some(2);
7799
7800        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
7801        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
7802            .expect("no io error acquiring directly")
7803        {
7804            crate::cache::AcquireOutcome::Acquired(g) => g,
7805            crate::cache::AcquireOutcome::Busy(b) => {
7806                panic!("expected the direct acquire to win the lease first: {b:?}")
7807            }
7808        };
7809
7810        let mut state = RunState::new(
7811            repo.clone(),
7812            "main".to_owned(),
7813            head.clone(),
7814            "task".to_owned(),
7815            config,
7816        );
7817        state.candidates = vec![Candidate {
7818            index: 0,
7819            label: 'A',
7820            agent: "alpha".to_owned(),
7821            branch: "does-not-exist".to_owned(),
7822            worktree: repo.clone(),
7823            summary: String::new(),
7824            stat: String::new(),
7825            files: 0,
7826            commits: 0,
7827            empty: false,
7828            failed: None,
7829            verified_noop: None,
7830            duration_ms: 0,
7831            folded: false,
7832        }];
7833        state.tally = Some(Tally {
7834            first_choice: BTreeMap::from([('A', 1)]),
7835            borda: BTreeMap::new(),
7836            winner: 'A',
7837            rankings: 1,
7838            unanimous_initial: true,
7839            deliberated: false,
7840            changed_votes: 0,
7841            unanimous_final: true,
7842            tie_break: None,
7843            judges: 0,
7844            present: 0,
7845            quorum: 0,
7846            met_quorum: true,
7847            uncontested: Some("only candidate A produced a change".to_owned()),
7848        });
7849        // The round budget's last round, deferred: `needs_catchup_run`'s
7850        // other trigger. `stop_reviewing`'s retry machinery must treat this
7851        // exactly like a resource-blocked attempt once it actually runs.
7852        state.reviews = vec![ReviewRound {
7853            round: 1,
7854            head: head.clone(),
7855            verified_head: None,
7856            verified_at: None,
7857            reviews: Vec::new(),
7858            e2e: Vec::new(),
7859            fix: None,
7860            blocking: 1,
7861            answered: 1,
7862            expected: 1,
7863            clean: false,
7864            verify_retried: false,
7865            e2e_deferred: true,
7866            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
7867            progressed: false,
7868            vote_split: false,
7869            reconsideration: Vec::new(),
7870            verdict: None,
7871        }];
7872
7873        let mut runner = Runner {
7874            state,
7875            roles: ResolvedRoles {
7876                implementers: Vec::new(),
7877                judges: Vec::new(),
7878                reviewers: Vec::new(),
7879                fixer: None,
7880                conductor: conductor(),
7881                implementer_roster: Vec::new(),
7882            },
7883            sem: Arc::new(Semaphore::new(1)),
7884            pause: Pause::new(),
7885            interrupt: Pause::new(),
7886        };
7887
7888        let shell = runner.state.config.shell();
7889        runner
7890            .stop_reviewing("round budget spent", &shell, &repo)
7891            .await
7892            .expect("stop_reviewing");
7893
7894        let last = runner.state.reviews.last().expect("round record");
7895        assert_eq!(
7896            last.e2e_status(),
7897            E2eStatus::ResourceBlocked,
7898            "the shared cache is still held; the attempt must read as blocked, not deferred or \
7899             failed: {last:?}"
7900        );
7901        assert_eq!(
7902            last.verified_head.as_deref(),
7903            Some(head.as_str()),
7904            "which commit this attempt targeted is known even though nothing finished checking \
7905             it"
7906        );
7907        let first_attempt_at = last
7908            .verified_at
7909            .expect("when this attempt ran is known too");
7910        assert_ne!(
7911            runner.state.status,
7912            RunStatus::Blocked,
7913            "contention is evidence about the machine, not the patch — it must not settle the \
7914             run as blocked: {:?}",
7915            runner.state.status
7916        );
7917        assert!(
7918            !runner
7919                .state
7920                .events
7921                .iter()
7922                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
7923            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
7924            runner.state.events
7925        );
7926
7927        // The cache is still held: a later reentry must retry the same
7928        // round's verification again — not leave it looking exactly as
7929        // untouched as the first blocked attempt, which is indistinguishable
7930        // from never having tried again at all.
7931        runner
7932            .stop_reviewing("round budget spent", &shell, &repo)
7933            .await
7934            .expect("stop_reviewing retry");
7935        assert_eq!(
7936            runner.state.reviews.len(),
7937            1,
7938            "no new round was started: {:?}",
7939            runner.state.reviews
7940        );
7941        let last = runner.state.reviews.last().expect("round record");
7942        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
7943        assert!(
7944            last.verified_at.expect("still known") > first_attempt_at,
7945            "a second reentry must be a fresh attempt, not a stale copy of the first"
7946        );
7947        assert_ne!(runner.state.status, RunStatus::Blocked);
7948
7949        held.release();
7950    }
7951
7952    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
7953    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
7954    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
7955    /// own top-of-function fast path (`review_conclusion`) correctly reads
7956    /// this shape as `None` rather than guessing `Blocked`, and the loop's
7957    /// own `for` range is empty once the round budget is spent, so
7958    /// `review_loop` must retry the check itself rather than silently doing
7959    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
7960    /// above exercises directly, but through `review_loop`'s own entry point
7961    /// this time, proving the wiring between the two rather than just the
7962    /// retry logic in isolation.
7963    #[tokio::test]
7964    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
7965        crate::run::set_home(std::env::temp_dir().join("magi-graph-test-home"));
7966        let home = crate::run::home();
7967
7968        let tmp = tempfile::tempdir().expect("tempdir");
7969        let repo = tmp.path().join("repo");
7970        std::fs::create_dir_all(&repo).unwrap();
7971        init_repo(&repo);
7972        let head = crate::git::rev_parse(&repo, "HEAD")
7973            .await
7974            .expect("rev-parse");
7975        let cache_dir = tmp.path().join("target");
7976
7977        let mut config = Config::default();
7978        config.verify.e2e = vec![format!(
7979            "CARGO_TARGET_DIR='{}' test -f README.md",
7980            cache_dir.display()
7981        )];
7982        config.graph.review_rounds = 1;
7983        config.graph.timeout_verify = Some(2);
7984
7985        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
7986        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
7987            .expect("no io error acquiring directly")
7988        {
7989            crate::cache::AcquireOutcome::Acquired(g) => g,
7990            crate::cache::AcquireOutcome::Busy(b) => {
7991                panic!("expected the direct acquire to win the lease first: {b:?}")
7992            }
7993        };
7994
7995        let mut state = RunState::new(
7996            repo.clone(),
7997            "main".to_owned(),
7998            head.clone(),
7999            "task".to_owned(),
8000            config,
8001        );
8002        state.candidates = vec![Candidate {
8003            index: 0,
8004            label: 'A',
8005            agent: "alpha".to_owned(),
8006            branch: "does-not-exist".to_owned(),
8007            worktree: repo.clone(),
8008            summary: String::new(),
8009            stat: String::new(),
8010            files: 0,
8011            commits: 0,
8012            empty: false,
8013            failed: None,
8014            verified_noop: None,
8015            duration_ms: 0,
8016            folded: false,
8017        }];
8018        state.tally = Some(Tally {
8019            first_choice: BTreeMap::from([('A', 1)]),
8020            borda: BTreeMap::new(),
8021            winner: 'A',
8022            rankings: 1,
8023            unanimous_initial: true,
8024            deliberated: false,
8025            changed_votes: 0,
8026            unanimous_final: true,
8027            tie_break: None,
8028            judges: 0,
8029            present: 0,
8030            quorum: 0,
8031            met_quorum: true,
8032            uncontested: Some("only candidate A produced a change".to_owned()),
8033        });
8034        // The exact shape a prior process's `stop_reviewing` would have left
8035        // on disk: the round budget's last round, a real attempt already
8036        // made and already resource-blocked.
8037        state.reviews = vec![ReviewRound {
8038            round: 1,
8039            head: head.clone(),
8040            verified_head: Some(head.clone()),
8041            verified_at: Some(jiff::Timestamp::now()),
8042            reviews: Vec::new(),
8043            e2e: vec![CommandOutcome {
8044                command: format!(
8045                    "CARGO_TARGET_DIR='{}' test -f README.md",
8046                    cache_dir.display()
8047                ),
8048                code: None,
8049                output_tail: "waiting for the shared build cache".to_owned(),
8050                duration_ms: 0,
8051                resource_blocked: true,
8052            }],
8053            fix: None,
8054            blocking: 1,
8055            answered: 1,
8056            expected: 1,
8057            clean: false,
8058            verify_retried: false,
8059            e2e_deferred: false,
8060            e2e_defer_reason: None,
8061            progressed: false,
8062            vote_split: false,
8063            reconsideration: Vec::new(),
8064            verdict: None,
8065        }];
8066
8067        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
8068        let mut runner = Runner {
8069            state,
8070            roles: ResolvedRoles {
8071                implementers: Vec::new(),
8072                judges: Vec::new(),
8073                reviewers: Vec::new(),
8074                fixer: None,
8075                conductor: conductor(),
8076                implementer_roster: Vec::new(),
8077            },
8078            sem: Arc::new(Semaphore::new(1)),
8079            pause: Pause::new(),
8080            interrupt: Pause::new(),
8081        };
8082
8083        // The lease is still held throughout, so this reentry's own retry is
8084        // also contended — proving `review_loop` actually tried again (not
8085        // that it happened to succeed) is what the timestamp comparison
8086        // below is for.
8087        runner.review_loop().await.expect("review_loop");
8088
8089        assert_eq!(
8090            runner.state.reviews.len(),
8091            1,
8092            "no new round was started on top of the unresolved one: {:?}",
8093            runner.state.reviews
8094        );
8095        let last = &runner.state.reviews[0];
8096        assert_eq!(
8097            last.e2e_status(),
8098            E2eStatus::ResourceBlocked,
8099            "still contended: {last:?}"
8100        );
8101        assert!(
8102            last.verified_at.expect("still known") > first_attempt_at,
8103            "review_loop must have actually retried the check, not left it exactly as found"
8104        );
8105        assert_ne!(
8106            runner.state.status,
8107            RunStatus::Blocked,
8108            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
8109            runner.state.status
8110        );
8111
8112        held.release();
8113    }
8114
8115    #[tokio::test]
8116    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
8117        crate::run::set_home(std::env::temp_dir().join("magi-graph-test-home"));
8118        let tmp = tempfile::tempdir().expect("tempdir");
8119        let repo = tmp.path().join("repo");
8120        std::fs::create_dir_all(&repo).unwrap();
8121        init_repo(&repo);
8122
8123        let mut config = Config::default();
8124        config.merge.mode = MergeMode::Pr;
8125        config.graph.land = true;
8126        config.graph.land_approval = false;
8127
8128        let mut state = RunState::new(
8129            repo.clone(),
8130            "main".to_owned(),
8131            "deadbeef".to_owned(),
8132            "task".to_owned(),
8133            config,
8134        );
8135        state.candidates = vec![Candidate {
8136            index: 0,
8137            label: 'A',
8138            agent: "alpha".to_owned(),
8139            branch: "does-not-exist".to_owned(),
8140            worktree: repo.clone(),
8141            summary: String::new(),
8142            stat: String::new(),
8143            files: 0,
8144            commits: 0,
8145            empty: false,
8146            failed: None,
8147            verified_noop: None,
8148            duration_ms: 0,
8149            folded: false,
8150        }];
8151        state.tally = Some(Tally {
8152            first_choice: BTreeMap::from([('A', 1)]),
8153            borda: BTreeMap::new(),
8154            winner: 'A',
8155            rankings: 1,
8156            unanimous_initial: true,
8157            deliberated: false,
8158            changed_votes: 0,
8159            unanimous_final: true,
8160            tie_break: None,
8161            judges: 0,
8162            present: 0,
8163            quorum: 0,
8164            met_quorum: true,
8165            uncontested: Some("only candidate A produced a change".to_owned()),
8166        });
8167        state.reviews = vec![ReviewRound {
8168            round: 1,
8169            head: "deadbeef".to_owned(),
8170            verified_head: None,
8171            verified_at: None,
8172            reviews: Vec::new(),
8173            e2e: Vec::new(),
8174            fix: None,
8175            blocking: 0,
8176            answered: 0,
8177            expected: 0,
8178            clean: true,
8179            verify_retried: false,
8180            e2e_deferred: false,
8181            e2e_defer_reason: None,
8182            progressed: false,
8183            vote_split: false,
8184            reconsideration: Vec::new(),
8185            verdict: None,
8186        }];
8187        state.gate = vec![CommandOutcome {
8188            command: "test".to_owned(),
8189            code: Some(0),
8190            output_tail: String::new(),
8191            duration_ms: 0,
8192            resource_blocked: false,
8193        }];
8194        state.gate_ran = true;
8195        // A first pass through `merge` already pushed and opened this pull
8196        // request; `status` is `Landing` because a previous call into `land`
8197        // parked or was interrupted before it reached a terminal outcome.
8198        state.status = RunStatus::Landing;
8199        state.merge = Some(MergeOutcome {
8200            mode: MergeMode::Pr,
8201            ok: true,
8202            detail: "https://example.invalid/x/y/pull/1".to_owned(),
8203        });
8204
8205        // The Landing-resume shortcut calls `run_land` directly rather than
8206        // through `merge`, which is exactly the call site that used to skip
8207        // `settle_questions` - see the fixture below.
8208        ask_test_home();
8209        let store = ask::Questions::open();
8210        let q = ask_open_question(&store, &state.id);
8211
8212        let mut runner = Runner {
8213            state,
8214            roles: ResolvedRoles {
8215                implementers: Vec::new(),
8216                judges: Vec::new(),
8217                reviewers: Vec::new(),
8218                fixer: None,
8219                conductor: conductor(),
8220                implementer_roster: Vec::new(),
8221            },
8222            sem: Arc::new(Semaphore::new(1)),
8223            pause: Pause::new(),
8224            interrupt: Pause::new(),
8225        };
8226
8227        // `execute`, not `merge` directly: the Landing-resume shortcut lives
8228        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
8229        // exactly because `review_loop` would otherwise clobber the marker
8230        // first.
8231        runner.execute().await.expect("execute");
8232
8233        assert_eq!(
8234            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
8235            Some("https://example.invalid/x/y/pull/1"),
8236            "reentry must not push again or open a second pull request over the \
8237             one `land` is already watching"
8238        );
8239        assert_ne!(
8240            runner.state.status,
8241            RunStatus::Landing,
8242            "land could not actually reach the fake pull request, so it must \
8243             have given up rather than left the run silently parked forever"
8244        );
8245        // `land` could not reach the fake pull request, so it gave up into
8246        // `Blocked` - still resumable, so the question must not have been
8247        // swept just because this branch now also calls `settle_questions`.
8248        assert_eq!(runner.state.status, RunStatus::Blocked);
8249        assert!(
8250            store.get(&q.id).unwrap().status.open(),
8251            "Blocked is still alive; settle_questions must have been a no-op here"
8252        );
8253    }
8254
8255    fn state_with_round(round: ReviewRound) -> RunState {
8256        let mut s = RunState::new(
8257            PathBuf::from("/repo"),
8258            "main".to_owned(),
8259            "abc1234".to_owned(),
8260            "add retries".to_owned(),
8261            Config::default(),
8262        );
8263        s.reviews = vec![round];
8264        s
8265    }
8266
8267    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
8268        crate::verdict::Finding {
8269            id: id.to_owned(),
8270            severity,
8271            file: None,
8272            line: None,
8273            title: title.to_owned(),
8274            detail: String::new(),
8275        }
8276    }
8277
8278    #[test]
8279    fn pr_body_names_open_findings_and_declined_ones() {
8280        let round = ReviewRound {
8281            round: 2,
8282            head: "deadbee".to_owned(),
8283            verified_head: None,
8284            verified_at: None,
8285            reviews: vec![ReviewRecord {
8286                attempts: 0,
8287                reviewer: 1,
8288                agent: "alpha".to_owned(),
8289                summary: String::new(),
8290                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
8291                vote: None,
8292                failed: None,
8293                duration_ms: 0,
8294            }],
8295            e2e: vec![CommandOutcome {
8296                command: "cargo test".to_owned(),
8297                code: Some(0),
8298                output_tail: String::new(),
8299                duration_ms: 0,
8300                resource_blocked: false,
8301            }],
8302            verify_retried: false,
8303            e2e_deferred: false,
8304            e2e_defer_reason: None,
8305            fix: Some(FixRecord {
8306                agent: "alpha".to_owned(),
8307                addressed: Vec::new(),
8308                rejected: vec![crate::verdict::Rejection {
8309                    id: "R1-1-1".to_owned(),
8310                    why: "not reachable from any caller".to_owned(),
8311                }],
8312                notes: String::new(),
8313                committed: true,
8314                failed: None,
8315                duration_ms: 0,
8316                continuation: None,
8317            }),
8318            blocking: 0,
8319            answered: 1,
8320            expected: 1,
8321            clean: false,
8322            progressed: true,
8323            vote_split: false,
8324            reconsideration: Vec::new(),
8325            verdict: None,
8326        };
8327        let state = state_with_round(round);
8328        let body = pr_body(&state, 'A');
8329
8330        assert!(body.contains("add retries"), "the task must still be there");
8331        assert!(body.contains("R2-1-1"), "{body}");
8332        assert!(body.contains("unused import"), "{body}");
8333        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
8334        assert!(
8335            body.contains("not reachable from any caller"),
8336            "the reason it was declined: {body}"
8337        );
8338    }
8339
8340    #[test]
8341    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
8342        let round = ReviewRound {
8343            round: 1,
8344            head: "deadbee".to_owned(),
8345            verified_head: None,
8346            verified_at: None,
8347            reviews: vec![ReviewRecord {
8348                attempts: 0,
8349                reviewer: 1,
8350                agent: "alpha".to_owned(),
8351                summary: String::new(),
8352                findings: Vec::new(),
8353                vote: None,
8354                failed: None,
8355                duration_ms: 0,
8356            }],
8357            e2e: Vec::new(),
8358            verify_retried: false,
8359            e2e_deferred: false,
8360            e2e_defer_reason: None,
8361            fix: None,
8362            blocking: 0,
8363            answered: 1,
8364            expected: 1,
8365            clean: true,
8366            progressed: false,
8367            vote_split: false,
8368            reconsideration: Vec::new(),
8369            verdict: None,
8370        };
8371        let state = state_with_round(round);
8372        let body = pr_body(&state, 'A');
8373        assert!(!body.contains("Open review findings"), "{body}");
8374        assert!(!body.contains("Declined"), "{body}");
8375    }
8376
8377    #[test]
8378    fn pr_body_titles_itself_from_the_task_not_run_or_candidate() {
8379        let state = RunState::new(
8380            PathBuf::from("/repo"),
8381            "main".to_owned(),
8382            "abc1234".to_owned(),
8383            "add retries".to_owned(),
8384            Config::default(),
8385        );
8386        let body = pr_body(&state, 'A');
8387        let title = body.lines().next().unwrap();
8388
8389        assert_eq!(
8390            title, "add retries",
8391            "the title must be the task, not run/candidate bookkeeping: {body}"
8392        );
8393        assert!(
8394            body.contains(&format!("magi:run/{}", state.id)),
8395            "the run id must still be recoverable from the footer: {body}"
8396        );
8397        assert!(
8398            body.contains("magi:candidate-a"),
8399            "the candidate must still be recoverable from the footer: {body}"
8400        );
8401    }
8402
8403    #[test]
8404    fn pr_body_never_titles_itself_off_a_blank_first_line() {
8405        let leading_blank = RunState::new(
8406            PathBuf::from("/repo"),
8407            "main".to_owned(),
8408            "abc1234".to_owned(),
8409            "\n\n  \nadd retries\n\ndetails".to_owned(),
8410            Config::default(),
8411        );
8412        let body = pr_body(&leading_blank, 'A');
8413        assert_eq!(
8414            body.lines().next(),
8415            Some("add retries"),
8416            "a leading blank line must not become an empty title: {body}"
8417        );
8418
8419        let whitespace_only = RunState::new(
8420            PathBuf::from("/repo"),
8421            "main".to_owned(),
8422            "abc1234".to_owned(),
8423            "   \n  \n".to_owned(),
8424            Config::default(),
8425        );
8426        let body = pr_body(&whitespace_only, 'A');
8427        let title = body.lines().next().unwrap_or_default();
8428        assert!(
8429            !title.is_empty(),
8430            "a whitespace-only instruction must still fall back to a non-empty title: {body}"
8431        );
8432    }
8433
8434    #[test]
8435    fn pr_title_truncates_a_first_line_over_githubs_limit() {
8436        // A run 2963-shaped instruction: a single first line well past
8437        // GitHub's 256-character createPullRequest limit, with a multi-byte
8438        // character mixed in so the truncation is exercised on `chars()`
8439        // counting rather than bytes.
8440        let long_line = format!("fix the thing 🎉 {}", "x".repeat(400));
8441        let title = pr_title(&long_line);
8442
8443        assert!(
8444            title.chars().count() <= PR_TITLE_MAX,
8445            "title must stay within PR_TITLE_MAX: {title:?} ({} chars)",
8446            title.chars().count()
8447        );
8448        assert!(
8449            title.chars().count() < 256,
8450            "title must stay within GitHub's 256-character limit: {title:?}"
8451        );
8452        assert!(
8453            title.ends_with('…'),
8454            "a truncated title must say so: {title:?}"
8455        );
8456    }
8457
8458    #[test]
8459    fn pr_title_leaves_a_short_title_untouched() {
8460        let title = pr_title("add retries\n\nmore detail below");
8461        assert_eq!(title, "add retries");
8462    }
8463
8464    #[test]
8465    fn pr_title_strips_markdown_heading_markers() {
8466        let title = pr_title("# Rework the config loader\n\ndetails");
8467        assert_eq!(title, "Rework the config loader");
8468    }
8469
8470    #[test]
8471    fn pr_title_of_pr_body_stays_within_githubs_limit() {
8472        let state = RunState::new(
8473            PathBuf::from("/repo"),
8474            "main".to_owned(),
8475            "abc1234".to_owned(),
8476            format!("fix the thing 🎉 {}", "x".repeat(400)),
8477            Config::default(),
8478        );
8479        let body = pr_body(&state, 'A');
8480        let title = pr_title(&body);
8481
8482        assert!(
8483            title.chars().count() < 256,
8484            "the title gh_pr_create sends must stay within GitHub's limit: {title:?}"
8485        );
8486    }
8487
8488    #[test]
8489    fn manual_merge_command_matches_the_configured_style() {
8490        let repo = Path::new("/repo");
8491        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
8492
8493        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
8494        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
8495
8496        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
8497        assert_eq!(
8498            squash,
8499            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
8500             \"Merge magi run 0832 (candidate A)\""
8501        );
8502
8503        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
8504        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
8505    }
8506
8507    #[test]
8508    fn a_nudge_gets_a_quarter_of_the_budget() {
8509        // The judge and implement budgets magi ships with.
8510        assert_eq!(retry_budget(secs(1200), true), secs(300));
8511        assert_eq!(retry_budget(secs(3600), true), secs(900));
8512    }
8513
8514    #[test]
8515    fn a_resent_prompt_keeps_the_whole_budget() {
8516        // The seat kept no context, so the retry is the original job again and
8517        // shortening it would only guarantee a second failure.
8518        assert_eq!(retry_budget(secs(1200), false), secs(1200));
8519        assert_eq!(retry_budget(secs(60), false), secs(60));
8520    }
8521
8522    #[test]
8523    fn the_floor_never_exceeds_the_original_budget() {
8524        // A short configured timeout must not be *raised* by the floor: the
8525        // operator asked for a bound, and a retry may not outlast the attempt
8526        // it is retrying.
8527        assert_eq!(retry_budget(secs(60), true), secs(60));
8528        assert_eq!(retry_budget(secs(480), true), secs(120));
8529        assert_eq!(retry_budget(secs(0), true), secs(0));
8530    }
8531
8532    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
8533        agent::CommandEvidence {
8534            id: "item1".to_owned(),
8535            description: "cargo test".to_owned(),
8536            exit_code,
8537            result_summary: String::new(),
8538            source: "codex".to_owned(),
8539        }
8540    }
8541
8542    #[test]
8543    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
8544        // No evidence is not the same fact as unconfirmed evidence: a
8545        // backend with no adapter, or a reply that ran no commands at all,
8546        // must not be misread as carrying a dangling job.
8547        assert!(!has_unconfirmed_command(&[]));
8548    }
8549
8550    #[test]
8551    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
8552        // Deliberately not a check on the exit code's *value*: a fixer
8553        // legitimately runs something that fails mid-iteration before it
8554        // succeeds, and that must never by itself reopen a valid report.
8555        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
8556        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
8557        assert!(!has_unconfirmed_command(&[
8558            evidence(Some(0)),
8559            evidence(Some(101))
8560        ]));
8561    }
8562
8563    #[test]
8564    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
8565        assert!(has_unconfirmed_command(&[
8566            evidence(Some(0)),
8567            evidence(None)
8568        ]));
8569    }
8570
8571    #[test]
8572    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
8573        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
8574        assert_eq!(
8575            verified_noop_claim(true, &[], text).as_deref(),
8576            Some("already fixed by b32cfc4, on main.")
8577        );
8578    }
8579
8580    #[test]
8581    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
8582        // A timeout or a bad exit code reads as the ordinary loss it is,
8583        // whatever the reply's own prose claims.
8584        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
8585        assert!(verified_noop_claim(false, &[], text).is_none());
8586    }
8587
8588    #[test]
8589    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
8590        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
8591        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
8592        // A confirmed command alongside the marker is fine.
8593        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
8594    }
8595
8596    #[test]
8597    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
8598        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
8599    }
8600
8601    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
8602    /// pair, in order, labelled A, B, C, ...
8603    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
8604        runner.state.candidates = shape
8605            .iter()
8606            .enumerate()
8607            .map(|(i, &(empty, verified))| Candidate {
8608                index: i,
8609                label: (b'A' + i as u8) as char,
8610                agent: "sonnet".to_owned(),
8611                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
8612                worktree: PathBuf::from(format!("/wt/{i}")),
8613                summary: String::new(),
8614                stat: String::new(),
8615                files: 0,
8616                commits: 0,
8617                empty,
8618                failed: None,
8619                verified_noop: verified.map(str::to_owned),
8620                duration_ms: 0,
8621                folded: false,
8622            })
8623            .collect();
8624    }
8625
8626    #[test]
8627    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
8628        ask_test_home();
8629        let mut runner = runner_at(RunStatus::Implementing);
8630        set_candidates(
8631            &mut runner,
8632            &[
8633                (true, Some("already on main at b32cfc4")),
8634                (true, Some("same fix, see the existing test")),
8635            ],
8636        );
8637
8638        runner
8639            .after_implement()
8640            .expect("a verified no-op is not an error");
8641
8642        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
8643    }
8644
8645    #[test]
8646    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
8647        ask_test_home();
8648        let mut runner = runner_at(RunStatus::Implementing);
8649        // Candidate A declares a verified no-op; candidate B simply wrote
8650        // nothing and said nothing about why. One candidate's claim is not
8651        // the whole run's agreement.
8652        set_candidates(
8653            &mut runner,
8654            &[(true, Some("already on main at b32cfc4")), (true, None)],
8655        );
8656
8657        let err = runner
8658            .after_implement()
8659            .expect_err("an unverified empty candidate must still fail the run");
8660
8661        assert!(
8662            err.to_string().contains("no candidate produced a change"),
8663            "{err}"
8664        );
8665        assert_eq!(runner.state.status, RunStatus::Failed);
8666    }
8667
8668    #[test]
8669    fn after_implement_still_fails_an_ordinary_all_empty_run() {
8670        ask_test_home();
8671        let mut runner = runner_at(RunStatus::Implementing);
8672        set_candidates(&mut runner, &[(true, None), (true, None)]);
8673
8674        let err = runner
8675            .after_implement()
8676            .expect_err("no candidate declared anything; this is an ordinary failure");
8677
8678        assert!(
8679            err.to_string().contains("no candidate produced a change"),
8680            "{err}"
8681        );
8682        assert_eq!(runner.state.status, RunStatus::Failed);
8683    }
8684}