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