Skip to main content

magi/
clean.rs

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