Skip to main content

magi/
run.rs

1//! Run state: what happened, where it is stored, and how a run is resumed.
2//!
3//! Every node writes its result into [`RunState`] and the whole struct is
4//! flushed to `run.json` before the next node starts. That is what makes a run
5//! resumable: a competition can take an hour, and dying in review round four
6//! should not throw away three implementations, nine judge reads and a
7//! deliberation.
8//!
9//! Patches and raw agent transcripts are *not* in `run.json` — they live beside
10//! it under `artifacts/`, so the state file stays small enough to read by hand.
11use std::collections::{BTreeMap, BTreeSet};
12use std::path::{Path, PathBuf};
13
14use anyhow::{Context as _, Result, bail};
15use jiff::{Timestamp, Zoned};
16use serde::{Deserialize, Serialize};
17
18use crate::agent::SeatState;
19use crate::blind::Leak;
20use crate::config::{Config, MergeMode};
21use crate::verdict::{Finding, Rejection, ReviewVote, Severity};
22
23/// On-disk format version. Bumped when a field changes meaning, so a resumed
24/// run never half-reads a state file written by a different magi.
25///
26/// 2: added `RunStatus::Stalled`, `RunState::quota` (rate-limit losses), and
27/// the quorum fields on `Tally`. `RunState::load` already fails loudly and
28/// clearly on a schema mismatch; an old `run.json` from schema 1 now says so
29/// instead of silently half-reading.
30///
31/// 3: added `RunState::judge_skipped`. A solo candidate makes `judge` write
32/// only an event, leaving `judgements` empty forever — indistinguishable from
33/// "not yet judged" on every later reentry, which is what let `judge` re-run
34/// on a finished run and clobber its status back to `Judging`. The flag is
35/// the missing record of the fact that judging was skipped on purpose.
36///
37/// Also 3: a single-viable-candidate tally records `Tally::judges` as `0` and
38/// fills `Tally::uncontested`, instead of leaving the full roster size sitting
39/// next to a panel that never sat. A schema-2 record keeps reading as "0 of 3
40/// judges present" forever, because a tally is computed once and never
41/// recomputed on resume; the bump keeps that stale reading from being mixed
42/// with the new meaning.
43///
44/// 4: added `ReviewRound::progressed`. `graph::STAGNANT_LIMIT` counts
45/// consecutive rounds with `progressed == false` to decide whether the
46/// review loop should give up early, and a schema-3 record's default
47/// `false` would misreport a round that, at the time, actually committed a
48/// real diff — the field simply did not exist yet to say so. Without the
49/// bump, resuming an old multi-round review could spuriously trip the
50/// stagnation check on rounds that were never stagnant.
51///
52/// 5: added `RunStatus::Landing`. A run inside [`crate::land`]'s post-merge
53/// loop used to carry whatever status `merge` set before calling it forward
54/// unchanged - `Merged`, even while still watching CI or waiting on the
55/// owner's approval - which is also the one status [`RunStatus::resumable`]
56/// treats as finished. A daemon that gave this run's slot back to poll
57/// something else while an approval was outstanding, or one that simply
58/// crashed mid-land, had no way to tell "still landing" from "actually
59/// merged" and would either restart the whole competition or leave the run
60/// stuck reading as done. A schema-4 record has no notion of `Landing` at
61/// all, so this is a meaning a resumed old run cannot be guessed into rather
62/// than a value it can default to - hence the bump, not a `#[serde(default)]`.
63///
64/// 6: a deferred e2e is represented by an empty outcome list plus
65/// `ReviewRound::e2e_deferred`. Schema 5 treated that same empty list as an
66/// unconfigured, successful check, so schema-5 records are migrated with the
67/// old (not-deferred) meaning while older binaries reject schema-6 records.
68///
69/// 7: added `RunState::gate_ran`. An empty `RunState::gate` used to carry two
70/// meanings at once — "never attempted, or the last attempt was
71/// resource-blocked" (`graph::Runner::gate`'s retry case) and "attempted,
72/// zero commands configured, vacuously passed" (a repo with no
73/// `verify.gate`) — and nothing told them apart. `graph::Runner::merge`
74/// therefore read the second case as the first and refused forever: a
75/// review-only run with no gate commands configured reached `Gating` and
76/// then could never leave it. A schema-6 record's non-empty `gate` is
77/// migrated to `gate_ran = true` (a recorded attempt, real or historical,
78/// should not be spent again); an empty one migrates to `gate_ran = false`
79/// and is simply re-attempted by the next `gate()` call, which self-heals
80/// instantly for the zero-commands case.
81///
82/// 8: `ReviewRound::verified_head` used to be `None` for the overwhelming
83/// majority of rounds — every ordinary round that ran e2e against its own
84/// `head` in the main review loop never set it at all, leaving only the
85/// rare catch-up-on-a-different-commit case populated. A reader (a review
86/// prompt, `magi show`, the web UI) had no field to ask "which commit did
87/// this round's `e2e` actually check" and fell back to assuming it was
88/// always `head`, which is also what let a stale round's red output get
89/// quoted to a later round's reviewers as if it were about their patch, not
90/// an earlier one (see `ReviewRound::verification_summary`, which now exists
91/// so nowhere else has to guess). `verified_head` is now set whenever `e2e`
92/// held a real attempt (`E2eStatus::Passed`/`Failed`), always naming the
93/// commit actually checked instead of only the divergent case, and
94/// `ReviewRound::verified_at` is new alongside it. A schema-7 round's own
95/// unconditional main-loop check was always against `head` whether or not
96/// this field said so, so a `None` with a non-empty `e2e` migrates to
97/// `Some(head)` — a reconstruction of a fact that was always true, not a
98/// guess. `verified_at` has no historical value to reconstruct and stays
99/// `None`, which reads through `verification_summary` as "checked at:
100/// unknown" — an honest gap, not a fabricated time.
101/// 9: added [`RunState::operator_fixes`] — one record per `magi fix`
102/// invocation, routing specific, already-recorded findings to a fixer as a
103/// targeted, out-of-band fix outside the normal round sequence. Kept in a
104/// channel of its own rather than folded into [`ReviewRound`], because a
105/// reviewer's own severity and vote (copied verbatim onto
106/// [`OperatorFixFinding`]) must never be rewritten to look like the operator
107/// manufactured a blocking verdict — see `graph::Runner::fix_selected`. A
108/// schema-8 record has no operator-fix history at all, and
109/// `#[serde(default)]` reads an empty list as exactly that: "none happened",
110/// not an unknown gap. Nothing about an existing field's meaning changes.
111///
112/// 10: added `RunStatus::VerifiedNoop` and `Candidate::verified_noop`. Before
113/// this, an implementer that correctly concluded (with evidence) that a
114/// task's request was already satisfied elsewhere had no way to say so: the
115/// run ended the same way as one where every candidate simply failed to
116/// write anything — `after_implement` bailing with "no candidate produced a
117/// change; nothing to judge" and the run settling as a plain `Failed`. That
118/// conflated two very different facts (investigation run 391f's audit is
119/// what surfaced it: two attempts that had, correctly, found their fix
120/// already on `main`). A schema-9 record has no notion of either the new
121/// status or field, so a `VerifiedNoop` value is a meaning that cannot be
122/// reconstructed from an old record — hence the bump, not a
123/// `#[serde(default)]` for the status. `Candidate::verified_noop` alone
124/// *does* default-read as `None` on an old record, which is the honest
125/// reading: a run written before this schema never made the claim.
126///
127/// The report task 391f itself was raised from also named `6c5e`, `8df3` and
128/// `e9ce` as three more tasks whose implement wave ended the same
129/// diff-zero way, and the investigation traced all three — they do not
130/// share one cause.
131///
132/// `6c5e` and `8df3` are the same already-landed pattern as `391f`, not a
133/// coincidence: all three were re-queued together by a same-day audit of
134/// `done`-but-unlanded magi tasks (queue talk `20260912-115153-7216`,
135/// 2026-09-12 02:51–04:24), which found 17 magi tasks marked `done` with no
136/// merge to show for it and re-queued 16 of them, `6c5e` (a fix for the
137/// owner's `magi ask --thread` back-and-forth) and `8df3` (release
138/// automation) included. A second, same-day audit (talk
139/// `20260912-222053-07fe`, 13:20–13:36) then found 12 of those re-queued
140/// tasks — `391f`, `6c5e` and `8df3` among them — already merged by another
141/// route, and the owner had them deleted (`magi task rm`); `391f` alone
142/// survived because a daemon still held its run at the moment of deletion,
143/// which is the only reason any record of this group still exists to audit.
144/// Quoted directly from that second audit's own turn (talk `07fe`, so this
145/// reads without needing access to that talk store), naming both by id:
146///
147/// > 12件がマージ済み(対応不要)、3件が未実装(妥当)、2件が部分実装(要確認)でした。
148/// > **マージ済み → hold/rmを推奨:** 6c5e, 1ddc, fcf5, e25b, cea2, 391f, 3202,
149/// > b0a1, 5365, af85, 9f26, 8df3
150///
151/// — followed by the owner answering "削除!" and the agent confirming "11件
152/// 削除完了。391f はいま実行中のdaemonが掴んでいて削除できませんでした."
153/// `git log` independently confirms both fixes: the ask-back feature `6c5e`
154/// wanted landed as `f0df474` ("let the owner ask back on a question...",
155/// #93) on 2026-09-06, and the release-bump automation `8df3` wanted landed
156/// as `61005dd`/`bedd925` (open a release-bump PR on merge) on 2026-09-07
157/// and `116fcdc` (proportional version bump, #108) on 2026-09-08 — all
158/// before the 09-12 requeue. No run record survives the deletion for either
159/// task, so this schema's evidence is the audit transcript plus the
160/// independently re-checked `git log`, not a `run.json`.
161///
162/// `e9ce` is not that pattern at all, and is the reason the adoption guard
163/// below is all-or-nothing rather than "any candidate said so": its task
164/// asked an implementer to merge the real repository's `main` and cut a
165/// GitHub release — a destructive, out-of-worktree operation `AGENTS.md`
166/// names explicitly as not something to hand to an unattended candidate.
167/// Both of its runs (`20260912-053352-49ad`, `20260912-062629-bab1`)
168/// correctly refused, filed `magi ask` (questions `6196`, `6c9a`), and ended
169/// with an empty diff only because no answer arrived before the implement
170/// node's timeout — `49ad` looped `magi ask --wait` in the foreground for
171/// roughly 50 minutes as instructed before the timeout cut it off; `bab1`
172/// ended its turn moments after filing its question without ever actually
173/// blocking on the wait, a separate protocol slip this schema change does
174/// not attempt to fix. `49ad`'s own `candidates[0].summary` (quoted here
175/// because both records predate schema 10 and, separately, predate a
176/// still-unrelated struct change that already makes today's `magi show`
177/// refuse to parse either of them — `unknown field 'planner'` — so this is
178/// read straight from `run.json` on disk, not through that command):
179///
180/// > タスクの内容(READY 状態の run を実リポジトリの main に `merge --no-ff`
181/// > する、GitHub Release を作る)を精査した結果、これは全てこのワーカーの
182/// > worktree の外にある実リポジトリと GitHub 上の共有状態に対する不可逆な
183/// > 操作であり […] 私自身の運用ルール「Work only inside this worktree.
184/// > Nothing outside it is yours.」と正面から矛盾すると判断しました。
185///
186/// Neither candidate's reply carries the
187/// `NO CHANGE NEEDED` marker below, so both runs correctly stay `Failed`
188/// under this schema, not `VerifiedNoop`: a run blocked on an unanswered
189/// authorization question is not a verified no-op, and reading the two
190/// alike is exactly the misclassification the guard's per-candidate and
191/// whole-run conditions exist to refuse.
192///
193/// `RunStatus::Superseded` (added without a bump, still schema 10) is
194/// additive in the ordinary sense — an old build reading a run written under
195/// a newer one only had `RunStatus` variants to worry about before this, and
196/// a record already on disk never contained the new variant to begin with —
197/// but it is not additive in the sense every earlier schema bump on this
198/// constant was: `daemon::supersede_prior_runs` now rewrites a `Blocked` or
199/// `Stalled` run's `status` field *after* it was first written, once a later
200/// attempt at the same task lands. Any tooling outside magi that reads
201/// `run.json` and assumes a terminal `status` is permanent once set — a
202/// monitoring script polling for `blocked`, say — needs to know that
203/// `superseded` is where some of those records now go instead of staying put
204/// forever; see that function's own doc for exactly when.
205///
206/// Schema 11 adds [`RunState::released_to`] / [`RunState::released_branches`]:
207/// a run whose worktree a later attempt at the same task took over
208/// (`crate::handover`) can no longer be resumed from where it was. The fields
209/// are additive, but an older build would happily resume such a run into a
210/// worktree that no longer exists, which is the one thing the bump is for.
211///
212/// Schema 12 adds [`RunState::driver_exited`]: the driver records that it
213/// stopped walking the graph. Additive, but an older build would keep reading
214/// a long-lived daemon's pid as a live driver of a run that ended long ago.
215///
216/// Schema 13 adds [`RunState::origin`]: who started the run and which task it
217/// stood in for. Additive, and an older record is deliberately left with
218/// `None` ("origin unknown") rather than guessed at — a run from before this
219/// existed must not read as an operator's when nobody knows. The bump exists
220/// so a run is never mistaken for one whose origin was known and empty.
221pub const SCHEMA: u32 = 13;
222
223/// What an unrecorded origin reads as, wherever one is shown.
224pub const ORIGIN_UNKNOWN: &str = "origin unknown (started before origins were recorded)";
225
226/// Who started a run. Legibility only: nothing branches on it, the same rule
227/// as `agent::Invocation::run` / `node`.
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(tag = "kind", rename_all = "snake_case")]
230pub enum StartedBy {
231    /// The daemon, minting an attempt for a queue task.
232    Queue {
233        /// The task the attempt belongs to.
234        task: String,
235    },
236    /// An agent inside a talk (chat) conversation, via `magi run` / `magi review`.
237    Chat {
238        /// Talk id, e.g. `4a7b`.
239        talk: String,
240    },
241    /// An agent seat inside another run, identified by the `MAGI_RUN` /
242    /// `MAGI_NODE` it was spawned with.
243    Seat {
244        /// Run the seat belonged to.
245        run: String,
246        /// Node it was working in.
247        node: String,
248    },
249    /// A person at a terminal (or anything that carries no attribution).
250    Operator,
251}
252
253/// Where a run came from, and the task it was meant to finish, if any.
254///
255/// Kept as two facts because they vary independently: a chat agent may start a
256/// run on behalf of a queue task.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258pub struct Origin {
259    /// Who started it.
260    pub by: StartedBy,
261    /// The queue task this run serves, when it names one.
262    #[serde(default)]
263    pub task: Option<String>,
264}
265
266impl Origin {
267    /// A run a person started with no task attached.
268    pub fn operator() -> Self {
269        Self {
270            by: StartedBy::Operator,
271            task: None,
272        }
273    }
274
275    /// An attempt the daemon mints for `task`.
276    pub fn queue(task: &str) -> Self {
277        Self {
278            by: StartedBy::Queue {
279                task: task.to_owned(),
280            },
281            task: Some(task.to_owned()),
282        }
283    }
284
285    /// Attribute from the `MAGI_RUN` / `MAGI_NODE` pair `agent::invoke`
286    /// exports, as `(run, node)`; `None` for no (or blank) `run` is an
287    /// operator. A node of `chat` is the talk layer, whose run is the talk id.
288    pub fn from_agent_env(env: Option<(String, String)>, task: Option<String>) -> Self {
289        let by = match env {
290            Some((run, node)) if node == crate::queue::CHAT_NODE => StartedBy::Chat { talk: run },
291            Some((run, node)) => StartedBy::Seat { run, node },
292            None => StartedBy::Operator,
293        };
294        Self { by, task }
295    }
296
297    /// The same origin, naming `task` as the one it serves.
298    pub fn serving(mut self, task: Option<String>) -> Self {
299        if task.is_some() {
300            self.task = task;
301        }
302        self
303    }
304
305    /// One short label for lists, reports and the web UI.
306    pub fn label(&self) -> String {
307        let by = match &self.by {
308            StartedBy::Queue { task } => format!("task {}", short_of(task)),
309            StartedBy::Chat { talk } => format!("chat {}", short_of(talk)),
310            StartedBy::Seat { run, node } => format!("{node}@{}", short_of(run)),
311            StartedBy::Operator => "operator".to_owned(),
312        };
313        match (&self.by, &self.task) {
314            (StartedBy::Queue { task: a }, Some(b)) if a == b => by,
315            (_, Some(t)) => format!("{by}, for task {}", short_of(t)),
316            _ => by,
317        }
318    }
319}
320
321/// [`Origin::label`] for a run that may predate origins.
322pub fn origin_label(origin: Option<&Origin>) -> String {
323    origin.map_or_else(|| ORIGIN_UNKNOWN.to_owned(), Origin::label)
324}
325
326/// Where a run got to.
327#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(rename_all = "snake_case")]
329pub enum RunStatus {
330    /// Worktrees being prepared.
331    Prep,
332    /// Candidates being implemented.
333    Implementing,
334    /// Judges ranking blind.
335    Judging,
336    /// Judges deliberating after a split.
337    Deliberating,
338    /// Final votes being collected privately.
339    Voting,
340    /// Winner in the review + verification loop.
341    Reviewing,
342    /// Gate commands running. Transient: `graph::Runner::gate` and
343    /// `graph::Runner::merge` always move a run on from here, whether or not
344    /// any gate commands are configured — see [`RunState::gate_status`] and
345    /// `SCHEMA`'s doc for schema 7, which fixed a repo with an empty
346    /// `verify.gate` stranding a review-only run in `Gating` forever.
347    Gating,
348    /// Inside [`crate::land`]'s post-merge loop: watching CI, running a fix
349    /// round, rebasing onto a moved base, or waiting on the owner's merge
350    /// approval. A run parked here while an approval is outstanding has
351    /// handed its daemon slot back — see [`crate::daemon`] — and resumes
352    /// through exactly this status, not a fresh competition.
353    Landing,
354    /// Winner merged.
355    Merged,
356    /// Winner passed the gate; merge was not requested.
357    Ready,
358    /// The judgement did not gather enough judges (e.g. rate limiting took out
359    /// seats), so the verdict is not trustworthy. The run stopped and kept its
360    /// work so it can be resumed or folded — it must never be confused with a
361    /// healthy `Ready`.
362    Stalled,
363    /// Review rounds exhausted with findings still open, or the gate failed.
364    Blocked,
365    /// The graph could not complete.
366    Failed,
367    /// Every candidate wrote nothing, and every one of them said why in a way
368    /// that survived [`crate::graph::Runner`]'s adoption guard: a clean CLI
369    /// exit, an actually-empty tree, no command left with an unconfirmed
370    /// exit status, and non-empty evidence. Distinct from `Failed` on
371    /// purpose — see `SCHEMA`'s doc for schema 10 — because the two read
372    /// identically to an operator glancing at a card ("nothing happened")
373    /// while meaning opposite things: one is an agent that could not do the
374    /// work, the other is an agent that checked and the work was already
375    /// done. Settles the task through [`crate::queue::Task::handed_off`], not
376    /// [`crate::queue::Task::fail`]: a human still has to look — the claim is
377    /// unverified by magi itself — and `Held` (not `Failed`-and-requeued)
378    /// means nothing retries the task unattended on the same unconfirmed
379    /// claim while that look is pending.
380    VerifiedNoop,
381    /// A later attempt at the same task already finished the job — see
382    /// `crate::queue::Task::superseded_attempts` — so this run's own
383    /// `Blocked`/`Stalled` no longer means anyone has to look at it. Written
384    /// only over one of those two statuses, only once the task itself is
385    /// `crate::queue::TaskStatus::Done`, and only onto an attempt that comes
386    /// before the one that succeeded. Unlike them, not [`Self::resumable`]:
387    /// there is nothing left to resume towards, the task already has its
388    /// answer, and a fold is free to clean this run's worktree away without
389    /// waiting on a human to confirm that first.
390    Superseded,
391    /// The winner's whole change is already on the base under other commit
392    /// ids (a cherry-pick or squash by another task) — see
393    /// [`crate::already`]. Terminal and not a failure: nothing is left to
394    /// land, so unlike `Blocked` nobody has to look, and unlike `Merged` this
395    /// run did not land anything. Never resumable; `BaseSync::already_in`
396    /// names the base commits that carry the change. Added without a schema
397    /// bump, like `Superseded`: no record on disk can contain it yet.
398    AlreadyInBase,
399}
400
401impl RunStatus {
402    /// Is this a terminal state?
403    pub fn done(self) -> bool {
404        matches!(
405            self,
406            Self::Merged
407                | Self::Ready
408                | Self::Stalled
409                | Self::Blocked
410                | Self::Failed
411                | Self::VerifiedNoop
412                | Self::Superseded
413                | Self::AlreadyInBase
414        )
415    }
416
417    /// The name this status is written and shown under, matching the
418    /// `snake_case` serde spelling so a log line, an error message and the
419    /// JSON a phone reads all say the same word.
420    pub fn as_str(self) -> &'static str {
421        match self {
422            Self::Prep => "prep",
423            Self::Implementing => "implementing",
424            Self::Judging => "judging",
425            Self::Deliberating => "deliberating",
426            Self::Voting => "voting",
427            Self::Reviewing => "reviewing",
428            Self::Gating => "gating",
429            Self::Landing => "landing",
430            Self::Merged => "merged",
431            Self::Ready => "ready",
432            Self::Stalled => "stalled",
433            Self::Blocked => "blocked",
434            Self::Failed => "failed",
435            Self::VerifiedNoop => "verified_noop",
436            Self::Superseded => "superseded",
437            Self::AlreadyInBase => "already_in_base",
438        }
439    }
440
441    /// Label for a human-facing listing or report — the same word as
442    /// [`Self::as_str`] except where the machine spelling would read harsher
443    /// than the state actually is. `VerifiedNoop` is the one case: its own
444    /// `as_str` exists for logs, JSON and event messages, none of which
445    /// should quietly grow a second vocabulary, but a bare "verified_noop" in
446    /// a report reads like an error code, not the qualified, evidence-backed
447    /// claim it actually is.
448    pub fn display_label(self) -> &'static str {
449        match self {
450            Self::VerifiedNoop => "agent-verified no-op",
451            Self::AlreadyInBase => "already in base",
452            other => other.as_str(),
453        }
454    }
455
456    /// Can this run be carried on from where it stopped?
457    ///
458    /// Everything except a finished run and a failed one. `execute` skips
459    /// nodes already recorded, so re-entering is cheap wherever the run
460    /// stopped, and the alternative is always a fresh competition against
461    /// work that already exists.
462    ///
463    /// - `Stalled` re-asks only the seats whose absence collapsed the panel,
464    ///   keeping the candidates that were already paid for.
465    /// - `Blocked` re-enters the review loop against a branch that is built.
466    /// - **A non-terminal status** means the run was interrupted: a parked
467    ///   run waiting for its upgrade, or one whose daemon was killed. This
468    ///   used to be excluded, which left run 4043 stuck at `reviewing` with
469    ///   the deck telling the operator it could not be resumed - the one
470    ///   state where resuming is the only sensible answer.
471    ///
472    /// `Failed` does not qualify: the graph could not complete and there is
473    /// no established point to continue from. Nor does a finished run, whose
474    /// answer is a new competition. Nor does `VerifiedNoop`: every candidate
475    /// already agreed nothing belongs in this worktree, and resuming would
476    /// only re-ask the same question — the answer is for a human to check
477    /// the evidence, not for the graph to run again. Nor does `Superseded`:
478    /// a later attempt at the same task already finished it, so there is
479    /// nothing left this run's own answer could still contribute.
480    ///
481    /// Whether anything is *already* driving the run is a separate question,
482    /// answered by `daemon::is_working_on` at the callers that need it.
483    pub fn resumable(self) -> bool {
484        !matches!(
485            self,
486            Self::Merged
487                | Self::Ready
488                | Self::Failed
489                | Self::VerifiedNoop
490                | Self::Superseded
491                | Self::AlreadyInBase
492        )
493    }
494}
495
496/// One candidate implementation.
497#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct Candidate {
499    /// Position in the implementer list.
500    pub index: usize,
501    /// Blind label as presented to judges.
502    pub label: char,
503    /// Which agent wrote it. Recorded for the stats tables, never shown to a
504    /// judge.
505    pub agent: String,
506    /// Branch, named after the label so judges can inspect it without learning
507    /// the author.
508    pub branch: String,
509    /// Worktree path.
510    pub worktree: PathBuf,
511    /// Sanitized author summary.
512    #[serde(default)]
513    pub summary: String,
514    /// `git diff --stat`.
515    #[serde(default)]
516    pub stat: String,
517    /// Files touched.
518    #[serde(default)]
519    pub files: usize,
520    /// Commits ahead of base.
521    #[serde(default)]
522    pub commits: usize,
523    /// True when the agent produced no change at all.
524    #[serde(default)]
525    pub empty: bool,
526    /// Why this candidate is not in the running.
527    #[serde(default)]
528    pub failed: Option<String>,
529    /// The evidence this candidate gave for writing no change on purpose —
530    /// the `NO CHANGE NEEDED:` marker `prompt::implement`'s reply format
531    /// documents, verbatim. `Some` only when [`crate::graph`]'s adoption
532    /// guard accepted the claim: the CLI exited cleanly, the tree really is
533    /// empty, no command in the reply was left with an unconfirmed exit
534    /// status, and the evidence itself is non-empty. A candidate that wrote
535    /// nothing and said nothing about why — the ordinary empty loss — always
536    /// reads `None` here, same as one written before schema 10 ever existed.
537    #[serde(default)]
538    pub verified_noop: Option<String>,
539    /// Wall-clock time for the implementation.
540    #[serde(default)]
541    pub duration_ms: u64,
542    /// Whether the worktree has been folded away.
543    #[serde(default)]
544    pub folded: bool,
545}
546
547impl Candidate {
548    /// Can this candidate be judged?
549    pub fn viable(&self) -> bool {
550        self.failed.is_none() && !self.empty
551    }
552}
553
554/// One judge's independent ranking.
555#[derive(Debug, Clone, Serialize, Deserialize)]
556pub struct Judgement {
557    /// Judge seat number, 1-based.
558    pub judge: usize,
559    /// Seat key.
560    pub seat: String,
561    /// Agent occupying the seat.
562    pub agent: String,
563    /// Best-first labels.
564    #[serde(default)]
565    pub ranking: Vec<char>,
566    /// Per-label justification.
567    #[serde(default)]
568    pub reasons: BTreeMap<String, String>,
569    /// Self-reported confidence.
570    #[serde(default)]
571    pub confidence: Option<u8>,
572    /// Order the candidates were presented in, as candidate indices.
573    #[serde(default)]
574    pub order: Vec<usize>,
575    /// Why this judge has no ranking.
576    #[serde(default)]
577    pub failed: Option<String>,
578    /// Wall-clock time.
579    #[serde(default)]
580    pub duration_ms: u64,
581}
582
583/// One judge's turn in a deliberation round.
584#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct DeliberationTurn {
586    /// Judge seat number, 1-based.
587    pub judge: usize,
588    /// Agent occupying the seat.
589    pub agent: String,
590    /// The argument, as written.
591    pub body: String,
592    /// Where the judge stood at the end of the turn.
593    #[serde(default)]
594    pub tentative: Option<char>,
595}
596
597/// A deliberation round.
598#[derive(Debug, Clone, Serialize, Deserialize)]
599pub struct DeliberationRound {
600    /// 1-based round number.
601    pub round: usize,
602    /// Turns, in the order they were taken.
603    pub turns: Vec<DeliberationTurn>,
604}
605
606/// A final vote, collected privately.
607#[derive(Debug, Clone, Serialize, Deserialize)]
608pub struct VoteRecord {
609    /// Judge seat number, 1-based.
610    pub judge: usize,
611    /// Agent occupying the seat.
612    pub agent: String,
613    /// The vote.
614    #[serde(default)]
615    pub vote: Option<char>,
616    /// Why.
617    #[serde(default)]
618    pub reason: String,
619    /// Did this judge move from its initial first choice?
620    #[serde(default)]
621    pub changed: bool,
622}
623
624/// A seat that was taken out by a CLI rate limit / quota, recorded so a run
625/// whose panel collapsed does not masquerade as a healthy one.
626#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
627pub struct QuotaLoss {
628    /// Seat key, e.g. `judge-1` or `review-2`.
629    pub seat: String,
630    /// Node that was running, e.g. `judge`, `vote`, `review`.
631    pub node: String,
632    /// When the CLI reported the limit.
633    pub at: Timestamp,
634    /// Reset hint if the CLI printed one, free text.
635    #[serde(default)]
636    pub reset: Option<String>,
637}
638
639/// A seat handed from one roster agent to the next after the first failed it
640/// (rate limit, timeout or an ordinary failure), recorded so the answer's
641/// author is never a mystery and a run that recovered on its second agent
642/// still says what it cost.
643#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
644pub struct Handover {
645    /// When the seat changed hands.
646    pub at: Timestamp,
647    /// Node that was running, e.g. `implement`, `judge`, `review`.
648    pub node: String,
649    /// Seat key, e.g. `impl-A` or `judge-2`.
650    pub seat: String,
651    /// Agent id that failed the seat.
652    pub from: String,
653    /// Agent id that took it over.
654    pub to: String,
655    /// Why: `rate limited (quota)`, `timed out`, or the failure's own message.
656    pub reason: String,
657}
658
659/// A newly created lockfile of a package manager the directory does not use,
660/// which a rescue commit left untracked instead of committing. Recorded so the
661/// omission is visible: the file may be one the task really wanted.
662#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
663pub struct Withheld {
664    /// Repo-relative path.
665    pub path: String,
666    /// The manager the file belongs to.
667    pub manager: String,
668    /// The tracked file (or missing manifest) that made it foreign.
669    pub kept_by: String,
670    /// Node whose rescue commit withheld it.
671    pub node: String,
672    /// When.
673    pub at: Timestamp,
674}
675
676/// The mechanical count.
677#[derive(Debug, Clone, Serialize, Deserialize)]
678pub struct Tally {
679    /// First-choice votes per label.
680    pub first_choice: BTreeMap<char, usize>,
681    /// Borda points from the initial rankings, used only to break a tie.
682    pub borda: BTreeMap<char, usize>,
683    /// The winning label.
684    pub winner: char,
685    /// How many judges produced a usable ranking. A panel of one is not a
686    /// consensus and must not be reported as a split.
687    #[serde(default)]
688    pub rankings: usize,
689    /// Did every judge's *initial* first choice agree?
690    pub unanimous_initial: bool,
691    /// Was deliberation run?
692    pub deliberated: bool,
693    /// Judges who moved between their initial ranking and their final vote.
694    pub changed_votes: usize,
695    /// Did the final votes agree?
696    pub unanimous_final: bool,
697    /// How the tie was broken, when it had to be.
698    #[serde(default)]
699    pub tie_break: Option<String>,
700    /// Configured judge count — the size of the full panel. `0` when no
701    /// panel was asked (see `uncontested`), not the roster size a panel that
702    /// never sat would have had.
703    #[serde(default)]
704    pub judges: usize,
705    /// Judges who actually contributed to the decision (not taken out by a
706    /// rate limit and producing a usable rank or vote).
707    #[serde(default)]
708    pub present: usize,
709    /// How many judges are required for a trustworthy verdict. Chosen as a
710    /// strict majority (`judges / 2 + 1`): a verdict backed by a minority must
711    /// never be presented as a healthy one, while a bare majority is still
712    /// real signal. A one-candidate run needs no quorum.
713    #[serde(default)]
714    pub quorum: usize,
715    /// `present >= quorum`, or no quorum was required.
716    #[serde(default)]
717    pub met_quorum: bool,
718    /// Why no panel was asked, when none was: a single viable candidate, or
719    /// a review-only run that never competed. `None` when judges actually
720    /// ranked and voted — including when too few of them survived to reach
721    /// quorum, which is a collapse and must keep reading as one.
722    #[serde(default)]
723    pub uncontested: Option<String>,
724}
725
726/// One reviewer's report in a round.
727#[derive(Debug, Clone, Serialize, Deserialize)]
728pub struct ReviewRecord {
729    /// Reviewer seat number, 1-based.
730    pub reviewer: usize,
731    /// Agent occupying the seat.
732    pub agent: String,
733    /// Reviewer prose.
734    #[serde(default)]
735    pub summary: String,
736    /// Findings, with magi-assigned ids.
737    #[serde(default)]
738    pub findings: Vec<Finding>,
739    /// This seat's initial vote. `None` on a record predating votes, exactly
740    /// like a round that genuinely had none cast — never a stand-in for a
741    /// vote that was lost.
742    #[serde(default)]
743    pub vote: Option<ReviewVote>,
744    /// Why this reviewer produced nothing.
745    #[serde(default)]
746    pub failed: Option<String>,
747    /// Wall-clock time.
748    #[serde(default)]
749    pub duration_ms: u64,
750    /// How many times this seat was asked before it settled — 0 for a first
751    /// answer, N after N nudges (`ask_json_wave`'s retry loop). Read this
752    /// together with [`Self::failed`], never `failed` alone: `failed: Some(_)`
753    /// with `attempts == 0` is a seat that never answered at all, while
754    /// `failed: None` with `attempts > 0` is one that only came back after a
755    /// nudge — recovered, not silent — and the two must not look the same in
756    /// history. A record written before this field existed defaults to `0`,
757    /// which under-reports a pre-existing retry rather than inventing one;
758    /// see `ask_json_wave`'s own doc for where this is filled in.
759    #[serde(default)]
760    pub attempts: usize,
761}
762
763/// One seat's revote during a round's reconsideration (see
764/// [`ReviewRound::reconsideration`]).
765#[derive(Debug, Clone, Serialize, Deserialize)]
766pub struct ReviewRevoteRecord {
767    /// Reviewer seat number, 1-based.
768    pub reviewer: usize,
769    /// Agent occupying the seat.
770    pub agent: String,
771    /// The revote. `None` when the seat did not answer.
772    #[serde(default)]
773    pub vote: Option<ReviewVote>,
774    /// Why.
775    #[serde(default)]
776    pub reason: String,
777    /// Why this seat produced no revote.
778    #[serde(default)]
779    pub failed: Option<String>,
780}
781
782/// One fix round spent on a failing `verify.gate`: which fixer, what it did to
783/// the tree, and the gate output it was shown.
784#[derive(Debug, Clone, Serialize, Deserialize)]
785pub struct GateFixRecord {
786    /// Agent that applied the fix.
787    pub agent: String,
788    /// The gate output the fixer was handed, tail-truncated.
789    pub failed: Vec<CommandOutcome>,
790    /// What the fixer said it changed.
791    #[serde(default)]
792    pub notes: String,
793    /// Did the fix produce a commit?
794    #[serde(default)]
795    pub committed: bool,
796    /// Why the fix step produced nothing.
797    #[serde(default)]
798    pub error: Option<String>,
799}
800
801/// One fixer round spent on a rebase that stopped on a conflict: which fixer,
802/// what it was shown and whether git says the rebase then finished.
803///
804/// The number of these is the budget spent (`graph.review_rounds` is the cap),
805/// written to disk *before* the fixer runs so a park or crash cannot hand the
806/// round back.
807#[derive(Debug, Clone, Serialize, Deserialize)]
808pub struct RebaseFixRecord {
809    /// Agent asked to resolve the conflict.
810    pub agent: String,
811    /// Paths git reported unmerged when the round started.
812    pub paths: Vec<String>,
813    /// The branch tip the rebase started from, so a resumed run can tell a
814    /// worktree still holding those files from one with edits of its own.
815    #[serde(default)]
816    pub from: Option<String>,
817    /// Did git report the rebase finished after the round?
818    #[serde(default)]
819    pub finished: bool,
820    /// Why the round produced nothing (agent failure, quota).
821    #[serde(default)]
822    pub error: Option<String>,
823}
824
825/// The fixer's response to a round.
826#[derive(Debug, Clone, Serialize, Deserialize)]
827pub struct FixRecord {
828    /// Agent that applied the fixes.
829    pub agent: String,
830    /// Finding ids acted on.
831    #[serde(default)]
832    pub addressed: Vec<String>,
833    /// Findings declined, with reasons.
834    #[serde(default)]
835    pub rejected: Vec<Rejection>,
836    /// What changed.
837    #[serde(default)]
838    pub notes: String,
839    /// Did the fix produce a commit?
840    #[serde(default)]
841    pub committed: bool,
842    /// Why the fix step produced nothing.
843    #[serde(default)]
844    pub failed: Option<String>,
845    /// Wall-clock time.
846    #[serde(default)]
847    pub duration_ms: u64,
848    /// How the fixer's own seat was made to answer when its CLI turn ended
849    /// cleanly but without an addressed/rejected report — see
850    /// [`graph::Runner::continue_fix_report`]. `None` for a record written
851    /// before this existed, which must read as "unknown", not as
852    /// [`ContinuationOutcome::NotNeeded`]: an old run really may have hit
853    /// this exact gap and simply had no mechanism to say so.
854    #[serde(default)]
855    pub continuation: Option<ContinuationRecord>,
856}
857
858/// How a node recovered — or failed to recover — a structured report after
859/// the CLI's own turn ended cleanly (a usable, non-empty, exit-0 reply)
860/// without it. A clean CLI turn is not the same fact as the node's own work
861/// being done — see the `fix` node's `continue_fix_report`, which is what
862/// produces this.
863#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
864pub enum ContinuationOutcome {
865    /// The first reply already carried the report; nothing was resumed.
866    NotNeeded,
867    /// A follow-up call in the same session recovered the report.
868    Resumed,
869    /// The continuation budget was spent without ever recovering it.
870    Exhausted,
871    /// A continuation attempt hit the CLI's rate limit; not retried further
872    /// — a quota fails the same way again immediately.
873    QuotaLost,
874    /// No session was left to resume into, so nothing was attempted.
875    NoSession,
876}
877
878/// Cost and outcome of one node's attempt to recover a missing report by
879/// resuming its own seat.
880#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
881pub struct ContinuationRecord {
882    /// Follow-up calls made to the same seat. `0` when the outcome is
883    /// [`ContinuationOutcome::NotNeeded`] or [`ContinuationOutcome::NoSession`].
884    pub attempts: usize,
885    /// Wall-clock time spent on those follow-up calls, summed — not counting
886    /// the original call whose reply this is recovering from.
887    pub cumulative_wait_ms: u64,
888    /// What ended the loop.
889    pub outcome: ContinuationOutcome,
890}
891
892impl ContinuationRecord {
893    /// The report was already there on the first try.
894    pub fn not_needed() -> Self {
895        Self {
896            attempts: 0,
897            cumulative_wait_ms: 0,
898            outcome: ContinuationOutcome::NotNeeded,
899        }
900    }
901}
902
903/// What happened to one operator-selected finding after the fixer ran, as
904/// part of an [`OperatorFixRequest`].
905#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
906#[serde(rename_all = "snake_case")]
907pub enum OperatorFixOutcome {
908    /// The request has not run yet, or never got far enough to report.
909    #[default]
910    Pending,
911    /// The fixer's adoption report named this finding as addressed.
912    Addressed,
913    /// The fixer's adoption report declined it, with an argument.
914    Rejected {
915        /// The fixer's own reason.
916        why: String,
917    },
918    /// The fixer never delivered a usable adoption report at all — a
919    /// dropped stream, a quota hit, or a continuation budget spent without
920    /// recovering one (see `graph::Runner::continue_fix_report`). Distinct
921    /// from `Rejected`, which needs an argument this never produced, and
922    /// never written back as "addressed" or silently left `Pending` — a
923    /// gap in the report is its own outcome, not evidence either way about
924    /// the finding.
925    Unreported,
926}
927
928/// One finding an operator selected for [`OperatorFixRequest`], with the
929/// provenance a reviewer originally gave it, copied here verbatim.
930///
931/// Severity and vote are snapshots, never recomputed and never treated as
932/// blocking just because an operator picked the finding — only
933/// [`Severity::blocks`] on the original [`ReviewRecord`] decides that. This
934/// type exists so an operator's selection is an auditable *addition* to the
935/// record, not a rewrite of what a reviewer actually said.
936#[derive(Debug, Clone, Serialize, Deserialize)]
937pub struct OperatorFixFinding {
938    /// Finding id, e.g. `R2-1-3`.
939    pub id: String,
940    /// Severity as the reviewer recorded it.
941    pub severity: Severity,
942    /// The reviewer seat's overall vote for the round this finding came
943    /// from, if one was cast.
944    #[serde(default)]
945    pub reviewer_vote: Option<ReviewVote>,
946    /// Review round the finding was raised in.
947    pub round: usize,
948    /// That round's own head — the commit the finding was actually raised
949    /// against, used for the freshness check against the branch's current
950    /// head at request time.
951    pub round_head: String,
952    /// Reviewer seat number, 1-based.
953    pub reviewer: usize,
954    /// Agent occupying that seat.
955    pub agent: String,
956    /// File the finding concerns.
957    #[serde(default)]
958    pub file: Option<String>,
959    /// Line the finding concerns.
960    #[serde(default)]
961    pub line: Option<u32>,
962    /// One-line summary.
963    pub title: String,
964    /// The argument.
965    #[serde(default)]
966    pub detail: String,
967    /// What happened to this finding after the fixer ran.
968    #[serde(default)]
969    pub outcome: OperatorFixOutcome,
970}
971
972/// One `magi fix` invocation: the operator's own record of which
973/// already-recorded findings they routed to a fixer, why, and what came
974/// back. See [`SCHEMA`]'s doc for schema 9 on why this is a channel of its
975/// own rather than a field on [`ReviewRound`].
976#[derive(Debug, Clone, Serialize, Deserialize)]
977pub struct OperatorFixRequest {
978    /// When `magi fix` was invoked.
979    pub requested_at: Timestamp,
980    /// The operator's own reasoning. Required and never empty at the CLI —
981    /// the audit trail this feature exists for.
982    pub reason: String,
983    /// The findings selected, each with its own provenance and outcome.
984    pub findings: Vec<OperatorFixFinding>,
985    /// The branch's head at the moment this request started executing.
986    pub head_at_request: String,
987    /// Did the operator pass `--allow-stale`?
988    pub allow_stale: bool,
989    /// Did any selected finding's own `round_head` differ from
990    /// `head_at_request`? Kept distinct from `allow_stale` — flipping that
991    /// flag does not retroactively make a request that was actually fresh
992    /// read as stale, or the reverse.
993    pub stale: bool,
994    /// The fixer's own attempt, once dispatched.
995    #[serde(default)]
996    pub fix: Option<FixRecord>,
997    /// Head after the fixer's commit, when it produced one.
998    #[serde(default)]
999    pub result_head: Option<String>,
1000    /// The review-only run opened to re-verify the change, when one was
1001    /// actually committed. `None` when nothing changed, so there was
1002    /// nothing new to re-review — never left implicit as "not gotten to
1003    /// yet".
1004    #[serde(default)]
1005    pub follow_up_review_run: Option<String>,
1006}
1007
1008/// A command a seat's own CLI reported running, kept for `magi show` and for
1009/// telling "this seat's turn ended" apart from "the process it started is
1010/// done" — see `agent::CommandEvidence`, which is the only source this is
1011/// ever built from. Never something magi polled or supervised; a command the
1012/// CLI never reported finishing (or a CLI this crate has no adapter for at
1013/// all) simply has no entry here, which must read as "unknown", not as
1014/// "nothing ran".
1015#[derive(Debug, Clone, Serialize, Deserialize)]
1016pub struct JobRecord {
1017    /// Graph node the seat belongs to, e.g. `"implement"`, `"fix"`.
1018    pub node: String,
1019    /// Review round this job belongs to, for a `"review"`/`"fix"` node —
1020    /// `None` for every other node, where rounds do not apply, and for every
1021    /// record written before this was tracked. Lets a reader ask "what did
1022    /// this seat itself actually run this round", distinct from and never
1023    /// substituted for magi's own recorded `ReviewRound::e2e` — an absent
1024    /// entry here means unobserved, not that nothing ran (see this type's
1025    /// own doc).
1026    #[serde(default)]
1027    pub round: Option<usize>,
1028    /// Seat key, e.g. `"impl-A"`.
1029    pub seat: String,
1030    /// The CLI's own id for this command.
1031    pub id: String,
1032    /// The command itself, as the CLI reported it.
1033    pub description: String,
1034    /// When this evidence was captured — the moment this seat's reply
1035    /// carrying it was read, not the command's own start time, which no
1036    /// adapter here currently has. A lower bound on staleness only.
1037    pub checked_at: Timestamp,
1038    /// What the CLI reported for it.
1039    pub status: JobStatus,
1040    /// Exit code the CLI reported.
1041    pub exit_code: Option<i32>,
1042    /// Tail of the command's own output, when reported.
1043    #[serde(default)]
1044    pub result_summary: String,
1045    /// Which CLI/event stream this came from, e.g. `"codex"`.
1046    pub source: String,
1047}
1048
1049/// What a [`JobRecord`]'s own CLI reported for it. There is no `Running`
1050/// variant: nothing here is ever polled live, so "still running" and
1051/// "finished but never reported" are the same absence of evidence, not a
1052/// state this type can name — see [`JobRecord`]'s own doc.
1053#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1054pub enum JobStatus {
1055    /// The command's own reported exit code was `0`.
1056    Completed,
1057    /// The command's own reported exit code was non-zero.
1058    Failed,
1059    /// The CLI reported this command but not a readable exit code.
1060    Unknown,
1061}
1062
1063/// Outcome of one shell command.
1064#[derive(Debug, Clone, Serialize, Deserialize)]
1065pub struct CommandOutcome {
1066    /// The command, as configured.
1067    pub command: String,
1068    /// Exit code, `None` on timeout or signal.
1069    pub code: Option<i32>,
1070    /// Tail of the combined output, for the report and the fix prompt.
1071    #[serde(default)]
1072    pub output_tail: String,
1073    /// Wall-clock time.
1074    #[serde(default)]
1075    pub duration_ms: u64,
1076    /// Set only by magi itself, never inferred from `output_tail`: the
1077    /// configured command was never actually run because a resource it
1078    /// needs — right now, only the shared build cache's lease or the
1079    /// freshness check that must precede using it — was not available
1080    /// within budget. Distinct from an ordinary failure or timeout (both of
1081    /// which *did* run something and are evidence about the patch); this is
1082    /// evidence about the machine, and must never be read as a verdict on
1083    /// the tree it named. `#[serde(default)]` so every record written
1084    /// before this field existed keeps reading as `false` — exactly what it
1085    /// was.
1086    #[serde(default)]
1087    pub resource_blocked: bool,
1088}
1089
1090/// Substrings that mark a Cargo/rustc/link failure: the toolchain could not
1091/// produce a binary to run at all, as opposed to producing one that ran and
1092/// failed. A Windows link race against a shared `CARGO_TARGET_DIR` (see
1093/// AGENTS.md, "Running magi on magi") looks exactly like a red command
1094/// otherwise, and a run has concluded `Blocked` on nothing but that race.
1095const BUILD_FAILURE_MARKERS: &[&str] = &[
1096    "error: could not compile",
1097    "error: linking with",
1098    "LINK : fatal error",
1099    "fatal error LNK",
1100];
1101
1102impl CommandOutcome {
1103    /// Did it pass?
1104    pub fn ok(&self) -> bool {
1105        self.code == Some(0)
1106    }
1107
1108    /// Did this command fail because the code could not be built or linked,
1109    /// rather than because it ran and produced a wrong result? A failure here
1110    /// is not a verdict on the patch under review.
1111    pub fn build_failed(&self) -> bool {
1112        !self.ok()
1113            && BUILD_FAILURE_MARKERS
1114                .iter()
1115                .any(|m| self.output_tail.contains(m))
1116    }
1117}
1118
1119/// One review + verify + fix round.
1120#[derive(Debug, Clone, Serialize, Deserialize)]
1121pub struct ReviewRound {
1122    /// 1-based round number.
1123    pub round: usize,
1124    /// Commit the round reviewed.
1125    pub head: String,
1126    /// The commit `e2e` was actually attempted against. Set whenever an
1127    /// attempt was dispatched (`e2e_status()` reads `Passed`, `Failed`, or
1128    /// `ResourceBlocked`), naming that commit even when it equals `head` —
1129    /// never left implicit, because an implicit "must have been `head`" is
1130    /// exactly what let a later round quote an earlier round's result
1131    /// without saying which commit it came from. A resource-blocked attempt
1132    /// still targeted a specific commit even though no command finished, and
1133    /// leaving that unrecorded is exactly what made a *fresh* blocked
1134    /// attempt read the same as an untracked one from before schema 8.
1135    /// `None` only when nothing was attempted at all (`NotConfigured`,
1136    /// `Deferred`). See `SCHEMA`'s doc for schema 8 for why this broadened
1137    /// from only the catch-up-on-a-different-commit case.
1138    #[serde(default)]
1139    pub verified_head: Option<String>,
1140    /// When the attempt behind `verified_head` actually ran. `None` on
1141    /// every record written before schema 8, and on a round where nothing
1142    /// ran —
1143    /// both read as "unknown", not as "now" or "never asked".
1144    #[serde(default)]
1145    pub verified_at: Option<Timestamp>,
1146    /// Reviewer reports.
1147    pub reviews: Vec<ReviewRecord>,
1148    /// E2E command outcomes for this round.
1149    #[serde(default)]
1150    pub e2e: Vec<CommandOutcome>,
1151    /// True when the first verify attempt this round could not build or
1152    /// link, and `e2e` above holds a second attempt run before concluding.
1153    /// A run must never be decided on a red it could not tell from an
1154    /// unrelated build race.
1155    #[serde(default)]
1156    pub verify_retried: bool,
1157    /// True when `e2e` was intentionally left empty this round: the round
1158    /// already had blocking findings and another round was available, so
1159    /// `graph::Runner::review_loop` sent the fixer straight at them instead
1160    /// of spending a full verify run on a head it already knew would need
1161    /// another fix. Distinct from an `e2e` that is simply empty because
1162    /// `verify.e2e` has no commands configured — `e2e.is_empty()` alone
1163    /// cannot tell those apart, and conflating them is exactly how a
1164    /// deferred check would get painted green. A record written before this
1165    /// field existed defaults to `false`, which is the truth for it: every
1166    /// round used to run e2e unconditionally.
1167    #[serde(default)]
1168    pub e2e_deferred: bool,
1169    /// Why `e2e` was deferred, set only when [`Self::e2e_deferred`] is true.
1170    /// Carried to the fixer's prompt and shown in the report so "deferred"
1171    /// never reads as silence.
1172    #[serde(default)]
1173    pub e2e_defer_reason: Option<String>,
1174    /// Fixer response, absent when the round was already clean.
1175    #[serde(default)]
1176    pub fix: Option<FixRecord>,
1177    /// Findings that hold the merge.
1178    #[serde(default)]
1179    pub blocking: usize,
1180    /// Reviewer seats that answered (did not time out, crash, or return
1181    /// something unparsable).
1182    #[serde(default)]
1183    pub answered: usize,
1184    /// Reviewer seats the round expected an answer from — normally
1185    /// `graph.reviewers`, but recorded per round so a config change between
1186    /// runs never has to be inferred from history.
1187    #[serde(default)]
1188    pub expected: usize,
1189    /// Round ended with no blocking findings and green verification, judged
1190    /// against the seats that answered. See [`Self::incomplete`] for whether
1191    /// that verdict is missing input.
1192    #[serde(default)]
1193    pub clean: bool,
1194    /// Did the tree actually move against `base` this round, comparing the
1195    /// diff after the fix to the diff the reviewers saw at the start of the
1196    /// round?
1197    ///
1198    /// Never derived from the fixer's own `addressed`/`rejected` count: that
1199    /// self-report has been caught lying twice on this workload (runs `b455`
1200    /// and `6218`, both of which committed a real, substantial diff while
1201    /// reporting `0 addressed`). `git` does not lie about whether the tree
1202    /// changed, so this is what `graph::Runner::review_loop` counts rounds of
1203    /// no progress against. Absent on a round with no fix attempt (already
1204    /// clean, or the round the budget ran out on), where it defaults to
1205    /// `false` and is not consulted.
1206    #[serde(default)]
1207    pub progressed: bool,
1208    /// Did the seats' initial votes ([`ReviewRecord::vote`]) disagree?
1209    #[serde(default)]
1210    pub vote_split: bool,
1211    /// One round of revoting, run only when `vote_split`: each seat that cast
1212    /// an initial vote reads every seat's findings and votes, then revotes.
1213    /// Empty when the initial votes already agreed, the same as a solo
1214    /// candidate leaving `deliberation` empty.
1215    #[serde(default)]
1216    pub reconsideration: Vec<ReviewRevoteRecord>,
1217    /// The round's verdict: the most cautious vote among the seats that
1218    /// answered, using each seat's revote where reconsideration ran and its
1219    /// initial vote otherwise. `None` when no seat produced a usable vote —
1220    /// including every record written before votes existed, which is the
1221    /// truth for those rounds, not a gap in this one.
1222    #[serde(default)]
1223    pub verdict: Option<ReviewVote>,
1224}
1225
1226/// A merge-approval question and the head commit it was asked about.
1227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1228pub struct LandApproval {
1229    /// Id of the question that was filed for `head`.
1230    pub question: String,
1231    /// The commit the question's panel was built from.
1232    pub head: String,
1233}
1234
1235/// The owner question filed when the posting gate withheld a pull request
1236/// title or description, and how it ended. One record per rejected text
1237/// (`fingerprint`); see `github_text` for the flow.
1238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1239pub struct GithubTextAsk {
1240    /// Hash of the rejected title and body; the text itself is never stored.
1241    pub fingerprint: String,
1242    /// The title is withheld.
1243    pub title: bool,
1244    /// The description is withheld.
1245    pub body: bool,
1246    /// Rule categories that fired.
1247    pub categories: Vec<String>,
1248    /// The question currently standing, if one was filed.
1249    #[serde(default)]
1250    pub question: Option<String>,
1251    /// Questions filed so far (at most 2: the second follows a bad reply).
1252    #[serde(default)]
1253    pub asks: u32,
1254    /// The decision has been made (saved before the pull request is opened,
1255    /// so it is applied once and survives a restart).
1256    #[serde(default)]
1257    pub resolved: bool,
1258    /// With `resolved`: the owner's vetted replacement title; `None` means the
1259    /// neutral text for every withheld field.
1260    #[serde(default)]
1261    pub chosen_title: Option<String>,
1262}
1263
1264/// A review hand-off the panel did not agree to: findings that hold the merge
1265/// are still open and at least one seat's final vote was reject. Recorded on
1266/// [`RunState::contested_handoff`] so `land` can name them in its question.
1267#[derive(Debug, Clone, Serialize, Deserialize)]
1268pub struct ContestedHandoff {
1269    /// Open findings of severity Major or above, in report order.
1270    pub findings: Vec<Finding>,
1271    /// Seats (1-based) whose final vote was reject, with the agent in the seat.
1272    pub rejecters: Vec<(usize, String)>,
1273}
1274
1275impl ReviewRound {
1276    /// Each answering seat's final vote: its revote where reconsideration ran
1277    /// and answered, its initial vote otherwise. The single place this is
1278    /// decided, shared by the round's verdict and [`Self::contested_handoff`].
1279    pub fn final_votes(&self) -> Vec<(usize, String, ReviewVote)> {
1280        self.reviews
1281            .iter()
1282            .filter_map(|r| {
1283                self.reconsideration
1284                    .iter()
1285                    .find(|rv| rv.reviewer == r.reviewer)
1286                    .and_then(|rv| rv.vote)
1287                    .or(r.vote)
1288                    .map(|v| (r.reviewer, r.agent.clone(), v))
1289            })
1290            .collect()
1291    }
1292
1293    /// Is this round's hand-off contested: a Major-or-above finding open and
1294    /// at least one final vote of reject? `None` otherwise. Kept as one small
1295    /// function so anything deciding on it reads the same answer.
1296    pub fn contested_handoff(&self) -> Option<ContestedHandoff> {
1297        let findings: Vec<Finding> = self
1298            .reviews
1299            .iter()
1300            .flat_map(|r| r.findings.iter())
1301            .filter(|f| f.severity.blocks())
1302            .cloned()
1303            .collect();
1304        if findings.is_empty() {
1305            return None;
1306        }
1307        let rejecters: Vec<(usize, String)> = self
1308            .final_votes()
1309            .into_iter()
1310            .filter(|(_, _, v)| *v == ReviewVote::Reject)
1311            .map(|(seat, agent, _)| (seat, agent))
1312            .collect();
1313        if rejecters.is_empty() {
1314            return None;
1315        }
1316        Some(ContestedHandoff {
1317            findings,
1318            rejecters,
1319        })
1320    }
1321
1322    /// Did at least one reviewer seat fail to answer this round?
1323    pub fn incomplete(&self) -> bool {
1324        self.answered < self.expected
1325    }
1326
1327    /// The honest state of this round's e2e leg.
1328    ///
1329    /// Never derive this from `e2e.is_empty()` alone anywhere else in the
1330    /// codebase — `NotConfigured` and `Deferred` both leave it empty, and
1331    /// only this method (backed by [`Self::e2e_deferred`]) tells them apart.
1332    /// A resource-blocked attempt is checked first and ahead of both: `e2e`
1333    /// is non-empty for it too, but `CommandOutcome::resource_blocked` says
1334    /// no command actually ran, and reading that as `Failed` is exactly how
1335    /// shared build-cache contention gets misreported as a verdict on the
1336    /// patch (see `CommandOutcome::resource_blocked`'s own doc).
1337    pub fn e2e_status(&self) -> E2eStatus {
1338        if self.e2e.iter().any(|o| o.resource_blocked) {
1339            E2eStatus::ResourceBlocked
1340        } else if !self.e2e.is_empty() {
1341            if self.e2e.iter().all(CommandOutcome::ok) {
1342                E2eStatus::Passed
1343            } else {
1344                E2eStatus::Failed
1345            }
1346        } else if self.e2e_deferred {
1347            E2eStatus::Deferred
1348        } else {
1349            E2eStatus::NotConfigured
1350        }
1351    }
1352
1353    /// Facts about this round's verification leg, judged against
1354    /// `current_head` — the commit whoever is asking is actually looking at
1355    /// right now. `None` when there is nothing worth surfacing: no
1356    /// `verify.e2e` configured, or the round's own check came back green (a
1357    /// passing result needs no skepticism attached to it, and an unread
1358    /// `None` is exactly what keeps a quiet round quiet instead of padding
1359    /// every prompt with "everything was fine").
1360    ///
1361    /// This is the single place that turns `e2e`/`e2e_deferred`/
1362    /// `verified_head`/`verified_at` into text. Every prompt and report that
1363    /// shows a round's verification result must build its wording from this,
1364    /// not re-derive its own summary at the call site — a hand-rolled
1365    /// version at one more place is exactly how "an old red read as today's
1366    /// answer" comes back through a different door (see the incident this
1367    /// type exists to prevent, recorded alongside `SCHEMA`'s doc for schema
1368    /// 8).
1369    pub fn verification_summary(&self, current_head: &str) -> Option<VerificationSummary> {
1370        let status = self.e2e_status();
1371        if matches!(status, E2eStatus::NotConfigured | E2eStatus::Passed) {
1372            return None;
1373        }
1374        let commit = match &self.verified_head {
1375            Some(h) if h == current_head => {
1376                format!("commit {} (this is the head being looked at now)", short(h))
1377            }
1378            Some(h) => format!("commit {} (an earlier head, since superseded)", short(h)),
1379            None => "commit unknown (no command finished checking one)".to_owned(),
1380        };
1381        let checked_at = match self.verified_at {
1382            Some(t) => format!("checked at {t}"),
1383            None => "checked at: unknown (recorded before this was tracked)".to_owned(),
1384        };
1385        let result = match status {
1386            E2eStatus::NotConfigured | E2eStatus::Passed => unreachable!("checked above"),
1387            E2eStatus::Failed => "result: FAILED".to_owned(),
1388            E2eStatus::Deferred => format!(
1389                "result: not run this round yet — deferred to the fixer{}. Not passed, not \
1390                 failed.",
1391                self.e2e_defer_reason
1392                    .as_deref()
1393                    .map(|why| format!(" ({why})"))
1394                    .unwrap_or_default()
1395            ),
1396            E2eStatus::ResourceBlocked => "result: could not run — the shared build cache was \
1397                                            not available. This is evidence about the machine, \
1398                                            not about the patch."
1399                .to_owned(),
1400        };
1401        let label = format!("round {}, {commit}, {checked_at}\n{result}", self.round);
1402        // `Failed` names the command that actually ran and failed;
1403        // `ResourceBlocked` names the operation magi was waiting on (or the
1404        // freshness check it could not confirm) — `command` still says what
1405        // was attempted even though nothing finished, and leaving it out is
1406        // exactly how a reviewer or fixer lost the one thing this leg *can*
1407        // still tell them: what was being checked, not whether it passed.
1408        let tail = matches!(status, E2eStatus::Failed | E2eStatus::ResourceBlocked).then(|| {
1409            self.e2e
1410                .iter()
1411                .filter(|o| !o.ok())
1412                .map(|o| format!("$ {}\n{}\n", o.command, o.output_tail))
1413                .collect::<String>()
1414        });
1415        Some(VerificationSummary { label, tail })
1416    }
1417}
1418
1419/// The honest state of a round's e2e leg. See [`ReviewRound::e2e_status`].
1420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1421pub enum E2eStatus {
1422    /// `verify.e2e` has no commands configured.
1423    NotConfigured,
1424    /// Skipped this round on purpose: blocking findings already required a
1425    /// fix, so the round went straight to the fixer instead of spending a
1426    /// full verify run on a head it already knew would need another pass.
1427    Deferred,
1428    /// Ran, and every command exited 0.
1429    Passed,
1430    /// Ran, and at least one command did not exit 0.
1431    Failed,
1432    /// Magi could not even get a command to run — the shared build cache's
1433    /// lease or freshness check was not available within budget. Evidence
1434    /// about the machine, never a verdict on the tree it named; must not be
1435    /// shown or counted the same as [`Self::Failed`].
1436    ResourceBlocked,
1437}
1438
1439/// [`ReviewRound::verification_summary`]'s output: the facts, pre-worded, for
1440/// a prompt or report to place under its own heading. Kept as two pieces
1441/// rather than one pre-joined string so a caller that wants to insert its own
1442/// note between the label and the raw command tail (see `prompt::review`) can
1443/// do so without re-parsing text back apart.
1444#[derive(Debug, Clone)]
1445pub struct VerificationSummary {
1446    /// Round, commit, freshness and result — always present.
1447    pub label: String,
1448    /// Raw `$ command` / output tail, present for `result: FAILED` and for
1449    /// a resource-blocked attempt (naming the operation magi was waiting on,
1450    /// even though nothing finished) — absent for every other result, which
1451    /// has nothing to add past the label.
1452    pub tail: Option<String>,
1453}
1454
1455/// The honest state of a run's final gate. See [`RunState::gate_status`].
1456#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1457pub enum GateStatus {
1458    /// Never attempted, or the last attempt was resource-blocked (the shared
1459    /// build cache could not be acquired or confirmed fresh in time) and
1460    /// needs a retry.
1461    NotRun,
1462    /// Ran with zero commands configured (`verify.gate` is empty) and
1463    /// therefore vacuously passed — there was nothing to check.
1464    PassedWithNoCommands,
1465    /// Ran one or more commands, and every one of them exited 0.
1466    Passed,
1467    /// Ran one or more commands, and at least one did not exit 0.
1468    Failed,
1469}
1470
1471impl GateStatus {
1472    /// May a run in this state proceed to merge?
1473    pub fn ok(self) -> bool {
1474        matches!(self, Self::PassedWithNoCommands | Self::Passed)
1475    }
1476}
1477
1478/// What happened to the winning branch.
1479#[derive(Debug, Clone, Serialize, Deserialize)]
1480pub struct MergeOutcome {
1481    /// Requested mode.
1482    pub mode: MergeMode,
1483    /// Did it land?
1484    pub ok: bool,
1485    /// Command output, or the command the operator should run.
1486    #[serde(default)]
1487    pub detail: String,
1488    /// The winner had no commits ahead of the base, so no pull request was
1489    /// attempted. Distinct from a `gh` failure: nothing was wrong with the
1490    /// tooling, there was simply nothing to land.
1491    #[serde(default)]
1492    pub empty: bool,
1493}
1494
1495/// A seat currently mid-answer: a prompt was sent and no reply has landed yet.
1496///
1497/// This is not the whole story of "is it alive" — a daemon killed mid-wave
1498/// leaves its last wave's entries here forever, since nothing ran to clear
1499/// them. A reader must cross-check a live daemon's heartbeat
1500/// (`daemon::is_working_on`) before trusting one of these as "still running"
1501/// rather than "abandoned". [`RunState::clear_active`] is what keeps that
1502/// leftover from surviving into the next attempt at this run: `execute` calls
1503/// it before doing anything else, so a resumed run never carries a stale
1504/// entry into its own report before the next wave repopulates it.
1505///
1506/// Deliberately carries no agent id: an implementer's agent is no secret, but
1507/// a judge or reviewer seat is blind (`SeatState::key` is keyed by seat, never
1508/// agent, for exactly this reason), and this struct has no way to tell which
1509/// kind of seat it describes. The seat key alone — already in the map this
1510/// lives under — is what every caller needs to say which seat is running.
1511///
1512/// The same map also carries entries for shell-command work that runs
1513/// outside any seat — `verify.e2e`, `verify.gate` — keyed by the task's own
1514/// name (`"e2e"`, `"gate"`) rather than a seat key. [`Self::task`] is `Some`
1515/// only for those; it is how a reader tells the two kinds of entry apart
1516/// without a second map, a second route, or a second SSE reason to poll for
1517/// — see [`RunState::seats_active`] / [`RunState::tasks_active`] for the
1518/// accessors that split them back apart. A task entry is exactly as blind as
1519/// a seat entry: no agent runs it, so there is nothing to leak, and
1520/// [`Self::command`] carries only the shell command being run, never
1521/// anything about who is running it.
1522#[derive(Debug, Clone, Serialize, Deserialize)]
1523pub struct ActiveSeat {
1524    /// Node the seat is answering for, e.g. `implement`, `judge`, `review`.
1525    /// For a task entry, the node the command list runs under (`verify`,
1526    /// `gate`).
1527    pub node: String,
1528    /// When this attempt — or, for a task entry, this one command — was
1529    /// started. A task entry's timer resets at every command boundary,
1530    /// because `verify.e2e` / `verify.gate` apply their timeout per command,
1531    /// not once across the whole list — see [`RunState::task_command`].
1532    pub started_at: Timestamp,
1533    /// The wall-clock budget for this attempt (a seat) or this one command
1534    /// (a task entry).
1535    pub timeout_secs: u64,
1536    /// 0 for the first ask, N for the Nth nudge or resume. For a task entry,
1537    /// 0 for the first pass over the command list, N for the Nth retry (see
1538    /// `run_e2e_with_retry`'s build/link retry).
1539    #[serde(default)]
1540    pub attempt: usize,
1541    /// `None` for a seat; `Some("e2e")` / `Some("gate")` for a running
1542    /// command-list task. This is the type tag that lets both kinds of entry
1543    /// share one map without a task ever being mistaken for a (blind) seat —
1544    /// see this struct's own doc. Omitted from JSON when absent (the common,
1545    /// seat case), rather than written out as a literal `null` on every one
1546    /// of a run's seat entries.
1547    #[serde(default, skip_serializing_if = "Option::is_none")]
1548    pub task: Option<String>,
1549    /// The command currently running, task entries only. Never set on a
1550    /// seat entry — a seat has no command, only a prompt, and a prompt is
1551    /// not safe to show mid-run (see this struct's blindness note).
1552    #[serde(default, skip_serializing_if = "Option::is_none")]
1553    pub command: Option<String>,
1554    /// 1-based position of [`Self::command`] within the task's command list.
1555    #[serde(default, skip_serializing_if = "Option::is_none")]
1556    pub index: Option<usize>,
1557    /// Number of commands in the task's list.
1558    #[serde(default, skip_serializing_if = "Option::is_none")]
1559    pub total: Option<usize>,
1560}
1561
1562impl ActiveSeat {
1563    /// Seconds since this attempt was sent.
1564    #[must_use]
1565    pub fn elapsed_secs(&self, now: Timestamp) -> i64 {
1566        (now.as_second() - self.started_at.as_second()).max(0)
1567    }
1568
1569    /// Seconds left before this attempt's own timeout fires, floored at zero
1570    /// rather than going negative once the CLI has overrun its budget.
1571    #[must_use]
1572    pub fn remaining_secs(&self, now: Timestamp) -> i64 {
1573        (self.timeout_secs as i64 - self.elapsed_secs(now)).max(0)
1574    }
1575}
1576
1577/// Whether a process is provably still driving a run, provably not, or
1578/// neither — see [`RunState::liveness`]. Serialized as a lowercase string
1579/// (`"live"` / `"dead"` / `"unknown"`) rather than a bool: a bool has no room
1580/// for "could not tell", and folding that case into either `true` or `false`
1581/// is exactly the wrong call for a display an operator uses to decide
1582/// whether to wait or to act — see the schema-10 field doc on
1583/// [`RunState::driver_pid`] for the report it used to produce instead.
1584#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1585#[serde(rename_all = "lowercase")]
1586pub enum Liveness {
1587    /// Proven: a daemon's heartbeat claims the run, or `driver_pid` answers
1588    /// alive under the same identity (`driver_started_at`) this run recorded
1589    /// for it.
1590    Live,
1591    /// Proven: no daemon claim, and either `driver_pid` answers dead outright
1592    /// or it answers alive under a *different* identity than recorded — a
1593    /// pid the OS has since handed to an unrelated process is exactly as
1594    /// good as proof the original driver is gone (see
1595    /// [`RunState::driver_started_at`]'s own doc).
1596    Dead,
1597    /// Neither proven — no daemon claim, and either no `driver_pid` to ask,
1598    /// the platform could not answer for it, or a live pid with nothing (or
1599    /// nothing queryable) to corroborate its identity against. Never treated
1600    /// as `Dead`: see [`RunState::liveness_with`].
1601    Unknown,
1602}
1603
1604/// A timestamped note about a node.
1605#[derive(Debug, Clone, Serialize, Deserialize)]
1606pub struct Event {
1607    /// When.
1608    pub at: Timestamp,
1609    /// Node name.
1610    pub node: String,
1611    /// What happened.
1612    pub message: String,
1613}
1614
1615/// How far the winner's tree trailed the landing base, last time it was
1616/// checked, and what came of trying to close that gap.
1617///
1618/// Set by `graph::Runner::sync_to_base`, which runs before the review loop and
1619/// again before the gate: verifying against a tree that does not yet contain
1620/// the base's tip answers "green on the commit this run branched from", not
1621/// "green on what is about to land", and a merge on that answer can revert
1622/// whatever landed elsewhere while the run was thinking.
1623#[derive(Debug, Clone, Serialize, Deserialize)]
1624pub struct BaseSync {
1625    /// `<remote>/<base>` tip the tree was last checked against.
1626    pub tip: String,
1627    /// Commits `tip` was ahead of the tree at that check, before any rebase
1628    /// this round tried to close the gap. Zero means the tree already
1629    /// contained `tip`.
1630    pub behind: usize,
1631    /// Rebase attempts spent so far this run, bounded by
1632    /// `graph::BASE_SYNC_ROUNDS`.
1633    pub attempts: usize,
1634    /// What git said, if the most recent rebase attempt conflicted or could
1635    /// not be pushed. `Some` here is what makes a `Blocked` run read as
1636    /// "stopped on the base, not on review or the gate" - the rebase is not
1637    /// retried again while this is set; a person has to look.
1638    #[serde(default)]
1639    pub conflict: Option<String>,
1640    /// Set when the winner's whole change turned out to be on the base already
1641    /// under other commit ids (see [`crate::already`]). Present exactly when the
1642    /// run ended as [`RunStatus::AlreadyInBase`].
1643    #[serde(default)]
1644    pub already_in: Option<crate::already::Evidence>,
1645}
1646
1647/// What the land loop saw last time it looked at the pull request.
1648///
1649/// Strings for `state` and `checks` on purpose: they are `gh`'s vocabulary, and
1650/// pinning them into an enum here would mean a new GitHub check conclusion
1651/// turns a readable status into a deserialisation error on a run someone is
1652/// trying to look at.
1653#[derive(Debug, Clone, Serialize, Deserialize)]
1654pub struct PrRecord {
1655    /// Pull request url.
1656    pub url: String,
1657    /// Pull request number.
1658    pub number: u64,
1659    /// `open`, `merged` or `closed`.
1660    pub state: String,
1661    /// `pending`, `green`, `red` or `unknown`.
1662    pub checks: String,
1663    /// Land round, 1-based, or 0 before the first fix.
1664    pub round: usize,
1665    /// Land round budget.
1666    pub rounds: usize,
1667    /// Checks that were red when the pull request merged anyway (the forge
1668    /// said they do not block it). Empty for a green merge, and for any run
1669    /// recorded before this field existed - so empty is not proof nothing was
1670    /// red.
1671    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1672    pub red_at_merge: Vec<String>,
1673}
1674
1675/// What the post-merge release-bump step did, and whether it needs a human.
1676///
1677/// Recorded next to the `bump` events rather than instead of them: the events
1678/// are the narrative, this is what `magi show`, the status word and the
1679/// notification read without parsing prose. `status` stays `Merged` - the
1680/// merge did happen - so [`RunState::needs_attention`] is the one place that
1681/// says a merged run is not fully done.
1682#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1683pub struct ReleaseBump {
1684    /// The release pull request, when one was opened.
1685    #[serde(default)]
1686    pub pr_url: Option<String>,
1687    /// The version it releases.
1688    #[serde(default)]
1689    pub version: Option<String>,
1690    /// Did enabling automerge on `pr_url` succeed?
1691    #[serde(default)]
1692    pub automerge_enabled: bool,
1693    /// GitHub refused automerge because CI had already finished (the pull
1694    /// request was in clean status), so magi merged it directly. Kept apart
1695    /// from `automerge_enabled`, which stays the plain fact it says it is.
1696    #[serde(default)]
1697    pub merged_directly: bool,
1698    /// `[release] mode = "local"`: no automerge was armed; the pull request is
1699    /// merged on the owner's approval and released by `magi serve`
1700    /// ([`crate::release_local`]).
1701    #[serde(default)]
1702    pub local: bool,
1703    /// What the local release did (tag, commit, each command's exit code and
1704    /// output tail), kept here because the watcher's own record is deleted
1705    /// once the release is done.
1706    #[serde(default)]
1707    pub release: Option<crate::release_local::Job>,
1708    /// What went wrong, verbatim from the tool that said it.
1709    #[serde(default)]
1710    pub problem: Option<String>,
1711    /// What the operator has to do about it. `Some` is what makes a merged run
1712    /// read as needing attention.
1713    #[serde(default)]
1714    pub action_required: Option<String>,
1715}
1716
1717/// The whole run.
1718#[derive(Debug, Clone, Serialize, Deserialize)]
1719pub struct RunState {
1720    /// On-disk format version.
1721    pub schema: u32,
1722    /// Run id, e.g. `20260830-153012-a1b2`.
1723    pub id: String,
1724    /// Repository the run operates on.
1725    pub repo: PathBuf,
1726    /// Branch the run started from.
1727    pub base_branch: String,
1728    /// Commit the run started from.
1729    pub base_commit: String,
1730    /// The task, verbatim.
1731    pub instruction: String,
1732    /// When the run was created.
1733    pub created_at: Timestamp,
1734    /// Last state flush.
1735    pub updated_at: Timestamp,
1736    /// Current status.
1737    pub status: RunStatus,
1738    /// Seed for labels and session ids.
1739    pub seed: u64,
1740    /// Config snapshot, so a resumed run behaves like the original.
1741    pub config: Config,
1742    /// Did this run take a reference on `extensions.worktreeConfig` being on
1743    /// (see [`crate::git::acquire_worktree_config`])? If so, cleanup releases
1744    /// it - which only actually turns the setting back off once every other
1745    /// run sharing this repository has released its own reference too.
1746    #[serde(default)]
1747    pub enabled_worktree_config: bool,
1748    /// Candidates.
1749    #[serde(default)]
1750    pub candidates: Vec<Candidate>,
1751    /// Initial blind rankings.
1752    #[serde(default)]
1753    pub judgements: Vec<Judgement>,
1754    /// `judge` decided a solo candidate needs no panel and only logged it.
1755    ///
1756    /// `judgements` stays empty in that case — nothing to distinguish from
1757    /// "not yet judged" — so this is the record that makes the skip
1758    /// idempotent: without it, every reentry re-ran `judge`, re-logged the
1759    /// same event, and rewrote `status` to `Judging` over whatever a later
1760    /// node had already concluded.
1761    #[serde(default)]
1762    pub judge_skipped: bool,
1763    /// Deliberation, if it happened.
1764    #[serde(default)]
1765    pub deliberation: Vec<DeliberationRound>,
1766    /// Private final votes.
1767    #[serde(default)]
1768    pub votes: Vec<VoteRecord>,
1769    /// The count.
1770    #[serde(default)]
1771    pub tally: Option<Tally>,
1772    /// Review rounds.
1773    #[serde(default)]
1774    pub reviews: Vec<ReviewRound>,
1775    /// Final gate.
1776    ///
1777    /// Never derive whether the gate has run from `gate.is_empty()` alone —
1778    /// use [`Self::gate_status`] instead. An empty list is ambiguous on its
1779    /// own: it is what an unattempted gate looks like, what a
1780    /// resource-blocked attempt leaves behind (see `graph::Runner::gate`'s
1781    /// own doc), and also what a repo with no `verify.gate` commands
1782    /// configured produces once it *has* run. [`Self::gate_ran`] is what
1783    /// tells the third case apart from the first two.
1784    #[serde(default)]
1785    pub gate: Vec<CommandOutcome>,
1786    /// Did `gate()` actually record an attempt — zero commands configured
1787    /// and vacuously passed, or one or more commands that ran to
1788    /// completion — as opposed to never having run, or having last hit a
1789    /// resource-blocked retry?
1790    ///
1791    /// `gate.is_empty()` cannot tell those apart by itself: a repo with no
1792    /// `verify.gate` commands leaves `gate` empty exactly like an
1793    /// unattempted or resource-blocked one does, and reading that empty list
1794    /// as "not yet run" is what stranded a review-only run in
1795    /// `RunStatus::Gating` forever on such a repo — see `SCHEMA`'s doc for
1796    /// schema 7. A record written before this field existed defaults to
1797    /// `false` and is migrated in [`migrate_schema`].
1798    #[serde(default)]
1799    pub gate_ran: bool,
1800    /// Fix rounds a failing gate has already spent, oldest first. Persisted
1801    /// right after each fixer call so a resumed run spends only what is left
1802    /// of `graph.gate_fix_rounds` instead of starting the budget over.
1803    #[serde(default)]
1804    pub gate_fixes: Vec<GateFixRecord>,
1805    /// Fixer rounds spent on a rebase conflict (base sync and land share one
1806    /// budget, `graph.review_rounds`), oldest first. Persisted right before
1807    /// each fixer call, so a resumed run spends only what is left.
1808    #[serde(default)]
1809    pub rebase_fixes: Vec<RebaseFixRecord>,
1810    /// Set at the review loop's hand-off when the last round ended with a
1811    /// blocking finding still open *and* a reviewer's final vote was reject
1812    /// (see [`ReviewRound::contested_handoff`]). `land` reads it to ask the
1813    /// owner before merging even with `graph.land_approval` off. A snapshot
1814    /// taken at hand-off, never recomputed later.
1815    #[serde(default)]
1816    pub contested_handoff: Option<ContestedHandoff>,
1817    /// The head commit `land` has armed (or is about to arm) GitHub auto-merge
1818    /// on. Saved *before* the arm call, so a crash right after it still tells
1819    /// a resume that the forge may be holding an armed merge. Cleared the
1820    /// moment auto-merge is disabled or the pull request is done.
1821    #[serde(default)]
1822    pub land_armed_head: Option<String>,
1823    /// The merge-approval question `land` last filed, and the head commit its
1824    /// panel showed. An answer is only honoured for that exact commit: a fix
1825    /// or rebase push makes a new head the owner has not seen.
1826    #[serde(default)]
1827    pub land_approval: Option<LandApproval>,
1828    /// The posting-gate question for this run's pull request text, if the gate
1829    /// withheld any. While `resolved` is `None` the run is parked on it.
1830    #[serde(default)]
1831    pub github_text: Option<GithubTextAsk>,
1832    /// Outcomes of the `verify.pre_gate` commands from the latest time they
1833    /// ran on the winner. Informational only: a failure here never blocks the
1834    /// run, the gate stays the single arbiter. Overwritten on each pass.
1835    #[serde(default)]
1836    pub pre_gate: Vec<CommandOutcome>,
1837    /// The latest commit a `pre_gate` pass made, if any pass left changes.
1838    #[serde(default)]
1839    pub pre_gate_commit: Option<String>,
1840    /// Merge outcome.
1841    #[serde(default)]
1842    pub merge: Option<MergeOutcome>,
1843    /// Vendor tokens seen in judged material.
1844    #[serde(default)]
1845    pub leaks: Vec<Leak>,
1846    /// Seats lost to a CLI rate limit / quota, in the order they hit.
1847    #[serde(default)]
1848    pub quota: Vec<QuotaLoss>,
1849    /// Seats handed to the next roster agent after a failure, in order.
1850    /// Additive, so `SCHEMA` is not bumped.
1851    #[serde(default)]
1852    pub handovers: Vec<Handover>,
1853    /// How many agent-change seats this run has minted; mixed into their
1854    /// session ids so re-handing a seat to an agent it already had never
1855    /// reuses that agent's earlier uuid. Additive.
1856    #[serde(default)]
1857    pub seat_epoch: u64,
1858    /// Per reviewer seat, which roster agents already failed it and which one
1859    /// last answered, carried across review rounds. Additive, so `SCHEMA` is
1860    /// not bumped. See [`SeatHistory`].
1861    #[serde(default)]
1862    pub seat_history: BTreeMap<String, SeatHistory>,
1863    /// Stray foreign lockfiles a rescue commit left out, one entry per path.
1864    #[serde(default)]
1865    pub withheld: Vec<Withheld>,
1866    /// Parked at a node boundary, waiting to be resumed.
1867    ///
1868    /// A run that is neither finished nor being worked on is otherwise
1869    /// indistinguishable from one whose daemon was killed, and the two want
1870    /// opposite things from an operator: the first is expected to be resumed,
1871    /// the second is a leftover. Cleared by the resume that carries it on.
1872    #[serde(default)]
1873    pub parked: bool,
1874    /// The run that took this run's worktree over, when one did — see
1875    /// [`crate::handover`]. `Some` means the worktree is gone on purpose and
1876    /// the run can no longer be resumed from it ([`Self::released`]).
1877    #[serde(default)]
1878    pub released_to: Option<String>,
1879    /// Branches that outlived this run's released worktree and now belong to
1880    /// the run in [`Self::released_to`] (and to its pull request). A later
1881    /// fold must leave them alone.
1882    #[serde(default)]
1883    pub released_branches: Vec<String>,
1884    /// Existing branches and commits the task text names, and what the
1885    /// repository says about each (`crate::refs`). Unmerged ones seed the
1886    /// candidates; `base_commit` stays the comparison point.
1887    #[serde(default)]
1888    pub seeds: Vec<crate::refs::Seed>,
1889    /// Per-seat conversation state.
1890    #[serde(default)]
1891    pub seats: BTreeMap<String, SeatState>,
1892    /// Seats currently mid-answer, keyed by seat.
1893    ///
1894    /// An entry exists from the moment a prompt is sent until a reply (of any
1895    /// kind — success, failure, quota, drop) comes back, so its keys are
1896    /// exactly "who hasn't answered yet" for whichever node populated it. See
1897    /// [`ActiveSeat`] for why a reader still has to check a live daemon
1898    /// before trusting one of these as "running" rather than "abandoned".
1899    #[serde(default)]
1900    pub active: BTreeMap<String, ActiveSeat>,
1901    /// Process id of whichever `execute()` call last drove this run —
1902    /// written at the very top of that method, the same place
1903    /// [`Self::clear_active`] runs, so a fresh reentry always overwrites the
1904    /// pid a previous, possibly-dead process left behind.
1905    ///
1906    /// A daemon-claimed run already has a stronger signal
1907    /// (`daemon::is_working_on`), but a `magi run` / `magi review` typed
1908    /// straight into a terminal claims nothing there — before this field
1909    /// existed, [`report::active_seats`] had no way to tell that run apart
1910    /// from one a killed process abandoned, and printed the same "no live
1911    /// daemon claims this run" warning over a run that was, in fact, still
1912    /// answering. See [`Liveness`] for how this and the daemon claim combine.
1913    #[serde(default)]
1914    pub driver_pid: Option<u32>,
1915    /// The OS-reported moment [`Self::driver_pid`] started, recorded in the
1916    /// same breath as the pid itself — an opaque marker
1917    /// (`crate::proc::process_started_at`, epoch seconds as an integer
1918    /// string), compared only for equality. Older runs hold a locale-dependent
1919    /// string here; those read as `Unknown`, never `Dead`.
1920    ///
1921    /// A pid alone never proves a live process is *this run's* driver: pids
1922    /// get reused, sometimes within minutes on a busy machine, and a killed
1923    /// manual `magi run` whose pid a later, wholly unrelated process happens
1924    /// to receive would otherwise read back as `Liveness::Live` from that
1925    /// coincidence alone. [`Self::liveness`] re-queries the current holder
1926    /// of `driver_pid` and requires this marker to still match before
1927    /// trusting a live answer — a mismatch means a different process now
1928    /// answers to that number, and no marker to compare (an old run, or a
1929    /// platform this build could not ask at record time) means neither
1930    /// extreme can be proven.
1931    #[serde(default)]
1932    pub driver_started_at: Option<String>,
1933    /// The process named by [`Self::driver_pid`] has stopped driving this run:
1934    /// its graph walk returned, whatever the outcome. Cleared at the start of
1935    /// every walk, set as the last write of one.
1936    ///
1937    /// A long-lived `magi serve` records its own pid and keeps it after the
1938    /// run ends, so that pid answers alive with a matching identity for as
1939    /// long as the daemon lives, and every blocked, failed or parked run it
1940    /// ever drove would read as being worked on right now. A crash or kill
1941    /// never sets this, and needs nothing to: the pid is dead then.
1942    #[serde(default)]
1943    pub driver_exited: bool,
1944    /// Last observation of the winner's pull request, when a land loop ran.
1945    ///
1946    /// Persisted rather than derived from the event log because the phone asks
1947    /// two questions about a run that has opened a PR - how are its checks and
1948    /// which round is it on - and parsing prose out of events to answer them
1949    /// would break the first time an event message was reworded.
1950    #[serde(default)]
1951    pub pr: Option<PrRecord>,
1952    /// The post-merge release-bump step's outcome, when it got as far as
1953    /// having one to report. See [`ReleaseBump`].
1954    #[serde(default)]
1955    pub release_bump: Option<ReleaseBump>,
1956    /// The last look at how far the winner's tree trailed the landing base,
1957    /// and the rebase(s) tried to close that gap. `None` until the tree has a
1958    /// winner to check.
1959    #[serde(default)]
1960    pub base_sync: Option<BaseSync>,
1961    /// The design-deliberation stage's output, when `[graph] advise` ran it:
1962    /// one record per advisor seat, plus the synthesis blended into the
1963    /// implementer's prompt. `None` when the stage is off, has not run yet,
1964    /// or could not even resolve its seats - see
1965    /// [`crate::graph::Runner::advise`].
1966    #[serde(default)]
1967    pub advice: Option<crate::advise::Advice>,
1968    /// Whether the design-deliberation stage has already been attempted this
1969    /// run, whatever it produced. The idempotency marker `Runner::advise`
1970    /// checks on reentry, the same role [`Self::judge_skipped`] plays for
1971    /// `judge` - without it a resumed run whose stage failed (a misconfigured
1972    /// `[roles] advisors`, every seat quota'd) would re-run it, and re-spend
1973    /// the agent calls, on every single reentry before `implement`.
1974    #[serde(default)]
1975    pub advise_attempted: bool,
1976    /// Node log.
1977    #[serde(default)]
1978    pub events: Vec<Event>,
1979    /// Commands seats' own CLIs reported running, across every node — see
1980    /// [`JobRecord`]. Populated in [`crate::graph::wave`] as each seat
1981    /// answers, so a resumed run keeps what earlier waves already collected
1982    /// rather than losing it to a reentry. Empty on a record written before
1983    /// this existed, or wherever no adapter reads structured job events for
1984    /// the backend a seat used — both read as "no evidence", not "nothing
1985    /// ran".
1986    #[serde(default)]
1987    pub jobs: Vec<JobRecord>,
1988    /// Operator-triggered targeted fixes — see [`OperatorFixRequest`] and
1989    /// `SCHEMA`'s doc for schema 9. Empty on every record written before
1990    /// this existed, which reads correctly as "no operator fix ever
1991    /// requested".
1992    #[serde(default)]
1993    pub operator_fixes: Vec<OperatorFixRequest>,
1994    /// Absolute paths of the files the task was filed with (see
1995    /// `crate::queue::Task::attachments`), listed in the implementers' prompt
1996    /// and made readable to their seats. Refreshed from the task on every
1997    /// start and resume, so a file attached while the task was held reaches a
1998    /// resumed run. Additive and `#[serde(default)]`, so `SCHEMA` stays put.
1999    #[serde(default)]
2000    pub attachments: Vec<PathBuf>,
2001    /// Subjects of the commits a review-only run examines, oldest first, as
2002    /// they stood when the run opened. `Some` marks the run as reviewing
2003    /// existing work: the pull request title is taken from these rather than
2004    /// from the review prompt in `instruction`. Additive and
2005    /// `#[serde(default)]`, so `SCHEMA` stays put.
2006    #[serde(default)]
2007    pub reviewed_commits: Option<Vec<String>>,
2008    /// Who started this run and which task it serves — see [`Origin`] and
2009    /// `SCHEMA`'s doc for schema 13. `None` is a run recorded before origins
2010    /// existed, and is reported as unknown, never as an operator's.
2011    #[serde(default)]
2012    pub origin: Option<Origin>,
2013    /// Follow-up tasks filed from this run's open findings after it merged
2014    /// (`crate::followup`). Additive and `#[serde(default)]`, so `SCHEMA`
2015    /// stays put.
2016    #[serde(default)]
2017    pub followups: Vec<FollowupRecord>,
2018    /// Follow-up depth of the task this run served, remembered the first
2019    /// time it was read so deleting that task cannot reset the cap.
2020    #[serde(default)]
2021    pub followup_generation: Option<u32>,
2022    /// Chat the task this run served descends from, fixed at start like
2023    /// `followup_generation` so deleting the task cannot lose it.
2024    #[serde(default)]
2025    pub origin_chat: Option<String>,
2026    /// The pull-request comment naming the filed follow-ups was posted.
2027    #[serde(default)]
2028    pub followup_commented: bool,
2029}
2030
2031/// One follow-up task filed from a merged run. See [`RunState::followups`].
2032#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2033pub struct FollowupRecord {
2034    /// Queue task id.
2035    pub task: String,
2036    /// Finding ids it covers.
2037    pub findings: Vec<String>,
2038}
2039
2040impl RunState {
2041    /// A fresh run.
2042    pub fn new(
2043        repo: PathBuf,
2044        base_branch: String,
2045        base_commit: String,
2046        instruction: String,
2047        config: Config,
2048    ) -> Self {
2049        let now = Timestamp::now();
2050        let seed = config.blind.seed.unwrap_or_else(crate::rng::entropy);
2051        Self {
2052            schema: SCHEMA,
2053            id: new_id(),
2054            repo,
2055            base_branch,
2056            base_commit,
2057            instruction,
2058            created_at: now,
2059            updated_at: now,
2060            status: RunStatus::Prep,
2061            seed,
2062            config,
2063            enabled_worktree_config: false,
2064            candidates: Vec::new(),
2065            judgements: Vec::new(),
2066            judge_skipped: false,
2067            deliberation: Vec::new(),
2068            votes: Vec::new(),
2069            tally: None,
2070            reviews: Vec::new(),
2071            gate: Vec::new(),
2072            gate_ran: false,
2073            gate_fixes: Vec::new(),
2074            rebase_fixes: Vec::new(),
2075            contested_handoff: None,
2076            land_armed_head: None,
2077            land_approval: None,
2078            github_text: None,
2079            pre_gate: Vec::new(),
2080            pre_gate_commit: None,
2081            merge: None,
2082            leaks: Vec::new(),
2083            quota: Vec::new(),
2084            handovers: Vec::new(),
2085            seat_epoch: 0,
2086            seat_history: BTreeMap::new(),
2087            withheld: Vec::new(),
2088            parked: false,
2089            released_to: None,
2090            released_branches: Vec::new(),
2091            seeds: Vec::new(),
2092            seats: BTreeMap::new(),
2093            active: BTreeMap::new(),
2094            driver_pid: None,
2095            driver_started_at: None,
2096            driver_exited: false,
2097            pr: None,
2098            release_bump: None,
2099            base_sync: None,
2100            advice: None,
2101            advise_attempted: false,
2102            attachments: Vec::new(),
2103            reviewed_commits: None,
2104            origin: None,
2105            followups: Vec::new(),
2106            followup_generation: None,
2107            origin_chat: None,
2108            followup_commented: false,
2109            events: Vec::new(),
2110            jobs: Vec::new(),
2111            operator_fixes: Vec::new(),
2112        }
2113    }
2114
2115    /// Directory holding this run's state and artifacts.
2116    pub fn dir(&self) -> PathBuf {
2117        run_dir(&self.id)
2118    }
2119
2120    /// Short form used in branch names and reports.
2121    pub fn short(&self) -> &str {
2122        short_of(&self.id)
2123    }
2124
2125    /// Branch name for a label.
2126    pub fn branch_for(&self, label: char) -> String {
2127        format!("magi/{}/{}", self.short(), label)
2128    }
2129
2130    /// Root of this run's worktrees.
2131    pub fn worktree_root(&self) -> PathBuf {
2132        self.config
2133            .graph
2134            .worktree_root
2135            .clone()
2136            .unwrap_or_else(default_worktree_root)
2137            .join(self.short())
2138    }
2139
2140    /// Record lockfiles a rescue commit withheld; a path already recorded by an
2141    /// earlier round is not repeated.
2142    pub fn note_withheld(&mut self, node: &str, strays: &[crate::git::Stray]) {
2143        for s in strays {
2144            if self.withheld.iter().any(|w| w.path == s.path) {
2145                continue;
2146            }
2147            self.event(
2148                node,
2149                format!(
2150                    "withheld stray lockfile {} ({}; the directory uses {})",
2151                    s.path, s.manager, s.kept_by
2152                ),
2153            );
2154            self.withheld.push(Withheld {
2155                path: s.path.clone(),
2156                manager: s.manager.clone(),
2157                kept_by: s.kept_by.clone(),
2158                node: node.to_owned(),
2159                at: Timestamp::now(),
2160            });
2161        }
2162    }
2163
2164    /// Note something in the run log and on the tracing stream.
2165    pub fn event(&mut self, node: &str, message: impl Into<String>) {
2166        let message = message.into();
2167        tracing::info!(node, "{message}");
2168        self.events.push(Event {
2169            at: Timestamp::now(),
2170            node: node.to_owned(),
2171            message,
2172        });
2173    }
2174
2175    /// The honest state of the final gate.
2176    ///
2177    /// Never derive this from `gate.is_empty()` alone anywhere else in the
2178    /// codebase — `NotRun` and `PassedWithNoCommands` both leave `gate`
2179    /// empty, and only this method (backed by [`Self::gate_ran`]) tells them
2180    /// apart. See `SCHEMA`'s doc for schema 7 for what conflating them used
2181    /// to do.
2182    pub fn gate_status(&self) -> GateStatus {
2183        if !self.gate_ran {
2184            GateStatus::NotRun
2185        } else if self.gate.is_empty() {
2186            GateStatus::PassedWithNoCommands
2187        } else if self.gate.iter().all(CommandOutcome::ok) {
2188            GateStatus::Passed
2189        } else {
2190            GateStatus::Failed
2191        }
2192    }
2193
2194    /// Record that `seat` was just sent a prompt for `node`, with the given
2195    /// wall-clock budget. `attempt` is 0 for the first ask and N for the Nth
2196    /// nudge or resume, purely for display — it does not change how the seat
2197    /// is treated.
2198    pub fn seat_started(
2199        &mut self,
2200        node: &str,
2201        seat: &str,
2202        timeout: std::time::Duration,
2203        attempt: usize,
2204    ) {
2205        self.active.insert(
2206            seat.to_owned(),
2207            ActiveSeat {
2208                node: node.to_owned(),
2209                started_at: Timestamp::now(),
2210                timeout_secs: timeout.as_secs(),
2211                attempt,
2212                task: None,
2213                command: None,
2214                index: None,
2215                total: None,
2216            },
2217        );
2218    }
2219
2220    /// Record that `seat` has answered, whatever the answer was.
2221    pub fn seat_finished(&mut self, seat: &str) {
2222        self.active.remove(seat);
2223    }
2224
2225    /// Record that `task` (`"e2e"` or `"gate"` — a shell-command list run
2226    /// outside any seat) has just started `command`, the `index`-th of
2227    /// `total`. Called at every command boundary, not once for the whole
2228    /// list: `verify.e2e` / `verify.gate` apply `timeout` per command, so
2229    /// this is the only way a reader can tell "how long is left" for
2230    /// whichever command is actually running right now, rather than a stale
2231    /// budget left over from the first one.
2232    #[allow(clippy::too_many_arguments)]
2233    pub fn task_command(
2234        &mut self,
2235        task: &str,
2236        node: &str,
2237        attempt: usize,
2238        command: &str,
2239        index: usize,
2240        total: usize,
2241        timeout: std::time::Duration,
2242    ) {
2243        self.active.insert(
2244            task.to_owned(),
2245            ActiveSeat {
2246                node: node.to_owned(),
2247                started_at: Timestamp::now(),
2248                timeout_secs: timeout.as_secs(),
2249                attempt,
2250                task: Some(task.to_owned()),
2251                command: Some(command.to_owned()),
2252                index: Some(index),
2253                total: Some(total),
2254            },
2255        );
2256    }
2257
2258    /// Record that `task` has finished its whole command list for this
2259    /// attempt.
2260    pub fn task_finished(&mut self, task: &str) {
2261        self.active.remove(task);
2262    }
2263
2264    /// The seats — never task entries — currently mid-answer. What
2265    /// `report::active_seats` and the phone's "who has not answered yet"
2266    /// note need: a seat's identifier is safe to show ([`ActiveSeat`]'s doc),
2267    /// so nothing here filters anything out beyond the type tag itself.
2268    pub fn seats_active(&self) -> impl Iterator<Item = (&String, &ActiveSeat)> {
2269        self.active.iter().filter(|(_, a)| a.task.is_none())
2270    }
2271
2272    /// The command-list tasks — never seat entries — currently running.
2273    /// Counterpart to [`Self::seats_active`]; see [`ActiveSeat::task`] for
2274    /// the tag both read.
2275    pub fn tasks_active(&self) -> impl Iterator<Item = (&String, &ActiveSeat)> {
2276        self.active.iter().filter(|(_, a)| a.task.is_some())
2277    }
2278
2279    /// Drop every seat this state still lists as answering, reporting whether
2280    /// anything was dropped.
2281    ///
2282    /// Called first thing in `execute`, on every entry — fresh, resumed, or
2283    /// recovering a stall — because an entry here only means something while
2284    /// the process that wrote it is still asking that seat something. A
2285    /// process killed mid-wave leaves its last batch of seats here with
2286    /// nobody left to clear them, and the next process to touch this run must
2287    /// not let that leftover read as "still going" before it has asked
2288    /// anyone anything.
2289    pub fn clear_active(&mut self) -> bool {
2290        if self.active.is_empty() {
2291            return false;
2292        }
2293        self.active.clear();
2294        true
2295    }
2296
2297    /// Does every seat this run still lists as [`Self::active`] sit past its
2298    /// own [`ActiveSeat::timeout_secs`]? `false` when nothing is active at
2299    /// all — an empty map is not evidence of anything overrunning.
2300    ///
2301    /// This alone is not proof the run is dead: a seat's own attempt can
2302    /// legitimately run a little past its budget while the process driving it
2303    /// is still tearing the attempt down. Every caller pairs this with its own
2304    /// `!live` reading (`daemon::is_working_on`) before treating the run as
2305    /// abandoned — this module cannot check that itself without depending on
2306    /// `crate::daemon`, and callers already have to ask that question anyway.
2307    #[must_use]
2308    pub fn active_all_overrun(&self, now: Timestamp) -> bool {
2309        !self.active.is_empty()
2310            && self
2311                .active
2312                .values()
2313                .all(|a| a.elapsed_secs(now) > a.timeout_secs as i64)
2314    }
2315
2316    /// Whether a process is actually still driving this run, given whether a
2317    /// daemon's heartbeat claims it and process-liveness/identity queries for
2318    /// [`Self::driver_pid`].
2319    ///
2320    /// A daemon claim wins outright when present — it is the stronger,
2321    /// independently-heartbeating signal. Absent that (every manual `magi
2322    /// run` / `magi review`, and every daemon-driven run whose daemon has
2323    /// since exited cleanly), `driver_pid` is asked directly. A live answer
2324    /// alone is not enough to trust, though: pids get reused, so `identity`
2325    /// re-queries whoever currently holds that pid and the result must still
2326    /// match [`Self::driver_started_at`] — the marker recorded at the same
2327    /// moment `driver_pid` was — before this reads `Live`. A mismatch means
2328    /// a *different* process now answers to that number, which is exactly as
2329    /// good as proof the original driver is gone, so that reads `Dead`. The
2330    /// marker is an epoch-seconds integer string; one that is not (a run
2331    /// recorded when it was a locale-dependent `ps` string) reads
2332    /// [`Liveness::Unknown`], never `Dead`. No
2333    /// marker to compare against (an old run, or a platform this build could
2334    /// not ask at record time) or a `None` from either query, and this
2335    /// cannot tell either way, so it reads [`Liveness::Unknown`] — never
2336    /// guessed as [`Liveness::Dead`] out of mere silence. A display that
2337    /// guessed "dead" out of missing information would be exactly the
2338    /// mtime-and-task-manager guessing this type exists to replace.
2339    ///
2340    /// Kept generic over `query` and `identity` so a test can inject answers
2341    /// without spawning a real process query — production code goes through
2342    /// [`Self::liveness`], which supplies [`crate::proc::pid_status`] and
2343    /// [`crate::proc::process_started_at`].
2344    #[must_use]
2345    pub fn liveness_with<F, G>(&self, daemon_claims: bool, query: F, identity: G) -> Liveness
2346    where
2347        F: FnOnce(u32) -> Option<bool>,
2348        G: FnOnce(u32) -> Option<String>,
2349    {
2350        if daemon_claims {
2351            return Liveness::Live;
2352        }
2353        // The driver said itself that it stopped; its pid may well be alive
2354        // (a daemon outlives the runs it drives), so it is not asked.
2355        if self.driver_exited {
2356            return Liveness::Dead;
2357        }
2358        let Some(pid) = self.driver_pid else {
2359            return Liveness::Unknown;
2360        };
2361        match query(pid) {
2362            Some(false) => Liveness::Dead,
2363            None => Liveness::Unknown,
2364            Some(true) => {
2365                let Some(recorded) = &self.driver_started_at else {
2366                    return Liveness::Unknown;
2367                };
2368                // A marker in the old locale-dependent format can never be
2369                // compared reliably, so it proves nothing either way.
2370                if !crate::proc::is_identity_marker(recorded) {
2371                    return Liveness::Unknown;
2372                }
2373                match identity(pid) {
2374                    Some(current) if !crate::proc::is_identity_marker(&current) => {
2375                        Liveness::Unknown
2376                    }
2377                    Some(current) if *recorded == current => Liveness::Live,
2378                    Some(_) => Liveness::Dead,
2379                    None => Liveness::Unknown,
2380                }
2381            }
2382        }
2383    }
2384
2385    /// [`Self::liveness_with`], backed by the real process-liveness and
2386    /// identity queries.
2387    #[must_use]
2388    pub fn liveness(&self, daemon_claims: bool) -> Liveness {
2389        self.liveness_with(
2390            daemon_claims,
2391            crate::proc::pid_status,
2392            crate::proc::process_started_at,
2393        )
2394    }
2395
2396    /// Clear every seat this run still lists as active and fail it, unless it
2397    /// had already reached a terminal status some other way.
2398    ///
2399    /// Callers must already have proven this run is dead — [`Self::active_all_overrun`]
2400    /// plus their own `!live` reading — before calling this; it does not
2401    /// check either itself. Unlike [`Self::clear_active`] (dropping a resumed
2402    /// run's own stale wave before repopulating it, called unconditionally at
2403    /// the top of every `execute()`), this is a verdict: a run left this way
2404    /// has nothing left to repopulate the wave, ever, and must stop reading as
2405    /// `implementing` (or whichever node) forever.
2406    pub fn abandon(&mut self, by: &str) {
2407        let seats: Vec<String> = self.active.keys().cloned().collect();
2408        self.clear_active();
2409        if !self.status.done() {
2410            self.status = RunStatus::Failed;
2411        }
2412        self.event(
2413            by,
2414            format!(
2415                "abandoned: seat(s) {} left behind by a killed process, past their own \
2416                 timeout with no live daemon claiming this run",
2417                seats.join(", ")
2418            ),
2419        );
2420    }
2421
2422    /// Flush to `run.json`, atomically, under the process-global [`home`].
2423    pub fn save(&mut self) -> Result<()> {
2424        let home = home();
2425        self.save_under(&home)
2426    }
2427
2428    /// [`Self::save`], rooted at an explicit `home` instead of the
2429    /// process-global one.
2430    ///
2431    /// For a caller that was already handed its own `home` explicitly — a
2432    /// housekeeping pass, mainly, for the same reason `Queue::at` and the
2433    /// daemon status path are parameters rather than resolved here (see
2434    /// `daemon::drive`'s own doc) — falling through to the global would write
2435    /// back through whichever directory some *other* process or test pinned
2436    /// into that `OnceLock` first, not the one this call was actually handed.
2437    pub fn save_under(&mut self, home: &Path) -> Result<()> {
2438        self.updated_at = Timestamp::now();
2439        let dir = home.join("runs").join(&self.id);
2440        std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
2441        let body = serde_json::to_string_pretty(self).context("serialize run state")?;
2442        let tmp = dir.join("run.json.tmp");
2443        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
2444        std::fs::rename(&tmp, dir.join("run.json")).with_context(|| "replace run.json")?;
2445        Ok(())
2446    }
2447
2448    /// Load a run by id or unambiguous id prefix.
2449    pub fn load(id: &str) -> Result<Self> {
2450        let resolved = resolve_id(id)?;
2451        let path = run_dir(&resolved).join("run.json");
2452        let body =
2453            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
2454        let state: Self =
2455            serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2456        migrate_schema(state)
2457    }
2458
2459    /// [`Self::load`], rooted at an explicit `home` instead of the
2460    /// process-global one, and for a full id rather than a prefix — a caller
2461    /// with its own `home` already has the exact id (from a `RunState` it
2462    /// already read, or from `Task::runs`) and has no `runs_root` to search
2463    /// for a prefix against in the first place. Same reasoning as
2464    /// [`Self::save_under`]: a caller holding its own `home` explicitly must
2465    /// not read back through whichever directory some *other* process or
2466    /// test pinned into the global [`home`] `OnceLock` first.
2467    pub fn load_under(id: &str, home: &Path) -> Result<Self> {
2468        let path = home.join("runs").join(id).join("run.json");
2469        let body =
2470            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
2471        let state: Self =
2472            serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2473        migrate_schema(state)
2474    }
2475}
2476
2477pub(crate) fn migrate_schema(mut state: RunState) -> Result<RunState> {
2478    // Schema 5 predates deferred e2e. Its empty e2e lists therefore mean
2479    // "not configured", never "deferred"; serde's field defaults retain
2480    // exactly that representation while this migration permits resumes.
2481    if state.schema == 5 {
2482        state.schema = 6;
2483    }
2484    // Schema 6 predates `gate_ran` and could not tell "never attempted or
2485    // resource-blocked" apart from "ran with zero commands configured" — see
2486    // `SCHEMA`'s doc for schema 7. A non-empty `gate` is a real recorded
2487    // attempt either way, so it is trusted as `gate_ran = true` rather than
2488    // spent again; an empty one is simply handed back to the next `gate()`
2489    // call, which re-attempts it and, for the zero-commands case, resolves
2490    // instantly.
2491    if state.schema == 6 {
2492        state.gate_ran = !state.gate.is_empty();
2493        state.schema = 7;
2494    }
2495    // Schema 7's main review loop always checked `e2e` against the round's
2496    // own `head`, it just never wrote that fact into `verified_head` unless
2497    // a catch-up run had checked a *different* commit — see `SCHEMA`'s doc
2498    // for schema 8. Reconstructing `Some(head)` for a round whose `e2e` held
2499    // a real attempt restores a fact that was always true; `verified_at` has
2500    // no historical value to recover and stays `None`.
2501    if state.schema == 7 {
2502        for round in &mut state.reviews {
2503            if round.verified_head.is_none()
2504                && matches!(round.e2e_status(), E2eStatus::Passed | E2eStatus::Failed)
2505            {
2506                round.verified_head = Some(round.head.clone());
2507            }
2508        }
2509        state.schema = 8;
2510    }
2511    // Schema 8 predates `operator_fixes`. There is nothing to reconstruct —
2512    // an old run simply never had one requested — so `#[serde(default)]`
2513    // already left it as the correct empty `Vec`; this only advances the
2514    // version number.
2515    if state.schema == 8 {
2516        state.schema = 9;
2517    }
2518    // Schema 9 predates `RunStatus::VerifiedNoop` and
2519    // `Candidate::verified_noop`. Nothing to reconstruct: an old record never
2520    // made the claim, `#[serde(default)]` already reads `verified_noop` as
2521    // `None` on every candidate, and a `VerifiedNoop` status cannot appear in
2522    // a schema-9 record at all — see `SCHEMA`'s doc for schema 10. This only
2523    // advances the version number.
2524    if state.schema == 9 {
2525        state.schema = 10;
2526    }
2527    // Schema 10 predates `released_to`: no old run ever had its worktree
2528    // handed over, and `#[serde(default)]` reads exactly that. Only the
2529    // version number advances.
2530    if state.schema == 10 {
2531        state.schema = 11;
2532    }
2533    // Schema 11 predates `driver_exited`. A run that had already ended
2534    // Blocked / Failed / Stalled, or was parked in Landing (which hands its
2535    // daemon slot back), stopped walking the graph, but its recorded
2536    // pid may belong to a daemon still alive doing other work, which would pin
2537    // it as running for good; those are marked exited. Any other status keeps
2538    // `false`, and its pid is asked as before. This is an inference from
2539    // status, sound because a schema-11 record was written by a build that is
2540    // gone once this one is installed (and a daemon claim, which wins
2541    // regardless, still protects a run a live daemon is driving).
2542    if state.schema == 11 {
2543        if matches!(
2544            state.status,
2545            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled | RunStatus::Landing
2546        ) {
2547            state.driver_exited = true;
2548        }
2549        state.schema = 12;
2550    }
2551    // Schema 12 predates `origin`. Nothing is reconstructed: `None` already
2552    // says "unknown", which is the truth for a run nobody recorded. Only the
2553    // version number advances.
2554    if state.schema == 12 {
2555        state.schema = SCHEMA;
2556    }
2557    if state.schema != SCHEMA {
2558        bail!(
2559            "run {} was written by a different magi (schema {}, this build \
2560                 speaks {SCHEMA})",
2561            state.id,
2562            state.schema
2563        );
2564    }
2565    Ok(state)
2566}
2567
2568impl RunState {
2569    /// Whether a later attempt took this run's worktree over, so a resume has
2570    /// nothing left to continue from.
2571    pub fn released(&self) -> bool {
2572        self.released_to.is_some()
2573    }
2574
2575    /// The winning candidate, once the tally has run.
2576    pub fn winner(&self) -> Option<&Candidate> {
2577        let label = self.tally.as_ref()?.winner;
2578        self.candidates.iter().find(|c| c.label == label)
2579    }
2580
2581    /// Candidates eligible for judging.
2582    pub fn viable(&self) -> Vec<&Candidate> {
2583        self.candidates.iter().filter(|c| c.viable()).collect()
2584    }
2585
2586    /// Did every candidate write nothing, and every one of them back it with
2587    /// evidence [`crate::graph`]'s adoption guard accepted?
2588    ///
2589    /// All-or-nothing on purpose: one candidate declaring `NO CHANGE NEEDED`
2590    /// while another simply failed to produce anything is not agreement, it
2591    /// is one candidate's unverified claim next to an ordinary loss, and the
2592    /// run must still read as the `Failed` it is. Only ever meaningful when
2593    /// [`Self::viable`] is already empty — a run with any real patch to judge
2594    /// never reaches the caller that asks this.
2595    pub fn all_candidates_verified_noop(&self) -> bool {
2596        !self.candidates.is_empty()
2597            && self
2598                .candidates
2599                .iter()
2600                .all(|c| c.empty && c.verified_noop.is_some())
2601    }
2602
2603    /// Findings still open when the review loop stopped trying: the last
2604    /// round's, exactly when that round was not clean. Empty on a run that
2605    /// never reviewed, or whose last round was clean.
2606    ///
2607    /// This is the last round's findings regardless of what the fixer claims
2608    /// to have addressed in that same round: a round that stopped the loop
2609    /// (round budget spent, or no tree progress for
2610    /// [`crate::graph::STAGNANT_LIMIT`] rounds) never had a *following* round
2611    /// to confirm the fix actually landed, and the self-reported adoption
2612    /// count is not trusted for that judgement either — see
2613    /// [`ReviewRound::progressed`].
2614    pub fn open_findings(&self) -> Vec<&Finding> {
2615        match self.reviews.last() {
2616            Some(r) if !r.clean => r
2617                .reviews
2618                .iter()
2619                .flat_map(|rec| rec.findings.iter())
2620                .collect(),
2621            _ => Vec::new(),
2622        }
2623    }
2624
2625    /// Every finding raised in the most recent review round, regardless of
2626    /// that round's own severity mix — unlike [`Self::open_findings`], not
2627    /// filtered to a round that was not clean. This is the pool `magi fix`
2628    /// reports as available to pick from: a round can conclude clean (no
2629    /// finding blocked merge) while still carrying minor findings nobody
2630    /// has acted on.
2631    pub fn last_round_findings(&self) -> Vec<&Finding> {
2632        self.reviews
2633            .last()
2634            .into_iter()
2635            .flat_map(|r| r.reviews.iter())
2636            .flat_map(|rec| rec.findings.iter())
2637            .collect()
2638    }
2639
2640    /// Look up a finding by id anywhere in this run's review history,
2641    /// together with the round and reviewer record that raised it — the
2642    /// provenance `magi fix` snapshots onto [`OperatorFixFinding`].
2643    pub fn finding(&self, id: &str) -> Option<(&ReviewRound, &ReviewRecord, &Finding)> {
2644        self.reviews.iter().find_map(|round| {
2645            round.reviews.iter().find_map(|rec| {
2646                rec.findings
2647                    .iter()
2648                    .find(|f| f.id == id)
2649                    .map(|f| (round, rec, f))
2650            })
2651        })
2652    }
2653
2654    /// Did this run reach a mergeable status (`Ready` or `Merged`) with
2655    /// review findings still open?
2656    ///
2657    /// That combination is the point of the review hand-off: the review
2658    /// round budget (or an unproductive round, see [`ReviewRound::progressed`])
2659    /// was spent while gate and e2e stayed green, so the run was handed off
2660    /// rather than blocked — but the findings did not disappear, and whoever
2661    /// reads the result should be told they are still there.
2662    pub fn handed_off_with_open_findings(&self) -> bool {
2663        matches!(self.status, RunStatus::Ready | RunStatus::Merged)
2664            && self.reviews.last().is_some_and(|r| !r.clean)
2665    }
2666
2667    /// Reached `Ready` because `[merge] mode = "none"` left it there by
2668    /// design, never to be picked up by the PR-polling merge watcher — as
2669    /// opposed to a `Ready` that is still a plausible landing candidate (a
2670    /// PR closed without merging, or a re-entry onto an already-concluded
2671    /// node). Both leave `status` at `Ready`; only this one leaves the
2672    /// winning branch permanently unwatched, which is what a caller needs to
2673    /// know before labelling the run in a listing.
2674    pub fn unmerged_by_design(&self) -> bool {
2675        self.status == RunStatus::Ready
2676            && self
2677                .merge
2678                .as_ref()
2679                .is_some_and(|m| m.mode == MergeMode::None)
2680    }
2681
2682    /// Did a step after the merge leave something only a human can finish?
2683    ///
2684    /// Derived, not a status: the merge happened, so `status` stays `Merged`
2685    /// and everything that branches on it keeps working. Display code asks
2686    /// this so a merged run with an unmerged release PR does not read as
2687    /// plain green.
2688    pub fn needs_attention(&self) -> bool {
2689        self.status == RunStatus::Merged
2690            && self
2691                .release_bump
2692                .as_ref()
2693                .is_some_and(|b| b.action_required.is_some())
2694    }
2695
2696    /// Local-time creation stamp for reports.
2697    pub fn created_local(&self) -> String {
2698        self.created_at
2699            .to_zoned(jiff::tz::TimeZone::system())
2700            .strftime("%Y-%m-%d %H:%M:%S")
2701            .to_string()
2702    }
2703
2704    /// Assert that this run is safe to delete.
2705    ///
2706    /// Refuses a run a live daemon is working on, and refuses any run whose
2707    /// candidate worktrees and branches have not been folded away with `magi
2708    /// fold`. The fold requirement is the real protection: it is what makes
2709    /// "delete" mean "remove a record" rather than "throw away a worktree
2710    /// somebody may still be editing".
2711    ///
2712    /// `in_flight` has to come from the caller, because a run's own status
2713    /// cannot answer the question. A daemon killed mid-run leaves its status at
2714    /// `implementing` forever, and a guard that trusted that would make every
2715    /// interrupted run permanently undeletable - the operator's only recourse
2716    /// being to edit `run.json` by hand, which is exactly the sort of thing
2717    /// this command exists to avoid. The queue already treats an orphaned
2718    /// `.lock` from a `SIGKILL`ed daemon the same way; this is that rule for
2719    /// runs.
2720    pub fn ensure_can_delete(&self, in_flight: bool) -> Result<()> {
2721        if in_flight {
2722            bail!(
2723                "run {} is being worked on by a live daemon right now",
2724                self.short()
2725            );
2726        }
2727        if self.candidates.iter().any(|c| !c.folded) {
2728            bail!(
2729                "run {} has unfolded candidates; fold first with `magi fold`",
2730                self.short()
2731            );
2732        }
2733        Ok(())
2734    }
2735}
2736
2737/// The short form of a commit, for a label a human or an LLM reads.
2738fn short(commit: &str) -> String {
2739    commit.chars().take(7).collect()
2740}
2741
2742/// The short form of a run id: the trailing block after the last `-`.
2743///
2744/// A free function as well as [`RunState::short`], because callers that have
2745/// only an id - an error message, a daemon status, a route handler - were
2746/// otherwise reimplementing the split, and two spellings of "short id" is one
2747/// rename away from branch names that no longer match their run.
2748pub fn short_of(id: &str) -> &str {
2749    id.split('-').next_back().unwrap_or(id)
2750}
2751
2752/// Where magi keeps its runs.
2753///
2754/// `MAGI_HOME` overrides the default, and [`set_home`] overrides both — which
2755/// is what lets the integration tests drive a whole graph without writing into
2756/// the operator's real history.
2757///
2758/// In a unit test build (`cfg(test)`), falling through to the real
2759/// `<data_local>/magi` is not a fallback worth having: it is exactly how
2760/// three broken fixture runs ended up in the operator's actual history and
2761/// were counted as `unreadable` by the deck. A test that reaches this point
2762/// forgot to call [`set_home`] (or set `MAGI_HOME`) - that is a bug in the
2763/// test, not a case to serve, so it panics instead of writing anywhere.
2764pub fn home() -> PathBuf {
2765    resolve_home(HOME.get().cloned(), std::env::var_os("MAGI_HOME"))
2766}
2767
2768/// The decision `home` makes, taking its two overrides as plain values
2769/// instead of reading the `OnceLock` and the environment itself.
2770///
2771/// Pulled out so the `cfg(test)` panic is asserted directly against a
2772/// `None, None` input, rather than racing every other unit test in the
2773/// binary for who touches the process-global `HOME` first.
2774fn resolve_home(pinned: Option<PathBuf>, magi_home_env: Option<std::ffi::OsString>) -> PathBuf {
2775    if let Some(dir) = pinned {
2776        return dir;
2777    }
2778    if let Some(dir) = magi_home_env {
2779        return PathBuf::from(dir);
2780    }
2781    #[cfg(test)]
2782    {
2783        panic!(
2784            "run::home() was reached in a test without run::set_home() or \
2785             MAGI_HOME; this would write into the operator's real \
2786             <data_local>/magi. Call `run::set_home(temp_dir)` before any \
2787             code path that touches a RunState."
2788        );
2789    }
2790    #[cfg(not(test))]
2791    {
2792        dirs::data_local_dir()
2793            .unwrap_or_else(|| PathBuf::from("."))
2794            .join("magi")
2795    }
2796}
2797
2798/// [`home`] without the test panic: `None` in a test that never pinned a
2799/// home, so best-effort writers (see [`crate::notices::raise`]) skip the write
2800/// instead of touching the operator's real state or aborting the test.
2801pub fn try_home() -> Option<PathBuf> {
2802    if cfg!(test) {
2803        HOME.get()
2804            .cloned()
2805            .or_else(|| std::env::var_os("MAGI_HOME").map(PathBuf::from))
2806    } else {
2807        Some(home())
2808    }
2809}
2810
2811/// Pin the run home for this process. The first call wins.
2812pub fn set_home(dir: PathBuf) {
2813    let _ = HOME.set(dir);
2814}
2815
2816/// A temp directory unique to this test process, created once and kept.
2817/// `set_home` is a first-wins `OnceLock`, so a fixed `temp_dir().join(..)`
2818/// would be shared by every concurrent `cargo test` process on the machine.
2819#[cfg(test)]
2820pub(crate) fn test_home() -> PathBuf {
2821    static DIR: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
2822    DIR.get_or_init(|| {
2823        tempfile::Builder::new()
2824            .prefix("magi-unit-home-")
2825            .tempdir()
2826            .expect("create the unit-test home")
2827            .keep()
2828    })
2829    .clone()
2830}
2831
2832/// [`set_home`] on [`test_home`]; the one way a unit test pins the home.
2833#[cfg(test)]
2834pub(crate) fn pin_test_home() {
2835    set_home(test_home());
2836}
2837
2838static HOME: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
2839
2840/// `<home>/runs`.
2841pub fn runs_root() -> PathBuf {
2842    home().join("runs")
2843}
2844
2845/// The worktree root a run uses when the config sets none: `~/wt/magi`.
2846///
2847/// One definition of the default, so the folder the janitor folds and the
2848/// folder the health view sizes cannot drift apart: a run with no configured
2849/// [`crate::config::Graph::worktree_root`] lays its worktrees exactly here.
2850pub fn default_worktree_root() -> PathBuf {
2851    dirs::home_dir()
2852        .unwrap_or_else(|| PathBuf::from("."))
2853        .join("wt")
2854        .join("magi")
2855}
2856
2857/// Directory for one run id.
2858pub fn run_dir(id: &str) -> PathBuf {
2859    runs_root().join(id)
2860}
2861
2862/// Every run id on disk, newest first.
2863///
2864/// A directory is a run because of its **name**, not because it holds a
2865/// readable `run.json`. A run whose very first save lost the machine's last
2866/// free bytes leaves `<id>/run.json.tmp` and nothing else, and filtering on
2867/// `run.json` made that run invisible everywhere: not in `magi list`, not in
2868/// `runs_unreadable`, not on the phone, so nothing could report it and no
2869/// route could clear it. `88c0` sat like that for two days. Unreadable is
2870/// counted, never hidden - the readers already say why each one cannot be
2871/// read, and `fold_unreadable` is how a record like this leaves.
2872pub fn list_ids() -> Vec<String> {
2873    list_ids_in(&runs_root())
2874}
2875
2876/// [`list_ids`] against an explicit runs root, for callers (and tests) that
2877/// must not depend on the process-global home.
2878pub fn list_ids_in(root: &Path) -> Vec<String> {
2879    let mut ids: Vec<String> = std::fs::read_dir(root)
2880        .into_iter()
2881        .flatten()
2882        .flatten()
2883        .filter(|e| e.path().is_dir())
2884        .map(|e| e.file_name().to_string_lossy().into_owned())
2885        .filter(|name| is_run_id(name))
2886        .collect();
2887    // Ids start with a sortable timestamp.
2888    ids.sort_unstable_by(|a, b| b.cmp(a));
2889    ids
2890}
2891
2892/// Does `name` have the shape [`new_id`] mints: `YYYYMMDD-HHMMSS-xxxx`?
2893///
2894/// The test for "this directory is a run", so a stray folder under
2895/// `<home>/runs` is not reported as a broken run.
2896///
2897/// The tag is checked for length and for being alphanumeric, not for being
2898/// hex: real ids are hex, but fixtures across this crate name runs
2899/// `...-dead` / `...-gone` / `...-once`, and a predicate that disowned those
2900/// would be asserting the fixtures' spelling rather than the shape.
2901pub fn is_run_id(name: &str) -> bool {
2902    let mut parts = name.split('-');
2903    let (Some(day), Some(time), Some(tag), None) =
2904        (parts.next(), parts.next(), parts.next(), parts.next())
2905    else {
2906        return false;
2907    };
2908    day.len() == 8
2909        && day.bytes().all(|b| b.is_ascii_digit())
2910        && time.len() == 6
2911        && time.bytes().all(|b| b.is_ascii_digit())
2912        && tag.len() == 4
2913        && tag.bytes().all(|b| b.is_ascii_alphanumeric())
2914}
2915
2916/// Expand an id prefix to exactly one run id.
2917pub fn resolve_id(prefix: &str) -> Result<String> {
2918    // A whole id names its directory, readable state or not: the run whose
2919    // `run.json` never landed still has to be reachable by `magi show` and
2920    // by the fold route, which is the only way its record ever leaves.
2921    if is_run_id(prefix) && run_dir(prefix).is_dir() {
2922        return Ok(prefix.to_owned());
2923    }
2924    let hits: Vec<String> = list_ids()
2925        .into_iter()
2926        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
2927        .collect();
2928    match hits.len() {
2929        1 => Ok(hits.into_iter().next().expect("exactly one hit")),
2930        0 => bail!("no run matches `{prefix}`"),
2931        _ => bail!(
2932            "`{prefix}` matches {} runs: {}",
2933            hits.len(),
2934            hits.join(", ")
2935        ),
2936    }
2937}
2938
2939/// The most recent run, if any.
2940pub fn latest_id() -> Option<String> {
2941    list_ids().into_iter().next()
2942}
2943
2944/// `YYYYMMDD-HHMMSS-xxxx`, sortable and short enough for a branch name.
2945///
2946/// The four hex digits are fresh entropy, **not** `blind.seed`. They were the
2947/// seed, and a pinned seed then made the whole id a function of the second it
2948/// started in: two runs a second apart were distinguishable, two in the same
2949/// second were not. Everything keyed on the id collided with them - the run
2950/// directory, `artifacts/`, and the candidate worktrees under
2951/// `wt/magi/<short>/`.
2952///
2953/// `tests/common` pins the seed on purpose, so its integration tests all share
2954/// one suffix. On Windows the suite is slow enough that the seconds differ and
2955/// nothing showed; on Linux `graph_dropped_stream`'s three tests run inside
2956/// 16s, so two of them shared a run directory and the second read an artifact
2957/// the first had written (`impl-B-resume.out`) - a failure that looked like the
2958/// resume logic misbehaving and was really two runs in one directory.
2959///
2960/// A seed exists to make the *blind* decisions reproducible: label assignment
2961/// and per-judge presentation order. It was never meant to name the run, and
2962/// `RunState::seed` still carries it for what it is for.
2963fn new_id() -> String {
2964    let stamp = Zoned::now().strftime("%Y%m%d-%H%M%S");
2965    let entropy = crate::rng::entropy();
2966    format!("{stamp}-{:04x}", (entropy ^ (entropy >> 32)) & 0xffff)
2967}
2968
2969/// Keep the last `max` bytes of `text`, on a line boundary.
2970pub fn tail(text: &str, max: usize) -> String {
2971    if text.len() <= max {
2972        return text.to_owned();
2973    }
2974    let mut cut = text.len() - max;
2975    while cut < text.len() && !text.is_char_boundary(cut) {
2976        cut += 1;
2977    }
2978    let slice = &text[cut..];
2979    let start = slice.find('\n').map_or(0, |i| i + 1);
2980    format!(
2981        "[... {} earlier bytes omitted ...]\n{}",
2982        cut,
2983        &slice[start..]
2984    )
2985}
2986
2987/// Path of a run artifact.
2988pub fn artifact_path(run: &RunState, name: &str) -> PathBuf {
2989    run.dir().join("artifacts").join(name)
2990}
2991
2992/// Write an artifact, creating the directory if needed.
2993pub fn write_artifact(run: &RunState, name: &str, body: &str) -> Result<PathBuf> {
2994    let path = artifact_path(run, name);
2995    if let Some(parent) = path.parent() {
2996        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
2997    }
2998    std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
2999    Ok(path)
3000}
3001
3002/// Read an artifact back, e.g. a stored patch on resume.
3003pub fn read_artifact(run: &RunState, name: &str) -> Option<String> {
3004    std::fs::read_to_string(artifact_path(run, name)).ok()
3005}
3006
3007#[cfg(test)]
3008mod tests {
3009    use crate::proc::Quiet as _;
3010
3011    #[test]
3012    fn test_home_is_private_stable_and_unique_per_process() {
3013        // Child mode: report this process's home and stop.
3014        if std::env::var_os("MAGI_HOME_PROBE").is_some() {
3015            println!("HOME={}", super::test_home().display());
3016            return;
3017        }
3018        let a = super::test_home();
3019        assert_eq!(a, super::test_home());
3020        assert!(a.is_dir() && a.starts_with(std::env::temp_dir()));
3021        let probe = || {
3022            let out = std::process::Command::new(std::env::current_exe().unwrap())
3023                .args([
3024                    "--exact",
3025                    "run::tests::test_home_is_private_stable_and_unique_per_process",
3026                    "--nocapture",
3027                    "--test-threads=1",
3028                ])
3029                .env("MAGI_HOME_PROBE", "1")
3030                .quiet()
3031                .output()
3032                .unwrap();
3033            String::from_utf8_lossy(&out.stdout)
3034                .lines()
3035                .find_map(|l| l.split_once("HOME=").map(|(_, h)| h.to_owned()))
3036                .expect("child reported a home")
3037        };
3038        let (b, c) = (probe(), probe());
3039        assert_ne!(b, c, "two processes must never share a unit-test home");
3040        assert_ne!(b, a.display().to_string());
3041    }
3042
3043    #[test]
3044    fn no_test_pins_a_fixed_temp_path_as_the_home() {
3045        let root = std::env::var_os("CARGO_MANIFEST_DIR")
3046            .map(PathBuf::from)
3047            .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));
3048        let needle = ["set_home(std::env::temp_dir()", ".join(\"magi-"].concat();
3049        for e in std::fs::read_dir(root.join("src")).unwrap() {
3050            let p = e.unwrap().path();
3051            if p.extension().and_then(|x| x.to_str()) != Some("rs") {
3052                continue;
3053            }
3054            let text = std::fs::read_to_string(&p).unwrap();
3055            assert!(
3056                !text.contains(&needle),
3057                "{} pins a fixed temp home; use run::pin_test_home()",
3058                p.display()
3059            );
3060        }
3061    }
3062
3063    use super::*;
3064
3065    fn state() -> RunState {
3066        RunState::new(
3067            PathBuf::from("/repo"),
3068            "main".to_owned(),
3069            "abc1234def".to_owned(),
3070            "add retries".to_owned(),
3071            Config::default(),
3072        )
3073    }
3074
3075    #[test]
3076    fn superseded_is_terminal_but_not_resumable() {
3077        assert!(RunStatus::Superseded.done());
3078        assert!(!RunStatus::Superseded.resumable());
3079        assert_eq!(RunStatus::Superseded.as_str(), "superseded");
3080        assert!(RunStatus::AlreadyInBase.done());
3081        assert!(!RunStatus::AlreadyInBase.resumable());
3082        assert_eq!(RunStatus::AlreadyInBase.as_str(), "already_in_base");
3083    }
3084
3085    #[test]
3086    fn load_under_reads_back_exactly_what_save_under_wrote_at_an_explicit_home() {
3087        // Both rooted at an explicit `home` rather than the process-global
3088        // one - a caller with its own `home` (a test fixture, a housekeeping
3089        // pass) must round-trip through exactly that directory, never
3090        // through whichever home some other test in the same binary pinned
3091        // into the global `OnceLock` first.
3092        let dir = tempfile::tempdir().unwrap();
3093        let mut original = state();
3094        original.id = "20260101-000000-load".to_owned();
3095        original.status = RunStatus::Blocked;
3096        original.save_under(dir.path()).unwrap();
3097
3098        let reloaded = RunState::load_under(&original.id, dir.path()).unwrap();
3099        assert_eq!(reloaded.id, original.id);
3100        assert_eq!(reloaded.status, RunStatus::Blocked);
3101
3102        assert!(
3103            RunState::load_under("20260101-000000-none", dir.path()).is_err(),
3104            "an id with nothing saved under this home must not silently read something else"
3105        );
3106    }
3107
3108    #[test]
3109    fn resolve_home_prefers_the_pin_then_the_env_var() {
3110        let pinned = PathBuf::from("/pinned");
3111        assert_eq!(
3112            resolve_home(Some(pinned.clone()), Some("/env".into())),
3113            pinned,
3114            "a pin wins even over MAGI_HOME"
3115        );
3116        assert_eq!(
3117            resolve_home(None, Some("/env".into())),
3118            PathBuf::from("/env")
3119        );
3120    }
3121
3122    #[test]
3123    #[should_panic(expected = "run::set_home()")]
3124    fn resolve_home_refuses_to_fall_back_to_the_operators_real_home() {
3125        // Neither override present is exactly the state a test reaches by
3126        // forgetting `set_home`/`MAGI_HOME` - the accident that put three
3127        // broken fixture runs into the operator's real history. Asserted
3128        // against the pure decision directly, not `home()` itself, because
3129        // `HOME` is a process-wide `OnceLock` another test may have already
3130        // set - this must not depend on test execution order.
3131        resolve_home(None, None);
3132    }
3133
3134    #[test]
3135    fn a_run_is_named_by_shape_so_a_state_less_directory_is_still_a_run() {
3136        // The shape `new_id` mints. A directory answering to it is a run even
3137        // with no readable `run.json`: that is how a save that ran out of
3138        // disk stays visible instead of vanishing from every listing.
3139        assert!(is_run_id(&new_id()));
3140        assert!(is_run_id("20260904-014540-88c0"));
3141        // Not runs: a stray folder, a truncated id, a non-hex tag, and an id
3142        // with an extra segment (a worktree label, say).
3143        assert!(!is_run_id("scratch"));
3144        assert!(!is_run_id("20260904-014540"));
3145        assert!(!is_run_id("20260904-014540-88c0f"));
3146        assert!(!is_run_id("2026090x-014540-88c0"));
3147        assert!(!is_run_id("20260904-014540-88c0-A"));
3148    }
3149
3150    #[test]
3151    fn ids_are_sortable_and_short_suffixed() {
3152        let s = state();
3153        let parts: Vec<&str> = s.id.split('-').collect();
3154        assert_eq!(parts.len(), 3);
3155        assert_eq!(parts[0].len(), 8);
3156        assert_eq!(parts[1].len(), 6);
3157        assert_eq!(parts[2].len(), 4);
3158        assert_eq!(s.short(), parts[2]);
3159    }
3160
3161    #[test]
3162    fn branch_names_carry_the_label_not_the_author() {
3163        let s = state();
3164        let b = s.branch_for('B');
3165        assert_eq!(b, format!("magi/{}/B", s.short()));
3166        assert!(!b.contains("claude"));
3167    }
3168
3169    /// A pinned seed reproduces the blind decisions. It must **not** reproduce
3170    /// the run's identity.
3171    ///
3172    /// `assert_eq!(a.short(), b.short())` used to stand where the last
3173    /// assertion is now, and it was pinning the defect: with the id's suffix
3174    /// derived from the seed, two runs started in the same second were the
3175    /// same run as far as the filesystem was concerned - one directory, one
3176    /// `artifacts/`, one set of candidate worktrees. `tests/common` pins a
3177    /// seed for every integration test, so on Linux, where the suite is fast,
3178    /// two tests in `graph_dropped_stream` shared a directory and one read the
3179    /// other's artifact.
3180    #[test]
3181    fn a_pinned_seed_is_reproducible_but_never_the_run_id() {
3182        let mut cfg = Config::default();
3183        cfg.blind.seed = Some(1234);
3184        let a = RunState::new(
3185            PathBuf::from("/r"),
3186            "main".to_owned(),
3187            "c".to_owned(),
3188            "t".to_owned(),
3189            cfg.clone(),
3190        );
3191        let b = RunState::new(
3192            PathBuf::from("/r"),
3193            "main".to_owned(),
3194            "c".to_owned(),
3195            "t".to_owned(),
3196            cfg,
3197        );
3198        // What the seed is for: the same shuffles, run after run.
3199        assert_eq!(a.seed, 1234);
3200        assert_eq!(a.seed, b.seed);
3201        // What it is not for. Two runs are two runs, in the same second or
3202        // not, and everything keyed on the id depends on that.
3203        assert_ne!(
3204            a.id, b.id,
3205            "two runs sharing an id share a directory, artifacts and worktrees"
3206        );
3207    }
3208
3209    #[test]
3210    fn status_terminality() {
3211        assert!(RunStatus::Merged.done());
3212        assert!(RunStatus::Blocked.done());
3213        assert!(!RunStatus::Reviewing.done());
3214    }
3215
3216    fn overrun_seat(now: Timestamp, elapsed_secs: i64, timeout_secs: u64) -> ActiveSeat {
3217        ActiveSeat {
3218            node: "implement".to_owned(),
3219            started_at: now - jiff::SignedDuration::new(elapsed_secs, 0),
3220            timeout_secs,
3221            attempt: 0,
3222            task: None,
3223            command: None,
3224            index: None,
3225            total: None,
3226        }
3227    }
3228
3229    #[test]
3230    fn active_all_overrun_requires_every_seat_past_its_own_timeout() {
3231        let mut s = state();
3232        let now = Timestamp::now();
3233        assert!(
3234            !s.active_all_overrun(now),
3235            "nothing active is not evidence of anything"
3236        );
3237
3238        s.active
3239            .insert("impl-A".to_owned(), overrun_seat(now, 21_000, 3_600));
3240        assert!(
3241            s.active_all_overrun(now),
3242            "21000s elapsed against a 3600s budget"
3243        );
3244
3245        // A seat still well within its own budget means the run is not
3246        // provably dead, however far its sibling has overrun.
3247        s.active
3248            .insert("impl-B".to_owned(), overrun_seat(now, 0, 3_600));
3249        assert!(!s.active_all_overrun(now));
3250    }
3251
3252    /// A schema-11 run that ended Blocked cannot be pinned by a daemon pid
3253    /// that is still alive; one still mid-walk keeps asking the pid.
3254    #[test]
3255    fn migrating_schema_11_marks_only_ended_runs_as_exited() {
3256        for (status, exited) in [
3257            (RunStatus::Blocked, true),
3258            (RunStatus::Failed, true),
3259            (RunStatus::Stalled, true),
3260            (RunStatus::Landing, true),
3261            (RunStatus::Reviewing, false),
3262        ] {
3263            let mut s = state();
3264            s.schema = 11;
3265            s.status = status;
3266            let m = migrate_schema(s).unwrap();
3267            assert_eq!(m.schema, SCHEMA);
3268            assert_eq!(m.driver_exited, exited, "{status:?}");
3269        }
3270    }
3271
3272    /// A driver that recorded its own exit reads dead without its pid being
3273    /// asked: a daemon's pid outlives the runs it drove.
3274    #[test]
3275    fn an_exited_driver_is_dead_even_when_its_pid_answers_alive() {
3276        let mut s = state();
3277        s.driver_pid = Some(4242);
3278        s.driver_started_at = Some("1790000000".to_owned());
3279        s.driver_exited = true;
3280        let never = |_| -> Option<bool> { panic!("the pid must not be asked") };
3281        assert_eq!(
3282            s.liveness_with(false, never, |_| panic!("nor its identity")),
3283            Liveness::Dead
3284        );
3285        assert_eq!(s.liveness_with(true, never, |_| None), Liveness::Live);
3286    }
3287
3288    /// A daemon claim wins outright, whatever `driver_pid` or either query
3289    /// says — the stronger, independently-heartbeating signal. Neither query
3290    /// closure is even called: a daemon claim short-circuits before either
3291    /// one, which panicking closures here prove.
3292    #[test]
3293    fn liveness_reads_live_from_a_daemon_claim_alone() {
3294        let mut s = state();
3295        s.driver_pid = None;
3296        assert_eq!(
3297            s.liveness_with(
3298                true,
3299                |_| panic!("a daemon claim needs no pid query"),
3300                |_| panic!("a daemon claim needs no identity query")
3301            ),
3302            Liveness::Live,
3303            "a daemon claim needs no pid to back it up"
3304        );
3305    }
3306
3307    /// The gap `driver_pid` closes: no daemon claim (every manual `magi run`
3308    /// / `magi review`), but the recorded pid answers alive *and* the
3309    /// process currently holding it still carries the same start-time
3310    /// marker this run recorded — proof it is genuinely the same process,
3311    /// not merely the same number.
3312    #[test]
3313    fn liveness_reads_live_from_a_confirmed_pid_with_a_matching_identity() {
3314        let mut s = state();
3315        s.driver_pid = Some(4242);
3316        s.driver_started_at = Some("1790000000".to_owned());
3317        assert_eq!(
3318            s.liveness_with(
3319                false,
3320                |pid| {
3321                    assert_eq!(pid, 4242);
3322                    Some(true)
3323                },
3324                |pid| {
3325                    assert_eq!(pid, 4242);
3326                    Some("1790000000".to_owned())
3327                }
3328            ),
3329            Liveness::Live
3330        );
3331    }
3332
3333    /// No daemon claim and the recorded pid confirmed gone by the OS itself
3334    /// — dead outright, and the identity query is never even reached (a
3335    /// panicking closure proves it), since there is nothing left to
3336    /// corroborate.
3337    #[test]
3338    fn liveness_reads_dead_from_a_confirmed_dead_pid() {
3339        let mut s = state();
3340        s.driver_pid = Some(4242);
3341        assert_eq!(
3342            s.liveness_with(
3343                false,
3344                |_| Some(false),
3345                |_| panic!("a confirmed-dead pid needs no identity query")
3346            ),
3347            Liveness::Dead
3348        );
3349    }
3350
3351    /// The gap this task's review round exists to close: a killed manual
3352    /// run's pid gets handed to a wholly unrelated later process. `pid_status`
3353    /// alone would read that as `Live` — the reused pid really is alive —
3354    /// but the process now holding it started at a different moment than the
3355    /// one this run recorded, so this must read `Dead`, not `Live`: a
3356    /// mismatch is exactly as good as proof the original driver is gone.
3357    #[test]
3358    fn liveness_reads_dead_when_a_live_pid_no_longer_matches_the_recorded_start_time() {
3359        let mut s = state();
3360        s.driver_pid = Some(4242);
3361        s.driver_started_at = Some("1790000000".to_owned());
3362        assert_eq!(
3363            s.liveness_with(false, |_| Some(true), |_| Some("1790005400".to_owned())),
3364            Liveness::Dead,
3365            "the pid is alive, but under a different process than the one this run recorded"
3366        );
3367    }
3368
3369    /// Missing information never collapses to `Dead`: an old run with no
3370    /// `driver_pid` at all, a `driver_pid` this build could not query, a live
3371    /// pid with no recorded start time to compare (an even older run, before
3372    /// that field existed), and a live pid whose current identity this build
3373    /// could not re-query, all read as `Unknown` — never a guess in either
3374    /// direction.
3375    #[test]
3376    fn a_locale_format_marker_on_a_live_pid_reads_unknown_never_dead() {
3377        let mut s = state();
3378        s.driver_pid = Some(4242);
3379        for old in ["日 10/ 4 17:27:03 2026", "Sun Oct  4 17:27:03 2026"] {
3380            s.driver_started_at = Some(old.to_owned());
3381            assert_eq!(
3382                s.liveness_with(
3383                    false,
3384                    |_| Some(true),
3385                    |_| panic!("an old-format marker needs no identity query")
3386                ),
3387                Liveness::Unknown,
3388                "{old}"
3389            );
3390        }
3391    }
3392
3393    #[test]
3394    fn integer_markers_compare_live_on_match_and_dead_on_difference() {
3395        let mut s = state();
3396        s.driver_pid = Some(4242);
3397        s.driver_started_at = Some("1790000000".to_owned());
3398        assert_eq!(
3399            s.liveness_with(false, |_| Some(true), |_| Some("1790000000".to_owned())),
3400            Liveness::Live
3401        );
3402        assert_eq!(
3403            s.liveness_with(false, |_| Some(true), |_| Some("1790000001".to_owned())),
3404            Liveness::Dead
3405        );
3406    }
3407
3408    #[test]
3409    fn liveness_never_guesses_out_of_missing_information() {
3410        let mut s = state();
3411        s.driver_pid = None;
3412        assert_eq!(
3413            s.liveness_with(
3414                false,
3415                |_| panic!("no pid to query"),
3416                |_| panic!("no pid to query")
3417            ),
3418            Liveness::Unknown,
3419            "no driver_pid recorded at all — an old run predating this field"
3420        );
3421
3422        s.driver_pid = Some(4242);
3423        assert_eq!(
3424            s.liveness_with(false, |_| None, |_| panic!("inconclusive already")),
3425            Liveness::Unknown,
3426            "a pid to ask, but the platform could not answer for it"
3427        );
3428
3429        s.driver_started_at = None;
3430        assert_eq!(
3431            s.liveness_with(false, |_| Some(true), |_| Some("anything".to_owned())),
3432            Liveness::Unknown,
3433            "a live pid, but no recorded marker to corroborate it against — an old run \
3434             predating `driver_started_at`"
3435        );
3436
3437        s.driver_started_at = Some("1790000000".to_owned());
3438        assert_eq!(
3439            s.liveness_with(false, |_| Some(true), |_| None),
3440            Liveness::Unknown,
3441            "a live pid and a recorded marker, but the identity re-query itself failed"
3442        );
3443    }
3444
3445    #[test]
3446    fn abandon_clears_active_and_fails_a_non_terminal_run() {
3447        let mut s = state();
3448        s.status = RunStatus::Implementing;
3449        let now = Timestamp::now();
3450        s.active
3451            .insert("impl-A".to_owned(), overrun_seat(now, 21_000, 3_600));
3452
3453        s.abandon("daemon");
3454
3455        assert!(s.active.is_empty());
3456        assert_eq!(s.status, RunStatus::Failed);
3457        assert!(
3458            s.events
3459                .last()
3460                .expect("an event was logged")
3461                .message
3462                .contains("impl-A"),
3463            "the event names the abandoned seat"
3464        );
3465    }
3466
3467    #[test]
3468    fn abandon_never_overwrites_a_status_already_terminal() {
3469        let mut s = state();
3470        s.status = RunStatus::Ready;
3471        let now = Timestamp::now();
3472        s.active
3473            .insert("impl-A".to_owned(), overrun_seat(now, 21_000, 3_600));
3474
3475        s.abandon("daemon");
3476
3477        assert!(s.active.is_empty());
3478        assert_eq!(
3479            s.status,
3480            RunStatus::Ready,
3481            "a run already done must not be relabelled Failed"
3482        );
3483    }
3484
3485    #[test]
3486    fn candidate_viability_excludes_empty_and_failed() {
3487        let mut c = Candidate {
3488            index: 0,
3489            label: 'A',
3490            agent: "a".to_owned(),
3491            branch: "b".to_owned(),
3492            worktree: PathBuf::from("/w"),
3493            summary: String::new(),
3494            stat: String::new(),
3495            files: 1,
3496            commits: 1,
3497            empty: false,
3498            failed: None,
3499            verified_noop: None,
3500            duration_ms: 0,
3501            folded: false,
3502        };
3503        assert!(c.viable());
3504        c.empty = true;
3505        assert!(!c.viable());
3506        c.empty = false;
3507        c.failed = Some("timeout".to_owned());
3508        assert!(!c.viable());
3509    }
3510
3511    #[test]
3512    fn build_failure_is_distinguished_from_a_failing_test() {
3513        let link_race = CommandOutcome {
3514            command: "cargo test".to_owned(),
3515            code: Some(1),
3516            output_tail: "LINK : fatal error LNK1104: cannot open file \
3517                          'graph_dirty_tree-71d4dc8e.exe'\n\
3518                          error: could not compile `magi-cli` (test \"graph_dirty_tree\")"
3519                .to_owned(),
3520            duration_ms: 500,
3521            resource_blocked: false,
3522        };
3523        assert!(!link_race.ok());
3524        assert!(link_race.build_failed());
3525
3526        let failing_test = CommandOutcome {
3527            command: "cargo test".to_owned(),
3528            code: Some(101),
3529            output_tail: "thread 'it_works' panicked at 'assertion failed'".to_owned(),
3530            duration_ms: 500,
3531            resource_blocked: false,
3532        };
3533        assert!(!failing_test.ok());
3534        assert!(
3535            !failing_test.build_failed(),
3536            "a real test failure must not be classed as a build failure"
3537        );
3538
3539        let passing = CommandOutcome {
3540            command: "cargo test".to_owned(),
3541            code: Some(0),
3542            output_tail: String::new(),
3543            duration_ms: 500,
3544            resource_blocked: false,
3545        };
3546        assert!(passing.ok());
3547        assert!(!passing.build_failed());
3548    }
3549
3550    #[test]
3551    fn tail_keeps_the_end_on_a_line_boundary() {
3552        let text = (0..100).map(|i| format!("line {i}\n")).collect::<String>();
3553        let t = tail(&text, 40);
3554        assert!(t.starts_with("[..."));
3555        assert!(t.ends_with("line 99\n"));
3556        assert!(t.len() < 120);
3557        assert_eq!(tail("short", 40), "short");
3558    }
3559
3560    #[test]
3561    fn tail_survives_multibyte_cuts() {
3562        let text = "あ".repeat(50);
3563        let t = tail(&text, 10);
3564        assert!(t.contains("earlier bytes omitted"));
3565        assert!(t.ends_with('あ'));
3566    }
3567
3568    fn finding(id: &str, severity: crate::verdict::Severity) -> crate::verdict::Finding {
3569        crate::verdict::Finding {
3570            id: id.to_owned(),
3571            severity,
3572            file: None,
3573            line: None,
3574            title: "x".to_owned(),
3575            detail: String::new(),
3576        }
3577    }
3578
3579    fn round(clean: bool, findings: Vec<crate::verdict::Finding>) -> ReviewRound {
3580        ReviewRound {
3581            round: 1,
3582            head: "h".to_owned(),
3583            verified_head: None,
3584            verified_at: None,
3585            reviews: vec![ReviewRecord {
3586                attempts: 0,
3587                reviewer: 1,
3588                agent: "a".to_owned(),
3589                summary: String::new(),
3590                findings,
3591                vote: None,
3592                failed: None,
3593                duration_ms: 0,
3594            }],
3595            e2e: Vec::new(),
3596            verify_retried: false,
3597            e2e_deferred: false,
3598            e2e_defer_reason: None,
3599            fix: None,
3600            blocking: 0,
3601            answered: 1,
3602            expected: 1,
3603            clean,
3604            progressed: false,
3605            vote_split: false,
3606            reconsideration: Vec::new(),
3607            verdict: None,
3608        }
3609    }
3610
3611    fn voted(
3612        findings: Vec<crate::verdict::Finding>,
3613        votes: &[ReviewVote],
3614        revotes: &[Option<ReviewVote>],
3615    ) -> ReviewRound {
3616        let mut r = round(false, findings);
3617        r.reviews = votes
3618            .iter()
3619            .enumerate()
3620            .map(|(i, v)| {
3621                let mut rec = r.reviews[0].clone();
3622                rec.reviewer = i + 1;
3623                rec.vote = Some(*v);
3624                if i > 0 {
3625                    rec.findings = Vec::new();
3626                }
3627                rec
3628            })
3629            .collect();
3630        r.reconsideration = revotes
3631            .iter()
3632            .enumerate()
3633            .map(|(i, v)| ReviewRevoteRecord {
3634                reviewer: i + 1,
3635                agent: "a".to_owned(),
3636                vote: *v,
3637                reason: String::new(),
3638                failed: None,
3639            })
3640            .collect();
3641        r
3642    }
3643
3644    #[test]
3645    fn a_hand_off_is_contested_only_by_a_blocking_finding_and_a_reject_vote() {
3646        use crate::verdict::Severity::{Major, Minor};
3647        use ReviewVote::{Approve, Reject};
3648        let major = || vec![finding("R1-1-1", Major)];
3649        let minor = || vec![finding("R1-1-1", Minor)];
3650
3651        let c = voted(major(), &[Reject, Approve], &[])
3652            .contested_handoff()
3653            .expect("major + reject");
3654        assert_eq!(c.findings.len(), 1);
3655        assert_eq!(c.rejecters, vec![(1, "a".to_owned())]);
3656
3657        assert!(
3658            voted(minor(), &[Reject, Approve], &[])
3659                .contested_handoff()
3660                .is_none()
3661        );
3662        assert!(
3663            voted(major(), &[Approve, Approve], &[])
3664                .contested_handoff()
3665                .is_none()
3666        );
3667        assert!(
3668            voted(Vec::new(), &[Reject], &[])
3669                .contested_handoff()
3670                .is_none()
3671        );
3672    }
3673
3674    #[test]
3675    fn a_reject_withdrawn_in_the_revote_does_not_contest_and_an_unanswered_one_stands() {
3676        use crate::verdict::Severity::Major;
3677        use ReviewVote::{Approve, Reject};
3678        let major = || vec![finding("R1-1-1", Major)];
3679
3680        let withdrawn = voted(major(), &[Reject, Approve], &[Some(Approve), Some(Approve)]);
3681        assert!(withdrawn.contested_handoff().is_none());
3682
3683        let unanswered = voted(major(), &[Reject, Approve], &[None, Some(Approve)]);
3684        assert!(
3685            unanswered.contested_handoff().is_some(),
3686            "no revote falls back to the initial reject"
3687        );
3688
3689        let raised = voted(major(), &[Approve, Approve], &[Some(Reject), Some(Approve)]);
3690        assert!(raised.contested_handoff().is_some());
3691    }
3692
3693    #[test]
3694    fn e2e_status_tells_deferred_apart_from_not_configured() {
3695        let mut r = round(false, Vec::new());
3696        assert_eq!(r.e2e_status(), E2eStatus::NotConfigured);
3697
3698        r.e2e_deferred = true;
3699        assert_eq!(
3700            r.e2e_status(),
3701            E2eStatus::Deferred,
3702            "an empty e2e must not read as unconfigured once it was deferred on purpose"
3703        );
3704
3705        r.e2e = vec![CommandOutcome {
3706            command: "test".to_owned(),
3707            code: Some(0),
3708            output_tail: String::new(),
3709            duration_ms: 0,
3710            resource_blocked: false,
3711        }];
3712        assert_eq!(
3713            r.e2e_status(),
3714            E2eStatus::Passed,
3715            "a round with real outcomes is never read as deferred, even if the flag is still set"
3716        );
3717    }
3718
3719    #[test]
3720    fn e2e_status_reports_a_real_failure_as_failed_not_deferred() {
3721        let mut r = round(false, Vec::new());
3722        r.e2e = vec![CommandOutcome {
3723            command: "test".to_owned(),
3724            code: Some(1),
3725            output_tail: "boom".to_owned(),
3726            duration_ms: 0,
3727            resource_blocked: false,
3728        }];
3729        assert_eq!(r.e2e_status(), E2eStatus::Failed);
3730    }
3731
3732    #[test]
3733    fn e2e_status_never_reads_a_resource_block_as_a_failure() {
3734        // The exact shape of contention on the shared build cache: `e2e`
3735        // holds one outcome, and it is `resource_blocked`, never a command
3736        // that actually ran and produced a red exit code.
3737        let mut r = round(false, Vec::new());
3738        r.e2e = vec![CommandOutcome {
3739            command: "(waiting for the shared build cache)".to_owned(),
3740            code: None,
3741            output_tail: "contended".to_owned(),
3742            duration_ms: 0,
3743            resource_blocked: true,
3744        }];
3745        assert_eq!(
3746            r.e2e_status(),
3747            E2eStatus::ResourceBlocked,
3748            "magi's own inability to get a command to run must not read as a verdict on the \
3749             patch"
3750        );
3751    }
3752
3753    #[test]
3754    fn verification_summary_is_silent_when_there_is_nothing_worth_saying() {
3755        let mut r = round(true, Vec::new());
3756        assert!(
3757            r.verification_summary("h").is_none(),
3758            "no verify.e2e configured: nothing to surface"
3759        );
3760        r.e2e = vec![CommandOutcome {
3761            command: "test".to_owned(),
3762            code: Some(0),
3763            output_tail: String::new(),
3764            duration_ms: 0,
3765            resource_blocked: false,
3766        }];
3767        assert!(
3768            r.verification_summary("h").is_none(),
3769            "a green result needs no skepticism attached to it"
3770        );
3771    }
3772
3773    #[test]
3774    fn verification_summary_tells_the_current_head_apart_from_an_earlier_one() {
3775        let mut r = round(false, Vec::new());
3776        r.head = "h1".to_owned();
3777        r.e2e = vec![CommandOutcome {
3778            command: "test".to_owned(),
3779            code: Some(1),
3780            output_tail: "boom".to_owned(),
3781            duration_ms: 0,
3782            resource_blocked: false,
3783        }];
3784        r.verified_head = Some("h1".to_owned());
3785        r.verified_at = Some(Timestamp::now());
3786
3787        let fresh = r.verification_summary("h1").expect("a failure is surfaced");
3788        assert!(
3789            fresh.label.contains("this is the head being looked at now"),
3790            "{}",
3791            fresh.label
3792        );
3793        assert_eq!(fresh.tail.as_deref(), Some("$ test\nboom\n"));
3794
3795        let stale = r.verification_summary("h2").expect("still surfaced");
3796        assert!(
3797            stale.label.contains("an earlier head, since superseded"),
3798            "a result about a different commit than the one being looked at now must say so, \
3799             not read as current: {}",
3800            stale.label
3801        );
3802    }
3803
3804    #[test]
3805    fn verification_summary_marks_a_resource_block_and_a_deferral_distinctly_from_a_failure() {
3806        let mut r = round(false, Vec::new());
3807        r.e2e = vec![CommandOutcome {
3808            command: "(waiting for the shared build cache)".to_owned(),
3809            code: None,
3810            output_tail: "contended".to_owned(),
3811            duration_ms: 0,
3812            resource_blocked: true,
3813        }];
3814        let blocked = r
3815            .verification_summary("h")
3816            .expect("a resource block is still surfaced, never silent");
3817        assert!(blocked.label.contains("could not run"));
3818        // No command actually ran, but which operation was attempted is
3819        // still a fact worth showing — never silent past the label either.
3820        let tail = blocked
3821            .tail
3822            .expect("the attempted operation is still named");
3823        assert!(tail.contains("(waiting for the shared build cache)"));
3824        assert!(tail.contains("contended"));
3825
3826        let mut d = round(false, Vec::new());
3827        d.e2e_deferred = true;
3828        d.e2e_defer_reason = Some("2 blocking finding(s) already required a fix".to_owned());
3829        let deferred = d.verification_summary("h").expect("deferred is surfaced");
3830        assert!(deferred.label.contains("deferred to the fixer"));
3831        assert!(deferred.label.contains("2 blocking finding(s)"));
3832        assert!(deferred.tail.is_none());
3833    }
3834
3835    #[test]
3836    fn verification_summary_says_unknown_rather_than_guessing_a_time_or_a_commit() {
3837        let mut r = round(false, Vec::new());
3838        r.e2e = vec![CommandOutcome {
3839            command: "test".to_owned(),
3840            code: Some(1),
3841            output_tail: "boom".to_owned(),
3842            duration_ms: 0,
3843            resource_blocked: false,
3844        }];
3845        // verified_head/verified_at left at their default `None` — exactly
3846        // the shape a schema-7 round with no reconstructable timestamp has.
3847        let summary = r.verification_summary("h").expect("a failure is surfaced");
3848        assert!(summary.label.contains("commit unknown"));
3849        assert!(summary.label.contains("checked at: unknown"));
3850    }
3851
3852    #[test]
3853    fn gate_status_tells_not_run_apart_from_passed_with_no_commands() {
3854        let mut s = state();
3855        assert_eq!(s.gate_status(), GateStatus::NotRun);
3856
3857        s.gate_ran = true;
3858        assert_eq!(
3859            s.gate_status(),
3860            GateStatus::PassedWithNoCommands,
3861            "an empty gate must read as a real pass once gate_ran says it actually ran"
3862        );
3863
3864        s.gate = vec![CommandOutcome {
3865            command: "cargo make check".to_owned(),
3866            code: Some(0),
3867            output_tail: String::new(),
3868            duration_ms: 0,
3869            resource_blocked: false,
3870        }];
3871        assert_eq!(s.gate_status(), GateStatus::Passed);
3872
3873        s.gate[0].code = Some(1);
3874        assert_eq!(s.gate_status(), GateStatus::Failed);
3875
3876        s.gate_ran = false;
3877        assert_eq!(
3878            s.gate_status(),
3879            GateStatus::NotRun,
3880            "gate_ran false must win even over a non-empty gate left from a stale record"
3881        );
3882    }
3883
3884    #[test]
3885    fn open_findings_is_empty_when_the_last_round_was_clean() {
3886        let mut s = state();
3887        s.reviews = vec![round(
3888            true,
3889            vec![finding("R1-1-1", crate::verdict::Severity::Minor)],
3890        )];
3891        assert!(s.open_findings().is_empty());
3892    }
3893
3894    #[test]
3895    fn open_findings_reads_the_last_non_clean_round() {
3896        let mut s = state();
3897        s.reviews = vec![round(
3898            false,
3899            vec![finding("R1-1-1", crate::verdict::Severity::Major)],
3900        )];
3901        let open = s.open_findings();
3902        assert_eq!(open.len(), 1);
3903        assert_eq!(open[0].id, "R1-1-1");
3904    }
3905
3906    #[test]
3907    fn handed_off_with_open_findings_needs_a_mergeable_status_and_an_open_round() {
3908        let mut s = state();
3909        s.reviews = vec![round(
3910            false,
3911            vec![finding("R1-1-1", crate::verdict::Severity::Major)],
3912        )];
3913
3914        s.status = RunStatus::Blocked;
3915        assert!(
3916            !s.handed_off_with_open_findings(),
3917            "a blocked run is not a hand-off"
3918        );
3919
3920        s.status = RunStatus::Ready;
3921        assert!(s.handed_off_with_open_findings());
3922
3923        s.reviews = vec![round(true, Vec::new())];
3924        assert!(
3925            !s.handed_off_with_open_findings(),
3926            "a clean last round has nothing to hand off"
3927        );
3928    }
3929
3930    #[test]
3931    fn unmerged_by_design_is_only_ready_reached_via_merge_mode_none() {
3932        let mut s = state();
3933
3934        s.status = RunStatus::Ready;
3935        assert!(
3936            !s.unmerged_by_design(),
3937            "no merge outcome recorded at all must not be flagged"
3938        );
3939
3940        s.merge = Some(MergeOutcome {
3941            mode: MergeMode::None,
3942            ok: true,
3943            detail: "git merge --no-ff magi/x/A".to_owned(),
3944            empty: false,
3945        });
3946        assert!(
3947            s.unmerged_by_design(),
3948            "Ready reached through mode none is the case this exists to flag"
3949        );
3950
3951        // A PR closed without merging also leaves `status` at `Ready`, but
3952        // through `mode = "pr"` — a run that may still have been landable by
3953        // a person watching the PR, unlike the honest mode-none no-op.
3954        s.merge = Some(MergeOutcome {
3955            mode: MergeMode::Pr,
3956            ok: false,
3957            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
3958            empty: false,
3959        });
3960        assert!(
3961            !s.unmerged_by_design(),
3962            "a closed pull request is a different Ready and must not be relabelled"
3963        );
3964
3965        // Same signal must not fire before the run actually got there.
3966        s.status = RunStatus::Gating;
3967        s.merge = Some(MergeOutcome {
3968            mode: MergeMode::None,
3969            ok: true,
3970            detail: "git merge --no-ff magi/x/A".to_owned(),
3971            empty: false,
3972        });
3973        assert!(
3974            !s.unmerged_by_design(),
3975            "status must actually be Ready, not merely have a stale mode-none merge record"
3976        );
3977    }
3978
3979    #[test]
3980    fn state_round_trips_through_json() {
3981        let s = state();
3982        let body = serde_json::to_string(&s).unwrap();
3983        let back: RunState = serde_json::from_str(&body).unwrap();
3984        assert_eq!(back.id, s.id);
3985        assert_eq!(back.instruction, "add retries");
3986        assert_eq!(back.status, RunStatus::Prep);
3987    }
3988
3989    #[test]
3990    fn a_round_recorded_before_e2e_deferral_existed_still_loads() {
3991        // Exactly the shape a pre-existing `run.json` has for a round: no
3992        // `e2e_deferred`, no `e2e_defer_reason`. Every round used to run e2e
3993        // unconditionally, so the honest reading of an old record's silence
3994        // on this is "it was not deferred" — `false`/`None`, not a load
3995        // failure and not a schema bump (see the `SCHEMA` doc comment: a
3996        // purely additive field whose absence has one unambiguous meaning
3997        // does not need one).
3998        let body = r#"{
3999            "round": 1,
4000            "head": "deadbeef",
4001            "reviews": [],
4002            "e2e": [],
4003            "verify_retried": false,
4004            "fix": null,
4005            "blocking": 0,
4006            "answered": 1,
4007            "expected": 1,
4008            "clean": true
4009        }"#;
4010        let r: ReviewRound = serde_json::from_str(body).expect("an old-shaped round must load");
4011        assert!(!r.e2e_deferred);
4012        assert!(r.e2e_defer_reason.is_none());
4013        assert_eq!(r.e2e_status(), E2eStatus::NotConfigured);
4014    }
4015
4016    #[test]
4017    fn schema_five_state_migrates_old_empty_e2e_and_legacy_verify_budget() {
4018        let mut value = serde_json::to_value(state()).expect("serialize state");
4019        let object = value.as_object_mut().expect("state object");
4020        object.insert("schema".to_owned(), serde_json::json!(5));
4021        let graph = object["config"]["graph"]
4022            .as_object_mut()
4023            .expect("graph object");
4024        graph.insert("timeout_review".to_owned(), serde_json::json!(3600));
4025        graph.remove("timeout_verify");
4026        let review = object["reviews"].as_array_mut().expect("reviews");
4027        review.push(serde_json::json!({
4028            "round": 1, "head": "old", "reviews": [], "e2e": [],
4029            "verify_retried": false, "blocking": 0, "answered": 1,
4030            "expected": 1, "clean": true
4031        }));
4032        let old: RunState = serde_json::from_value(value).expect("schema-5 shape parses");
4033        let migrated = migrate_schema(old).expect("schema 5 migrates");
4034        assert_eq!(migrated.schema, SCHEMA);
4035        assert_eq!(migrated.config.graph.verify_timeout(), 3600);
4036        assert_eq!(migrated.reviews[0].e2e_status(), E2eStatus::NotConfigured);
4037    }
4038
4039    #[test]
4040    fn schema_six_state_with_a_recorded_gate_migrates_to_gate_ran_true() {
4041        let mut value = serde_json::to_value(state()).expect("serialize state");
4042        let object = value.as_object_mut().expect("state object");
4043        object.insert("schema".to_owned(), serde_json::json!(6));
4044        object.insert(
4045            "gate".to_owned(),
4046            serde_json::json!([{
4047                "command": "cargo make check",
4048                "code": 0,
4049                "output_tail": "",
4050                "duration_ms": 0,
4051                "resource_blocked": false
4052            }]),
4053        );
4054        let old: RunState = serde_json::from_value(value).expect("schema-6 shape parses");
4055        let migrated = migrate_schema(old).expect("schema 6 migrates");
4056        assert_eq!(migrated.schema, SCHEMA);
4057        assert!(
4058            migrated.gate_ran,
4059            "a non-empty recorded gate is a real attempt, not an unrun one"
4060        );
4061        assert_eq!(migrated.gate_status(), GateStatus::Passed);
4062    }
4063
4064    #[test]
4065    fn schema_six_state_with_an_empty_gate_migrates_to_gate_ran_false_and_is_retried() {
4066        // The exact shape of the stuck `shoka` run this schema bump fixes:
4067        // `verify.gate` empty, `gate` empty, schema 6. It must come back as
4068        // "not yet run" so the next `gate()` call re-attempts it — and for a
4069        // repo with no gate commands configured, that resolves instantly to
4070        // `PassedWithNoCommands` instead of staying stuck forever.
4071        let mut value = serde_json::to_value(state()).expect("serialize state");
4072        let object = value.as_object_mut().expect("state object");
4073        object.insert("schema".to_owned(), serde_json::json!(6));
4074        object.insert("gate".to_owned(), serde_json::json!([]));
4075        let old: RunState = serde_json::from_value(value).expect("schema-6 shape parses");
4076        let migrated = migrate_schema(old).expect("schema 6 migrates");
4077        assert_eq!(migrated.schema, SCHEMA);
4078        assert!(
4079            !migrated.gate_ran,
4080            "an empty gate on schema 6 is ambiguous and must be treated as unrun"
4081        );
4082        assert_eq!(migrated.gate_status(), GateStatus::NotRun);
4083    }
4084
4085    #[test]
4086    fn schema_seven_state_reconstructs_verified_head_for_a_round_that_actually_ran_e2e() {
4087        // Schema 7's main review loop always checked `e2e` against the
4088        // round's own `head` — it just never wrote that into `verified_head`
4089        // unless a catch-up run had checked a *different* commit. Migrating
4090        // to schema 8 restores that always-true fact instead of leaving a
4091        // reader to assume it.
4092        let mut value = serde_json::to_value(state()).expect("serialize state");
4093        let object = value.as_object_mut().expect("state object");
4094        object.insert("schema".to_owned(), serde_json::json!(7));
4095        let reviews = object["reviews"].as_array_mut().expect("reviews");
4096        reviews.push(serde_json::json!({
4097            "round": 1, "head": "deadbeef", "reviews": [],
4098            "e2e": [{
4099                "command": "cargo test", "code": 0, "output_tail": "",
4100                "duration_ms": 0, "resource_blocked": false
4101            }],
4102            "verify_retried": false, "blocking": 0, "answered": 1,
4103            "expected": 1, "clean": true
4104        }));
4105        let old: RunState = serde_json::from_value(value).expect("schema-7 shape parses");
4106        let migrated = migrate_schema(old).expect("schema 7 migrates");
4107        assert_eq!(migrated.schema, SCHEMA);
4108        assert_eq!(
4109            migrated.reviews[0].verified_head.as_deref(),
4110            Some("deadbeef"),
4111            "a schema-7 round's main-loop e2e was always against its own head, even though the \
4112             field never said so"
4113        );
4114        assert!(
4115            migrated.reviews[0].verified_at.is_none(),
4116            "no historical timestamp exists to reconstruct; unknown stays unknown, not a \
4117             guessed 'now'"
4118        );
4119    }
4120
4121    #[test]
4122    fn schema_seven_state_leaves_a_deferred_round_with_no_verified_head() {
4123        let mut value = serde_json::to_value(state()).expect("serialize state");
4124        let object = value.as_object_mut().expect("state object");
4125        object.insert("schema".to_owned(), serde_json::json!(7));
4126        let reviews = object["reviews"].as_array_mut().expect("reviews");
4127        reviews.push(serde_json::json!({
4128            "round": 1, "head": "deadbeef", "reviews": [],
4129            "e2e": [], "e2e_deferred": true,
4130            "verify_retried": false, "blocking": 1, "answered": 1,
4131            "expected": 1, "clean": false
4132        }));
4133        let old: RunState = serde_json::from_value(value).expect("schema-7 shape parses");
4134        let migrated = migrate_schema(old).expect("schema 7 migrates");
4135        assert!(
4136            migrated.reviews[0].verified_head.is_none(),
4137            "a deferred round never ran e2e; there is nothing to reconstruct"
4138        );
4139    }
4140
4141    #[test]
4142    fn origin_round_trips_through_the_run_state() {
4143        let mut s = state();
4144        s.origin = Some(Origin::from_agent_env(
4145            Some(("4a7b".to_owned(), "chat".to_owned())),
4146            Some("20260930-092817-4f6f".to_owned()),
4147        ));
4148        let back: RunState =
4149            serde_json::from_str(&serde_json::to_string(&s).unwrap()).expect("parse back");
4150        assert_eq!(back.origin, s.origin);
4151        assert_eq!(
4152            back.origin.as_ref().unwrap().by,
4153            StartedBy::Chat {
4154                talk: "4a7b".to_owned()
4155            }
4156        );
4157        assert_eq!(
4158            origin_label(back.origin.as_ref()),
4159            "chat 4a7b, for task 4f6f"
4160        );
4161    }
4162
4163    #[test]
4164    fn a_schema_twelve_record_without_an_origin_loads_and_reads_as_unknown() {
4165        let mut value = serde_json::to_value(state()).expect("serialize state");
4166        let object = value.as_object_mut().expect("state object");
4167        object.insert("schema".to_owned(), serde_json::json!(12));
4168        object.remove("origin");
4169        let old: RunState = serde_json::from_value(value).expect("schema-12 shape parses");
4170        assert!(old.origin.is_none());
4171        let migrated = migrate_schema(old).expect("schema 12 migrates");
4172        assert_eq!(migrated.schema, SCHEMA);
4173        assert!(
4174            migrated.origin.is_none(),
4175            "an origin nobody recorded is not invented"
4176        );
4177        assert_eq!(
4178            origin_label(migrated.origin.as_ref()),
4179            "origin unknown (started before origins were recorded)"
4180        );
4181    }
4182
4183    #[test]
4184    fn origin_attributes_agents_by_node_and_never_by_guesswork() {
4185        let chat = Origin::from_agent_env(Some(("4a7b".to_owned(), "chat".to_owned())), None);
4186        assert_eq!(
4187            chat.by,
4188            StartedBy::Chat {
4189                talk: "4a7b".into()
4190            }
4191        );
4192        let seat = Origin::from_agent_env(
4193            Some(("20260930-092817-ec34".to_owned(), "implement".to_owned())),
4194            None,
4195        );
4196        assert_eq!(seat.label(), "implement@ec34");
4197        assert_eq!(Origin::from_agent_env(None, None), Origin::operator());
4198        assert_eq!(Origin::operator().label(), "operator");
4199        assert_eq!(Origin::queue("20260930-000000-4f6f").label(), "task 4f6f");
4200        assert_eq!(
4201            Origin::operator()
4202                .serving(Some("20260930-000000-4f6f".to_owned()))
4203                .label(),
4204            "operator, for task 4f6f"
4205        );
4206    }
4207
4208    #[test]
4209    fn schema_six_serialization_is_rejected_by_a_schema_five_reader() {
4210        let body = serde_json::to_value(state()).expect("serialize state");
4211        assert_eq!(body["schema"], serde_json::json!(SCHEMA));
4212        assert_ne!(body["schema"], serde_json::json!(5));
4213    }
4214
4215    #[test]
4216    fn seat_started_and_finished_track_who_has_not_answered_yet() {
4217        let mut s = state();
4218        s.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
4219        s.seat_started("judge", "judge-2", std::time::Duration::from_secs(60), 0);
4220        assert_eq!(s.active.len(), 2, "both seats are still out");
4221
4222        s.seat_finished("judge-1");
4223        assert_eq!(
4224            s.active.keys().collect::<Vec<_>>(),
4225            vec!["judge-2"],
4226            "only the seat that answered drops out; judge-2 is still waited on"
4227        );
4228    }
4229
4230    /// `seats_active` / `tasks_active` are the accessors report/web read
4231    /// instead of `active` directly, so neither ever counts the other kind of
4232    /// entry as a seat — a `verify.e2e` task must never inflate a quorum or
4233    /// seat count, and a seat must never show up in a task listing.
4234    #[test]
4235    fn seats_active_and_tasks_active_never_cross_over() {
4236        let mut s = state();
4237        s.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
4238        s.task_command(
4239            "e2e",
4240            "verify",
4241            0,
4242            "cargo test",
4243            1,
4244            2,
4245            std::time::Duration::from_secs(600),
4246        );
4247
4248        assert_eq!(
4249            s.seats_active()
4250                .map(|(k, _)| k.as_str())
4251                .collect::<Vec<_>>(),
4252            vec!["judge-1"]
4253        );
4254        assert_eq!(
4255            s.tasks_active()
4256                .map(|(k, _)| k.as_str())
4257                .collect::<Vec<_>>(),
4258            vec!["e2e"]
4259        );
4260
4261        // A command boundary updates the same entry in place — still one
4262        // task, never a second one accumulating alongside it.
4263        s.task_command(
4264            "e2e",
4265            "verify",
4266            0,
4267            "cargo clippy",
4268            2,
4269            2,
4270            std::time::Duration::from_secs(600),
4271        );
4272        assert_eq!(s.tasks_active().count(), 1);
4273        assert_eq!(s.active["e2e"].command.as_deref(), Some("cargo clippy"));
4274
4275        s.task_finished("e2e");
4276        assert!(s.tasks_active().next().is_none());
4277        assert_eq!(
4278            s.seats_active()
4279                .map(|(k, _)| k.as_str())
4280                .collect::<Vec<_>>(),
4281            vec!["judge-1"],
4282            "clearing the task must not touch the seat entry"
4283        );
4284    }
4285
4286    #[test]
4287    fn a_retry_is_recorded_as_a_later_attempt_on_the_same_seat() {
4288        let mut s = state();
4289        s.seat_started("review", "review-2", std::time::Duration::from_secs(30), 0);
4290        s.seat_finished("review-2");
4291        // A nudge re-asks the same seat; attempt says this is not the first
4292        // time, which is the only trace a nudge otherwise leaves behind.
4293        s.seat_started("review", "review-2", std::time::Duration::from_secs(30), 1);
4294        assert_eq!(s.active["review-2"].attempt, 1);
4295    }
4296
4297    #[test]
4298    fn active_seat_reports_elapsed_and_remaining_time() {
4299        let now = Timestamp::now();
4300        let started = now - jiff::SignedDuration::from_secs(30);
4301        let seat = ActiveSeat {
4302            node: "judge".to_owned(),
4303            started_at: started,
4304            timeout_secs: 100,
4305            attempt: 0,
4306            task: None,
4307            command: None,
4308            index: None,
4309            total: None,
4310        };
4311        assert_eq!(seat.elapsed_secs(now), 30);
4312        assert_eq!(seat.remaining_secs(now), 70);
4313    }
4314
4315    #[test]
4316    fn remaining_time_never_goes_negative_past_the_timeout() {
4317        // `agy`'s own print-timeout occasionally overruns by a hair before the
4318        // kill lands; a naive subtraction would print a negative "time left".
4319        let now = Timestamp::now();
4320        let started = now - jiff::SignedDuration::from_secs(200);
4321        let seat = ActiveSeat {
4322            node: "implement".to_owned(),
4323            started_at: started,
4324            timeout_secs: 100,
4325            attempt: 1,
4326            task: None,
4327            command: None,
4328            index: None,
4329            total: None,
4330        };
4331        assert_eq!(seat.remaining_secs(now), 0);
4332    }
4333
4334    #[test]
4335    fn clear_active_drops_stale_seats_and_reports_whether_it_did() {
4336        let mut s = state();
4337        assert!(!s.clear_active(), "nothing to clear on a fresh run");
4338        s.seat_started(
4339            "implement",
4340            "impl-B",
4341            std::time::Duration::from_secs(3600),
4342            0,
4343        );
4344        assert!(s.clear_active(), "a leftover entry is reported as cleared");
4345        assert!(s.active.is_empty());
4346    }
4347
4348    #[test]
4349    fn active_seat_carries_nothing_that_could_be_read_as_output_bytes() {
4350        // `agy` prints exactly one JSON object, at the very end (see
4351        // `agent::dropped_stream`'s doc comment) — a seat can sit at zero
4352        // captured bytes for its whole timeout while working normally. So
4353        // `ActiveSeat` records only the wall-clock facts (when it started,
4354        // its budget, which attempt), never a byte count, which is what
4355        // keeps a reader from being able to build "0 bytes => dead" out of
4356        // it even by accident.
4357        let seat = ActiveSeat {
4358            node: "implement".to_owned(),
4359            started_at: Timestamp::now(),
4360            timeout_secs: 60,
4361            attempt: 0,
4362            task: None,
4363            command: None,
4364            index: None,
4365            total: None,
4366        };
4367        let value = serde_json::to_value(&seat).unwrap();
4368        let keys: std::collections::BTreeSet<String> =
4369            value.as_object().unwrap().keys().cloned().collect();
4370        assert_eq!(
4371            keys,
4372            std::collections::BTreeSet::from([
4373                "node".to_owned(),
4374                "started_at".to_owned(),
4375                "timeout_secs".to_owned(),
4376                "attempt".to_owned(),
4377            ]),
4378            "a byte count here would be a lever to declare a silent-but-healthy seat dead, and \
4379             the task-only fields must stay absent (not null) on an ordinary seat entry"
4380        );
4381    }
4382
4383    /// The same guarantee as
4384    /// [`active_seat_carries_nothing_that_could_be_read_as_output_bytes`],
4385    /// extended to a task entry: `verify.e2e` / `verify.gate` are exactly as
4386    /// silent as `agy` between commands, so a running command-list task must
4387    /// never carry anything a reader could mistake for output-byte evidence
4388    /// either.
4389    #[test]
4390    fn task_active_seat_carries_nothing_that_could_be_read_as_output_bytes() {
4391        let seat = ActiveSeat {
4392            node: "verify".to_owned(),
4393            started_at: Timestamp::now(),
4394            timeout_secs: 600,
4395            attempt: 0,
4396            task: Some("e2e".to_owned()),
4397            command: Some("cargo test".to_owned()),
4398            index: Some(1),
4399            total: Some(3),
4400        };
4401        let value = serde_json::to_value(&seat).unwrap();
4402        let keys: std::collections::BTreeSet<String> =
4403            value.as_object().unwrap().keys().cloned().collect();
4404        assert_eq!(
4405            keys,
4406            std::collections::BTreeSet::from([
4407                "node".to_owned(),
4408                "started_at".to_owned(),
4409                "timeout_secs".to_owned(),
4410                "attempt".to_owned(),
4411                "task".to_owned(),
4412                "command".to_owned(),
4413                "index".to_owned(),
4414                "total".to_owned(),
4415            ]),
4416        );
4417    }
4418
4419    #[test]
4420    fn an_old_run_json_without_active_seats_still_loads() {
4421        // Schema did not bump for this field: an already-written run.json
4422        // simply lacks the key, and `#[serde(default)]` must fill it in
4423        // rather than fail the whole read.
4424        let s = state();
4425        let mut value = serde_json::to_value(&s).unwrap();
4426        value.as_object_mut().unwrap().remove("active");
4427        let back: RunState = serde_json::from_value(value).unwrap();
4428        assert!(back.active.is_empty());
4429        assert_eq!(back.schema, SCHEMA);
4430    }
4431
4432    #[test]
4433    fn an_old_run_json_without_jobs_still_loads() {
4434        // No schema bump for this field either, for the same reason: an
4435        // empty `jobs` list on an old record means exactly what it always
4436        // meant for that record — no adapter existed yet to report one —
4437        // and `#[serde(default)]` fills it in rather than failing the read.
4438        let s = state();
4439        let mut value = serde_json::to_value(&s).unwrap();
4440        value.as_object_mut().unwrap().remove("jobs");
4441        let back: RunState = serde_json::from_value(value).unwrap();
4442        assert!(back.jobs.is_empty());
4443        assert_eq!(back.schema, SCHEMA);
4444    }
4445
4446    #[test]
4447    fn ensure_can_delete_guards_live_and_unfolded_runs() {
4448        let mut s = state();
4449        // 1. A daemon is working on it right now.
4450        s.status = RunStatus::Prep;
4451        let err = s.ensure_can_delete(true).unwrap_err().to_string();
4452        assert!(err.contains("live daemon"), "{err}");
4453
4454        // 2. The same unfinished run with no daemon behind it is a leftover
4455        // from a killed process, and deletable. Without this an interrupted
4456        // run could never be removed: its status stays `prep` forever.
4457        assert!(s.ensure_can_delete(false).is_ok());
4458
4459        // 3. Unfolded candidates are refused either way — that is the guard
4460        // that stops a delete from discarding a worktree.
4461        s.status = RunStatus::Merged;
4462        s.candidates.push(Candidate {
4463            index: 0,
4464            label: 'A',
4465            agent: "a".to_owned(),
4466            branch: "b".to_owned(),
4467            worktree: PathBuf::from("/w"),
4468            summary: String::new(),
4469            stat: String::new(),
4470            files: 1,
4471            commits: 1,
4472            empty: false,
4473            failed: None,
4474            verified_noop: None,
4475            duration_ms: 0,
4476            folded: false,
4477        });
4478        let err = s.ensure_can_delete(false).unwrap_err().to_string();
4479        assert!(
4480            err.contains("magi fold"),
4481            "error must suggest `magi fold`: {err}"
4482        );
4483
4484        // 4. Folded and nobody working on it.
4485        s.candidates[0].folded = true;
4486        assert!(s.ensure_can_delete(false).is_ok());
4487    }
4488}
4489
4490impl RunState {
4491    /// A seed for a seat that changes agent, distinct on every call.
4492    pub fn next_seat_seed(&mut self) -> u64 {
4493        self.seat_epoch += 1;
4494        self.seed ^ self.seat_epoch.wrapping_mul(0x9E37_79B9_7F4A_7C15)
4495    }
4496}
4497
4498/// What kind of failure ended an agent's turn on a seat, for deciding whether
4499/// the seat is worth handing to the next roster agent.
4500#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4501pub enum FailClass {
4502    /// A CLI rate limit.
4503    Quota,
4504    /// The turn outlived its budget.
4505    Timeout,
4506    /// Any other failure, with the message's shape (`failure_signature`,
4507    /// capped at 120 characters).
4508    Other(String),
4509}
4510
4511/// One reviewer seat's record across review rounds, so a round does not ask
4512/// an agent that already failed the seat while another one is answering.
4513///
4514/// `failed` is a *priority* set, not a bound: the per-round `tried` set in
4515/// `ask_json_wave` starts empty every round, so an agent that answered is
4516/// never locked out. A failed id is only asked again once nothing else on the
4517/// roster is left (once per round, and the rounds are `review_rounds`).
4518#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
4519pub struct SeatHistory {
4520    /// Roster ids that failed this seat and have not answered it since.
4521    #[serde(default)]
4522    pub failed: BTreeSet<String>,
4523    /// The agent that last answered this seat.
4524    #[serde(default)]
4525    pub last_ok: Option<String>,
4526    /// The class of the seat's most recent failure; cleared by an answer.
4527    #[serde(default)]
4528    pub last_fail: Option<FailClass>,
4529}