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, Serialize};
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    match crate::build_target::prune_registered(home, &cfg.disk) {
132        Ok(pruned) => {
133            out.cache_files = out.cache_files.saturating_add(pruned.files);
134            out.cache_freed = out.cache_freed.saturating_add(pruned.freed);
135        }
136        Err(e) => tracing::warn!("housekeep: prune isolated builds: {e:#}"),
137    }
138    // Unconditional, unlike the two passes above: this is not a disk policy
139    // with a cap or an opt-out, it is closing a gap `graph::Runner` itself
140    // cannot - a run that reached `Merged`/`Ready`/`Failed` before this
141    // cleanup existed, or whose process died between saving that status and
142    // abandoning the question it leaves behind (see `Runner::settle_questions`).
143    // Left alone, that question sits `open` forever: the owner's badge,
144    // banner and title all keep counting a decision nobody is left to read.
145    out.questions_abandoned =
146        abandon_settled_questions(&Questions::at(home.join("questions")), &home.join("runs"));
147    // Also unconditional: leftovers of run deletions that were killed between
148    // moving the directory away and removing it (see `sweep_graveyard`).
149    sweep_graveyard(home);
150    out
151}
152
153/// Abandon every open question whose run has already settled into a status
154/// nothing comes back from, worded with what the run became - the same
155/// cleanup `graph::Runner::settle_questions` runs the moment `status` lands
156/// there, for questions that missed it.
157///
158/// Scans questions rather than runs: the open list is normally short, and a
159/// run that never asked anything costs nothing here. A run this cannot read,
160/// deleted or written by a schema this build does not speak, is left alone
161/// the same as everywhere else in this module; the question stays open
162/// rather than guessed at.
163pub fn abandon_settled_questions(store: &Questions, runs: &Path) -> usize {
164    let waiting_on: BTreeSet<String> = store
165        .list()
166        .into_iter()
167        .filter(|q| q.status.open())
168        .map(|q| q.run)
169        .collect();
170    let mut abandoned = 0;
171    for run in waiting_on {
172        let Ok(meta) = read_meta(runs, &run) else {
173            continue;
174        };
175        match store.settle_run(&run, meta.status) {
176            Ok(n) => abandoned += n,
177            Err(e) => tracing::warn!("housekeep: abandon questions for {run}: {e:#}"),
178        }
179    }
180    abandoned
181}
182
183/// Fold every run that is finished, older than the grace period, and not being
184/// worked on; return `(folded, unreadable)`.
185///
186/// A run whose `run.json` genuinely cannot be parsed — missing fields, broken
187/// JSON, a schema newer than this build has ever heard of — is left exactly
188/// as it is. Automatic housekeeping cannot tell a mid-write file from one that
189/// will never parse again, and `<home>/runs/<id>/` is the evidence `magi
190/// stats` and the deck read; when unsure whether it is safe to touch, the
191/// janitor keeps rather than deletes (see the module docs). Discarding a
192/// record this unreadable is an explicit operator action (`magi fold`, or the
193/// equivalent phone route), never something that happens unattended. Every
194/// such skip is counted in the returned `unreadable` and logged through
195/// `tracing::warn` with the parse failure that caused it - silence here is
196/// exactly the failure mode that let 90 of 93 runs sit unfolded with nothing
197/// to show for it.
198///
199/// A run merely written by a *different* schema number is not unreadable: as
200/// long as `run.json` still parses, it folds like any other terminal run (see
201/// the module docs for why the two are different questions).
202///
203/// Runnable statuses and runs newer than the grace period are also left
204/// alone; folding them would throw away work that is still the answer to
205/// somebody's question. `Merged` runs forget their winner's worktree (the
206/// merge already landed it); `Ready` and `Failed` runs keep it.
207pub async fn fold_due(
208    runs: &Path,
209    home: &Path,
210    _worktrees_root: &Path,
211    disk: &Disk,
212    now: Timestamp,
213) -> Result<(usize, usize)> {
214    let mut folded = 0usize;
215    let mut unreadable = 0usize;
216    for id in fold_ids(runs) {
217        match fold_one(runs, home, disk, now, &id, false, &mut || {})
218            .await
219            .outcome
220        {
221            FoldOutcome::Folded | FoldOutcome::NothingLeft => folded += 1,
222            FoldOutcome::Unreadable => unreadable += 1,
223            _ => {}
224        }
225    }
226    Ok((folded, unreadable))
227}
228
229/// Every run directory [`fold_due`] considers, oldest id first.
230fn fold_ids(runs: &Path) -> Vec<String> {
231    let mut ids: Vec<String> = std::fs::read_dir(runs)
232        .into_iter()
233        .flatten()
234        .flatten()
235        .filter(|e| e.path().join("run.json").is_file())
236        .map(|e| e.file_name().to_string_lossy().into_owned())
237        .collect();
238    ids.sort_unstable();
239    ids
240}
241
242/// The run directories [`fold_turn`] walks: [`fold_ids`] restricted to names
243/// that are run ids. The turn saves an id as its cursor and high-water mark and
244/// refuses to continue from one that is not a run id, so a stray directory with
245/// a `run.json` (`runs/backup/`) must not be able to become either: it would
246/// restart the cycle on every pass and starve the runs after the inspection
247/// bound. The idle pass keeps its wider inventory.
248fn fold_turn_ids(runs: &Path) -> Vec<String> {
249    let mut ids = fold_ids(runs);
250    ids.retain(|id| crate::run::is_run_id(id));
251    ids
252}
253
254/// What one run's turn through [`fold_one`] came to.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256enum FoldOutcome {
257    /// `graph::fold_run_when` ran and removed something.
258    Folded,
259    /// `graph::fold_run_when` ran and found nothing left to remove.
260    NothingLeft,
261    /// The run is `settled`: a fold recorded that it found nothing left and
262    /// the bay is confirmed absent, so no fold was started (only the busy-time
263    /// turn asks for this).
264    AlreadyFolded,
265    /// A live claim, or a held execution/ownership/output lease, protects the run.
266    Live,
267    /// A resumable status: someone may still continue this run.
268    Resumable,
269    /// Finished less than `fold_grace_secs` ago.
270    WithinGrace,
271    /// Explicitly retained recovery source (`pr_recovery::source_retention_reason`).
272    Retained,
273    /// The proof that nothing is lost is incomplete: startup or candidate
274    /// preservation unfinished, or the confirmed-merge source proof.
275    ProofIncomplete,
276    /// `run.json` could not be parsed, or became unreadable once the fold
277    /// held the run's locks.
278    Unreadable,
279    /// The record was deleted while the fold waited for its locks.
280    RecordGone,
281    /// `graph::fold_run_when` failed (git, filesystem).
282    Failed,
283}
284
285/// One run's [`FoldOutcome`], with the text of what stopped it where there is
286/// any worth keeping (`ProofIncomplete`, `Failed`).
287struct Judged {
288    outcome: FoldOutcome,
289    note: Option<String>,
290}
291
292impl From<FoldOutcome> for Judged {
293    fn from(outcome: FoldOutcome) -> Self {
294        Self {
295            outcome,
296            note: None,
297        }
298    }
299}
300
301fn refused(refusal: &crate::graph::FoldRefusal) -> Judged {
302    use crate::graph::FoldRefusal;
303    match refusal {
304        FoldRefusal::Live(_) => FoldOutcome::Live.into(),
305        FoldRefusal::Resumable => FoldOutcome::Resumable.into(),
306        FoldRefusal::WithinGrace => FoldOutcome::WithinGrace.into(),
307        FoldRefusal::Retained(_) => FoldOutcome::Retained.into(),
308        FoldRefusal::ProofIncomplete(detail) => Judged {
309            outcome: FoldOutcome::ProofIncomplete,
310            note: Some(detail.clone()),
311        },
312        FoldRefusal::RecordGone => FoldOutcome::RecordGone.into(),
313        FoldRefusal::Unreadable(_) => FoldOutcome::Unreadable.into(),
314    }
315}
316
317/// May this record be folded now, and does its winner go too? The one
318/// decision, shared by the idle janitor and the busy-time turn, and asked
319/// twice: on the record read before any lock, and again by
320/// `graph::fold_run_when` on the record it reloads under the run's owner lock
321/// and execution lease. See [`fold_due`] for why every refusal is a skip and
322/// not an error.
323fn eligibility(
324    state: &RunState,
325    home: &Path,
326    disk: &Disk,
327    now: Timestamp,
328) -> Result<bool, crate::graph::FoldRefusal> {
329    use crate::graph::FoldRefusal;
330    if crate::daemon::is_working_on(home, &state.id, now) {
331        return Err(FoldRefusal::Live(
332            "claimed by a live driver or worker".into(),
333        ));
334    }
335    if state.status.resumable() {
336        return Err(FoldRefusal::Resumable);
337    }
338    if !due(now, state.updated_at, disk.fold_grace_secs) {
339        return Err(FoldRefusal::WithinGrace);
340    }
341    if state.startup.as_ref().is_some_and(|s| !s.complete) {
342        return Err(FoldRefusal::ProofIncomplete("startup incomplete".into()));
343    }
344    handover_settled(state, home, now)?;
345    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state) {
346        tracing::info!(id = %state.id, %reason, "housekeep: source retained; fold refused");
347        return Err(FoldRefusal::Retained(reason));
348    }
349    // The same predicate `graph::fold_run_when` refuses on before it takes any lock.
350    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
351        return Err(FoldRefusal::ProofIncomplete(
352            "candidate preservation incomplete; refusing cleanup".into(),
353        ));
354    }
355    // `Merged`'s winner branch is safe to drop because it already landed
356    // in the real target branch; `Superseded`'s winner branch is safe to
357    // drop for a different reason - a later attempt at the same task is
358    // what actually landed (or didn't), so *this* run's own winner is
359    // never going to be merged by anyone. Every other terminal status
360    // keeps the winner: `Ready`/`Blocked`/`Stalled`/`Failed`/`VerifiedNoop`
361    // may still have a human's decision pending on that exact branch.
362    // `AlreadyInBase` is the same: the change is on the base under other
363    // commit ids, so the branch holds nothing anyone still needs.
364    Ok(matches!(
365        state.status,
366        RunStatus::Merged | RunStatus::Superseded | RunStatus::AlreadyInBase
367    ))
368}
369
370/// A handover in flight is not folded: a record naming a successor
371/// (`released_to`) whose startup has not settled, or whose driver is live, is
372/// `live` and nothing is touched.
373///
374/// `handover::release` records `released_to` under the predecessor's owner
375/// lock and keeps going; when the successor's startup then fails,
376/// `handover::Released::restore` takes the same owner lock to put the old
377/// worktree back. An automatic fold that holds that lock at that moment would
378/// make the rollback abandon, leaving the predecessor marked as released to a
379/// run that never started. The successor's own record says whether it is still
380/// starting (`startup` present, not complete, no failure recorded - a failed
381/// startup has settled: its rollback is what follows) or driving (a live
382/// driver). A successor record that is not there protects nothing; one that
383/// cannot be read is unknown, which refuses. A startup killed mid-way leaves the
384/// same marker as one in progress, so it keeps its predecessor out of automatic
385/// folding until an operator settles that run - the safe direction. Asked on
386/// the first read and again on the record the fold reloads under its locks.
387fn handover_settled(
388    state: &RunState,
389    home: &Path,
390    now: Timestamp,
391) -> Result<(), crate::graph::FoldRefusal> {
392    use crate::graph::FoldRefusal;
393    let Some(next) = state.released_to.as_deref() else {
394        return Ok(());
395    };
396    let successor = match RunState::load_tolerant_under(next, home) {
397        Ok(successor) => successor,
398        Err(e)
399            if e.chain().any(|cause| {
400                cause
401                    .downcast_ref::<std::io::Error>()
402                    .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
403            }) =>
404        {
405            return Ok(());
406        }
407        Err(e) => {
408            return Err(FoldRefusal::Live(format!(
409                "the successor {next} of a handover cannot be read: {e:#}"
410            )));
411        }
412    };
413    if successor
414        .startup
415        .as_ref()
416        .is_some_and(|startup| !startup.complete && startup.failure.is_none())
417    {
418        return Err(FoldRefusal::Live(format!(
419            "handover in flight: run {next} is still starting"
420        )));
421    }
422    let claimed = crate::daemon::is_working_on(home, next, now);
423    if successor.liveness_under(home, claimed) == crate::run::Liveness::Live {
424        return Err(FoldRefusal::Live(format!(
425            "handover in flight: run {next} is being driven"
426        )));
427    }
428    Ok(())
429}
430
431/// Fold the run whose merge was just recorded from the forge
432/// (`reconcile_external_merges`). An automatic caller like the janitor's own
433/// fold: the record is read again under the run's locks, tolerant of older
434/// schemas, and the conditions that made this a confirmed merge are re-checked
435/// on it - it must still be a confirmed merge, its winner goes too, and a
436/// handover in flight still protects it. There is no grace - the merge is the
437/// news - and every other refusal stays with `graph::fold_run_when`.
438async fn fold_recorded_merge(
439    state: &mut RunState,
440    home: &Path,
441    now: Timestamp,
442) -> Result<Vec<String>> {
443    crate::graph::fold_run_when(state, home, &|fresh| {
444        use crate::graph::FoldRefusal;
445        if fresh.status != RunStatus::Merged || !fresh.merge.as_ref().is_some_and(|merge| merge.ok)
446        {
447            return Err(FoldRefusal::ProofIncomplete(
448                "the run is not a confirmed merge".into(),
449            ));
450        }
451        handover_settled(fresh, home, now)?;
452        Ok(true)
453    })
454    .await
455}
456
457/// May the busy-time turn answer a run without starting a fold?
458///
459/// Only on a fact a fold itself recorded: `graph::fold_run_when` completed under
460/// the run's locks, found nothing left to remove and saw the worktree bay gone
461/// (`RunState::fold_settled_at`), *and* the bay is confirmed absent now -
462/// `bay` is the answer of `Path::try_exists`, so a failing check and a bay that
463/// exists (even an empty one, which a fold removes) both mean "judge normally and
464/// invoke the fold". Nothing is inferred from candidate flags, directory listings
465/// or Git: a stale registration or a leftover branch without a bay is not disk
466/// and is left to the ordinary paths. A pending worktree-config release is work,
467/// so it is not skipped either. This spares a run that was folded long ago the
468/// fold budget every cycle; the idle pass never skips.
469fn settled(state: &RunState, drop_winner: bool, bay: std::io::Result<bool>) -> bool {
470    state.fold_settled_at.is_some()
471        && !(state.enabled_worktree_config && drop_winner)
472        && matches!(bay, Ok(false))
473}
474
475/// Judge one run and, when [`eligibility`] allows it, fold it.
476///
477/// Shared by the idle janitor ([`fold_due`]) and the bounded busy-time turn
478/// ([`fold_turn`]); neither may decide differently, so the checks live here
479/// and nowhere else. `skip_finished` (the turn only) answers a run that is
480/// [`settled`] without starting a fold. `begin_fold` is called right
481/// before `graph::fold_run_when` is entered, whatever it then returns, so the
482/// caller's budget is charged for every invocation, not only for the ones that
483/// removed something.
484async fn fold_one(
485    runs: &Path,
486    home: &Path,
487    disk: &Disk,
488    now: Timestamp,
489    id: &str,
490    skip_finished: bool,
491    begin_fold: &mut (dyn FnMut() + Send),
492) -> Judged {
493    if crate::daemon::is_working_on(home, id, now) {
494        return FoldOutcome::Live.into();
495    }
496    let meta = match read_meta(runs, id) {
497        Ok(meta) => meta,
498        Err(e) => {
499            tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
500            return FoldOutcome::Unreadable.into();
501        }
502    };
503    if meta.status.resumable() {
504        return FoldOutcome::Resumable.into();
505    }
506    if !due(now, meta.updated_at, disk.fold_grace_secs) {
507        return FoldOutcome::WithinGrace.into();
508    }
509    // `read_meta` already proved the file parses; `read_state` asks for
510    // the rest of the fields `graph::fold_run` needs (worktree paths,
511    // candidates, tally). A schema mismatch alone does not fail this -
512    // see the module docs - so reaching `Err` here means the JSON itself
513    // is broken in a way `read_meta` did not exercise, which is rare but
514    // not impossible (a body truncated between the two fields it reads
515    // and the rest). That must not cost every other run its turn through
516    // the caller's loop, so it is a skip, not a `?`.
517    let mut state = match read_state(runs, id) {
518        Ok(state) => state,
519        Err(e) => {
520            tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
521            return FoldOutcome::Unreadable.into();
522        }
523    };
524    let decide = |state: &RunState| eligibility(state, home, disk, now);
525    let drop_winner = match decide(&state) {
526        Ok(drop_winner) => drop_winner,
527        Err(refusal) => return refused(&refusal),
528    };
529    if state.schema != SCHEMA {
530        tracing::info!(
531            "housekeep: run {id} was written by schema {} (this build speaks {SCHEMA}); \
532             folding it anyway",
533            state.schema
534        );
535    }
536    if skip_finished && settled(&state, drop_winner, state.worktree_root().try_exists()) {
537        return FoldOutcome::AlreadyFolded.into();
538    }
539    // The window a handover can fall into: after the read above, before the
540    // fold takes the run's locks. Tests run their handover here, deterministically.
541    #[cfg(test)]
542    if let Some(hook) = tests::AFTER_FIRST_READ.with(|hook| hook.borrow_mut().take()) {
543        hook(home, id);
544    }
545    // One run's fold must not cost every later run its turn. A worktree
546    // another borrower holds, a branch git refuses to delete, a repository
547    // that has since moved: each is a reason this run cannot be folded
548    // now, and none is a reason to stop the pass. Left unfolded, it is
549    // simply due again next time; a `?` here stopped automatic folding
550    // permanently at the first such run (finding R3-1-1 of run 51a3).
551    begin_fold();
552    match crate::graph::fold_run_when(&mut state, home, &decide).await {
553        Ok(removed) if removed.is_empty() => FoldOutcome::NothingLeft.into(),
554        Ok(_) => FoldOutcome::Folded.into(),
555        Err(e) => match e.downcast_ref::<crate::graph::FoldRefusal>() {
556            Some(refusal) => {
557                tracing::info!("housekeep: fold {id}: {refusal}");
558                refused(refusal)
559            }
560            None => {
561                tracing::warn!("housekeep: fold {id}: {e:#}");
562                Judged {
563                    outcome: FoldOutcome::Failed,
564                    note: Some(format!("{e:#}")),
565                }
566            }
567        },
568    }
569}
570
571/// How much one [`fold_turn`] may do. Whichever bound is reached first ends the
572/// pass; the cycle state says where the next one continues.
573#[derive(Debug, Clone, Copy)]
574pub struct FoldBounds {
575    /// Run records read and judged (cheap: one JSON each).
576    pub inspect: usize,
577    /// `graph::fold_run_when` invocations (expensive: git, locks, deleting
578    /// build output), charged when the invocation begins, whatever it returns.
579    pub fold: usize,
580    /// Wall clock, inventory included, checked between runs only; a started
581    /// fold always finishes.
582    pub budget: std::time::Duration,
583}
584
585/// What the scheduler's busy-time turn may do per pass: judging at most 64
586/// records (a 218-run history is four passes), starting at most four folds and
587/// starting none after five minutes, whichever bound comes first.
588///
589/// The costs are not alike, and none is "milliseconds" in general. Judging a
590/// record reads its `run.json` and asks for a live claim (`daemon.json`, the
591/// worker store); one that is eligible is read in full and its decision
592/// evaluated, which reads the queue for recovery-source retention. Those are
593/// local file reads and are bounded by `inspect`, but their wall time depends
594/// on the disk and on how loaded the machine is, which is why the time budget
595/// also applies to them. A fold can take a minute (Git plus deleting
596/// gigabytes of build output), so the fold bound, not the inspect bound, is
597/// what limits how long a pass holds run ownership locks. It never waits for
598/// repository coordination while it holds them (see `graph::fold_run_when`).
599///
600/// The inventory (listing `runs/`, sorting the ids) is not bounded by
601/// `inspect`: it costs one directory listing plus one `is_file` per record on
602/// every pass, i.e. O(history) syscalls. It is counted in the pass's elapsed
603/// time and reported (`FoldTurn::records`, `FoldTurn::elapsed_ms`).
604///
605/// **The bound on revisiting.** A cycle covers the run ids that are not newer
606/// than the persisted high-water mark, the newest id present when it began,
607/// in id order, and then ends; the next pass begins a new cycle. With N records
608/// at the start of a cycle, every one of them is judged within
609/// `ceil(N / inspect)` passes plus the passes its fold invocations consume
610/// (`ceil(F / fold)` for F invocations), plus one more for every pass the time
611/// budget cuts short - a pass can spend the whole budget judging records
612/// without starting a fold, so each such pass is charged by itself. Ids start with the
613/// local wall-clock time of creation, so runs created later sort after the mark
614/// and wait for the next cycle: a growing history cannot postpone the
615/// wraparound. Two things can still put a later run inside the range - one
616/// created in the same second as the mark's, or after the clock stepped
617/// backwards - and each such run adds at most its own judgement to the cycle;
618/// there is no cohort list, so that is the whole bound on them. A run that
619/// left its grace period after being judged is folded within the next cycle:
620/// at most one cycle plus one cycle later.
621pub const BUSY_FOLD_BOUNDS: FoldBounds = FoldBounds {
622    inspect: 64,
623    fold: 4,
624    budget: std::time::Duration::from_secs(300),
625};
626
627/// Why a [`fold_turn`] ended.
628#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
629#[serde(rename_all = "snake_case")]
630pub enum FoldStop {
631    /// Every run of the cycle's range was judged; the next pass starts a new cycle.
632    EndOfCycle,
633    /// The bound on run records judged was reached.
634    InspectLimit,
635    /// The bound on folds started was reached.
636    FoldLimit,
637    /// The wall-clock budget was spent (checked between runs).
638    TimeBudget,
639}
640
641/// What stopped one run, for the receipt: the run, the outcome, and the text.
642#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
643pub struct FoldNote {
644    /// The run id.
645    pub run: String,
646    /// `proof_incomplete` or `failed`.
647    pub outcome: &'static str,
648    /// Scrubbed and clipped to [`NOTE_CHARS`].
649    pub text: String,
650}
651
652/// Notes kept per pass, and characters kept per note.
653const MAX_NOTES: usize = 8;
654const NOTE_CHARS: usize = 300;
655
656/// What one [`fold_turn`] did, per outcome, for the service receipt.
657#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
658pub struct FoldTurn {
659    /// Run records in the history when the pass began (the inventory's size).
660    pub records: usize,
661    /// Run records judged this pass.
662    pub inspected: usize,
663    /// `graph::fold_run_when` invocations this pass (what `bounds.fold` bounds).
664    pub invoked: usize,
665    /// Folds that ran and removed something.
666    pub folded: usize,
667    /// Folds that ran and found nothing left to remove.
668    pub nothing_left: usize,
669    /// Runs the record shows to be folded already; no fold was started.
670    pub already_folded: usize,
671    /// Claimed by a live driver or worker, or a lease/lock of it is held.
672    pub live: usize,
673    /// A resumable status: someone may still continue the run.
674    pub resumable: usize,
675    /// Finished less than `fold_grace_secs` ago.
676    pub within_grace: usize,
677    /// Explicitly retained recovery sources.
678    pub recovery_retained: usize,
679    /// Startup, candidate preservation or the confirmed-merge source proof incomplete.
680    pub proof_incomplete: usize,
681    /// `run.json` could not be parsed, or became unreadable once the run's
682    /// locks were held.
683    pub unreadable: usize,
684    /// The record was deleted while the fold waited for its locks.
685    pub record_gone: usize,
686    /// `graph::fold_run_when` failed (git, filesystem).
687    pub failed: usize,
688    /// Run id the next pass continues after; `None`: it starts a new cycle.
689    pub cursor: Option<String>,
690    /// Last run id of the cycle's range, fixed when the cycle began.
691    pub high_water: Option<String>,
692    /// Why this pass ended.
693    pub stopped: FoldStop,
694    /// Why a new cycle was started although one was saved, when it was
695    /// (unreadable cursor file, high-water mark below the cursor, a cursor
696    /// naming a run that no longer exists).
697    pub cycle_restart: Option<String>,
698    /// The cycle file could not be saved: the next pass repeats this slice.
699    pub cursor_error: Option<String>,
700    /// Wall clock of the pass, inventory included.
701    pub elapsed_ms: u64,
702    /// What stopped the first few `proof_incomplete` and `failed` runs.
703    pub notes: Vec<FoldNote>,
704}
705
706impl FoldTurn {
707    fn begin(records: usize) -> Self {
708        Self {
709            records,
710            inspected: 0,
711            invoked: 0,
712            folded: 0,
713            nothing_left: 0,
714            already_folded: 0,
715            live: 0,
716            resumable: 0,
717            within_grace: 0,
718            recovery_retained: 0,
719            proof_incomplete: 0,
720            unreadable: 0,
721            record_gone: 0,
722            failed: 0,
723            cursor: None,
724            high_water: None,
725            stopped: FoldStop::EndOfCycle,
726            cycle_restart: None,
727            cursor_error: None,
728            elapsed_ms: 0,
729            notes: Vec::new(),
730        }
731    }
732
733    fn record(&mut self, id: &str, judged: Judged) {
734        match judged.outcome {
735            FoldOutcome::Folded => self.folded += 1,
736            FoldOutcome::NothingLeft => self.nothing_left += 1,
737            FoldOutcome::AlreadyFolded => self.already_folded += 1,
738            FoldOutcome::Live => self.live += 1,
739            FoldOutcome::Resumable => self.resumable += 1,
740            FoldOutcome::WithinGrace => self.within_grace += 1,
741            FoldOutcome::Retained => self.recovery_retained += 1,
742            FoldOutcome::ProofIncomplete => self.proof_incomplete += 1,
743            FoldOutcome::Unreadable => self.unreadable += 1,
744            FoldOutcome::RecordGone => self.record_gone += 1,
745            FoldOutcome::Failed => self.failed += 1,
746        }
747        let outcome = match judged.outcome {
748            FoldOutcome::ProofIncomplete => "proof_incomplete",
749            FoldOutcome::Failed => "failed",
750            _ => return,
751        };
752        if let (Some(text), true) = (judged.note, self.notes.len() < MAX_NOTES) {
753            let text = crate::scrub::scrub(&text, &crate::scrub::Identity::current());
754            self.notes.push(FoldNote {
755                run: id.to_owned(),
756                outcome,
757                text: text.chars().take(NOTE_CHARS).collect(),
758            });
759        }
760    }
761}
762
763/// Where one cycle through the history stands, saved between passes.
764///
765/// `high_water` is the last run id that existed when the cycle began; the
766/// cycle covers `(cursor, high_water]` and nothing created later.
767#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
768struct Cycle {
769    cursor: Option<String>,
770    high_water: String,
771}
772
773/// What the cycle file held.
774enum Saved {
775    /// No cycle in progress: the next pass begins one.
776    Absent,
777    Cycle(Cycle),
778    /// The file exists and cannot be used (read failure, bad JSON).
779    Unreadable(String),
780}
781
782/// One bounded, resumable step through finished-run folding.
783///
784/// Continues the saved cycle (or begins one), judges each run with
785/// [`fold_one`] - the same decision, grace, liveness and source-retention
786/// checks as [`fold_due`] - and stops at the first bound in `bounds`. At least
787/// one run is always judged, so a zero budget still makes progress. Returns
788/// the cycle to save: `None` when the cycle's range is exhausted.
789///
790/// A saved cycle that cannot be trusted starts a fresh one, and the receipt
791/// says why (`cycle_restart`): an unreadable file, a high-water mark below the
792/// cursor, a cursor naming a run that no longer exists, or a range with
793/// nothing left in it. Starting over only costs judging runs again.
794async fn fold_turn_from(
795    runs: &Path,
796    home: &Path,
797    disk: &Disk,
798    now: Timestamp,
799    saved: Saved,
800    bounds: FoldBounds,
801) -> (FoldTurn, Option<Cycle>) {
802    let began = std::time::Instant::now();
803    let ids = fold_turn_ids(runs);
804    let mut turn = FoldTurn::begin(ids.len());
805    let mut cycle = match saved {
806        Saved::Absent => None,
807        Saved::Unreadable(why) => {
808            turn.cycle_restart = Some(format!("cursor file unreadable: {why}"));
809            None
810        }
811        Saved::Cycle(cycle) => {
812            let restart = if !crate::run::is_run_id(&cycle.high_water)
813                || cycle
814                    .cursor
815                    .as_deref()
816                    .is_some_and(|cursor| !crate::run::is_run_id(cursor))
817            {
818                Some("cycle file names an id that is not a run id")
819            } else if ids.last().is_none_or(|newest| cycle.high_water > *newest) {
820                Some("high-water mark is newer than every run")
821            } else {
822                match &cycle.cursor {
823                    Some(cursor) if *cursor > cycle.high_water => {
824                        Some("high-water mark is below the cursor")
825                    }
826                    Some(cursor) if ids.binary_search(cursor).is_err() => {
827                        Some("cursor names a run that no longer exists")
828                    }
829                    _ => None,
830                }
831            };
832            match restart {
833                Some(why) => {
834                    turn.cycle_restart = Some(why.into());
835                    None
836                }
837                None => Some(cycle),
838            }
839        }
840    };
841    let range = |cycle: &Cycle| {
842        let start = cycle
843            .cursor
844            .as_deref()
845            .map_or(0, |c| ids.partition_point(|id| id.as_str() <= c));
846        let end = ids.partition_point(|id| id.as_str() <= cycle.high_water.as_str());
847        (start, end)
848    };
849    if cycle.as_ref().is_some_and(|c| {
850        let (start, end) = range(c);
851        start >= end
852    }) {
853        turn.cycle_restart = Some("the saved cycle had nothing left in its range".into());
854        cycle = None;
855    }
856    let Some(cycle) = cycle.or_else(|| {
857        ids.last().map(|last| Cycle {
858            cursor: None,
859            high_water: last.clone(),
860        })
861    }) else {
862        turn.elapsed_ms = began.elapsed().as_millis() as u64;
863        return (turn, None);
864    };
865    turn.high_water = Some(cycle.high_water.clone());
866    let (start, end) = range(&cycle);
867    let mut begun = 0usize;
868    let mut last: Option<&String> = None;
869    let mut next = None;
870    for id in &ids[start..end] {
871        let stop = if turn.inspected == 0 {
872            None
873        } else if turn.inspected >= bounds.inspect {
874            Some(FoldStop::InspectLimit)
875        } else if begun >= bounds.fold {
876            Some(FoldStop::FoldLimit)
877        } else if began.elapsed() >= bounds.budget {
878            Some(FoldStop::TimeBudget)
879        } else {
880            None
881        };
882        if let Some(stop) = stop {
883            turn.stopped = stop;
884            turn.cursor = last.cloned();
885            next = Some(Cycle {
886                cursor: last.cloned(),
887                high_water: cycle.high_water.clone(),
888            });
889            break;
890        }
891        turn.inspected += 1;
892        last = Some(id);
893        let judged = fold_one(runs, home, disk, now, id, true, &mut || begun += 1).await;
894        turn.record(id, judged);
895    }
896    turn.invoked = begun;
897    turn.elapsed_ms = began.elapsed().as_millis() as u64;
898    (turn, next)
899}
900
901/// Where [`fold_turn`] remembers its cycle: JSON `{cursor, high_water}`. Absent
902/// means "no cycle in progress", an unusable file starts a new one and is
903/// reported; either only costs judging runs again.
904const FOLD_TURN_CURSOR_FILE: &str = "fold-turn-cursor";
905
906fn read_cycle(home: &Path) -> Saved {
907    match std::fs::read(home.join(FOLD_TURN_CURSOR_FILE)) {
908        Ok(body) => match serde_json::from_slice(&body) {
909            Ok(cycle) => Saved::Cycle(cycle),
910            Err(e) => Saved::Unreadable(e.to_string()),
911        },
912        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Saved::Absent,
913        Err(e) => Saved::Unreadable(e.to_string()),
914    }
915}
916
917fn write_cycle(home: &Path, cycle: Option<&Cycle>) -> Result<()> {
918    let path = home.join(FOLD_TURN_CURSOR_FILE);
919    match cycle {
920        Some(cycle) => crate::fold_evidence::atomic_write(&path, &serde_json::to_vec(cycle)?),
921        None => match std::fs::remove_file(&path) {
922            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
923            _ => Ok(()),
924        },
925    }
926}
927
928/// [`fold_turn_from`] continuing from, and saving, the persisted cycle.
929///
930/// The cycle is saved after every pass, before the caller reports it, so a
931/// restart resumes where this pass ended. A save failure is reported in
932/// [`FoldTurn::cursor_error`] rather than hidden: the next pass would then
933/// repeat the same slice, and the receipt must say so. Passes never overlap:
934/// the scheduler admits one `fold` service worker at a time.
935pub async fn fold_turn(
936    runs: &Path,
937    home: &Path,
938    disk: &Disk,
939    now: Timestamp,
940    bounds: FoldBounds,
941) -> FoldTurn {
942    let (mut turn, next) = fold_turn_from(runs, home, disk, now, read_cycle(home), bounds).await;
943    if let Err(e) = write_cycle(home, next.as_ref()) {
944        tracing::warn!("housekeep: persist the fold turn's cycle: {e:#}");
945        turn.cursor_error = Some(format!("{e:#}"));
946    }
947    turn
948}
949
950/// What one [`fetch_origins`] pass did.
951#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
952pub struct FetchReport {
953    /// Repos whose fetch succeeded.
954    pub fetched: usize,
955    /// Repos with no `origin` remote, skipped.
956    pub no_origin: usize,
957    /// Repos whose fetch failed or timed out.
958    pub failed: usize,
959}
960
961/// Run `git fetch origin` in every checkout under `roots` (the set `magi
962/// repos` lists), so `origin/main` stays current.
963///
964/// Fetch only: never a checkout, merge or fast-forward, so no HEAD, branch or
965/// working tree moves. Best-effort like [`fold_due`]: a repo with no `origin`
966/// is skipped silently, a failure or timeout is a warning, and the pass never
967/// errors. `stop` is checked between repos.
968pub async fn fetch_origins(
969    roots: &[PathBuf],
970    per_repo: std::time::Duration,
971    stop: impl Fn() -> bool,
972) -> FetchReport {
973    let mut report = FetchReport::default();
974    for repo in crate::repos::scan(roots) {
975        if stop() {
976            break;
977        }
978        match crate::git::git_raw(&repo.path, &["remote", "get-url", "origin"]).await {
979            Ok(out) if out.ok() => {}
980            _ => {
981                report.no_origin += 1;
982                continue;
983            }
984        }
985        match crate::git::fetch_origin(&repo.path, per_repo).await {
986            Ok(()) => report.fetched += 1,
987            Err(e) => {
988                tracing::warn!("fetch origin in {}: {e:#}", repo.name);
989                report.failed += 1;
990            }
991        }
992    }
993    report
994}
995
996/// Is `updated` old enough, measured against `now`, that the run may fold?
997///
998/// Pure; the janitor compares against wallclock, tests inject both sides. The
999/// comparison is strict, so a run exactly at the edge of its grace period is
1000/// left alone one more pass — the same convention as [`crate::disk::over_limit`].
1001pub fn due(now: Timestamp, updated: Timestamp, grace_secs: u64) -> bool {
1002    now.duration_since(updated) > SignedDuration::new(grace_secs as i64, 0)
1003}
1004
1005/// The two fields the janitor decides on, read with a serde that tolerates
1006/// everything else about the run being unreadable.
1007#[derive(Deserialize)]
1008struct Meta {
1009    /// Absent from records too broken to say; present, it must name the
1010    /// directory the record was read from.
1011    #[serde(default)]
1012    id: Option<String>,
1013    status: RunStatus,
1014    updated_at: Timestamp,
1015}
1016
1017/// Read `status` and `updated_at` straight off the state file, asking for
1018/// nothing else. `Err` when the file is missing, not parseable, a status in
1019/// a version this build does not speak, or the record of another run than the
1020/// directory's - all of which mean "unreadable".
1021fn read_meta(runs: &Path, id: &str) -> Result<Meta> {
1022    let path = runs.join(id).join("run.json");
1023    let body =
1024        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
1025    let meta: Meta =
1026        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1027    if let Some(recorded) = &meta.id {
1028        anyhow::ensure!(
1029            recorded == id,
1030            "runs/{id}/run.json records run {recorded}, not run {id}"
1031        );
1032    }
1033    Ok(meta)
1034}
1035
1036/// Runs checked against GitHub in one janitor pass, at most.
1037///
1038/// A fleet with many stuck runs must not turn every idle tick into a burst of
1039/// `gh pr list` calls; a run left unchecked this pass is checked again next
1040/// pass, same as an unfolded due run is.
1041const MAX_EXTERNAL_MERGE_CHECKS_PER_PASS: usize = 5;
1042
1043/// The fields [`reconcile_external_merges`] filters on before paying for a
1044/// full [`RunState`] parse or a `gh` round trip.
1045#[derive(Deserialize)]
1046struct ExternalMergeMeta {
1047    status: RunStatus,
1048    updated_at: Timestamp,
1049    #[serde(default)]
1050    merge: Option<crate::run::MergeOutcome>,
1051}
1052
1053fn read_external_merge_meta(runs: &Path, id: &str) -> Result<ExternalMergeMeta> {
1054    let path = runs.join(id).join("run.json");
1055    let body =
1056        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
1057    let meta: ExternalMergeMeta =
1058        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1059    Ok(meta)
1060}
1061
1062/// Is a run worth asking GitHub about?
1063///
1064/// Pure, so the filter itself is assertable without a fixture that writes
1065/// `run.json` files or spawns `gh`. Narrower than "blocked": `merge_recorded`
1066/// excludes a run `land::land` already finished landing (successfully or
1067/// not) - that path already carries its own record of what happened - and
1068/// `due` gives an operator who is about to fix a run by hand a grace window
1069/// before the janitor starts asking the same question about it.
1070pub fn eligible_for_external_merge_check(
1071    status: RunStatus,
1072    merge_recorded: bool,
1073    updated_at: Timestamp,
1074    now: Timestamp,
1075    grace_secs: u64,
1076) -> bool {
1077    status == RunStatus::Blocked && !merge_recorded && due(now, updated_at, grace_secs)
1078}
1079
1080/// Rotate `ids` so a fixed per-pass cap does not always land on the same
1081/// prefix of the list, starting at `start` (already reduced modulo nothing -
1082/// callers pass whatever a persisted cursor last recorded, and this takes it
1083/// modulo `ids.len()` itself).
1084///
1085/// Pure: the offset is the caller's problem, not wall-clock time. An earlier
1086/// version derived `start` from `now.as_second() % ids.len()`, which looked
1087/// independent of any state to persist but is not actually independent of
1088/// how often the janitor runs - a poll interval and a pass's own duration
1089/// that alias onto the same handful of `now.as_second()` values (say, a
1090/// ten-second poll and a pass that finishes in under a second) revisit only
1091/// those same few residues forever and never advance into the rest of the
1092/// list at all. [`reconcile_external_merges`] instead persists a cursor
1093/// across passes ([`read_external_merge_cursor`] /
1094/// [`write_external_merge_cursor`]) and advances it by exactly how many ids
1095/// this pass actually looked at, which is the only quantity that is
1096/// guaranteed to move forward pass over pass regardless of timing.
1097fn rotate_from(ids: &[String], start: usize) -> Vec<String> {
1098    if ids.is_empty() {
1099        return Vec::new();
1100    }
1101    let start = start % ids.len();
1102    ids[start..]
1103        .iter()
1104        .chain(ids[..start].iter())
1105        .cloned()
1106        .collect()
1107}
1108
1109/// Where [`reconcile_external_merges`] remembers how far it got, so a fixed
1110/// per-pass cap advances through a fleet's eligible runs pass over pass
1111/// instead of camping on whichever ones happen to sort first.
1112const EXTERNAL_MERGE_CURSOR_FILE: &str = "external-merge-cursor";
1113
1114/// `0` for anything this cannot read as a plain number - a first run, a
1115/// corrupt or missing file, a build that has never written one - which is
1116/// exactly as good a starting point as any: the cursor's whole job is to
1117/// keep moving, not to encode any particular position as meaningful.
1118fn read_external_merge_cursor(home: &Path) -> usize {
1119    std::fs::read_to_string(home.join(EXTERNAL_MERGE_CURSOR_FILE))
1120        .ok()
1121        .and_then(|s| s.trim().parse().ok())
1122        .unwrap_or(0)
1123}
1124
1125/// Best-effort, like every other write in this module's sweep: a failure to
1126/// persist the cursor costs the fleet one pass's worth of forward progress
1127/// on this sweep, never the run whose housekeeping it is racing to keep up
1128/// with.
1129fn write_external_merge_cursor(home: &Path, cursor: usize) {
1130    if let Err(e) = std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), cursor.to_string()) {
1131        tracing::warn!("housekeep: persist the external-merge sweep's cursor: {e:#}");
1132    }
1133}
1134
1135/// Close the gap `magi fold --merged` exists for, without waiting for an
1136/// operator to notice and go find the pull request URL: a run that stopped
1137/// `Blocked` with no `merge` recorded may have been merged anyway, by hand,
1138/// on a pull request `land::land` never opened or never got to observe as
1139/// merged. `land::find_external_merge` asks GitHub about the run's own
1140/// winning branch, and only a pull request it can uniquely tie back to this
1141/// run is ever acted on - see that function's own doc for what "uniquely"
1142/// excludes.
1143///
1144/// A run this finds and fixes goes through
1145/// [`crate::land::correct_confirmed_external_merge`] - the same correction
1146/// `magi fold --merged` performs, minus the same-repo guard that command
1147/// needs and this loop doesn't (see that function's own doc: the URL here
1148/// was never operator-supplied, it came from asking `state.repo`'s own
1149/// remote) - then through [`crate::graph::fold_run`] so it stops holding
1150/// worktrees the moment it stops needing them. A run this cannot decide
1151/// about - `gh` unreachable, more than one candidate pull
1152/// request, nothing found at all - is left exactly as it is; only an error
1153/// asking GitHub raises a notice, since "nothing found" is the ordinary,
1154/// expected shape of a run that really is just blocked.
1155async fn reconcile_external_merges(runs: &Path, home: &Path, disk: &Disk, now: Timestamp) -> usize {
1156    reconcile_external_merges_with(runs, home, disk, now, |state| async move {
1157        crate::land::find_external_merge(&state).await
1158    })
1159    .await
1160}
1161
1162async fn reconcile_external_merges_with<F, Fut>(
1163    runs: &Path,
1164    home: &Path,
1165    disk: &Disk,
1166    now: Timestamp,
1167    check: F,
1168) -> usize
1169where
1170    F: Fn(RunState) -> Fut,
1171    Fut: std::future::Future<Output = Result<Option<crate::land::ExternalMerge>>>,
1172{
1173    let mut ids: Vec<String> = std::fs::read_dir(runs)
1174        .into_iter()
1175        .flatten()
1176        .flatten()
1177        .filter(|e| e.path().join("run.json").is_file())
1178        .map(|e| e.file_name().to_string_lossy().into_owned())
1179        .collect();
1180    ids.sort_unstable();
1181
1182    // Every eligible id first, cheaply (a `Meta` read, no `gh`), then rotated
1183    // before the cap is applied. Capping the sorted order directly would
1184    // always land on the same lexicographic prefix - a fleet's oldest run ids
1185    // - so a handful of long-blocked runs that never turn out to be merged
1186    // would starve every id after them of a `gh` check, forever.
1187    let mut eligible: Vec<String> = Vec::new();
1188    for id in ids {
1189        if crate::daemon::is_working_on(home, &id, now) {
1190            continue;
1191        }
1192        let meta = match read_external_merge_meta(runs, &id) {
1193            Ok(meta) => meta,
1194            // Already counted as unreadable by `fold_due`'s own pass; not
1195            // worth a second warning for the same file.
1196            Err(_) => continue,
1197        };
1198        if eligible_for_external_merge_check(
1199            meta.status,
1200            meta.merge.is_some(),
1201            meta.updated_at,
1202            now,
1203            disk.fold_grace_secs,
1204        ) {
1205            eligible.push(id);
1206        }
1207    }
1208
1209    if eligible.is_empty() {
1210        return 0;
1211    }
1212    let cursor = read_external_merge_cursor(home);
1213    let window: Vec<String> = rotate_from(&eligible, cursor)
1214        .into_iter()
1215        .take(MAX_EXTERNAL_MERGE_CHECKS_PER_PASS)
1216        .collect();
1217    // Advances by exactly how many ids this pass looked at, regardless of
1218    // what came of looking - a run that turned out not to be merged after
1219    // all must not be revisited before every other eligible run has had its
1220    // own turn.
1221    write_external_merge_cursor(home, (cursor + window.len()) % eligible.len());
1222
1223    let mut reconciled = 0usize;
1224    for id in window {
1225        let mut state = match read_state(runs, &id) {
1226            Ok(state) => state,
1227            Err(_) => continue,
1228        };
1229        if let Ok(record) = serde_json::to_value(&state)
1230            && let Some(reason) =
1231                crate::external_merge_attention::historical_reason(home, &id, &record)
1232        {
1233            tracing::info!("housekeep: external merge for {id}: {reason}");
1234            continue;
1235        }
1236        match check(state.clone()).await {
1237            Ok(Some(found)) => {
1238                match crate::land::correct_confirmed_external_merge(&mut state, &found.url).await {
1239                    Ok(_) => {
1240                        if let Err(e) = fold_recorded_merge(&mut state, home, now).await {
1241                            tracing::warn!(
1242                                "housekeep: fold {id} after recording its external merge: {e:#}"
1243                            );
1244                        }
1245                        reconciled += 1;
1246                    }
1247                    Err(e) => tracing::warn!(
1248                        "housekeep: record external merge {} for {id}: {e:#}",
1249                        found.url
1250                    ),
1251                }
1252            }
1253            Ok(None) => {}
1254            Err(e) => {
1255                tracing::warn!("housekeep: check external merge for {id}: {e:#}");
1256                crate::notices::raise_in(
1257                    home,
1258                    crate::notices::Notice::warn(
1259                        &format!("merged-unrecorded:{id}"),
1260                        format!(
1261                            "Run {id} is blocked with no recorded merge, and checking GitHub \
1262                             for a merge failed; check by hand."
1263                        ),
1264                    )
1265                    .link(crate::notices::Link::Run { id: id.clone() }),
1266                );
1267            }
1268        }
1269    }
1270    reconciled
1271}
1272
1273/// Read a whole run state from a runs directory, for folding only.
1274///
1275/// Deliberately more permissive than [`RunState::load`], which this does not
1276/// call: `load` backs `--resume` and every hand-driven command, where a
1277/// schema this build disagrees with the *meaning* of must refuse outright
1278/// rather than resume a review round or a tally against stale semantics
1279/// (`RunState::SCHEMA`'s own docs list what has changed meaning at each
1280/// bump). Folding recomputes nothing - it only reads worktree paths, branch
1281/// names and a tally winner off the struct to remove them - so an old
1282/// schema's values are exactly as good here as a current one's; every schema
1283/// bump so far has only ever added a field or a variant, never repurposed an
1284/// existing one, and serde already fills an added field's default when an
1285/// older record has nothing to say about it. What this cannot tolerate, and
1286/// what still surfaces as an `Err`, is `run.json` failing to parse at all.
1287fn read_state(runs: &Path, id: &str) -> Result<RunState> {
1288    let state = RunState::read_unmigrated(&runs.join(id).join("run.json"))?;
1289    state.ensure_directory(id)?;
1290    Ok(state)
1291}
1292
1293/// Remove only verified clean Git worktrees and empty directory scaffolding.
1294/// Unknown files or unreadable Git state require recovery, never recursive deletion.
1295async fn remove_clean_bay(root: &Path) -> Result<()> {
1296    let mut pending = vec![root.to_path_buf()];
1297    let mut directories = Vec::new();
1298    let mut worktrees = Vec::new();
1299    while let Some(path) = pending.pop() {
1300        if path.join(".git").exists() {
1301            if !crate::git::is_clean(&path).await? {
1302                anyhow::bail!("uncommitted work in {}; recovery required", path.display());
1303            }
1304            worktrees.push(path);
1305        } else {
1306            for entry in std::fs::read_dir(&path)? {
1307                let entry = entry?;
1308                if !entry.file_type()?.is_dir() {
1309                    anyhow::bail!(
1310                        "unknown worktree content in {}; recovery required",
1311                        path.display()
1312                    );
1313                }
1314                pending.push(entry.path());
1315            }
1316            directories.push(path);
1317        }
1318    }
1319    for path in worktrees {
1320        if !crate::git::worktree_remove_clean(&path, &path).await? {
1321            anyhow::bail!("clean worktree removal refused: {}", path.display());
1322        }
1323    }
1324    for path in directories.into_iter().rev() {
1325        std::fs::remove_dir(path)?;
1326    }
1327    Ok(())
1328}
1329
1330/// A run's lock is held by somebody: a [`DeleteRefused`] that says so. Any other
1331/// failure of the lock call stays what it was.
1332fn busy_run(id: &str) -> impl Fn(anyhow::Error) -> anyhow::Error + '_ {
1333    move |e| {
1334        if crate::graph::held_by_live_owner(&e) {
1335            DeleteRefused(format!(
1336                "run {id} is being worked on or folded right now ({e:#}); try again later"
1337            ))
1338            .into()
1339        } else {
1340            e
1341        }
1342    }
1343}
1344
1345/// Remove a run that cannot be read: its state directory under `runs` and its
1346/// worktree directory under `worktrees_root`.
1347///
1348/// Inspect worktrees before deleting any state or artifacts. Only clean registered
1349/// worktrees and empty directory scaffolding can be reclaimed; unknown or dirty
1350/// content remains available for recovery. Nonstandard worktree roots remain the
1351/// operator's responsibility when the state file cannot identify them.
1352pub async fn fold_unreadable(runs: &Path, worktrees_root: &Path, id: &str) -> Result<Vec<String>> {
1353    let resolved = resolve_id_path(runs, id)?;
1354    ensure_record_identity(runs, &resolved)?;
1355    let mut removed = Vec::new();
1356    let run_dir = runs.join(&resolved);
1357    // The two locks every writer of the record takes, held until the directory
1358    // is gone: a fold in progress makes this a refusal, not a race.
1359    let locks = if run_dir.is_dir()
1360        && let Some(home) = runs.parent()
1361    {
1362        let busy = busy_run(&resolved);
1363        Some((
1364            crate::pr_head::owner_lock(home, &resolved).map_err(&busy)?,
1365            crate::driver::maintenance(home, &resolved).map_err(&busy)?,
1366        ))
1367    } else {
1368        None
1369    };
1370    let wt = worktrees_root.join(short_of(&resolved));
1371    if wt.exists() {
1372        remove_clean_bay(&wt).await?;
1373        removed.push(wt.to_string_lossy().into_owned());
1374    }
1375    // Keep the recovery artifacts if any worktree could not be removed safely.
1376    if run_dir.exists() {
1377        // With both guards held the directory leaves through the tombstone, like
1378        // a deleted run's, so its lock files and `run.json` disappear together.
1379        match (&locks, runs.parent()) {
1380            (Some(_), Some(home)) => remove_run_dir(home, &resolved, &run_dir)?,
1381            _ => std::fs::remove_dir_all(&run_dir)
1382                .with_context(|| format!("remove {}", run_dir.display()))?,
1383        }
1384        removed.push(format!("runs/{resolved}"));
1385    }
1386    Ok(removed)
1387}
1388
1389/// Reclaim worktrees under `worktrees_root` that no run record in `runs`
1390/// claims anymore, and return how many were removed.
1391///
1392/// [`fold_due`] only ever sees a worktree by walking `runs/` first, so a
1393/// worktree whose run record is already gone — `magi run rm`, or a record
1394/// deleted before its worktree — never enters that loop at all: nothing there
1395/// is looking for it. This walks the worktree bay directly instead, and
1396/// removes any `<short>` directory that no run id maps to.
1397///
1398/// Two things must never happen, and this checks both before ever touching a
1399/// directory:
1400///
1401/// - **A worktree bay is never the only kind of thing under `worktrees_root`,
1402///   and this must not assume it is.** A hand-placed scratch directory, or
1403///   anything else an operator or another tool left in the same bay, has the
1404///   same "no run claims it" shape as a genuine orphan but is not one -
1405///   [`looks_like_a_worktree_bay`] is the same tag shape [`crate::run::is_run_id`]
1406///   already requires of a real run's short id, and anything else is left
1407///   alone regardless of what else is true about it.
1408/// - **A worktree that was only just created might not have a `run.json` yet
1409///   for a reason that has nothing to do with being orphaned.** `Runner::start`
1410///   and `Runner::review` both create the worktree before the first
1411///   `RunState::save` lands, and that gap - several `git` subprocesses wide -
1412///   is invisible to [`crate::daemon::is_working_on_short`] whenever the run
1413///   is not being driven through this daemon's own `poll` loop at all (a
1414///   `magi review` invocation, for one). A directory whose own modification
1415///   time is within `grace_secs` of `now` is left alone on that basis alone,
1416///   the same margin [`fold_due`] gives a run before treating it as truly
1417///   finished - long enough that no realistic gap between a `worktree add`
1418///   and its `run.json` could ever be mistaken for one.
1419///
1420/// The one failure this must never cause is deleting the worktree of a run
1421/// that is genuinely in flight. [`crate::daemon::is_working_on_short`] is the
1422/// same liveness check [`fold_due`] trusts everywhere else in this module,
1423/// checked by short id because there is no full id to compare here; when it
1424/// cannot tell, this leaves the directory alone. Best-effort like the rest of
1425/// housekeeping: one directory git or the filesystem refuses to give up is a
1426/// `tracing::warn`, not a reason to abandon the rest of the pass.
1427pub async fn fold_orphaned_worktrees(
1428    runs: &Path,
1429    worktrees_root: &Path,
1430    home: &Path,
1431    grace_secs: u64,
1432    now: Timestamp,
1433) -> usize {
1434    let known: std::collections::HashSet<String> = std::fs::read_dir(runs)
1435        .into_iter()
1436        .flatten()
1437        .flatten()
1438        .map(|e| e.file_name().to_string_lossy().into_owned())
1439        .filter(|name| crate::run::is_run_id(name))
1440        .map(|id| short_of(&id).to_owned())
1441        .collect();
1442
1443    let mut folded = 0usize;
1444    for entry in std::fs::read_dir(worktrees_root)
1445        .into_iter()
1446        .flatten()
1447        .flatten()
1448    {
1449        if !entry.path().is_dir() {
1450            continue;
1451        }
1452        let short = entry.file_name().to_string_lossy().into_owned();
1453        if !looks_like_a_worktree_bay(&short) {
1454            continue;
1455        }
1456        if known.contains(&short) || crate::daemon::is_working_on_short(home, &short, now) {
1457            continue;
1458        }
1459        let wt = entry.path();
1460        if !stale_enough(&wt, grace_secs, now) {
1461            continue;
1462        }
1463        match remove_clean_bay(&wt).await {
1464            Ok(()) => folded += 1,
1465            Err(e) => tracing::warn!(
1466                "housekeep: remove orphaned worktree {}: {e:#}",
1467                wt.display()
1468            ),
1469        }
1470    }
1471    folded
1472}
1473
1474/// Does `name` have the shape a run's own worktree bay is named with: the
1475/// same 4-character alphanumeric tag [`crate::run::is_run_id`] requires of a
1476/// full id's trailing block (see [`short_of`])?
1477///
1478/// Anything else under `worktrees_root` is not a bay this function reclaims
1479/// at all, claimed or not - answering "does a run claim this?" about a
1480/// directory that was never a run's worktree in the first place is exactly
1481/// the wrong question to ask before deleting it.
1482fn looks_like_a_worktree_bay(name: &str) -> bool {
1483    name.len() == 4 && name.bytes().all(|b| b.is_ascii_alphanumeric())
1484}
1485
1486/// Is `dir`'s own modification time old enough, against `grace_secs` and
1487/// `now`, that its emptiness of a run record can be trusted rather than
1488/// caught mid-creation?
1489///
1490/// A directory this pass cannot stat at all - a race with its own removal, a
1491/// permission error - is treated as not yet stale: unreadable metadata is not
1492/// evidence of anything, and the janitor already keeps rather than deletes
1493/// whenever it cannot tell (see the module docs).
1494///
1495/// `grace_secs` is floored at [`MIN_ORPHAN_AGE_SECS`] regardless of what the
1496/// caller passes: `0` is a documented, legitimate value for
1497/// [`crate::config::Disk::fold_grace_secs`] (`due`'s own "always due" case),
1498/// because that grace answers a policy question the operator owns - how long
1499/// a *known, finished* run's worktree lingers before cleanup. Whether an
1500/// orphan worktree is actually a race with `Runner::review`'s `git worktree
1501/// add` landing before its `run.json` is not a policy question, and must not
1502/// collapse to zero just because the operator turned the other grace off -
1503/// that would defeat the very check meant to catch it.
1504fn stale_enough(dir: &Path, grace_secs: u64, now: Timestamp) -> bool {
1505    let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) else {
1506        return false;
1507    };
1508    let Ok(ts) = Timestamp::try_from(modified) else {
1509        return false;
1510    };
1511    due(now, ts, grace_secs.max(MIN_ORPHAN_AGE_SECS))
1512}
1513
1514/// The floor under [`stale_enough`]'s grace, independent of
1515/// [`crate::config::Disk::fold_grace_secs`].
1516///
1517/// Ample next to the race it guards: the gap between `Runner::start` or
1518/// `Runner::review` creating a worktree and the first `RunState::save`
1519/// landing is a handful of `git` subprocess calls, not minutes - but the
1520/// janitor cannot tell "still mid-setup" from "orphaned" by any other signal
1521/// for a run that never registers with `daemon::Status` at all (a `magi
1522/// review` invocation, for one), so this is generous on purpose rather than
1523/// tuned to the observed case.
1524const MIN_ORPHAN_AGE_SECS: u64 = 5 * 60;
1525
1526/// Resolve an id or prefix against an explicit runs directory, exactly the way
1527/// [`crate::run::resolve_id`] does against the global home.
1528fn resolve_id_path(runs: &Path, prefix: &str) -> Result<String> {
1529    // Keyed on the directory, not on a readable state file: the record this
1530    // route exists to remove may be a lone `run.json.tmp` from a save that
1531    // ran out of disk, and that is precisely the one a human needs a way to
1532    // clear (see `crate::run::list_ids`).
1533    if runs.join(prefix).is_dir() && crate::run::is_run_id(prefix) {
1534        return Ok(prefix.to_owned());
1535    }
1536    let mut hits: Vec<String> = Vec::new();
1537    for e in std::fs::read_dir(runs).into_iter().flatten().flatten() {
1538        if !e.path().is_dir() {
1539            continue;
1540        }
1541        let id = e.file_name().to_string_lossy().into_owned();
1542        if crate::run::is_run_id(&id) && (id.starts_with(prefix) || id.ends_with(prefix)) {
1543            hits.push(id);
1544        }
1545    }
1546    match hits.len() {
1547        1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1548        0 => bail!("no run matches `{prefix}`"),
1549        _ => bail!(
1550            "`{prefix}` matches {} runs: {}",
1551            hits.len(),
1552            hits.join(", ")
1553        ),
1554    }
1555}
1556
1557/// `magi fold`'s recovery path for a run whose worktrees are already gone —
1558/// so [`crate::graph::fold_run`] removed nothing — but whose `run.json` still
1559/// lists active seats nobody is left to answer for: no live daemon claims the
1560/// run, and every one of those seats has overrun its own timeout (see
1561/// [`RunState::active_all_overrun`]). Clearing them and failing the run is
1562/// what lets it be deleted afterward — [`RunState::ensure_can_delete`] only
1563/// ever checks whether a live daemon is working on the run and whether its
1564/// candidates are folded, not `status`, but a run stuck `implementing`
1565/// forever with an empty worktree still reads as unresolved everywhere else
1566/// (`magi show`, the deck, the phone) until this runs.
1567///
1568/// Returns `false` without changing anything when a live daemon still claims
1569/// the run, or when some active seat has not actually overrun its budget yet
1570/// — a run that is merely between waves must never be guessed at.
1571///
1572/// `state` is only the caller's first look. The record is written under the
1573/// run's owner lock and execution lease (the locks `graph::fold_run` and a
1574/// handover take), read again once they are held, and the conditions above are
1575/// judged on that record; `state` is replaced by it. Saving the caller's copy
1576/// would erase a handover (`released_to` / `released_branches`) that landed
1577/// after the fold released its own locks. A lock held by somebody else, or a
1578/// record that is gone, changes nothing and answers `false`.
1579pub fn clear_abandoned_active(state: &mut RunState, home: &Path, now: Timestamp) -> Result<bool> {
1580    let id = state.id.clone();
1581    if !home.join("runs").join(&id).join("run.json").try_exists()? {
1582        return Ok(false);
1583    }
1584    let Some(_owner) = uncontended(crate::pr_head::owner_lock(home, &id))? else {
1585        return Ok(false);
1586    };
1587    let Some(_driver) = uncontended(crate::driver::maintenance(home, &id))? else {
1588        return Ok(false);
1589    };
1590    match RunState::load_under(&id, home) {
1591        Ok(fresh) if fresh.id == id => *state = fresh,
1592        Err(e)
1593            if e.chain().any(|cause| {
1594                cause
1595                    .downcast_ref::<std::io::Error>()
1596                    .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
1597            }) =>
1598        {
1599            return Ok(false);
1600        }
1601        Ok(_) => return Ok(false),
1602        Err(e) => return Err(e),
1603    }
1604    if crate::daemon::is_working_on(home, &id, now) || !state.active_all_overrun(now) {
1605        return Ok(false);
1606    }
1607    state.abandon("fold");
1608    state.save_under(home)?;
1609    // The seat that asked is gone for good now - the same door
1610    // `graph::Runner::settle_questions` closes the moment `status` lands
1611    // somewhere non-resumable, see that method's own doc. Without this, an
1612    // open question the abandoned seat left behind would keep badging the
1613    // operator until the next daemon startup's `abandon_settled_questions`
1614    // pass happened to notice it, or forever if nothing is running `magi
1615    // serve` at all.
1616    if let Err(e) = Questions::at(home.join("questions")).settle_run(&state.id, state.status) {
1617        tracing::warn!("abandon questions for {}: {e:#}", state.id);
1618    }
1619    Ok(true)
1620}
1621
1622/// `Some(lock)`, or `None` when somebody else holds it; any other failure of
1623/// the lock call stays an error.
1624fn uncontended<T>(locked: Result<T>) -> Result<Option<T>> {
1625    match locked {
1626        Err(e) if crate::graph::held_by_live_owner(&e) => Ok(None),
1627        other => other.map(Some),
1628    }
1629}
1630
1631/// Why [`delete_run`] left a run record alone: somebody holds the run, it is
1632/// not finished with its worktrees, or it is gone. Callers answer a refusal
1633/// with a conflict and anything else with a failure.
1634#[derive(Debug)]
1635pub struct DeleteRefused(pub String);
1636
1637impl std::fmt::Display for DeleteRefused {
1638    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1639        f.write_str(&self.0)
1640    }
1641}
1642
1643impl std::error::Error for DeleteRefused {}
1644
1645/// Delete a run's directory (`magi run rm`, the phone's delete button) under
1646/// the protocol every writer of the run record follows.
1647///
1648/// A fold (`graph::fold_run*`) holds the run's owner lock and execution lease
1649/// from the moment it locks the record until it has saved it, and acts on what
1650/// it reads once they are held. A deletion that took no part in that let the
1651/// record vanish under a fold - which then recreated it from a stale copy - and
1652/// let the run's four-character worktree suffix be reserved by a new run while
1653/// the fold was still deleting that suffix's directories. So the deletion takes
1654/// both locks without waiting (a held lock means the run is busy, and the
1655/// answer is a refusal, not a wait), reads the record under them, and judges
1656/// [`RunState::ensure_can_delete`] on that read, not on the caller's.
1657pub fn delete_run(home: &Path, id: &str, now: Timestamp) -> Result<()> {
1658    let dir = home.join("runs").join(id);
1659    if !dir.join("run.json").try_exists()? {
1660        return Err(DeleteRefused(format!("run {id}: record gone")).into());
1661    }
1662    let busy = busy_run(id);
1663    let _owner = crate::pr_head::owner_lock(home, id).map_err(&busy)?;
1664    let _driver = crate::driver::maintenance(home, id).map_err(&busy)?;
1665    let state = RunState::load_under(id, home)?;
1666    state
1667        .ensure_can_delete(crate::daemon::is_working_on(home, id, now))
1668        .map_err(|e| DeleteRefused(format!("{e:#}")))?;
1669    remove_run_dir(home, id, &dir)
1670}
1671
1672/// Where a removed run's directory waits, for the moment between its rename
1673/// and its removal. Nothing scans it: `runs/` is what every reader lists.
1674fn graveyard(home: &Path) -> PathBuf {
1675    home.join("deleted-runs")
1676}
1677
1678/// Remove what earlier deletions left in the graveyard: a process killed
1679/// between the rename and the removal leaves a complete run directory there,
1680/// invisible to every inventory and report. The run was already authorised for
1681/// deletion when it was moved and nothing else reads the directory, so any
1682/// entry is a leftover. Best effort: an entry that cannot be removed now (a
1683/// deletion in another process is removing it this very moment, a file in use)
1684/// is tried again by the next deletion or housekeeping pass. Returns how many
1685/// entries are gone.
1686pub fn sweep_graveyard(home: &Path) -> usize {
1687    let mut removed = 0;
1688    for entry in std::fs::read_dir(graveyard(home))
1689        .into_iter()
1690        .flatten()
1691        .flatten()
1692    {
1693        let path = entry.path();
1694        let gone = match std::fs::remove_dir_all(&path) {
1695            Ok(()) => true,
1696            Err(e) => {
1697                // Taken by a concurrent sweep or deletion: nothing left to do.
1698                if !matches!(path.try_exists(), Ok(false)) {
1699                    tracing::warn!("housekeep: remove leftover {}: {e}", path.display());
1700                }
1701                false
1702            }
1703        };
1704        removed += usize::from(gone);
1705    }
1706    removed
1707}
1708
1709/// Remove a run's directory while the caller still holds both of its guards, so
1710/// that the lock files and `run.json` disappear together.
1711///
1712/// Holding a file lock does not stop the file being unlinked (on Unix), and
1713/// unlinking the lock files one by one while `run.json` was still there let a
1714/// concurrent fold open replacement lock files and read the record of a run
1715/// being deleted. The directory is first renamed - one atomic step - to a
1716/// tombstone outside `runs/`, which nothing scans, and removed there. Where a
1717/// directory with open files in it cannot be renamed (Windows), `run.json` goes
1718/// first instead, so a reader that finds the lock files finds no record.
1719///
1720/// A crash between the rename and the removal leaves the tombstone behind;
1721/// [`sweep_graveyard`] removes such leftovers, here before this deletion
1722/// starts (so it never meets its own tombstone) and in idle housekeeping.
1723fn remove_run_dir(home: &Path, id: &str, dir: &Path) -> Result<()> {
1724    sweep_graveyard(home);
1725    let graveyard = graveyard(home);
1726    let tombstone = graveyard.join(format!("{id}-{}", Timestamp::now().as_nanosecond()));
1727    let renamed = std::fs::create_dir_all(&graveyard)
1728        .and_then(|()| std::fs::rename(dir, &tombstone))
1729        .is_ok();
1730    if renamed {
1731        return remove_tombstone(id, &tombstone);
1732    }
1733    match std::fs::remove_file(dir.join("run.json")) {
1734        Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
1735            return Err(e).with_context(|| format!("remove run record of {id}"));
1736        }
1737        _ => {}
1738    }
1739    std::fs::remove_dir_all(dir).with_context(|| format!("remove run directory {}", dir.display()))
1740}
1741
1742/// Remove a tombstone that a deletion has just made. A tombstone that is
1743/// already gone, or that a concurrent [`sweep_graveyard`] removes while this
1744/// removal is under way, is a finished deletion: after a removal error only a
1745/// tombstone that still exists is a failure.
1746fn remove_tombstone(id: &str, tombstone: &Path) -> Result<()> {
1747    match std::fs::remove_dir_all(tombstone) {
1748        Err(e) if !matches!(tombstone.try_exists(), Ok(false)) => Err(e).with_context(|| {
1749            format!(
1750                "run {id} was deleted, but its leftovers remain in {}",
1751                tombstone.display()
1752            )
1753        }),
1754        _ => Ok(()),
1755    }
1756}
1757
1758/// The run record in `runs/<id>/run.json`, when it parses at all, names this
1759/// run. Read before any schema migration, so that a record another run's, in a
1760/// schema this build refuses, is an identity error rather than an "unreadable"
1761/// run that is removed wholesale. A missing or unparseable record, or one with
1762/// no id, says nothing about identity and passes.
1763pub fn ensure_record_identity(runs: &Path, id: &str) -> Result<()> {
1764    #[derive(Deserialize)]
1765    struct Recorded {
1766        #[serde(default)]
1767        id: Option<String>,
1768    }
1769    let Ok(body) = std::fs::read_to_string(runs.join(id).join("run.json")) else {
1770        return Ok(());
1771    };
1772    if let Ok(Recorded { id: Some(recorded) }) = serde_json::from_str(&body) {
1773        anyhow::ensure!(
1774            recorded == id,
1775            "runs/{id}/run.json records run {recorded}, not run {id}"
1776        );
1777    }
1778    Ok(())
1779}
1780
1781/// Delete files from the shared build cache until it fits its cap — but only
1782/// while nobody live is registered as using it. [`crate::cache::maintenance_prune`]
1783/// takes out the same lease a build would, so a prune can never race a
1784/// compile in flight (this run's own, another run's, or a human's `magi
1785/// review`) into deleting a file that build still needs. `Ok(None)` when the
1786/// cache is in use right now; the next pass catches it once the borrower
1787/// releases it, the same way a cap of `0` or a missing `CARGO_TARGET_DIR`
1788/// already meant "nothing to do this time" here.
1789pub fn prune_cache(home: &Path, cache: &Path, limit_bytes: u64) -> Result<Option<Prune>> {
1790    crate::cache::maintenance_prune(home, cache, limit_bytes)
1791}
1792
1793/// [`prune_cache`], but resolving the operator's opt-out and missing
1794/// `CARGO_TARGET_DIR` first — the same two checks [`housekeep`]'s idle pass
1795/// makes before ever measuring the cache, factored out so
1796/// [`crate::daemon`]'s between-runs check (see the module's own doc for why
1797/// congestion can make "idle" arrive too rarely to matter) makes them
1798/// identically rather than growing its own copy that could drift. `Ok(None)`
1799/// covers a cap of `0` (see the module docs on `cache_limit_bytes`), a config
1800/// that renders no `CARGO_TARGET_DIR` to aggregate at all, and a cache
1801/// currently in use (see [`prune_cache`]).
1802pub fn prune_cache_if_over_limit(
1803    cfg: &crate::config::Config,
1804    home: &Path,
1805) -> Result<Option<Prune>> {
1806    prune_cache_under_pressure(cfg, home, crate::disk::free_bytes)
1807}
1808
1809/// [`prune_cache_if_over_limit`] with the free-space measurement supplied by
1810/// the caller.
1811///
1812/// Free space on the cache's volume below
1813/// [`Disk::reclaim_threshold`](crate::config::Disk::reclaim_threshold) - the
1814/// collection threshold, not the admission floor - shrinks the limit by the
1815/// deficit ([`crate::disk::pressure_limit`]). While free space is at or above
1816/// the admission floor and below the collection threshold the cache also keeps
1817/// a reserve of half its cap
1818/// ([`crate::disk::pressure_reserve`]), and that is enforced where files are
1819/// removed: the pruning routine skips a file whose removal would leave less
1820/// ([`crate::disk::prune_dir_keeping`]), so one artifact larger than
1821/// `size - reserve` is kept rather than taking the cache to nothing.
1822///
1823/// This is estimated-deficit collection: free space is measured once, the
1824/// deficit computed from that one number, and that many *logical* bytes are
1825/// removed oldest-first. There is no re-measuring loop: hard links and other
1826/// writers mean the space freed can differ, and the next pass (the service's
1827/// ordinary period away) measures again and continues. A pass that removes
1828/// nothing is not an error. An unreadable measurement prunes to the plain cap.
1829/// The cache is measured (`dir_size`, for the limit) only below the threshold.
1830///
1831/// Log contract: a pass that *runs to completion* - it measured free space,
1832/// took the maintenance lease and walked the cache - emits one `info` line
1833/// with the admission floor, the collection threshold, the free bytes
1834/// measured, the size the pruning routine's own inventory reported, the
1835/// logical bytes removed and an outcome ([`crate::disk::PressureOutcome`]:
1836/// `within limit`, `at reserve`, `collected`, `nothing eligible`). A pass that
1837/// is refused or fails (lease or Cargo lock held, an I/O error, an unreadable
1838/// free-space measurement) reports exactly as it did before the threshold
1839/// existed - its return value or error - and emits no additional line.
1840pub(crate) fn prune_cache_under_pressure(
1841    cfg: &crate::config::Config,
1842    home: &Path,
1843    free_bytes: impl Fn(&Path) -> Result<u64>,
1844) -> Result<Option<Prune>> {
1845    let cap = cfg.disk.cache_limit_bytes;
1846    if cap == 0 {
1847        return Ok(None);
1848    }
1849    let Some(cache) = cfg.cache_dir() else {
1850        return Ok(None);
1851    };
1852    let floor = cfg.disk.min_free_bytes;
1853    let threshold = cfg.disk.reclaim_threshold();
1854    let free = free_bytes(&cache).ok();
1855    let (limit, keep) = free
1856        .filter(|free| *free < threshold)
1857        .map_or((cap, 0), |free| {
1858            (
1859                crate::disk::pressure_limit(dir_size(&cache), cap, floor, threshold, free),
1860                crate::disk::pressure_reserve(cap, floor, threshold, free),
1861            )
1862        });
1863    let prune = crate::cache::maintenance_prune_keeping(home, &cache, limit, keep)?;
1864    if let (Some(free), Some(pruned)) = (free, prune) {
1865        let size = pruned.remaining.saturating_add(pruned.freed);
1866        let outcome = crate::disk::pressure_outcome(pruned.freed, size, limit, keep);
1867        tracing::info!(
1868            cache = %cache.display(),
1869            admission_floor = floor,
1870            collection_threshold = threshold,
1871            free,
1872            size,
1873            removed = pruned.freed,
1874            outcome = outcome.as_str(),
1875            "shared build cache pressure pass"
1876        );
1877    }
1878    Ok(prune)
1879}
1880
1881/// The cache's path, size and cap, for `magi cache show` and the health view.
1882/// `None` when the config declares no `CARGO_TARGET_DIR` to aggregate.
1883///
1884/// A cap of `0` means the operator opted out of pruning; the size is then
1885/// reported but never acted on.
1886pub fn cache_report(cfg: &crate::config::Config) -> Option<(PathBuf, u64, u64)> {
1887    let cache = cfg.cache_dir()?;
1888    Some((
1889        cache.clone(),
1890        cache_size(&cache),
1891        cfg.disk.cache_limit_bytes,
1892    ))
1893}
1894
1895/// Size in bytes of the shared build cache.
1896pub fn cache_size(cache: &Path) -> u64 {
1897    dir_size(cache)
1898}
1899
1900#[cfg(test)]
1901pub(crate) mod tests {
1902
1903    async fn sh(cwd: &Path, args: &[&str]) {
1904        let out = crate::git::git_raw(cwd, args).await.expect("spawn git");
1905        assert!(out.ok(), "git {args:?}: {}", out.stderr);
1906    }
1907
1908    async fn commit(cwd: &Path, file: &str, body: &str) {
1909        std::fs::write(cwd.join(file), body).unwrap();
1910        sh(cwd, &["add", file]).await;
1911        sh(
1912            cwd,
1913            &[
1914                "-c",
1915                "user.name=t",
1916                "-c",
1917                "user.email=t@example.com",
1918                "commit",
1919                "-q",
1920                "-m",
1921                body,
1922            ],
1923        )
1924        .await;
1925    }
1926
1927    const LONG: std::time::Duration = std::time::Duration::from_secs(30);
1928
1929    #[tokio::test]
1930    async fn fetch_advances_origin_main_and_leaves_the_checkout_alone() {
1931        let tmp = tempfile::tempdir().unwrap();
1932        let t = tmp.path();
1933        let bare = t.join("remote.git");
1934        sh(
1935            t,
1936            &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
1937        )
1938        .await;
1939        let dir = t.join("root/h/o/r");
1940        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
1941        sh(
1942            t,
1943            &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
1944        )
1945        .await;
1946        sh(&dir, &["checkout", "-q", "-b", "main"]).await;
1947        commit(&dir, "a.txt", "one").await;
1948        sh(&dir, &["push", "-q", "origin", "main"]).await;
1949        sh(&dir, &["checkout", "-q", "--detach"]).await;
1950        std::fs::write(dir.join("a.txt"), "dirty").unwrap();
1951
1952        let other = t.join("other");
1953        sh(
1954            t,
1955            &[
1956                "clone",
1957                "-q",
1958                bare.to_str().unwrap(),
1959                other.to_str().unwrap(),
1960            ],
1961        )
1962        .await;
1963        commit(&other, "b.txt", "two").await;
1964        sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;
1965
1966        let rev = |d: PathBuf, r: &'static str| async move {
1967            crate::git::git(&d, &["rev-parse", r]).await.unwrap()
1968        };
1969        let head = rev(dir.clone(), "HEAD").await;
1970        let before = rev(dir.clone(), "origin/main").await;
1971        let status = crate::git::git(&dir, &["status", "--porcelain"])
1972            .await
1973            .unwrap();
1974
1975        let r = fetch_origins(&[t.join("root")], LONG, || false).await;
1976        assert_eq!(
1977            r,
1978            FetchReport {
1979                fetched: 1,
1980                no_origin: 0,
1981                failed: 0
1982            }
1983        );
1984
1985        assert_ne!(rev(dir.clone(), "origin/main").await, before);
1986        assert_eq!(rev(dir.clone(), "HEAD").await, head);
1987        assert_eq!(
1988            crate::git::git(&dir, &["status", "--porcelain"])
1989                .await
1990                .unwrap(),
1991            status
1992        );
1993        assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "dirty");
1994    }
1995
1996    #[tokio::test]
1997    async fn fetch_never_writes_a_local_branch_whatever_the_configured_refspec() {
1998        let tmp = tempfile::tempdir().unwrap();
1999        let t = tmp.path();
2000        let bare = t.join("remote.git");
2001        sh(
2002            t,
2003            &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
2004        )
2005        .await;
2006        let dir = t.join("root/h/o/r");
2007        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
2008        sh(
2009            t,
2010            &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
2011        )
2012        .await;
2013        sh(&dir, &["checkout", "-q", "-b", "main"]).await;
2014        commit(&dir, "a.txt", "one").await;
2015        sh(&dir, &["push", "-q", "origin", "main"]).await;
2016        sh(&dir, &["checkout", "-q", "--detach"]).await;
2017        // A hostile mapping onto the local branch, and no origin/* at all.
2018        sh(
2019            &dir,
2020            &[
2021                "config",
2022                "remote.origin.fetch",
2023                "+refs/heads/main:refs/heads/main",
2024            ],
2025        )
2026        .await;
2027        let _ = crate::git::git_raw(&dir, &["update-ref", "-d", "refs/remotes/origin/main"]).await;
2028
2029        let other = t.join("other");
2030        sh(
2031            t,
2032            &[
2033                "clone",
2034                "-q",
2035                bare.to_str().unwrap(),
2036                other.to_str().unwrap(),
2037            ],
2038        )
2039        .await;
2040        commit(&other, "b.txt", "two").await;
2041        sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;
2042        let remote_tip = crate::git::git(&other, &["rev-parse", "HEAD"])
2043            .await
2044            .unwrap();
2045        let local_main = crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
2046            .await
2047            .unwrap();
2048
2049        let r = fetch_origins(&[t.join("root")], LONG, || false).await;
2050        assert_eq!(r.fetched, 1);
2051        assert_eq!(
2052            crate::git::git(&dir, &["rev-parse", "refs/remotes/origin/main"])
2053                .await
2054                .unwrap(),
2055            remote_tip
2056        );
2057        assert_eq!(
2058            crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
2059                .await
2060                .unwrap(),
2061            local_main
2062        );
2063    }
2064
2065    #[tokio::test]
2066    async fn fetch_skips_no_origin_and_survives_an_unreachable_origin() {
2067        let tmp = tempfile::tempdir().unwrap();
2068        let t = tmp.path();
2069        let root = t.join("root");
2070        let bare = t.join("remote.git");
2071        sh(t, &["init", "-q", "--bare", bare.to_str().unwrap()]).await;
2072
2073        let none = root.join("h/o/none");
2074        let dead = root.join("h/o/dead");
2075        let good = root.join("h/o/good");
2076        for d in [&none, &dead, &good] {
2077            std::fs::create_dir_all(d).unwrap();
2078            sh(d, &["init", "-q"]).await;
2079        }
2080        sh(
2081            &dead,
2082            &[
2083                "remote",
2084                "add",
2085                "origin",
2086                t.join("missing").to_str().unwrap(),
2087            ],
2088        )
2089        .await;
2090        sh(&good, &["remote", "add", "origin", bare.to_str().unwrap()]).await;
2091
2092        let r = fetch_origins(&[root], LONG, || false).await;
2093        assert_eq!(
2094            r,
2095            FetchReport {
2096                fetched: 1,
2097                no_origin: 1,
2098                failed: 1
2099            }
2100        );
2101    }
2102    use super::*;
2103    use crate::config::Disk;
2104    use std::fs;
2105
2106    fn ts(s: &str) -> Timestamp {
2107        s.parse().expect("rfc3339")
2108    }
2109
2110    fn block_on<F: std::future::Future>(f: F) -> F::Output {
2111        tokio::runtime::Runtime::new().expect("runtime").block_on(f)
2112    }
2113
2114    #[test]
2115    fn a_run_is_due_after_its_grace_and_not_before() {
2116        let now = ts("2026-09-05T00:00:00Z");
2117        let grace = 600;
2118        let old = now - SignedDuration::new(601, 0);
2119        let fresh = now - SignedDuration::new(599, 0);
2120        assert!(due(now, old, grace));
2121        assert!(!due(now, fresh, grace));
2122        // Exactly at the edge: not yet due.
2123        let edge = now - SignedDuration::new(600, 0);
2124        assert!(!due(now, edge, grace));
2125        // A zero grace folds everything, ever.
2126        assert!(due(now, old, 0));
2127    }
2128
2129    #[test]
2130    fn rotate_from_moves_the_starting_point_as_the_cursor_advances() {
2131        let ids: Vec<String> = ["a", "b", "c", "d", "e"]
2132            .iter()
2133            .map(|s| s.to_string())
2134            .collect();
2135
2136        // A cursor of 0 starts at the front, same as an unrotated list.
2137        assert_eq!(rotate_from(&ids, 0), ids);
2138
2139        // A cursor of 2 starts two ids further along, with the skipped
2140        // front wrapping to the tail rather than being dropped.
2141        let at_2 = rotate_from(&ids, 2);
2142        assert_eq!(at_2, vec!["c", "d", "e", "a", "b"]);
2143        for id in &ids {
2144            assert!(at_2.contains(id));
2145        }
2146
2147        // A cursor past the list's own length wraps rather than panicking -
2148        // the caller never has to reduce it modulo anything itself.
2149        assert_eq!(rotate_from(&ids, 7), rotate_from(&ids, 2));
2150
2151        // An empty list has no start point to compute and must not panic.
2152        assert_eq!(rotate_from(&[], 0), Vec::<String>::new());
2153    }
2154
2155    /// A fleet with more eligible runs than one pass can check must not park
2156    /// the same handful at the front of the window forever: advancing the
2157    /// cursor by exactly how many ids one pass actually looked at - the
2158    /// arithmetic [`reconcile_external_merges`] itself does - walks every id
2159    /// to the front within one full rotation, with no reliance on how often
2160    /// or how regularly passes happen to run.
2161    #[test]
2162    fn advancing_the_cursor_by_the_window_size_gives_every_id_a_turn() {
2163        let ids: Vec<String> = (0..12).map(|n| format!("run-{n}")).collect();
2164        let cap = 5usize;
2165        let mut cursor = 0usize;
2166        let mut ever_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2167        for _ in 0..ids.len() {
2168            let window: Vec<String> = rotate_from(&ids, cursor).into_iter().take(cap).collect();
2169            ever_seen.extend(window.iter().cloned());
2170            cursor = (cursor + window.len()) % ids.len();
2171        }
2172        assert_eq!(
2173            ever_seen.len(),
2174            ids.len(),
2175            "every id must be checked at least once across a full rotation, whatever \
2176             the cadence between passes"
2177        );
2178    }
2179
2180    #[test]
2181    fn the_external_merge_cursor_round_trips_through_a_files_absence() {
2182        let dir = tempfile::tempdir().unwrap();
2183        let home = dir.path();
2184
2185        // Nothing written yet: starts at 0, not an error.
2186        assert_eq!(read_external_merge_cursor(home), 0);
2187
2188        write_external_merge_cursor(home, 7);
2189        assert_eq!(read_external_merge_cursor(home), 7);
2190
2191        // Anything unreadable as a plain number falls back to 0 rather than
2192        // wedging the sweep on a corrupt file.
2193        std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), "not a number").unwrap();
2194        assert_eq!(read_external_merge_cursor(home), 0);
2195    }
2196
2197    #[test]
2198    fn a_run_qualifies_for_an_external_merge_check_only_when_blocked_unmerged_and_due() {
2199        let now = ts("2026-09-05T00:00:00Z");
2200        let grace = 600;
2201        let old = now - SignedDuration::new(601, 0);
2202        let fresh = now - SignedDuration::new(599, 0);
2203
2204        assert!(
2205            eligible_for_external_merge_check(RunStatus::Blocked, false, old, now, grace),
2206            "blocked, unmerged, and past its grace period is exactly the run this exists for"
2207        );
2208        assert!(
2209            !eligible_for_external_merge_check(RunStatus::Blocked, false, fresh, now, grace),
2210            "an operator mid-fix deserves the same grace window `fold_due` gives before \
2211             the janitor starts asking GitHub about it"
2212        );
2213        assert!(
2214            !eligible_for_external_merge_check(RunStatus::Blocked, true, old, now, grace),
2215            "a run `land::land` already recorded a merge outcome for has its own answer \
2216             already; this check is only for a run with nothing recorded at all"
2217        );
2218        assert!(
2219            !eligible_for_external_merge_check(RunStatus::Stalled, false, old, now, grace),
2220            "stalled is not blocked - it means the tally never reached quorum, which a \
2221             pull request cannot fix"
2222        );
2223        assert!(
2224            !eligible_for_external_merge_check(RunStatus::Ready, false, old, now, grace),
2225            "ready has nothing to correct - it was never landed by design"
2226        );
2227        assert!(
2228            !eligible_for_external_merge_check(RunStatus::Superseded, false, old, now, grace),
2229            "a superseded run's task already has its answer from a later attempt; \
2230             there is nothing left for GitHub to confirm here"
2231        );
2232    }
2233
2234    /// A blocked run with a winner in an isolated repository directory.
2235    /// Consumer tests inject forge results without invoking a real CLI.
2236    fn write_blocked_run(runs: &Path, id: &str, updated_at: Timestamp) {
2237        use crate::run::{Candidate, Tally};
2238        use std::collections::BTreeMap;
2239
2240        let mut state = RunState::new(
2241            runs.parent().unwrap().to_path_buf(),
2242            "main".to_owned(),
2243            "0000000000000000000000000000000000000000".to_owned(),
2244            String::new(),
2245            crate::config::Config::default(),
2246        );
2247        state.id = id.to_owned();
2248        state.status = RunStatus::Blocked;
2249        state.updated_at = updated_at;
2250        state.candidates.push(Candidate {
2251            index: 0,
2252            label: 'A',
2253            agent: "agent".to_owned(),
2254            branch: format!("magi/{id}/A"),
2255            worktree: runs.parent().unwrap().join("candidate"),
2256            summary: String::new(),
2257            stat: String::new(),
2258            files: 0,
2259            commits: 0,
2260            empty: false,
2261            failed: None,
2262            verified_noop: None,
2263            duration_ms: 0,
2264            folded: false,
2265        });
2266        state.tally = Some(Tally {
2267            first_choice: BTreeMap::from([('A', 1)]),
2268            borda: BTreeMap::new(),
2269            winner: 'A',
2270            rankings: 1,
2271            unanimous_initial: true,
2272            deliberated: false,
2273            changed_votes: 0,
2274            unanimous_final: true,
2275            tie_break: None,
2276            judges: 1,
2277            present: 1,
2278            quorum: 1,
2279            met_quorum: true,
2280            uncontested: None,
2281        });
2282        std::fs::create_dir_all(runs.join(id)).unwrap();
2283        std::fs::write(
2284            runs.join(id).join("run.json"),
2285            serde_json::to_string_pretty(&state).unwrap(),
2286        )
2287        .unwrap();
2288    }
2289
2290    /// No run here can be confirmed merged - one has a forge error,
2291    /// one has not sat blocked long enough, and one is
2292    /// claimed by a live daemon - so the sweep must leave every one of them
2293    /// exactly as it found them and never panic on the failures in between.
2294    #[tokio::test]
2295    async fn reconcile_external_merges_leaves_ineligible_and_unconfirmable_runs_alone() {
2296        let dir = tempfile::tempdir().unwrap();
2297        let runs = dir.path().join("runs");
2298        let home = dir.path().to_path_buf();
2299        std::fs::create_dir_all(&runs).unwrap();
2300
2301        let now = ts("2026-09-05T00:00:00Z");
2302        let disk = Disk {
2303            fold_grace_secs: 600,
2304            ..Disk::default()
2305        };
2306
2307        let due_id = "20260905-000000-blkd";
2308        write_blocked_run(&runs, due_id, ts("2026-08-01T00:00:00Z"));
2309
2310        let fresh_id = "20260905-000000-fres";
2311        write_blocked_run(&runs, fresh_id, now);
2312
2313        let live_id = "20260905-000000-live";
2314        write_blocked_run(&runs, live_id, ts("2026-08-01T00:00:00Z"));
2315        let mut status = crate::daemon::Status::new();
2316        status.current = vec![crate::daemon::Current {
2317            worker: None,
2318            task: "20260905-000000-task".to_owned(),
2319            run: live_id.to_owned(),
2320        }];
2321        status.updated_at = now;
2322        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
2323
2324        let reconciled = reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
2325            anyhow::bail!("injected forge authentication failure")
2326        })
2327        .await;
2328        assert_eq!(reconciled, 0, "a forge failure can never confirm a merge");
2329        for id in [due_id, fresh_id, live_id] {
2330            assert_eq!(
2331                read_meta(&runs, id).unwrap().status,
2332                RunStatus::Blocked,
2333                "{id} must be left exactly as it was found"
2334            );
2335        }
2336        let notices = crate::notices::Notices::at(home.join("notifications")).list();
2337        let due_notice = notices
2338            .iter()
2339            .find(|n| n.key == format!("merged-unrecorded:{due_id}"))
2340            .expect("notice for due_id must be raised");
2341        assert_eq!(
2342            due_notice.link,
2343            Some(crate::notices::Link::Run {
2344                id: due_id.to_owned(),
2345            })
2346        );
2347    }
2348
2349    #[tokio::test]
2350    async fn historical_external_merge_check_preserves_unknown_history() {
2351        let home = tempfile::tempdir().unwrap();
2352        let runs = home.path().join("runs");
2353        let id = "legacy";
2354        write_blocked_run(&runs, id, ts("2026-08-01T00:00:00Z"));
2355        let path = runs.join(id).join("run.json");
2356        let mut state = read_state(&runs, id).unwrap();
2357        state.repo = home.path().join("removed");
2358        state.candidates[0].folded = true;
2359        let original = serde_json::to_vec(&state).unwrap();
2360        std::fs::write(&path, &original).unwrap();
2361        let count = reconcile_external_merges_with(
2362            &runs,
2363            home.path(),
2364            &Disk::default(),
2365            ts("2026-11-14T00:00:00Z"),
2366            |_| async { panic!("historical unavailable checkout must not invoke the forge") },
2367        )
2368        .await;
2369        assert_eq!(count, 0);
2370        assert_eq!(std::fs::read(&path).unwrap(), original);
2371        assert!(
2372            crate::notices::Notices::at(home.path().join("notifications"))
2373                .all()
2374                .is_empty()
2375        );
2376
2377        // The same folded run is actionable when a current task owns it.
2378        let queue = crate::queue::Queue::at(home.path().join("queue"));
2379        let mut task = crate::queue::Task::new(
2380            "current".into(),
2381            "current".into(),
2382            state.repo.clone(),
2383            crate::queue::Source::Human,
2384        );
2385        task.runs.push(id.into());
2386        queue.put(&mut task).unwrap();
2387        reconcile_external_merges_with(
2388            &runs,
2389            home.path(),
2390            &Disk::default(),
2391            ts("2026-11-14T00:00:00Z"),
2392            |_| async { anyhow::bail!("current checkout unavailable") },
2393        )
2394        .await;
2395        assert_eq!(
2396            crate::notices::Notices::at(home.path().join("notifications"))
2397                .list()
2398                .len(),
2399            1
2400        );
2401        assert_eq!(std::fs::read(&path).unwrap(), original);
2402    }
2403
2404    /// The bug this exists to pin: a first version rotated on
2405    /// `now.as_second() % len`, which is fully determined by wall-clock time
2406    /// and nothing else. Two passes seconds apart - as they would be when a
2407    /// short poll interval and a fast pass alias onto the same handful of
2408    /// `now.as_second()` residues - landed on the *same* starting point and
2409    /// never covered a fleet bigger than the per-pass cap, however many
2410    /// times housekeeping ran. Persisting a cursor makes forward progress a
2411    /// function of how many ids got looked at, not of when the clock reads
2412    /// this pass happened to run.
2413    #[tokio::test]
2414    async fn reconcile_external_merges_covers_a_larger_fleet_across_repeated_passes_at_one_instant()
2415    {
2416        let dir = tempfile::tempdir().unwrap();
2417        let runs = dir.path().join("runs");
2418        let home = dir.path().to_path_buf();
2419        std::fs::create_dir_all(&runs).unwrap();
2420
2421        let now = ts("2026-09-05T00:00:00Z");
2422        let disk = Disk {
2423            fold_grace_secs: 600,
2424            ..Disk::default()
2425        };
2426        let old = ts("2026-08-01T00:00:00Z");
2427
2428        let ids: Vec<String> = (0..8).map(|n| format!("20260905-000000-r{n:03}")).collect();
2429        for id in &ids {
2430            write_blocked_run(&runs, id, old);
2431        }
2432
2433        let notices = crate::notices::Notices::at(home.join("notifications"));
2434
2435        // Two passes at the exact same `now`, exactly what a fast pass on a
2436        // short poll interval looks like. Each of the 8 injected forge-failure
2437        // runs raises its own notice the first time it is looked at, so the
2438        // count of distinct notices is a direct readout of how many distinct
2439        // ids have been checked so far.
2440        reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
2441            anyhow::bail!("injected forge authentication failure")
2442        })
2443        .await;
2444        let after_first = notices.list().len();
2445        assert_eq!(
2446            after_first, MAX_EXTERNAL_MERGE_CHECKS_PER_PASS,
2447            "the first pass checks exactly one cap's worth"
2448        );
2449
2450        reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
2451            anyhow::bail!("injected forge authentication failure")
2452        })
2453        .await;
2454        let after_second = notices.list().len();
2455        assert_eq!(
2456            after_second,
2457            ids.len(),
2458            "a second pass at the same instant must still reach every id the \
2459             first pass had no room for, not repeat the same cap's worth"
2460        );
2461    }
2462
2463    #[test]
2464    fn the_meta_reader_is_tolerant_of_everything_except_the_deciders() {
2465        let dir = tempfile::tempdir().unwrap();
2466        let runs = dir.path().join("runs");
2467        let id = "20260905-000000-abcd";
2468        std::fs::create_dir_all(runs.join(id)).unwrap();
2469        std::fs::write(
2470            runs.join(id).join("run.json"),
2471            r#"{"schema": 99, "id": "20260905-000000-abcd", "updated_at": "2026-09-05T00:00:00Z", "status": "ready", "junk_from_another_build": [1, 2, 3]}"#,
2472        )
2473        .unwrap();
2474        let meta = read_meta(&runs, id).expect("readable");
2475        assert_eq!(meta.status, RunStatus::Ready);
2476        assert_eq!(meta.updated_at, ts("2026-09-05T00:00:00Z"));
2477        assert!(read_meta(&runs, "nope").is_err(), "missing file unreadable");
2478        std::fs::write(runs.join(id).join("run.json"), "not json at all").unwrap();
2479        assert!(read_meta(&runs, id).is_err(), "garbage unreadable");
2480    }
2481
2482    #[test]
2483    fn fold_unreadable_preserves_unknown_content_and_recovery_artifacts() {
2484        let dir = tempfile::tempdir().unwrap();
2485        let runs = dir.path().join("runs");
2486        let wt = dir.path().join("wt");
2487        let id = "20260905-000000-abcd";
2488        std::fs::create_dir_all(runs.join(id).join("artifacts")).unwrap();
2489        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
2490        std::fs::create_dir_all(wt.join("abcd")).unwrap();
2491        std::fs::write(wt.join("abcd/leftover"), "owned edits").unwrap();
2492        assert!(block_on(fold_unreadable(&runs, &wt, id)).is_err());
2493        assert!(runs.join(id).join("artifacts").exists());
2494        assert_eq!(
2495            std::fs::read_to_string(wt.join("abcd/leftover")).unwrap(),
2496            "owned edits"
2497        );
2498    }
2499
2500    #[test]
2501    fn fold_unreadable_releases_run_dir_and_worktrees() {
2502        let dir = tempfile::tempdir().unwrap();
2503        let runs = dir.path().join("runs");
2504        let wt = dir.path().join("wt");
2505        let id = "20260905-000000-abcd";
2506        std::fs::create_dir_all(runs.join(id)).unwrap();
2507        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
2508        std::fs::create_dir_all(wt.join("abcd")).unwrap();
2509
2510        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold");
2511        assert_eq!(removed.len(), 2);
2512        assert!(!runs.join(id).exists(), "run dir gone");
2513        assert!(!wt.join("abcd").exists(), "worktrees gone");
2514
2515        // A prefix resolves like `run::resolve_id` does.
2516        std::fs::create_dir_all(runs.join(id)).unwrap();
2517        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
2518        std::fs::create_dir_all(wt.join("abcd")).unwrap();
2519        let removed = block_on(fold_unreadable(&runs, &wt, "20260905")).expect("by prefix");
2520        assert_eq!(removed.len(), 2);
2521        // Once gone, `id` cannot be resolved at all - same as `run::resolve_id`
2522        // on an id nothing on disk matches - so a repeat pass errors rather
2523        // than silently reporting nothing removed.
2524        assert!(
2525            block_on(fold_unreadable(&runs, &wt, id)).is_err(),
2526            "a run already gone cannot be resolved again"
2527        );
2528    }
2529
2530    #[test]
2531    fn prune_cache_sheds_the_oldest_generation_until_it_fits() {
2532        let home = tempfile::tempdir().unwrap();
2533        let dir = tempfile::tempdir().unwrap();
2534        // Same size, different age: only the age decides, and the newest
2535        // generation - the one the next build reuses - is what survives.
2536        fs::write(dir.path().join("old"), b"xx").unwrap();
2537        fs::write(dir.path().join("new"), b"yy").unwrap();
2538        touch(&dir.path().join("old"), 1_000_000);
2539        touch(&dir.path().join("new"), 2_000_000);
2540
2541        let out = prune_cache(home.path(), dir.path(), 2)
2542            .expect("prune")
2543            .expect("the cache is free");
2544        assert_eq!(out.files, 1, "one deletion is enough to reach the cap");
2545        assert_eq!(out.remaining, 2);
2546        assert!(!dir.path().join("old").exists(), "the older file went");
2547        assert!(dir.path().join("new").exists(), "the newer one stayed");
2548
2549        // A whole generation shares one timestamp tick, so the tie has to be
2550        // decided too: largest first, which reaches the cap in the fewest
2551        // deletions. Left to `read_dir` and an unstable sort this deleted
2552        // both files on Linux and one on Windows.
2553        let tied = tempfile::tempdir().unwrap();
2554        fs::write(tied.path().join("big"), b"xxxx").unwrap();
2555        fs::write(tied.path().join("small"), b"yy").unwrap();
2556        touch(&tied.path().join("big"), 1_000_000);
2557        touch(&tied.path().join("small"), 1_000_000);
2558        let out = prune_cache(home.path(), tied.path(), 2)
2559            .expect("prune")
2560            .expect("the cache is free");
2561        assert_eq!(out.files, 1, "the big one alone gets under the cap");
2562        assert_eq!(out.remaining, 2);
2563        assert!(tied.path().join("small").exists());
2564    }
2565
2566    #[test]
2567    fn prune_cache_if_over_limit_resolves_the_opt_outs_before_ever_measuring() {
2568        let home = tempfile::tempdir().unwrap();
2569        let dir = tempfile::tempdir().unwrap();
2570        fs::write(dir.path().join("big"), vec![0u8; 10]).unwrap();
2571
2572        let mut cfg = crate::config::Config::default();
2573        cfg.verify.gate = vec![format!(
2574            "CARGO_TARGET_DIR={} cargo make check",
2575            dir.path().display()
2576        )];
2577
2578        // A cap of `0` is the operator's opt-out: never measured, never
2579        // pruned, regardless of what is actually on disk.
2580        cfg.disk.cache_limit_bytes = 0;
2581        assert_eq!(
2582            prune_cache_if_over_limit(&cfg, home.path()).unwrap(),
2583            None,
2584            "a zero cap must not even look at the directory"
2585        );
2586        assert!(dir.path().join("big").exists());
2587
2588        // No `CARGO_TARGET_DIR` in either verify command: nothing to
2589        // aggregate, so there is nothing to prune either.
2590        let mut no_cache = crate::config::Config::default();
2591        no_cache.disk.cache_limit_bytes = 1;
2592        assert_eq!(
2593            prune_cache_if_over_limit(&no_cache, home.path()).unwrap(),
2594            None
2595        );
2596
2597        // Over the cap and configured: pruned exactly like `prune_cache`
2598        // itself would.
2599        cfg.disk.cache_limit_bytes = 1;
2600        let pruned = prune_cache_if_over_limit(&cfg, home.path())
2601            .unwrap()
2602            .expect("a real cache dir over its cap prunes");
2603        assert_eq!(pruned.files, 1);
2604        assert!(!dir.path().join("big").exists());
2605    }
2606
2607    /// A shared cache of four 100-byte files, `f1` the oldest, capped at 500
2608    /// (so its reserve is 250), and a config that names it with the given
2609    /// admission floor and collection setting. The cache dir is quoted in the
2610    /// command, as a path with spaces needs.
2611    fn pressure_fixture(
2612        min_free_bytes: u64,
2613        reclaim_free_bytes: Option<u64>,
2614    ) -> (tempfile::TempDir, tempfile::TempDir, crate::config::Config) {
2615        let home = tempfile::tempdir().unwrap();
2616        let dir = tempfile::tempdir().unwrap();
2617        for (i, name) in ["f1", "f2", "f3", "f4"].into_iter().enumerate() {
2618            fs::write(dir.path().join(name), vec![0u8; 100]).unwrap();
2619            touch(&dir.path().join(name), 1_000_000 + i as u64);
2620        }
2621        let mut cfg = crate::config::Config::default();
2622        cfg.verify.gate = vec![format!(
2623            "CARGO_TARGET_DIR=\"{}\" cargo make check",
2624            dir.path().display()
2625        )];
2626        cfg.disk.cache_limit_bytes = 500;
2627        cfg.disk.min_free_bytes = min_free_bytes;
2628        cfg.disk.reclaim_free_bytes = reclaim_free_bytes;
2629        (home, dir, cfg)
2630    }
2631
2632    /// One pass with `free` as the volume's free space, and the files left.
2633    fn pass(
2634        cfg: &crate::config::Config,
2635        home: &Path,
2636        dir: &Path,
2637        free: u64,
2638    ) -> (Option<Prune>, Vec<&'static str>) {
2639        let pruned = prune_cache_under_pressure(cfg, home, |_| Ok(free)).unwrap();
2640        let left = ["f1", "f2", "f3", "f4"]
2641            .into_iter()
2642            .filter(|name| dir.join(name).exists())
2643            .collect();
2644        (pruned, left)
2645    }
2646
2647    #[test]
2648    fn a_pass_removes_the_estimated_deficit_between_the_floor_and_the_threshold() {
2649        // Floor 10, threshold 30, free 11 (one byte above the floor): a 19-byte
2650        // deficit on a 400-byte cache above its reserve (250), so the limit is
2651        // 381 and the oldest file (100 logical bytes) covers it. The pass
2652        // measures free space once: the injected 11 never changes.
2653        // On origin/main (threshold = floor) the same input has no deficit and
2654        // removes nothing, so these assertions fail there.
2655        let (home, dir, cfg) = pressure_fixture(10, Some(30));
2656        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 11);
2657        let pruned = pruned.expect("cache is free");
2658        assert_eq!(
2659            (pruned.files, pruned.freed, pruned.remaining),
2660            (1, 100, 300)
2661        );
2662        assert_eq!(left, ["f2", "f3", "f4"]);
2663
2664        // The default threshold (twice the floor = 20) collects at free 11 too.
2665        let (home, dir, cfg) = pressure_fixture(10, None);
2666        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 11);
2667        assert_eq!(pruned.unwrap().files, 1);
2668        assert_eq!(left, ["f2", "f3", "f4"]);
2669    }
2670
2671    #[test]
2672    fn the_shared_cache_is_left_alone_at_or_above_the_threshold() {
2673        let (home, dir, cfg) = pressure_fixture(10, Some(30));
2674        for free in [30, 31, u64::MAX] {
2675            let (pruned, left) = pass(&cfg, home.path(), dir.path(), free);
2676            assert_eq!(pruned.unwrap().files, 0, "free {free}");
2677            assert_eq!(left.len(), 4);
2678        }
2679        // A threshold equal to the floor is the old behaviour: nothing at 11.
2680        let (home2, dir2, floor_only) = pressure_fixture(10, Some(10));
2681        let (pruned, left) = pass(&floor_only, home2.path(), dir2.path(), 11);
2682        assert_eq!(pruned.unwrap().files, 0);
2683        assert_eq!(left.len(), 4);
2684
2685        // A zero cap is still "pruning off", whatever the pressure.
2686        let (home3, dir3, mut off) = pressure_fixture(10, Some(1000));
2687        off.disk.cache_limit_bytes = 0;
2688        assert!(
2689            prune_cache_under_pressure(&off, home3.path(), |_| Ok(0))
2690                .unwrap()
2691                .is_none()
2692        );
2693        assert!(dir3.path().join("f1").exists());
2694    }
2695
2696    #[test]
2697    fn above_the_floor_the_reserve_is_enforced_where_files_go_and_passes_converge() {
2698        // The threshold is out of reach and free space is pinned at 11 by
2699        // another program. Reserve = half the 500 cap = 250. The limit (250)
2700        // would take the cache from 400 to 250; the oldest file goes (300),
2701        // and the next removal would leave 200, below the reserve, so it is
2702        // skipped, as is every later one.
2703        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
2704        let (first, left) = pass(&cfg, home.path(), dir.path(), 11);
2705        let first = first.unwrap();
2706        assert_eq!((first.files, first.remaining), (1, 300), "{first:?}");
2707        assert_eq!(left, ["f2", "f3", "f4"]);
2708
2709        // However long the pressure lasts, nothing more goes.
2710        let (second, left) = pass(&cfg, home.path(), dir.path(), 11);
2711        assert_eq!(second.unwrap().files, 0);
2712        assert_eq!(left, ["f2", "f3", "f4"]);
2713    }
2714
2715    #[test]
2716    fn an_artifact_larger_than_size_minus_reserve_survives_every_pass() {
2717        // One 300-byte artifact, cap 500 (reserve 250), free pinned at 11
2718        // between the floor (10) and the threshold. The limit is 250, which
2719        // alone would delete the artifact; the next build recreates it and the
2720        // next pass would delete it again. The reserve keeps it.
2721        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
2722        for name in ["f1", "f2", "f3", "f4"] {
2723            fs::remove_file(dir.path().join(name)).unwrap();
2724        }
2725        let artifact = dir.path().join("artifact");
2726        for _ in 0..3 {
2727            fs::write(&artifact, vec![0u8; 300]).unwrap();
2728            let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(11))
2729                .unwrap()
2730                .expect("the cache is free");
2731            assert_eq!((pruned.files, pruned.remaining), (0, 300), "{pruned:?}");
2732            assert!(artifact.exists());
2733        }
2734        // Below the admission floor the reserve is gone: space outranks it.
2735        let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(0))
2736            .unwrap()
2737            .expect("the cache is free");
2738        assert_eq!(pruned.files, 1);
2739        assert!(!artifact.exists());
2740    }
2741
2742    #[test]
2743    fn an_oversized_oldest_artifact_is_skipped_and_smaller_files_are_still_collected() {
2744        // Cap 500 (reserve 250), free pinned at 11 between the floor (10) and
2745        // the threshold. The oldest artifact is 300 bytes of a 400-byte cache:
2746        // removing it would leave 100, below the reserve, so it stays - and the
2747        // pass goes on to the four newer 25-byte files (400 -> 300), each of
2748        // which leaves at least the reserve. A caller that stopped at the
2749        // oversized artifact would remove nothing.
2750        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
2751        for name in ["f1", "f2", "f3", "f4"] {
2752            fs::remove_file(dir.path().join(name)).unwrap();
2753        }
2754        let big = dir.path().join("big");
2755        fs::write(&big, vec![0u8; 300]).unwrap();
2756        touch(&big, 1_000_000);
2757        let small = ["s1", "s2", "s3", "s4"];
2758        for (i, name) in small.into_iter().enumerate() {
2759            let path = dir.path().join(name);
2760            fs::write(&path, vec![0u8; 25]).unwrap();
2761            touch(&path, 1_000_001 + i as u64);
2762        }
2763        let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(11))
2764            .unwrap()
2765            .expect("the cache is free");
2766        assert_eq!(
2767            (pruned.files, pruned.freed, pruned.remaining),
2768            (4, 100, 300),
2769            "{pruned:?}"
2770        );
2771        assert!(big.exists());
2772        for name in small {
2773            assert!(!dir.path().join(name).exists(), "{name} should be gone");
2774        }
2775
2776        // The reserve holds on the next pass: nothing more goes.
2777        let again = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(11))
2778            .unwrap()
2779            .expect("the cache is free");
2780        assert_eq!((again.files, again.remaining), (0, 300), "{again:?}");
2781        assert!(big.exists());
2782    }
2783
2784    #[test]
2785    fn below_the_admission_floor_there_is_no_reserve() {
2786        // Floor 150, threshold 300. At free 160 (above the floor) the reserve
2787        // keeps 250 of the 400 bytes: one file goes (to 300), the next would
2788        // leave 200. At free 0 (below the floor) the old rule applies - the
2789        // limit is 400 - 150 = 250 - and two go, below the reserve.
2790        let (home, dir, cfg) = pressure_fixture(150, Some(300));
2791        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 160);
2792        assert_eq!(pruned.unwrap().files, 1);
2793        assert_eq!(left, ["f2", "f3", "f4"]);
2794
2795        let (home, dir, cfg) = pressure_fixture(150, Some(300));
2796        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 0);
2797        let pruned = pruned.unwrap();
2798        assert_eq!((pruned.files, pruned.remaining), (2, 200));
2799        assert_eq!(left, ["f3", "f4"]);
2800    }
2801
2802    #[test]
2803    fn a_cache_in_use_is_left_alone() {
2804        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
2805        let owner = crate::cache::Owner::here("run", "node", "seat", dir.path(), "head");
2806        let _held = match crate::cache::try_acquire(home.path(), dir.path(), &owner).unwrap() {
2807            crate::cache::AcquireOutcome::Acquired(guard) => guard,
2808            crate::cache::AcquireOutcome::Busy(_) => panic!("fresh cache is busy"),
2809        };
2810        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 11);
2811        assert!(pruned.is_none());
2812        assert_eq!(left.len(), 4);
2813    }
2814
2815    #[test]
2816    fn an_unmeasurable_volume_prunes_to_the_plain_cap() {
2817        let (home, dir, mut cfg) = pressure_fixture(10, Some(1_000_000));
2818        cfg.disk.cache_limit_bytes = 350;
2819        let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| anyhow::bail!("no volume"))
2820            .unwrap()
2821            .unwrap();
2822        assert_eq!(pruned.files, 1, "only the cap applies");
2823        assert!(!dir.path().join("f1").exists() && dir.path().join("f2").exists());
2824    }
2825
2826    /// Pin a file's mtime, so a test asserts the policy and not the runner's
2827    /// timestamp granularity.
2828    fn touch(path: &Path, secs: u64) {
2829        let f = fs::File::options().write(true).open(path).unwrap();
2830        f.set_times(fs::FileTimes::new().set_modified(
2831            std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs),
2832        ))
2833        .unwrap();
2834    }
2835
2836    /// The disk-full casualty: a run whose first save left `run.json.tmp` and
2837    /// nothing else. It has to be clearable, or the record is permanent.
2838    #[test]
2839    fn fold_unreadable_clears_a_run_whose_state_never_landed() {
2840        let dir = tempfile::tempdir().unwrap();
2841        let runs = dir.path().join("runs");
2842        let wt = dir.path().join("wt");
2843        let id = "20260904-014540-88c0";
2844        std::fs::create_dir_all(runs.join(id)).unwrap();
2845        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
2846
2847        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold by id");
2848        assert_eq!(removed, vec![format!("runs/{id}")]);
2849        assert!(!runs.join(id).exists(), "record gone");
2850
2851        // And by prefix, the way the deck and the phone address a run.
2852        std::fs::create_dir_all(runs.join(id)).unwrap();
2853        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
2854        assert!(
2855            block_on(fold_unreadable(&runs, &wt, "88c0")).is_ok(),
2856            "by prefix"
2857        );
2858
2859        // A directory under `runs` that is not a run is never a fold target.
2860        std::fs::create_dir_all(runs.join("scratch")).unwrap();
2861        assert!(
2862            block_on(fold_unreadable(&runs, &wt, "scratch")).is_err(),
2863            "a stray directory is not a run"
2864        );
2865    }
2866
2867    #[test]
2868    fn fold_due_folds_terminal_runs_of_any_schema_but_leaves_genuinely_unreadable_ones() {
2869        let dir = tempfile::tempdir().unwrap();
2870        let runs = dir.path().join("runs");
2871        let wt = dir.path().join("wt");
2872        let home = dir.path().to_path_buf();
2873        let disk = Disk::default();
2874        let now = ts("2026-09-05T00:00:00Z");
2875
2876        // 1. Runnable (judging): never folded, however old.
2877        let judging = "20260801-000000-0001";
2878        write_meta(&runs, judging, "judging", "2026-08-01T00:00:00Z");
2879
2880        // 2. Finished but fresh: grace not elapsed. Within the default 6h
2881        //    grace of `now`, so `fold_due` must stop at the freshness check
2882        //    and never even reach `read_state` - `write_meta`'s minimal JSON
2883        //    would fail that full parse anyway, and this case exists to
2884        //    prove freshness is why the run survives, not an accident of the
2885        //    fixture being unparseable as a whole `RunState`.
2886        let ready_fresh = "20260904-220000-0002";
2887        write_meta(&runs, ready_fresh, "ready", "2026-09-04T22:00:00Z");
2888
2889        // 3. Genuinely unreadable: broken JSON, not merely an unfamiliar
2890        //    schema number. Left alone and counted - this is the one case
2891        //    automatic housekeeping must never touch (see `fold_due`'s docs);
2892        //    discarding it is an explicit operator action, not something a
2893        //    background pass does.
2894        let garbage = "20260901-000000-0004";
2895        std::fs::create_dir_all(runs.join(garbage)).unwrap();
2896        std::fs::write(runs.join(garbage).join("run.json"), "not json").unwrap();
2897        std::fs::create_dir_all(wt.join("0004")).unwrap();
2898
2899        // 4. Finished, well past grace, current schema: the ordinary case
2900        //    `fold_due` has always acted on.
2901        let due_ready = due_run(&runs, &wt, "20260801-000000-ffff", SCHEMA);
2902
2903        // 5. Finished, well past grace, but written by a schema number this
2904        //    build no longer matches - the defect this task exists to fix.
2905        //    It still parses cleanly, so only the version number differs, and
2906        //    that alone must not block folding.
2907        let due_old_schema = due_run(&runs, &wt, "20260801-000000-eeee", SCHEMA - 1);
2908
2909        let (folded, unreadable) =
2910            block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
2911        assert_eq!(
2912            folded, 2,
2913            "both due, parseable runs fold regardless of their schema number"
2914        );
2915        assert_eq!(
2916            unreadable, 1,
2917            "only the run with broken JSON counts as unreadable"
2918        );
2919        assert!(runs.join(judging).exists(), "runnable never folded");
2920        assert!(runs.join(ready_fresh).exists(), "fresh never folded");
2921        assert!(runs.join(garbage).exists(), "unreadable record kept");
2922        assert!(wt.join("0004").exists(), "unreadable worktree kept");
2923        assert!(
2924            runs.join(&due_ready).exists(),
2925            "folding drops worktrees, not the record"
2926        );
2927        assert!(
2928            runs.join(&due_old_schema).exists(),
2929            "an old-schema record survives its fold exactly like a current one"
2930        );
2931        // `graph::fold_run` saves the state it just folded back to disk. That
2932        // write must land under this test's own `runs` - the argument it
2933        // passed to `fold_due`, not the process-global `run::home` - or a
2934        // fold that landed somewhere else entirely would still be counted
2935        // above as one of the two `folded` runs.
2936        for id in [&due_ready, &due_old_schema] {
2937            let saved = read_meta(&runs, id).expect("folded run still parses");
2938            assert_ne!(
2939                saved.updated_at,
2940                ts("2026-08-01T00:00:00Z"),
2941                "fold_run must have saved the updated state back through the \
2942                 `runs` directory this test passed to fold_due"
2943            );
2944        }
2945    }
2946
2947    /// `[disk] auto_fold = false` must leave the janitor's fold-and-reclaim
2948    /// passes completely inert - a due run's worktree and record both
2949    /// survive exactly as if `housekeep` had never run at all. Cache pruning
2950    /// is a separate opt-out (`cache_limit_bytes`) and stays disabled here
2951    /// too, so this test is only ever about `auto_fold`.
2952    #[tokio::test]
2953    async fn housekeep_leaves_everything_alone_when_auto_fold_is_disabled() {
2954        let dir = tempfile::tempdir().unwrap();
2955        let runs = dir.path().join("runs");
2956        let wt = dir.path().join("wt");
2957        let home = dir.path().to_path_buf();
2958        crate::run::set_home(dir.path().to_path_buf());
2959
2960        let due_id = due_run(&runs, &wt, "20260801-000000-abcd", SCHEMA);
2961        std::fs::create_dir_all(wt.join("orphan").join("cand-A")).unwrap();
2962
2963        let mut cfg = crate::config::Config::default();
2964        cfg.disk.auto_fold = false;
2965        cfg.disk.cache_limit_bytes = 0;
2966
2967        let out = housekeep(&cfg, &home, &wt, &dir.path().join("repo"), Timestamp::now()).await;
2968
2969        assert_eq!(out.folded, 0);
2970        assert_eq!(out.unreadable, 0);
2971        assert_eq!(out.orphaned_worktrees, 0);
2972        assert!(
2973            runs.join(&due_id).exists(),
2974            "a due run's record survives untouched"
2975        );
2976        assert!(
2977            wt.join("orphan").exists(),
2978            "an orphaned worktree survives untouched: the reclaim pass never ran"
2979        );
2980    }
2981
2982    #[test]
2983    fn fold_orphaned_worktrees_removes_only_worktrees_no_run_claims_and_none_in_flight() {
2984        let dir = tempfile::tempdir().unwrap();
2985        let runs = dir.path().join("runs");
2986        let wt = dir.path().join("wt");
2987        let home = dir.path().to_path_buf();
2988
2989        // A run record exists for this one: its worktree is claimed, not
2990        // orphaned, however old the record.
2991        write_meta(
2992            &runs,
2993            "20260801-000000-aaaa",
2994            "ready",
2995            "2026-08-01T00:00:00Z",
2996        );
2997        std::fs::create_dir_all(wt.join("aaaa").join("cand-A")).unwrap();
2998
2999        // No run record at all, and nobody is working on it: this is the
3000        // leftover `fold_due` can never see, because it only ever walks
3001        // `runs/`.
3002        std::fs::create_dir_all(wt.join("bbbb").join("cand-A")).unwrap();
3003
3004        // No run record either, but a live daemon status names a run with
3005        // this short id - the save-timing gap between the daemon claiming a
3006        // task and `RunState::new` writing its first `run.json`. Must survive
3007        // untouched.
3008        std::fs::create_dir_all(wt.join("cccc")).unwrap();
3009
3010        // Not shaped like a run's short id at all - a scratch directory an
3011        // operator or another tool left in the same bay - so it is never a
3012        // reclaim target regardless of what runs claim it or not.
3013        std::fs::create_dir_all(wt.join("scratch")).unwrap();
3014
3015        // `now` pushed comfortably past `MIN_ORPHAN_AGE_SECS`, so a zero
3016        // grace - the same "always due" escape hatch `due` itself documents
3017        // - still reclaims once a worktree is genuinely old, without faking
3018        // an mtime: real directory creation just above is already in the
3019        // past relative to this `now`, by design rather than by timing.
3020        let now = Timestamp::now() + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
3021        let mut status = crate::daemon::Status::new();
3022        status.current = vec![crate::daemon::Current {
3023            worker: None,
3024            task: "20260905-000000-t111".to_owned(),
3025            run: "20260905-000000-cccc".to_owned(),
3026        }];
3027        status.updated_at = now;
3028        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
3029
3030        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
3031        assert_eq!(
3032            folded, 1,
3033            "only the truly orphaned, idle, bay-shaped worktree is removed"
3034        );
3035        assert!(wt.join("aaaa").exists(), "claimed by a run record");
3036        assert!(!wt.join("bbbb").exists(), "orphaned and idle: reclaimed");
3037        assert!(wt.join("cccc").exists(), "a run in flight is never touched");
3038        assert!(
3039            wt.join("scratch").exists(),
3040            "not shaped like a worktree bay, so never a reclaim target"
3041        );
3042    }
3043
3044    /// The gap this closes: `Runner::review` (`magi review`) creates the
3045    /// worktree with `git worktree add` before `RunState::save` ever writes a
3046    /// `run.json`, and that path never runs through the daemon's own `poll`
3047    /// loop at all, so `daemon::Status` never names it either. Without a
3048    /// grace window, a janitor pass landing in that gap would read the
3049    /// worktree as an orphan nothing is waiting on and delete a review still
3050    /// being set up.
3051    #[test]
3052    fn fold_orphaned_worktrees_leaves_a_freshly_created_bay_alone() {
3053        let dir = tempfile::tempdir().unwrap();
3054        let runs = dir.path().join("runs");
3055        let wt = dir.path().join("wt");
3056        let home = dir.path().to_path_buf();
3057
3058        std::fs::create_dir_all(wt.join("dddd").join("under-review")).unwrap();
3059
3060        let now = Timestamp::now();
3061        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 6 * 60 * 60, now));
3062        assert_eq!(
3063            folded, 0,
3064            "too fresh to tell apart from a run still being set up"
3065        );
3066        assert!(wt.join("dddd").exists());
3067    }
3068
3069    /// A fresh open question on `run`, stored and handed back for assertions.
3070    fn open_question(store: &Questions, run: &str) -> crate::ask::Question {
3071        let mut q = crate::ask::Question::new(
3072            run.to_owned(),
3073            "implement".to_owned(),
3074            "impl-A".to_owned(),
3075            "Which storage backend should the cache use?".to_owned(),
3076            String::new(),
3077            vec!["SQLite".to_owned(), "Redis".to_owned()],
3078        );
3079        store.put(&mut q).unwrap();
3080        q
3081    }
3082
3083    /// The exact ghost the phone showed: a run that already finished, with a
3084    /// question its dead seat asked still sitting `open` because it reached
3085    /// that status before `graph::Runner::settle_questions` existed (or
3086    /// missed it in the crash window `daemon::reclaim_orphaned_running`
3087    /// covers). This sweep is the second door to the same fact.
3088    #[test]
3089    fn a_finished_runs_open_question_is_swept_up() {
3090        let dir = tempfile::tempdir().unwrap();
3091        let runs = dir.path().join("runs");
3092        let store = Questions::at(dir.path().join("questions"));
3093
3094        let failed = "20260908-205802-c9eb";
3095        write_meta(&runs, failed, "failed", "2026-09-08T20:58:02Z");
3096        let failed_q = open_question(&store, failed);
3097
3098        let merged = "20260908-205501-ca67";
3099        write_meta(&runs, merged, "merged", "2026-09-08T20:55:01Z");
3100        let merged_q = open_question(&store, merged);
3101
3102        let n = abandon_settled_questions(&store, &runs);
3103        assert_eq!(n, 2, "both dead runs' questions are swept in one pass");
3104
3105        for (id, run) in [(&failed_q.id, failed), (&merged_q.id, merged)] {
3106            let back = store.get(id).unwrap();
3107            assert!(!back.status.open(), "{run} is done; nobody reads an answer");
3108            assert!(back.detail.contains(run), "{}", back.detail);
3109        }
3110    }
3111
3112    #[test]
3113    fn a_still_alive_runs_open_question_survives_the_sweep() {
3114        let dir = tempfile::tempdir().unwrap();
3115        let runs = dir.path().join("runs");
3116        let store = Questions::at(dir.path().join("questions"));
3117
3118        // `Blocked` and `Stalled` are `RunStatus::resumable`: the run can
3119        // still be picked back up, so its question may yet get a real
3120        // answer. A run still mid-competition is even more obviously alive.
3121        for (id, status) in [
3122            ("20260908-000000-b10c", "blocked"),
3123            ("20260908-000000-5ta1", "stalled"),
3124            ("20260908-000000-jud6", "judging"),
3125        ] {
3126            write_meta(&runs, id, status, "2026-09-08T00:00:00Z");
3127            let q = open_question(&store, id);
3128
3129            let n = abandon_settled_questions(&store, &runs);
3130            assert_eq!(n, 0, "{status} run is not done; nothing to sweep");
3131            assert!(
3132                store.get(&q.id).unwrap().status.open(),
3133                "{status} run's question must still be waiting"
3134            );
3135        }
3136    }
3137
3138    #[test]
3139    fn the_sweep_leaves_an_answered_question_and_an_unreadable_run_alone() {
3140        let dir = tempfile::tempdir().unwrap();
3141        let runs = dir.path().join("runs");
3142        let store = Questions::at(dir.path().join("questions"));
3143
3144        // Already decided: a sweep must never revisit it, whatever the run
3145        // that asked went on to become.
3146        let done = "20260908-000000-answ";
3147        write_meta(&runs, done, "failed", "2026-09-08T00:00:00Z");
3148        let mut answered = open_question(&store, done);
3149        answered
3150            .answer(crate::ask::Answer::Choice("SQLite".to_owned()))
3151            .unwrap();
3152        store.put(&mut answered).unwrap();
3153
3154        // No `run.json` at all for this one - deleted, or never landed.
3155        let gone = "20260908-000000-gone";
3156        let orphan = open_question(&store, gone);
3157
3158        assert_eq!(abandon_settled_questions(&store, &runs), 0);
3159        assert_eq!(
3160            store.get(&answered.id).unwrap().status,
3161            crate::ask::QuestionStatus::Answered,
3162            "a real answer is never overwritten by a sweep"
3163        );
3164        assert!(
3165            store.get(&orphan.id).unwrap().status.open(),
3166            "a run this sweep cannot read is left exactly as it was, not guessed at"
3167        );
3168    }
3169
3170    /// A grace of `0` is a legitimate, documented value for the operator's
3171    /// own `Disk::fold_grace_secs` - `due`'s "always due" case - but the
3172    /// freshness check this guards is not that policy, and must not collapse
3173    /// to it: a `0` handed straight through would reclaim a worktree the
3174    /// instant it exists, exactly the race `fold_orphaned_worktrees_leaves_a_
3175    /// freshly_created_bay_alone` exists to rule out, just with the operator
3176    /// having turned the other grace off instead of leaving it at its
3177    /// default.
3178    #[test]
3179    fn fold_orphaned_worktrees_floors_a_zero_grace_at_the_race_safe_minimum() {
3180        let dir = tempfile::tempdir().unwrap();
3181        let runs = dir.path().join("runs");
3182        let wt = dir.path().join("wt");
3183        let home = dir.path().to_path_buf();
3184
3185        std::fs::create_dir_all(wt.join("eeee").join("under-review")).unwrap();
3186
3187        // Too fresh, even with the grace argument at zero.
3188        let now = Timestamp::now();
3189        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
3190        assert_eq!(
3191            folded, 0,
3192            "a zero grace must not defeat the race-safety floor"
3193        );
3194        assert!(wt.join("eeee").exists());
3195
3196        // Once genuinely past the floor, a zero grace reclaims it - the
3197        // floor is a minimum, not a replacement policy that never fires.
3198        let later = now + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
3199        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, later));
3200        assert_eq!(folded, 1, "old enough now, regardless of the zero grace");
3201        assert!(!wt.join("eeee").exists());
3202    }
3203
3204    #[test]
3205    fn clear_abandoned_active_only_acts_once_dead_and_overrun() {
3206        let dir = tempfile::tempdir().unwrap();
3207        // Harmless if another test in this binary already pinned the global
3208        // home first (see `run::set_home`'s own doc): this test only checks
3209        // the in-memory mutation `clear_abandoned_active` makes, never a
3210        // write that landed under this exact directory.
3211        crate::run::set_home(dir.path().to_path_buf());
3212        let home = dir.path().to_path_buf();
3213        let now = ts("2026-09-14T12:00:00Z");
3214        let overrun_seat = || crate::run::ActiveSeat {
3215            node: "implement".to_owned(),
3216            started_at: now - SignedDuration::new(21_000, 0),
3217            timeout_secs: 3_600,
3218            attempt: 0,
3219            task: None,
3220            command: None,
3221            index: None,
3222            total: None,
3223        };
3224
3225        let mut state = RunState::new(
3226            PathBuf::from("/repo"),
3227            "main".to_owned(),
3228            "abc1234".to_owned(),
3229            "fixture".to_owned(),
3230            crate::config::Config::default(),
3231        );
3232        state.status = RunStatus::Implementing;
3233        state.active.insert("impl-A".to_owned(), overrun_seat());
3234
3235        // A seat still within its own budget: not provably dead yet, so this
3236        // must change nothing.
3237        let mut fresh = state.clone();
3238        fresh.active.insert(
3239            "impl-B".to_owned(),
3240            crate::run::ActiveSeat {
3241                node: "implement".to_owned(),
3242                started_at: now,
3243                timeout_secs: 3_600,
3244                attempt: 0,
3245                task: None,
3246                command: None,
3247                index: None,
3248                total: None,
3249            },
3250        );
3251        // The record is judged as saved, under the run's locks, not as the
3252        // caller holds it: so the records are saved first.
3253        fresh.save_under(&home).unwrap();
3254        assert!(!clear_abandoned_active(&mut fresh, &home, now).unwrap());
3255        assert!(!fresh.active.is_empty());
3256        assert_eq!(fresh.status, RunStatus::Implementing);
3257
3258        state.save_under(&home).unwrap();
3259        let store = Questions::at(home.join("questions"));
3260        let q = open_question(&store, &state.id);
3261
3262        assert!(clear_abandoned_active(&mut state, &home, now).unwrap());
3263        assert!(state.active.is_empty());
3264        assert_eq!(state.status, RunStatus::Failed);
3265        assert!(
3266            !store.get(&q.id).unwrap().status.open(),
3267            "the abandoned seat's own open question must not keep badging the \
3268             operator until some later daemon startup notices it"
3269        );
3270    }
3271
3272    fn overrun_run(now: Timestamp) -> RunState {
3273        let mut state = RunState::new(
3274            PathBuf::from("/repo"),
3275            "main".to_owned(),
3276            "abc1234".to_owned(),
3277            "fixture".to_owned(),
3278            crate::config::Config::default(),
3279        );
3280        state.status = RunStatus::Implementing;
3281        state.active.insert(
3282            "impl-A".to_owned(),
3283            crate::run::ActiveSeat {
3284                node: "implement".to_owned(),
3285                started_at: now - SignedDuration::new(21_000, 0),
3286                timeout_secs: 3_600,
3287                attempt: 0,
3288                task: None,
3289                command: None,
3290                index: None,
3291                total: None,
3292            },
3293        );
3294        state
3295    }
3296
3297    /// The cleanup writes the record under the run's locks, from a fresh read:
3298    /// a handover that landed after the fold released its own locks is neither
3299    /// erased by the caller's copy nor allowed to go unnoticed.
3300    #[test]
3301    fn clearing_abandoned_seats_keeps_a_handover_that_landed_after_the_fold() {
3302        let dir = tempfile::tempdir().unwrap();
3303        let home = dir.path().to_path_buf();
3304        let now = ts("2026-09-14T12:00:00Z");
3305        let mut stale = overrun_run(now);
3306        stale.save_under(&home).unwrap();
3307        let mut handed = RunState::load_under(&stale.id, &home).unwrap();
3308        handed.released_to = Some("20260901-000000-succ".to_owned());
3309        handed.released_branches.push("magi/branch/A".to_owned());
3310        handed.save_under(&home).unwrap();
3311
3312        assert!(clear_abandoned_active(&mut stale, &home, now).unwrap());
3313        let saved = RunState::load_under(&stale.id, &home).unwrap();
3314        assert_eq!(saved.released_to.as_deref(), Some("20260901-000000-succ"));
3315        assert_eq!(saved.released_branches, ["magi/branch/A"]);
3316        assert_eq!(saved.status, RunStatus::Failed);
3317        assert!(saved.active.is_empty());
3318    }
3319
3320    /// Held locks and vanished records are "nothing done", never a write.
3321    #[test]
3322    fn clearing_abandoned_seats_writes_nothing_while_the_run_is_held_or_gone() {
3323        let dir = tempfile::tempdir().unwrap();
3324        let home = dir.path().to_path_buf();
3325        let now = ts("2026-09-14T12:00:00Z");
3326        let mut state = overrun_run(now);
3327        state.save_under(&home).unwrap();
3328        let record = home.join("runs").join(&state.id).join("run.json");
3329        let before = std::fs::read(&record).unwrap();
3330        {
3331            let _owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
3332            assert!(!clear_abandoned_active(&mut state, &home, now).unwrap());
3333        }
3334        {
3335            let _lease = crate::driver::maintenance(&home, &state.id).unwrap();
3336            assert!(!clear_abandoned_active(&mut state, &home, now).unwrap());
3337        }
3338        assert_eq!(std::fs::read(&record).unwrap(), before);
3339
3340        std::fs::remove_dir_all(home.join("runs").join(&state.id)).unwrap();
3341        assert!(!clear_abandoned_active(&mut state, &home, now).unwrap());
3342        assert!(
3343            !home.join("runs").join(&state.id).exists(),
3344            "a deleted run is not brought back by its cleanup"
3345        );
3346    }
3347
3348    /// Write a whole `run.json` that magi can read, over the given state.
3349    fn write_meta(runs: &Path, id: &str, status: &str, updated_at: &str) {
3350        let day = &updated_at[..10];
3351        std::fs::create_dir_all(runs.join(id)).unwrap();
3352        let body = format!(
3353            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}}"#
3354        );
3355        std::fs::write(runs.join(id).join("run.json"), body).unwrap();
3356    }
3357
3358    /// Write a fully-formed, `Ready`, well-past-grace `run.json` tagged with
3359    /// an arbitrary schema number - so a test can write one this build's own
3360    /// `RunState::new` could never produce on its own. Returns the id.
3361    ///
3362    /// `wt` becomes this run's `graph.worktree_root`: left at the config
3363    /// default, `RunState::worktree_root` falls through to
3364    /// `run::default_worktree_root` - the operator's real `~/wt/magi` - and
3365    /// `graph::fold_run`'s second sweep would then `read_dir` and remove
3366    /// worktrees there instead of anything this test owns.
3367    fn due_run(runs: &Path, wt: &Path, id: &str, schema: u32) -> String {
3368        due_run_with_status(runs, wt, id, schema, RunStatus::Ready)
3369    }
3370
3371    /// [`due_run`], with the terminal status a caller wants instead of the
3372    /// `Ready` every other caller here happens to want.
3373    fn due_run_with_status(
3374        runs: &Path,
3375        wt: &Path,
3376        id: &str,
3377        schema: u32,
3378        status: RunStatus,
3379    ) -> String {
3380        let mut config = crate::config::Config::default();
3381        config.graph.worktree_root = Some(wt.to_path_buf());
3382        let mut state = RunState::new(
3383            PathBuf::from("/nonexistent/repo"),
3384            "main".to_owned(),
3385            "0000000000000000000000000000000000000000".to_owned(),
3386            String::new(),
3387            config,
3388        );
3389        state.id = id.to_owned();
3390        state.status = status;
3391        state.updated_at = ts("2026-08-01T00:00:00Z");
3392        let mut value = serde_json::to_value(&state).unwrap();
3393        value["schema"] = serde_json::json!(schema);
3394        std::fs::create_dir_all(runs.join(id)).unwrap();
3395        std::fs::write(
3396            runs.join(id).join("run.json"),
3397            serde_json::to_string_pretty(&value).unwrap(),
3398        )
3399        .unwrap();
3400        id.to_owned()
3401    }
3402
3403    #[test]
3404    fn fold_due_folds_a_superseded_run_same_as_any_other_terminal_one() {
3405        let dir = tempfile::tempdir().unwrap();
3406        let runs = dir.path().join("runs");
3407        let wt = dir.path().join("wt");
3408        let home = dir.path().to_path_buf();
3409        let disk = Disk::default();
3410        let now = ts("2026-09-05T00:00:00Z");
3411
3412        let superseded = due_run_with_status(
3413            &runs,
3414            &wt,
3415            "20260801-000000-cccc",
3416            SCHEMA,
3417            RunStatus::Superseded,
3418        );
3419
3420        let (folded, unreadable) =
3421            block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
3422        assert_eq!(
3423            folded, 1,
3424            "a superseded run has nothing left for a human to check, so it folds \
3425             exactly like a merged one"
3426        );
3427        assert_eq!(unreadable, 0);
3428        assert!(
3429            read_meta(&runs, &superseded).is_ok(),
3430            "folding drops the worktree, not the record"
3431        );
3432    }
3433
3434    /// A throwaway repo with one commit on `main`, for a test that needs a
3435    /// real winner worktree `fold_run` can actually remove.
3436    pub(crate) fn init_repo(dir: &Path) {
3437        use crate::proc::Quiet as _;
3438        let run = |args: &[&str]| {
3439            let out = std::process::Command::new("git")
3440                .args(args)
3441                .current_dir(dir)
3442                .quiet()
3443                .output()
3444                .expect("spawn git");
3445            assert!(
3446                out.status.success(),
3447                "git {args:?} failed: {}",
3448                String::from_utf8_lossy(&out.stderr)
3449            );
3450        };
3451        run(&["init", "-b", "main"]);
3452        run(&["config", "user.name", "magi test"]);
3453        run(&["config", "user.email", "magi@example.com"]);
3454        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
3455        run(&["add", "-A"]);
3456        run(&["commit", "-m", "init"]);
3457    }
3458
3459    /// A due, terminal run with a decided winner that still has a real
3460    /// worktree and branch on disk - so a test can tell whether folding it
3461    /// actually removed the winner or only left it registered as folded.
3462    pub(crate) async fn due_run_with_winner_worktree(
3463        runs: &Path,
3464        wt: &Path,
3465        repo: &Path,
3466        id: &str,
3467        status: RunStatus,
3468    ) -> (String, PathBuf) {
3469        use crate::run::{Candidate, Tally};
3470        use std::collections::BTreeMap;
3471
3472        let mut config = crate::config::Config::default();
3473        config.graph.worktree_root = Some(wt.to_path_buf());
3474        let mut state = RunState::new(
3475            repo.to_path_buf(),
3476            "main".to_owned(),
3477            "0000000000000000000000000000000000000000".to_owned(),
3478            String::new(),
3479            config,
3480        );
3481        state.id = id.to_owned();
3482        state.status = status;
3483        state.updated_at = ts("2026-08-01T00:00:00Z");
3484
3485        let winner_wt = state.worktree_root().join("cand-A");
3486        crate::git::worktree_add_branch(repo, &winner_wt, &format!("magi/{id}/A"), "main")
3487            .await
3488            .expect("winner worktree");
3489
3490        state.candidates.push(Candidate {
3491            index: 0,
3492            label: 'A',
3493            agent: "agent".to_owned(),
3494            branch: format!("magi/{id}/A"),
3495            worktree: winner_wt.clone(),
3496            summary: String::new(),
3497            stat: String::new(),
3498            files: 0,
3499            commits: 0,
3500            empty: false,
3501            failed: None,
3502            verified_noop: None,
3503            duration_ms: 0,
3504            folded: false,
3505        });
3506        state.tally = Some(Tally {
3507            first_choice: BTreeMap::from([('A', 1)]),
3508            borda: BTreeMap::new(),
3509            winner: 'A',
3510            rankings: 1,
3511            unanimous_initial: true,
3512            deliberated: false,
3513            changed_votes: 0,
3514            unanimous_final: true,
3515            tie_break: None,
3516            judges: 1,
3517            present: 1,
3518            quorum: 1,
3519            met_quorum: true,
3520            uncontested: None,
3521        });
3522        std::fs::create_dir_all(runs.join(id)).unwrap();
3523        std::fs::write(
3524            runs.join(id).join("run.json"),
3525            serde_json::to_string_pretty(&state).unwrap(),
3526        )
3527        .unwrap();
3528        (id.to_owned(), winner_wt)
3529    }
3530
3531    /// [`due_run_with_winner_worktree`] for a *confirmed merged* run: the
3532    /// fetched base (`refs/remotes/origin/main`) already holds the winner's
3533    /// tip, so the confirmed-merge source proof passes and the fold keeps an
3534    /// evidence manifest instead of any patch. The record keeps its old
3535    /// `updated_at`, so the run stays past any grace.
3536    pub(crate) async fn merged_run_with_worktree(
3537        home: &Path,
3538        repo: &Path,
3539        wt: &Path,
3540        id: &str,
3541    ) -> (String, PathBuf) {
3542        let (id, worktree) =
3543            due_run_with_winner_worktree(&home.join("runs"), wt, repo, id, RunStatus::Merged).await;
3544        crate::git::git(repo, &["update-ref", "refs/remotes/origin/main", "main"])
3545            .await
3546            .unwrap();
3547        let mut state = RunState::load_under(&id, home).unwrap();
3548        state.merge = Some(crate::run::MergeOutcome {
3549            mode: crate::config::MergeMode::Pr,
3550            ok: true,
3551            detail: "confirmed merged".into(),
3552            empty: false,
3553        });
3554        state.driver_exited = true;
3555        let aged = state.updated_at;
3556        state.save_under_at(home, aged).unwrap();
3557        (id, worktree)
3558    }
3559
3560    #[tokio::test]
3561    async fn completed_task_retains_independent_historical_sources_without_a_merge_proof() {
3562        let dir = tempfile::tempdir().unwrap();
3563        let home = dir.path();
3564        let runs = home.join("runs");
3565        let wt = home.join("wt");
3566        let repo = home.join("repo");
3567        std::fs::create_dir_all(&repo).unwrap();
3568        init_repo(&repo);
3569        let queue = crate::queue::Queue::at(home.join("queue"));
3570        let mut task = crate::queue::Task::new(
3571            "completed".into(),
3572            "retain independent historical changes".into(),
3573            repo.clone(),
3574            crate::queue::Source::Human,
3575        );
3576        let mut sources = Vec::new();
3577        for (id, status) in [
3578            ("20260801-000000-old1", RunStatus::Superseded),
3579            ("20260801-000000-old2", RunStatus::Failed),
3580        ] {
3581            let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
3582            std::fs::write(worktree.join("independent.txt"), &id).unwrap();
3583            crate::git::git(&worktree, &["add", "independent.txt"])
3584                .await
3585                .unwrap();
3586            crate::git::git(
3587                &worktree,
3588                &["commit", "-m", "Independent historical change"],
3589            )
3590            .await
3591            .unwrap();
3592            let head = crate::git::rev_parse(&worktree, "HEAD").await.unwrap();
3593            let mut state = RunState::load_under(&id, home).unwrap();
3594            state.driver_exited = true;
3595            if status == RunStatus::Failed {
3596                state.tally = None;
3597            }
3598            state.save_under(home).unwrap();
3599            task.link_run(&id);
3600            sources.push((id, worktree, head));
3601        }
3602        // A newer empty attempt and task completion are no proof that either
3603        // independent historical implementation was incorporated.
3604        let mut latest = RunState::new(
3605            repo.clone(),
3606            "main".into(),
3607            crate::git::rev_parse(&repo, "main").await.unwrap(),
3608            task.instruction.clone(),
3609            crate::config::Config::default(),
3610        );
3611        latest.status = RunStatus::Ready;
3612        latest.driver_exited = true;
3613        latest.save_under(home).unwrap();
3614        task.start(latest.id.clone());
3615        task.succeed(crate::queue::CompletionContext::new(
3616            crate::queue::CompletionActor::DaemonSettle,
3617            None,
3618            home,
3619            &task,
3620        ));
3621        queue.put(&mut task).unwrap();
3622
3623        let (folded, unreadable) = fold_due(
3624            &runs,
3625            home,
3626            &wt,
3627            &Disk::default(),
3628            ts("2026-09-05T00:00:00Z"),
3629        )
3630        .await
3631        .unwrap();
3632        assert_eq!((folded, unreadable), (0, 0));
3633        for (id, worktree, head) in sources {
3634            assert!(worktree.exists());
3635            assert_eq!(
3636                crate::git::rev_parse(&worktree, "HEAD").await.unwrap(),
3637                head
3638            );
3639            let mut state = RunState::load_under(&id, home).unwrap();
3640            assert!(!state.candidates[0].folded);
3641            let error = crate::graph::fold_run(&mut state, true, home)
3642                .await
3643                .unwrap_err();
3644            assert!(
3645                error
3646                    .to_string()
3647                    .contains(&format!("source of task {}", task.id))
3648            );
3649            assert_eq!(
3650                crate::git::rev_parse(&repo, &state.candidates[0].branch)
3651                    .await
3652                    .unwrap(),
3653                head
3654            );
3655            assert!(worktree.exists());
3656            assert!(runs.join(&id).join("run.json").exists());
3657        }
3658    }
3659
3660    #[tokio::test]
3661    async fn recovery_retains_historical_sources_after_success_and_automatic_cleanup() {
3662        let dir = tempfile::tempdir().unwrap();
3663        let home = dir.path();
3664        let runs = home.join("runs");
3665        let wt = home.join("wt");
3666        let repo = home.join("repo");
3667        std::fs::create_dir_all(&repo).unwrap();
3668        init_repo(&repo);
3669        let mut task = crate::queue::Task::new(
3670            "recover".into(),
3671            "keep measured behavior".into(),
3672            repo.clone(),
3673            crate::queue::Source::Human,
3674        );
3675        let mut sources = Vec::new();
3676        for (id, status) in [
3677            ("20260801-000000-old1", RunStatus::Blocked),
3678            ("20260801-000000-old2", RunStatus::Stalled),
3679        ] {
3680            let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
3681            let mut state = RunState::load_under(&id, home).unwrap();
3682            state.driver_exited = true;
3683            state.save_under(home).unwrap();
3684            task.link_run(&id);
3685            sources.push((id, worktree));
3686        }
3687        crate::pr_recovery::retain_sources(&task, home).unwrap();
3688        let mut recovered = RunState::new(
3689            repo.clone(),
3690            "main".into(),
3691            "base".into(),
3692            task.instruction.clone(),
3693            crate::config::Config::default(),
3694        );
3695        recovered.config.graph.worktree_root = Some(wt.clone());
3696        recovered.status = RunStatus::Ready;
3697        recovered.driver_exited = true;
3698        recovered.save_under(home).unwrap();
3699        task.start(recovered.id.clone());
3700        task.succeed(crate::queue::CompletionContext::new(
3701            crate::queue::CompletionActor::DaemonSettle,
3702            None,
3703            home,
3704            &task,
3705        ));
3706        crate::daemon::supersede_prior_runs(&task, home);
3707        for (id, _) in &sources {
3708            assert_eq!(
3709                RunState::load_under(id, home).unwrap().status,
3710                RunStatus::Superseded
3711            );
3712        }
3713        let disk = Disk::default();
3714        let now = Timestamp::now()
3715            .checked_add(SignedDuration::from_secs(
3716                i64::try_from(disk.fold_grace_secs + 1).unwrap(),
3717            ))
3718            .unwrap();
3719        let (_, unreadable) = fold_due(&runs, home, &wt, &disk, now).await.unwrap();
3720        assert_eq!(unreadable, 0);
3721        for (id, worktree) in sources {
3722            assert!(worktree.exists());
3723            assert!(
3724                crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
3725                    .await
3726                    .unwrap()
3727            );
3728            let mut historical = RunState::load_under(&id, home).unwrap();
3729            assert!(!historical.candidates[0].folded);
3730            let error = crate::graph::fold_run(&mut historical, true, home)
3731                .await
3732                .unwrap_err();
3733            assert!(
3734                error
3735                    .to_string()
3736                    .contains("explicitly retained recovery source")
3737            );
3738            assert!(!historical.candidates[0].folded);
3739            assert!(
3740                worktree.exists(),
3741                "every automatic fold entry preserves retained sources"
3742            );
3743        }
3744    }
3745
3746    #[tokio::test]
3747    async fn fold_due_drops_a_superseded_runs_own_winner_worktree_but_keeps_a_readys() {
3748        let dir = tempfile::tempdir().unwrap();
3749        let runs = dir.path().join("runs");
3750        let wt = dir.path().join("wt");
3751        let repo = dir.path().join("repo");
3752        let home = dir.path().to_path_buf();
3753        let disk = Disk::default();
3754        let now = ts("2026-09-05T00:00:00Z");
3755        std::fs::create_dir_all(&repo).unwrap();
3756        init_repo(&repo);
3757
3758        let (superseded_id, superseded_wt) = due_run_with_winner_worktree(
3759            &runs,
3760            &wt,
3761            &repo,
3762            "20260801-000000-supw",
3763            RunStatus::Superseded,
3764        )
3765        .await;
3766        // `Ready` is auto-folded exactly like `Superseded` (both terminal and
3767        // non-resumable), but never landed anywhere - its own winner is
3768        // deliberately kept, which is what makes it the right contrast here.
3769        // `Blocked`/`Stalled` are `resumable()` and so never even reach
3770        // `fold_run` in the first place; they would not exercise the
3771        // `drop_winner` choice this test is about.
3772        let (ready_id, ready_wt) = due_run_with_winner_worktree(
3773            &runs,
3774            &wt,
3775            &repo,
3776            "20260801-000000-rdyw",
3777            RunStatus::Ready,
3778        )
3779        .await;
3780
3781        let (folded, unreadable) = fold_due(&runs, &home, &wt, &disk, now)
3782            .await
3783            .expect("fold_due");
3784        assert_eq!(folded, 2);
3785        assert_eq!(unreadable, 0);
3786
3787        assert!(
3788            !superseded_wt.exists(),
3789            "a superseded run's own winner never lands anywhere else, so its worktree \
3790             must be dropped exactly like a merged run's"
3791        );
3792        assert!(
3793            ready_wt.exists(),
3794            "a still-ready run's winner may yet be merged by hand - folding must not \
3795             touch it"
3796        );
3797
3798        // Both records survive the fold; only the worktrees differ.
3799        assert!(read_meta(&runs, &superseded_id).is_ok());
3800        assert!(read_meta(&runs, &ready_id).is_ok());
3801    }
3802
3803    /// What a test does between `fold_one`'s first read and its locks.
3804    type Interleaving = Box<dyn FnOnce(&Path, &str)>;
3805
3806    thread_local! {
3807        /// Run once by `fold_one` after its first read of a run and before the
3808        /// fold takes the run's locks: the window a handover falls into.
3809        pub(crate) static AFTER_FIRST_READ: std::cell::RefCell<Option<Interleaving>> =
3810            const { std::cell::RefCell::new(None) };
3811    }
3812
3813    /// Rewrite one field of a saved `run.json` without going through `RunState`.
3814    fn edit_run(runs: &Path, id: &str, edit: impl FnOnce(&mut serde_json::Value)) {
3815        let path = runs.join(id).join("run.json");
3816        let mut value: serde_json::Value =
3817            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
3818        edit(&mut value);
3819        std::fs::write(path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
3820    }
3821
3822    const NO_BOUNDS: FoldBounds = FoldBounds {
3823        inspect: usize::MAX,
3824        fold: usize::MAX,
3825        budget: std::time::Duration::from_secs(3600),
3826    };
3827
3828    /// A pass that is far enough in the future for every fixture run to be past
3829    /// its grace period even after `fold_run` re-saved it (which stamps real time).
3830    fn well_after_every_fold() -> Timestamp {
3831        Timestamp::now()
3832            .checked_add(SignedDuration::from_hours(48))
3833            .unwrap()
3834    }
3835
3836    /// One pass from an explicit saved state, without touching the home's cycle file.
3837    async fn pass_from(
3838        runs: &Path,
3839        home: &Path,
3840        disk: &Disk,
3841        now: Timestamp,
3842        saved: Saved,
3843        bounds: FoldBounds,
3844    ) -> FoldTurn {
3845        fold_turn_from(runs, home, disk, now, saved, bounds).await.0
3846    }
3847
3848    fn run_json(home: &Path, id: &str) -> RunState {
3849        RunState::load_under(id, home).unwrap()
3850    }
3851
3852    #[tokio::test]
3853    async fn a_mixed_pass_counts_each_outcome_and_touches_only_what_fold_due_would() {
3854        let dir = tempfile::tempdir().unwrap();
3855        let home = dir.path();
3856        let runs = home.join("runs");
3857        let wt = home.join("wt");
3858        let repo = home.join("repo");
3859        std::fs::create_dir_all(&repo).unwrap();
3860        init_repo(&repo);
3861        let now = ts("2026-09-05T00:00:00Z");
3862        let disk = Disk {
3863            fold_grace_secs: 600,
3864            ..Disk::default()
3865        };
3866        let run = |n: u32| format!("20260801-000000-a{n:03}");
3867        let mut worktrees = Vec::new();
3868        for (n, status) in [
3869            (1, RunStatus::Superseded),  // folds
3870            (2, RunStatus::Ready),       // nothing to remove: its winner is kept
3871            (3, RunStatus::Blocked),     // resumable
3872            (4, RunStatus::Superseded),  // within grace
3873            (5, RunStatus::Superseded),  // live (daemon claim)
3874            (6, RunStatus::Superseded),  // unreadable
3875            (7, RunStatus::Superseded),  // startup incomplete
3876            (8, RunStatus::Superseded),  // candidate preservation pending
3877            (9, RunStatus::Superseded),  // explicitly retained
3878            (10, RunStatus::Superseded), // fold fails: its repository is gone
3879            (11, RunStatus::Merged),     // confirmed merge, no fetched base to prove it
3880            (12, RunStatus::Superseded), // live (a borrower holds its output lease)
3881        ] {
3882            let (_, worktree) =
3883                due_run_with_winner_worktree(&runs, &wt, &repo, &run(n), status).await;
3884            worktrees.push(worktree);
3885        }
3886        let mut merged = RunState::load_under(&run(11), home).unwrap();
3887        merged.merge = Some(crate::run::MergeOutcome {
3888            mode: crate::config::MergeMode::Pr,
3889            ok: true,
3890            detail: "confirmed merged".into(),
3891            empty: false,
3892        });
3893        let aged = merged.updated_at;
3894        merged.save_under_at(home, aged).unwrap();
3895        edit_run(&runs, &run(4), |v| {
3896            v["updated_at"] = "2026-09-04T23:59:00Z".into()
3897        });
3898        let mut status = crate::daemon::Status::new();
3899        status.current = vec![crate::daemon::Current {
3900            worker: None,
3901            task: "20260905-000000-task".to_owned(),
3902            run: run(5),
3903        }];
3904        status.updated_at = now;
3905        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
3906        std::fs::write(runs.join(run(6)).join("run.json"), "{ not json").unwrap();
3907        edit_run(&runs, &run(7), |v| {
3908            v["startup"] = serde_json::json!({
3909                "kind": "implementation", "branch": null, "stage": "prepare",
3910                "complete": false, "failure": null
3911            })
3912        });
3913        edit_run(&runs, &run(8), |v| {
3914            v["candidate_preservation"] = serde_json::json!({"A": "rescue pending"})
3915        });
3916        let mut task = crate::queue::Task::new(
3917            "keep".into(),
3918            "keep".into(),
3919            repo.clone(),
3920            crate::queue::Source::Human,
3921        );
3922        task.link_run(&run(9));
3923        crate::pr_recovery::retain_sources(&task, home).unwrap();
3924        edit_run(&runs, &run(10), |v| {
3925            v["repo"] = home.join("gone").to_string_lossy().into_owned().into()
3926        });
3927        let _borrower = crate::retention::OutputLease::take(&worktrees[11], false).unwrap();
3928
3929        let turn = pass_from(&runs, home, &disk, now, Saved::Absent, NO_BOUNDS).await;
3930        assert_eq!(
3931            (
3932                turn.inspected,
3933                turn.invoked,
3934                turn.folded,
3935                turn.nothing_left,
3936                turn.already_folded,
3937                turn.resumable,
3938                turn.within_grace,
3939                turn.live,
3940                turn.unreadable,
3941                turn.proof_incomplete,
3942                turn.recovery_retained,
3943                turn.failed,
3944            ),
3945            // Run 2 (`Ready`, winner kept) has a bay on disk, so it is not
3946            // settled: a fold is invoked and finds nothing to remove.
3947            (12, 5, 1, 1, 0, 1, 1, 2, 1, 3, 1, 1),
3948            "{turn:?}"
3949        );
3950        assert_eq!(
3951            (turn.cursor.as_deref(), turn.stopped),
3952            (None, FoldStop::EndOfCycle)
3953        );
3954        assert!(!worktrees[0].exists(), "the due superseded run folded");
3955        for (n, worktree) in worktrees.iter().enumerate().skip(1) {
3956            assert!(
3957                worktree.exists(),
3958                "run {} must be left exactly as it was found",
3959                n + 1
3960            );
3961        }
3962        let note = |id: String| turn.notes.iter().find(|note| note.run == id).unwrap();
3963        assert_eq!(note(run(7)).outcome, "proof_incomplete");
3964        let unproven = note(run(11));
3965        assert_eq!(unproven.outcome, "proof_incomplete");
3966        assert!(unproven.text.contains("fetched base"), "{unproven:?}");
3967        assert_eq!(note(run(10)).outcome, "failed");
3968        assert!(
3969            turn.notes
3970                .iter()
3971                .all(|note| note.text.chars().count() <= NOTE_CHARS)
3972        );
3973    }
3974
3975    /// Bound, cursor and restart: more eligible runs than one pass may fold.
3976    #[tokio::test]
3977    async fn bounded_passes_resume_from_the_saved_cursor_and_fold_each_run_once() {
3978        let dir = tempfile::tempdir().unwrap();
3979        let home = dir.path();
3980        let runs = home.join("runs");
3981        let wt = home.join("wt");
3982        let repo = home.join("repo");
3983        std::fs::create_dir_all(&repo).unwrap();
3984        init_repo(&repo);
3985        let now = well_after_every_fold();
3986        let disk = Disk {
3987            fold_grace_secs: 600,
3988            ..Disk::default()
3989        };
3990        let bounds = FoldBounds {
3991            fold: 2,
3992            ..NO_BOUNDS
3993        };
3994        let ids: Vec<String> = (1..=5)
3995            .map(|n| format!("20260801-000000-b{n:03}"))
3996            .collect();
3997        let mut worktrees = Vec::new();
3998        for id in &ids {
3999            let (_, worktree) =
4000                due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
4001            worktrees.push(worktree);
4002        }
4003        let gone = |worktrees: &[PathBuf]| worktrees.iter().filter(|w| !w.exists()).count();
4004
4005        let first = fold_turn(&runs, home, &disk, now, bounds).await;
4006        assert_eq!(
4007            (first.folded, first.inspected, first.invoked),
4008            (2, 2, 2),
4009            "{first:?}"
4010        );
4011        assert_eq!(first.stopped, FoldStop::FoldLimit);
4012        assert_eq!(first.cursor.as_deref(), Some(ids[1].as_str()));
4013        assert_eq!(first.high_water.as_deref(), Some(ids[4].as_str()));
4014        assert_eq!(gone(&worktrees), 2);
4015        let saved: serde_json::Value =
4016            serde_json::from_slice(&std::fs::read(home.join(FOLD_TURN_CURSOR_FILE)).unwrap())
4017                .unwrap();
4018        assert_eq!(
4019            (saved["cursor"].as_str(), saved["high_water"].as_str()),
4020            (Some(ids[1].as_str()), Some(ids[4].as_str())),
4021            "the cycle is saved before anyone could restart"
4022        );
4023
4024        // Nothing is held in memory between passes: this is the restart.
4025        let second = fold_turn(&runs, home, &disk, now, bounds).await;
4026        assert_eq!(
4027            (second.folded, second.nothing_left, second.already_folded),
4028            (2, 0, 0),
4029            "the first two are not revisited: {second:?}"
4030        );
4031        assert_eq!(second.cursor.as_deref(), Some(ids[3].as_str()));
4032        assert_eq!(gone(&worktrees), 4);
4033
4034        let third = fold_turn(&runs, home, &disk, now, bounds).await;
4035        assert_eq!((third.folded, third.inspected), (1, 1), "{third:?}");
4036        assert_eq!(
4037            (third.cursor.as_deref(), third.stopped),
4038            (None, FoldStop::EndOfCycle)
4039        );
4040        assert_eq!(gone(&worktrees), 5);
4041        assert!(
4042            !home.join(FOLD_TURN_CURSOR_FILE).exists(),
4043            "a finished cycle leaves nothing saved; the next pass begins another"
4044        );
4045        assert_eq!(first.folded + second.folded + third.folded, ids.len());
4046
4047        // A fold that removed something has not seen the bay empty yet: the next
4048        // cycle's fold finds nothing left and records it (`fold_settled_at`),
4049        // so each of these runs spends one more invocation, once.
4050        let fourth = fold_turn(&runs, home, &disk, now, NO_BOUNDS).await;
4051        assert_eq!(
4052            (fourth.nothing_left, fourth.already_folded, fourth.invoked),
4053            (5, 0, 5),
4054            "{fourth:?}"
4055        );
4056        // Then the whole history is judged in one pass and no fold is started:
4057        // the fact a fold recorded and a bay confirmed absent are the whole proof.
4058        let fifth = fold_turn(&runs, home, &disk, now, bounds).await;
4059        assert_eq!(
4060            (fifth.already_folded, fifth.inspected, fifth.invoked),
4061            (5, 5, 0),
4062            "{fifth:?}"
4063        );
4064        assert_eq!(fifth.stopped, FoldStop::EndOfCycle);
4065    }
4066
4067    #[tokio::test]
4068    async fn a_zero_time_budget_still_judges_one_run_per_pass_and_reaches_the_tail() {
4069        let dir = tempfile::tempdir().unwrap();
4070        let home = dir.path();
4071        let runs = home.join("runs");
4072        let wt = home.join("wt");
4073        let repo = home.join("repo");
4074        std::fs::create_dir_all(&repo).unwrap();
4075        init_repo(&repo);
4076        let disk = Disk::default();
4077        let now = well_after_every_fold();
4078        let mut worktrees = Vec::new();
4079        for n in 1..=3 {
4080            let id = format!("20260801-000000-c{n:03}");
4081            let (_, worktree) =
4082                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
4083            worktrees.push(worktree);
4084        }
4085        let bounds = FoldBounds {
4086            budget: std::time::Duration::ZERO,
4087            ..NO_BOUNDS
4088        };
4089        for (pass, worktree) in worktrees.iter().enumerate() {
4090            let turn = fold_turn(&runs, home, &disk, now, bounds).await;
4091            assert_eq!(
4092                (turn.inspected, turn.folded),
4093                (1, 1),
4094                "pass {pass}: {turn:?}"
4095            );
4096            assert!(!worktree.exists());
4097            let expected = if pass == 2 {
4098                FoldStop::EndOfCycle
4099            } else {
4100                FoldStop::TimeBudget
4101            };
4102            assert_eq!(turn.stopped, expected);
4103        }
4104    }
4105
4106    #[tokio::test]
4107    async fn judging_is_bounded_too() {
4108        let dir = tempfile::tempdir().unwrap();
4109        let home = dir.path();
4110        let runs = home.join("runs");
4111        let disk = Disk::default();
4112        let now = ts("2026-09-05T00:00:00Z");
4113        let ids: Vec<String> = (1..=5)
4114            .map(|n| format!("20260801-000000-d{n:03}"))
4115            .collect();
4116        for id in &ids {
4117            write_meta(&runs, id, "blocked", "2026-08-01T00:00:00Z");
4118        }
4119        let bounds = FoldBounds {
4120            inspect: 2,
4121            ..NO_BOUNDS
4122        };
4123        let mut seen = Vec::new();
4124        for _ in 0..3 {
4125            let turn = fold_turn(&runs, home, &disk, now, bounds).await;
4126            assert_eq!(turn.resumable, turn.inspected);
4127            seen.push((turn.inspected, turn.cursor, turn.stopped));
4128        }
4129        assert_eq!(
4130            seen,
4131            vec![
4132                (2, Some(ids[1].clone()), FoldStop::InspectLimit),
4133                (2, Some(ids[3].clone()), FoldStop::InspectLimit),
4134                (1, None, FoldStop::EndOfCycle),
4135            ]
4136        );
4137    }
4138
4139    /// A saved cycle that cannot be trusted starts a clean one, and says so.
4140    #[tokio::test]
4141    async fn a_saved_cycle_that_cannot_be_trusted_starts_over_and_says_why() {
4142        let ids: Vec<String> = (1..=5)
4143            .map(|n| format!("20260801-000000-r{n:03}"))
4144            .collect();
4145        let saved = |cursor: &str, high_water: &str| {
4146            serde_json::json!({"cursor": cursor, "high_water": high_water}).to_string()
4147        };
4148        let cases = [
4149            ("unreadable", Some("{ not json".to_owned())),
4150            (
4151                "unreadable",
4152                Some(ids[2].clone()), // the plain-id format of an earlier build
4153            ),
4154            (
4155                "no longer exists",
4156                Some(saved("20260801-000000-q999", &ids[4])),
4157            ),
4158            ("below the cursor", Some(saved(&ids[3], &ids[1]))),
4159            ("nothing left", Some(saved(&ids[4], &ids[4]))),
4160            // Ids that cannot be run ids, and a mark newer than every run:
4161            // with the latter, arrivals would never end the cycle.
4162            ("not a run id", Some(saved("nonsense", &ids[4]))),
4163            ("not a run id", Some(saved(&ids[1], "zzzz"))),
4164            (
4165                "newer than every run",
4166                Some(saved(&ids[1], "20260801-000000-zzzz")),
4167            ),
4168            ("unreadable", None), // a directory where the file belongs
4169        ];
4170        for (reason, body) in cases {
4171            let dir = tempfile::tempdir().unwrap();
4172            let home = dir.path();
4173            let runs = home.join("runs");
4174            for id in &ids {
4175                write_meta(&runs, id, "blocked", "2026-08-01T00:00:00Z");
4176            }
4177            match body {
4178                Some(body) => std::fs::write(home.join(FOLD_TURN_CURSOR_FILE), body).unwrap(),
4179                None => std::fs::create_dir(home.join(FOLD_TURN_CURSOR_FILE)).unwrap(),
4180            }
4181            let bounds = FoldBounds {
4182                inspect: 2,
4183                ..NO_BOUNDS
4184            };
4185            let turn = fold_turn(
4186                &runs,
4187                home,
4188                &Disk::default(),
4189                ts("2026-09-05T00:00:00Z"),
4190                bounds,
4191            )
4192            .await;
4193            assert!(
4194                turn.cycle_restart
4195                    .as_deref()
4196                    .is_some_and(|why| why.contains(reason)),
4197                "{reason}: {turn:?}"
4198            );
4199            assert_eq!(turn.inspected, 2, "{reason}: restarted from the oldest");
4200            assert_eq!(turn.cursor.as_deref(), Some(ids[1].as_str()), "{reason}");
4201            assert_eq!(
4202                turn.high_water.as_deref(),
4203                Some(ids[4].as_str()),
4204                "{reason}: a fresh high-water mark"
4205            );
4206        }
4207    }
4208
4209    #[tokio::test]
4210    async fn an_unsaved_cursor_is_reported_not_hidden() {
4211        let dir = tempfile::tempdir().unwrap();
4212        let home = dir.path();
4213        let runs = home.join("runs");
4214        for n in 1..=2 {
4215            write_meta(
4216                &runs,
4217                &format!("20260801-000000-e{n:03}"),
4218                "blocked",
4219                "2026-08-01T00:00:00Z",
4220            );
4221        }
4222        // A directory where the cursor file belongs cannot be replaced.
4223        std::fs::create_dir(home.join(FOLD_TURN_CURSOR_FILE)).unwrap();
4224        let bounds = FoldBounds {
4225            inspect: 1,
4226            ..NO_BOUNDS
4227        };
4228        let turn = fold_turn(
4229            &runs,
4230            home,
4231            &Disk::default(),
4232            ts("2026-09-05T00:00:00Z"),
4233            bounds,
4234        )
4235        .await;
4236        assert!(turn.cursor_error.is_some(), "{turn:?}");
4237    }
4238
4239    /// Runs created while a cycle is under way wait for the next one, so a
4240    /// history that keeps growing cannot keep an earlier run from being
4241    /// revisited after it leaves its grace period. With a cursor that only
4242    /// wrapped at the current end of the history, two arrivals per pass against
4243    /// two judgements per pass never reached the end and the run was never folded.
4244    #[tokio::test]
4245    async fn continuous_arrivals_cannot_postpone_a_run_that_leaves_its_grace() {
4246        let dir = tempfile::tempdir().unwrap();
4247        let home = dir.path();
4248        let runs = home.join("runs");
4249        let wt = home.join("wt");
4250        let repo = home.join("repo");
4251        std::fs::create_dir_all(&repo).unwrap();
4252        init_repo(&repo);
4253        let disk = Disk {
4254            fold_grace_secs: 600,
4255            ..Disk::default()
4256        };
4257        let bounds = FoldBounds {
4258            inspect: 2,
4259            ..NO_BOUNDS
4260        };
4261        // The run's record says 2026-08-01T00:00:00Z: inside its grace at the
4262        // first pass, long past it afterwards.
4263        let (_, worktree) = due_run_with_winner_worktree(
4264            &runs,
4265            &wt,
4266            &repo,
4267            "20260801-000000-g001",
4268            RunStatus::Superseded,
4269        )
4270        .await;
4271        for n in 2..=4 {
4272            write_meta(
4273                &runs,
4274                &format!("20260801-000000-g{n:03}"),
4275                "blocked",
4276                "2026-08-01T00:00:00Z",
4277            );
4278        }
4279        // Run ids have a four-character tag, which the turn's inventory requires.
4280        let arrive = |pass: u32| {
4281            for k in 0..2 {
4282                write_meta(
4283                    &runs,
4284                    &format!("20260802-000000-n{pass:02}{k}"),
4285                    "blocked",
4286                    "2026-08-02T00:00:00Z",
4287                );
4288            }
4289        };
4290        let early = ts("2026-08-01T00:05:00Z");
4291        let late = ts("2026-09-05T00:00:00Z");
4292
4293        // N = 4 records at the start: ceil(4 / 2) = 2 passes for the cycle,
4294        // and the run is folded by the first pass of the next one.
4295        let first = fold_turn(&runs, home, &disk, early, bounds).await;
4296        assert_eq!(first.within_grace, 1, "{first:?}");
4297        assert_eq!(first.stopped, FoldStop::InspectLimit);
4298        arrive(1);
4299        let second = fold_turn(&runs, home, &disk, late, bounds).await;
4300        assert_eq!(second.high_water, first.high_water, "same cycle");
4301        assert_eq!(second.stopped, FoldStop::EndOfCycle, "{second:?}");
4302        assert!(worktree.exists(), "judged inside its grace in this cycle");
4303        arrive(2);
4304        let third = fold_turn(&runs, home, &disk, late, bounds).await;
4305        assert_ne!(third.high_water, first.high_water, "a new cycle");
4306        assert_eq!(third.folded, 1, "{third:?}");
4307        assert!(!worktree.exists());
4308    }
4309
4310    /// A contended fold is still a fold invocation: it takes the run's locks and
4311    /// reads its record, so the bound counts it. Charging only the folds that
4312    /// removed something let 64 contended runs start 64 folds.
4313    #[tokio::test]
4314    async fn contended_folds_are_charged_to_the_fold_budget() {
4315        let dir = tempfile::tempdir().unwrap();
4316        let home = dir.path();
4317        let runs = home.join("runs");
4318        let wt = home.join("wt");
4319        let repo = home.join("repo");
4320        std::fs::create_dir_all(&repo).unwrap();
4321        init_repo(&repo);
4322        let now = well_after_every_fold();
4323        let mut borrowers = Vec::new();
4324        let mut worktrees = Vec::new();
4325        for n in 1..=6 {
4326            let id = format!("20260801-000000-h{n:03}");
4327            let (_, worktree) =
4328                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
4329            borrowers.push(crate::retention::OutputLease::take(&worktree, false).unwrap());
4330            worktrees.push(worktree);
4331        }
4332        let bounds = FoldBounds {
4333            fold: 2,
4334            ..NO_BOUNDS
4335        };
4336        let turn = pass_from(&runs, home, &Disk::default(), now, Saved::Absent, bounds).await;
4337        assert_eq!(
4338            (turn.invoked, turn.live, turn.inspected, turn.stopped),
4339            (2, 2, 2, FoldStop::FoldLimit),
4340            "{turn:?}"
4341        );
4342        assert!(worktrees.iter().all(|w| w.exists()));
4343        drop(borrowers);
4344    }
4345
4346    /// The fold acts on the record as it is once the run's locks are held. A
4347    /// handover (`handover::release`) that lands between the first read and the
4348    /// locks records `released_to` / `released_branches` and removes the old
4349    /// worktree, keeping the branch; acting on the earlier read deleted that
4350    /// branch and saved the earlier record over the handover.
4351    #[tokio::test]
4352    async fn a_handover_between_the_read_and_the_locks_is_neither_undone_nor_overwritten() {
4353        let dir = tempfile::tempdir().unwrap();
4354        let home = dir.path();
4355        let runs = home.join("runs");
4356        let wt = home.join("wt");
4357        let repo = home.join("repo");
4358        std::fs::create_dir_all(&repo).unwrap();
4359        init_repo(&repo);
4360        let id = "20260801-000000-k001";
4361        let (_, worktree) =
4362            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
4363        let branch = format!("magi/{id}/A");
4364        AFTER_FIRST_READ.with(|hook| {
4365            let (repo, worktree, branch) = (repo.clone(), worktree.clone(), branch.clone());
4366            *hook.borrow_mut() = Some(Box::new(move |home: &Path, id: &str| {
4367                use crate::proc::Quiet as _;
4368                let mut fresh = RunState::load_under(id, home).unwrap();
4369                fresh.candidates[0].folded = true;
4370                fresh.released_to = Some("20260901-000000-succ".to_owned());
4371                fresh.released_branches.push(branch);
4372                let aged = fresh.updated_at;
4373                fresh.save_under_at(home, aged).unwrap();
4374                let removed = std::process::Command::new("git")
4375                    .args(["worktree", "remove"])
4376                    .arg(&worktree)
4377                    .current_dir(&repo)
4378                    .quiet()
4379                    .output()
4380                    .unwrap();
4381                assert!(removed.status.success());
4382            }));
4383        });
4384
4385        let turn = pass_from(
4386            &runs,
4387            home,
4388            &Disk::default(),
4389            well_after_every_fold(),
4390            Saved::Absent,
4391            NO_BOUNDS,
4392        )
4393        .await;
4394        assert_eq!(
4395            (turn.invoked, turn.folded, turn.nothing_left),
4396            (1, 0, 1),
4397            "the run was handed over, not folded: {turn:?}"
4398        );
4399        assert!(
4400            crate::git::branch_exists(&repo, &branch).await.unwrap(),
4401            "the handed-over branch survives"
4402        );
4403        let saved = run_json(home, id);
4404        assert_eq!(saved.released_to.as_deref(), Some("20260901-000000-succ"));
4405        assert_eq!(saved.released_branches, [branch]);
4406        assert!(saved.candidates[0].folded);
4407    }
4408
4409    /// Eligibility is judged again on the fresh record: a run that became
4410    /// resumable between the read and the locks is left exactly as it is.
4411    #[tokio::test]
4412    async fn a_run_that_became_resumable_after_the_read_is_left_alone() {
4413        let dir = tempfile::tempdir().unwrap();
4414        let home = dir.path();
4415        let runs = home.join("runs");
4416        let wt = home.join("wt");
4417        let repo = home.join("repo");
4418        std::fs::create_dir_all(&repo).unwrap();
4419        init_repo(&repo);
4420        let id = "20260801-000000-k002";
4421        let (_, worktree) =
4422            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
4423        AFTER_FIRST_READ.with(|hook| {
4424            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
4425                let mut fresh = RunState::load_under(id, home).unwrap();
4426                fresh.status = RunStatus::Blocked;
4427                let aged = fresh.updated_at;
4428                fresh.save_under_at(home, aged).unwrap();
4429            }));
4430        });
4431
4432        let turn = pass_from(
4433            &runs,
4434            home,
4435            &Disk::default(),
4436            well_after_every_fold(),
4437            Saved::Absent,
4438            NO_BOUNDS,
4439        )
4440        .await;
4441        assert_eq!(
4442            (turn.invoked, turn.resumable, turn.folded),
4443            (1, 1, 0),
4444            "{turn:?}"
4445        );
4446        assert!(worktree.exists());
4447        assert_eq!(run_json(home, id).status, RunStatus::Blocked);
4448    }
4449
4450    /// A confirmed merge is folded on the turn, and its evidence stays.
4451    #[tokio::test]
4452    async fn a_confirmed_merged_run_is_folded_and_keeps_its_evidence() {
4453        let dir = tempfile::tempdir().unwrap();
4454        let home = dir.path();
4455        let wt = home.join("wt");
4456        let repo = home.join("repo");
4457        std::fs::create_dir_all(&repo).unwrap();
4458        init_repo(&repo);
4459        let (id, worktree) =
4460            merged_run_with_worktree(home, &repo, &wt, "20260801-000000-m001").await;
4461        let turn = pass_from(
4462            &home.join("runs"),
4463            home,
4464            &Disk::default(),
4465            well_after_every_fold(),
4466            Saved::Absent,
4467            NO_BOUNDS,
4468        )
4469        .await;
4470        assert_eq!(
4471            (turn.folded, turn.proof_incomplete, turn.failed),
4472            (1, 0, 0),
4473            "{turn:?}"
4474        );
4475        assert!(!worktree.exists());
4476        assert!(
4477            !crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
4478                .await
4479                .unwrap()
4480        );
4481        let evidence = home.join("runs").join(&id).join("artifacts/fold-evidence");
4482        assert!(evidence.join("manifest.json").is_file());
4483        assert!(home.join("runs").join(&id).join("run.json").is_file());
4484    }
4485
4486    /// A directory in `runs/` that is not a run but holds a `run.json` must not
4487    /// become the cycle's high-water mark: the turn refuses to continue from an
4488    /// id that is not a run id, restarts from the oldest run on every pass and
4489    /// never reaches the tail past the inspection bound.
4490    #[tokio::test]
4491    async fn a_stray_directory_with_a_record_does_not_starve_the_runs_after_the_bound() {
4492        let dir = tempfile::tempdir().unwrap();
4493        let home = dir.path();
4494        let runs = home.join("runs");
4495        let wt = home.join("wt");
4496        let repo = home.join("repo");
4497        std::fs::create_dir_all(&repo).unwrap();
4498        init_repo(&repo);
4499        let mut worktrees = Vec::new();
4500        for n in 1..=5 {
4501            let id = format!("20260801-000000-s{n:03}");
4502            let (_, worktree) =
4503                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
4504            worktrees.push(worktree);
4505        }
4506        // Sorts after every run id.
4507        std::fs::create_dir_all(runs.join("backup")).unwrap();
4508        std::fs::copy(
4509            runs.join("20260801-000000-s001").join("run.json"),
4510            runs.join("backup").join("run.json"),
4511        )
4512        .unwrap();
4513        let bounds = FoldBounds {
4514            inspect: 2,
4515            ..NO_BOUNDS
4516        };
4517        let now = well_after_every_fold();
4518        let mut inspected = Vec::new();
4519        for _ in 0..3 {
4520            let turn = fold_turn(&runs, home, &Disk::default(), now, bounds).await;
4521            assert_eq!(turn.cycle_restart, None, "{turn:?}");
4522            assert_eq!(
4523                turn.records, 5,
4524                "the stray directory is not a record: {turn:?}"
4525            );
4526            inspected.push(turn.inspected);
4527        }
4528        assert_eq!(inspected, [2, 2, 1]);
4529        assert!(
4530            worktrees.iter().all(|w| !w.exists()),
4531            "the tail was reached"
4532        );
4533        assert!(runs.join("backup").join("run.json").is_file());
4534    }
4535
4536    fn start_of(home: &Path, id: &str, complete: bool, failure: Option<&str>) {
4537        let mut successor = RunState::load_under(id, home).unwrap();
4538        successor.startup = Some(crate::run::Startup {
4539            kind: "review".to_owned(),
4540            branch: None,
4541            stage: "open-review".to_owned(),
4542            complete,
4543            failure: failure.map(str::to_owned),
4544        });
4545        let aged = successor.updated_at;
4546        successor.save_under_at(home, aged).unwrap();
4547    }
4548
4549    fn hand_over_to(home: &Path, id: &str, successor: &str) {
4550        let mut predecessor = RunState::load_under(id, home).unwrap();
4551        predecessor.released_to = Some(successor.to_owned());
4552        let aged = predecessor.updated_at;
4553        predecessor.save_under_at(home, aged).unwrap();
4554    }
4555
4556    /// `handover::Released::restore` needs the predecessor's owner lock, and an
4557    /// automatic fold that holds it for a moment makes the rollback abandon. A
4558    /// predecessor whose successor is still starting (or cannot be read) is
4559    /// left alone; one whose successor has settled - startup failed, or
4560    /// completed and nothing drives it - is folded as before.
4561    #[tokio::test]
4562    async fn a_handover_in_flight_protects_its_predecessor_until_the_successor_settles() {
4563        let dir = tempfile::tempdir().unwrap();
4564        let home = dir.path();
4565        let runs = home.join("runs");
4566        let wt = home.join("wt");
4567        let repo = home.join("repo");
4568        std::fs::create_dir_all(&repo).unwrap();
4569        init_repo(&repo);
4570        let mut folded = Vec::new();
4571        for (n, case) in ["starting", "failed", "complete", "unreadable", "gone"]
4572            .into_iter()
4573            .enumerate()
4574        {
4575            let id = format!("20260801-000000-p{n:03}");
4576            let next = format!("20260901-000000-n{n:03}");
4577            let (_, worktree) =
4578                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
4579            if case != "gone" {
4580                due_run(&runs, &wt, &next, SCHEMA);
4581            }
4582            match case {
4583                "starting" => start_of(home, &next, false, None),
4584                "failed" => start_of(home, &next, false, Some("setup failed")),
4585                "complete" => start_of(home, &next, true, None),
4586                "unreadable" => {
4587                    std::fs::write(runs.join(&next).join("run.json"), "not json").unwrap()
4588                }
4589                _ => {}
4590            }
4591            hand_over_to(home, &id, &next);
4592            folded.push((case, id, worktree));
4593        }
4594        let turn = pass_from(
4595            &runs,
4596            home,
4597            &Disk::default(),
4598            well_after_every_fold(),
4599            Saved::Absent,
4600            NO_BOUNDS,
4601        )
4602        .await;
4603        for (case, id, worktree) in &folded {
4604            let protected = matches!(*case, "starting" | "unreadable");
4605            assert_eq!(
4606                worktree.exists(),
4607                protected,
4608                "{case}: protected={protected} {turn:?}"
4609            );
4610            assert_eq!(
4611                run_json(home, id)
4612                    .released_to
4613                    .as_deref()
4614                    .map(|s| s.starts_with("20260901")),
4615                Some(true),
4616                "{case}: the record still says where the run went"
4617            );
4618        }
4619        assert!(turn.live >= 2, "{turn:?}");
4620    }
4621
4622    /// The janitor's own fold after it recorded an external merge is an
4623    /// automatic caller: it reads the record under the run's locks tolerantly
4624    /// (the explicit loader refuses a schema it cannot migrate, which left the
4625    /// run unfolded until a later pass and another grace period), and the
4626    /// conditions that made it a confirmed merge are re-checked on that record.
4627    #[tokio::test]
4628    async fn a_recorded_external_merge_is_folded_on_the_locked_record_whatever_its_schema() {
4629        let dir = tempfile::tempdir().unwrap();
4630        let home = dir.path();
4631        let wt = home.join("wt");
4632        let repo = home.join("repo");
4633        std::fs::create_dir_all(&repo).unwrap();
4634        init_repo(&repo);
4635        let (id, worktree) =
4636            merged_run_with_worktree(home, &repo, &wt, "20260801-000000-x001").await;
4637        let record = home.join("runs").join(&id).join("run.json");
4638        let mut value: serde_json::Value =
4639            serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();
4640        value["schema"] = serde_json::json!(3);
4641        std::fs::write(&record, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
4642        assert!(
4643            RunState::load_under(&id, home).is_err(),
4644            "the migrating loader refuses this record"
4645        );
4646        let mut state = read_state(&home.join("runs"), &id).unwrap();
4647        let removed = fold_recorded_merge(&mut state, home, Timestamp::now())
4648            .await
4649            .unwrap();
4650        assert!(!removed.is_empty() && !worktree.exists(), "{removed:?}");
4651
4652        // Not a confirmed merge any more: refused, nothing removed.
4653        let (other, kept) = due_run_with_winner_worktree(
4654            &home.join("runs"),
4655            &wt,
4656            &repo,
4657            "20260801-000000-x002",
4658            RunStatus::Superseded,
4659        )
4660        .await;
4661        let mut state = read_state(&home.join("runs"), &other).unwrap();
4662        let error = fold_recorded_merge(&mut state, home, Timestamp::now())
4663            .await
4664            .unwrap_err();
4665        assert!(
4666            matches!(
4667                error.downcast_ref::<crate::graph::FoldRefusal>(),
4668                Some(crate::graph::FoldRefusal::ProofIncomplete(_))
4669            ),
4670            "{error:#}"
4671        );
4672        assert!(kept.exists());
4673    }
4674
4675    /// The scenario of issue 1275: a queue that always has something runnable
4676    /// and a busy worker. Housekeeping is never admitted there, so before this
4677    /// turn nothing called `fold_due`: the assertion that the old run's
4678    /// worktree is gone after one fold service pass is what failed on
4679    /// `origin/main`.
4680    #[tokio::test]
4681    async fn the_fold_service_folds_an_old_run_beside_runnable_and_running_work() {
4682        let dir = tempfile::tempdir().unwrap();
4683        let home = dir.path();
4684        let runs = home.join("runs");
4685        let wt = home.join("wt");
4686        let repo = home.join("repo");
4687        std::fs::create_dir_all(&repo).unwrap();
4688        init_repo(&repo);
4689        let queue = crate::queue::Queue::at(home.join("queue"));
4690        let mut running = crate::queue::Task::new(
4691            "busy".into(),
4692            "busy".into(),
4693            repo.clone(),
4694            crate::queue::Source::Human,
4695        );
4696        running.status = crate::queue::TaskStatus::Running;
4697        queue.put(&mut running).unwrap();
4698        let mut waiting = crate::queue::Task::new(
4699            "next".into(),
4700            "next".into(),
4701            repo.clone(),
4702            crate::queue::Source::Human,
4703        );
4704        queue.put(&mut waiting).unwrap();
4705        let (id, worktree) = due_run_with_winner_worktree(
4706            &runs,
4707            &wt,
4708            &repo,
4709            "20260801-000000-f001",
4710            RunStatus::Superseded,
4711        )
4712        .await;
4713        let config = home.join("magi.toml");
4714        let write_config = |auto_fold: bool| {
4715            std::fs::write(
4716                &config,
4717                format!(
4718                    "[disk]\nmin_free_bytes = 0\ncache_limit_bytes = 0\nauto_fold = {auto_fold}\n"
4719                ),
4720            )
4721            .unwrap();
4722        };
4723        let payload = serde_json::json!({
4724            "opts": crate::daemon::Opts {
4725                repo: home.join("not-a-checkout"),
4726                config: Some(config.clone()),
4727                ..crate::daemon::Opts::default()
4728            },
4729            "queue": queue.root(),
4730            "worktrees_root": wt,
4731            "operation": "fold",
4732        });
4733        let receipt = || -> serde_json::Value {
4734            serde_json::from_slice(
4735                &std::fs::read(home.join("source-eviction-fold-worker.json")).unwrap(),
4736            )
4737            .unwrap()
4738        };
4739
4740        write_config(false);
4741        crate::daemon::run_service_worker(home, payload.clone())
4742            .await
4743            .unwrap();
4744        assert!(worktree.exists(), "auto_fold = false folds nothing");
4745        assert_eq!(receipt()["outcome"], "skipped");
4746        assert_eq!(receipt()["detail"], "auto_fold disabled");
4747
4748        write_config(true);
4749        crate::daemon::run_service_worker(home, payload)
4750            .await
4751            .unwrap();
4752        assert!(!worktree.exists(), "one pass folded the old finished run");
4753        assert!(runs.join(&id).join("run.json").exists());
4754        let receipt = receipt();
4755        assert_eq!(receipt["outcome"], "completed");
4756        assert_eq!(receipt["operation"], "fold");
4757        let fold = &receipt["fold"];
4758        assert_eq!(fold["records"], 1);
4759        assert_eq!(fold["inspected"], 1);
4760        assert_eq!(fold["invoked"], 1);
4761        assert_eq!(fold["folded"], 1);
4762        for zero in [
4763            "nothing_left",
4764            "already_folded",
4765            "live",
4766            "resumable",
4767            "within_grace",
4768            "recovery_retained",
4769            "proof_incomplete",
4770            "unreadable",
4771            "record_gone",
4772            "failed",
4773        ] {
4774            assert_eq!(fold[zero], 0, "{zero}");
4775        }
4776        assert_eq!(fold["stopped"], "end_of_cycle");
4777        assert_eq!(fold["high_water"], id);
4778        assert!(fold["cursor"].is_null());
4779        assert!(fold["cursor_error"].is_null());
4780        assert!(fold["cycle_restart"].is_null());
4781        assert!(fold["elapsed_ms"].is_u64());
4782        assert_eq!(fold["notes"], serde_json::json!([]));
4783    }
4784
4785    /// One pass, no bounds, from the home's own cycle file's absence.
4786    async fn one_pass(home: &Path, now: Timestamp) -> FoldTurn {
4787        pass_from(
4788            &home.join("runs"),
4789            home,
4790            &Disk::default(),
4791            now,
4792            Saved::Absent,
4793            NO_BOUNDS,
4794        )
4795        .await
4796    }
4797
4798    /// A due `Superseded` run with a winner worktree under `home`, plus its repo.
4799    async fn due_superseded(home: &Path, id: &str) -> (PathBuf, PathBuf) {
4800        let repo = home.join("repo");
4801        if !repo.exists() {
4802            std::fs::create_dir_all(&repo).unwrap();
4803            init_repo(&repo);
4804        }
4805        let (_, worktree) = due_run_with_winner_worktree(
4806            &home.join("runs"),
4807            &home.join("wt"),
4808            &repo,
4809            id,
4810            RunStatus::Superseded,
4811        )
4812        .await;
4813        (repo, worktree)
4814    }
4815
4816    /// What a fold itself found is what lets the turn skip a run: nothing left
4817    /// and no bay, recorded under its locks, and the bay confirmed absent now.
4818    #[tokio::test]
4819    async fn a_fold_that_finds_nothing_marks_the_run_and_the_turn_then_skips_it() {
4820        let dir = tempfile::tempdir().unwrap();
4821        let home = dir.path();
4822        let id = "20260801-000000-z001";
4823        let (_, worktree) = due_superseded(home, id).await;
4824        let now = well_after_every_fold();
4825
4826        let first = one_pass(home, now).await;
4827        assert_eq!((first.folded, first.invoked), (1, 1), "{first:?}");
4828        assert!(!worktree.exists());
4829        assert!(
4830            run_json(home, id).fold_settled_at.is_none(),
4831            "a fold that removed something has not yet seen the bay empty"
4832        );
4833
4834        let second = one_pass(home, now).await;
4835        assert_eq!((second.nothing_left, second.invoked), (1, 1), "{second:?}");
4836        assert!(run_json(home, id).fold_settled_at.is_some());
4837
4838        let record = home.join("runs").join(id).join("run.json");
4839        let before = std::fs::read(&record).unwrap();
4840        let third = one_pass(home, now).await;
4841        assert_eq!(
4842            (third.already_folded, third.invoked, third.nothing_left),
4843            (1, 0, 0),
4844            "{third:?}"
4845        );
4846        assert_eq!(std::fs::read(&record).unwrap(), before, "no fold, no save");
4847    }
4848
4849    /// An existing bay - even an empty one - is not "gone": the fold is invoked,
4850    /// removes it and records what it saw.
4851    #[tokio::test]
4852    async fn an_empty_bay_is_work_and_a_marked_run_with_work_is_folded() {
4853        let dir = tempfile::tempdir().unwrap();
4854        let home = dir.path();
4855        let id = "20260801-000000-z002";
4856        let (_, worktree) = due_superseded(home, id).await;
4857        let now = well_after_every_fold();
4858        one_pass(home, now).await;
4859        one_pass(home, now).await;
4860        let bay = run_json(home, id).worktree_root();
4861        assert!(run_json(home, id).fold_settled_at.is_some());
4862        assert!(!bay.exists());
4863
4864        std::fs::create_dir_all(&bay).unwrap();
4865        let pass = one_pass(home, now).await;
4866        assert_eq!((pass.invoked, pass.already_folded), (1, 0), "{pass:?}");
4867        assert!(!bay.exists(), "the fold removed the empty bay");
4868        assert!(run_json(home, id).fold_settled_at.is_some());
4869
4870        // Work behind a mark: a bay that holds a worktree again. The fold that
4871        // removes it clears the mark in the same save.
4872        std::fs::create_dir_all(worktree.parent().unwrap()).unwrap();
4873        crate::git::worktree_add_branch(&home.join("repo"), &worktree, "magi/z002-again", "main")
4874            .await
4875            .unwrap();
4876        let pass = one_pass(home, now).await;
4877        assert_eq!((pass.invoked, pass.already_folded), (1, 0), "{pass:?}");
4878        assert!(!worktree.exists());
4879        assert!(
4880            run_json(home, id).fold_settled_at.is_none(),
4881            "a fold that found work clears the mark"
4882        );
4883    }
4884
4885    #[test]
4886    fn settled_needs_the_mark_and_a_bay_confirmed_absent() {
4887        let mut state = RunState::new(
4888            PathBuf::from("/repo"),
4889            "main".to_owned(),
4890            "abc".to_owned(),
4891            "fixture".to_owned(),
4892            crate::config::Config::default(),
4893        );
4894        assert!(!settled(&state, true, Ok(false)), "no mark: unknown");
4895        state.fold_settled_at = Some(Timestamp::now());
4896        assert!(settled(&state, true, Ok(false)));
4897        assert!(!settled(&state, true, Ok(true)), "a bay on disk is work");
4898        let failed = Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
4899        assert!(!settled(&state, true, failed), "an unanswered check is not");
4900        state.enabled_worktree_config = true;
4901        assert!(
4902            !settled(&state, true, Ok(false)),
4903            "a pending worktree-config release is work"
4904        );
4905        assert!(settled(&state, false, Ok(false)));
4906    }
4907
4908    /// A run deleted between the first read and the fold's locks is refused and
4909    /// nothing of it is brought back: no record, no directory, no lock files.
4910    #[tokio::test]
4911    async fn a_run_deleted_after_the_first_read_is_refused_and_not_recreated() {
4912        let dir = tempfile::tempdir().unwrap();
4913        let home = dir.path();
4914        let id = "20260801-000000-z003";
4915        let (repo, worktree) = due_superseded(home, id).await;
4916        AFTER_FIRST_READ.with(|hook| {
4917            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
4918                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
4919            }));
4920        });
4921
4922        let turn = one_pass(home, well_after_every_fold()).await;
4923        assert_eq!(
4924            (turn.invoked, turn.record_gone, turn.folded, turn.failed),
4925            (1, 1, 0, 0),
4926            "{turn:?}"
4927        );
4928        assert!(
4929            !home.join("runs").join(id).exists(),
4930            "the fold recreated what was deleted"
4931        );
4932        assert!(worktree.exists(), "nothing of a deleted run is folded");
4933        assert!(
4934            crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
4935                .await
4936                .unwrap()
4937        );
4938    }
4939
4940    /// A record readable at the first look and not under the locks is
4941    /// `unreadable` - the idle pass counts it like any unreadable record - and
4942    /// is left exactly as found.
4943    #[tokio::test]
4944    async fn a_record_that_became_unreadable_under_the_locks_is_unreadable() {
4945        let dir = tempfile::tempdir().unwrap();
4946        let home = dir.path();
4947        let id = "20260801-000000-z004";
4948        let (_, worktree) = due_superseded(home, id).await;
4949        AFTER_FIRST_READ.with(|hook| {
4950            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
4951                std::fs::write(home.join("runs").join(id).join("run.json"), "{ not json").unwrap();
4952            }));
4953        });
4954        let (folded, unreadable) = fold_due(
4955            &home.join("runs"),
4956            home,
4957            &home.join("wt"),
4958            &Disk::default(),
4959            well_after_every_fold(),
4960        )
4961        .await
4962        .unwrap();
4963        assert_eq!((folded, unreadable), (0, 1));
4964        assert!(worktree.exists());
4965        assert_eq!(
4966            std::fs::read(home.join("runs").join(id).join("run.json")).unwrap(),
4967            b"{ not json"
4968        );
4969    }
4970
4971    /// Explicit callers keep the migrating loader: a schema-14 record whose
4972    /// unfolded candidate is empty and unverified gets its legacy preservation
4973    /// marker from the migration, and the explicit fold refuses on that fresh
4974    /// record. The tolerant read housekeeping uses never derives the marker.
4975    #[tokio::test]
4976    async fn an_explicit_fold_applies_the_migration_its_preservation_check_rests_on() {
4977        let dir = tempfile::tempdir().unwrap();
4978        let home = dir.path();
4979        let id = "20260801-000000-z005";
4980        let (_, worktree) = due_superseded(home, id).await;
4981        edit_run(&home.join("runs"), id, |v| {
4982            v["schema"] = 14.into();
4983            v["candidates"][0]["empty"] = true.into();
4984        });
4985        let record = home.join("runs").join(id).join("run.json");
4986        let before = std::fs::read(&record).unwrap();
4987
4988        let mut first_look = read_state(&home.join("runs"), id).unwrap();
4989        assert!(first_look.candidate_preservation.is_empty());
4990        let error = crate::graph::fold_run(&mut first_look, true, home)
4991            .await
4992            .unwrap_err();
4993        assert!(
4994            matches!(
4995                error.downcast_ref::<crate::graph::FoldRefusal>(),
4996                Some(crate::graph::FoldRefusal::ProofIncomplete(_))
4997            ),
4998            "{error:#}"
4999        );
5000        assert!(worktree.exists());
5001        assert_eq!(std::fs::read(&record).unwrap(), before, "nothing was saved");
5002
5003        let turn = one_pass(home, well_after_every_fold()).await;
5004        assert_eq!(
5005            turn.folded, 1,
5006            "housekeeping reads the record as saved: {turn:?}"
5007        );
5008        assert!(!worktree.exists());
5009    }
5010
5011    /// Only contention is "somebody holds it"; any other failure of a lock call
5012    /// is a real failure.
5013    #[test]
5014    fn only_lock_contention_means_a_live_owner() {
5015        use crate::graph::held_by_live_owner;
5016        let io = |kind| anyhow::Error::from(std::io::Error::from(kind));
5017        assert!(held_by_live_owner(&io(std::io::ErrorKind::WouldBlock)));
5018        assert!(held_by_live_owner(
5019            &io(std::io::ErrorKind::WouldBlock).context("run execution lease unavailable")
5020        ));
5021        assert!(!held_by_live_owner(&io(std::io::ErrorKind::Interrupted)));
5022        assert!(!held_by_live_owner(
5023            &anyhow::Error::msg("ENOLCK").context("output lease: lock")
5024        ));
5025        assert!(!held_by_live_owner(&io(
5026            std::io::ErrorKind::PermissionDenied
5027        )));
5028        let held = tempfile::tempdir().unwrap();
5029        std::fs::create_dir_all(held.path().join("wt")).unwrap();
5030        let lock = held.path().join("magi-output.lock");
5031        let _first = crate::retention::OutputLease::lock(&lock, true).unwrap();
5032        let error = crate::retention::OutputLease::lock(&lock, true)
5033            .err()
5034            .unwrap();
5035        assert!(held_by_live_owner(&error), "{error:#}");
5036    }
5037
5038    /// Deleting a run record takes the fold's locks: a held lock is a refusal,
5039    /// never a record vanishing under a fold.
5040    #[tokio::test]
5041    async fn deleting_a_run_is_refused_while_a_fold_holds_it_and_leaves_no_trace_when_gone() {
5042        let dir = tempfile::tempdir().unwrap();
5043        let home = dir.path();
5044        let now = Timestamp::now();
5045        let refused = |result: Result<()>| -> String {
5046            let error = result.unwrap_err();
5047            error
5048                .downcast_ref::<DeleteRefused>()
5049                .unwrap_or_else(|| panic!("not a refusal: {error:#}"))
5050                .0
5051                .clone()
5052        };
5053        let id = "20260801-000000-z006";
5054        let mut state = RunState::new(
5055            PathBuf::from("/repo"),
5056            "main".to_owned(),
5057            "abc".to_owned(),
5058            "fixture".to_owned(),
5059            crate::config::Config::default(),
5060        );
5061        state.id = id.to_owned();
5062        state.status = RunStatus::Failed;
5063        state.save_under(home).unwrap();
5064        let run_dir = home.join("runs").join(id);
5065
5066        {
5067            let _owner = crate::pr_head::owner_lock(home, id).unwrap();
5068            assert!(refused(delete_run(home, id, now)).contains("try again later"));
5069        }
5070        {
5071            let _lease = crate::driver::maintenance(home, id).unwrap();
5072            assert!(refused(delete_run(home, id, now)).contains("try again later"));
5073        }
5074        assert!(run_dir.join("run.json").is_file());
5075
5076        delete_run(home, id, now).unwrap();
5077        assert!(!run_dir.exists());
5078        assert_eq!(
5079            std::fs::read_dir(home.join("deleted-runs"))
5080                .map(|entries| entries.count())
5081                .unwrap_or(0),
5082            0,
5083            "the run's lock files and record go together, tombstone included"
5084        );
5085        assert!(refused(delete_run(home, id, now)).contains("record gone"));
5086        assert!(
5087            !run_dir.exists(),
5088            "refusing must not recreate the directory"
5089        );
5090
5091        // The guard on unfolded candidates is judged on the record read under the locks.
5092        let unfolded = "20260801-000000-z007";
5093        let (_, worktree) = due_superseded(home, unfolded).await;
5094        assert!(refused(delete_run(home, unfolded, now)).contains("magi fold"));
5095        assert!(worktree.exists());
5096        assert!(home.join("runs").join(unfolded).join("run.json").is_file());
5097    }
5098
5099    /// The wholesale removal of an unreadable run takes the same two locks.
5100    #[tokio::test]
5101    async fn an_unreadable_run_is_not_removed_while_a_fold_holds_it() {
5102        let dir = tempfile::tempdir().unwrap();
5103        let home = dir.path();
5104        let runs = home.join("runs");
5105        let wt = home.join("wt");
5106        let id = "20260801-000000-z008";
5107        write_meta(&runs, id, "failed", "2026-08-01T00:00:00Z");
5108        {
5109            let _lease = crate::driver::maintenance(home, id).unwrap();
5110            let error = fold_unreadable(&runs, &wt, id).await.unwrap_err();
5111            assert!(error.is::<DeleteRefused>(), "{error:#}");
5112            assert!(runs.join(id).join("run.json").is_file());
5113        }
5114        let removed = fold_unreadable(&runs, &wt, id).await.unwrap();
5115        assert_eq!(removed, [format!("runs/{id}")]);
5116        assert!(!runs.join(id).exists());
5117    }
5118
5119    /// What a deletion killed between the rename and the removal leaves behind.
5120    fn leftover_tombstone(home: &Path, name: &str) -> PathBuf {
5121        let leftover = home.join("deleted-runs").join(name);
5122        std::fs::create_dir_all(leftover.join("artifacts")).unwrap();
5123        std::fs::write(leftover.join("run.json"), "{}").unwrap();
5124        std::fs::write(leftover.join("artifacts/review.json"), "findings").unwrap();
5125        leftover
5126    }
5127
5128    /// A tombstone is removed by the next run deletion, by the wholesale removal
5129    /// of an unreadable run (which now leaves through the tombstone too) and by
5130    /// idle housekeeping: it was authorised for deletion when it was moved and
5131    /// nothing else reads the directory.
5132    #[tokio::test]
5133    async fn a_leftover_tombstone_is_removed_by_the_next_deletion_and_by_housekeeping() {
5134        let dir = tempfile::tempdir().unwrap();
5135        let home = dir.path();
5136        let now = Timestamp::now();
5137
5138        let first = leftover_tombstone(home, "20260701-000000-dead-1");
5139        let id = "20260801-000000-z009";
5140        let mut state = RunState::new(
5141            PathBuf::from("/repo"),
5142            "main".to_owned(),
5143            "abc".to_owned(),
5144            "fixture".to_owned(),
5145            crate::config::Config::default(),
5146        );
5147        state.id = id.to_owned();
5148        state.status = RunStatus::Failed;
5149        state.save_under(home).unwrap();
5150        delete_run(home, id, now).unwrap();
5151        assert!(!home.join("runs").join(id).exists());
5152        assert!(!first.exists(), "the next deletion removed the leftover");
5153
5154        let second = leftover_tombstone(home, "20260701-000000-dead-2");
5155        let mut cfg = crate::config::Config::default();
5156        cfg.disk.auto_fold = false;
5157        cfg.disk.cache_limit_bytes = 0;
5158        housekeep(&cfg, home, &home.join("wt"), &home.join("repo"), now).await;
5159        assert!(!second.exists(), "idle housekeeping removed the leftover");
5160        assert_eq!(sweep_graveyard(home), 0, "nothing is left to remove");
5161    }
5162
5163    /// A record that parses, names another run and has a schema the migrating
5164    /// loader refuses is an identity error, never an "unreadable" run removed
5165    /// wholesale.
5166    #[tokio::test]
5167    async fn a_foreign_record_in_a_refused_schema_is_not_removed_as_unreadable() {
5168        let dir = tempfile::tempdir().unwrap();
5169        let home = dir.path();
5170        let runs = home.join("runs");
5171        let id = "20260801-000000-z011";
5172        std::fs::create_dir_all(runs.join(id)).unwrap();
5173        let record = br#"{"schema": 99999, "id": "20260801-000000-z012"}"#.to_vec();
5174        std::fs::write(runs.join(id).join("run.json"), &record).unwrap();
5175
5176        let error = ensure_record_identity(&runs, id).unwrap_err();
5177        assert!(
5178            format!("{error:#}").contains("records run 20260801-000000-z012"),
5179            "{error:#}"
5180        );
5181        let error = fold_unreadable(&runs, &home.join("wt"), id)
5182            .await
5183            .unwrap_err();
5184        assert!(
5185            format!("{error:#}").contains("records run 20260801-000000-z012"),
5186            "{error:#}"
5187        );
5188        assert_eq!(
5189            std::fs::read(runs.join(id).join("run.json")).unwrap(),
5190            record
5191        );
5192        // A record that names this run, or none that parses, passes.
5193        std::fs::write(
5194            runs.join(id).join("run.json"),
5195            format!(r#"{{"schema": 99999, "id": "{id}"}}"#),
5196        )
5197        .unwrap();
5198        ensure_record_identity(&runs, id).unwrap();
5199        std::fs::write(runs.join(id).join("run.json"), "not json").unwrap();
5200        ensure_record_identity(&runs, id).unwrap();
5201    }
5202
5203    /// A sweep that takes the tombstone between a deletion's rename and its
5204    /// removal has finished that deletion; so has one that finds it gone.
5205    #[test]
5206    fn a_tombstone_taken_by_a_sweep_is_a_finished_deletion() {
5207        let dir = tempfile::tempdir().unwrap();
5208        let home = dir.path();
5209        let tombstone = leftover_tombstone(home, "20260801-000000-z013-1");
5210        assert_eq!(sweep_graveyard(home), 1);
5211        assert!(!tombstone.exists());
5212        remove_tombstone("20260801-000000-z013", &tombstone).unwrap();
5213        let present = leftover_tombstone(home, "20260801-000000-z013-2");
5214        remove_tombstone("20260801-000000-z013", &present).unwrap();
5215        assert!(!present.exists());
5216    }
5217
5218    /// An unreadable run's directory leaves through the same tombstone as a
5219    /// deleted run's, whose sweep is what removes the earlier leftover here.
5220    #[tokio::test]
5221    async fn an_unreadable_run_leaves_through_the_tombstone_helper() {
5222        let dir = tempfile::tempdir().unwrap();
5223        let home = dir.path();
5224        let runs = home.join("runs");
5225        let id = "20260801-000000-z010";
5226        write_meta(&runs, id, "failed", "2026-08-01T00:00:00Z");
5227        let leftover = leftover_tombstone(home, "20260701-000000-dead-3");
5228        let removed = fold_unreadable(&runs, &home.join("wt"), id).await.unwrap();
5229        assert_eq!(removed, [format!("runs/{id}")]);
5230        assert!(!runs.join(id).exists());
5231        assert!(!leftover.exists(), "it went through `remove_run_dir`");
5232        assert_eq!(
5233            std::fs::read_dir(home.join("deleted-runs"))
5234                .map(|entries| entries.count())
5235                .unwrap_or(0),
5236            0
5237        );
5238    }
5239
5240    /// `runs/<A>/run.json` holding run B's record is not run A: the automatic
5241    /// callers judge it unreadable at the first read and touch nothing, and the
5242    /// explicit entry points refuse it.
5243    #[tokio::test]
5244    async fn a_record_naming_another_run_is_unreadable_at_the_first_read() {
5245        let dir = tempfile::tempdir().unwrap();
5246        let home = dir.path();
5247        let runs = home.join("runs");
5248        let (a, b) = ("20260801-000000-m001", "20260801-000000-m002");
5249        let (_, wt_a) = due_superseded(home, a).await;
5250        let (_, wt_b) = due_superseded(home, b).await;
5251        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
5252        let record_a = std::fs::read(runs.join(a).join("run.json")).unwrap();
5253        let now = well_after_every_fold();
5254
5255        let judged = fold_one(&runs, home, &Disk::default(), now, a, false, &mut || {}).await;
5256        assert_eq!(judged.outcome, FoldOutcome::Unreadable);
5257        assert!(read_state(&runs, a).is_err());
5258        assert!(
5259            RunState::read_unmigrated(&runs.join(a).join("run.json"))
5260                .unwrap()
5261                .ensure_directory(a)
5262                .is_err()
5263        );
5264
5265        let turn = one_pass(home, now).await;
5266        assert_eq!((turn.unreadable, turn.folded), (1, 1), "{turn:?}");
5267        assert!(wt_a.exists() && !wt_b.exists(), "only run B was folded");
5268        assert_eq!(
5269            std::fs::read(runs.join(a).join("run.json")).unwrap(),
5270            record_a,
5271            "nothing was saved over the directory's record"
5272        );
5273    }
5274
5275    /// The real operations in the window that matters: a `Ready` predecessor
5276    /// is handed over by `handover::release`, then an automatic fold with no
5277    /// grace judges it - `live`, nothing read back differently - and the
5278    /// rollback after the successor's startup failed still finds the worktree,
5279    /// the branch tip and the ownership record where it left them.
5280    #[tokio::test]
5281    async fn an_automatic_fold_between_a_real_release_and_its_rollback_finds_the_run_live() {
5282        let dir = tempfile::tempdir().unwrap();
5283        let home = dir.path();
5284        let runs = home.join("runs");
5285        let wt = home.join("wt");
5286        let repo = home.join("repo");
5287        std::fs::create_dir_all(&repo).unwrap();
5288        init_repo(&repo);
5289        let (id, next) = ("20260801-000000-h001", "20260901-000000-h002");
5290        let (_, worktree) =
5291            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Ready).await;
5292        let branch = format!("magi/{id}/A");
5293        let tip = crate::git::rev_parse(&repo, &branch).await.unwrap();
5294        let mut stopped = RunState::load_under(id, home).unwrap();
5295        stopped.driver_exited = true;
5296        let aged = stopped.updated_at;
5297        stopped.save_under_at(home, aged).unwrap();
5298        due_run(&runs, &wt, next, SCHEMA);
5299        start_of(home, next, false, None);
5300
5301        let takeover = crate::handover::Takeover {
5302            earlier: vec![id.to_owned()],
5303            home: home.to_owned(),
5304            choice: None,
5305            task_instruction: None,
5306        };
5307        let released = crate::handover::release(&repo, &branch, next, &takeover)
5308            .await
5309            .unwrap()
5310            .expect("the stopped worktree is released");
5311        assert!(!worktree.exists());
5312        let record = std::fs::read(runs.join(id).join("run.json")).unwrap();
5313
5314        let disk = Disk {
5315            fold_grace_secs: 0,
5316            ..Disk::default()
5317        };
5318        let now = well_after_every_fold();
5319        let judged = fold_one(&runs, home, &disk, now, id, false, &mut || {}).await;
5320        assert_eq!(judged.outcome, FoldOutcome::Live, "{:?}", judged.note);
5321        assert_eq!(
5322            std::fs::read(runs.join(id).join("run.json")).unwrap(),
5323            record,
5324            "the fold saved nothing over the handover"
5325        );
5326
5327        start_of(home, next, false, Some("setup failed"));
5328        released.restore(&repo, &branch).await;
5329        let restored = run_json(home, id);
5330        assert!(restored.released_to.is_none() && !restored.candidates[0].folded);
5331        assert!(restored.driver_exited);
5332        assert_eq!(restored.status, RunStatus::Ready);
5333        assert!(worktree.exists(), "the worktree is back");
5334        assert_eq!(crate::git::rev_parse(&worktree, "HEAD").await.unwrap(), tip);
5335        assert_eq!(crate::git::rev_parse(&repo, &branch).await.unwrap(), tip);
5336    }
5337
5338    /// A successor whose startup completed and whose execution lease is held is
5339    /// being driven: the handover is still in flight, whatever its record says
5340    /// about the predecessor. Once the lease is gone nothing protects it.
5341    #[tokio::test]
5342    async fn a_successor_holding_its_execution_lease_protects_its_predecessor() {
5343        let dir = tempfile::tempdir().unwrap();
5344        let home = dir.path();
5345        let runs = home.join("runs");
5346        let wt = home.join("wt");
5347        let repo = home.join("repo");
5348        std::fs::create_dir_all(&repo).unwrap();
5349        init_repo(&repo);
5350        let (id, next) = ("20260801-000000-l001", "20260901-000000-l002");
5351        let (_, worktree) =
5352            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
5353        due_run(&runs, &wt, next, SCHEMA);
5354        hand_over_to(home, id, next);
5355        // Complete startup, no process identity: the held lease is the only
5356        // evidence the successor is running.
5357        let mut successor = RunState::load_under(next, home).unwrap();
5358        successor.startup = Some(crate::run::Startup {
5359            kind: "review".to_owned(),
5360            branch: None,
5361            stage: "open-review".to_owned(),
5362            complete: true,
5363            failure: None,
5364        });
5365        successor.status = RunStatus::Reviewing;
5366        successor.driver_exited = false;
5367        successor.driver_pid = None;
5368        successor.driver_started_at = None;
5369        successor.begin_pass();
5370        let aged = successor.updated_at;
5371        successor.save_under_at(home, aged).unwrap();
5372        let mut driving = crate::driver::DriverGuard::acquire(home, &successor).unwrap();
5373        driving.record(&successor).unwrap();
5374
5375        let disk = Disk {
5376            fold_grace_secs: 0,
5377            ..Disk::default()
5378        };
5379        let now = well_after_every_fold();
5380        let judged = fold_one(&runs, home, &disk, now, id, false, &mut || {}).await;
5381        assert_eq!(judged.outcome, FoldOutcome::Live, "{:?}", judged.note);
5382        assert!(worktree.exists());
5383
5384        drop(driving);
5385        let judged = fold_one(&runs, home, &disk, now, id, false, &mut || {}).await;
5386        assert_eq!(judged.outcome, FoldOutcome::Folded, "{:?}", judged.note);
5387        assert!(!worktree.exists());
5388    }
5389}