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