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