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