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