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, prune_dir};
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}
63
64/// Run the janitor: fold due runs, reclaim orphaned worktrees, prune stale
65/// worktree registrations, then prune the cache if it is over its cap.
66///
67/// Every part is best-effort; a jammed cache lock or a run whose worktree
68/// another borrower holds must not stop the rest. Errors are reported through
69/// `tracing::warn` - this is housekeeping, and the daemon keeps serving
70/// either way.
71pub async fn housekeep(
72    cfg: &crate::config::Config,
73    home: &Path,
74    worktrees_root: &Path,
75    repo: &Path,
76    now: Timestamp,
77) -> Housekeeping {
78    let mut out = Housekeeping::default();
79    if cfg.disk.auto_fold {
80        let runs = home.join("runs");
81        match fold_due(&runs, home, worktrees_root, &cfg.disk, now).await {
82            Ok((folded, unreadable)) => {
83                out.folded = folded;
84                out.unreadable = unreadable;
85            }
86            Err(e) => tracing::warn!("housekeep: fold due runs: {e:#}"),
87        }
88        out.orphaned_worktrees =
89            fold_orphaned_worktrees(&runs, worktrees_root, home, cfg.disk.fold_grace_secs, now)
90                .await;
91        // Best-effort in the same sense as everything else here: a repository
92        // this janitor pass has nothing to do with (or none at all, in a unit
93        // test) must not turn a `warn` into a reason to skip the rest.
94        if let Err(e) = crate::git::worktree_prune(repo).await {
95            tracing::warn!("housekeep: prune worktree registrations: {e:#}");
96        }
97    }
98    match prune_cache_if_over_limit(cfg) {
99        Ok(Some(pruned)) => {
100            out.cache_files = pruned.files;
101            out.cache_freed = pruned.freed;
102        }
103        Ok(None) => {}
104        Err(e) => tracing::warn!("housekeep: prune cache: {e:#}"),
105    }
106    // Unconditional, unlike the two passes above: this is not a disk policy
107    // with a cap or an opt-out, it is closing a gap `graph::Runner` itself
108    // cannot - a run that reached `Merged`/`Ready`/`Failed` before this
109    // cleanup existed, or whose process died between saving that status and
110    // abandoning the question it leaves behind (see `Runner::settle_questions`).
111    // Left alone, that question sits `open` forever: the owner's badge,
112    // banner and title all keep counting a decision nobody is left to read.
113    out.questions_abandoned =
114        abandon_settled_questions(&Questions::at(home.join("questions")), &home.join("runs"));
115    out
116}
117
118/// Abandon every open question whose run has already settled into a status
119/// nothing comes back from, worded with what the run became - the same
120/// cleanup `graph::Runner::settle_questions` runs the moment `status` lands
121/// there, for questions that missed it.
122///
123/// Scans questions rather than runs: the open list is normally short, and a
124/// run that never asked anything costs nothing here. A run this cannot read,
125/// deleted or written by a schema this build does not speak, is left alone
126/// the same as everywhere else in this module; the question stays open
127/// rather than guessed at.
128pub fn abandon_settled_questions(store: &Questions, runs: &Path) -> usize {
129    let waiting_on: BTreeSet<String> = store
130        .list()
131        .into_iter()
132        .filter(|q| q.status.open())
133        .map(|q| q.run)
134        .collect();
135    let mut abandoned = 0;
136    for run in waiting_on {
137        let Ok(meta) = read_meta(runs, &run) else {
138            continue;
139        };
140        match store.settle_run(&run, meta.status) {
141            Ok(n) => abandoned += n,
142            Err(e) => tracing::warn!("housekeep: abandon questions for {run}: {e:#}"),
143        }
144    }
145    abandoned
146}
147
148/// Fold every run that is finished, older than the grace period, and not being
149/// worked on; return `(folded, unreadable)`.
150///
151/// A run whose `run.json` genuinely cannot be parsed — missing fields, broken
152/// JSON, a schema newer than this build has ever heard of — is left exactly
153/// as it is. Automatic housekeeping cannot tell a mid-write file from one that
154/// will never parse again, and `<home>/runs/<id>/` is the evidence `magi
155/// stats` and the deck read; when unsure whether it is safe to touch, the
156/// janitor keeps rather than deletes (see the module docs). Discarding a
157/// record this unreadable is an explicit operator action (`magi fold`, or the
158/// equivalent phone route), never something that happens unattended. Every
159/// such skip is counted in the returned `unreadable` and logged through
160/// `tracing::warn` with the parse failure that caused it - silence here is
161/// exactly the failure mode that let 90 of 93 runs sit unfolded with nothing
162/// to show for it.
163///
164/// A run merely written by a *different* schema number is not unreadable: as
165/// long as `run.json` still parses, it folds like any other terminal run (see
166/// the module docs for why the two are different questions).
167///
168/// Runnable statuses and runs newer than the grace period are also left
169/// alone; folding them would throw away work that is still the answer to
170/// somebody's question. `Merged` runs forget their winner's worktree (the
171/// merge already landed it); `Ready` and `Failed` runs keep it.
172pub async fn fold_due(
173    runs: &Path,
174    home: &Path,
175    _worktrees_root: &Path,
176    disk: &Disk,
177    now: Timestamp,
178) -> Result<(usize, usize)> {
179    let mut folded = 0usize;
180    let mut unreadable = 0usize;
181    let mut ids: Vec<String> = std::fs::read_dir(runs)
182        .into_iter()
183        .flatten()
184        .flatten()
185        .filter(|e| e.path().join("run.json").is_file())
186        .map(|e| e.file_name().to_string_lossy().into_owned())
187        .collect();
188    ids.sort_unstable();
189    for id in ids {
190        if crate::daemon::is_working_on(home, &id, now) {
191            continue;
192        }
193        let meta = match read_meta(runs, &id) {
194            Ok(meta) => meta,
195            Err(e) => {
196                unreadable += 1;
197                tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
198                continue;
199            }
200        };
201        if meta.status.resumable() || !due(now, meta.updated_at, disk.fold_grace_secs) {
202            continue;
203        }
204        // `read_meta` already proved the file parses; `read_state` asks for
205        // the rest of the fields `graph::fold_run` needs (worktree paths,
206        // candidates, tally). A schema mismatch alone does not fail this -
207        // see the module docs - so reaching `Err` here means the JSON itself
208        // is broken in a way `read_meta` did not exercise, which is rare but
209        // not impossible (a body truncated between the two fields it reads
210        // and the rest). That must not cost every other run its turn through
211        // this loop, so it is a skip, not a `?`.
212        let mut state = match read_state(runs, &id) {
213            Ok(state) => state,
214            Err(e) => {
215                unreadable += 1;
216                tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
217                continue;
218            }
219        };
220        if state.schema != SCHEMA {
221            tracing::info!(
222                "housekeep: run {id} was written by schema {} (this build speaks {SCHEMA}); \
223                 folding it anyway",
224                state.schema
225            );
226        }
227        let drop_winner = state.status == RunStatus::Merged;
228        // One run's fold must not cost every later run its turn. A worktree
229        // another borrower holds, a branch git refuses to delete, a repository
230        // that has since moved: each is a reason this run cannot be folded
231        // now, and none is a reason to stop the pass. Left unfolded, it is
232        // simply due again next time; a `?` here stopped automatic folding
233        // permanently at the first such run (finding R3-1-1 of run 51a3).
234        match crate::graph::fold_run(&mut state, drop_winner).await {
235            Ok(_) => folded += 1,
236            Err(e) => tracing::warn!("housekeep: fold {id}: {e:#}"),
237        }
238    }
239    Ok((folded, unreadable))
240}
241
242/// Is `updated` old enough, measured against `now`, that the run may fold?
243///
244/// Pure; the janitor compares against wallclock, tests inject both sides. The
245/// comparison is strict, so a run exactly at the edge of its grace period is
246/// left alone one more pass — the same convention as [`crate::disk::over_limit`].
247pub fn due(now: Timestamp, updated: Timestamp, grace_secs: u64) -> bool {
248    now.duration_since(updated) > SignedDuration::new(grace_secs as i64, 0)
249}
250
251/// The two fields the janitor decides on, read with a serde that tolerates
252/// everything else about the run being unreadable.
253#[derive(Deserialize)]
254struct Meta {
255    status: RunStatus,
256    updated_at: Timestamp,
257}
258
259/// Read `status` and `updated_at` straight off the state file, asking for
260/// nothing else. `Err` when the file is missing, not parseable, or a status in
261/// a version this build does not speak - all of which mean "unreadable".
262fn read_meta(runs: &Path, id: &str) -> Result<Meta> {
263    let path = runs.join(id).join("run.json");
264    let body =
265        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
266    let meta: Meta =
267        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
268    Ok(meta)
269}
270
271/// Read a whole run state from a runs directory, for folding only.
272///
273/// Deliberately more permissive than [`RunState::load`], which this does not
274/// call: `load` backs `--resume` and every hand-driven command, where a
275/// schema this build disagrees with the *meaning* of must refuse outright
276/// rather than resume a review round or a tally against stale semantics
277/// (`RunState::SCHEMA`'s own docs list what has changed meaning at each
278/// bump). Folding recomputes nothing - it only reads worktree paths, branch
279/// names and a tally winner off the struct to remove them - so an old
280/// schema's values are exactly as good here as a current one's; every schema
281/// bump so far has only ever added a field or a variant, never repurposed an
282/// existing one, and serde already fills an added field's default when an
283/// older record has nothing to say about it. What this cannot tolerate, and
284/// what still surfaces as an `Err`, is `run.json` failing to parse at all.
285fn read_state(runs: &Path, id: &str) -> Result<RunState> {
286    let path = runs.join(id).join("run.json");
287    let body =
288        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
289    let state: RunState =
290        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
291    Ok(state)
292}
293
294/// Remove a run that cannot be read: its state directory under `runs` and its
295/// worktree directory under `worktrees_root`.
296///
297/// The state file is the only record of a run's repository and branches, so a
298/// run this unreadable is discarded at the filesystem level - there is no
299/// candidate list to fold first. The worktrees live under
300/// [`crate::run::default_worktree_root`] unless the run's config relocated
301/// them, which an unreadable run cannot tell us; the default location is
302/// removed, and anything the run placed elsewhere is a leftover for whoever
303/// knows where it went.
304///
305/// Deleting a worktree directory by hand leaves its registration in git, and a
306/// registered path cannot be re-`worktree add`-ed until it is pruned - so every
307/// worktree is unregistered from its repository first, best-effort, via the
308/// `gitdir:` link git keeps inside the directory.
309pub async fn fold_unreadable(runs: &Path, worktrees_root: &Path, id: &str) -> Result<Vec<String>> {
310    let resolved = resolve_id_path(runs, id)?;
311    let mut removed = Vec::new();
312    let run_dir = runs.join(&resolved);
313    if run_dir.exists() {
314        std::fs::remove_dir_all(&run_dir)
315            .with_context(|| format!("remove {}", run_dir.display()))?;
316        removed.push(format!("runs/{resolved}"));
317    }
318    let wt = worktrees_root.join(short_of(&resolved));
319    if wt.exists() {
320        crate::git::remove_worktree_from_linked(&wt).await;
321        for e in std::fs::read_dir(&wt).into_iter().flatten().flatten() {
322            crate::git::remove_worktree_from_linked(&e.path()).await;
323        }
324        std::fs::remove_dir_all(&wt).with_context(|| format!("remove {}", wt.display()))?;
325        removed.push(wt.to_string_lossy().into_owned());
326    }
327    Ok(removed)
328}
329
330/// Reclaim worktrees under `worktrees_root` that no run record in `runs`
331/// claims anymore, and return how many were removed.
332///
333/// [`fold_due`] only ever sees a worktree by walking `runs/` first, so a
334/// worktree whose run record is already gone — `magi run rm`, or a record
335/// deleted before its worktree — never enters that loop at all: nothing there
336/// is looking for it. This walks the worktree bay directly instead, and
337/// removes any `<short>` directory that no run id maps to.
338///
339/// Two things must never happen, and this checks both before ever touching a
340/// directory:
341///
342/// - **A worktree bay is never the only kind of thing under `worktrees_root`,
343///   and this must not assume it is.** A hand-placed scratch directory, or
344///   anything else an operator or another tool left in the same bay, has the
345///   same "no run claims it" shape as a genuine orphan but is not one -
346///   [`looks_like_a_worktree_bay`] is the same tag shape [`crate::run::is_run_id`]
347///   already requires of a real run's short id, and anything else is left
348///   alone regardless of what else is true about it.
349/// - **A worktree that was only just created might not have a `run.json` yet
350///   for a reason that has nothing to do with being orphaned.** `Runner::start`
351///   and `Runner::review` both create the worktree before the first
352///   `RunState::save` lands, and that gap - several `git` subprocesses wide -
353///   is invisible to [`crate::daemon::is_working_on_short`] whenever the run
354///   is not being driven through this daemon's own `poll` loop at all (a
355///   `magi review` invocation, for one). A directory whose own modification
356///   time is within `grace_secs` of `now` is left alone on that basis alone,
357///   the same margin [`fold_due`] gives a run before treating it as truly
358///   finished - long enough that no realistic gap between a `worktree add`
359///   and its `run.json` could ever be mistaken for one.
360///
361/// The one failure this must never cause is deleting the worktree of a run
362/// that is genuinely in flight. [`crate::daemon::is_working_on_short`] is the
363/// same liveness check [`fold_due`] trusts everywhere else in this module,
364/// checked by short id because there is no full id to compare here; when it
365/// cannot tell, this leaves the directory alone. Best-effort like the rest of
366/// housekeeping: one directory git or the filesystem refuses to give up is a
367/// `tracing::warn`, not a reason to abandon the rest of the pass.
368pub async fn fold_orphaned_worktrees(
369    runs: &Path,
370    worktrees_root: &Path,
371    home: &Path,
372    grace_secs: u64,
373    now: Timestamp,
374) -> usize {
375    let known: std::collections::HashSet<String> = std::fs::read_dir(runs)
376        .into_iter()
377        .flatten()
378        .flatten()
379        .map(|e| e.file_name().to_string_lossy().into_owned())
380        .filter(|name| crate::run::is_run_id(name))
381        .map(|id| short_of(&id).to_owned())
382        .collect();
383
384    let mut folded = 0usize;
385    for entry in std::fs::read_dir(worktrees_root)
386        .into_iter()
387        .flatten()
388        .flatten()
389    {
390        if !entry.path().is_dir() {
391            continue;
392        }
393        let short = entry.file_name().to_string_lossy().into_owned();
394        if !looks_like_a_worktree_bay(&short) {
395            continue;
396        }
397        if known.contains(&short) || crate::daemon::is_working_on_short(home, &short, now) {
398            continue;
399        }
400        let wt = entry.path();
401        if !stale_enough(&wt, grace_secs, now) {
402            continue;
403        }
404        crate::git::remove_worktree_from_linked(&wt).await;
405        for e in std::fs::read_dir(&wt).into_iter().flatten().flatten() {
406            crate::git::remove_worktree_from_linked(&e.path()).await;
407        }
408        match std::fs::remove_dir_all(&wt) {
409            Ok(()) => folded += 1,
410            Err(e) => tracing::warn!(
411                "housekeep: remove orphaned worktree {}: {e:#}",
412                wt.display()
413            ),
414        }
415    }
416    folded
417}
418
419/// Does `name` have the shape a run's own worktree bay is named with: the
420/// same 4-character alphanumeric tag [`crate::run::is_run_id`] requires of a
421/// full id's trailing block (see [`short_of`])?
422///
423/// Anything else under `worktrees_root` is not a bay this function reclaims
424/// at all, claimed or not - answering "does a run claim this?" about a
425/// directory that was never a run's worktree in the first place is exactly
426/// the wrong question to ask before deleting it.
427fn looks_like_a_worktree_bay(name: &str) -> bool {
428    name.len() == 4 && name.bytes().all(|b| b.is_ascii_alphanumeric())
429}
430
431/// Is `dir`'s own modification time old enough, against `grace_secs` and
432/// `now`, that its emptiness of a run record can be trusted rather than
433/// caught mid-creation?
434///
435/// A directory this pass cannot stat at all - a race with its own removal, a
436/// permission error - is treated as not yet stale: unreadable metadata is not
437/// evidence of anything, and the janitor already keeps rather than deletes
438/// whenever it cannot tell (see the module docs).
439///
440/// `grace_secs` is floored at [`MIN_ORPHAN_AGE_SECS`] regardless of what the
441/// caller passes: `0` is a documented, legitimate value for
442/// [`crate::config::Disk::fold_grace_secs`] (`due`'s own "always due" case),
443/// because that grace answers a policy question the operator owns - how long
444/// a *known, finished* run's worktree lingers before cleanup. Whether an
445/// orphan worktree is actually a race with `Runner::review`'s `git worktree
446/// add` landing before its `run.json` is not a policy question, and must not
447/// collapse to zero just because the operator turned the other grace off -
448/// that would defeat the very check meant to catch it.
449fn stale_enough(dir: &Path, grace_secs: u64, now: Timestamp) -> bool {
450    let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) else {
451        return false;
452    };
453    let Ok(ts) = Timestamp::try_from(modified) else {
454        return false;
455    };
456    due(now, ts, grace_secs.max(MIN_ORPHAN_AGE_SECS))
457}
458
459/// The floor under [`stale_enough`]'s grace, independent of
460/// [`crate::config::Disk::fold_grace_secs`].
461///
462/// Ample next to the race it guards: the gap between `Runner::start` or
463/// `Runner::review` creating a worktree and the first `RunState::save`
464/// landing is a handful of `git` subprocess calls, not minutes - but the
465/// janitor cannot tell "still mid-setup" from "orphaned" by any other signal
466/// for a run that never registers with `daemon::Status` at all (a `magi
467/// review` invocation, for one), so this is generous on purpose rather than
468/// tuned to the observed case.
469const MIN_ORPHAN_AGE_SECS: u64 = 5 * 60;
470
471/// Resolve an id or prefix against an explicit runs directory, exactly the way
472/// [`crate::run::resolve_id`] does against the global home.
473fn resolve_id_path(runs: &Path, prefix: &str) -> Result<String> {
474    // Keyed on the directory, not on a readable state file: the record this
475    // route exists to remove may be a lone `run.json.tmp` from a save that
476    // ran out of disk, and that is precisely the one a human needs a way to
477    // clear (see `crate::run::list_ids`).
478    if runs.join(prefix).is_dir() && crate::run::is_run_id(prefix) {
479        return Ok(prefix.to_owned());
480    }
481    let mut hits: Vec<String> = Vec::new();
482    for e in std::fs::read_dir(runs).into_iter().flatten().flatten() {
483        if !e.path().is_dir() {
484            continue;
485        }
486        let id = e.file_name().to_string_lossy().into_owned();
487        if crate::run::is_run_id(&id) && (id.starts_with(prefix) || id.ends_with(prefix)) {
488            hits.push(id);
489        }
490    }
491    match hits.len() {
492        1 => Ok(hits.into_iter().next().expect("exactly one hit")),
493        0 => bail!("no run matches `{prefix}`"),
494        _ => bail!(
495            "`{prefix}` matches {} runs: {}",
496            hits.len(),
497            hits.join(", ")
498        ),
499    }
500}
501
502/// `magi fold`'s recovery path for a run whose worktrees are already gone —
503/// so [`crate::graph::fold_run`] removed nothing — but whose `run.json` still
504/// lists active seats nobody is left to answer for: no live daemon claims the
505/// run, and every one of those seats has overrun its own timeout (see
506/// [`RunState::active_all_overrun`]). Clearing them and failing the run is
507/// what lets it be deleted afterward — [`RunState::ensure_can_delete`] only
508/// ever checks whether a live daemon is working on the run and whether its
509/// candidates are folded, not `status`, but a run stuck `implementing`
510/// forever with an empty worktree still reads as unresolved everywhere else
511/// (`magi show`, the deck, the phone) until this runs.
512///
513/// Returns `false` without changing anything when a live daemon still claims
514/// the run, or when some active seat has not actually overrun its budget yet
515/// — a run that is merely between waves must never be guessed at.
516pub fn clear_abandoned_active(state: &mut RunState, home: &Path, now: Timestamp) -> Result<bool> {
517    if crate::daemon::is_working_on(home, &state.id, now) || !state.active_all_overrun(now) {
518        return Ok(false);
519    }
520    state.abandon("fold");
521    state.save_under(home)?;
522    // The seat that asked is gone for good now - the same door
523    // `graph::Runner::settle_questions` closes the moment `status` lands
524    // somewhere non-resumable, see that method's own doc. Without this, an
525    // open question the abandoned seat left behind would keep badging the
526    // operator until the next daemon startup's `abandon_settled_questions`
527    // pass happened to notice it, or forever if nothing is running `magi
528    // serve` at all.
529    if let Err(e) = Questions::at(home.join("questions")).settle_run(&state.id, state.status) {
530        tracing::warn!("abandon questions for {}: {e:#}", state.id);
531    }
532    Ok(true)
533}
534
535/// Delete files from the shared build cache until it fits its cap.
536///
537/// See [`crate::disk::prune_dir`] for the oldest-first policy.
538pub fn prune_cache(cache: &Path, limit_bytes: u64) -> Result<Prune> {
539    prune_dir(cache, limit_bytes)
540}
541
542/// [`prune_cache`], but resolving the operator's opt-out and missing
543/// `CARGO_TARGET_DIR` first — the same two checks [`housekeep`]'s idle pass
544/// makes before ever measuring the cache, factored out so
545/// [`crate::daemon`]'s between-runs check (see the module's own doc for why
546/// congestion can make "idle" arrive too rarely to matter) makes them
547/// identically rather than growing its own copy that could drift. `Ok(None)`
548/// covers both a cap of `0` (see the module docs on `cache_limit_bytes`) and
549/// a config that renders no `CARGO_TARGET_DIR` to aggregate at all.
550pub fn prune_cache_if_over_limit(cfg: &crate::config::Config) -> Result<Option<Prune>> {
551    if cfg.disk.cache_limit_bytes == 0 {
552        return Ok(None);
553    }
554    let Some(cache) = cfg.cache_dir() else {
555        return Ok(None);
556    };
557    prune_cache(&cache, cfg.disk.cache_limit_bytes).map(Some)
558}
559
560/// The cache's path, size and cap, for `magi cache show` and the health view.
561/// `None` when the config declares no `CARGO_TARGET_DIR` to aggregate.
562///
563/// A cap of `0` means the operator opted out of pruning; the size is then
564/// reported but never acted on.
565pub fn cache_report(cfg: &crate::config::Config) -> Option<(PathBuf, u64, u64)> {
566    let cache = cfg.cache_dir()?;
567    Some((
568        cache.clone(),
569        cache_size(&cache),
570        cfg.disk.cache_limit_bytes,
571    ))
572}
573
574/// Size in bytes of the shared build cache.
575pub fn cache_size(cache: &Path) -> u64 {
576    dir_size(cache)
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582    use crate::config::Disk;
583    use std::fs;
584
585    fn ts(s: &str) -> Timestamp {
586        s.parse().expect("rfc3339")
587    }
588
589    fn block_on<F: std::future::Future>(f: F) -> F::Output {
590        tokio::runtime::Runtime::new().expect("runtime").block_on(f)
591    }
592
593    #[test]
594    fn a_run_is_due_after_its_grace_and_not_before() {
595        let now = ts("2026-09-05T00:00:00Z");
596        let grace = 600;
597        let old = now - SignedDuration::new(601, 0);
598        let fresh = now - SignedDuration::new(599, 0);
599        assert!(due(now, old, grace));
600        assert!(!due(now, fresh, grace));
601        // Exactly at the edge: not yet due.
602        let edge = now - SignedDuration::new(600, 0);
603        assert!(!due(now, edge, grace));
604        // A zero grace folds everything, ever.
605        assert!(due(now, old, 0));
606    }
607
608    #[test]
609    fn the_meta_reader_is_tolerant_of_everything_except_the_deciders() {
610        let dir = tempfile::tempdir().unwrap();
611        let runs = dir.path().join("runs");
612        let id = "20260905-000000-abcd";
613        std::fs::create_dir_all(runs.join(id)).unwrap();
614        std::fs::write(
615            runs.join(id).join("run.json"),
616            r#"{"schema": 99, "id": "20260905-000000-abcd", "updated_at": "2026-09-05T00:00:00Z", "status": "ready", "junk_from_another_build": [1, 2, 3]}"#,
617        )
618        .unwrap();
619        let meta = read_meta(&runs, id).expect("readable");
620        assert_eq!(meta.status, RunStatus::Ready);
621        assert_eq!(meta.updated_at, ts("2026-09-05T00:00:00Z"));
622        assert!(read_meta(&runs, "nope").is_err(), "missing file unreadable");
623        std::fs::write(runs.join(id).join("run.json"), "not json at all").unwrap();
624        assert!(read_meta(&runs, id).is_err(), "garbage unreadable");
625    }
626
627    #[test]
628    fn fold_unreadable_releases_run_dir_and_worktrees() {
629        let dir = tempfile::tempdir().unwrap();
630        let runs = dir.path().join("runs");
631        let wt = dir.path().join("wt");
632        let id = "20260905-000000-abcd";
633        std::fs::create_dir_all(runs.join(id)).unwrap();
634        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
635        std::fs::create_dir_all(wt.join("abcd")).unwrap();
636        std::fs::write(wt.join("abcd").join("leftover"), b"x").unwrap();
637
638        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold");
639        assert_eq!(removed.len(), 2);
640        assert!(!runs.join(id).exists(), "run dir gone");
641        assert!(!wt.join("abcd").exists(), "worktrees gone");
642
643        // A prefix resolves like `run::resolve_id` does.
644        std::fs::create_dir_all(runs.join(id)).unwrap();
645        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
646        std::fs::create_dir_all(wt.join("abcd")).unwrap();
647        std::fs::write(wt.join("abcd").join("leftover"), b"x").unwrap();
648        let removed = block_on(fold_unreadable(&runs, &wt, "20260905")).expect("by prefix");
649        assert_eq!(removed.len(), 2);
650        // Once gone, `id` cannot be resolved at all - same as `run::resolve_id`
651        // on an id nothing on disk matches - so a repeat pass errors rather
652        // than silently reporting nothing removed.
653        assert!(
654            block_on(fold_unreadable(&runs, &wt, id)).is_err(),
655            "a run already gone cannot be resolved again"
656        );
657    }
658
659    #[test]
660    fn prune_cache_sheds_the_oldest_generation_until_it_fits() {
661        let dir = tempfile::tempdir().unwrap();
662        // Same size, different age: only the age decides, and the newest
663        // generation - the one the next build reuses - is what survives.
664        fs::write(dir.path().join("old"), b"xx").unwrap();
665        fs::write(dir.path().join("new"), b"yy").unwrap();
666        touch(&dir.path().join("old"), 1_000_000);
667        touch(&dir.path().join("new"), 2_000_000);
668
669        let out = prune_cache(dir.path(), 2).expect("prune");
670        assert_eq!(out.files, 1, "one deletion is enough to reach the cap");
671        assert_eq!(out.remaining, 2);
672        assert!(!dir.path().join("old").exists(), "the older file went");
673        assert!(dir.path().join("new").exists(), "the newer one stayed");
674
675        // A whole generation shares one timestamp tick, so the tie has to be
676        // decided too: largest first, which reaches the cap in the fewest
677        // deletions. Left to `read_dir` and an unstable sort this deleted
678        // both files on Linux and one on Windows.
679        let tied = tempfile::tempdir().unwrap();
680        fs::write(tied.path().join("big"), b"xxxx").unwrap();
681        fs::write(tied.path().join("small"), b"yy").unwrap();
682        touch(&tied.path().join("big"), 1_000_000);
683        touch(&tied.path().join("small"), 1_000_000);
684        let out = prune_cache(tied.path(), 2).expect("prune");
685        assert_eq!(out.files, 1, "the big one alone gets under the cap");
686        assert_eq!(out.remaining, 2);
687        assert!(tied.path().join("small").exists());
688    }
689
690    #[test]
691    fn prune_cache_if_over_limit_resolves_the_opt_outs_before_ever_measuring() {
692        let dir = tempfile::tempdir().unwrap();
693        fs::write(dir.path().join("big"), vec![0u8; 10]).unwrap();
694
695        let mut cfg = crate::config::Config::default();
696        cfg.verify.gate = vec![format!(
697            "CARGO_TARGET_DIR={} cargo make check",
698            dir.path().display()
699        )];
700
701        // A cap of `0` is the operator's opt-out: never measured, never
702        // pruned, regardless of what is actually on disk.
703        cfg.disk.cache_limit_bytes = 0;
704        assert_eq!(
705            prune_cache_if_over_limit(&cfg).unwrap(),
706            None,
707            "a zero cap must not even look at the directory"
708        );
709        assert!(dir.path().join("big").exists());
710
711        // No `CARGO_TARGET_DIR` in either verify command: nothing to
712        // aggregate, so there is nothing to prune either.
713        let mut no_cache = crate::config::Config::default();
714        no_cache.disk.cache_limit_bytes = 1;
715        assert_eq!(prune_cache_if_over_limit(&no_cache).unwrap(), None);
716
717        // Over the cap and configured: pruned exactly like `prune_cache`
718        // itself would.
719        cfg.disk.cache_limit_bytes = 1;
720        let pruned = prune_cache_if_over_limit(&cfg)
721            .unwrap()
722            .expect("a real cache dir over its cap prunes");
723        assert_eq!(pruned.files, 1);
724        assert!(!dir.path().join("big").exists());
725    }
726
727    /// Pin a file's mtime, so a test asserts the policy and not the runner's
728    /// timestamp granularity.
729    fn touch(path: &Path, secs: u64) {
730        let f = fs::File::options().write(true).open(path).unwrap();
731        f.set_times(fs::FileTimes::new().set_modified(
732            std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs),
733        ))
734        .unwrap();
735    }
736
737    /// The disk-full casualty: a run whose first save left `run.json.tmp` and
738    /// nothing else. It has to be clearable, or the record is permanent.
739    #[test]
740    fn fold_unreadable_clears_a_run_whose_state_never_landed() {
741        let dir = tempfile::tempdir().unwrap();
742        let runs = dir.path().join("runs");
743        let wt = dir.path().join("wt");
744        let id = "20260904-014540-88c0";
745        std::fs::create_dir_all(runs.join(id)).unwrap();
746        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
747
748        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold by id");
749        assert_eq!(removed, vec![format!("runs/{id}")]);
750        assert!(!runs.join(id).exists(), "record gone");
751
752        // And by prefix, the way the deck and the phone address a run.
753        std::fs::create_dir_all(runs.join(id)).unwrap();
754        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
755        assert!(
756            block_on(fold_unreadable(&runs, &wt, "88c0")).is_ok(),
757            "by prefix"
758        );
759
760        // A directory under `runs` that is not a run is never a fold target.
761        std::fs::create_dir_all(runs.join("scratch")).unwrap();
762        assert!(
763            block_on(fold_unreadable(&runs, &wt, "scratch")).is_err(),
764            "a stray directory is not a run"
765        );
766    }
767
768    #[test]
769    fn fold_due_folds_terminal_runs_of_any_schema_but_leaves_genuinely_unreadable_ones() {
770        let dir = tempfile::tempdir().unwrap();
771        let runs = dir.path().join("runs");
772        let wt = dir.path().join("wt");
773        let home = dir.path().to_path_buf();
774        let disk = Disk::default();
775        let now = ts("2026-09-05T00:00:00Z");
776        // `graph::fold_run` (invoked below for the due, readable runs) saves
777        // through the process-global home; pinning it to this test's own
778        // directory is what keeps that write off the operator's real one (see
779        // `run::home`'s doc). Harmless if another test already pinned it
780        // first - this test never reads that global value back.
781        crate::run::set_home(dir.path().to_path_buf());
782
783        // 1. Runnable (judging): never folded, however old.
784        let judging = "20260801-000000-0001";
785        write_meta(&runs, judging, "judging", "2026-08-01T00:00:00Z");
786
787        // 2. Finished but fresh: grace not elapsed. Within the default 6h
788        //    grace of `now`, so `fold_due` must stop at the freshness check
789        //    and never even reach `read_state` - `write_meta`'s minimal JSON
790        //    would fail that full parse anyway, and this case exists to
791        //    prove freshness is why the run survives, not an accident of the
792        //    fixture being unparseable as a whole `RunState`.
793        let ready_fresh = "20260904-220000-0002";
794        write_meta(&runs, ready_fresh, "ready", "2026-09-04T22:00:00Z");
795
796        // 3. Genuinely unreadable: broken JSON, not merely an unfamiliar
797        //    schema number. Left alone and counted - this is the one case
798        //    automatic housekeeping must never touch (see `fold_due`'s docs);
799        //    discarding it is an explicit operator action, not something a
800        //    background pass does.
801        let garbage = "20260901-000000-0004";
802        std::fs::create_dir_all(runs.join(garbage)).unwrap();
803        std::fs::write(runs.join(garbage).join("run.json"), "not json").unwrap();
804        std::fs::create_dir_all(wt.join("0004")).unwrap();
805
806        // 4. Finished, well past grace, current schema: the ordinary case
807        //    `fold_due` has always acted on.
808        let due_ready = due_run(&runs, "20260801-000000-ffff", SCHEMA);
809
810        // 5. Finished, well past grace, but written by a schema number this
811        //    build no longer matches - the defect this task exists to fix.
812        //    It still parses cleanly, so only the version number differs, and
813        //    that alone must not block folding.
814        let due_old_schema = due_run(&runs, "20260801-000000-eeee", SCHEMA - 1);
815
816        let (folded, unreadable) =
817            block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
818        assert_eq!(
819            folded, 2,
820            "both due, parseable runs fold regardless of their schema number"
821        );
822        assert_eq!(
823            unreadable, 1,
824            "only the run with broken JSON counts as unreadable"
825        );
826        assert!(runs.join(judging).exists(), "runnable never folded");
827        assert!(runs.join(ready_fresh).exists(), "fresh never folded");
828        assert!(runs.join(garbage).exists(), "unreadable record kept");
829        assert!(wt.join("0004").exists(), "unreadable worktree kept");
830        assert!(
831            runs.join(&due_ready).exists(),
832            "folding drops worktrees, not the record"
833        );
834        assert!(
835            runs.join(&due_old_schema).exists(),
836            "an old-schema record survives its fold exactly like a current one"
837        );
838    }
839
840    #[test]
841    fn fold_orphaned_worktrees_removes_only_worktrees_no_run_claims_and_none_in_flight() {
842        let dir = tempfile::tempdir().unwrap();
843        let runs = dir.path().join("runs");
844        let wt = dir.path().join("wt");
845        let home = dir.path().to_path_buf();
846
847        // A run record exists for this one: its worktree is claimed, not
848        // orphaned, however old the record.
849        write_meta(
850            &runs,
851            "20260801-000000-aaaa",
852            "ready",
853            "2026-08-01T00:00:00Z",
854        );
855        std::fs::create_dir_all(wt.join("aaaa").join("cand-A")).unwrap();
856
857        // No run record at all, and nobody is working on it: this is the
858        // leftover `fold_due` can never see, because it only ever walks
859        // `runs/`.
860        std::fs::create_dir_all(wt.join("bbbb").join("cand-A")).unwrap();
861
862        // No run record either, but a live daemon status names a run with
863        // this short id - the save-timing gap between the daemon claiming a
864        // task and `RunState::new` writing its first `run.json`. Must survive
865        // untouched.
866        std::fs::create_dir_all(wt.join("cccc")).unwrap();
867
868        // Not shaped like a run's short id at all - a scratch directory an
869        // operator or another tool left in the same bay - so it is never a
870        // reclaim target regardless of what runs claim it or not.
871        std::fs::create_dir_all(wt.join("scratch")).unwrap();
872
873        // `now` pushed comfortably past `MIN_ORPHAN_AGE_SECS`, so a zero
874        // grace - the same "always due" escape hatch `due` itself documents
875        // - still reclaims once a worktree is genuinely old, without faking
876        // an mtime: real directory creation just above is already in the
877        // past relative to this `now`, by design rather than by timing.
878        let now = Timestamp::now() + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
879        let mut status = crate::daemon::Status::new();
880        status.current = vec![crate::daemon::Current {
881            task: "20260905-000000-t111".to_owned(),
882            run: "20260905-000000-cccc".to_owned(),
883        }];
884        status.updated_at = now;
885        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
886
887        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
888        assert_eq!(
889            folded, 1,
890            "only the truly orphaned, idle, bay-shaped worktree is removed"
891        );
892        assert!(wt.join("aaaa").exists(), "claimed by a run record");
893        assert!(!wt.join("bbbb").exists(), "orphaned and idle: reclaimed");
894        assert!(wt.join("cccc").exists(), "a run in flight is never touched");
895        assert!(
896            wt.join("scratch").exists(),
897            "not shaped like a worktree bay, so never a reclaim target"
898        );
899    }
900
901    /// The gap this closes: `Runner::review` (`magi review`) creates the
902    /// worktree with `git worktree add` before `RunState::save` ever writes a
903    /// `run.json`, and that path never runs through the daemon's own `poll`
904    /// loop at all, so `daemon::Status` never names it either. Without a
905    /// grace window, a janitor pass landing in that gap would read the
906    /// worktree as an orphan nothing is waiting on and delete a review still
907    /// being set up.
908    #[test]
909    fn fold_orphaned_worktrees_leaves_a_freshly_created_bay_alone() {
910        let dir = tempfile::tempdir().unwrap();
911        let runs = dir.path().join("runs");
912        let wt = dir.path().join("wt");
913        let home = dir.path().to_path_buf();
914
915        std::fs::create_dir_all(wt.join("dddd").join("under-review")).unwrap();
916
917        let now = Timestamp::now();
918        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 6 * 60 * 60, now));
919        assert_eq!(
920            folded, 0,
921            "too fresh to tell apart from a run still being set up"
922        );
923        assert!(wt.join("dddd").exists());
924    }
925
926    /// A fresh open question on `run`, stored and handed back for assertions.
927    fn open_question(store: &Questions, run: &str) -> crate::ask::Question {
928        let mut q = crate::ask::Question::new(
929            run.to_owned(),
930            "implement".to_owned(),
931            "impl-A".to_owned(),
932            "Which storage backend should the cache use?".to_owned(),
933            String::new(),
934            vec!["SQLite".to_owned(), "Redis".to_owned()],
935        );
936        store.put(&mut q).unwrap();
937        q
938    }
939
940    /// The exact ghost the phone showed: a run that already finished, with a
941    /// question its dead seat asked still sitting `open` because it reached
942    /// that status before `graph::Runner::settle_questions` existed (or
943    /// missed it in the crash window `daemon::reclaim_orphaned_running`
944    /// covers). This sweep is the second door to the same fact.
945    #[test]
946    fn a_finished_runs_open_question_is_swept_up() {
947        let dir = tempfile::tempdir().unwrap();
948        let runs = dir.path().join("runs");
949        let store = Questions::at(dir.path().join("questions"));
950
951        let failed = "20260908-205802-c9eb";
952        write_meta(&runs, failed, "failed", "2026-09-08T20:58:02Z");
953        let failed_q = open_question(&store, failed);
954
955        let merged = "20260908-205501-ca67";
956        write_meta(&runs, merged, "merged", "2026-09-08T20:55:01Z");
957        let merged_q = open_question(&store, merged);
958
959        let n = abandon_settled_questions(&store, &runs);
960        assert_eq!(n, 2, "both dead runs' questions are swept in one pass");
961
962        for (id, run) in [(&failed_q.id, failed), (&merged_q.id, merged)] {
963            let back = store.get(id).unwrap();
964            assert!(!back.status.open(), "{run} is done; nobody reads an answer");
965            assert!(back.detail.contains(run), "{}", back.detail);
966        }
967    }
968
969    #[test]
970    fn a_still_alive_runs_open_question_survives_the_sweep() {
971        let dir = tempfile::tempdir().unwrap();
972        let runs = dir.path().join("runs");
973        let store = Questions::at(dir.path().join("questions"));
974
975        // `Blocked` and `Stalled` are `RunStatus::resumable`: the run can
976        // still be picked back up, so its question may yet get a real
977        // answer. A run still mid-competition is even more obviously alive.
978        for (id, status) in [
979            ("20260908-000000-b10c", "blocked"),
980            ("20260908-000000-5ta1", "stalled"),
981            ("20260908-000000-jud6", "judging"),
982        ] {
983            write_meta(&runs, id, status, "2026-09-08T00:00:00Z");
984            let q = open_question(&store, id);
985
986            let n = abandon_settled_questions(&store, &runs);
987            assert_eq!(n, 0, "{status} run is not done; nothing to sweep");
988            assert!(
989                store.get(&q.id).unwrap().status.open(),
990                "{status} run's question must still be waiting"
991            );
992        }
993    }
994
995    #[test]
996    fn the_sweep_leaves_an_answered_question_and_an_unreadable_run_alone() {
997        let dir = tempfile::tempdir().unwrap();
998        let runs = dir.path().join("runs");
999        let store = Questions::at(dir.path().join("questions"));
1000
1001        // Already decided: a sweep must never revisit it, whatever the run
1002        // that asked went on to become.
1003        let done = "20260908-000000-answ";
1004        write_meta(&runs, done, "failed", "2026-09-08T00:00:00Z");
1005        let mut answered = open_question(&store, done);
1006        answered
1007            .answer(crate::ask::Answer::Choice("SQLite".to_owned()))
1008            .unwrap();
1009        store.put(&mut answered).unwrap();
1010
1011        // No `run.json` at all for this one - deleted, or never landed.
1012        let gone = "20260908-000000-gone";
1013        let orphan = open_question(&store, gone);
1014
1015        assert_eq!(abandon_settled_questions(&store, &runs), 0);
1016        assert_eq!(
1017            store.get(&answered.id).unwrap().status,
1018            crate::ask::QuestionStatus::Answered,
1019            "a real answer is never overwritten by a sweep"
1020        );
1021        assert!(
1022            store.get(&orphan.id).unwrap().status.open(),
1023            "a run this sweep cannot read is left exactly as it was, not guessed at"
1024        );
1025    }
1026
1027    /// A grace of `0` is a legitimate, documented value for the operator's
1028    /// own `Disk::fold_grace_secs` - `due`'s "always due" case - but the
1029    /// freshness check this guards is not that policy, and must not collapse
1030    /// to it: a `0` handed straight through would reclaim a worktree the
1031    /// instant it exists, exactly the race `fold_orphaned_worktrees_leaves_a_
1032    /// freshly_created_bay_alone` exists to rule out, just with the operator
1033    /// having turned the other grace off instead of leaving it at its
1034    /// default.
1035    #[test]
1036    fn fold_orphaned_worktrees_floors_a_zero_grace_at_the_race_safe_minimum() {
1037        let dir = tempfile::tempdir().unwrap();
1038        let runs = dir.path().join("runs");
1039        let wt = dir.path().join("wt");
1040        let home = dir.path().to_path_buf();
1041
1042        std::fs::create_dir_all(wt.join("eeee").join("under-review")).unwrap();
1043
1044        // Too fresh, even with the grace argument at zero.
1045        let now = Timestamp::now();
1046        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
1047        assert_eq!(
1048            folded, 0,
1049            "a zero grace must not defeat the race-safety floor"
1050        );
1051        assert!(wt.join("eeee").exists());
1052
1053        // Once genuinely past the floor, a zero grace reclaims it - the
1054        // floor is a minimum, not a replacement policy that never fires.
1055        let later = now + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
1056        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, later));
1057        assert_eq!(folded, 1, "old enough now, regardless of the zero grace");
1058        assert!(!wt.join("eeee").exists());
1059    }
1060
1061    #[test]
1062    fn clear_abandoned_active_only_acts_once_dead_and_overrun() {
1063        let dir = tempfile::tempdir().unwrap();
1064        // Harmless if another test in this binary already pinned the global
1065        // home first (see `run::set_home`'s own doc): this test only checks
1066        // the in-memory mutation `clear_abandoned_active` makes, never a
1067        // write that landed under this exact directory.
1068        crate::run::set_home(dir.path().to_path_buf());
1069        let home = dir.path().to_path_buf();
1070        let now = ts("2026-09-14T12:00:00Z");
1071        let overrun_seat = || crate::run::ActiveSeat {
1072            node: "implement".to_owned(),
1073            started_at: now - SignedDuration::new(21_000, 0),
1074            timeout_secs: 3_600,
1075            attempt: 0,
1076        };
1077
1078        let mut state = RunState::new(
1079            PathBuf::from("/repo"),
1080            "main".to_owned(),
1081            "abc1234".to_owned(),
1082            "fixture".to_owned(),
1083            crate::config::Config::default(),
1084        );
1085        state.status = RunStatus::Implementing;
1086        state.active.insert("impl-A".to_owned(), overrun_seat());
1087
1088        // A seat still within its own budget: not provably dead yet, so this
1089        // must change nothing.
1090        let mut fresh = state.clone();
1091        fresh.active.insert(
1092            "impl-B".to_owned(),
1093            crate::run::ActiveSeat {
1094                node: "implement".to_owned(),
1095                started_at: now,
1096                timeout_secs: 3_600,
1097                attempt: 0,
1098            },
1099        );
1100        assert!(!clear_abandoned_active(&mut fresh, &home, now).unwrap());
1101        assert!(!fresh.active.is_empty());
1102        assert_eq!(fresh.status, RunStatus::Implementing);
1103
1104        let store = Questions::at(home.join("questions"));
1105        let q = open_question(&store, &state.id);
1106
1107        assert!(clear_abandoned_active(&mut state, &home, now).unwrap());
1108        assert!(state.active.is_empty());
1109        assert_eq!(state.status, RunStatus::Failed);
1110        assert!(
1111            !store.get(&q.id).unwrap().status.open(),
1112            "the abandoned seat's own open question must not keep badging the \
1113             operator until some later daemon startup notices it"
1114        );
1115    }
1116
1117    /// Write a whole `run.json` that magi can read, over the given state.
1118    fn write_meta(runs: &Path, id: &str, status: &str, updated_at: &str) {
1119        let day = &updated_at[..10];
1120        std::fs::create_dir_all(runs.join(id)).unwrap();
1121        let body = format!(
1122            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}}"#
1123        );
1124        std::fs::write(runs.join(id).join("run.json"), body).unwrap();
1125    }
1126
1127    /// Write a fully-formed, `Ready`, well-past-grace `run.json` tagged with
1128    /// an arbitrary schema number - so a test can write one this build's own
1129    /// `RunState::new` could never produce on its own. Returns the id.
1130    fn due_run(runs: &Path, id: &str, schema: u32) -> String {
1131        let mut state = RunState::new(
1132            PathBuf::from("/nonexistent/repo"),
1133            "main".to_owned(),
1134            "0000000000000000000000000000000000000000".to_owned(),
1135            String::new(),
1136            crate::config::Config::default(),
1137        );
1138        state.id = id.to_owned();
1139        state.status = RunStatus::Ready;
1140        state.updated_at = ts("2026-08-01T00:00:00Z");
1141        let mut value = serde_json::to_value(&state).unwrap();
1142        value["schema"] = serde_json::json!(schema);
1143        std::fs::create_dir_all(runs.join(id)).unwrap();
1144        std::fs::write(
1145            runs.join(id).join("run.json"),
1146            serde_json::to_string_pretty(&value).unwrap(),
1147        )
1148        .unwrap();
1149        id.to_owned()
1150    }
1151}