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    /// Run records that still called their pull request open after it was
68    /// merged or closed, and were rewritten (see
69    /// [`crate::land::repair_stale_pr_states`]).
70    pub stale_pr_states_repaired: usize,
71}
72
73/// Run the janitor: fold due runs, reclaim orphaned worktrees, prune stale
74/// worktree registrations, then prune the cache if it is over its cap.
75///
76/// Every part is best-effort; a jammed cache lock or a run whose worktree
77/// another borrower holds must not stop the rest. Errors are reported through
78/// `tracing::warn` - this is housekeeping, and the daemon keeps serving
79/// either way.
80pub async fn housekeep(
81    cfg: &crate::config::Config,
82    home: &Path,
83    worktrees_root: &Path,
84    repo: &Path,
85    now: Timestamp,
86) -> Housekeeping {
87    let mut out = Housekeeping::default();
88    crate::retention::sweep(home, &cfg.disk, now).await;
89    if cfg.disk.auto_fold {
90        let runs = home.join("runs");
91        match fold_due(&runs, home, worktrees_root, &cfg.disk, now).await {
92            Ok((folded, unreadable)) => {
93                out.folded = folded;
94                out.unreadable = unreadable;
95            }
96            Err(e) => {
97                tracing::warn!("housekeep: fold due runs: {e:#}");
98                // Stable wording: the reason varies per pass, and a changed
99                // message would relight the bell on every retry.
100                crate::notices::raise_in(
101                    home,
102                    crate::notices::Notice::warn(
103                        "housekeep:fold",
104                        "Automatic cleanup of finished runs failed; disk usage may keep growing.",
105                    ),
106                );
107            }
108        }
109        out.orphaned_worktrees =
110            fold_orphaned_worktrees(&runs, worktrees_root, home, cfg.disk.fold_grace_secs, now)
111                .await;
112        // Best-effort in the same sense as everything else here: a repository
113        // this janitor pass has nothing to do with (or none at all, in a unit
114        // test) must not turn a `warn` into a reason to skip the rest.
115        if let Err(e) = crate::git::worktree_prune(repo).await {
116            tracing::warn!("housekeep: prune worktree registrations: {e:#}");
117        }
118        out.external_merges_recorded = reconcile_external_merges(&runs, home, &cfg.disk, now).await;
119        // Bounded: a handful of forge lookups a pass keeps this cheap, and the
120        // pass is idempotent, so a backlog drains over several passes.
121        out.stale_pr_states_repaired = crate::land::repair_stale_pr_states(home, 5).await.0;
122    }
123    match prune_cache_if_over_limit(cfg, home) {
124        Ok(Some(pruned)) => {
125            out.cache_files = pruned.files;
126            out.cache_freed = pruned.freed;
127        }
128        Ok(None) => {}
129        Err(e) => tracing::warn!("housekeep: prune cache: {e:#}"),
130    }
131    // Unconditional, unlike the two passes above: this is not a disk policy
132    // with a cap or an opt-out, it is closing a gap `graph::Runner` itself
133    // cannot - a run that reached `Merged`/`Ready`/`Failed` before this
134    // cleanup existed, or whose process died between saving that status and
135    // abandoning the question it leaves behind (see `Runner::settle_questions`).
136    // Left alone, that question sits `open` forever: the owner's badge,
137    // banner and title all keep counting a decision nobody is left to read.
138    out.questions_abandoned =
139        abandon_settled_questions(&Questions::at(home.join("questions")), &home.join("runs"));
140    out
141}
142
143/// Abandon every open question whose run has already settled into a status
144/// nothing comes back from, worded with what the run became - the same
145/// cleanup `graph::Runner::settle_questions` runs the moment `status` lands
146/// there, for questions that missed it.
147///
148/// Scans questions rather than runs: the open list is normally short, and a
149/// run that never asked anything costs nothing here. A run this cannot read,
150/// deleted or written by a schema this build does not speak, is left alone
151/// the same as everywhere else in this module; the question stays open
152/// rather than guessed at.
153pub fn abandon_settled_questions(store: &Questions, runs: &Path) -> usize {
154    let waiting_on: BTreeSet<String> = store
155        .list()
156        .into_iter()
157        .filter(|q| q.status.open())
158        .map(|q| q.run)
159        .collect();
160    let mut abandoned = 0;
161    for run in waiting_on {
162        let Ok(meta) = read_meta(runs, &run) else {
163            continue;
164        };
165        match store.settle_run(&run, meta.status) {
166            Ok(n) => abandoned += n,
167            Err(e) => tracing::warn!("housekeep: abandon questions for {run}: {e:#}"),
168        }
169    }
170    abandoned
171}
172
173/// Fold every run that is finished, older than the grace period, and not being
174/// worked on; return `(folded, unreadable)`.
175///
176/// A run whose `run.json` genuinely cannot be parsed — missing fields, broken
177/// JSON, a schema newer than this build has ever heard of — is left exactly
178/// as it is. Automatic housekeeping cannot tell a mid-write file from one that
179/// will never parse again, and `<home>/runs/<id>/` is the evidence `magi
180/// stats` and the deck read; when unsure whether it is safe to touch, the
181/// janitor keeps rather than deletes (see the module docs). Discarding a
182/// record this unreadable is an explicit operator action (`magi fold`, or the
183/// equivalent phone route), never something that happens unattended. Every
184/// such skip is counted in the returned `unreadable` and logged through
185/// `tracing::warn` with the parse failure that caused it - silence here is
186/// exactly the failure mode that let 90 of 93 runs sit unfolded with nothing
187/// to show for it.
188///
189/// A run merely written by a *different* schema number is not unreadable: as
190/// long as `run.json` still parses, it folds like any other terminal run (see
191/// the module docs for why the two are different questions).
192///
193/// Runnable statuses and runs newer than the grace period are also left
194/// alone; folding them would throw away work that is still the answer to
195/// somebody's question. `Merged` runs forget their winner's worktree (the
196/// merge already landed it); `Ready` and `Failed` runs keep it.
197pub async fn fold_due(
198    runs: &Path,
199    home: &Path,
200    _worktrees_root: &Path,
201    disk: &Disk,
202    now: Timestamp,
203) -> Result<(usize, usize)> {
204    let mut folded = 0usize;
205    let mut unreadable = 0usize;
206    let mut ids: Vec<String> = std::fs::read_dir(runs)
207        .into_iter()
208        .flatten()
209        .flatten()
210        .filter(|e| e.path().join("run.json").is_file())
211        .map(|e| e.file_name().to_string_lossy().into_owned())
212        .collect();
213    ids.sort_unstable();
214    for id in ids {
215        if crate::daemon::is_working_on(home, &id, now) {
216            continue;
217        }
218        let meta = match read_meta(runs, &id) {
219            Ok(meta) => meta,
220            Err(e) => {
221                unreadable += 1;
222                tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
223                continue;
224            }
225        };
226        if meta.status.resumable() || !due(now, meta.updated_at, disk.fold_grace_secs) {
227            continue;
228        }
229        // `read_meta` already proved the file parses; `read_state` asks for
230        // the rest of the fields `graph::fold_run` needs (worktree paths,
231        // candidates, tally). A schema mismatch alone does not fail this -
232        // see the module docs - so reaching `Err` here means the JSON itself
233        // is broken in a way `read_meta` did not exercise, which is rare but
234        // not impossible (a body truncated between the two fields it reads
235        // and the rest). That must not cost every other run its turn through
236        // this loop, so it is a skip, not a `?`.
237        let mut state = match read_state(runs, &id) {
238            Ok(state) => state,
239            Err(e) => {
240                unreadable += 1;
241                tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
242                continue;
243            }
244        };
245        if let Some(reason) = crate::pr_recovery::source_retention_reason(home, &state) {
246            tracing::info!(%id, %reason, "housekeep: source retained; fold refused");
247            continue;
248        }
249        if state.schema != SCHEMA {
250            tracing::info!(
251                "housekeep: run {id} was written by schema {} (this build speaks {SCHEMA}); \
252                 folding it anyway",
253                state.schema
254            );
255        }
256        // `Merged`'s winner branch is safe to drop because it already landed
257        // in the real target branch; `Superseded`'s winner branch is safe to
258        // drop for a different reason - a later attempt at the same task is
259        // what actually landed (or didn't), so *this* run's own winner is
260        // never going to be merged by anyone. Every other terminal status
261        // keeps the winner: `Ready`/`Blocked`/`Stalled`/`Failed`/`VerifiedNoop`
262        // may still have a human's decision pending on that exact branch.
263        // `AlreadyInBase` is the same: the change is on the base under other
264        // commit ids, so the branch holds nothing anyone still needs.
265        let drop_winner = matches!(
266            state.status,
267            RunStatus::Merged | RunStatus::Superseded | RunStatus::AlreadyInBase
268        );
269        // One run's fold must not cost every later run its turn. A worktree
270        // another borrower holds, a branch git refuses to delete, a repository
271        // that has since moved: each is a reason this run cannot be folded
272        // now, and none is a reason to stop the pass. Left unfolded, it is
273        // simply due again next time; a `?` here stopped automatic folding
274        // permanently at the first such run (finding R3-1-1 of run 51a3).
275        match crate::graph::fold_run(&mut state, drop_winner, home).await {
276            Ok(_) => folded += 1,
277            Err(e) => tracing::warn!("housekeep: fold {id}: {e:#}"),
278        }
279    }
280    Ok((folded, unreadable))
281}
282
283/// What one [`fetch_origins`] pass did.
284#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
285pub struct FetchReport {
286    /// Repos whose fetch succeeded.
287    pub fetched: usize,
288    /// Repos with no `origin` remote, skipped.
289    pub no_origin: usize,
290    /// Repos whose fetch failed or timed out.
291    pub failed: usize,
292}
293
294/// Run `git fetch origin` in every checkout under `roots` (the set `magi
295/// repos` lists), so `origin/main` stays current.
296///
297/// Fetch only: never a checkout, merge or fast-forward, so no HEAD, branch or
298/// working tree moves. Best-effort like [`fold_due`]: a repo with no `origin`
299/// is skipped silently, a failure or timeout is a warning, and the pass never
300/// errors. `stop` is checked between repos.
301pub async fn fetch_origins(
302    roots: &[PathBuf],
303    per_repo: std::time::Duration,
304    stop: impl Fn() -> bool,
305) -> FetchReport {
306    let mut report = FetchReport::default();
307    for repo in crate::repos::scan(roots) {
308        if stop() {
309            break;
310        }
311        match crate::git::git_raw(&repo.path, &["remote", "get-url", "origin"]).await {
312            Ok(out) if out.ok() => {}
313            _ => {
314                report.no_origin += 1;
315                continue;
316            }
317        }
318        match crate::git::fetch_origin(&repo.path, per_repo).await {
319            Ok(()) => report.fetched += 1,
320            Err(e) => {
321                tracing::warn!("fetch origin in {}: {e:#}", repo.name);
322                report.failed += 1;
323            }
324        }
325    }
326    report
327}
328
329/// Is `updated` old enough, measured against `now`, that the run may fold?
330///
331/// Pure; the janitor compares against wallclock, tests inject both sides. The
332/// comparison is strict, so a run exactly at the edge of its grace period is
333/// left alone one more pass — the same convention as [`crate::disk::over_limit`].
334pub fn due(now: Timestamp, updated: Timestamp, grace_secs: u64) -> bool {
335    now.duration_since(updated) > SignedDuration::new(grace_secs as i64, 0)
336}
337
338/// The two fields the janitor decides on, read with a serde that tolerates
339/// everything else about the run being unreadable.
340#[derive(Deserialize)]
341struct Meta {
342    status: RunStatus,
343    updated_at: Timestamp,
344}
345
346/// Read `status` and `updated_at` straight off the state file, asking for
347/// nothing else. `Err` when the file is missing, not parseable, or a status in
348/// a version this build does not speak - all of which mean "unreadable".
349fn read_meta(runs: &Path, id: &str) -> Result<Meta> {
350    let path = runs.join(id).join("run.json");
351    let body =
352        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
353    let meta: Meta =
354        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
355    Ok(meta)
356}
357
358/// Runs checked against GitHub in one janitor pass, at most.
359///
360/// A fleet with many stuck runs must not turn every idle tick into a burst of
361/// `gh pr list` calls; a run left unchecked this pass is checked again next
362/// pass, same as an unfolded due run is.
363const MAX_EXTERNAL_MERGE_CHECKS_PER_PASS: usize = 5;
364
365/// The fields [`reconcile_external_merges`] filters on before paying for a
366/// full [`RunState`] parse or a `gh` round trip.
367#[derive(Deserialize)]
368struct ExternalMergeMeta {
369    status: RunStatus,
370    updated_at: Timestamp,
371    #[serde(default)]
372    merge: Option<crate::run::MergeOutcome>,
373}
374
375fn read_external_merge_meta(runs: &Path, id: &str) -> Result<ExternalMergeMeta> {
376    let path = runs.join(id).join("run.json");
377    let body =
378        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
379    let meta: ExternalMergeMeta =
380        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
381    Ok(meta)
382}
383
384/// Is a run worth asking GitHub about?
385///
386/// Pure, so the filter itself is assertable without a fixture that writes
387/// `run.json` files or spawns `gh`. Narrower than "blocked": `merge_recorded`
388/// excludes a run `land::land` already finished landing (successfully or
389/// not) - that path already carries its own record of what happened - and
390/// `due` gives an operator who is about to fix a run by hand a grace window
391/// before the janitor starts asking the same question about it.
392pub fn eligible_for_external_merge_check(
393    status: RunStatus,
394    merge_recorded: bool,
395    updated_at: Timestamp,
396    now: Timestamp,
397    grace_secs: u64,
398) -> bool {
399    status == RunStatus::Blocked && !merge_recorded && due(now, updated_at, grace_secs)
400}
401
402/// Rotate `ids` so a fixed per-pass cap does not always land on the same
403/// prefix of the list, starting at `start` (already reduced modulo nothing -
404/// callers pass whatever a persisted cursor last recorded, and this takes it
405/// modulo `ids.len()` itself).
406///
407/// Pure: the offset is the caller's problem, not wall-clock time. An earlier
408/// version derived `start` from `now.as_second() % ids.len()`, which looked
409/// independent of any state to persist but is not actually independent of
410/// how often the janitor runs - a poll interval and a pass's own duration
411/// that alias onto the same handful of `now.as_second()` values (say, a
412/// ten-second poll and a pass that finishes in under a second) revisit only
413/// those same few residues forever and never advance into the rest of the
414/// list at all. [`reconcile_external_merges`] instead persists a cursor
415/// across passes ([`read_external_merge_cursor`] /
416/// [`write_external_merge_cursor`]) and advances it by exactly how many ids
417/// this pass actually looked at, which is the only quantity that is
418/// guaranteed to move forward pass over pass regardless of timing.
419fn rotate_from(ids: &[String], start: usize) -> Vec<String> {
420    if ids.is_empty() {
421        return Vec::new();
422    }
423    let start = start % ids.len();
424    ids[start..]
425        .iter()
426        .chain(ids[..start].iter())
427        .cloned()
428        .collect()
429}
430
431/// Where [`reconcile_external_merges`] remembers how far it got, so a fixed
432/// per-pass cap advances through a fleet's eligible runs pass over pass
433/// instead of camping on whichever ones happen to sort first.
434const EXTERNAL_MERGE_CURSOR_FILE: &str = "external-merge-cursor";
435
436/// `0` for anything this cannot read as a plain number - a first run, a
437/// corrupt or missing file, a build that has never written one - which is
438/// exactly as good a starting point as any: the cursor's whole job is to
439/// keep moving, not to encode any particular position as meaningful.
440fn read_external_merge_cursor(home: &Path) -> usize {
441    std::fs::read_to_string(home.join(EXTERNAL_MERGE_CURSOR_FILE))
442        .ok()
443        .and_then(|s| s.trim().parse().ok())
444        .unwrap_or(0)
445}
446
447/// Best-effort, like every other write in this module's sweep: a failure to
448/// persist the cursor costs the fleet one pass's worth of forward progress
449/// on this sweep, never the run whose housekeeping it is racing to keep up
450/// with.
451fn write_external_merge_cursor(home: &Path, cursor: usize) {
452    if let Err(e) = std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), cursor.to_string()) {
453        tracing::warn!("housekeep: persist the external-merge sweep's cursor: {e:#}");
454    }
455}
456
457/// Close the gap `magi fold --merged` exists for, without waiting for an
458/// operator to notice and go find the pull request URL: a run that stopped
459/// `Blocked` with no `merge` recorded may have been merged anyway, by hand,
460/// on a pull request `land::land` never opened or never got to observe as
461/// merged. `land::find_external_merge` asks GitHub about the run's own
462/// winning branch, and only a pull request it can uniquely tie back to this
463/// run is ever acted on - see that function's own doc for what "uniquely"
464/// excludes.
465///
466/// A run this finds and fixes goes through
467/// [`crate::land::correct_confirmed_external_merge`] - the same correction
468/// `magi fold --merged` performs, minus the same-repo guard that command
469/// needs and this loop doesn't (see that function's own doc: the URL here
470/// was never operator-supplied, it came from asking `state.repo`'s own
471/// remote) - then through [`crate::graph::fold_run`] so it stops holding
472/// worktrees the moment it stops needing them. A run this cannot decide
473/// about - `gh` unreachable, more than one candidate pull
474/// request, nothing found at all - is left exactly as it is; only an error
475/// asking GitHub raises a notice, since "nothing found" is the ordinary,
476/// expected shape of a run that really is just blocked.
477async fn reconcile_external_merges(runs: &Path, home: &Path, disk: &Disk, now: Timestamp) -> usize {
478    let mut ids: Vec<String> = std::fs::read_dir(runs)
479        .into_iter()
480        .flatten()
481        .flatten()
482        .filter(|e| e.path().join("run.json").is_file())
483        .map(|e| e.file_name().to_string_lossy().into_owned())
484        .collect();
485    ids.sort_unstable();
486
487    // Every eligible id first, cheaply (a `Meta` read, no `gh`), then rotated
488    // before the cap is applied. Capping the sorted order directly would
489    // always land on the same lexicographic prefix - a fleet's oldest run ids
490    // - so a handful of long-blocked runs that never turn out to be merged
491    // would starve every id after them of a `gh` check, forever.
492    let mut eligible: Vec<String> = Vec::new();
493    for id in ids {
494        if crate::daemon::is_working_on(home, &id, now) {
495            continue;
496        }
497        let meta = match read_external_merge_meta(runs, &id) {
498            Ok(meta) => meta,
499            // Already counted as unreadable by `fold_due`'s own pass; not
500            // worth a second warning for the same file.
501            Err(_) => continue,
502        };
503        if eligible_for_external_merge_check(
504            meta.status,
505            meta.merge.is_some(),
506            meta.updated_at,
507            now,
508            disk.fold_grace_secs,
509        ) {
510            eligible.push(id);
511        }
512    }
513
514    if eligible.is_empty() {
515        return 0;
516    }
517    let cursor = read_external_merge_cursor(home);
518    let window: Vec<String> = rotate_from(&eligible, cursor)
519        .into_iter()
520        .take(MAX_EXTERNAL_MERGE_CHECKS_PER_PASS)
521        .collect();
522    // Advances by exactly how many ids this pass looked at, regardless of
523    // what came of looking - a run that turned out not to be merged after
524    // all must not be revisited before every other eligible run has had its
525    // own turn.
526    write_external_merge_cursor(home, (cursor + window.len()) % eligible.len());
527
528    let mut reconciled = 0usize;
529    for id in window {
530        let mut state = match read_state(runs, &id) {
531            Ok(state) => state,
532            Err(_) => continue,
533        };
534        match crate::land::find_external_merge(&state).await {
535            Ok(Some(found)) => {
536                match crate::land::correct_confirmed_external_merge(&mut state, &found.url).await {
537                    Ok(_) => {
538                        if let Err(e) = crate::graph::fold_run(&mut state, true, home).await {
539                            tracing::warn!(
540                                "housekeep: fold {id} after recording its external merge: {e:#}"
541                            );
542                        }
543                        reconciled += 1;
544                    }
545                    Err(e) => tracing::warn!(
546                        "housekeep: record external merge {} for {id}: {e:#}",
547                        found.url
548                    ),
549                }
550            }
551            Ok(None) => {}
552            Err(e) => {
553                tracing::warn!("housekeep: check external merge for {id}: {e:#}");
554                crate::notices::raise_in(
555                    home,
556                    crate::notices::Notice::warn(
557                        &format!("merged-unrecorded:{id}"),
558                        format!(
559                            "Run {id} is blocked with no recorded merge, and checking GitHub \
560                             for a merge failed; check by hand."
561                        ),
562                    )
563                    .link(crate::notices::Link::Run { id: id.clone() }),
564                );
565            }
566        }
567    }
568    reconciled
569}
570
571/// Read a whole run state from a runs directory, for folding only.
572///
573/// Deliberately more permissive than [`RunState::load`], which this does not
574/// call: `load` backs `--resume` and every hand-driven command, where a
575/// schema this build disagrees with the *meaning* of must refuse outright
576/// rather than resume a review round or a tally against stale semantics
577/// (`RunState::SCHEMA`'s own docs list what has changed meaning at each
578/// bump). Folding recomputes nothing - it only reads worktree paths, branch
579/// names and a tally winner off the struct to remove them - so an old
580/// schema's values are exactly as good here as a current one's; every schema
581/// bump so far has only ever added a field or a variant, never repurposed an
582/// existing one, and serde already fills an added field's default when an
583/// older record has nothing to say about it. What this cannot tolerate, and
584/// what still surfaces as an `Err`, is `run.json` failing to parse at all.
585fn read_state(runs: &Path, id: &str) -> Result<RunState> {
586    let path = runs.join(id).join("run.json");
587    let body =
588        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
589    let state: RunState =
590        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
591    Ok(state)
592}
593
594/// Remove only verified clean Git worktrees and empty directory scaffolding.
595/// Unknown files or unreadable Git state require recovery, never recursive deletion.
596async fn remove_clean_bay(root: &Path) -> Result<()> {
597    let mut pending = vec![root.to_path_buf()];
598    let mut directories = Vec::new();
599    let mut worktrees = Vec::new();
600    while let Some(path) = pending.pop() {
601        if path.join(".git").exists() {
602            if !crate::git::is_clean(&path).await? {
603                anyhow::bail!("uncommitted work in {}; recovery required", path.display());
604            }
605            worktrees.push(path);
606        } else {
607            for entry in std::fs::read_dir(&path)? {
608                let entry = entry?;
609                if !entry.file_type()?.is_dir() {
610                    anyhow::bail!(
611                        "unknown worktree content in {}; recovery required",
612                        path.display()
613                    );
614                }
615                pending.push(entry.path());
616            }
617            directories.push(path);
618        }
619    }
620    for path in worktrees {
621        if !crate::git::worktree_remove_clean(&path, &path).await? {
622            anyhow::bail!("clean worktree removal refused: {}", path.display());
623        }
624    }
625    for path in directories.into_iter().rev() {
626        std::fs::remove_dir(path)?;
627    }
628    Ok(())
629}
630
631/// Remove a run that cannot be read: its state directory under `runs` and its
632/// worktree directory under `worktrees_root`.
633///
634/// Inspect worktrees before deleting any state or artifacts. Only clean registered
635/// worktrees and empty directory scaffolding can be reclaimed; unknown or dirty
636/// content remains available for recovery. Nonstandard worktree roots remain the
637/// operator's responsibility when the state file cannot identify them.
638pub async fn fold_unreadable(runs: &Path, worktrees_root: &Path, id: &str) -> Result<Vec<String>> {
639    let resolved = resolve_id_path(runs, id)?;
640    let mut removed = Vec::new();
641    let run_dir = runs.join(&resolved);
642    let wt = worktrees_root.join(short_of(&resolved));
643    if wt.exists() {
644        remove_clean_bay(&wt).await?;
645        removed.push(wt.to_string_lossy().into_owned());
646    }
647    // Keep the recovery artifacts if any worktree could not be removed safely.
648    if run_dir.exists() {
649        std::fs::remove_dir_all(&run_dir)
650            .with_context(|| format!("remove {}", run_dir.display()))?;
651        removed.push(format!("runs/{resolved}"));
652    }
653    Ok(removed)
654}
655
656/// Reclaim worktrees under `worktrees_root` that no run record in `runs`
657/// claims anymore, and return how many were removed.
658///
659/// [`fold_due`] only ever sees a worktree by walking `runs/` first, so a
660/// worktree whose run record is already gone — `magi run rm`, or a record
661/// deleted before its worktree — never enters that loop at all: nothing there
662/// is looking for it. This walks the worktree bay directly instead, and
663/// removes any `<short>` directory that no run id maps to.
664///
665/// Two things must never happen, and this checks both before ever touching a
666/// directory:
667///
668/// - **A worktree bay is never the only kind of thing under `worktrees_root`,
669///   and this must not assume it is.** A hand-placed scratch directory, or
670///   anything else an operator or another tool left in the same bay, has the
671///   same "no run claims it" shape as a genuine orphan but is not one -
672///   [`looks_like_a_worktree_bay`] is the same tag shape [`crate::run::is_run_id`]
673///   already requires of a real run's short id, and anything else is left
674///   alone regardless of what else is true about it.
675/// - **A worktree that was only just created might not have a `run.json` yet
676///   for a reason that has nothing to do with being orphaned.** `Runner::start`
677///   and `Runner::review` both create the worktree before the first
678///   `RunState::save` lands, and that gap - several `git` subprocesses wide -
679///   is invisible to [`crate::daemon::is_working_on_short`] whenever the run
680///   is not being driven through this daemon's own `poll` loop at all (a
681///   `magi review` invocation, for one). A directory whose own modification
682///   time is within `grace_secs` of `now` is left alone on that basis alone,
683///   the same margin [`fold_due`] gives a run before treating it as truly
684///   finished - long enough that no realistic gap between a `worktree add`
685///   and its `run.json` could ever be mistaken for one.
686///
687/// The one failure this must never cause is deleting the worktree of a run
688/// that is genuinely in flight. [`crate::daemon::is_working_on_short`] is the
689/// same liveness check [`fold_due`] trusts everywhere else in this module,
690/// checked by short id because there is no full id to compare here; when it
691/// cannot tell, this leaves the directory alone. Best-effort like the rest of
692/// housekeeping: one directory git or the filesystem refuses to give up is a
693/// `tracing::warn`, not a reason to abandon the rest of the pass.
694pub async fn fold_orphaned_worktrees(
695    runs: &Path,
696    worktrees_root: &Path,
697    home: &Path,
698    grace_secs: u64,
699    now: Timestamp,
700) -> usize {
701    let known: std::collections::HashSet<String> = std::fs::read_dir(runs)
702        .into_iter()
703        .flatten()
704        .flatten()
705        .map(|e| e.file_name().to_string_lossy().into_owned())
706        .filter(|name| crate::run::is_run_id(name))
707        .map(|id| short_of(&id).to_owned())
708        .collect();
709
710    let mut folded = 0usize;
711    for entry in std::fs::read_dir(worktrees_root)
712        .into_iter()
713        .flatten()
714        .flatten()
715    {
716        if !entry.path().is_dir() {
717            continue;
718        }
719        let short = entry.file_name().to_string_lossy().into_owned();
720        if !looks_like_a_worktree_bay(&short) {
721            continue;
722        }
723        if known.contains(&short) || crate::daemon::is_working_on_short(home, &short, now) {
724            continue;
725        }
726        let wt = entry.path();
727        if !stale_enough(&wt, grace_secs, now) {
728            continue;
729        }
730        match remove_clean_bay(&wt).await {
731            Ok(()) => folded += 1,
732            Err(e) => tracing::warn!(
733                "housekeep: remove orphaned worktree {}: {e:#}",
734                wt.display()
735            ),
736        }
737    }
738    folded
739}
740
741/// Does `name` have the shape a run's own worktree bay is named with: the
742/// same 4-character alphanumeric tag [`crate::run::is_run_id`] requires of a
743/// full id's trailing block (see [`short_of`])?
744///
745/// Anything else under `worktrees_root` is not a bay this function reclaims
746/// at all, claimed or not - answering "does a run claim this?" about a
747/// directory that was never a run's worktree in the first place is exactly
748/// the wrong question to ask before deleting it.
749fn looks_like_a_worktree_bay(name: &str) -> bool {
750    name.len() == 4 && name.bytes().all(|b| b.is_ascii_alphanumeric())
751}
752
753/// Is `dir`'s own modification time old enough, against `grace_secs` and
754/// `now`, that its emptiness of a run record can be trusted rather than
755/// caught mid-creation?
756///
757/// A directory this pass cannot stat at all - a race with its own removal, a
758/// permission error - is treated as not yet stale: unreadable metadata is not
759/// evidence of anything, and the janitor already keeps rather than deletes
760/// whenever it cannot tell (see the module docs).
761///
762/// `grace_secs` is floored at [`MIN_ORPHAN_AGE_SECS`] regardless of what the
763/// caller passes: `0` is a documented, legitimate value for
764/// [`crate::config::Disk::fold_grace_secs`] (`due`'s own "always due" case),
765/// because that grace answers a policy question the operator owns - how long
766/// a *known, finished* run's worktree lingers before cleanup. Whether an
767/// orphan worktree is actually a race with `Runner::review`'s `git worktree
768/// add` landing before its `run.json` is not a policy question, and must not
769/// collapse to zero just because the operator turned the other grace off -
770/// that would defeat the very check meant to catch it.
771fn stale_enough(dir: &Path, grace_secs: u64, now: Timestamp) -> bool {
772    let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) else {
773        return false;
774    };
775    let Ok(ts) = Timestamp::try_from(modified) else {
776        return false;
777    };
778    due(now, ts, grace_secs.max(MIN_ORPHAN_AGE_SECS))
779}
780
781/// The floor under [`stale_enough`]'s grace, independent of
782/// [`crate::config::Disk::fold_grace_secs`].
783///
784/// Ample next to the race it guards: the gap between `Runner::start` or
785/// `Runner::review` creating a worktree and the first `RunState::save`
786/// landing is a handful of `git` subprocess calls, not minutes - but the
787/// janitor cannot tell "still mid-setup" from "orphaned" by any other signal
788/// for a run that never registers with `daemon::Status` at all (a `magi
789/// review` invocation, for one), so this is generous on purpose rather than
790/// tuned to the observed case.
791const MIN_ORPHAN_AGE_SECS: u64 = 5 * 60;
792
793/// Resolve an id or prefix against an explicit runs directory, exactly the way
794/// [`crate::run::resolve_id`] does against the global home.
795fn resolve_id_path(runs: &Path, prefix: &str) -> Result<String> {
796    // Keyed on the directory, not on a readable state file: the record this
797    // route exists to remove may be a lone `run.json.tmp` from a save that
798    // ran out of disk, and that is precisely the one a human needs a way to
799    // clear (see `crate::run::list_ids`).
800    if runs.join(prefix).is_dir() && crate::run::is_run_id(prefix) {
801        return Ok(prefix.to_owned());
802    }
803    let mut hits: Vec<String> = Vec::new();
804    for e in std::fs::read_dir(runs).into_iter().flatten().flatten() {
805        if !e.path().is_dir() {
806            continue;
807        }
808        let id = e.file_name().to_string_lossy().into_owned();
809        if crate::run::is_run_id(&id) && (id.starts_with(prefix) || id.ends_with(prefix)) {
810            hits.push(id);
811        }
812    }
813    match hits.len() {
814        1 => Ok(hits.into_iter().next().expect("exactly one hit")),
815        0 => bail!("no run matches `{prefix}`"),
816        _ => bail!(
817            "`{prefix}` matches {} runs: {}",
818            hits.len(),
819            hits.join(", ")
820        ),
821    }
822}
823
824/// `magi fold`'s recovery path for a run whose worktrees are already gone —
825/// so [`crate::graph::fold_run`] removed nothing — but whose `run.json` still
826/// lists active seats nobody is left to answer for: no live daemon claims the
827/// run, and every one of those seats has overrun its own timeout (see
828/// [`RunState::active_all_overrun`]). Clearing them and failing the run is
829/// what lets it be deleted afterward — [`RunState::ensure_can_delete`] only
830/// ever checks whether a live daemon is working on the run and whether its
831/// candidates are folded, not `status`, but a run stuck `implementing`
832/// forever with an empty worktree still reads as unresolved everywhere else
833/// (`magi show`, the deck, the phone) until this runs.
834///
835/// Returns `false` without changing anything when a live daemon still claims
836/// the run, or when some active seat has not actually overrun its budget yet
837/// — a run that is merely between waves must never be guessed at.
838pub fn clear_abandoned_active(state: &mut RunState, home: &Path, now: Timestamp) -> Result<bool> {
839    if crate::daemon::is_working_on(home, &state.id, now) || !state.active_all_overrun(now) {
840        return Ok(false);
841    }
842    state.abandon("fold");
843    state.save_under(home)?;
844    // The seat that asked is gone for good now - the same door
845    // `graph::Runner::settle_questions` closes the moment `status` lands
846    // somewhere non-resumable, see that method's own doc. Without this, an
847    // open question the abandoned seat left behind would keep badging the
848    // operator until the next daemon startup's `abandon_settled_questions`
849    // pass happened to notice it, or forever if nothing is running `magi
850    // serve` at all.
851    if let Err(e) = Questions::at(home.join("questions")).settle_run(&state.id, state.status) {
852        tracing::warn!("abandon questions for {}: {e:#}", state.id);
853    }
854    Ok(true)
855}
856
857/// Delete files from the shared build cache until it fits its cap — but only
858/// while nobody live is registered as using it. [`crate::cache::maintenance_prune`]
859/// takes out the same lease a build would, so a prune can never race a
860/// compile in flight (this run's own, another run's, or a human's `magi
861/// review`) into deleting a file that build still needs. `Ok(None)` when the
862/// cache is in use right now; the next pass catches it once the borrower
863/// releases it, the same way a cap of `0` or a missing `CARGO_TARGET_DIR`
864/// already meant "nothing to do this time" here.
865pub fn prune_cache(home: &Path, cache: &Path, limit_bytes: u64) -> Result<Option<Prune>> {
866    crate::cache::maintenance_prune(home, cache, limit_bytes)
867}
868
869/// [`prune_cache`], but resolving the operator's opt-out and missing
870/// `CARGO_TARGET_DIR` first — the same two checks [`housekeep`]'s idle pass
871/// makes before ever measuring the cache, factored out so
872/// [`crate::daemon`]'s between-runs check (see the module's own doc for why
873/// congestion can make "idle" arrive too rarely to matter) makes them
874/// identically rather than growing its own copy that could drift. `Ok(None)`
875/// covers a cap of `0` (see the module docs on `cache_limit_bytes`), a config
876/// that renders no `CARGO_TARGET_DIR` to aggregate at all, and a cache
877/// currently in use (see [`prune_cache`]).
878pub fn prune_cache_if_over_limit(
879    cfg: &crate::config::Config,
880    home: &Path,
881) -> Result<Option<Prune>> {
882    if cfg.disk.cache_limit_bytes == 0 {
883        return Ok(None);
884    }
885    let Some(cache) = cfg.cache_dir() else {
886        return Ok(None);
887    };
888    let limit = crate::disk::free_bytes(&cache)
889        .ok()
890        .map_or(cfg.disk.cache_limit_bytes, |free| {
891            crate::disk::pressure_limit(
892                dir_size(&cache),
893                cfg.disk.cache_limit_bytes,
894                cfg.disk.min_free_bytes,
895                free,
896            )
897        });
898    prune_cache(home, &cache, limit)
899}
900
901/// The cache's path, size and cap, for `magi cache show` and the health view.
902/// `None` when the config declares no `CARGO_TARGET_DIR` to aggregate.
903///
904/// A cap of `0` means the operator opted out of pruning; the size is then
905/// reported but never acted on.
906pub fn cache_report(cfg: &crate::config::Config) -> Option<(PathBuf, u64, u64)> {
907    let cache = cfg.cache_dir()?;
908    Some((
909        cache.clone(),
910        cache_size(&cache),
911        cfg.disk.cache_limit_bytes,
912    ))
913}
914
915/// Size in bytes of the shared build cache.
916pub fn cache_size(cache: &Path) -> u64 {
917    dir_size(cache)
918}
919
920#[cfg(test)]
921mod tests {
922
923    async fn sh(cwd: &Path, args: &[&str]) {
924        let out = crate::git::git_raw(cwd, args).await.expect("spawn git");
925        assert!(out.ok(), "git {args:?}: {}", out.stderr);
926    }
927
928    async fn commit(cwd: &Path, file: &str, body: &str) {
929        std::fs::write(cwd.join(file), body).unwrap();
930        sh(cwd, &["add", file]).await;
931        sh(
932            cwd,
933            &[
934                "-c",
935                "user.name=t",
936                "-c",
937                "user.email=t@example.com",
938                "commit",
939                "-q",
940                "-m",
941                body,
942            ],
943        )
944        .await;
945    }
946
947    const LONG: std::time::Duration = std::time::Duration::from_secs(30);
948
949    #[tokio::test]
950    async fn fetch_advances_origin_main_and_leaves_the_checkout_alone() {
951        let tmp = tempfile::tempdir().unwrap();
952        let t = tmp.path();
953        let bare = t.join("remote.git");
954        sh(
955            t,
956            &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
957        )
958        .await;
959        let dir = t.join("root/h/o/r");
960        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
961        sh(
962            t,
963            &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
964        )
965        .await;
966        sh(&dir, &["checkout", "-q", "-b", "main"]).await;
967        commit(&dir, "a.txt", "one").await;
968        sh(&dir, &["push", "-q", "origin", "main"]).await;
969        sh(&dir, &["checkout", "-q", "--detach"]).await;
970        std::fs::write(dir.join("a.txt"), "dirty").unwrap();
971
972        let other = t.join("other");
973        sh(
974            t,
975            &[
976                "clone",
977                "-q",
978                bare.to_str().unwrap(),
979                other.to_str().unwrap(),
980            ],
981        )
982        .await;
983        commit(&other, "b.txt", "two").await;
984        sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;
985
986        let rev = |d: PathBuf, r: &'static str| async move {
987            crate::git::git(&d, &["rev-parse", r]).await.unwrap()
988        };
989        let head = rev(dir.clone(), "HEAD").await;
990        let before = rev(dir.clone(), "origin/main").await;
991        let status = crate::git::git(&dir, &["status", "--porcelain"])
992            .await
993            .unwrap();
994
995        let r = fetch_origins(&[t.join("root")], LONG, || false).await;
996        assert_eq!(
997            r,
998            FetchReport {
999                fetched: 1,
1000                no_origin: 0,
1001                failed: 0
1002            }
1003        );
1004
1005        assert_ne!(rev(dir.clone(), "origin/main").await, before);
1006        assert_eq!(rev(dir.clone(), "HEAD").await, head);
1007        assert_eq!(
1008            crate::git::git(&dir, &["status", "--porcelain"])
1009                .await
1010                .unwrap(),
1011            status
1012        );
1013        assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "dirty");
1014    }
1015
1016    #[tokio::test]
1017    async fn fetch_never_writes_a_local_branch_whatever_the_configured_refspec() {
1018        let tmp = tempfile::tempdir().unwrap();
1019        let t = tmp.path();
1020        let bare = t.join("remote.git");
1021        sh(
1022            t,
1023            &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
1024        )
1025        .await;
1026        let dir = t.join("root/h/o/r");
1027        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
1028        sh(
1029            t,
1030            &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
1031        )
1032        .await;
1033        sh(&dir, &["checkout", "-q", "-b", "main"]).await;
1034        commit(&dir, "a.txt", "one").await;
1035        sh(&dir, &["push", "-q", "origin", "main"]).await;
1036        sh(&dir, &["checkout", "-q", "--detach"]).await;
1037        // A hostile mapping onto the local branch, and no origin/* at all.
1038        sh(
1039            &dir,
1040            &[
1041                "config",
1042                "remote.origin.fetch",
1043                "+refs/heads/main:refs/heads/main",
1044            ],
1045        )
1046        .await;
1047        let _ = crate::git::git_raw(&dir, &["update-ref", "-d", "refs/remotes/origin/main"]).await;
1048
1049        let other = t.join("other");
1050        sh(
1051            t,
1052            &[
1053                "clone",
1054                "-q",
1055                bare.to_str().unwrap(),
1056                other.to_str().unwrap(),
1057            ],
1058        )
1059        .await;
1060        commit(&other, "b.txt", "two").await;
1061        sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;
1062        let remote_tip = crate::git::git(&other, &["rev-parse", "HEAD"])
1063            .await
1064            .unwrap();
1065        let local_main = crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
1066            .await
1067            .unwrap();
1068
1069        let r = fetch_origins(&[t.join("root")], LONG, || false).await;
1070        assert_eq!(r.fetched, 1);
1071        assert_eq!(
1072            crate::git::git(&dir, &["rev-parse", "refs/remotes/origin/main"])
1073                .await
1074                .unwrap(),
1075            remote_tip
1076        );
1077        assert_eq!(
1078            crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
1079                .await
1080                .unwrap(),
1081            local_main
1082        );
1083    }
1084
1085    #[tokio::test]
1086    async fn fetch_skips_no_origin_and_survives_an_unreachable_origin() {
1087        let tmp = tempfile::tempdir().unwrap();
1088        let t = tmp.path();
1089        let root = t.join("root");
1090        let bare = t.join("remote.git");
1091        sh(t, &["init", "-q", "--bare", bare.to_str().unwrap()]).await;
1092
1093        let none = root.join("h/o/none");
1094        let dead = root.join("h/o/dead");
1095        let good = root.join("h/o/good");
1096        for d in [&none, &dead, &good] {
1097            std::fs::create_dir_all(d).unwrap();
1098            sh(d, &["init", "-q"]).await;
1099        }
1100        sh(
1101            &dead,
1102            &[
1103                "remote",
1104                "add",
1105                "origin",
1106                t.join("missing").to_str().unwrap(),
1107            ],
1108        )
1109        .await;
1110        sh(&good, &["remote", "add", "origin", bare.to_str().unwrap()]).await;
1111
1112        let r = fetch_origins(&[root], LONG, || false).await;
1113        assert_eq!(
1114            r,
1115            FetchReport {
1116                fetched: 1,
1117                no_origin: 1,
1118                failed: 1
1119            }
1120        );
1121    }
1122    use super::*;
1123    use crate::config::Disk;
1124    use std::fs;
1125
1126    fn ts(s: &str) -> Timestamp {
1127        s.parse().expect("rfc3339")
1128    }
1129
1130    fn block_on<F: std::future::Future>(f: F) -> F::Output {
1131        tokio::runtime::Runtime::new().expect("runtime").block_on(f)
1132    }
1133
1134    #[test]
1135    fn a_run_is_due_after_its_grace_and_not_before() {
1136        let now = ts("2026-09-05T00:00:00Z");
1137        let grace = 600;
1138        let old = now - SignedDuration::new(601, 0);
1139        let fresh = now - SignedDuration::new(599, 0);
1140        assert!(due(now, old, grace));
1141        assert!(!due(now, fresh, grace));
1142        // Exactly at the edge: not yet due.
1143        let edge = now - SignedDuration::new(600, 0);
1144        assert!(!due(now, edge, grace));
1145        // A zero grace folds everything, ever.
1146        assert!(due(now, old, 0));
1147    }
1148
1149    #[test]
1150    fn rotate_from_moves_the_starting_point_as_the_cursor_advances() {
1151        let ids: Vec<String> = ["a", "b", "c", "d", "e"]
1152            .iter()
1153            .map(|s| s.to_string())
1154            .collect();
1155
1156        // A cursor of 0 starts at the front, same as an unrotated list.
1157        assert_eq!(rotate_from(&ids, 0), ids);
1158
1159        // A cursor of 2 starts two ids further along, with the skipped
1160        // front wrapping to the tail rather than being dropped.
1161        let at_2 = rotate_from(&ids, 2);
1162        assert_eq!(at_2, vec!["c", "d", "e", "a", "b"]);
1163        for id in &ids {
1164            assert!(at_2.contains(id));
1165        }
1166
1167        // A cursor past the list's own length wraps rather than panicking -
1168        // the caller never has to reduce it modulo anything itself.
1169        assert_eq!(rotate_from(&ids, 7), rotate_from(&ids, 2));
1170
1171        // An empty list has no start point to compute and must not panic.
1172        assert_eq!(rotate_from(&[], 0), Vec::<String>::new());
1173    }
1174
1175    /// A fleet with more eligible runs than one pass can check must not park
1176    /// the same handful at the front of the window forever: advancing the
1177    /// cursor by exactly how many ids one pass actually looked at - the
1178    /// arithmetic [`reconcile_external_merges`] itself does - walks every id
1179    /// to the front within one full rotation, with no reliance on how often
1180    /// or how regularly passes happen to run.
1181    #[test]
1182    fn advancing_the_cursor_by_the_window_size_gives_every_id_a_turn() {
1183        let ids: Vec<String> = (0..12).map(|n| format!("run-{n}")).collect();
1184        let cap = 5usize;
1185        let mut cursor = 0usize;
1186        let mut ever_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1187        for _ in 0..ids.len() {
1188            let window: Vec<String> = rotate_from(&ids, cursor).into_iter().take(cap).collect();
1189            ever_seen.extend(window.iter().cloned());
1190            cursor = (cursor + window.len()) % ids.len();
1191        }
1192        assert_eq!(
1193            ever_seen.len(),
1194            ids.len(),
1195            "every id must be checked at least once across a full rotation, whatever \
1196             the cadence between passes"
1197        );
1198    }
1199
1200    #[test]
1201    fn the_external_merge_cursor_round_trips_through_a_files_absence() {
1202        let dir = tempfile::tempdir().unwrap();
1203        let home = dir.path();
1204
1205        // Nothing written yet: starts at 0, not an error.
1206        assert_eq!(read_external_merge_cursor(home), 0);
1207
1208        write_external_merge_cursor(home, 7);
1209        assert_eq!(read_external_merge_cursor(home), 7);
1210
1211        // Anything unreadable as a plain number falls back to 0 rather than
1212        // wedging the sweep on a corrupt file.
1213        std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), "not a number").unwrap();
1214        assert_eq!(read_external_merge_cursor(home), 0);
1215    }
1216
1217    #[test]
1218    fn a_run_qualifies_for_an_external_merge_check_only_when_blocked_unmerged_and_due() {
1219        let now = ts("2026-09-05T00:00:00Z");
1220        let grace = 600;
1221        let old = now - SignedDuration::new(601, 0);
1222        let fresh = now - SignedDuration::new(599, 0);
1223
1224        assert!(
1225            eligible_for_external_merge_check(RunStatus::Blocked, false, old, now, grace),
1226            "blocked, unmerged, and past its grace period is exactly the run this exists for"
1227        );
1228        assert!(
1229            !eligible_for_external_merge_check(RunStatus::Blocked, false, fresh, now, grace),
1230            "an operator mid-fix deserves the same grace window `fold_due` gives before \
1231             the janitor starts asking GitHub about it"
1232        );
1233        assert!(
1234            !eligible_for_external_merge_check(RunStatus::Blocked, true, old, now, grace),
1235            "a run `land::land` already recorded a merge outcome for has its own answer \
1236             already; this check is only for a run with nothing recorded at all"
1237        );
1238        assert!(
1239            !eligible_for_external_merge_check(RunStatus::Stalled, false, old, now, grace),
1240            "stalled is not blocked - it means the tally never reached quorum, which a \
1241             pull request cannot fix"
1242        );
1243        assert!(
1244            !eligible_for_external_merge_check(RunStatus::Ready, false, old, now, grace),
1245            "ready has nothing to correct - it was never landed by design"
1246        );
1247        assert!(
1248            !eligible_for_external_merge_check(RunStatus::Superseded, false, old, now, grace),
1249            "a superseded run's task already has its answer from a later attempt; \
1250             there is nothing left for GitHub to confirm here"
1251        );
1252    }
1253
1254    /// A `Blocked` run with a decided winner, so `land::find_external_merge`
1255    /// has a branch to ask `gh` about instead of returning early for lack of
1256    /// one - which is what makes an unreachable `/nonexistent/repo` fail
1257    /// loudly (an `Err`, raising a notice) rather than silently (an early
1258    /// `Ok(None)`, raising nothing) when this run's sweep is exercised.
1259    fn write_blocked_run(runs: &Path, id: &str, updated_at: Timestamp) {
1260        use crate::run::{Candidate, Tally};
1261        use std::collections::BTreeMap;
1262
1263        let mut state = RunState::new(
1264            PathBuf::from("/nonexistent/repo"),
1265            "main".to_owned(),
1266            "0000000000000000000000000000000000000000".to_owned(),
1267            String::new(),
1268            crate::config::Config::default(),
1269        );
1270        state.id = id.to_owned();
1271        state.status = RunStatus::Blocked;
1272        state.updated_at = updated_at;
1273        state.candidates.push(Candidate {
1274            index: 0,
1275            label: 'A',
1276            agent: "agent".to_owned(),
1277            branch: format!("magi/{id}/A"),
1278            worktree: PathBuf::from("/nonexistent/repo"),
1279            summary: String::new(),
1280            stat: String::new(),
1281            files: 0,
1282            commits: 0,
1283            empty: false,
1284            failed: None,
1285            verified_noop: None,
1286            duration_ms: 0,
1287            folded: false,
1288        });
1289        state.tally = Some(Tally {
1290            first_choice: BTreeMap::from([('A', 1)]),
1291            borda: BTreeMap::new(),
1292            winner: 'A',
1293            rankings: 1,
1294            unanimous_initial: true,
1295            deliberated: false,
1296            changed_votes: 0,
1297            unanimous_final: true,
1298            tie_break: None,
1299            judges: 1,
1300            present: 1,
1301            quorum: 1,
1302            met_quorum: true,
1303            uncontested: None,
1304        });
1305        std::fs::create_dir_all(runs.join(id)).unwrap();
1306        std::fs::write(
1307            runs.join(id).join("run.json"),
1308            serde_json::to_string_pretty(&state).unwrap(),
1309        )
1310        .unwrap();
1311    }
1312
1313    /// No run here can be confirmed merged - one has no repository `gh` can
1314    /// even ask about, one has not sat blocked long enough, and one is
1315    /// claimed by a live daemon - so the sweep must leave every one of them
1316    /// exactly as it found them and never panic on the failures in between.
1317    #[tokio::test]
1318    async fn reconcile_external_merges_leaves_ineligible_and_unconfirmable_runs_alone() {
1319        let dir = tempfile::tempdir().unwrap();
1320        let runs = dir.path().join("runs");
1321        let home = dir.path().to_path_buf();
1322        std::fs::create_dir_all(&runs).unwrap();
1323
1324        let now = ts("2026-09-05T00:00:00Z");
1325        let disk = Disk {
1326            fold_grace_secs: 600,
1327            ..Disk::default()
1328        };
1329
1330        let due_id = "20260905-000000-blkd";
1331        write_blocked_run(&runs, due_id, ts("2026-08-01T00:00:00Z"));
1332
1333        let fresh_id = "20260905-000000-fres";
1334        write_blocked_run(&runs, fresh_id, now);
1335
1336        let live_id = "20260905-000000-live";
1337        write_blocked_run(&runs, live_id, ts("2026-08-01T00:00:00Z"));
1338        let mut status = crate::daemon::Status::new();
1339        status.current = vec![crate::daemon::Current {
1340            worker: None,
1341            task: "20260905-000000-task".to_owned(),
1342            run: live_id.to_owned(),
1343        }];
1344        status.updated_at = now;
1345        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
1346
1347        let reconciled = reconcile_external_merges(&runs, &home, &disk, now).await;
1348        assert_eq!(
1349            reconciled, 0,
1350            "an unreachable repository can never be confirmed merged"
1351        );
1352        for id in [due_id, fresh_id, live_id] {
1353            assert_eq!(
1354                read_meta(&runs, id).unwrap().status,
1355                RunStatus::Blocked,
1356                "{id} must be left exactly as it was found"
1357            );
1358        }
1359        let notices = crate::notices::Notices::at(home.join("notifications")).list();
1360        let due_notice = notices
1361            .iter()
1362            .find(|n| n.key == format!("merged-unrecorded:{due_id}"))
1363            .expect("notice for due_id must be raised");
1364        assert_eq!(
1365            due_notice.link,
1366            Some(crate::notices::Link::Run {
1367                id: due_id.to_owned(),
1368            })
1369        );
1370    }
1371
1372    /// The bug this exists to pin: a first version rotated on
1373    /// `now.as_second() % len`, which is fully determined by wall-clock time
1374    /// and nothing else. Two passes seconds apart - as they would be when a
1375    /// short poll interval and a fast pass alias onto the same handful of
1376    /// `now.as_second()` residues - landed on the *same* starting point and
1377    /// never covered a fleet bigger than the per-pass cap, however many
1378    /// times housekeeping ran. Persisting a cursor makes forward progress a
1379    /// function of how many ids got looked at, not of when the clock reads
1380    /// this pass happened to run.
1381    #[tokio::test]
1382    async fn reconcile_external_merges_covers_a_larger_fleet_across_repeated_passes_at_one_instant()
1383    {
1384        let dir = tempfile::tempdir().unwrap();
1385        let runs = dir.path().join("runs");
1386        let home = dir.path().to_path_buf();
1387        std::fs::create_dir_all(&runs).unwrap();
1388
1389        let now = ts("2026-09-05T00:00:00Z");
1390        let disk = Disk {
1391            fold_grace_secs: 600,
1392            ..Disk::default()
1393        };
1394        let old = ts("2026-08-01T00:00:00Z");
1395
1396        let ids: Vec<String> = (0..8).map(|n| format!("20260905-000000-r{n:03}")).collect();
1397        for id in &ids {
1398            write_blocked_run(&runs, id, old);
1399        }
1400
1401        let notices = crate::notices::Notices::at(home.join("notifications"));
1402
1403        // Two passes at the exact same `now`, exactly what a fast pass on a
1404        // short poll interval looks like. Each of the 8 unreachable-repo
1405        // runs raises its own notice the first time it is looked at, so the
1406        // count of distinct notices is a direct readout of how many distinct
1407        // ids have been checked so far.
1408        reconcile_external_merges(&runs, &home, &disk, now).await;
1409        let after_first = notices.list().len();
1410        assert_eq!(
1411            after_first, MAX_EXTERNAL_MERGE_CHECKS_PER_PASS,
1412            "the first pass checks exactly one cap's worth"
1413        );
1414
1415        reconcile_external_merges(&runs, &home, &disk, now).await;
1416        let after_second = notices.list().len();
1417        assert_eq!(
1418            after_second,
1419            ids.len(),
1420            "a second pass at the same instant must still reach every id the \
1421             first pass had no room for, not repeat the same cap's worth"
1422        );
1423    }
1424
1425    #[test]
1426    fn the_meta_reader_is_tolerant_of_everything_except_the_deciders() {
1427        let dir = tempfile::tempdir().unwrap();
1428        let runs = dir.path().join("runs");
1429        let id = "20260905-000000-abcd";
1430        std::fs::create_dir_all(runs.join(id)).unwrap();
1431        std::fs::write(
1432            runs.join(id).join("run.json"),
1433            r#"{"schema": 99, "id": "20260905-000000-abcd", "updated_at": "2026-09-05T00:00:00Z", "status": "ready", "junk_from_another_build": [1, 2, 3]}"#,
1434        )
1435        .unwrap();
1436        let meta = read_meta(&runs, id).expect("readable");
1437        assert_eq!(meta.status, RunStatus::Ready);
1438        assert_eq!(meta.updated_at, ts("2026-09-05T00:00:00Z"));
1439        assert!(read_meta(&runs, "nope").is_err(), "missing file unreadable");
1440        std::fs::write(runs.join(id).join("run.json"), "not json at all").unwrap();
1441        assert!(read_meta(&runs, id).is_err(), "garbage unreadable");
1442    }
1443
1444    #[test]
1445    fn fold_unreadable_preserves_unknown_content_and_recovery_artifacts() {
1446        let dir = tempfile::tempdir().unwrap();
1447        let runs = dir.path().join("runs");
1448        let wt = dir.path().join("wt");
1449        let id = "20260905-000000-abcd";
1450        std::fs::create_dir_all(runs.join(id).join("artifacts")).unwrap();
1451        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1452        std::fs::create_dir_all(wt.join("abcd")).unwrap();
1453        std::fs::write(wt.join("abcd/leftover"), "owned edits").unwrap();
1454        assert!(block_on(fold_unreadable(&runs, &wt, id)).is_err());
1455        assert!(runs.join(id).join("artifacts").exists());
1456        assert_eq!(
1457            std::fs::read_to_string(wt.join("abcd/leftover")).unwrap(),
1458            "owned edits"
1459        );
1460    }
1461
1462    #[test]
1463    fn fold_unreadable_releases_run_dir_and_worktrees() {
1464        let dir = tempfile::tempdir().unwrap();
1465        let runs = dir.path().join("runs");
1466        let wt = dir.path().join("wt");
1467        let id = "20260905-000000-abcd";
1468        std::fs::create_dir_all(runs.join(id)).unwrap();
1469        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1470        std::fs::create_dir_all(wt.join("abcd")).unwrap();
1471
1472        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold");
1473        assert_eq!(removed.len(), 2);
1474        assert!(!runs.join(id).exists(), "run dir gone");
1475        assert!(!wt.join("abcd").exists(), "worktrees gone");
1476
1477        // A prefix resolves like `run::resolve_id` does.
1478        std::fs::create_dir_all(runs.join(id)).unwrap();
1479        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
1480        std::fs::create_dir_all(wt.join("abcd")).unwrap();
1481        let removed = block_on(fold_unreadable(&runs, &wt, "20260905")).expect("by prefix");
1482        assert_eq!(removed.len(), 2);
1483        // Once gone, `id` cannot be resolved at all - same as `run::resolve_id`
1484        // on an id nothing on disk matches - so a repeat pass errors rather
1485        // than silently reporting nothing removed.
1486        assert!(
1487            block_on(fold_unreadable(&runs, &wt, id)).is_err(),
1488            "a run already gone cannot be resolved again"
1489        );
1490    }
1491
1492    #[test]
1493    fn prune_cache_sheds_the_oldest_generation_until_it_fits() {
1494        let home = tempfile::tempdir().unwrap();
1495        let dir = tempfile::tempdir().unwrap();
1496        // Same size, different age: only the age decides, and the newest
1497        // generation - the one the next build reuses - is what survives.
1498        fs::write(dir.path().join("old"), b"xx").unwrap();
1499        fs::write(dir.path().join("new"), b"yy").unwrap();
1500        touch(&dir.path().join("old"), 1_000_000);
1501        touch(&dir.path().join("new"), 2_000_000);
1502
1503        let out = prune_cache(home.path(), dir.path(), 2)
1504            .expect("prune")
1505            .expect("the cache is free");
1506        assert_eq!(out.files, 1, "one deletion is enough to reach the cap");
1507        assert_eq!(out.remaining, 2);
1508        assert!(!dir.path().join("old").exists(), "the older file went");
1509        assert!(dir.path().join("new").exists(), "the newer one stayed");
1510
1511        // A whole generation shares one timestamp tick, so the tie has to be
1512        // decided too: largest first, which reaches the cap in the fewest
1513        // deletions. Left to `read_dir` and an unstable sort this deleted
1514        // both files on Linux and one on Windows.
1515        let tied = tempfile::tempdir().unwrap();
1516        fs::write(tied.path().join("big"), b"xxxx").unwrap();
1517        fs::write(tied.path().join("small"), b"yy").unwrap();
1518        touch(&tied.path().join("big"), 1_000_000);
1519        touch(&tied.path().join("small"), 1_000_000);
1520        let out = prune_cache(home.path(), tied.path(), 2)
1521            .expect("prune")
1522            .expect("the cache is free");
1523        assert_eq!(out.files, 1, "the big one alone gets under the cap");
1524        assert_eq!(out.remaining, 2);
1525        assert!(tied.path().join("small").exists());
1526    }
1527
1528    #[test]
1529    fn prune_cache_if_over_limit_resolves_the_opt_outs_before_ever_measuring() {
1530        let home = tempfile::tempdir().unwrap();
1531        let dir = tempfile::tempdir().unwrap();
1532        fs::write(dir.path().join("big"), vec![0u8; 10]).unwrap();
1533
1534        let mut cfg = crate::config::Config::default();
1535        cfg.verify.gate = vec![format!(
1536            "CARGO_TARGET_DIR={} cargo make check",
1537            dir.path().display()
1538        )];
1539
1540        // A cap of `0` is the operator's opt-out: never measured, never
1541        // pruned, regardless of what is actually on disk.
1542        cfg.disk.cache_limit_bytes = 0;
1543        assert_eq!(
1544            prune_cache_if_over_limit(&cfg, home.path()).unwrap(),
1545            None,
1546            "a zero cap must not even look at the directory"
1547        );
1548        assert!(dir.path().join("big").exists());
1549
1550        // No `CARGO_TARGET_DIR` in either verify command: nothing to
1551        // aggregate, so there is nothing to prune either.
1552        let mut no_cache = crate::config::Config::default();
1553        no_cache.disk.cache_limit_bytes = 1;
1554        assert_eq!(
1555            prune_cache_if_over_limit(&no_cache, home.path()).unwrap(),
1556            None
1557        );
1558
1559        // Over the cap and configured: pruned exactly like `prune_cache`
1560        // itself would.
1561        cfg.disk.cache_limit_bytes = 1;
1562        let pruned = prune_cache_if_over_limit(&cfg, home.path())
1563            .unwrap()
1564            .expect("a real cache dir over its cap prunes");
1565        assert_eq!(pruned.files, 1);
1566        assert!(!dir.path().join("big").exists());
1567    }
1568
1569    /// Pin a file's mtime, so a test asserts the policy and not the runner's
1570    /// timestamp granularity.
1571    fn touch(path: &Path, secs: u64) {
1572        let f = fs::File::options().write(true).open(path).unwrap();
1573        f.set_times(fs::FileTimes::new().set_modified(
1574            std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs),
1575        ))
1576        .unwrap();
1577    }
1578
1579    /// The disk-full casualty: a run whose first save left `run.json.tmp` and
1580    /// nothing else. It has to be clearable, or the record is permanent.
1581    #[test]
1582    fn fold_unreadable_clears_a_run_whose_state_never_landed() {
1583        let dir = tempfile::tempdir().unwrap();
1584        let runs = dir.path().join("runs");
1585        let wt = dir.path().join("wt");
1586        let id = "20260904-014540-88c0";
1587        std::fs::create_dir_all(runs.join(id)).unwrap();
1588        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
1589
1590        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold by id");
1591        assert_eq!(removed, vec![format!("runs/{id}")]);
1592        assert!(!runs.join(id).exists(), "record gone");
1593
1594        // And by prefix, the way the deck and the phone address a run.
1595        std::fs::create_dir_all(runs.join(id)).unwrap();
1596        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
1597        assert!(
1598            block_on(fold_unreadable(&runs, &wt, "88c0")).is_ok(),
1599            "by prefix"
1600        );
1601
1602        // A directory under `runs` that is not a run is never a fold target.
1603        std::fs::create_dir_all(runs.join("scratch")).unwrap();
1604        assert!(
1605            block_on(fold_unreadable(&runs, &wt, "scratch")).is_err(),
1606            "a stray directory is not a run"
1607        );
1608    }
1609
1610    #[test]
1611    fn fold_due_folds_terminal_runs_of_any_schema_but_leaves_genuinely_unreadable_ones() {
1612        let dir = tempfile::tempdir().unwrap();
1613        let runs = dir.path().join("runs");
1614        let wt = dir.path().join("wt");
1615        let home = dir.path().to_path_buf();
1616        let disk = Disk::default();
1617        let now = ts("2026-09-05T00:00:00Z");
1618
1619        // 1. Runnable (judging): never folded, however old.
1620        let judging = "20260801-000000-0001";
1621        write_meta(&runs, judging, "judging", "2026-08-01T00:00:00Z");
1622
1623        // 2. Finished but fresh: grace not elapsed. Within the default 6h
1624        //    grace of `now`, so `fold_due` must stop at the freshness check
1625        //    and never even reach `read_state` - `write_meta`'s minimal JSON
1626        //    would fail that full parse anyway, and this case exists to
1627        //    prove freshness is why the run survives, not an accident of the
1628        //    fixture being unparseable as a whole `RunState`.
1629        let ready_fresh = "20260904-220000-0002";
1630        write_meta(&runs, ready_fresh, "ready", "2026-09-04T22:00:00Z");
1631
1632        // 3. Genuinely unreadable: broken JSON, not merely an unfamiliar
1633        //    schema number. Left alone and counted - this is the one case
1634        //    automatic housekeeping must never touch (see `fold_due`'s docs);
1635        //    discarding it is an explicit operator action, not something a
1636        //    background pass does.
1637        let garbage = "20260901-000000-0004";
1638        std::fs::create_dir_all(runs.join(garbage)).unwrap();
1639        std::fs::write(runs.join(garbage).join("run.json"), "not json").unwrap();
1640        std::fs::create_dir_all(wt.join("0004")).unwrap();
1641
1642        // 4. Finished, well past grace, current schema: the ordinary case
1643        //    `fold_due` has always acted on.
1644        let due_ready = due_run(&runs, &wt, "20260801-000000-ffff", SCHEMA);
1645
1646        // 5. Finished, well past grace, but written by a schema number this
1647        //    build no longer matches - the defect this task exists to fix.
1648        //    It still parses cleanly, so only the version number differs, and
1649        //    that alone must not block folding.
1650        let due_old_schema = due_run(&runs, &wt, "20260801-000000-eeee", SCHEMA - 1);
1651
1652        let (folded, unreadable) =
1653            block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
1654        assert_eq!(
1655            folded, 2,
1656            "both due, parseable runs fold regardless of their schema number"
1657        );
1658        assert_eq!(
1659            unreadable, 1,
1660            "only the run with broken JSON counts as unreadable"
1661        );
1662        assert!(runs.join(judging).exists(), "runnable never folded");
1663        assert!(runs.join(ready_fresh).exists(), "fresh never folded");
1664        assert!(runs.join(garbage).exists(), "unreadable record kept");
1665        assert!(wt.join("0004").exists(), "unreadable worktree kept");
1666        assert!(
1667            runs.join(&due_ready).exists(),
1668            "folding drops worktrees, not the record"
1669        );
1670        assert!(
1671            runs.join(&due_old_schema).exists(),
1672            "an old-schema record survives its fold exactly like a current one"
1673        );
1674        // `graph::fold_run` saves the state it just folded back to disk. That
1675        // write must land under this test's own `runs` - the argument it
1676        // passed to `fold_due`, not the process-global `run::home` - or a
1677        // fold that landed somewhere else entirely would still be counted
1678        // above as one of the two `folded` runs.
1679        for id in [&due_ready, &due_old_schema] {
1680            let saved = read_meta(&runs, id).expect("folded run still parses");
1681            assert_ne!(
1682                saved.updated_at,
1683                ts("2026-08-01T00:00:00Z"),
1684                "fold_run must have saved the updated state back through the \
1685                 `runs` directory this test passed to fold_due"
1686            );
1687        }
1688    }
1689
1690    /// `[disk] auto_fold = false` must leave the janitor's fold-and-reclaim
1691    /// passes completely inert - a due run's worktree and record both
1692    /// survive exactly as if `housekeep` had never run at all. Cache pruning
1693    /// is a separate opt-out (`cache_limit_bytes`) and stays disabled here
1694    /// too, so this test is only ever about `auto_fold`.
1695    #[tokio::test]
1696    async fn housekeep_leaves_everything_alone_when_auto_fold_is_disabled() {
1697        let dir = tempfile::tempdir().unwrap();
1698        let runs = dir.path().join("runs");
1699        let wt = dir.path().join("wt");
1700        let home = dir.path().to_path_buf();
1701        crate::run::set_home(dir.path().to_path_buf());
1702
1703        let due_id = due_run(&runs, &wt, "20260801-000000-abcd", SCHEMA);
1704        std::fs::create_dir_all(wt.join("orphan").join("cand-A")).unwrap();
1705
1706        let mut cfg = crate::config::Config::default();
1707        cfg.disk.auto_fold = false;
1708        cfg.disk.cache_limit_bytes = 0;
1709
1710        let out = housekeep(&cfg, &home, &wt, &dir.path().join("repo"), Timestamp::now()).await;
1711
1712        assert_eq!(out.folded, 0);
1713        assert_eq!(out.unreadable, 0);
1714        assert_eq!(out.orphaned_worktrees, 0);
1715        assert!(
1716            runs.join(&due_id).exists(),
1717            "a due run's record survives untouched"
1718        );
1719        assert!(
1720            wt.join("orphan").exists(),
1721            "an orphaned worktree survives untouched: the reclaim pass never ran"
1722        );
1723    }
1724
1725    #[test]
1726    fn fold_orphaned_worktrees_removes_only_worktrees_no_run_claims_and_none_in_flight() {
1727        let dir = tempfile::tempdir().unwrap();
1728        let runs = dir.path().join("runs");
1729        let wt = dir.path().join("wt");
1730        let home = dir.path().to_path_buf();
1731
1732        // A run record exists for this one: its worktree is claimed, not
1733        // orphaned, however old the record.
1734        write_meta(
1735            &runs,
1736            "20260801-000000-aaaa",
1737            "ready",
1738            "2026-08-01T00:00:00Z",
1739        );
1740        std::fs::create_dir_all(wt.join("aaaa").join("cand-A")).unwrap();
1741
1742        // No run record at all, and nobody is working on it: this is the
1743        // leftover `fold_due` can never see, because it only ever walks
1744        // `runs/`.
1745        std::fs::create_dir_all(wt.join("bbbb").join("cand-A")).unwrap();
1746
1747        // No run record either, but a live daemon status names a run with
1748        // this short id - the save-timing gap between the daemon claiming a
1749        // task and `RunState::new` writing its first `run.json`. Must survive
1750        // untouched.
1751        std::fs::create_dir_all(wt.join("cccc")).unwrap();
1752
1753        // Not shaped like a run's short id at all - a scratch directory an
1754        // operator or another tool left in the same bay - so it is never a
1755        // reclaim target regardless of what runs claim it or not.
1756        std::fs::create_dir_all(wt.join("scratch")).unwrap();
1757
1758        // `now` pushed comfortably past `MIN_ORPHAN_AGE_SECS`, so a zero
1759        // grace - the same "always due" escape hatch `due` itself documents
1760        // - still reclaims once a worktree is genuinely old, without faking
1761        // an mtime: real directory creation just above is already in the
1762        // past relative to this `now`, by design rather than by timing.
1763        let now = Timestamp::now() + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
1764        let mut status = crate::daemon::Status::new();
1765        status.current = vec![crate::daemon::Current {
1766            worker: None,
1767            task: "20260905-000000-t111".to_owned(),
1768            run: "20260905-000000-cccc".to_owned(),
1769        }];
1770        status.updated_at = now;
1771        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
1772
1773        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
1774        assert_eq!(
1775            folded, 1,
1776            "only the truly orphaned, idle, bay-shaped worktree is removed"
1777        );
1778        assert!(wt.join("aaaa").exists(), "claimed by a run record");
1779        assert!(!wt.join("bbbb").exists(), "orphaned and idle: reclaimed");
1780        assert!(wt.join("cccc").exists(), "a run in flight is never touched");
1781        assert!(
1782            wt.join("scratch").exists(),
1783            "not shaped like a worktree bay, so never a reclaim target"
1784        );
1785    }
1786
1787    /// The gap this closes: `Runner::review` (`magi review`) creates the
1788    /// worktree with `git worktree add` before `RunState::save` ever writes a
1789    /// `run.json`, and that path never runs through the daemon's own `poll`
1790    /// loop at all, so `daemon::Status` never names it either. Without a
1791    /// grace window, a janitor pass landing in that gap would read the
1792    /// worktree as an orphan nothing is waiting on and delete a review still
1793    /// being set up.
1794    #[test]
1795    fn fold_orphaned_worktrees_leaves_a_freshly_created_bay_alone() {
1796        let dir = tempfile::tempdir().unwrap();
1797        let runs = dir.path().join("runs");
1798        let wt = dir.path().join("wt");
1799        let home = dir.path().to_path_buf();
1800
1801        std::fs::create_dir_all(wt.join("dddd").join("under-review")).unwrap();
1802
1803        let now = Timestamp::now();
1804        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 6 * 60 * 60, now));
1805        assert_eq!(
1806            folded, 0,
1807            "too fresh to tell apart from a run still being set up"
1808        );
1809        assert!(wt.join("dddd").exists());
1810    }
1811
1812    /// A fresh open question on `run`, stored and handed back for assertions.
1813    fn open_question(store: &Questions, run: &str) -> crate::ask::Question {
1814        let mut q = crate::ask::Question::new(
1815            run.to_owned(),
1816            "implement".to_owned(),
1817            "impl-A".to_owned(),
1818            "Which storage backend should the cache use?".to_owned(),
1819            String::new(),
1820            vec!["SQLite".to_owned(), "Redis".to_owned()],
1821        );
1822        store.put(&mut q).unwrap();
1823        q
1824    }
1825
1826    /// The exact ghost the phone showed: a run that already finished, with a
1827    /// question its dead seat asked still sitting `open` because it reached
1828    /// that status before `graph::Runner::settle_questions` existed (or
1829    /// missed it in the crash window `daemon::reclaim_orphaned_running`
1830    /// covers). This sweep is the second door to the same fact.
1831    #[test]
1832    fn a_finished_runs_open_question_is_swept_up() {
1833        let dir = tempfile::tempdir().unwrap();
1834        let runs = dir.path().join("runs");
1835        let store = Questions::at(dir.path().join("questions"));
1836
1837        let failed = "20260908-205802-c9eb";
1838        write_meta(&runs, failed, "failed", "2026-09-08T20:58:02Z");
1839        let failed_q = open_question(&store, failed);
1840
1841        let merged = "20260908-205501-ca67";
1842        write_meta(&runs, merged, "merged", "2026-09-08T20:55:01Z");
1843        let merged_q = open_question(&store, merged);
1844
1845        let n = abandon_settled_questions(&store, &runs);
1846        assert_eq!(n, 2, "both dead runs' questions are swept in one pass");
1847
1848        for (id, run) in [(&failed_q.id, failed), (&merged_q.id, merged)] {
1849            let back = store.get(id).unwrap();
1850            assert!(!back.status.open(), "{run} is done; nobody reads an answer");
1851            assert!(back.detail.contains(run), "{}", back.detail);
1852        }
1853    }
1854
1855    #[test]
1856    fn a_still_alive_runs_open_question_survives_the_sweep() {
1857        let dir = tempfile::tempdir().unwrap();
1858        let runs = dir.path().join("runs");
1859        let store = Questions::at(dir.path().join("questions"));
1860
1861        // `Blocked` and `Stalled` are `RunStatus::resumable`: the run can
1862        // still be picked back up, so its question may yet get a real
1863        // answer. A run still mid-competition is even more obviously alive.
1864        for (id, status) in [
1865            ("20260908-000000-b10c", "blocked"),
1866            ("20260908-000000-5ta1", "stalled"),
1867            ("20260908-000000-jud6", "judging"),
1868        ] {
1869            write_meta(&runs, id, status, "2026-09-08T00:00:00Z");
1870            let q = open_question(&store, id);
1871
1872            let n = abandon_settled_questions(&store, &runs);
1873            assert_eq!(n, 0, "{status} run is not done; nothing to sweep");
1874            assert!(
1875                store.get(&q.id).unwrap().status.open(),
1876                "{status} run's question must still be waiting"
1877            );
1878        }
1879    }
1880
1881    #[test]
1882    fn the_sweep_leaves_an_answered_question_and_an_unreadable_run_alone() {
1883        let dir = tempfile::tempdir().unwrap();
1884        let runs = dir.path().join("runs");
1885        let store = Questions::at(dir.path().join("questions"));
1886
1887        // Already decided: a sweep must never revisit it, whatever the run
1888        // that asked went on to become.
1889        let done = "20260908-000000-answ";
1890        write_meta(&runs, done, "failed", "2026-09-08T00:00:00Z");
1891        let mut answered = open_question(&store, done);
1892        answered
1893            .answer(crate::ask::Answer::Choice("SQLite".to_owned()))
1894            .unwrap();
1895        store.put(&mut answered).unwrap();
1896
1897        // No `run.json` at all for this one - deleted, or never landed.
1898        let gone = "20260908-000000-gone";
1899        let orphan = open_question(&store, gone);
1900
1901        assert_eq!(abandon_settled_questions(&store, &runs), 0);
1902        assert_eq!(
1903            store.get(&answered.id).unwrap().status,
1904            crate::ask::QuestionStatus::Answered,
1905            "a real answer is never overwritten by a sweep"
1906        );
1907        assert!(
1908            store.get(&orphan.id).unwrap().status.open(),
1909            "a run this sweep cannot read is left exactly as it was, not guessed at"
1910        );
1911    }
1912
1913    /// A grace of `0` is a legitimate, documented value for the operator's
1914    /// own `Disk::fold_grace_secs` - `due`'s "always due" case - but the
1915    /// freshness check this guards is not that policy, and must not collapse
1916    /// to it: a `0` handed straight through would reclaim a worktree the
1917    /// instant it exists, exactly the race `fold_orphaned_worktrees_leaves_a_
1918    /// freshly_created_bay_alone` exists to rule out, just with the operator
1919    /// having turned the other grace off instead of leaving it at its
1920    /// default.
1921    #[test]
1922    fn fold_orphaned_worktrees_floors_a_zero_grace_at_the_race_safe_minimum() {
1923        let dir = tempfile::tempdir().unwrap();
1924        let runs = dir.path().join("runs");
1925        let wt = dir.path().join("wt");
1926        let home = dir.path().to_path_buf();
1927
1928        std::fs::create_dir_all(wt.join("eeee").join("under-review")).unwrap();
1929
1930        // Too fresh, even with the grace argument at zero.
1931        let now = Timestamp::now();
1932        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
1933        assert_eq!(
1934            folded, 0,
1935            "a zero grace must not defeat the race-safety floor"
1936        );
1937        assert!(wt.join("eeee").exists());
1938
1939        // Once genuinely past the floor, a zero grace reclaims it - the
1940        // floor is a minimum, not a replacement policy that never fires.
1941        let later = now + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
1942        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, later));
1943        assert_eq!(folded, 1, "old enough now, regardless of the zero grace");
1944        assert!(!wt.join("eeee").exists());
1945    }
1946
1947    #[test]
1948    fn clear_abandoned_active_only_acts_once_dead_and_overrun() {
1949        let dir = tempfile::tempdir().unwrap();
1950        // Harmless if another test in this binary already pinned the global
1951        // home first (see `run::set_home`'s own doc): this test only checks
1952        // the in-memory mutation `clear_abandoned_active` makes, never a
1953        // write that landed under this exact directory.
1954        crate::run::set_home(dir.path().to_path_buf());
1955        let home = dir.path().to_path_buf();
1956        let now = ts("2026-09-14T12:00:00Z");
1957        let overrun_seat = || crate::run::ActiveSeat {
1958            node: "implement".to_owned(),
1959            started_at: now - SignedDuration::new(21_000, 0),
1960            timeout_secs: 3_600,
1961            attempt: 0,
1962            task: None,
1963            command: None,
1964            index: None,
1965            total: None,
1966        };
1967
1968        let mut state = RunState::new(
1969            PathBuf::from("/repo"),
1970            "main".to_owned(),
1971            "abc1234".to_owned(),
1972            "fixture".to_owned(),
1973            crate::config::Config::default(),
1974        );
1975        state.status = RunStatus::Implementing;
1976        state.active.insert("impl-A".to_owned(), overrun_seat());
1977
1978        // A seat still within its own budget: not provably dead yet, so this
1979        // must change nothing.
1980        let mut fresh = state.clone();
1981        fresh.active.insert(
1982            "impl-B".to_owned(),
1983            crate::run::ActiveSeat {
1984                node: "implement".to_owned(),
1985                started_at: now,
1986                timeout_secs: 3_600,
1987                attempt: 0,
1988                task: None,
1989                command: None,
1990                index: None,
1991                total: None,
1992            },
1993        );
1994        assert!(!clear_abandoned_active(&mut fresh, &home, now).unwrap());
1995        assert!(!fresh.active.is_empty());
1996        assert_eq!(fresh.status, RunStatus::Implementing);
1997
1998        let store = Questions::at(home.join("questions"));
1999        let q = open_question(&store, &state.id);
2000
2001        assert!(clear_abandoned_active(&mut state, &home, now).unwrap());
2002        assert!(state.active.is_empty());
2003        assert_eq!(state.status, RunStatus::Failed);
2004        assert!(
2005            !store.get(&q.id).unwrap().status.open(),
2006            "the abandoned seat's own open question must not keep badging the \
2007             operator until some later daemon startup notices it"
2008        );
2009    }
2010
2011    /// Write a whole `run.json` that magi can read, over the given state.
2012    fn write_meta(runs: &Path, id: &str, status: &str, updated_at: &str) {
2013        let day = &updated_at[..10];
2014        std::fs::create_dir_all(runs.join(id)).unwrap();
2015        let body = format!(
2016            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}}"#
2017        );
2018        std::fs::write(runs.join(id).join("run.json"), body).unwrap();
2019    }
2020
2021    /// Write a fully-formed, `Ready`, well-past-grace `run.json` tagged with
2022    /// an arbitrary schema number - so a test can write one this build's own
2023    /// `RunState::new` could never produce on its own. Returns the id.
2024    ///
2025    /// `wt` becomes this run's `graph.worktree_root`: left at the config
2026    /// default, `RunState::worktree_root` falls through to
2027    /// `run::default_worktree_root` - the operator's real `~/wt/magi` - and
2028    /// `graph::fold_run`'s second sweep would then `read_dir` and remove
2029    /// worktrees there instead of anything this test owns.
2030    fn due_run(runs: &Path, wt: &Path, id: &str, schema: u32) -> String {
2031        due_run_with_status(runs, wt, id, schema, RunStatus::Ready)
2032    }
2033
2034    /// [`due_run`], with the terminal status a caller wants instead of the
2035    /// `Ready` every other caller here happens to want.
2036    fn due_run_with_status(
2037        runs: &Path,
2038        wt: &Path,
2039        id: &str,
2040        schema: u32,
2041        status: RunStatus,
2042    ) -> String {
2043        let mut config = crate::config::Config::default();
2044        config.graph.worktree_root = Some(wt.to_path_buf());
2045        let mut state = RunState::new(
2046            PathBuf::from("/nonexistent/repo"),
2047            "main".to_owned(),
2048            "0000000000000000000000000000000000000000".to_owned(),
2049            String::new(),
2050            config,
2051        );
2052        state.id = id.to_owned();
2053        state.status = status;
2054        state.updated_at = ts("2026-08-01T00:00:00Z");
2055        let mut value = serde_json::to_value(&state).unwrap();
2056        value["schema"] = serde_json::json!(schema);
2057        std::fs::create_dir_all(runs.join(id)).unwrap();
2058        std::fs::write(
2059            runs.join(id).join("run.json"),
2060            serde_json::to_string_pretty(&value).unwrap(),
2061        )
2062        .unwrap();
2063        id.to_owned()
2064    }
2065
2066    #[test]
2067    fn fold_due_folds_a_superseded_run_same_as_any_other_terminal_one() {
2068        let dir = tempfile::tempdir().unwrap();
2069        let runs = dir.path().join("runs");
2070        let wt = dir.path().join("wt");
2071        let home = dir.path().to_path_buf();
2072        let disk = Disk::default();
2073        let now = ts("2026-09-05T00:00:00Z");
2074
2075        let superseded = due_run_with_status(
2076            &runs,
2077            &wt,
2078            "20260801-000000-cccc",
2079            SCHEMA,
2080            RunStatus::Superseded,
2081        );
2082
2083        let (folded, unreadable) =
2084            block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
2085        assert_eq!(
2086            folded, 1,
2087            "a superseded run has nothing left for a human to check, so it folds \
2088             exactly like a merged one"
2089        );
2090        assert_eq!(unreadable, 0);
2091        assert!(
2092            read_meta(&runs, &superseded).is_ok(),
2093            "folding drops the worktree, not the record"
2094        );
2095    }
2096
2097    /// A throwaway repo with one commit on `main`, for a test that needs a
2098    /// real winner worktree `fold_run` can actually remove.
2099    fn init_repo(dir: &Path) {
2100        use crate::proc::Quiet as _;
2101        let run = |args: &[&str]| {
2102            let out = std::process::Command::new("git")
2103                .args(args)
2104                .current_dir(dir)
2105                .quiet()
2106                .output()
2107                .expect("spawn git");
2108            assert!(
2109                out.status.success(),
2110                "git {args:?} failed: {}",
2111                String::from_utf8_lossy(&out.stderr)
2112            );
2113        };
2114        run(&["init", "-b", "main"]);
2115        run(&["config", "user.name", "magi test"]);
2116        run(&["config", "user.email", "magi@example.com"]);
2117        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
2118        run(&["add", "-A"]);
2119        run(&["commit", "-m", "init"]);
2120    }
2121
2122    /// A due, terminal run with a decided winner that still has a real
2123    /// worktree and branch on disk - so a test can tell whether folding it
2124    /// actually removed the winner or only left it registered as folded.
2125    async fn due_run_with_winner_worktree(
2126        runs: &Path,
2127        wt: &Path,
2128        repo: &Path,
2129        id: &str,
2130        status: RunStatus,
2131    ) -> (String, PathBuf) {
2132        use crate::run::{Candidate, Tally};
2133        use std::collections::BTreeMap;
2134
2135        let mut config = crate::config::Config::default();
2136        config.graph.worktree_root = Some(wt.to_path_buf());
2137        let mut state = RunState::new(
2138            repo.to_path_buf(),
2139            "main".to_owned(),
2140            "0000000000000000000000000000000000000000".to_owned(),
2141            String::new(),
2142            config,
2143        );
2144        state.id = id.to_owned();
2145        state.status = status;
2146        state.updated_at = ts("2026-08-01T00:00:00Z");
2147
2148        let winner_wt = state.worktree_root().join("cand-A");
2149        crate::git::worktree_add_branch(repo, &winner_wt, &format!("magi/{id}/A"), "main")
2150            .await
2151            .expect("winner worktree");
2152
2153        state.candidates.push(Candidate {
2154            index: 0,
2155            label: 'A',
2156            agent: "agent".to_owned(),
2157            branch: format!("magi/{id}/A"),
2158            worktree: winner_wt.clone(),
2159            summary: String::new(),
2160            stat: String::new(),
2161            files: 0,
2162            commits: 0,
2163            empty: false,
2164            failed: None,
2165            verified_noop: None,
2166            duration_ms: 0,
2167            folded: false,
2168        });
2169        state.tally = Some(Tally {
2170            first_choice: BTreeMap::from([('A', 1)]),
2171            borda: BTreeMap::new(),
2172            winner: 'A',
2173            rankings: 1,
2174            unanimous_initial: true,
2175            deliberated: false,
2176            changed_votes: 0,
2177            unanimous_final: true,
2178            tie_break: None,
2179            judges: 1,
2180            present: 1,
2181            quorum: 1,
2182            met_quorum: true,
2183            uncontested: None,
2184        });
2185        std::fs::create_dir_all(runs.join(id)).unwrap();
2186        std::fs::write(
2187            runs.join(id).join("run.json"),
2188            serde_json::to_string_pretty(&state).unwrap(),
2189        )
2190        .unwrap();
2191        (id.to_owned(), winner_wt)
2192    }
2193
2194    #[tokio::test]
2195    async fn completed_task_retains_independent_historical_sources_without_a_merge_proof() {
2196        let dir = tempfile::tempdir().unwrap();
2197        let home = dir.path();
2198        let runs = home.join("runs");
2199        let wt = home.join("wt");
2200        let repo = home.join("repo");
2201        std::fs::create_dir_all(&repo).unwrap();
2202        init_repo(&repo);
2203        let queue = crate::queue::Queue::at(home.join("queue"));
2204        let mut task = crate::queue::Task::new(
2205            "completed".into(),
2206            "retain independent historical changes".into(),
2207            repo.clone(),
2208            crate::queue::Source::Human,
2209        );
2210        let mut sources = Vec::new();
2211        for (id, status) in [
2212            ("20260801-000000-old1", RunStatus::Superseded),
2213            ("20260801-000000-old2", RunStatus::Failed),
2214        ] {
2215            let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
2216            std::fs::write(worktree.join("independent.txt"), &id).unwrap();
2217            crate::git::git(&worktree, &["add", "independent.txt"])
2218                .await
2219                .unwrap();
2220            crate::git::git(
2221                &worktree,
2222                &["commit", "-m", "Independent historical change"],
2223            )
2224            .await
2225            .unwrap();
2226            let head = crate::git::rev_parse(&worktree, "HEAD").await.unwrap();
2227            let mut state = RunState::load_under(&id, home).unwrap();
2228            state.driver_exited = true;
2229            if status == RunStatus::Failed {
2230                state.tally = None;
2231            }
2232            state.save_under(home).unwrap();
2233            task.link_run(&id);
2234            sources.push((id, worktree, head));
2235        }
2236        // A newer empty attempt and task completion are no proof that either
2237        // independent historical implementation was incorporated.
2238        let mut latest = RunState::new(
2239            repo.clone(),
2240            "main".into(),
2241            crate::git::rev_parse(&repo, "main").await.unwrap(),
2242            task.instruction.clone(),
2243            crate::config::Config::default(),
2244        );
2245        latest.status = RunStatus::Ready;
2246        latest.driver_exited = true;
2247        latest.save_under(home).unwrap();
2248        task.start(latest.id.clone());
2249        task.succeed();
2250        queue.put(&mut task).unwrap();
2251
2252        let (folded, unreadable) = fold_due(
2253            &runs,
2254            home,
2255            &wt,
2256            &Disk::default(),
2257            ts("2026-09-05T00:00:00Z"),
2258        )
2259        .await
2260        .unwrap();
2261        assert_eq!((folded, unreadable), (0, 0));
2262        for (id, worktree, head) in sources {
2263            assert!(worktree.exists());
2264            assert_eq!(
2265                crate::git::rev_parse(&worktree, "HEAD").await.unwrap(),
2266                head
2267            );
2268            let mut state = RunState::load_under(&id, home).unwrap();
2269            assert!(!state.candidates[0].folded);
2270            let error = crate::graph::fold_run(&mut state, true, home)
2271                .await
2272                .unwrap_err();
2273            assert!(
2274                error
2275                    .to_string()
2276                    .contains(&format!("source of task {}", task.id))
2277            );
2278            assert_eq!(
2279                crate::git::rev_parse(&repo, &state.candidates[0].branch)
2280                    .await
2281                    .unwrap(),
2282                head
2283            );
2284            assert!(worktree.exists());
2285            assert!(runs.join(&id).join("run.json").exists());
2286        }
2287    }
2288
2289    #[tokio::test]
2290    async fn recovery_retains_historical_sources_after_success_and_automatic_cleanup() {
2291        let dir = tempfile::tempdir().unwrap();
2292        let home = dir.path();
2293        let runs = home.join("runs");
2294        let wt = home.join("wt");
2295        let repo = home.join("repo");
2296        std::fs::create_dir_all(&repo).unwrap();
2297        init_repo(&repo);
2298        let mut task = crate::queue::Task::new(
2299            "recover".into(),
2300            "keep measured behavior".into(),
2301            repo.clone(),
2302            crate::queue::Source::Human,
2303        );
2304        let mut sources = Vec::new();
2305        for (id, status) in [
2306            ("20260801-000000-old1", RunStatus::Blocked),
2307            ("20260801-000000-old2", RunStatus::Stalled),
2308        ] {
2309            let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
2310            let mut state = RunState::load_under(&id, home).unwrap();
2311            state.driver_exited = true;
2312            state.save_under(home).unwrap();
2313            task.link_run(&id);
2314            sources.push((id, worktree));
2315        }
2316        crate::pr_recovery::retain_sources(&task, home).unwrap();
2317        let mut recovered = RunState::new(
2318            repo.clone(),
2319            "main".into(),
2320            "base".into(),
2321            task.instruction.clone(),
2322            crate::config::Config::default(),
2323        );
2324        recovered.config.graph.worktree_root = Some(wt.clone());
2325        recovered.status = RunStatus::Ready;
2326        recovered.driver_exited = true;
2327        recovered.save_under(home).unwrap();
2328        task.start(recovered.id.clone());
2329        task.succeed();
2330        crate::daemon::supersede_prior_runs(&task, home);
2331        for (id, _) in &sources {
2332            assert_eq!(
2333                RunState::load_under(id, home).unwrap().status,
2334                RunStatus::Superseded
2335            );
2336        }
2337        let disk = Disk::default();
2338        let now = Timestamp::now()
2339            .checked_add(SignedDuration::from_secs(
2340                i64::try_from(disk.fold_grace_secs + 1).unwrap(),
2341            ))
2342            .unwrap();
2343        let (_, unreadable) = fold_due(&runs, home, &wt, &disk, now).await.unwrap();
2344        assert_eq!(unreadable, 0);
2345        for (id, worktree) in sources {
2346            assert!(worktree.exists());
2347            assert!(
2348                crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
2349                    .await
2350                    .unwrap()
2351            );
2352            let mut historical = RunState::load_under(&id, home).unwrap();
2353            assert!(!historical.candidates[0].folded);
2354            let error = crate::graph::fold_run(&mut historical, true, home)
2355                .await
2356                .unwrap_err();
2357            assert!(
2358                error
2359                    .to_string()
2360                    .contains("explicitly retained recovery source")
2361            );
2362            assert!(!historical.candidates[0].folded);
2363            assert!(
2364                worktree.exists(),
2365                "every automatic fold entry preserves retained sources"
2366            );
2367        }
2368    }
2369
2370    #[tokio::test]
2371    async fn fold_due_drops_a_superseded_runs_own_winner_worktree_but_keeps_a_readys() {
2372        let dir = tempfile::tempdir().unwrap();
2373        let runs = dir.path().join("runs");
2374        let wt = dir.path().join("wt");
2375        let repo = dir.path().join("repo");
2376        let home = dir.path().to_path_buf();
2377        let disk = Disk::default();
2378        let now = ts("2026-09-05T00:00:00Z");
2379        std::fs::create_dir_all(&repo).unwrap();
2380        init_repo(&repo);
2381
2382        let (superseded_id, superseded_wt) = due_run_with_winner_worktree(
2383            &runs,
2384            &wt,
2385            &repo,
2386            "20260801-000000-supw",
2387            RunStatus::Superseded,
2388        )
2389        .await;
2390        // `Ready` is auto-folded exactly like `Superseded` (both terminal and
2391        // non-resumable), but never landed anywhere - its own winner is
2392        // deliberately kept, which is what makes it the right contrast here.
2393        // `Blocked`/`Stalled` are `resumable()` and so never even reach
2394        // `fold_run` in the first place; they would not exercise the
2395        // `drop_winner` choice this test is about.
2396        let (ready_id, ready_wt) = due_run_with_winner_worktree(
2397            &runs,
2398            &wt,
2399            &repo,
2400            "20260801-000000-rdyw",
2401            RunStatus::Ready,
2402        )
2403        .await;
2404
2405        let (folded, unreadable) = fold_due(&runs, &home, &wt, &disk, now)
2406            .await
2407            .expect("fold_due");
2408        assert_eq!(folded, 2);
2409        assert_eq!(unreadable, 0);
2410
2411        assert!(
2412            !superseded_wt.exists(),
2413            "a superseded run's own winner never lands anywhere else, so its worktree \
2414             must be dropped exactly like a merged run's"
2415        );
2416        assert!(
2417            ready_wt.exists(),
2418            "a still-ready run's winner may yet be merged by hand - folding must not \
2419             touch it"
2420        );
2421
2422        // Both records survive the fold; only the worktrees differ.
2423        assert!(read_meta(&runs, &superseded_id).is_ok());
2424        assert!(read_meta(&runs, &ready_id).is_ok());
2425    }
2426}