Skip to main content

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