Skip to main content

magi/
run.rs

1//! Run state: what happened, where it is stored, and how a run is resumed.
2//!
3//! Every node writes its result into [`RunState`] and the whole struct is
4//! flushed to `run.json` before the next node starts. That is what makes a run
5//! resumable: a competition can take an hour, and dying in review round four
6//! should not throw away three implementations, nine judge reads and a
7//! deliberation.
8//!
9//! Patches and raw agent transcripts are *not* in `run.json` — they live beside
10//! it under `artifacts/`, so the state file stays small enough to read by hand.
11use std::collections::BTreeMap;
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};
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.
68pub const SCHEMA: u32 = 6;
69
70/// Where a run got to.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(rename_all = "snake_case")]
73pub enum RunStatus {
74    /// Worktrees being prepared.
75    Prep,
76    /// Candidates being implemented.
77    Implementing,
78    /// Judges ranking blind.
79    Judging,
80    /// Judges deliberating after a split.
81    Deliberating,
82    /// Final votes being collected privately.
83    Voting,
84    /// Winner in the review + verification loop.
85    Reviewing,
86    /// Gate commands running.
87    Gating,
88    /// Inside [`crate::land`]'s post-merge loop: watching CI, running a fix
89    /// round, rebasing onto a moved base, or waiting on the owner's merge
90    /// approval. A run parked here while an approval is outstanding has
91    /// handed its daemon slot back — see [`crate::daemon`] — and resumes
92    /// through exactly this status, not a fresh competition.
93    Landing,
94    /// Winner merged.
95    Merged,
96    /// Winner passed the gate; merge was not requested.
97    Ready,
98    /// The judgement did not gather enough judges (e.g. rate limiting took out
99    /// seats), so the verdict is not trustworthy. The run stopped and kept its
100    /// work so it can be resumed or folded — it must never be confused with a
101    /// healthy `Ready`.
102    Stalled,
103    /// Review rounds exhausted with findings still open, or the gate failed.
104    Blocked,
105    /// The graph could not complete.
106    Failed,
107}
108
109impl RunStatus {
110    /// Is this a terminal state?
111    pub fn done(self) -> bool {
112        matches!(
113            self,
114            Self::Merged | Self::Ready | Self::Stalled | Self::Blocked | Self::Failed
115        )
116    }
117
118    /// The name this status is written and shown under, matching the
119    /// `snake_case` serde spelling so a log line, an error message and the
120    /// JSON a phone reads all say the same word.
121    pub fn as_str(self) -> &'static str {
122        match self {
123            Self::Prep => "prep",
124            Self::Implementing => "implementing",
125            Self::Judging => "judging",
126            Self::Deliberating => "deliberating",
127            Self::Voting => "voting",
128            Self::Reviewing => "reviewing",
129            Self::Gating => "gating",
130            Self::Landing => "landing",
131            Self::Merged => "merged",
132            Self::Ready => "ready",
133            Self::Stalled => "stalled",
134            Self::Blocked => "blocked",
135            Self::Failed => "failed",
136        }
137    }
138
139    /// Can this run be carried on from where it stopped?
140    ///
141    /// Everything except a finished run and a failed one. `execute` skips
142    /// nodes already recorded, so re-entering is cheap wherever the run
143    /// stopped, and the alternative is always a fresh competition against
144    /// work that already exists.
145    ///
146    /// - `Stalled` re-asks only the seats whose absence collapsed the panel,
147    ///   keeping the candidates that were already paid for.
148    /// - `Blocked` re-enters the review loop against a branch that is built.
149    /// - **A non-terminal status** means the run was interrupted: a parked
150    ///   run waiting for its upgrade, or one whose daemon was killed. This
151    ///   used to be excluded, which left run 4043 stuck at `reviewing` with
152    ///   the deck telling the operator it could not be resumed - the one
153    ///   state where resuming is the only sensible answer.
154    ///
155    /// `Failed` does not qualify: the graph could not complete and there is
156    /// no established point to continue from. Nor does a finished run, whose
157    /// answer is a new competition.
158    ///
159    /// Whether anything is *already* driving the run is a separate question,
160    /// answered by `daemon::is_working_on` at the callers that need it.
161    pub fn resumable(self) -> bool {
162        !matches!(self, Self::Merged | Self::Ready | Self::Failed)
163    }
164}
165
166/// One candidate implementation.
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct Candidate {
169    /// Position in the implementer list.
170    pub index: usize,
171    /// Blind label as presented to judges.
172    pub label: char,
173    /// Which agent wrote it. Recorded for the stats tables, never shown to a
174    /// judge.
175    pub agent: String,
176    /// Branch, named after the label so judges can inspect it without learning
177    /// the author.
178    pub branch: String,
179    /// Worktree path.
180    pub worktree: PathBuf,
181    /// Sanitized author summary.
182    #[serde(default)]
183    pub summary: String,
184    /// `git diff --stat`.
185    #[serde(default)]
186    pub stat: String,
187    /// Files touched.
188    #[serde(default)]
189    pub files: usize,
190    /// Commits ahead of base.
191    #[serde(default)]
192    pub commits: usize,
193    /// True when the agent produced no change at all.
194    #[serde(default)]
195    pub empty: bool,
196    /// Why this candidate is not in the running.
197    #[serde(default)]
198    pub failed: Option<String>,
199    /// Wall-clock time for the implementation.
200    #[serde(default)]
201    pub duration_ms: u64,
202    /// Whether the worktree has been folded away.
203    #[serde(default)]
204    pub folded: bool,
205}
206
207impl Candidate {
208    /// Can this candidate be judged?
209    pub fn viable(&self) -> bool {
210        self.failed.is_none() && !self.empty
211    }
212}
213
214/// One judge's independent ranking.
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct Judgement {
217    /// Judge seat number, 1-based.
218    pub judge: usize,
219    /// Seat key.
220    pub seat: String,
221    /// Agent occupying the seat.
222    pub agent: String,
223    /// Best-first labels.
224    #[serde(default)]
225    pub ranking: Vec<char>,
226    /// Per-label justification.
227    #[serde(default)]
228    pub reasons: BTreeMap<String, String>,
229    /// Self-reported confidence.
230    #[serde(default)]
231    pub confidence: Option<u8>,
232    /// Order the candidates were presented in, as candidate indices.
233    #[serde(default)]
234    pub order: Vec<usize>,
235    /// Why this judge has no ranking.
236    #[serde(default)]
237    pub failed: Option<String>,
238    /// Wall-clock time.
239    #[serde(default)]
240    pub duration_ms: u64,
241}
242
243/// One judge's turn in a deliberation round.
244#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct DeliberationTurn {
246    /// Judge seat number, 1-based.
247    pub judge: usize,
248    /// Agent occupying the seat.
249    pub agent: String,
250    /// The argument, as written.
251    pub body: String,
252    /// Where the judge stood at the end of the turn.
253    #[serde(default)]
254    pub tentative: Option<char>,
255}
256
257/// A deliberation round.
258#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct DeliberationRound {
260    /// 1-based round number.
261    pub round: usize,
262    /// Turns, in the order they were taken.
263    pub turns: Vec<DeliberationTurn>,
264}
265
266/// A final vote, collected privately.
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct VoteRecord {
269    /// Judge seat number, 1-based.
270    pub judge: usize,
271    /// Agent occupying the seat.
272    pub agent: String,
273    /// The vote.
274    #[serde(default)]
275    pub vote: Option<char>,
276    /// Why.
277    #[serde(default)]
278    pub reason: String,
279    /// Did this judge move from its initial first choice?
280    #[serde(default)]
281    pub changed: bool,
282}
283
284/// A seat that was taken out by a CLI rate limit / quota, recorded so a run
285/// whose panel collapsed does not masquerade as a healthy one.
286#[derive(Debug, Clone, Serialize, Deserialize)]
287pub struct QuotaLoss {
288    /// Seat key, e.g. `judge-1` or `review-2`.
289    pub seat: String,
290    /// Node that was running, e.g. `judge`, `vote`, `review`.
291    pub node: String,
292    /// When the CLI reported the limit.
293    pub at: Timestamp,
294    /// Reset hint if the CLI printed one, free text.
295    #[serde(default)]
296    pub reset: Option<String>,
297}
298
299/// The mechanical count.
300#[derive(Debug, Clone, Serialize, Deserialize)]
301pub struct Tally {
302    /// First-choice votes per label.
303    pub first_choice: BTreeMap<char, usize>,
304    /// Borda points from the initial rankings, used only to break a tie.
305    pub borda: BTreeMap<char, usize>,
306    /// The winning label.
307    pub winner: char,
308    /// How many judges produced a usable ranking. A panel of one is not a
309    /// consensus and must not be reported as a split.
310    #[serde(default)]
311    pub rankings: usize,
312    /// Did every judge's *initial* first choice agree?
313    pub unanimous_initial: bool,
314    /// Was deliberation run?
315    pub deliberated: bool,
316    /// Judges who moved between their initial ranking and their final vote.
317    pub changed_votes: usize,
318    /// Did the final votes agree?
319    pub unanimous_final: bool,
320    /// How the tie was broken, when it had to be.
321    #[serde(default)]
322    pub tie_break: Option<String>,
323    /// Configured judge count — the size of the full panel. `0` when no
324    /// panel was asked (see `uncontested`), not the roster size a panel that
325    /// never sat would have had.
326    #[serde(default)]
327    pub judges: usize,
328    /// Judges who actually contributed to the decision (not taken out by a
329    /// rate limit and producing a usable rank or vote).
330    #[serde(default)]
331    pub present: usize,
332    /// How many judges are required for a trustworthy verdict. Chosen as a
333    /// strict majority (`judges / 2 + 1`): a verdict backed by a minority must
334    /// never be presented as a healthy one, while a bare majority is still
335    /// real signal. A one-candidate run needs no quorum.
336    #[serde(default)]
337    pub quorum: usize,
338    /// `present >= quorum`, or no quorum was required.
339    #[serde(default)]
340    pub met_quorum: bool,
341    /// Why no panel was asked, when none was: a single viable candidate, or
342    /// a review-only run that never competed. `None` when judges actually
343    /// ranked and voted — including when too few of them survived to reach
344    /// quorum, which is a collapse and must keep reading as one.
345    #[serde(default)]
346    pub uncontested: Option<String>,
347}
348
349/// One reviewer's report in a round.
350#[derive(Debug, Clone, Serialize, Deserialize)]
351pub struct ReviewRecord {
352    /// Reviewer seat number, 1-based.
353    pub reviewer: usize,
354    /// Agent occupying the seat.
355    pub agent: String,
356    /// Reviewer prose.
357    #[serde(default)]
358    pub summary: String,
359    /// Findings, with magi-assigned ids.
360    #[serde(default)]
361    pub findings: Vec<Finding>,
362    /// This seat's initial vote. `None` on a record predating votes, exactly
363    /// like a round that genuinely had none cast — never a stand-in for a
364    /// vote that was lost.
365    #[serde(default)]
366    pub vote: Option<ReviewVote>,
367    /// Why this reviewer produced nothing.
368    #[serde(default)]
369    pub failed: Option<String>,
370    /// Wall-clock time.
371    #[serde(default)]
372    pub duration_ms: u64,
373}
374
375/// One seat's revote during a round's reconsideration (see
376/// [`ReviewRound::reconsideration`]).
377#[derive(Debug, Clone, Serialize, Deserialize)]
378pub struct ReviewRevoteRecord {
379    /// Reviewer seat number, 1-based.
380    pub reviewer: usize,
381    /// Agent occupying the seat.
382    pub agent: String,
383    /// The revote. `None` when the seat did not answer.
384    #[serde(default)]
385    pub vote: Option<ReviewVote>,
386    /// Why.
387    #[serde(default)]
388    pub reason: String,
389    /// Why this seat produced no revote.
390    #[serde(default)]
391    pub failed: Option<String>,
392}
393
394/// The fixer's response to a round.
395#[derive(Debug, Clone, Serialize, Deserialize)]
396pub struct FixRecord {
397    /// Agent that applied the fixes.
398    pub agent: String,
399    /// Finding ids acted on.
400    #[serde(default)]
401    pub addressed: Vec<String>,
402    /// Findings declined, with reasons.
403    #[serde(default)]
404    pub rejected: Vec<Rejection>,
405    /// What changed.
406    #[serde(default)]
407    pub notes: String,
408    /// Did the fix produce a commit?
409    #[serde(default)]
410    pub committed: bool,
411    /// Why the fix step produced nothing.
412    #[serde(default)]
413    pub failed: Option<String>,
414    /// Wall-clock time.
415    #[serde(default)]
416    pub duration_ms: u64,
417}
418
419/// Outcome of one shell command.
420#[derive(Debug, Clone, Serialize, Deserialize)]
421pub struct CommandOutcome {
422    /// The command, as configured.
423    pub command: String,
424    /// Exit code, `None` on timeout or signal.
425    pub code: Option<i32>,
426    /// Tail of the combined output, for the report and the fix prompt.
427    #[serde(default)]
428    pub output_tail: String,
429    /// Wall-clock time.
430    #[serde(default)]
431    pub duration_ms: u64,
432}
433
434/// Substrings that mark a Cargo/rustc/link failure: the toolchain could not
435/// produce a binary to run at all, as opposed to producing one that ran and
436/// failed. A Windows link race against a shared `CARGO_TARGET_DIR` (see
437/// AGENTS.md, "Running magi on magi") looks exactly like a red command
438/// otherwise, and a run has concluded `Blocked` on nothing but that race.
439const BUILD_FAILURE_MARKERS: &[&str] = &[
440    "error: could not compile",
441    "error: linking with",
442    "LINK : fatal error",
443    "fatal error LNK",
444];
445
446impl CommandOutcome {
447    /// Did it pass?
448    pub fn ok(&self) -> bool {
449        self.code == Some(0)
450    }
451
452    /// Did this command fail because the code could not be built or linked,
453    /// rather than because it ran and produced a wrong result? A failure here
454    /// is not a verdict on the patch under review.
455    pub fn build_failed(&self) -> bool {
456        !self.ok()
457            && BUILD_FAILURE_MARKERS
458                .iter()
459                .any(|m| self.output_tail.contains(m))
460    }
461}
462
463/// One review + verify + fix round.
464#[derive(Debug, Clone, Serialize, Deserialize)]
465pub struct ReviewRound {
466    /// 1-based round number.
467    pub round: usize,
468    /// Commit the round reviewed.
469    pub head: String,
470    /// Commit actually checked by a catch-up e2e, when it differs from the
471    /// reviewed commit. Kept separate so reports never attribute a command
472    /// result to a review target the command did not inspect.
473    #[serde(default)]
474    pub verified_head: Option<String>,
475    /// Reviewer reports.
476    pub reviews: Vec<ReviewRecord>,
477    /// E2E command outcomes for this round.
478    #[serde(default)]
479    pub e2e: Vec<CommandOutcome>,
480    /// True when the first verify attempt this round could not build or
481    /// link, and `e2e` above holds a second attempt run before concluding.
482    /// A run must never be decided on a red it could not tell from an
483    /// unrelated build race.
484    #[serde(default)]
485    pub verify_retried: bool,
486    /// True when `e2e` was intentionally left empty this round: the round
487    /// already had blocking findings and another round was available, so
488    /// `graph::Runner::review_loop` sent the fixer straight at them instead
489    /// of spending a full verify run on a head it already knew would need
490    /// another fix. Distinct from an `e2e` that is simply empty because
491    /// `verify.e2e` has no commands configured — `e2e.is_empty()` alone
492    /// cannot tell those apart, and conflating them is exactly how a
493    /// deferred check would get painted green. A record written before this
494    /// field existed defaults to `false`, which is the truth for it: every
495    /// round used to run e2e unconditionally.
496    #[serde(default)]
497    pub e2e_deferred: bool,
498    /// Why `e2e` was deferred, set only when [`Self::e2e_deferred`] is true.
499    /// Carried to the fixer's prompt and shown in the report so "deferred"
500    /// never reads as silence.
501    #[serde(default)]
502    pub e2e_defer_reason: Option<String>,
503    /// Fixer response, absent when the round was already clean.
504    #[serde(default)]
505    pub fix: Option<FixRecord>,
506    /// Findings that hold the merge.
507    #[serde(default)]
508    pub blocking: usize,
509    /// Reviewer seats that answered (did not time out, crash, or return
510    /// something unparsable).
511    #[serde(default)]
512    pub answered: usize,
513    /// Reviewer seats the round expected an answer from — normally
514    /// `graph.reviewers`, but recorded per round so a config change between
515    /// runs never has to be inferred from history.
516    #[serde(default)]
517    pub expected: usize,
518    /// Round ended with no blocking findings and green verification, judged
519    /// against the seats that answered. See [`Self::incomplete`] for whether
520    /// that verdict is missing input.
521    #[serde(default)]
522    pub clean: bool,
523    /// Did the tree actually move against `base` this round, comparing the
524    /// diff after the fix to the diff the reviewers saw at the start of the
525    /// round?
526    ///
527    /// Never derived from the fixer's own `addressed`/`rejected` count: that
528    /// self-report has been caught lying twice on this workload (runs `b455`
529    /// and `6218`, both of which committed a real, substantial diff while
530    /// reporting `0 addressed`). `git` does not lie about whether the tree
531    /// changed, so this is what `graph::Runner::review_loop` counts rounds of
532    /// no progress against. Absent on a round with no fix attempt (already
533    /// clean, or the round the budget ran out on), where it defaults to
534    /// `false` and is not consulted.
535    #[serde(default)]
536    pub progressed: bool,
537    /// Did the seats' initial votes ([`ReviewRecord::vote`]) disagree?
538    #[serde(default)]
539    pub vote_split: bool,
540    /// One round of revoting, run only when `vote_split`: each seat that cast
541    /// an initial vote reads every seat's findings and votes, then revotes.
542    /// Empty when the initial votes already agreed, the same as a solo
543    /// candidate leaving `deliberation` empty.
544    #[serde(default)]
545    pub reconsideration: Vec<ReviewRevoteRecord>,
546    /// The round's verdict: the most cautious vote among the seats that
547    /// answered, using each seat's revote where reconsideration ran and its
548    /// initial vote otherwise. `None` when no seat produced a usable vote —
549    /// including every record written before votes existed, which is the
550    /// truth for those rounds, not a gap in this one.
551    #[serde(default)]
552    pub verdict: Option<ReviewVote>,
553}
554
555impl ReviewRound {
556    /// Did at least one reviewer seat fail to answer this round?
557    pub fn incomplete(&self) -> bool {
558        self.answered < self.expected
559    }
560
561    /// The honest state of this round's e2e leg.
562    ///
563    /// Never derive this from `e2e.is_empty()` alone anywhere else in the
564    /// codebase — `NotConfigured` and `Deferred` both leave it empty, and
565    /// only this method (backed by [`Self::e2e_deferred`]) tells them apart.
566    pub fn e2e_status(&self) -> E2eStatus {
567        if !self.e2e.is_empty() {
568            if self.e2e.iter().all(CommandOutcome::ok) {
569                E2eStatus::Passed
570            } else {
571                E2eStatus::Failed
572            }
573        } else if self.e2e_deferred {
574            E2eStatus::Deferred
575        } else {
576            E2eStatus::NotConfigured
577        }
578    }
579}
580
581/// The honest state of a round's e2e leg. See [`ReviewRound::e2e_status`].
582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
583pub enum E2eStatus {
584    /// `verify.e2e` has no commands configured.
585    NotConfigured,
586    /// Skipped this round on purpose: blocking findings already required a
587    /// fix, so the round went straight to the fixer instead of spending a
588    /// full verify run on a head it already knew would need another pass.
589    Deferred,
590    /// Ran, and every command exited 0.
591    Passed,
592    /// Ran, and at least one command did not exit 0.
593    Failed,
594}
595
596/// What happened to the winning branch.
597#[derive(Debug, Clone, Serialize, Deserialize)]
598pub struct MergeOutcome {
599    /// Requested mode.
600    pub mode: MergeMode,
601    /// Did it land?
602    pub ok: bool,
603    /// Command output, or the command the operator should run.
604    #[serde(default)]
605    pub detail: String,
606}
607
608/// A seat currently mid-answer: a prompt was sent and no reply has landed yet.
609///
610/// This is not the whole story of "is it alive" — a daemon killed mid-wave
611/// leaves its last wave's entries here forever, since nothing ran to clear
612/// them. A reader must cross-check a live daemon's heartbeat
613/// (`daemon::is_working_on`) before trusting one of these as "still running"
614/// rather than "abandoned". [`RunState::clear_active`] is what keeps that
615/// leftover from surviving into the next attempt at this run: `execute` calls
616/// it before doing anything else, so a resumed run never carries a stale
617/// entry into its own report before the next wave repopulates it.
618///
619/// Deliberately carries no agent id: an implementer's agent is no secret, but
620/// a judge or reviewer seat is blind (`SeatState::key` is keyed by seat, never
621/// agent, for exactly this reason), and this struct has no way to tell which
622/// kind of seat it describes. The seat key alone — already in the map this
623/// lives under — is what every caller needs to say which seat is running.
624#[derive(Debug, Clone, Serialize, Deserialize)]
625pub struct ActiveSeat {
626    /// Node the seat is answering for, e.g. `implement`, `judge`, `review`.
627    pub node: String,
628    /// When this attempt was sent.
629    pub started_at: Timestamp,
630    /// The CLI's wall-clock budget for this attempt.
631    pub timeout_secs: u64,
632    /// 0 for the first ask, N for the Nth nudge or resume.
633    #[serde(default)]
634    pub attempt: usize,
635}
636
637impl ActiveSeat {
638    /// Seconds since this attempt was sent.
639    #[must_use]
640    pub fn elapsed_secs(&self, now: Timestamp) -> i64 {
641        (now.as_second() - self.started_at.as_second()).max(0)
642    }
643
644    /// Seconds left before this attempt's own timeout fires, floored at zero
645    /// rather than going negative once the CLI has overrun its budget.
646    #[must_use]
647    pub fn remaining_secs(&self, now: Timestamp) -> i64 {
648        (self.timeout_secs as i64 - self.elapsed_secs(now)).max(0)
649    }
650}
651
652/// A timestamped note about a node.
653#[derive(Debug, Clone, Serialize, Deserialize)]
654pub struct Event {
655    /// When.
656    pub at: Timestamp,
657    /// Node name.
658    pub node: String,
659    /// What happened.
660    pub message: String,
661}
662
663/// How far the winner's tree trailed the landing base, last time it was
664/// checked, and what came of trying to close that gap.
665///
666/// Set by `graph::Runner::sync_to_base`, which runs before the review loop and
667/// again before the gate: verifying against a tree that does not yet contain
668/// the base's tip answers "green on the commit this run branched from", not
669/// "green on what is about to land", and a merge on that answer can revert
670/// whatever landed elsewhere while the run was thinking.
671#[derive(Debug, Clone, Serialize, Deserialize)]
672pub struct BaseSync {
673    /// `<remote>/<base>` tip the tree was last checked against.
674    pub tip: String,
675    /// Commits `tip` was ahead of the tree at that check, before any rebase
676    /// this round tried to close the gap. Zero means the tree already
677    /// contained `tip`.
678    pub behind: usize,
679    /// Rebase attempts spent so far this run, bounded by
680    /// `graph::BASE_SYNC_ROUNDS`.
681    pub attempts: usize,
682    /// What git said, if the most recent rebase attempt conflicted or could
683    /// not be pushed. `Some` here is what makes a `Blocked` run read as
684    /// "stopped on the base, not on review or the gate" - the rebase is not
685    /// retried again while this is set; a person has to look.
686    #[serde(default)]
687    pub conflict: Option<String>,
688}
689
690/// What the land loop saw last time it looked at the pull request.
691///
692/// Strings for `state` and `checks` on purpose: they are `gh`'s vocabulary, and
693/// pinning them into an enum here would mean a new GitHub check conclusion
694/// turns a readable status into a deserialisation error on a run someone is
695/// trying to look at.
696#[derive(Debug, Clone, Serialize, Deserialize)]
697pub struct PrRecord {
698    /// Pull request url.
699    pub url: String,
700    /// Pull request number.
701    pub number: u64,
702    /// `open`, `merged` or `closed`.
703    pub state: String,
704    /// `pending`, `green`, `red` or `unknown`.
705    pub checks: String,
706    /// Land round, 1-based, or 0 before the first fix.
707    pub round: usize,
708    /// Land round budget.
709    pub rounds: usize,
710}
711
712/// The whole run.
713#[derive(Debug, Clone, Serialize, Deserialize)]
714pub struct RunState {
715    /// On-disk format version.
716    pub schema: u32,
717    /// Run id, e.g. `20260830-153012-a1b2`.
718    pub id: String,
719    /// Repository the run operates on.
720    pub repo: PathBuf,
721    /// Branch the run started from.
722    pub base_branch: String,
723    /// Commit the run started from.
724    pub base_commit: String,
725    /// The task, verbatim.
726    pub instruction: String,
727    /// When the run was created.
728    pub created_at: Timestamp,
729    /// Last state flush.
730    pub updated_at: Timestamp,
731    /// Current status.
732    pub status: RunStatus,
733    /// Seed for labels and session ids.
734    pub seed: u64,
735    /// Config snapshot, so a resumed run behaves like the original.
736    pub config: Config,
737    /// Did this run take a reference on `extensions.worktreeConfig` being on
738    /// (see [`crate::git::acquire_worktree_config`])? If so, cleanup releases
739    /// it - which only actually turns the setting back off once every other
740    /// run sharing this repository has released its own reference too.
741    #[serde(default)]
742    pub enabled_worktree_config: bool,
743    /// Candidates.
744    #[serde(default)]
745    pub candidates: Vec<Candidate>,
746    /// Initial blind rankings.
747    #[serde(default)]
748    pub judgements: Vec<Judgement>,
749    /// `judge` decided a solo candidate needs no panel and only logged it.
750    ///
751    /// `judgements` stays empty in that case — nothing to distinguish from
752    /// "not yet judged" — so this is the record that makes the skip
753    /// idempotent: without it, every reentry re-ran `judge`, re-logged the
754    /// same event, and rewrote `status` to `Judging` over whatever a later
755    /// node had already concluded.
756    #[serde(default)]
757    pub judge_skipped: bool,
758    /// Deliberation, if it happened.
759    #[serde(default)]
760    pub deliberation: Vec<DeliberationRound>,
761    /// Private final votes.
762    #[serde(default)]
763    pub votes: Vec<VoteRecord>,
764    /// The count.
765    #[serde(default)]
766    pub tally: Option<Tally>,
767    /// Review rounds.
768    #[serde(default)]
769    pub reviews: Vec<ReviewRound>,
770    /// Final gate.
771    #[serde(default)]
772    pub gate: Vec<CommandOutcome>,
773    /// Merge outcome.
774    #[serde(default)]
775    pub merge: Option<MergeOutcome>,
776    /// Vendor tokens seen in judged material.
777    #[serde(default)]
778    pub leaks: Vec<Leak>,
779    /// Seats lost to a CLI rate limit / quota, in the order they hit.
780    #[serde(default)]
781    pub quota: Vec<QuotaLoss>,
782    /// Parked at a node boundary, waiting to be resumed.
783    ///
784    /// A run that is neither finished nor being worked on is otherwise
785    /// indistinguishable from one whose daemon was killed, and the two want
786    /// opposite things from an operator: the first is expected to be resumed,
787    /// the second is a leftover. Cleared by the resume that carries it on.
788    #[serde(default)]
789    pub parked: bool,
790    /// Per-seat conversation state.
791    #[serde(default)]
792    pub seats: BTreeMap<String, SeatState>,
793    /// Seats currently mid-answer, keyed by seat.
794    ///
795    /// An entry exists from the moment a prompt is sent until a reply (of any
796    /// kind — success, failure, quota, drop) comes back, so its keys are
797    /// exactly "who hasn't answered yet" for whichever node populated it. See
798    /// [`ActiveSeat`] for why a reader still has to check a live daemon
799    /// before trusting one of these as "running" rather than "abandoned".
800    #[serde(default)]
801    pub active: BTreeMap<String, ActiveSeat>,
802    /// Last observation of the winner's pull request, when a land loop ran.
803    ///
804    /// Persisted rather than derived from the event log because the phone asks
805    /// two questions about a run that has opened a PR - how are its checks and
806    /// which round is it on - and parsing prose out of events to answer them
807    /// would break the first time an event message was reworded.
808    #[serde(default)]
809    pub pr: Option<PrRecord>,
810    /// The last look at how far the winner's tree trailed the landing base,
811    /// and the rebase(s) tried to close that gap. `None` until the tree has a
812    /// winner to check.
813    #[serde(default)]
814    pub base_sync: Option<BaseSync>,
815    /// Node log.
816    #[serde(default)]
817    pub events: Vec<Event>,
818}
819
820impl RunState {
821    /// A fresh run.
822    pub fn new(
823        repo: PathBuf,
824        base_branch: String,
825        base_commit: String,
826        instruction: String,
827        config: Config,
828    ) -> Self {
829        let now = Timestamp::now();
830        let seed = config.blind.seed.unwrap_or_else(crate::rng::entropy);
831        Self {
832            schema: SCHEMA,
833            id: new_id(),
834            repo,
835            base_branch,
836            base_commit,
837            instruction,
838            created_at: now,
839            updated_at: now,
840            status: RunStatus::Prep,
841            seed,
842            config,
843            enabled_worktree_config: false,
844            candidates: Vec::new(),
845            judgements: Vec::new(),
846            judge_skipped: false,
847            deliberation: Vec::new(),
848            votes: Vec::new(),
849            tally: None,
850            reviews: Vec::new(),
851            gate: Vec::new(),
852            merge: None,
853            leaks: Vec::new(),
854            quota: Vec::new(),
855            parked: false,
856            seats: BTreeMap::new(),
857            active: BTreeMap::new(),
858            pr: None,
859            base_sync: None,
860            events: Vec::new(),
861        }
862    }
863
864    /// Directory holding this run's state and artifacts.
865    pub fn dir(&self) -> PathBuf {
866        run_dir(&self.id)
867    }
868
869    /// Short form used in branch names and reports.
870    pub fn short(&self) -> &str {
871        short_of(&self.id)
872    }
873
874    /// Branch name for a label.
875    pub fn branch_for(&self, label: char) -> String {
876        format!("magi/{}/{}", self.short(), label)
877    }
878
879    /// Root of this run's worktrees.
880    pub fn worktree_root(&self) -> PathBuf {
881        self.config
882            .graph
883            .worktree_root
884            .clone()
885            .unwrap_or_else(default_worktree_root)
886            .join(self.short())
887    }
888
889    /// Note something in the run log and on the tracing stream.
890    pub fn event(&mut self, node: &str, message: impl Into<String>) {
891        let message = message.into();
892        tracing::info!(node, "{message}");
893        self.events.push(Event {
894            at: Timestamp::now(),
895            node: node.to_owned(),
896            message,
897        });
898    }
899
900    /// Record that `seat` was just sent a prompt for `node`, with the given
901    /// wall-clock budget. `attempt` is 0 for the first ask and N for the Nth
902    /// nudge or resume, purely for display — it does not change how the seat
903    /// is treated.
904    pub fn seat_started(
905        &mut self,
906        node: &str,
907        seat: &str,
908        timeout: std::time::Duration,
909        attempt: usize,
910    ) {
911        self.active.insert(
912            seat.to_owned(),
913            ActiveSeat {
914                node: node.to_owned(),
915                started_at: Timestamp::now(),
916                timeout_secs: timeout.as_secs(),
917                attempt,
918            },
919        );
920    }
921
922    /// Record that `seat` has answered, whatever the answer was.
923    pub fn seat_finished(&mut self, seat: &str) {
924        self.active.remove(seat);
925    }
926
927    /// Drop every seat this state still lists as answering, reporting whether
928    /// anything was dropped.
929    ///
930    /// Called first thing in `execute`, on every entry — fresh, resumed, or
931    /// recovering a stall — because an entry here only means something while
932    /// the process that wrote it is still asking that seat something. A
933    /// process killed mid-wave leaves its last batch of seats here with
934    /// nobody left to clear them, and the next process to touch this run must
935    /// not let that leftover read as "still going" before it has asked
936    /// anyone anything.
937    pub fn clear_active(&mut self) -> bool {
938        if self.active.is_empty() {
939            return false;
940        }
941        self.active.clear();
942        true
943    }
944
945    /// Does every seat this run still lists as [`Self::active`] sit past its
946    /// own [`ActiveSeat::timeout_secs`]? `false` when nothing is active at
947    /// all — an empty map is not evidence of anything overrunning.
948    ///
949    /// This alone is not proof the run is dead: a seat's own attempt can
950    /// legitimately run a little past its budget while the process driving it
951    /// is still tearing the attempt down. Every caller pairs this with its own
952    /// `!live` reading (`daemon::is_working_on`) before treating the run as
953    /// abandoned — this module cannot check that itself without depending on
954    /// `crate::daemon`, and callers already have to ask that question anyway.
955    #[must_use]
956    pub fn active_all_overrun(&self, now: Timestamp) -> bool {
957        !self.active.is_empty()
958            && self
959                .active
960                .values()
961                .all(|a| a.elapsed_secs(now) > a.timeout_secs as i64)
962    }
963
964    /// Clear every seat this run still lists as active and fail it, unless it
965    /// had already reached a terminal status some other way.
966    ///
967    /// Callers must already have proven this run is dead — [`Self::active_all_overrun`]
968    /// plus their own `!live` reading — before calling this; it does not
969    /// check either itself. Unlike [`Self::clear_active`] (dropping a resumed
970    /// run's own stale wave before repopulating it, called unconditionally at
971    /// the top of every `execute()`), this is a verdict: a run left this way
972    /// has nothing left to repopulate the wave, ever, and must stop reading as
973    /// `implementing` (or whichever node) forever.
974    pub fn abandon(&mut self, by: &str) {
975        let seats: Vec<String> = self.active.keys().cloned().collect();
976        self.clear_active();
977        if !self.status.done() {
978            self.status = RunStatus::Failed;
979        }
980        self.event(
981            by,
982            format!(
983                "abandoned: seat(s) {} left behind by a killed process, past their own \
984                 timeout with no live daemon claiming this run",
985                seats.join(", ")
986            ),
987        );
988    }
989
990    /// Flush to `run.json`, atomically, under the process-global [`home`].
991    pub fn save(&mut self) -> Result<()> {
992        let home = home();
993        self.save_under(&home)
994    }
995
996    /// [`Self::save`], rooted at an explicit `home` instead of the
997    /// process-global one.
998    ///
999    /// For a caller that was already handed its own `home` explicitly — a
1000    /// housekeeping pass, mainly, for the same reason `Queue::at` and the
1001    /// daemon status path are parameters rather than resolved here (see
1002    /// `daemon::drive`'s own doc) — falling through to the global would write
1003    /// back through whichever directory some *other* process or test pinned
1004    /// into that `OnceLock` first, not the one this call was actually handed.
1005    pub fn save_under(&mut self, home: &Path) -> Result<()> {
1006        self.updated_at = Timestamp::now();
1007        let dir = home.join("runs").join(&self.id);
1008        std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
1009        let body = serde_json::to_string_pretty(self).context("serialize run state")?;
1010        let tmp = dir.join("run.json.tmp");
1011        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1012        std::fs::rename(&tmp, dir.join("run.json")).with_context(|| "replace run.json")?;
1013        Ok(())
1014    }
1015
1016    /// Load a run by id or unambiguous id prefix.
1017    pub fn load(id: &str) -> Result<Self> {
1018        let resolved = resolve_id(id)?;
1019        let path = run_dir(&resolved).join("run.json");
1020        let body =
1021            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
1022        let state: Self =
1023            serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1024        migrate_schema(state)
1025    }
1026}
1027
1028fn migrate_schema(mut state: RunState) -> Result<RunState> {
1029    // Schema 5 predates deferred e2e. Its empty e2e lists therefore mean
1030    // "not configured", never "deferred"; serde's field defaults retain
1031    // exactly that representation while this migration permits resumes.
1032    if state.schema == 5 {
1033        state.schema = SCHEMA;
1034    }
1035    if state.schema != SCHEMA {
1036        bail!(
1037            "run {} was written by a different magi (schema {}, this build \
1038                 speaks {SCHEMA})",
1039            state.id,
1040            state.schema
1041        );
1042    }
1043    Ok(state)
1044}
1045
1046impl RunState {
1047    /// The winning candidate, once the tally has run.
1048    pub fn winner(&self) -> Option<&Candidate> {
1049        let label = self.tally.as_ref()?.winner;
1050        self.candidates.iter().find(|c| c.label == label)
1051    }
1052
1053    /// Candidates eligible for judging.
1054    pub fn viable(&self) -> Vec<&Candidate> {
1055        self.candidates.iter().filter(|c| c.viable()).collect()
1056    }
1057
1058    /// Findings still open when the review loop stopped trying: the last
1059    /// round's, exactly when that round was not clean. Empty on a run that
1060    /// never reviewed, or whose last round was clean.
1061    ///
1062    /// This is the last round's findings regardless of what the fixer claims
1063    /// to have addressed in that same round: a round that stopped the loop
1064    /// (round budget spent, or no tree progress for
1065    /// [`crate::graph::STAGNANT_LIMIT`] rounds) never had a *following* round
1066    /// to confirm the fix actually landed, and the self-reported adoption
1067    /// count is not trusted for that judgement either — see
1068    /// [`ReviewRound::progressed`].
1069    pub fn open_findings(&self) -> Vec<&Finding> {
1070        match self.reviews.last() {
1071            Some(r) if !r.clean => r
1072                .reviews
1073                .iter()
1074                .flat_map(|rec| rec.findings.iter())
1075                .collect(),
1076            _ => Vec::new(),
1077        }
1078    }
1079
1080    /// Did this run reach a mergeable status (`Ready` or `Merged`) with
1081    /// review findings still open?
1082    ///
1083    /// That combination is the point of the review hand-off: the review
1084    /// round budget (or an unproductive round, see [`ReviewRound::progressed`])
1085    /// was spent while gate and e2e stayed green, so the run was handed off
1086    /// rather than blocked — but the findings did not disappear, and whoever
1087    /// reads the result should be told they are still there.
1088    pub fn handed_off_with_open_findings(&self) -> bool {
1089        matches!(self.status, RunStatus::Ready | RunStatus::Merged)
1090            && self.reviews.last().is_some_and(|r| !r.clean)
1091    }
1092
1093    /// Local-time creation stamp for reports.
1094    pub fn created_local(&self) -> String {
1095        self.created_at
1096            .to_zoned(jiff::tz::TimeZone::system())
1097            .strftime("%Y-%m-%d %H:%M:%S")
1098            .to_string()
1099    }
1100
1101    /// Assert that this run is safe to delete.
1102    ///
1103    /// Refuses a run a live daemon is working on, and refuses any run whose
1104    /// candidate worktrees and branches have not been folded away with `magi
1105    /// fold`. The fold requirement is the real protection: it is what makes
1106    /// "delete" mean "remove a record" rather than "throw away a worktree
1107    /// somebody may still be editing".
1108    ///
1109    /// `in_flight` has to come from the caller, because a run's own status
1110    /// cannot answer the question. A daemon killed mid-run leaves its status at
1111    /// `implementing` forever, and a guard that trusted that would make every
1112    /// interrupted run permanently undeletable - the operator's only recourse
1113    /// being to edit `run.json` by hand, which is exactly the sort of thing
1114    /// this command exists to avoid. The queue already treats an orphaned
1115    /// `.lock` from a `SIGKILL`ed daemon the same way; this is that rule for
1116    /// runs.
1117    pub fn ensure_can_delete(&self, in_flight: bool) -> Result<()> {
1118        if in_flight {
1119            bail!(
1120                "run {} is being worked on by a live daemon right now",
1121                self.short()
1122            );
1123        }
1124        if self.candidates.iter().any(|c| !c.folded) {
1125            bail!(
1126                "run {} has unfolded candidates; fold first with `magi fold`",
1127                self.short()
1128            );
1129        }
1130        Ok(())
1131    }
1132}
1133
1134/// The short form of a run id: the trailing block after the last `-`.
1135///
1136/// A free function as well as [`RunState::short`], because callers that have
1137/// only an id - an error message, a daemon status, a route handler - were
1138/// otherwise reimplementing the split, and two spellings of "short id" is one
1139/// rename away from branch names that no longer match their run.
1140pub fn short_of(id: &str) -> &str {
1141    id.split('-').next_back().unwrap_or(id)
1142}
1143
1144/// Where magi keeps its runs.
1145///
1146/// `MAGI_HOME` overrides the default, and [`set_home`] overrides both — which
1147/// is what lets the integration tests drive a whole graph without writing into
1148/// the operator's real history.
1149///
1150/// In a unit test build (`cfg(test)`), falling through to the real
1151/// `<data_local>/magi` is not a fallback worth having: it is exactly how
1152/// three broken fixture runs ended up in the operator's actual history and
1153/// were counted as `unreadable` by the deck. A test that reaches this point
1154/// forgot to call [`set_home`] (or set `MAGI_HOME`) - that is a bug in the
1155/// test, not a case to serve, so it panics instead of writing anywhere.
1156pub fn home() -> PathBuf {
1157    resolve_home(HOME.get().cloned(), std::env::var_os("MAGI_HOME"))
1158}
1159
1160/// The decision `home` makes, taking its two overrides as plain values
1161/// instead of reading the `OnceLock` and the environment itself.
1162///
1163/// Pulled out so the `cfg(test)` panic is asserted directly against a
1164/// `None, None` input, rather than racing every other unit test in the
1165/// binary for who touches the process-global `HOME` first.
1166fn resolve_home(pinned: Option<PathBuf>, magi_home_env: Option<std::ffi::OsString>) -> PathBuf {
1167    if let Some(dir) = pinned {
1168        return dir;
1169    }
1170    if let Some(dir) = magi_home_env {
1171        return PathBuf::from(dir);
1172    }
1173    #[cfg(test)]
1174    {
1175        panic!(
1176            "run::home() was reached in a test without run::set_home() or \
1177             MAGI_HOME; this would write into the operator's real \
1178             <data_local>/magi. Call `run::set_home(temp_dir)` before any \
1179             code path that touches a RunState."
1180        );
1181    }
1182    #[cfg(not(test))]
1183    {
1184        dirs::data_local_dir()
1185            .unwrap_or_else(|| PathBuf::from("."))
1186            .join("magi")
1187    }
1188}
1189
1190/// Pin the run home for this process. The first call wins.
1191pub fn set_home(dir: PathBuf) {
1192    let _ = HOME.set(dir);
1193}
1194
1195static HOME: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
1196
1197/// `<home>/runs`.
1198pub fn runs_root() -> PathBuf {
1199    home().join("runs")
1200}
1201
1202/// The worktree root a run uses when the config sets none: `~/wt/magi`.
1203///
1204/// One definition of the default, so the folder the janitor folds and the
1205/// folder the health view sizes cannot drift apart: a run with no configured
1206/// [`crate::config::Graph::worktree_root`] lays its worktrees exactly here.
1207pub fn default_worktree_root() -> PathBuf {
1208    dirs::home_dir()
1209        .unwrap_or_else(|| PathBuf::from("."))
1210        .join("wt")
1211        .join("magi")
1212}
1213
1214/// Directory for one run id.
1215pub fn run_dir(id: &str) -> PathBuf {
1216    runs_root().join(id)
1217}
1218
1219/// Every run id on disk, newest first.
1220///
1221/// A directory is a run because of its **name**, not because it holds a
1222/// readable `run.json`. A run whose very first save lost the machine's last
1223/// free bytes leaves `<id>/run.json.tmp` and nothing else, and filtering on
1224/// `run.json` made that run invisible everywhere: not in `magi list`, not in
1225/// `runs_unreadable`, not on the phone, so nothing could report it and no
1226/// route could clear it. `88c0` sat like that for two days. Unreadable is
1227/// counted, never hidden - the readers already say why each one cannot be
1228/// read, and `fold_unreadable` is how a record like this leaves.
1229pub fn list_ids() -> Vec<String> {
1230    let mut ids: Vec<String> = std::fs::read_dir(runs_root())
1231        .into_iter()
1232        .flatten()
1233        .flatten()
1234        .filter(|e| e.path().is_dir())
1235        .map(|e| e.file_name().to_string_lossy().into_owned())
1236        .filter(|name| is_run_id(name))
1237        .collect();
1238    // Ids start with a sortable timestamp.
1239    ids.sort_unstable_by(|a, b| b.cmp(a));
1240    ids
1241}
1242
1243/// Does `name` have the shape [`new_id`] mints: `YYYYMMDD-HHMMSS-xxxx`?
1244///
1245/// The test for "this directory is a run", so a stray folder under
1246/// `<home>/runs` is not reported as a broken run.
1247///
1248/// The tag is checked for length and for being alphanumeric, not for being
1249/// hex: real ids are hex, but fixtures across this crate name runs
1250/// `...-dead` / `...-gone` / `...-once`, and a predicate that disowned those
1251/// would be asserting the fixtures' spelling rather than the shape.
1252pub fn is_run_id(name: &str) -> bool {
1253    let mut parts = name.split('-');
1254    let (Some(day), Some(time), Some(tag), None) =
1255        (parts.next(), parts.next(), parts.next(), parts.next())
1256    else {
1257        return false;
1258    };
1259    day.len() == 8
1260        && day.bytes().all(|b| b.is_ascii_digit())
1261        && time.len() == 6
1262        && time.bytes().all(|b| b.is_ascii_digit())
1263        && tag.len() == 4
1264        && tag.bytes().all(|b| b.is_ascii_alphanumeric())
1265}
1266
1267/// Expand an id prefix to exactly one run id.
1268pub fn resolve_id(prefix: &str) -> Result<String> {
1269    // A whole id names its directory, readable state or not: the run whose
1270    // `run.json` never landed still has to be reachable by `magi show` and
1271    // by the fold route, which is the only way its record ever leaves.
1272    if is_run_id(prefix) && run_dir(prefix).is_dir() {
1273        return Ok(prefix.to_owned());
1274    }
1275    let hits: Vec<String> = list_ids()
1276        .into_iter()
1277        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
1278        .collect();
1279    match hits.len() {
1280        1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1281        0 => bail!("no run matches `{prefix}`"),
1282        _ => bail!(
1283            "`{prefix}` matches {} runs: {}",
1284            hits.len(),
1285            hits.join(", ")
1286        ),
1287    }
1288}
1289
1290/// The most recent run, if any.
1291pub fn latest_id() -> Option<String> {
1292    list_ids().into_iter().next()
1293}
1294
1295/// `YYYYMMDD-HHMMSS-xxxx`, sortable and short enough for a branch name.
1296///
1297/// The four hex digits are fresh entropy, **not** `blind.seed`. They were the
1298/// seed, and a pinned seed then made the whole id a function of the second it
1299/// started in: two runs a second apart were distinguishable, two in the same
1300/// second were not. Everything keyed on the id collided with them - the run
1301/// directory, `artifacts/`, and the candidate worktrees under
1302/// `wt/magi/<short>/`.
1303///
1304/// `tests/common` pins the seed on purpose, so its integration tests all share
1305/// one suffix. On Windows the suite is slow enough that the seconds differ and
1306/// nothing showed; on Linux `graph_dropped_stream`'s three tests run inside
1307/// 16s, so two of them shared a run directory and the second read an artifact
1308/// the first had written (`impl-B-resume.out`) - a failure that looked like the
1309/// resume logic misbehaving and was really two runs in one directory.
1310///
1311/// A seed exists to make the *blind* decisions reproducible: label assignment
1312/// and per-judge presentation order. It was never meant to name the run, and
1313/// `RunState::seed` still carries it for what it is for.
1314fn new_id() -> String {
1315    let stamp = Zoned::now().strftime("%Y%m%d-%H%M%S");
1316    let entropy = crate::rng::entropy();
1317    format!("{stamp}-{:04x}", (entropy ^ (entropy >> 32)) & 0xffff)
1318}
1319
1320/// Keep the last `max` bytes of `text`, on a line boundary.
1321pub fn tail(text: &str, max: usize) -> String {
1322    if text.len() <= max {
1323        return text.to_owned();
1324    }
1325    let mut cut = text.len() - max;
1326    while cut < text.len() && !text.is_char_boundary(cut) {
1327        cut += 1;
1328    }
1329    let slice = &text[cut..];
1330    let start = slice.find('\n').map_or(0, |i| i + 1);
1331    format!(
1332        "[... {} earlier bytes omitted ...]\n{}",
1333        cut,
1334        &slice[start..]
1335    )
1336}
1337
1338/// Path of a run artifact.
1339pub fn artifact_path(run: &RunState, name: &str) -> PathBuf {
1340    run.dir().join("artifacts").join(name)
1341}
1342
1343/// Write an artifact, creating the directory if needed.
1344pub fn write_artifact(run: &RunState, name: &str, body: &str) -> Result<PathBuf> {
1345    let path = artifact_path(run, name);
1346    if let Some(parent) = path.parent() {
1347        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
1348    }
1349    std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
1350    Ok(path)
1351}
1352
1353/// Read an artifact back, e.g. a stored patch on resume.
1354pub fn read_artifact(run: &RunState, name: &str) -> Option<String> {
1355    std::fs::read_to_string(artifact_path(run, name)).ok()
1356}
1357
1358#[cfg(test)]
1359mod tests {
1360    use super::*;
1361
1362    fn state() -> RunState {
1363        RunState::new(
1364            PathBuf::from("/repo"),
1365            "main".to_owned(),
1366            "abc1234def".to_owned(),
1367            "add retries".to_owned(),
1368            Config::default(),
1369        )
1370    }
1371
1372    #[test]
1373    fn resolve_home_prefers_the_pin_then_the_env_var() {
1374        let pinned = PathBuf::from("/pinned");
1375        assert_eq!(
1376            resolve_home(Some(pinned.clone()), Some("/env".into())),
1377            pinned,
1378            "a pin wins even over MAGI_HOME"
1379        );
1380        assert_eq!(
1381            resolve_home(None, Some("/env".into())),
1382            PathBuf::from("/env")
1383        );
1384    }
1385
1386    #[test]
1387    #[should_panic(expected = "run::set_home()")]
1388    fn resolve_home_refuses_to_fall_back_to_the_operators_real_home() {
1389        // Neither override present is exactly the state a test reaches by
1390        // forgetting `set_home`/`MAGI_HOME` - the accident that put three
1391        // broken fixture runs into the operator's real history. Asserted
1392        // against the pure decision directly, not `home()` itself, because
1393        // `HOME` is a process-wide `OnceLock` another test may have already
1394        // set - this must not depend on test execution order.
1395        resolve_home(None, None);
1396    }
1397
1398    #[test]
1399    fn a_run_is_named_by_shape_so_a_state_less_directory_is_still_a_run() {
1400        // The shape `new_id` mints. A directory answering to it is a run even
1401        // with no readable `run.json`: that is how a save that ran out of
1402        // disk stays visible instead of vanishing from every listing.
1403        assert!(is_run_id(&new_id()));
1404        assert!(is_run_id("20260904-014540-88c0"));
1405        // Not runs: a stray folder, a truncated id, a non-hex tag, and an id
1406        // with an extra segment (a worktree label, say).
1407        assert!(!is_run_id("scratch"));
1408        assert!(!is_run_id("20260904-014540"));
1409        assert!(!is_run_id("20260904-014540-88c0f"));
1410        assert!(!is_run_id("2026090x-014540-88c0"));
1411        assert!(!is_run_id("20260904-014540-88c0-A"));
1412    }
1413
1414    #[test]
1415    fn ids_are_sortable_and_short_suffixed() {
1416        let s = state();
1417        let parts: Vec<&str> = s.id.split('-').collect();
1418        assert_eq!(parts.len(), 3);
1419        assert_eq!(parts[0].len(), 8);
1420        assert_eq!(parts[1].len(), 6);
1421        assert_eq!(parts[2].len(), 4);
1422        assert_eq!(s.short(), parts[2]);
1423    }
1424
1425    #[test]
1426    fn branch_names_carry_the_label_not_the_author() {
1427        let s = state();
1428        let b = s.branch_for('B');
1429        assert_eq!(b, format!("magi/{}/B", s.short()));
1430        assert!(!b.contains("claude"));
1431    }
1432
1433    /// A pinned seed reproduces the blind decisions. It must **not** reproduce
1434    /// the run's identity.
1435    ///
1436    /// `assert_eq!(a.short(), b.short())` used to stand where the last
1437    /// assertion is now, and it was pinning the defect: with the id's suffix
1438    /// derived from the seed, two runs started in the same second were the
1439    /// same run as far as the filesystem was concerned - one directory, one
1440    /// `artifacts/`, one set of candidate worktrees. `tests/common` pins a
1441    /// seed for every integration test, so on Linux, where the suite is fast,
1442    /// two tests in `graph_dropped_stream` shared a directory and one read the
1443    /// other's artifact.
1444    #[test]
1445    fn a_pinned_seed_is_reproducible_but_never_the_run_id() {
1446        let mut cfg = Config::default();
1447        cfg.blind.seed = Some(1234);
1448        let a = RunState::new(
1449            PathBuf::from("/r"),
1450            "main".to_owned(),
1451            "c".to_owned(),
1452            "t".to_owned(),
1453            cfg.clone(),
1454        );
1455        let b = RunState::new(
1456            PathBuf::from("/r"),
1457            "main".to_owned(),
1458            "c".to_owned(),
1459            "t".to_owned(),
1460            cfg,
1461        );
1462        // What the seed is for: the same shuffles, run after run.
1463        assert_eq!(a.seed, 1234);
1464        assert_eq!(a.seed, b.seed);
1465        // What it is not for. Two runs are two runs, in the same second or
1466        // not, and everything keyed on the id depends on that.
1467        assert_ne!(
1468            a.id, b.id,
1469            "two runs sharing an id share a directory, artifacts and worktrees"
1470        );
1471    }
1472
1473    #[test]
1474    fn status_terminality() {
1475        assert!(RunStatus::Merged.done());
1476        assert!(RunStatus::Blocked.done());
1477        assert!(!RunStatus::Reviewing.done());
1478    }
1479
1480    fn overrun_seat(now: Timestamp, elapsed_secs: i64, timeout_secs: u64) -> ActiveSeat {
1481        ActiveSeat {
1482            node: "implement".to_owned(),
1483            started_at: now - jiff::SignedDuration::new(elapsed_secs, 0),
1484            timeout_secs,
1485            attempt: 0,
1486        }
1487    }
1488
1489    #[test]
1490    fn active_all_overrun_requires_every_seat_past_its_own_timeout() {
1491        let mut s = state();
1492        let now = Timestamp::now();
1493        assert!(
1494            !s.active_all_overrun(now),
1495            "nothing active is not evidence of anything"
1496        );
1497
1498        s.active
1499            .insert("impl-A".to_owned(), overrun_seat(now, 21_000, 3_600));
1500        assert!(
1501            s.active_all_overrun(now),
1502            "21000s elapsed against a 3600s budget"
1503        );
1504
1505        // A seat still well within its own budget means the run is not
1506        // provably dead, however far its sibling has overrun.
1507        s.active
1508            .insert("impl-B".to_owned(), overrun_seat(now, 0, 3_600));
1509        assert!(!s.active_all_overrun(now));
1510    }
1511
1512    #[test]
1513    fn abandon_clears_active_and_fails_a_non_terminal_run() {
1514        let mut s = state();
1515        s.status = RunStatus::Implementing;
1516        let now = Timestamp::now();
1517        s.active
1518            .insert("impl-A".to_owned(), overrun_seat(now, 21_000, 3_600));
1519
1520        s.abandon("daemon");
1521
1522        assert!(s.active.is_empty());
1523        assert_eq!(s.status, RunStatus::Failed);
1524        assert!(
1525            s.events
1526                .last()
1527                .expect("an event was logged")
1528                .message
1529                .contains("impl-A"),
1530            "the event names the abandoned seat"
1531        );
1532    }
1533
1534    #[test]
1535    fn abandon_never_overwrites_a_status_already_terminal() {
1536        let mut s = state();
1537        s.status = RunStatus::Ready;
1538        let now = Timestamp::now();
1539        s.active
1540            .insert("impl-A".to_owned(), overrun_seat(now, 21_000, 3_600));
1541
1542        s.abandon("daemon");
1543
1544        assert!(s.active.is_empty());
1545        assert_eq!(
1546            s.status,
1547            RunStatus::Ready,
1548            "a run already done must not be relabelled Failed"
1549        );
1550    }
1551
1552    #[test]
1553    fn candidate_viability_excludes_empty_and_failed() {
1554        let mut c = Candidate {
1555            index: 0,
1556            label: 'A',
1557            agent: "a".to_owned(),
1558            branch: "b".to_owned(),
1559            worktree: PathBuf::from("/w"),
1560            summary: String::new(),
1561            stat: String::new(),
1562            files: 1,
1563            commits: 1,
1564            empty: false,
1565            failed: None,
1566            duration_ms: 0,
1567            folded: false,
1568        };
1569        assert!(c.viable());
1570        c.empty = true;
1571        assert!(!c.viable());
1572        c.empty = false;
1573        c.failed = Some("timeout".to_owned());
1574        assert!(!c.viable());
1575    }
1576
1577    #[test]
1578    fn build_failure_is_distinguished_from_a_failing_test() {
1579        let link_race = CommandOutcome {
1580            command: "cargo test".to_owned(),
1581            code: Some(1),
1582            output_tail: "LINK : fatal error LNK1104: cannot open file \
1583                          'graph_dirty_tree-71d4dc8e.exe'\n\
1584                          error: could not compile `magi-cli` (test \"graph_dirty_tree\")"
1585                .to_owned(),
1586            duration_ms: 500,
1587        };
1588        assert!(!link_race.ok());
1589        assert!(link_race.build_failed());
1590
1591        let failing_test = CommandOutcome {
1592            command: "cargo test".to_owned(),
1593            code: Some(101),
1594            output_tail: "thread 'it_works' panicked at 'assertion failed'".to_owned(),
1595            duration_ms: 500,
1596        };
1597        assert!(!failing_test.ok());
1598        assert!(
1599            !failing_test.build_failed(),
1600            "a real test failure must not be classed as a build failure"
1601        );
1602
1603        let passing = CommandOutcome {
1604            command: "cargo test".to_owned(),
1605            code: Some(0),
1606            output_tail: String::new(),
1607            duration_ms: 500,
1608        };
1609        assert!(passing.ok());
1610        assert!(!passing.build_failed());
1611    }
1612
1613    #[test]
1614    fn tail_keeps_the_end_on_a_line_boundary() {
1615        let text = (0..100).map(|i| format!("line {i}\n")).collect::<String>();
1616        let t = tail(&text, 40);
1617        assert!(t.starts_with("[..."));
1618        assert!(t.ends_with("line 99\n"));
1619        assert!(t.len() < 120);
1620        assert_eq!(tail("short", 40), "short");
1621    }
1622
1623    #[test]
1624    fn tail_survives_multibyte_cuts() {
1625        let text = "あ".repeat(50);
1626        let t = tail(&text, 10);
1627        assert!(t.contains("earlier bytes omitted"));
1628        assert!(t.ends_with('あ'));
1629    }
1630
1631    fn finding(id: &str, severity: crate::verdict::Severity) -> crate::verdict::Finding {
1632        crate::verdict::Finding {
1633            id: id.to_owned(),
1634            severity,
1635            file: None,
1636            line: None,
1637            title: "x".to_owned(),
1638            detail: String::new(),
1639        }
1640    }
1641
1642    fn round(clean: bool, findings: Vec<crate::verdict::Finding>) -> ReviewRound {
1643        ReviewRound {
1644            round: 1,
1645            head: "h".to_owned(),
1646            verified_head: None,
1647            reviews: vec![ReviewRecord {
1648                reviewer: 1,
1649                agent: "a".to_owned(),
1650                summary: String::new(),
1651                findings,
1652                vote: None,
1653                failed: None,
1654                duration_ms: 0,
1655            }],
1656            e2e: Vec::new(),
1657            verify_retried: false,
1658            e2e_deferred: false,
1659            e2e_defer_reason: None,
1660            fix: None,
1661            blocking: 0,
1662            answered: 1,
1663            expected: 1,
1664            clean,
1665            progressed: false,
1666            vote_split: false,
1667            reconsideration: Vec::new(),
1668            verdict: None,
1669        }
1670    }
1671
1672    #[test]
1673    fn e2e_status_tells_deferred_apart_from_not_configured() {
1674        let mut r = round(false, Vec::new());
1675        assert_eq!(r.e2e_status(), E2eStatus::NotConfigured);
1676
1677        r.e2e_deferred = true;
1678        assert_eq!(
1679            r.e2e_status(),
1680            E2eStatus::Deferred,
1681            "an empty e2e must not read as unconfigured once it was deferred on purpose"
1682        );
1683
1684        r.e2e = vec![CommandOutcome {
1685            command: "test".to_owned(),
1686            code: Some(0),
1687            output_tail: String::new(),
1688            duration_ms: 0,
1689        }];
1690        assert_eq!(
1691            r.e2e_status(),
1692            E2eStatus::Passed,
1693            "a round with real outcomes is never read as deferred, even if the flag is still set"
1694        );
1695    }
1696
1697    #[test]
1698    fn e2e_status_reports_a_real_failure_as_failed_not_deferred() {
1699        let mut r = round(false, Vec::new());
1700        r.e2e = vec![CommandOutcome {
1701            command: "test".to_owned(),
1702            code: Some(1),
1703            output_tail: "boom".to_owned(),
1704            duration_ms: 0,
1705        }];
1706        assert_eq!(r.e2e_status(), E2eStatus::Failed);
1707    }
1708
1709    #[test]
1710    fn open_findings_is_empty_when_the_last_round_was_clean() {
1711        let mut s = state();
1712        s.reviews = vec![round(
1713            true,
1714            vec![finding("R1-1-1", crate::verdict::Severity::Minor)],
1715        )];
1716        assert!(s.open_findings().is_empty());
1717    }
1718
1719    #[test]
1720    fn open_findings_reads_the_last_non_clean_round() {
1721        let mut s = state();
1722        s.reviews = vec![round(
1723            false,
1724            vec![finding("R1-1-1", crate::verdict::Severity::Major)],
1725        )];
1726        let open = s.open_findings();
1727        assert_eq!(open.len(), 1);
1728        assert_eq!(open[0].id, "R1-1-1");
1729    }
1730
1731    #[test]
1732    fn handed_off_with_open_findings_needs_a_mergeable_status_and_an_open_round() {
1733        let mut s = state();
1734        s.reviews = vec![round(
1735            false,
1736            vec![finding("R1-1-1", crate::verdict::Severity::Major)],
1737        )];
1738
1739        s.status = RunStatus::Blocked;
1740        assert!(
1741            !s.handed_off_with_open_findings(),
1742            "a blocked run is not a hand-off"
1743        );
1744
1745        s.status = RunStatus::Ready;
1746        assert!(s.handed_off_with_open_findings());
1747
1748        s.reviews = vec![round(true, Vec::new())];
1749        assert!(
1750            !s.handed_off_with_open_findings(),
1751            "a clean last round has nothing to hand off"
1752        );
1753    }
1754
1755    #[test]
1756    fn state_round_trips_through_json() {
1757        let s = state();
1758        let body = serde_json::to_string(&s).unwrap();
1759        let back: RunState = serde_json::from_str(&body).unwrap();
1760        assert_eq!(back.id, s.id);
1761        assert_eq!(back.instruction, "add retries");
1762        assert_eq!(back.status, RunStatus::Prep);
1763    }
1764
1765    #[test]
1766    fn a_round_recorded_before_e2e_deferral_existed_still_loads() {
1767        // Exactly the shape a pre-existing `run.json` has for a round: no
1768        // `e2e_deferred`, no `e2e_defer_reason`. Every round used to run e2e
1769        // unconditionally, so the honest reading of an old record's silence
1770        // on this is "it was not deferred" — `false`/`None`, not a load
1771        // failure and not a schema bump (see the `SCHEMA` doc comment: a
1772        // purely additive field whose absence has one unambiguous meaning
1773        // does not need one).
1774        let body = r#"{
1775            "round": 1,
1776            "head": "deadbeef",
1777            "reviews": [],
1778            "e2e": [],
1779            "verify_retried": false,
1780            "fix": null,
1781            "blocking": 0,
1782            "answered": 1,
1783            "expected": 1,
1784            "clean": true
1785        }"#;
1786        let r: ReviewRound = serde_json::from_str(body).expect("an old-shaped round must load");
1787        assert!(!r.e2e_deferred);
1788        assert!(r.e2e_defer_reason.is_none());
1789        assert_eq!(r.e2e_status(), E2eStatus::NotConfigured);
1790    }
1791
1792    #[test]
1793    fn schema_five_state_migrates_old_empty_e2e_and_legacy_verify_budget() {
1794        let mut value = serde_json::to_value(state()).expect("serialize state");
1795        let object = value.as_object_mut().expect("state object");
1796        object.insert("schema".to_owned(), serde_json::json!(5));
1797        let graph = object["config"]["graph"]
1798            .as_object_mut()
1799            .expect("graph object");
1800        graph.insert("timeout_review".to_owned(), serde_json::json!(3600));
1801        graph.remove("timeout_verify");
1802        let review = object["reviews"].as_array_mut().expect("reviews");
1803        review.push(serde_json::json!({
1804            "round": 1, "head": "old", "reviews": [], "e2e": [],
1805            "verify_retried": false, "blocking": 0, "answered": 1,
1806            "expected": 1, "clean": true
1807        }));
1808        let old: RunState = serde_json::from_value(value).expect("schema-5 shape parses");
1809        let migrated = migrate_schema(old).expect("schema 5 migrates");
1810        assert_eq!(migrated.schema, SCHEMA);
1811        assert_eq!(migrated.config.graph.verify_timeout(), 3600);
1812        assert_eq!(migrated.reviews[0].e2e_status(), E2eStatus::NotConfigured);
1813    }
1814
1815    #[test]
1816    fn schema_six_serialization_is_rejected_by_a_schema_five_reader() {
1817        let body = serde_json::to_value(state()).expect("serialize state");
1818        assert_eq!(body["schema"], serde_json::json!(SCHEMA));
1819        assert_ne!(body["schema"], serde_json::json!(5));
1820    }
1821
1822    #[test]
1823    fn seat_started_and_finished_track_who_has_not_answered_yet() {
1824        let mut s = state();
1825        s.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
1826        s.seat_started("judge", "judge-2", std::time::Duration::from_secs(60), 0);
1827        assert_eq!(s.active.len(), 2, "both seats are still out");
1828
1829        s.seat_finished("judge-1");
1830        assert_eq!(
1831            s.active.keys().collect::<Vec<_>>(),
1832            vec!["judge-2"],
1833            "only the seat that answered drops out; judge-2 is still waited on"
1834        );
1835    }
1836
1837    #[test]
1838    fn a_retry_is_recorded_as_a_later_attempt_on_the_same_seat() {
1839        let mut s = state();
1840        s.seat_started("review", "review-2", std::time::Duration::from_secs(30), 0);
1841        s.seat_finished("review-2");
1842        // A nudge re-asks the same seat; attempt says this is not the first
1843        // time, which is the only trace a nudge otherwise leaves behind.
1844        s.seat_started("review", "review-2", std::time::Duration::from_secs(30), 1);
1845        assert_eq!(s.active["review-2"].attempt, 1);
1846    }
1847
1848    #[test]
1849    fn active_seat_reports_elapsed_and_remaining_time() {
1850        let now = Timestamp::now();
1851        let started = now - jiff::SignedDuration::from_secs(30);
1852        let seat = ActiveSeat {
1853            node: "judge".to_owned(),
1854            started_at: started,
1855            timeout_secs: 100,
1856            attempt: 0,
1857        };
1858        assert_eq!(seat.elapsed_secs(now), 30);
1859        assert_eq!(seat.remaining_secs(now), 70);
1860    }
1861
1862    #[test]
1863    fn remaining_time_never_goes_negative_past_the_timeout() {
1864        // `agy`'s own print-timeout occasionally overruns by a hair before the
1865        // kill lands; a naive subtraction would print a negative "time left".
1866        let now = Timestamp::now();
1867        let started = now - jiff::SignedDuration::from_secs(200);
1868        let seat = ActiveSeat {
1869            node: "implement".to_owned(),
1870            started_at: started,
1871            timeout_secs: 100,
1872            attempt: 1,
1873        };
1874        assert_eq!(seat.remaining_secs(now), 0);
1875    }
1876
1877    #[test]
1878    fn clear_active_drops_stale_seats_and_reports_whether_it_did() {
1879        let mut s = state();
1880        assert!(!s.clear_active(), "nothing to clear on a fresh run");
1881        s.seat_started(
1882            "implement",
1883            "impl-B",
1884            std::time::Duration::from_secs(3600),
1885            0,
1886        );
1887        assert!(s.clear_active(), "a leftover entry is reported as cleared");
1888        assert!(s.active.is_empty());
1889    }
1890
1891    #[test]
1892    fn active_seat_carries_nothing_that_could_be_read_as_output_bytes() {
1893        // `agy` prints exactly one JSON object, at the very end (see
1894        // `agent::dropped_stream`'s doc comment) — a seat can sit at zero
1895        // captured bytes for its whole timeout while working normally. So
1896        // `ActiveSeat` records only the wall-clock facts (when it started,
1897        // its budget, which attempt), never a byte count, which is what
1898        // keeps a reader from being able to build "0 bytes => dead" out of
1899        // it even by accident.
1900        let seat = ActiveSeat {
1901            node: "implement".to_owned(),
1902            started_at: Timestamp::now(),
1903            timeout_secs: 60,
1904            attempt: 0,
1905        };
1906        let value = serde_json::to_value(&seat).unwrap();
1907        let keys: std::collections::BTreeSet<String> =
1908            value.as_object().unwrap().keys().cloned().collect();
1909        assert_eq!(
1910            keys,
1911            std::collections::BTreeSet::from([
1912                "node".to_owned(),
1913                "started_at".to_owned(),
1914                "timeout_secs".to_owned(),
1915                "attempt".to_owned(),
1916            ]),
1917            "a byte count here would be a lever to declare a silent-but-healthy seat dead"
1918        );
1919    }
1920
1921    #[test]
1922    fn an_old_run_json_without_active_seats_still_loads() {
1923        // Schema did not bump for this field: an already-written run.json
1924        // simply lacks the key, and `#[serde(default)]` must fill it in
1925        // rather than fail the whole read.
1926        let s = state();
1927        let mut value = serde_json::to_value(&s).unwrap();
1928        value.as_object_mut().unwrap().remove("active");
1929        let back: RunState = serde_json::from_value(value).unwrap();
1930        assert!(back.active.is_empty());
1931        assert_eq!(back.schema, SCHEMA);
1932    }
1933
1934    #[test]
1935    fn ensure_can_delete_guards_live_and_unfolded_runs() {
1936        let mut s = state();
1937        // 1. A daemon is working on it right now.
1938        s.status = RunStatus::Prep;
1939        let err = s.ensure_can_delete(true).unwrap_err().to_string();
1940        assert!(err.contains("live daemon"), "{err}");
1941
1942        // 2. The same unfinished run with no daemon behind it is a leftover
1943        // from a killed process, and deletable. Without this an interrupted
1944        // run could never be removed: its status stays `prep` forever.
1945        assert!(s.ensure_can_delete(false).is_ok());
1946
1947        // 3. Unfolded candidates are refused either way — that is the guard
1948        // that stops a delete from discarding a worktree.
1949        s.status = RunStatus::Merged;
1950        s.candidates.push(Candidate {
1951            index: 0,
1952            label: 'A',
1953            agent: "a".to_owned(),
1954            branch: "b".to_owned(),
1955            worktree: PathBuf::from("/w"),
1956            summary: String::new(),
1957            stat: String::new(),
1958            files: 1,
1959            commits: 1,
1960            empty: false,
1961            failed: None,
1962            duration_ms: 0,
1963            folded: false,
1964        });
1965        let err = s.ensure_can_delete(false).unwrap_err().to_string();
1966        assert!(
1967            err.contains("magi fold"),
1968            "error must suggest `magi fold`: {err}"
1969        );
1970
1971        // 4. Folded and nobody working on it.
1972        s.candidates[0].folded = true;
1973        assert!(s.ensure_can_delete(false).is_ok());
1974    }
1975}