magi/clean.rs
1//! The disk janitor: finished runs get their worktrees folded, worktrees whose
2//! run record is already gone get reclaimed too, and the shared build cache is
3//! pruned to its cap.
4//!
5//! A run's state being written by an older schema is not the same thing as it
6//! being unreadable, and this module used to conflate the two: [`fold_due`]
7//! treated any `run.json` its version check rejected exactly like one that
8//! failed to parse at all, so a single schema bump silently stopped every
9//! automatic fold in the fleet the moment it shipped, and did so with no
10//! counter and no log line to say so. A record magi genuinely cannot parse —
11//! missing fields, broken JSON, a schema newer than this build has ever heard
12//! of — is still left alone here, still counted in
13//! [`Housekeeping::unreadable`], and still only ever removed by an explicit
14//! operator action (`magi fold`, or the equivalent phone route). One written
15//! by a schema this build merely disagrees with the *meaning* of is not that:
16//! as long as it still parses, folding proceeds regardless of the number in
17//! its `schema` field.
18//!
19//! Everything policy-shaped — which statuses are foldable, how long a finished
20//! run is left alone, whether the cache is over its limit — is a pure function
21//! injected with numbers, so nothing here has to ask the operating system to
22//! be testable. The only I/O is the removal itself.
23
24use std::collections::BTreeSet;
25use std::path::{Path, PathBuf};
26
27use anyhow::{Context as _, Result, bail};
28use jiff::{SignedDuration, Timestamp};
29use serde::Deserialize;
30
31use crate::ask::Questions;
32use crate::config::Disk;
33use crate::run::{RunState, RunStatus, SCHEMA, short_of};
34
35use crate::disk::{Prune, dir_size};
36
37/// What one janitor pass did, for the caller's log line.
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub struct Housekeeping {
40 /// Runs folded (worktrees dropped).
41 pub folded: usize,
42 /// Runs [`fold_due`] left alone because their `run.json` genuinely could
43 /// not be read - missing, broken JSON, a schema this build has never
44 /// heard of - as opposed to one merely written by a different schema
45 /// number, which is folded like any other (see the module docs). This was
46 /// defined but never incremented for a long stretch of this module's
47 /// history, which is exactly how 90 of 93 runs sat unfolded on one
48 /// operator's machine with nothing anywhere saying why: every one of them
49 /// was misclassified as unreadable by a schema check that has since been
50 /// narrowed to only the runs that actually are.
51 pub unreadable: usize,
52 /// Worktrees under the worktree bay reclaimed because no run record in
53 /// `runs/` claims them anymore (see [`fold_orphaned_worktrees`]).
54 pub orphaned_worktrees: usize,
55 /// Files dropped from the shared cache.
56 pub cache_files: usize,
57 /// Bytes freed from the shared cache.
58 pub cache_freed: u64,
59 /// Open questions abandoned because the run that asked them has already
60 /// settled where nothing is coming back to read an answer.
61 pub questions_abandoned: usize,
62 /// Runs found blocked on a merge magi never recorded — a pull request the
63 /// operator merged by hand while `land::land` never got as far as
64 /// opening one itself — and corrected automatically. See
65 /// [`reconcile_external_merges`].
66 pub external_merges_recorded: usize,
67}
68
69/// Run the janitor: fold due runs, reclaim orphaned worktrees, prune stale
70/// worktree registrations, then prune the cache if it is over its cap.
71///
72/// Every part is best-effort; a jammed cache lock or a run whose worktree
73/// another borrower holds must not stop the rest. Errors are reported through
74/// `tracing::warn` - this is housekeeping, and the daemon keeps serving
75/// either way.
76pub async fn housekeep(
77 cfg: &crate::config::Config,
78 home: &Path,
79 worktrees_root: &Path,
80 repo: &Path,
81 now: Timestamp,
82) -> Housekeeping {
83 let mut out = Housekeeping::default();
84 if cfg.disk.auto_fold {
85 let runs = home.join("runs");
86 match fold_due(&runs, home, worktrees_root, &cfg.disk, now).await {
87 Ok((folded, unreadable)) => {
88 out.folded = folded;
89 out.unreadable = unreadable;
90 }
91 Err(e) => {
92 tracing::warn!("housekeep: fold due runs: {e:#}");
93 // Stable wording: the reason varies per pass, and a changed
94 // message would relight the bell on every retry.
95 crate::notices::raise_in(
96 home,
97 crate::notices::Notice::warn(
98 "housekeep:fold",
99 "Automatic cleanup of finished runs failed; disk usage may keep growing.",
100 ),
101 );
102 }
103 }
104 out.orphaned_worktrees =
105 fold_orphaned_worktrees(&runs, worktrees_root, home, cfg.disk.fold_grace_secs, now)
106 .await;
107 // Best-effort in the same sense as everything else here: a repository
108 // this janitor pass has nothing to do with (or none at all, in a unit
109 // test) must not turn a `warn` into a reason to skip the rest.
110 if let Err(e) = crate::git::worktree_prune(repo).await {
111 tracing::warn!("housekeep: prune worktree registrations: {e:#}");
112 }
113 out.external_merges_recorded = reconcile_external_merges(&runs, home, &cfg.disk, now).await;
114 }
115 match prune_cache_if_over_limit(cfg, home) {
116 Ok(Some(pruned)) => {
117 out.cache_files = pruned.files;
118 out.cache_freed = pruned.freed;
119 }
120 Ok(None) => {}
121 Err(e) => tracing::warn!("housekeep: prune cache: {e:#}"),
122 }
123 // Unconditional, unlike the two passes above: this is not a disk policy
124 // with a cap or an opt-out, it is closing a gap `graph::Runner` itself
125 // cannot - a run that reached `Merged`/`Ready`/`Failed` before this
126 // cleanup existed, or whose process died between saving that status and
127 // abandoning the question it leaves behind (see `Runner::settle_questions`).
128 // Left alone, that question sits `open` forever: the owner's badge,
129 // banner and title all keep counting a decision nobody is left to read.
130 out.questions_abandoned =
131 abandon_settled_questions(&Questions::at(home.join("questions")), &home.join("runs"));
132 out
133}
134
135/// Abandon every open question whose run has already settled into a status
136/// nothing comes back from, worded with what the run became - the same
137/// cleanup `graph::Runner::settle_questions` runs the moment `status` lands
138/// there, for questions that missed it.
139///
140/// Scans questions rather than runs: the open list is normally short, and a
141/// run that never asked anything costs nothing here. A run this cannot read,
142/// deleted or written by a schema this build does not speak, is left alone
143/// the same as everywhere else in this module; the question stays open
144/// rather than guessed at.
145pub fn abandon_settled_questions(store: &Questions, runs: &Path) -> usize {
146 let waiting_on: BTreeSet<String> = store
147 .list()
148 .into_iter()
149 .filter(|q| q.status.open())
150 .map(|q| q.run)
151 .collect();
152 let mut abandoned = 0;
153 for run in waiting_on {
154 let Ok(meta) = read_meta(runs, &run) else {
155 continue;
156 };
157 match store.settle_run(&run, meta.status) {
158 Ok(n) => abandoned += n,
159 Err(e) => tracing::warn!("housekeep: abandon questions for {run}: {e:#}"),
160 }
161 }
162 abandoned
163}
164
165/// Fold every run that is finished, older than the grace period, and not being
166/// worked on; return `(folded, unreadable)`.
167///
168/// A run whose `run.json` genuinely cannot be parsed — missing fields, broken
169/// JSON, a schema newer than this build has ever heard of — is left exactly
170/// as it is. Automatic housekeeping cannot tell a mid-write file from one that
171/// will never parse again, and `<home>/runs/<id>/` is the evidence `magi
172/// stats` and the deck read; when unsure whether it is safe to touch, the
173/// janitor keeps rather than deletes (see the module docs). Discarding a
174/// record this unreadable is an explicit operator action (`magi fold`, or the
175/// equivalent phone route), never something that happens unattended. Every
176/// such skip is counted in the returned `unreadable` and logged through
177/// `tracing::warn` with the parse failure that caused it - silence here is
178/// exactly the failure mode that let 90 of 93 runs sit unfolded with nothing
179/// to show for it.
180///
181/// A run merely written by a *different* schema number is not unreadable: as
182/// long as `run.json` still parses, it folds like any other terminal run (see
183/// the module docs for why the two are different questions).
184///
185/// Runnable statuses and runs newer than the grace period are also left
186/// alone; folding them would throw away work that is still the answer to
187/// somebody's question. `Merged` runs forget their winner's worktree (the
188/// merge already landed it); `Ready` and `Failed` runs keep it.
189pub async fn fold_due(
190 runs: &Path,
191 home: &Path,
192 _worktrees_root: &Path,
193 disk: &Disk,
194 now: Timestamp,
195) -> Result<(usize, usize)> {
196 let mut folded = 0usize;
197 let mut unreadable = 0usize;
198 let mut ids: Vec<String> = std::fs::read_dir(runs)
199 .into_iter()
200 .flatten()
201 .flatten()
202 .filter(|e| e.path().join("run.json").is_file())
203 .map(|e| e.file_name().to_string_lossy().into_owned())
204 .collect();
205 ids.sort_unstable();
206 for id in ids {
207 if crate::daemon::is_working_on(home, &id, now) {
208 continue;
209 }
210 let meta = match read_meta(runs, &id) {
211 Ok(meta) => meta,
212 Err(e) => {
213 unreadable += 1;
214 tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
215 continue;
216 }
217 };
218 if meta.status.resumable() || !due(now, meta.updated_at, disk.fold_grace_secs) {
219 continue;
220 }
221 // `read_meta` already proved the file parses; `read_state` asks for
222 // the rest of the fields `graph::fold_run` needs (worktree paths,
223 // candidates, tally). A schema mismatch alone does not fail this -
224 // see the module docs - so reaching `Err` here means the JSON itself
225 // is broken in a way `read_meta` did not exercise, which is rare but
226 // not impossible (a body truncated between the two fields it reads
227 // and the rest). That must not cost every other run its turn through
228 // this loop, so it is a skip, not a `?`.
229 let mut state = match read_state(runs, &id) {
230 Ok(state) => state,
231 Err(e) => {
232 unreadable += 1;
233 tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
234 continue;
235 }
236 };
237 if state.schema != SCHEMA {
238 tracing::info!(
239 "housekeep: run {id} was written by schema {} (this build speaks {SCHEMA}); \
240 folding it anyway",
241 state.schema
242 );
243 }
244 let drop_winner = state.status == RunStatus::Merged;
245 // One run's fold must not cost every later run its turn. A worktree
246 // another borrower holds, a branch git refuses to delete, a repository
247 // that has since moved: each is a reason this run cannot be folded
248 // now, and none is a reason to stop the pass. Left unfolded, it is
249 // simply due again next time; a `?` here stopped automatic folding
250 // permanently at the first such run (finding R3-1-1 of run 51a3).
251 match crate::graph::fold_run(&mut state, drop_winner, home).await {
252 Ok(_) => folded += 1,
253 Err(e) => tracing::warn!("housekeep: fold {id}: {e:#}"),
254 }
255 }
256 Ok((folded, unreadable))
257}
258
259/// Is `updated` old enough, measured against `now`, that the run may fold?
260///
261/// Pure; the janitor compares against wallclock, tests inject both sides. The
262/// comparison is strict, so a run exactly at the edge of its grace period is
263/// left alone one more pass — the same convention as [`crate::disk::over_limit`].
264pub fn due(now: Timestamp, updated: Timestamp, grace_secs: u64) -> bool {
265 now.duration_since(updated) > SignedDuration::new(grace_secs as i64, 0)
266}
267
268/// The two fields the janitor decides on, read with a serde that tolerates
269/// everything else about the run being unreadable.
270#[derive(Deserialize)]
271struct Meta {
272 status: RunStatus,
273 updated_at: Timestamp,
274}
275
276/// Read `status` and `updated_at` straight off the state file, asking for
277/// nothing else. `Err` when the file is missing, not parseable, or a status in
278/// a version this build does not speak - all of which mean "unreadable".
279fn read_meta(runs: &Path, id: &str) -> Result<Meta> {
280 let path = runs.join(id).join("run.json");
281 let body =
282 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
283 let meta: Meta =
284 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
285 Ok(meta)
286}
287
288/// Runs checked against GitHub in one janitor pass, at most.
289///
290/// A fleet with many stuck runs must not turn every idle tick into a burst of
291/// `gh pr list` calls; a run left unchecked this pass is checked again next
292/// pass, same as an unfolded due run is.
293const MAX_EXTERNAL_MERGE_CHECKS_PER_PASS: usize = 5;
294
295/// The fields [`reconcile_external_merges`] filters on before paying for a
296/// full [`RunState`] parse or a `gh` round trip.
297#[derive(Deserialize)]
298struct ExternalMergeMeta {
299 status: RunStatus,
300 updated_at: Timestamp,
301 #[serde(default)]
302 merge: Option<crate::run::MergeOutcome>,
303}
304
305fn read_external_merge_meta(runs: &Path, id: &str) -> Result<ExternalMergeMeta> {
306 let path = runs.join(id).join("run.json");
307 let body =
308 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
309 let meta: ExternalMergeMeta =
310 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
311 Ok(meta)
312}
313
314/// Is a run worth asking GitHub about?
315///
316/// Pure, so the filter itself is assertable without a fixture that writes
317/// `run.json` files or spawns `gh`. Narrower than "blocked": `merge_recorded`
318/// excludes a run `land::land` already finished landing (successfully or
319/// not) - that path already carries its own record of what happened - and
320/// `due` gives an operator who is about to fix a run by hand a grace window
321/// before the janitor starts asking the same question about it.
322pub fn eligible_for_external_merge_check(
323 status: RunStatus,
324 merge_recorded: bool,
325 updated_at: Timestamp,
326 now: Timestamp,
327 grace_secs: u64,
328) -> bool {
329 status == RunStatus::Blocked && !merge_recorded && due(now, updated_at, grace_secs)
330}
331
332/// Rotate `ids` so a fixed per-pass cap does not always land on the same
333/// prefix of the list, starting at `start` (already reduced modulo nothing -
334/// callers pass whatever a persisted cursor last recorded, and this takes it
335/// modulo `ids.len()` itself).
336///
337/// Pure: the offset is the caller's problem, not wall-clock time. An earlier
338/// version derived `start` from `now.as_second() % ids.len()`, which looked
339/// independent of any state to persist but is not actually independent of
340/// how often the janitor runs - a poll interval and a pass's own duration
341/// that alias onto the same handful of `now.as_second()` values (say, a
342/// ten-second poll and a pass that finishes in under a second) revisit only
343/// those same few residues forever and never advance into the rest of the
344/// list at all. [`reconcile_external_merges`] instead persists a cursor
345/// across passes ([`read_external_merge_cursor`] /
346/// [`write_external_merge_cursor`]) and advances it by exactly how many ids
347/// this pass actually looked at, which is the only quantity that is
348/// guaranteed to move forward pass over pass regardless of timing.
349fn rotate_from(ids: &[String], start: usize) -> Vec<String> {
350 if ids.is_empty() {
351 return Vec::new();
352 }
353 let start = start % ids.len();
354 ids[start..]
355 .iter()
356 .chain(ids[..start].iter())
357 .cloned()
358 .collect()
359}
360
361/// Where [`reconcile_external_merges`] remembers how far it got, so a fixed
362/// per-pass cap advances through a fleet's eligible runs pass over pass
363/// instead of camping on whichever ones happen to sort first.
364const EXTERNAL_MERGE_CURSOR_FILE: &str = "external-merge-cursor";
365
366/// `0` for anything this cannot read as a plain number - a first run, a
367/// corrupt or missing file, a build that has never written one - which is
368/// exactly as good a starting point as any: the cursor's whole job is to
369/// keep moving, not to encode any particular position as meaningful.
370fn read_external_merge_cursor(home: &Path) -> usize {
371 std::fs::read_to_string(home.join(EXTERNAL_MERGE_CURSOR_FILE))
372 .ok()
373 .and_then(|s| s.trim().parse().ok())
374 .unwrap_or(0)
375}
376
377/// Best-effort, like every other write in this module's sweep: a failure to
378/// persist the cursor costs the fleet one pass's worth of forward progress
379/// on this sweep, never the run whose housekeeping it is racing to keep up
380/// with.
381fn write_external_merge_cursor(home: &Path, cursor: usize) {
382 if let Err(e) = std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), cursor.to_string()) {
383 tracing::warn!("housekeep: persist the external-merge sweep's cursor: {e:#}");
384 }
385}
386
387/// Close the gap `magi fold --merged` exists for, without waiting for an
388/// operator to notice and go find the pull request URL: a run that stopped
389/// `Blocked` with no `merge` recorded may have been merged anyway, by hand,
390/// on a pull request `land::land` never opened or never got to observe as
391/// merged. `land::find_external_merge` asks GitHub about the run's own
392/// winning branch, and only a pull request it can uniquely tie back to this
393/// run is ever acted on - see that function's own doc for what "uniquely"
394/// excludes.
395///
396/// A run this finds and fixes goes through
397/// [`crate::land::correct_confirmed_external_merge`] - the same correction
398/// `magi fold --merged` performs, minus the same-repo guard that command
399/// needs and this loop doesn't (see that function's own doc: the URL here
400/// was never operator-supplied, it came from asking `state.repo`'s own
401/// remote) - then through [`crate::graph::fold_run`] so it stops holding
402/// worktrees the moment it stops needing them. A run this cannot decide
403/// about - `gh` unreachable, more than one candidate pull
404/// request, nothing found at all - is left exactly as it is; only an error
405/// asking GitHub raises a notice, since "nothing found" is the ordinary,
406/// expected shape of a run that really is just blocked.
407async fn reconcile_external_merges(runs: &Path, home: &Path, disk: &Disk, now: Timestamp) -> usize {
408 let mut ids: Vec<String> = std::fs::read_dir(runs)
409 .into_iter()
410 .flatten()
411 .flatten()
412 .filter(|e| e.path().join("run.json").is_file())
413 .map(|e| e.file_name().to_string_lossy().into_owned())
414 .collect();
415 ids.sort_unstable();
416
417 // Every eligible id first, cheaply (a `Meta` read, no `gh`), then rotated
418 // before the cap is applied. Capping the sorted order directly would
419 // always land on the same lexicographic prefix - a fleet's oldest run ids
420 // - so a handful of long-blocked runs that never turn out to be merged
421 // would starve every id after them of a `gh` check, forever.
422 let mut eligible: Vec<String> = Vec::new();
423 for id in ids {
424 if crate::daemon::is_working_on(home, &id, now) {
425 continue;
426 }
427 let meta = match read_external_merge_meta(runs, &id) {
428 Ok(meta) => meta,
429 // Already counted as unreadable by `fold_due`'s own pass; not
430 // worth a second warning for the same file.
431 Err(_) => continue,
432 };
433 if eligible_for_external_merge_check(
434 meta.status,
435 meta.merge.is_some(),
436 meta.updated_at,
437 now,
438 disk.fold_grace_secs,
439 ) {
440 eligible.push(id);
441 }
442 }
443
444 if eligible.is_empty() {
445 return 0;
446 }
447 let cursor = read_external_merge_cursor(home);
448 let window: Vec<String> = rotate_from(&eligible, cursor)
449 .into_iter()
450 .take(MAX_EXTERNAL_MERGE_CHECKS_PER_PASS)
451 .collect();
452 // Advances by exactly how many ids this pass looked at, regardless of
453 // what came of looking - a run that turned out not to be merged after
454 // all must not be revisited before every other eligible run has had its
455 // own turn.
456 write_external_merge_cursor(home, (cursor + window.len()) % eligible.len());
457
458 let mut reconciled = 0usize;
459 for id in window {
460 let mut state = match read_state(runs, &id) {
461 Ok(state) => state,
462 Err(_) => continue,
463 };
464 match crate::land::find_external_merge(&state).await {
465 Ok(Some(found)) => {
466 match crate::land::correct_confirmed_external_merge(&mut state, &found.url).await {
467 Ok(_) => {
468 if let Err(e) = crate::graph::fold_run(&mut state, true, home).await {
469 tracing::warn!(
470 "housekeep: fold {id} after recording its external merge: {e:#}"
471 );
472 }
473 reconciled += 1;
474 }
475 Err(e) => tracing::warn!(
476 "housekeep: record external merge {} for {id}: {e:#}",
477 found.url
478 ),
479 }
480 }
481 Ok(None) => {}
482 Err(e) => {
483 tracing::warn!("housekeep: check external merge for {id}: {e:#}");
484 crate::notices::raise_in(
485 home,
486 crate::notices::Notice::warn(
487 &format!("merged-unrecorded:{id}"),
488 format!(
489 "Run {id} is blocked with no recorded merge, and checking GitHub \
490 for a merge failed; check by hand."
491 ),
492 ),
493 );
494 }
495 }
496 }
497 reconciled
498}
499
500/// Read a whole run state from a runs directory, for folding only.
501///
502/// Deliberately more permissive than [`RunState::load`], which this does not
503/// call: `load` backs `--resume` and every hand-driven command, where a
504/// schema this build disagrees with the *meaning* of must refuse outright
505/// rather than resume a review round or a tally against stale semantics
506/// (`RunState::SCHEMA`'s own docs list what has changed meaning at each
507/// bump). Folding recomputes nothing - it only reads worktree paths, branch
508/// names and a tally winner off the struct to remove them - so an old
509/// schema's values are exactly as good here as a current one's; every schema
510/// bump so far has only ever added a field or a variant, never repurposed an
511/// existing one, and serde already fills an added field's default when an
512/// older record has nothing to say about it. What this cannot tolerate, and
513/// what still surfaces as an `Err`, is `run.json` failing to parse at all.
514fn read_state(runs: &Path, id: &str) -> Result<RunState> {
515 let path = runs.join(id).join("run.json");
516 let body =
517 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
518 let state: RunState =
519 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
520 Ok(state)
521}
522
523/// Remove a run that cannot be read: its state directory under `runs` and its
524/// worktree directory under `worktrees_root`.
525///
526/// The state file is the only record of a run's repository and branches, so a
527/// run this unreadable is discarded at the filesystem level - there is no
528/// candidate list to fold first. The worktrees live under
529/// [`crate::run::default_worktree_root`] unless the run's config relocated
530/// them, which an unreadable run cannot tell us; the default location is
531/// removed, and anything the run placed elsewhere is a leftover for whoever
532/// knows where it went.
533///
534/// Deleting a worktree directory by hand leaves its registration in git, and a
535/// registered path cannot be re-`worktree add`-ed until it is pruned - so every
536/// worktree is unregistered from its repository first, best-effort, via the
537/// `gitdir:` link git keeps inside the directory.
538pub async fn fold_unreadable(runs: &Path, worktrees_root: &Path, id: &str) -> Result<Vec<String>> {
539 let resolved = resolve_id_path(runs, id)?;
540 let mut removed = Vec::new();
541 let run_dir = runs.join(&resolved);
542 if run_dir.exists() {
543 std::fs::remove_dir_all(&run_dir)
544 .with_context(|| format!("remove {}", run_dir.display()))?;
545 removed.push(format!("runs/{resolved}"));
546 }
547 let wt = worktrees_root.join(short_of(&resolved));
548 if wt.exists() {
549 crate::git::remove_worktree_from_linked(&wt).await;
550 for e in std::fs::read_dir(&wt).into_iter().flatten().flatten() {
551 crate::git::remove_worktree_from_linked(&e.path()).await;
552 }
553 std::fs::remove_dir_all(&wt).with_context(|| format!("remove {}", wt.display()))?;
554 removed.push(wt.to_string_lossy().into_owned());
555 }
556 Ok(removed)
557}
558
559/// Reclaim worktrees under `worktrees_root` that no run record in `runs`
560/// claims anymore, and return how many were removed.
561///
562/// [`fold_due`] only ever sees a worktree by walking `runs/` first, so a
563/// worktree whose run record is already gone — `magi run rm`, or a record
564/// deleted before its worktree — never enters that loop at all: nothing there
565/// is looking for it. This walks the worktree bay directly instead, and
566/// removes any `<short>` directory that no run id maps to.
567///
568/// Two things must never happen, and this checks both before ever touching a
569/// directory:
570///
571/// - **A worktree bay is never the only kind of thing under `worktrees_root`,
572/// and this must not assume it is.** A hand-placed scratch directory, or
573/// anything else an operator or another tool left in the same bay, has the
574/// same "no run claims it" shape as a genuine orphan but is not one -
575/// [`looks_like_a_worktree_bay`] is the same tag shape [`crate::run::is_run_id`]
576/// already requires of a real run's short id, and anything else is left
577/// alone regardless of what else is true about it.
578/// - **A worktree that was only just created might not have a `run.json` yet
579/// for a reason that has nothing to do with being orphaned.** `Runner::start`
580/// and `Runner::review` both create the worktree before the first
581/// `RunState::save` lands, and that gap - several `git` subprocesses wide -
582/// is invisible to [`crate::daemon::is_working_on_short`] whenever the run
583/// is not being driven through this daemon's own `poll` loop at all (a
584/// `magi review` invocation, for one). A directory whose own modification
585/// time is within `grace_secs` of `now` is left alone on that basis alone,
586/// the same margin [`fold_due`] gives a run before treating it as truly
587/// finished - long enough that no realistic gap between a `worktree add`
588/// and its `run.json` could ever be mistaken for one.
589///
590/// The one failure this must never cause is deleting the worktree of a run
591/// that is genuinely in flight. [`crate::daemon::is_working_on_short`] is the
592/// same liveness check [`fold_due`] trusts everywhere else in this module,
593/// checked by short id because there is no full id to compare here; when it
594/// cannot tell, this leaves the directory alone. Best-effort like the rest of
595/// housekeeping: one directory git or the filesystem refuses to give up is a
596/// `tracing::warn`, not a reason to abandon the rest of the pass.
597pub async fn fold_orphaned_worktrees(
598 runs: &Path,
599 worktrees_root: &Path,
600 home: &Path,
601 grace_secs: u64,
602 now: Timestamp,
603) -> usize {
604 let known: std::collections::HashSet<String> = std::fs::read_dir(runs)
605 .into_iter()
606 .flatten()
607 .flatten()
608 .map(|e| e.file_name().to_string_lossy().into_owned())
609 .filter(|name| crate::run::is_run_id(name))
610 .map(|id| short_of(&id).to_owned())
611 .collect();
612
613 let mut folded = 0usize;
614 for entry in std::fs::read_dir(worktrees_root)
615 .into_iter()
616 .flatten()
617 .flatten()
618 {
619 if !entry.path().is_dir() {
620 continue;
621 }
622 let short = entry.file_name().to_string_lossy().into_owned();
623 if !looks_like_a_worktree_bay(&short) {
624 continue;
625 }
626 if known.contains(&short) || crate::daemon::is_working_on_short(home, &short, now) {
627 continue;
628 }
629 let wt = entry.path();
630 if !stale_enough(&wt, grace_secs, now) {
631 continue;
632 }
633 crate::git::remove_worktree_from_linked(&wt).await;
634 for e in std::fs::read_dir(&wt).into_iter().flatten().flatten() {
635 crate::git::remove_worktree_from_linked(&e.path()).await;
636 }
637 match std::fs::remove_dir_all(&wt) {
638 Ok(()) => folded += 1,
639 Err(e) => tracing::warn!(
640 "housekeep: remove orphaned worktree {}: {e:#}",
641 wt.display()
642 ),
643 }
644 }
645 folded
646}
647
648/// Does `name` have the shape a run's own worktree bay is named with: the
649/// same 4-character alphanumeric tag [`crate::run::is_run_id`] requires of a
650/// full id's trailing block (see [`short_of`])?
651///
652/// Anything else under `worktrees_root` is not a bay this function reclaims
653/// at all, claimed or not - answering "does a run claim this?" about a
654/// directory that was never a run's worktree in the first place is exactly
655/// the wrong question to ask before deleting it.
656fn looks_like_a_worktree_bay(name: &str) -> bool {
657 name.len() == 4 && name.bytes().all(|b| b.is_ascii_alphanumeric())
658}
659
660/// Is `dir`'s own modification time old enough, against `grace_secs` and
661/// `now`, that its emptiness of a run record can be trusted rather than
662/// caught mid-creation?
663///
664/// A directory this pass cannot stat at all - a race with its own removal, a
665/// permission error - is treated as not yet stale: unreadable metadata is not
666/// evidence of anything, and the janitor already keeps rather than deletes
667/// whenever it cannot tell (see the module docs).
668///
669/// `grace_secs` is floored at [`MIN_ORPHAN_AGE_SECS`] regardless of what the
670/// caller passes: `0` is a documented, legitimate value for
671/// [`crate::config::Disk::fold_grace_secs`] (`due`'s own "always due" case),
672/// because that grace answers a policy question the operator owns - how long
673/// a *known, finished* run's worktree lingers before cleanup. Whether an
674/// orphan worktree is actually a race with `Runner::review`'s `git worktree
675/// add` landing before its `run.json` is not a policy question, and must not
676/// collapse to zero just because the operator turned the other grace off -
677/// that would defeat the very check meant to catch it.
678fn stale_enough(dir: &Path, grace_secs: u64, now: Timestamp) -> bool {
679 let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) else {
680 return false;
681 };
682 let Ok(ts) = Timestamp::try_from(modified) else {
683 return false;
684 };
685 due(now, ts, grace_secs.max(MIN_ORPHAN_AGE_SECS))
686}
687
688/// The floor under [`stale_enough`]'s grace, independent of
689/// [`crate::config::Disk::fold_grace_secs`].
690///
691/// Ample next to the race it guards: the gap between `Runner::start` or
692/// `Runner::review` creating a worktree and the first `RunState::save`
693/// landing is a handful of `git` subprocess calls, not minutes - but the
694/// janitor cannot tell "still mid-setup" from "orphaned" by any other signal
695/// for a run that never registers with `daemon::Status` at all (a `magi
696/// review` invocation, for one), so this is generous on purpose rather than
697/// tuned to the observed case.
698const MIN_ORPHAN_AGE_SECS: u64 = 5 * 60;
699
700/// Resolve an id or prefix against an explicit runs directory, exactly the way
701/// [`crate::run::resolve_id`] does against the global home.
702fn resolve_id_path(runs: &Path, prefix: &str) -> Result<String> {
703 // Keyed on the directory, not on a readable state file: the record this
704 // route exists to remove may be a lone `run.json.tmp` from a save that
705 // ran out of disk, and that is precisely the one a human needs a way to
706 // clear (see `crate::run::list_ids`).
707 if runs.join(prefix).is_dir() && crate::run::is_run_id(prefix) {
708 return Ok(prefix.to_owned());
709 }
710 let mut hits: Vec<String> = Vec::new();
711 for e in std::fs::read_dir(runs).into_iter().flatten().flatten() {
712 if !e.path().is_dir() {
713 continue;
714 }
715 let id = e.file_name().to_string_lossy().into_owned();
716 if crate::run::is_run_id(&id) && (id.starts_with(prefix) || id.ends_with(prefix)) {
717 hits.push(id);
718 }
719 }
720 match hits.len() {
721 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
722 0 => bail!("no run matches `{prefix}`"),
723 _ => bail!(
724 "`{prefix}` matches {} runs: {}",
725 hits.len(),
726 hits.join(", ")
727 ),
728 }
729}
730
731/// `magi fold`'s recovery path for a run whose worktrees are already gone —
732/// so [`crate::graph::fold_run`] removed nothing — but whose `run.json` still
733/// lists active seats nobody is left to answer for: no live daemon claims the
734/// run, and every one of those seats has overrun its own timeout (see
735/// [`RunState::active_all_overrun`]). Clearing them and failing the run is
736/// what lets it be deleted afterward — [`RunState::ensure_can_delete`] only
737/// ever checks whether a live daemon is working on the run and whether its
738/// candidates are folded, not `status`, but a run stuck `implementing`
739/// forever with an empty worktree still reads as unresolved everywhere else
740/// (`magi show`, the deck, the phone) until this runs.
741///
742/// Returns `false` without changing anything when a live daemon still claims
743/// the run, or when some active seat has not actually overrun its budget yet
744/// — a run that is merely between waves must never be guessed at.
745pub fn clear_abandoned_active(state: &mut RunState, home: &Path, now: Timestamp) -> Result<bool> {
746 if crate::daemon::is_working_on(home, &state.id, now) || !state.active_all_overrun(now) {
747 return Ok(false);
748 }
749 state.abandon("fold");
750 state.save_under(home)?;
751 // The seat that asked is gone for good now - the same door
752 // `graph::Runner::settle_questions` closes the moment `status` lands
753 // somewhere non-resumable, see that method's own doc. Without this, an
754 // open question the abandoned seat left behind would keep badging the
755 // operator until the next daemon startup's `abandon_settled_questions`
756 // pass happened to notice it, or forever if nothing is running `magi
757 // serve` at all.
758 if let Err(e) = Questions::at(home.join("questions")).settle_run(&state.id, state.status) {
759 tracing::warn!("abandon questions for {}: {e:#}", state.id);
760 }
761 Ok(true)
762}
763
764/// Delete files from the shared build cache until it fits its cap — but only
765/// while nobody live is registered as using it. [`crate::cache::maintenance_prune`]
766/// takes out the same lease a build would, so a prune can never race a
767/// compile in flight (this run's own, another run's, or a human's `magi
768/// review`) into deleting a file that build still needs. `Ok(None)` when the
769/// cache is in use right now; the next pass catches it once the borrower
770/// releases it, the same way a cap of `0` or a missing `CARGO_TARGET_DIR`
771/// already meant "nothing to do this time" here.
772pub fn prune_cache(home: &Path, cache: &Path, limit_bytes: u64) -> Result<Option<Prune>> {
773 crate::cache::maintenance_prune(home, cache, limit_bytes)
774}
775
776/// [`prune_cache`], but resolving the operator's opt-out and missing
777/// `CARGO_TARGET_DIR` first — the same two checks [`housekeep`]'s idle pass
778/// makes before ever measuring the cache, factored out so
779/// [`crate::daemon`]'s between-runs check (see the module's own doc for why
780/// congestion can make "idle" arrive too rarely to matter) makes them
781/// identically rather than growing its own copy that could drift. `Ok(None)`
782/// covers a cap of `0` (see the module docs on `cache_limit_bytes`), a config
783/// that renders no `CARGO_TARGET_DIR` to aggregate at all, and a cache
784/// currently in use (see [`prune_cache`]).
785pub fn prune_cache_if_over_limit(
786 cfg: &crate::config::Config,
787 home: &Path,
788) -> Result<Option<Prune>> {
789 if cfg.disk.cache_limit_bytes == 0 {
790 return Ok(None);
791 }
792 let Some(cache) = cfg.cache_dir() else {
793 return Ok(None);
794 };
795 prune_cache(home, &cache, cfg.disk.cache_limit_bytes)
796}
797
798/// The cache's path, size and cap, for `magi cache show` and the health view.
799/// `None` when the config declares no `CARGO_TARGET_DIR` to aggregate.
800///
801/// A cap of `0` means the operator opted out of pruning; the size is then
802/// reported but never acted on.
803pub fn cache_report(cfg: &crate::config::Config) -> Option<(PathBuf, u64, u64)> {
804 let cache = cfg.cache_dir()?;
805 Some((
806 cache.clone(),
807 cache_size(&cache),
808 cfg.disk.cache_limit_bytes,
809 ))
810}
811
812/// Size in bytes of the shared build cache.
813pub fn cache_size(cache: &Path) -> u64 {
814 dir_size(cache)
815}
816
817#[cfg(test)]
818mod tests {
819 use super::*;
820 use crate::config::Disk;
821 use std::fs;
822
823 fn ts(s: &str) -> Timestamp {
824 s.parse().expect("rfc3339")
825 }
826
827 fn block_on<F: std::future::Future>(f: F) -> F::Output {
828 tokio::runtime::Runtime::new().expect("runtime").block_on(f)
829 }
830
831 #[test]
832 fn a_run_is_due_after_its_grace_and_not_before() {
833 let now = ts("2026-09-05T00:00:00Z");
834 let grace = 600;
835 let old = now - SignedDuration::new(601, 0);
836 let fresh = now - SignedDuration::new(599, 0);
837 assert!(due(now, old, grace));
838 assert!(!due(now, fresh, grace));
839 // Exactly at the edge: not yet due.
840 let edge = now - SignedDuration::new(600, 0);
841 assert!(!due(now, edge, grace));
842 // A zero grace folds everything, ever.
843 assert!(due(now, old, 0));
844 }
845
846 #[test]
847 fn rotate_from_moves_the_starting_point_as_the_cursor_advances() {
848 let ids: Vec<String> = ["a", "b", "c", "d", "e"]
849 .iter()
850 .map(|s| s.to_string())
851 .collect();
852
853 // A cursor of 0 starts at the front, same as an unrotated list.
854 assert_eq!(rotate_from(&ids, 0), ids);
855
856 // A cursor of 2 starts two ids further along, with the skipped
857 // front wrapping to the tail rather than being dropped.
858 let at_2 = rotate_from(&ids, 2);
859 assert_eq!(at_2, vec!["c", "d", "e", "a", "b"]);
860 for id in &ids {
861 assert!(at_2.contains(id));
862 }
863
864 // A cursor past the list's own length wraps rather than panicking -
865 // the caller never has to reduce it modulo anything itself.
866 assert_eq!(rotate_from(&ids, 7), rotate_from(&ids, 2));
867
868 // An empty list has no start point to compute and must not panic.
869 assert_eq!(rotate_from(&[], 0), Vec::<String>::new());
870 }
871
872 /// A fleet with more eligible runs than one pass can check must not park
873 /// the same handful at the front of the window forever: advancing the
874 /// cursor by exactly how many ids one pass actually looked at - the
875 /// arithmetic [`reconcile_external_merges`] itself does - walks every id
876 /// to the front within one full rotation, with no reliance on how often
877 /// or how regularly passes happen to run.
878 #[test]
879 fn advancing_the_cursor_by_the_window_size_gives_every_id_a_turn() {
880 let ids: Vec<String> = (0..12).map(|n| format!("run-{n}")).collect();
881 let cap = 5usize;
882 let mut cursor = 0usize;
883 let mut ever_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
884 for _ in 0..ids.len() {
885 let window: Vec<String> = rotate_from(&ids, cursor).into_iter().take(cap).collect();
886 ever_seen.extend(window.iter().cloned());
887 cursor = (cursor + window.len()) % ids.len();
888 }
889 assert_eq!(
890 ever_seen.len(),
891 ids.len(),
892 "every id must be checked at least once across a full rotation, whatever \
893 the cadence between passes"
894 );
895 }
896
897 #[test]
898 fn the_external_merge_cursor_round_trips_through_a_files_absence() {
899 let dir = tempfile::tempdir().unwrap();
900 let home = dir.path();
901
902 // Nothing written yet: starts at 0, not an error.
903 assert_eq!(read_external_merge_cursor(home), 0);
904
905 write_external_merge_cursor(home, 7);
906 assert_eq!(read_external_merge_cursor(home), 7);
907
908 // Anything unreadable as a plain number falls back to 0 rather than
909 // wedging the sweep on a corrupt file.
910 std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), "not a number").unwrap();
911 assert_eq!(read_external_merge_cursor(home), 0);
912 }
913
914 #[test]
915 fn a_run_qualifies_for_an_external_merge_check_only_when_blocked_unmerged_and_due() {
916 let now = ts("2026-09-05T00:00:00Z");
917 let grace = 600;
918 let old = now - SignedDuration::new(601, 0);
919 let fresh = now - SignedDuration::new(599, 0);
920
921 assert!(
922 eligible_for_external_merge_check(RunStatus::Blocked, false, old, now, grace),
923 "blocked, unmerged, and past its grace period is exactly the run this exists for"
924 );
925 assert!(
926 !eligible_for_external_merge_check(RunStatus::Blocked, false, fresh, now, grace),
927 "an operator mid-fix deserves the same grace window `fold_due` gives before \
928 the janitor starts asking GitHub about it"
929 );
930 assert!(
931 !eligible_for_external_merge_check(RunStatus::Blocked, true, old, now, grace),
932 "a run `land::land` already recorded a merge outcome for has its own answer \
933 already; this check is only for a run with nothing recorded at all"
934 );
935 assert!(
936 !eligible_for_external_merge_check(RunStatus::Stalled, false, old, now, grace),
937 "stalled is not blocked - it means the tally never reached quorum, which a \
938 pull request cannot fix"
939 );
940 assert!(
941 !eligible_for_external_merge_check(RunStatus::Ready, false, old, now, grace),
942 "ready has nothing to correct - it was never landed by design"
943 );
944 }
945
946 /// A `Blocked` run with a decided winner, so `land::find_external_merge`
947 /// has a branch to ask `gh` about instead of returning early for lack of
948 /// one - which is what makes an unreachable `/nonexistent/repo` fail
949 /// loudly (an `Err`, raising a notice) rather than silently (an early
950 /// `Ok(None)`, raising nothing) when this run's sweep is exercised.
951 fn write_blocked_run(runs: &Path, id: &str, updated_at: Timestamp) {
952 use crate::run::{Candidate, Tally};
953 use std::collections::BTreeMap;
954
955 let mut state = RunState::new(
956 PathBuf::from("/nonexistent/repo"),
957 "main".to_owned(),
958 "0000000000000000000000000000000000000000".to_owned(),
959 String::new(),
960 crate::config::Config::default(),
961 );
962 state.id = id.to_owned();
963 state.status = RunStatus::Blocked;
964 state.updated_at = updated_at;
965 state.candidates.push(Candidate {
966 index: 0,
967 label: 'A',
968 agent: "agent".to_owned(),
969 branch: format!("magi/{id}/A"),
970 worktree: PathBuf::from("/nonexistent/repo"),
971 summary: String::new(),
972 stat: String::new(),
973 files: 0,
974 commits: 0,
975 empty: false,
976 failed: None,
977 verified_noop: None,
978 duration_ms: 0,
979 folded: false,
980 });
981 state.tally = Some(Tally {
982 first_choice: BTreeMap::from([('A', 1)]),
983 borda: BTreeMap::new(),
984 winner: 'A',
985 rankings: 1,
986 unanimous_initial: true,
987 deliberated: false,
988 changed_votes: 0,
989 unanimous_final: true,
990 tie_break: None,
991 judges: 1,
992 present: 1,
993 quorum: 1,
994 met_quorum: true,
995 uncontested: None,
996 });
997 std::fs::create_dir_all(runs.join(id)).unwrap();
998 std::fs::write(
999 runs.join(id).join("run.json"),
1000 serde_json::to_string_pretty(&state).unwrap(),
1001 )
1002 .unwrap();
1003 }
1004
1005 /// No run here can be confirmed merged - one has no repository `gh` can
1006 /// even ask about, one has not sat blocked long enough, and one is
1007 /// claimed by a live daemon - so the sweep must leave every one of them
1008 /// exactly as it found them and never panic on the failures in between.
1009 #[tokio::test]
1010 async fn reconcile_external_merges_leaves_ineligible_and_unconfirmable_runs_alone() {
1011 let dir = tempfile::tempdir().unwrap();
1012 let runs = dir.path().join("runs");
1013 let home = dir.path().to_path_buf();
1014 std::fs::create_dir_all(&runs).unwrap();
1015
1016 let now = ts("2026-09-05T00:00:00Z");
1017 let disk = Disk {
1018 fold_grace_secs: 600,
1019 ..Disk::default()
1020 };
1021
1022 let due_id = "20260905-000000-blkd";
1023 write_blocked_run(&runs, due_id, ts("2026-08-01T00:00:00Z"));
1024
1025 let fresh_id = "20260905-000000-fres";
1026 write_blocked_run(&runs, fresh_id, now);
1027
1028 let live_id = "20260905-000000-live";
1029 write_blocked_run(&runs, live_id, ts("2026-08-01T00:00:00Z"));
1030 let mut status = crate::daemon::Status::new();
1031 status.current = vec![crate::daemon::Current {
1032 task: "20260905-000000-task".to_owned(),
1033 run: live_id.to_owned(),
1034 }];
1035 status.updated_at = now;
1036 crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
1037
1038 let reconciled = reconcile_external_merges(&runs, &home, &disk, now).await;
1039 assert_eq!(
1040 reconciled, 0,
1041 "an unreachable repository can never be confirmed merged"
1042 );
1043 for id in [due_id, fresh_id, live_id] {
1044 assert_eq!(
1045 read_meta(&runs, id).unwrap().status,
1046 RunStatus::Blocked,
1047 "{id} must be left exactly as it was found"
1048 );
1049 }
1050 }
1051
1052 /// The bug this exists to pin: a first version rotated on
1053 /// `now.as_second() % len`, which is fully determined by wall-clock time
1054 /// and nothing else. Two passes seconds apart - as they would be when a
1055 /// short poll interval and a fast pass alias onto the same handful of
1056 /// `now.as_second()` residues - landed on the *same* starting point and
1057 /// never covered a fleet bigger than the per-pass cap, however many
1058 /// times housekeeping ran. Persisting a cursor makes forward progress a
1059 /// function of how many ids got looked at, not of when the clock reads
1060 /// this pass happened to run.
1061 #[tokio::test]
1062 async fn reconcile_external_merges_covers_a_larger_fleet_across_repeated_passes_at_one_instant()
1063 {
1064 let dir = tempfile::tempdir().unwrap();
1065 let runs = dir.path().join("runs");
1066 let home = dir.path().to_path_buf();
1067 std::fs::create_dir_all(&runs).unwrap();
1068
1069 let now = ts("2026-09-05T00:00:00Z");
1070 let disk = Disk {
1071 fold_grace_secs: 600,
1072 ..Disk::default()
1073 };
1074 let old = ts("2026-08-01T00:00:00Z");
1075
1076 let ids: Vec<String> = (0..8).map(|n| format!("20260905-000000-r{n:03}")).collect();
1077 for id in &ids {
1078 write_blocked_run(&runs, id, old);
1079 }
1080
1081 let notices = crate::notices::Notices::at(home.join("notifications"));
1082
1083 // Two passes at the exact same `now`, exactly what a fast pass on a
1084 // short poll interval looks like. Each of the 8 unreachable-repo
1085 // runs raises its own notice the first time it is looked at, so the
1086 // count of distinct notices is a direct readout of how many distinct
1087 // ids have been checked so far.
1088 reconcile_external_merges(&runs, &home, &disk, now).await;
1089 let after_first = notices.list().len();
1090 assert_eq!(
1091 after_first, MAX_EXTERNAL_MERGE_CHECKS_PER_PASS,
1092 "the first pass checks exactly one cap's worth"
1093 );
1094
1095 reconcile_external_merges(&runs, &home, &disk, now).await;
1096 let after_second = notices.list().len();
1097 assert_eq!(
1098 after_second,
1099 ids.len(),
1100 "a second pass at the same instant must still reach every id the \
1101 first pass had no room for, not repeat the same cap's worth"
1102 );
1103 }
1104
1105 #[test]
1106 fn the_meta_reader_is_tolerant_of_everything_except_the_deciders() {
1107 let dir = tempfile::tempdir().unwrap();
1108 let runs = dir.path().join("runs");
1109 let id = "20260905-000000-abcd";
1110 std::fs::create_dir_all(runs.join(id)).unwrap();
1111 std::fs::write(
1112 runs.join(id).join("run.json"),
1113 r#"{"schema": 99, "id": "20260905-000000-abcd", "updated_at": "2026-09-05T00:00:00Z", "status": "ready", "junk_from_another_build": [1, 2, 3]}"#,
1114 )
1115 .unwrap();
1116 let meta = read_meta(&runs, id).expect("readable");
1117 assert_eq!(meta.status, RunStatus::Ready);
1118 assert_eq!(meta.updated_at, ts("2026-09-05T00:00:00Z"));
1119 assert!(read_meta(&runs, "nope").is_err(), "missing file unreadable");
1120 std::fs::write(runs.join(id).join("run.json"), "not json at all").unwrap();
1121 assert!(read_meta(&runs, id).is_err(), "garbage unreadable");
1122 }
1123
1124 #[test]
1125 fn fold_unreadable_releases_run_dir_and_worktrees() {
1126 let dir = tempfile::tempdir().unwrap();
1127 let runs = dir.path().join("runs");
1128 let wt = dir.path().join("wt");
1129 let id = "20260905-000000-abcd";
1130 std::fs::create_dir_all(runs.join(id)).unwrap();
1131 std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1132 std::fs::create_dir_all(wt.join("abcd")).unwrap();
1133 std::fs::write(wt.join("abcd").join("leftover"), b"x").unwrap();
1134
1135 let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold");
1136 assert_eq!(removed.len(), 2);
1137 assert!(!runs.join(id).exists(), "run dir gone");
1138 assert!(!wt.join("abcd").exists(), "worktrees gone");
1139
1140 // A prefix resolves like `run::resolve_id` does.
1141 std::fs::create_dir_all(runs.join(id)).unwrap();
1142 std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1143 std::fs::create_dir_all(wt.join("abcd")).unwrap();
1144 std::fs::write(wt.join("abcd").join("leftover"), b"x").unwrap();
1145 let removed = block_on(fold_unreadable(&runs, &wt, "20260905")).expect("by prefix");
1146 assert_eq!(removed.len(), 2);
1147 // Once gone, `id` cannot be resolved at all - same as `run::resolve_id`
1148 // on an id nothing on disk matches - so a repeat pass errors rather
1149 // than silently reporting nothing removed.
1150 assert!(
1151 block_on(fold_unreadable(&runs, &wt, id)).is_err(),
1152 "a run already gone cannot be resolved again"
1153 );
1154 }
1155
1156 #[test]
1157 fn prune_cache_sheds_the_oldest_generation_until_it_fits() {
1158 let home = tempfile::tempdir().unwrap();
1159 let dir = tempfile::tempdir().unwrap();
1160 // Same size, different age: only the age decides, and the newest
1161 // generation - the one the next build reuses - is what survives.
1162 fs::write(dir.path().join("old"), b"xx").unwrap();
1163 fs::write(dir.path().join("new"), b"yy").unwrap();
1164 touch(&dir.path().join("old"), 1_000_000);
1165 touch(&dir.path().join("new"), 2_000_000);
1166
1167 let out = prune_cache(home.path(), dir.path(), 2)
1168 .expect("prune")
1169 .expect("the cache is free");
1170 assert_eq!(out.files, 1, "one deletion is enough to reach the cap");
1171 assert_eq!(out.remaining, 2);
1172 assert!(!dir.path().join("old").exists(), "the older file went");
1173 assert!(dir.path().join("new").exists(), "the newer one stayed");
1174
1175 // A whole generation shares one timestamp tick, so the tie has to be
1176 // decided too: largest first, which reaches the cap in the fewest
1177 // deletions. Left to `read_dir` and an unstable sort this deleted
1178 // both files on Linux and one on Windows.
1179 let tied = tempfile::tempdir().unwrap();
1180 fs::write(tied.path().join("big"), b"xxxx").unwrap();
1181 fs::write(tied.path().join("small"), b"yy").unwrap();
1182 touch(&tied.path().join("big"), 1_000_000);
1183 touch(&tied.path().join("small"), 1_000_000);
1184 let out = prune_cache(home.path(), tied.path(), 2)
1185 .expect("prune")
1186 .expect("the cache is free");
1187 assert_eq!(out.files, 1, "the big one alone gets under the cap");
1188 assert_eq!(out.remaining, 2);
1189 assert!(tied.path().join("small").exists());
1190 }
1191
1192 #[test]
1193 fn prune_cache_if_over_limit_resolves_the_opt_outs_before_ever_measuring() {
1194 let home = tempfile::tempdir().unwrap();
1195 let dir = tempfile::tempdir().unwrap();
1196 fs::write(dir.path().join("big"), vec![0u8; 10]).unwrap();
1197
1198 let mut cfg = crate::config::Config::default();
1199 cfg.verify.gate = vec![format!(
1200 "CARGO_TARGET_DIR={} cargo make check",
1201 dir.path().display()
1202 )];
1203
1204 // A cap of `0` is the operator's opt-out: never measured, never
1205 // pruned, regardless of what is actually on disk.
1206 cfg.disk.cache_limit_bytes = 0;
1207 assert_eq!(
1208 prune_cache_if_over_limit(&cfg, home.path()).unwrap(),
1209 None,
1210 "a zero cap must not even look at the directory"
1211 );
1212 assert!(dir.path().join("big").exists());
1213
1214 // No `CARGO_TARGET_DIR` in either verify command: nothing to
1215 // aggregate, so there is nothing to prune either.
1216 let mut no_cache = crate::config::Config::default();
1217 no_cache.disk.cache_limit_bytes = 1;
1218 assert_eq!(
1219 prune_cache_if_over_limit(&no_cache, home.path()).unwrap(),
1220 None
1221 );
1222
1223 // Over the cap and configured: pruned exactly like `prune_cache`
1224 // itself would.
1225 cfg.disk.cache_limit_bytes = 1;
1226 let pruned = prune_cache_if_over_limit(&cfg, home.path())
1227 .unwrap()
1228 .expect("a real cache dir over its cap prunes");
1229 assert_eq!(pruned.files, 1);
1230 assert!(!dir.path().join("big").exists());
1231 }
1232
1233 /// Pin a file's mtime, so a test asserts the policy and not the runner's
1234 /// timestamp granularity.
1235 fn touch(path: &Path, secs: u64) {
1236 let f = fs::File::options().write(true).open(path).unwrap();
1237 f.set_times(fs::FileTimes::new().set_modified(
1238 std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs),
1239 ))
1240 .unwrap();
1241 }
1242
1243 /// The disk-full casualty: a run whose first save left `run.json.tmp` and
1244 /// nothing else. It has to be clearable, or the record is permanent.
1245 #[test]
1246 fn fold_unreadable_clears_a_run_whose_state_never_landed() {
1247 let dir = tempfile::tempdir().unwrap();
1248 let runs = dir.path().join("runs");
1249 let wt = dir.path().join("wt");
1250 let id = "20260904-014540-88c0";
1251 std::fs::create_dir_all(runs.join(id)).unwrap();
1252 std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
1253
1254 let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold by id");
1255 assert_eq!(removed, vec![format!("runs/{id}")]);
1256 assert!(!runs.join(id).exists(), "record gone");
1257
1258 // And by prefix, the way the deck and the phone address a run.
1259 std::fs::create_dir_all(runs.join(id)).unwrap();
1260 std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
1261 assert!(
1262 block_on(fold_unreadable(&runs, &wt, "88c0")).is_ok(),
1263 "by prefix"
1264 );
1265
1266 // A directory under `runs` that is not a run is never a fold target.
1267 std::fs::create_dir_all(runs.join("scratch")).unwrap();
1268 assert!(
1269 block_on(fold_unreadable(&runs, &wt, "scratch")).is_err(),
1270 "a stray directory is not a run"
1271 );
1272 }
1273
1274 #[test]
1275 fn fold_due_folds_terminal_runs_of_any_schema_but_leaves_genuinely_unreadable_ones() {
1276 let dir = tempfile::tempdir().unwrap();
1277 let runs = dir.path().join("runs");
1278 let wt = dir.path().join("wt");
1279 let home = dir.path().to_path_buf();
1280 let disk = Disk::default();
1281 let now = ts("2026-09-05T00:00:00Z");
1282
1283 // 1. Runnable (judging): never folded, however old.
1284 let judging = "20260801-000000-0001";
1285 write_meta(&runs, judging, "judging", "2026-08-01T00:00:00Z");
1286
1287 // 2. Finished but fresh: grace not elapsed. Within the default 6h
1288 // grace of `now`, so `fold_due` must stop at the freshness check
1289 // and never even reach `read_state` - `write_meta`'s minimal JSON
1290 // would fail that full parse anyway, and this case exists to
1291 // prove freshness is why the run survives, not an accident of the
1292 // fixture being unparseable as a whole `RunState`.
1293 let ready_fresh = "20260904-220000-0002";
1294 write_meta(&runs, ready_fresh, "ready", "2026-09-04T22:00:00Z");
1295
1296 // 3. Genuinely unreadable: broken JSON, not merely an unfamiliar
1297 // schema number. Left alone and counted - this is the one case
1298 // automatic housekeeping must never touch (see `fold_due`'s docs);
1299 // discarding it is an explicit operator action, not something a
1300 // background pass does.
1301 let garbage = "20260901-000000-0004";
1302 std::fs::create_dir_all(runs.join(garbage)).unwrap();
1303 std::fs::write(runs.join(garbage).join("run.json"), "not json").unwrap();
1304 std::fs::create_dir_all(wt.join("0004")).unwrap();
1305
1306 // 4. Finished, well past grace, current schema: the ordinary case
1307 // `fold_due` has always acted on.
1308 let due_ready = due_run(&runs, &wt, "20260801-000000-ffff", SCHEMA);
1309
1310 // 5. Finished, well past grace, but written by a schema number this
1311 // build no longer matches - the defect this task exists to fix.
1312 // It still parses cleanly, so only the version number differs, and
1313 // that alone must not block folding.
1314 let due_old_schema = due_run(&runs, &wt, "20260801-000000-eeee", SCHEMA - 1);
1315
1316 let (folded, unreadable) =
1317 block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
1318 assert_eq!(
1319 folded, 2,
1320 "both due, parseable runs fold regardless of their schema number"
1321 );
1322 assert_eq!(
1323 unreadable, 1,
1324 "only the run with broken JSON counts as unreadable"
1325 );
1326 assert!(runs.join(judging).exists(), "runnable never folded");
1327 assert!(runs.join(ready_fresh).exists(), "fresh never folded");
1328 assert!(runs.join(garbage).exists(), "unreadable record kept");
1329 assert!(wt.join("0004").exists(), "unreadable worktree kept");
1330 assert!(
1331 runs.join(&due_ready).exists(),
1332 "folding drops worktrees, not the record"
1333 );
1334 assert!(
1335 runs.join(&due_old_schema).exists(),
1336 "an old-schema record survives its fold exactly like a current one"
1337 );
1338 // `graph::fold_run` saves the state it just folded back to disk. That
1339 // write must land under this test's own `runs` - the argument it
1340 // passed to `fold_due`, not the process-global `run::home` - or a
1341 // fold that landed somewhere else entirely would still be counted
1342 // above as one of the two `folded` runs.
1343 for id in [&due_ready, &due_old_schema] {
1344 let saved = read_meta(&runs, id).expect("folded run still parses");
1345 assert_ne!(
1346 saved.updated_at,
1347 ts("2026-08-01T00:00:00Z"),
1348 "fold_run must have saved the updated state back through the \
1349 `runs` directory this test passed to fold_due"
1350 );
1351 }
1352 }
1353
1354 /// `[disk] auto_fold = false` must leave the janitor's fold-and-reclaim
1355 /// passes completely inert - a due run's worktree and record both
1356 /// survive exactly as if `housekeep` had never run at all. Cache pruning
1357 /// is a separate opt-out (`cache_limit_bytes`) and stays disabled here
1358 /// too, so this test is only ever about `auto_fold`.
1359 #[tokio::test]
1360 async fn housekeep_leaves_everything_alone_when_auto_fold_is_disabled() {
1361 let dir = tempfile::tempdir().unwrap();
1362 let runs = dir.path().join("runs");
1363 let wt = dir.path().join("wt");
1364 let home = dir.path().to_path_buf();
1365 crate::run::set_home(dir.path().to_path_buf());
1366
1367 let due_id = due_run(&runs, &wt, "20260801-000000-abcd", SCHEMA);
1368 std::fs::create_dir_all(wt.join("orphan").join("cand-A")).unwrap();
1369
1370 let mut cfg = crate::config::Config::default();
1371 cfg.disk.auto_fold = false;
1372 cfg.disk.cache_limit_bytes = 0;
1373
1374 let out = housekeep(&cfg, &home, &wt, &dir.path().join("repo"), Timestamp::now()).await;
1375
1376 assert_eq!(out.folded, 0);
1377 assert_eq!(out.unreadable, 0);
1378 assert_eq!(out.orphaned_worktrees, 0);
1379 assert!(
1380 runs.join(&due_id).exists(),
1381 "a due run's record survives untouched"
1382 );
1383 assert!(
1384 wt.join("orphan").exists(),
1385 "an orphaned worktree survives untouched: the reclaim pass never ran"
1386 );
1387 }
1388
1389 #[test]
1390 fn fold_orphaned_worktrees_removes_only_worktrees_no_run_claims_and_none_in_flight() {
1391 let dir = tempfile::tempdir().unwrap();
1392 let runs = dir.path().join("runs");
1393 let wt = dir.path().join("wt");
1394 let home = dir.path().to_path_buf();
1395
1396 // A run record exists for this one: its worktree is claimed, not
1397 // orphaned, however old the record.
1398 write_meta(
1399 &runs,
1400 "20260801-000000-aaaa",
1401 "ready",
1402 "2026-08-01T00:00:00Z",
1403 );
1404 std::fs::create_dir_all(wt.join("aaaa").join("cand-A")).unwrap();
1405
1406 // No run record at all, and nobody is working on it: this is the
1407 // leftover `fold_due` can never see, because it only ever walks
1408 // `runs/`.
1409 std::fs::create_dir_all(wt.join("bbbb").join("cand-A")).unwrap();
1410
1411 // No run record either, but a live daemon status names a run with
1412 // this short id - the save-timing gap between the daemon claiming a
1413 // task and `RunState::new` writing its first `run.json`. Must survive
1414 // untouched.
1415 std::fs::create_dir_all(wt.join("cccc")).unwrap();
1416
1417 // Not shaped like a run's short id at all - a scratch directory an
1418 // operator or another tool left in the same bay - so it is never a
1419 // reclaim target regardless of what runs claim it or not.
1420 std::fs::create_dir_all(wt.join("scratch")).unwrap();
1421
1422 // `now` pushed comfortably past `MIN_ORPHAN_AGE_SECS`, so a zero
1423 // grace - the same "always due" escape hatch `due` itself documents
1424 // - still reclaims once a worktree is genuinely old, without faking
1425 // an mtime: real directory creation just above is already in the
1426 // past relative to this `now`, by design rather than by timing.
1427 let now = Timestamp::now() + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
1428 let mut status = crate::daemon::Status::new();
1429 status.current = vec![crate::daemon::Current {
1430 task: "20260905-000000-t111".to_owned(),
1431 run: "20260905-000000-cccc".to_owned(),
1432 }];
1433 status.updated_at = now;
1434 crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
1435
1436 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
1437 assert_eq!(
1438 folded, 1,
1439 "only the truly orphaned, idle, bay-shaped worktree is removed"
1440 );
1441 assert!(wt.join("aaaa").exists(), "claimed by a run record");
1442 assert!(!wt.join("bbbb").exists(), "orphaned and idle: reclaimed");
1443 assert!(wt.join("cccc").exists(), "a run in flight is never touched");
1444 assert!(
1445 wt.join("scratch").exists(),
1446 "not shaped like a worktree bay, so never a reclaim target"
1447 );
1448 }
1449
1450 /// The gap this closes: `Runner::review` (`magi review`) creates the
1451 /// worktree with `git worktree add` before `RunState::save` ever writes a
1452 /// `run.json`, and that path never runs through the daemon's own `poll`
1453 /// loop at all, so `daemon::Status` never names it either. Without a
1454 /// grace window, a janitor pass landing in that gap would read the
1455 /// worktree as an orphan nothing is waiting on and delete a review still
1456 /// being set up.
1457 #[test]
1458 fn fold_orphaned_worktrees_leaves_a_freshly_created_bay_alone() {
1459 let dir = tempfile::tempdir().unwrap();
1460 let runs = dir.path().join("runs");
1461 let wt = dir.path().join("wt");
1462 let home = dir.path().to_path_buf();
1463
1464 std::fs::create_dir_all(wt.join("dddd").join("under-review")).unwrap();
1465
1466 let now = Timestamp::now();
1467 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 6 * 60 * 60, now));
1468 assert_eq!(
1469 folded, 0,
1470 "too fresh to tell apart from a run still being set up"
1471 );
1472 assert!(wt.join("dddd").exists());
1473 }
1474
1475 /// A fresh open question on `run`, stored and handed back for assertions.
1476 fn open_question(store: &Questions, run: &str) -> crate::ask::Question {
1477 let mut q = crate::ask::Question::new(
1478 run.to_owned(),
1479 "implement".to_owned(),
1480 "impl-A".to_owned(),
1481 "Which storage backend should the cache use?".to_owned(),
1482 String::new(),
1483 vec!["SQLite".to_owned(), "Redis".to_owned()],
1484 );
1485 store.put(&mut q).unwrap();
1486 q
1487 }
1488
1489 /// The exact ghost the phone showed: a run that already finished, with a
1490 /// question its dead seat asked still sitting `open` because it reached
1491 /// that status before `graph::Runner::settle_questions` existed (or
1492 /// missed it in the crash window `daemon::reclaim_orphaned_running`
1493 /// covers). This sweep is the second door to the same fact.
1494 #[test]
1495 fn a_finished_runs_open_question_is_swept_up() {
1496 let dir = tempfile::tempdir().unwrap();
1497 let runs = dir.path().join("runs");
1498 let store = Questions::at(dir.path().join("questions"));
1499
1500 let failed = "20260908-205802-c9eb";
1501 write_meta(&runs, failed, "failed", "2026-09-08T20:58:02Z");
1502 let failed_q = open_question(&store, failed);
1503
1504 let merged = "20260908-205501-ca67";
1505 write_meta(&runs, merged, "merged", "2026-09-08T20:55:01Z");
1506 let merged_q = open_question(&store, merged);
1507
1508 let n = abandon_settled_questions(&store, &runs);
1509 assert_eq!(n, 2, "both dead runs' questions are swept in one pass");
1510
1511 for (id, run) in [(&failed_q.id, failed), (&merged_q.id, merged)] {
1512 let back = store.get(id).unwrap();
1513 assert!(!back.status.open(), "{run} is done; nobody reads an answer");
1514 assert!(back.detail.contains(run), "{}", back.detail);
1515 }
1516 }
1517
1518 #[test]
1519 fn a_still_alive_runs_open_question_survives_the_sweep() {
1520 let dir = tempfile::tempdir().unwrap();
1521 let runs = dir.path().join("runs");
1522 let store = Questions::at(dir.path().join("questions"));
1523
1524 // `Blocked` and `Stalled` are `RunStatus::resumable`: the run can
1525 // still be picked back up, so its question may yet get a real
1526 // answer. A run still mid-competition is even more obviously alive.
1527 for (id, status) in [
1528 ("20260908-000000-b10c", "blocked"),
1529 ("20260908-000000-5ta1", "stalled"),
1530 ("20260908-000000-jud6", "judging"),
1531 ] {
1532 write_meta(&runs, id, status, "2026-09-08T00:00:00Z");
1533 let q = open_question(&store, id);
1534
1535 let n = abandon_settled_questions(&store, &runs);
1536 assert_eq!(n, 0, "{status} run is not done; nothing to sweep");
1537 assert!(
1538 store.get(&q.id).unwrap().status.open(),
1539 "{status} run's question must still be waiting"
1540 );
1541 }
1542 }
1543
1544 #[test]
1545 fn the_sweep_leaves_an_answered_question_and_an_unreadable_run_alone() {
1546 let dir = tempfile::tempdir().unwrap();
1547 let runs = dir.path().join("runs");
1548 let store = Questions::at(dir.path().join("questions"));
1549
1550 // Already decided: a sweep must never revisit it, whatever the run
1551 // that asked went on to become.
1552 let done = "20260908-000000-answ";
1553 write_meta(&runs, done, "failed", "2026-09-08T00:00:00Z");
1554 let mut answered = open_question(&store, done);
1555 answered
1556 .answer(crate::ask::Answer::Choice("SQLite".to_owned()))
1557 .unwrap();
1558 store.put(&mut answered).unwrap();
1559
1560 // No `run.json` at all for this one - deleted, or never landed.
1561 let gone = "20260908-000000-gone";
1562 let orphan = open_question(&store, gone);
1563
1564 assert_eq!(abandon_settled_questions(&store, &runs), 0);
1565 assert_eq!(
1566 store.get(&answered.id).unwrap().status,
1567 crate::ask::QuestionStatus::Answered,
1568 "a real answer is never overwritten by a sweep"
1569 );
1570 assert!(
1571 store.get(&orphan.id).unwrap().status.open(),
1572 "a run this sweep cannot read is left exactly as it was, not guessed at"
1573 );
1574 }
1575
1576 /// A grace of `0` is a legitimate, documented value for the operator's
1577 /// own `Disk::fold_grace_secs` - `due`'s "always due" case - but the
1578 /// freshness check this guards is not that policy, and must not collapse
1579 /// to it: a `0` handed straight through would reclaim a worktree the
1580 /// instant it exists, exactly the race `fold_orphaned_worktrees_leaves_a_
1581 /// freshly_created_bay_alone` exists to rule out, just with the operator
1582 /// having turned the other grace off instead of leaving it at its
1583 /// default.
1584 #[test]
1585 fn fold_orphaned_worktrees_floors_a_zero_grace_at_the_race_safe_minimum() {
1586 let dir = tempfile::tempdir().unwrap();
1587 let runs = dir.path().join("runs");
1588 let wt = dir.path().join("wt");
1589 let home = dir.path().to_path_buf();
1590
1591 std::fs::create_dir_all(wt.join("eeee").join("under-review")).unwrap();
1592
1593 // Too fresh, even with the grace argument at zero.
1594 let now = Timestamp::now();
1595 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
1596 assert_eq!(
1597 folded, 0,
1598 "a zero grace must not defeat the race-safety floor"
1599 );
1600 assert!(wt.join("eeee").exists());
1601
1602 // Once genuinely past the floor, a zero grace reclaims it - the
1603 // floor is a minimum, not a replacement policy that never fires.
1604 let later = now + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
1605 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, later));
1606 assert_eq!(folded, 1, "old enough now, regardless of the zero grace");
1607 assert!(!wt.join("eeee").exists());
1608 }
1609
1610 #[test]
1611 fn clear_abandoned_active_only_acts_once_dead_and_overrun() {
1612 let dir = tempfile::tempdir().unwrap();
1613 // Harmless if another test in this binary already pinned the global
1614 // home first (see `run::set_home`'s own doc): this test only checks
1615 // the in-memory mutation `clear_abandoned_active` makes, never a
1616 // write that landed under this exact directory.
1617 crate::run::set_home(dir.path().to_path_buf());
1618 let home = dir.path().to_path_buf();
1619 let now = ts("2026-09-14T12:00:00Z");
1620 let overrun_seat = || crate::run::ActiveSeat {
1621 node: "implement".to_owned(),
1622 started_at: now - SignedDuration::new(21_000, 0),
1623 timeout_secs: 3_600,
1624 attempt: 0,
1625 task: None,
1626 command: None,
1627 index: None,
1628 total: None,
1629 };
1630
1631 let mut state = RunState::new(
1632 PathBuf::from("/repo"),
1633 "main".to_owned(),
1634 "abc1234".to_owned(),
1635 "fixture".to_owned(),
1636 crate::config::Config::default(),
1637 );
1638 state.status = RunStatus::Implementing;
1639 state.active.insert("impl-A".to_owned(), overrun_seat());
1640
1641 // A seat still within its own budget: not provably dead yet, so this
1642 // must change nothing.
1643 let mut fresh = state.clone();
1644 fresh.active.insert(
1645 "impl-B".to_owned(),
1646 crate::run::ActiveSeat {
1647 node: "implement".to_owned(),
1648 started_at: now,
1649 timeout_secs: 3_600,
1650 attempt: 0,
1651 task: None,
1652 command: None,
1653 index: None,
1654 total: None,
1655 },
1656 );
1657 assert!(!clear_abandoned_active(&mut fresh, &home, now).unwrap());
1658 assert!(!fresh.active.is_empty());
1659 assert_eq!(fresh.status, RunStatus::Implementing);
1660
1661 let store = Questions::at(home.join("questions"));
1662 let q = open_question(&store, &state.id);
1663
1664 assert!(clear_abandoned_active(&mut state, &home, now).unwrap());
1665 assert!(state.active.is_empty());
1666 assert_eq!(state.status, RunStatus::Failed);
1667 assert!(
1668 !store.get(&q.id).unwrap().status.open(),
1669 "the abandoned seat's own open question must not keep badging the \
1670 operator until some later daemon startup notices it"
1671 );
1672 }
1673
1674 /// Write a whole `run.json` that magi can read, over the given state.
1675 fn write_meta(runs: &Path, id: &str, status: &str, updated_at: &str) {
1676 let day = &updated_at[..10];
1677 std::fs::create_dir_all(runs.join(id)).unwrap();
1678 let body = format!(
1679 r#"{{"schema": {SCHEMA}, "id": "{id}", "repo": "/nonexistent/repo", "base_branch": "main", "base_commit": "0000000000000000000000000000000000000000", "instruction": "", "created_at": "{day}T00:00:00Z", "updated_at": "{updated_at}", "status": "{status}", "seed": 1}}"#
1680 );
1681 std::fs::write(runs.join(id).join("run.json"), body).unwrap();
1682 }
1683
1684 /// Write a fully-formed, `Ready`, well-past-grace `run.json` tagged with
1685 /// an arbitrary schema number - so a test can write one this build's own
1686 /// `RunState::new` could never produce on its own. Returns the id.
1687 ///
1688 /// `wt` becomes this run's `graph.worktree_root`: left at the config
1689 /// default, `RunState::worktree_root` falls through to
1690 /// `run::default_worktree_root` - the operator's real `~/wt/magi` - and
1691 /// `graph::fold_run`'s second sweep would then `read_dir` and remove
1692 /// worktrees there instead of anything this test owns.
1693 fn due_run(runs: &Path, wt: &Path, id: &str, schema: u32) -> String {
1694 let mut config = crate::config::Config::default();
1695 config.graph.worktree_root = Some(wt.to_path_buf());
1696 let mut state = RunState::new(
1697 PathBuf::from("/nonexistent/repo"),
1698 "main".to_owned(),
1699 "0000000000000000000000000000000000000000".to_owned(),
1700 String::new(),
1701 config,
1702 );
1703 state.id = id.to_owned();
1704 state.status = RunStatus::Ready;
1705 state.updated_at = ts("2026-08-01T00:00:00Z");
1706 let mut value = serde_json::to_value(&state).unwrap();
1707 value["schema"] = serde_json::json!(schema);
1708 std::fs::create_dir_all(runs.join(id)).unwrap();
1709 std::fs::write(
1710 runs.join(id).join("run.json"),
1711 serde_json::to_string_pretty(&value).unwrap(),
1712 )
1713 .unwrap();
1714 id.to_owned()
1715 }
1716}