magi/clean.rs
1//! The disk janitor: finished runs get their worktrees folded, worktrees whose
2//! run record is already gone get reclaimed too, and the shared build cache is
3//! pruned to its cap.
4//!
5//! A run's state being written by an older schema is not the same thing as it
6//! being unreadable, and this module used to conflate the two: [`fold_due`]
7//! treated any `run.json` its version check rejected exactly like one that
8//! failed to parse at all, so a single schema bump silently stopped every
9//! automatic fold in the fleet the moment it shipped, and did so with no
10//! counter and no log line to say so. A record magi genuinely cannot parse —
11//! missing fields, broken JSON, a schema newer than this build has ever heard
12//! of — is still left alone here, still counted in
13//! [`Housekeeping::unreadable`], and still only ever removed by an explicit
14//! operator action (`magi fold`, or the equivalent phone route). One written
15//! by a schema this build merely disagrees with the *meaning* of is not that:
16//! as long as it still parses, folding proceeds regardless of the number in
17//! its `schema` field.
18//!
19//! Everything policy-shaped — which statuses are foldable, how long a finished
20//! run is left alone, whether the cache is over its limit — is a pure function
21//! injected with numbers, so nothing here has to ask the operating system to
22//! be testable. The only I/O is the removal itself.
23
24use std::collections::BTreeSet;
25use std::path::{Path, PathBuf};
26
27use anyhow::{Context as _, Result, bail};
28use jiff::{SignedDuration, Timestamp};
29use serde::Deserialize;
30
31use crate::ask::Questions;
32use crate::config::Disk;
33use crate::run::{RunState, RunStatus, SCHEMA, short_of};
34
35use crate::disk::{Prune, dir_size};
36
37/// What one janitor pass did, for the caller's log line.
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub struct Housekeeping {
40 /// Runs folded (worktrees dropped).
41 pub folded: usize,
42 /// Runs [`fold_due`] left alone because their `run.json` genuinely could
43 /// not be read - missing, broken JSON, a schema this build has never
44 /// heard of - as opposed to one merely written by a different schema
45 /// number, which is folded like any other (see the module docs). This was
46 /// defined but never incremented for a long stretch of this module's
47 /// history, which is exactly how 90 of 93 runs sat unfolded on one
48 /// operator's machine with nothing anywhere saying why: every one of them
49 /// was misclassified as unreadable by a schema check that has since been
50 /// narrowed to only the runs that actually are.
51 pub unreadable: usize,
52 /// Worktrees under the worktree bay reclaimed because no run record in
53 /// `runs/` claims them anymore (see [`fold_orphaned_worktrees`]).
54 pub orphaned_worktrees: usize,
55 /// Files dropped from the shared cache.
56 pub cache_files: usize,
57 /// Bytes freed from the shared cache.
58 pub cache_freed: u64,
59 /// Open questions abandoned because the run that asked them has already
60 /// settled where nothing is coming back to read an answer.
61 pub questions_abandoned: usize,
62}
63
64/// Run the janitor: fold due runs, reclaim orphaned worktrees, prune stale
65/// worktree registrations, then prune the cache if it is over its cap.
66///
67/// Every part is best-effort; a jammed cache lock or a run whose worktree
68/// another borrower holds must not stop the rest. Errors are reported through
69/// `tracing::warn` - this is housekeeping, and the daemon keeps serving
70/// either way.
71pub async fn housekeep(
72 cfg: &crate::config::Config,
73 home: &Path,
74 worktrees_root: &Path,
75 repo: &Path,
76 now: Timestamp,
77) -> Housekeeping {
78 let mut out = Housekeeping::default();
79 if cfg.disk.auto_fold {
80 let runs = home.join("runs");
81 match fold_due(&runs, home, worktrees_root, &cfg.disk, now).await {
82 Ok((folded, unreadable)) => {
83 out.folded = folded;
84 out.unreadable = unreadable;
85 }
86 Err(e) => tracing::warn!("housekeep: fold due runs: {e:#}"),
87 }
88 out.orphaned_worktrees =
89 fold_orphaned_worktrees(&runs, worktrees_root, home, cfg.disk.fold_grace_secs, now)
90 .await;
91 // Best-effort in the same sense as everything else here: a repository
92 // this janitor pass has nothing to do with (or none at all, in a unit
93 // test) must not turn a `warn` into a reason to skip the rest.
94 if let Err(e) = crate::git::worktree_prune(repo).await {
95 tracing::warn!("housekeep: prune worktree registrations: {e:#}");
96 }
97 }
98 match prune_cache_if_over_limit(cfg, home) {
99 Ok(Some(pruned)) => {
100 out.cache_files = pruned.files;
101 out.cache_freed = pruned.freed;
102 }
103 Ok(None) => {}
104 Err(e) => tracing::warn!("housekeep: prune cache: {e:#}"),
105 }
106 // Unconditional, unlike the two passes above: this is not a disk policy
107 // with a cap or an opt-out, it is closing a gap `graph::Runner` itself
108 // cannot - a run that reached `Merged`/`Ready`/`Failed` before this
109 // cleanup existed, or whose process died between saving that status and
110 // abandoning the question it leaves behind (see `Runner::settle_questions`).
111 // Left alone, that question sits `open` forever: the owner's badge,
112 // banner and title all keep counting a decision nobody is left to read.
113 out.questions_abandoned =
114 abandon_settled_questions(&Questions::at(home.join("questions")), &home.join("runs"));
115 out
116}
117
118/// Abandon every open question whose run has already settled into a status
119/// nothing comes back from, worded with what the run became - the same
120/// cleanup `graph::Runner::settle_questions` runs the moment `status` lands
121/// there, for questions that missed it.
122///
123/// Scans questions rather than runs: the open list is normally short, and a
124/// run that never asked anything costs nothing here. A run this cannot read,
125/// deleted or written by a schema this build does not speak, is left alone
126/// the same as everywhere else in this module; the question stays open
127/// rather than guessed at.
128pub fn abandon_settled_questions(store: &Questions, runs: &Path) -> usize {
129 let waiting_on: BTreeSet<String> = store
130 .list()
131 .into_iter()
132 .filter(|q| q.status.open())
133 .map(|q| q.run)
134 .collect();
135 let mut abandoned = 0;
136 for run in waiting_on {
137 let Ok(meta) = read_meta(runs, &run) else {
138 continue;
139 };
140 match store.settle_run(&run, meta.status) {
141 Ok(n) => abandoned += n,
142 Err(e) => tracing::warn!("housekeep: abandon questions for {run}: {e:#}"),
143 }
144 }
145 abandoned
146}
147
148/// Fold every run that is finished, older than the grace period, and not being
149/// worked on; return `(folded, unreadable)`.
150///
151/// A run whose `run.json` genuinely cannot be parsed — missing fields, broken
152/// JSON, a schema newer than this build has ever heard of — is left exactly
153/// as it is. Automatic housekeeping cannot tell a mid-write file from one that
154/// will never parse again, and `<home>/runs/<id>/` is the evidence `magi
155/// stats` and the deck read; when unsure whether it is safe to touch, the
156/// janitor keeps rather than deletes (see the module docs). Discarding a
157/// record this unreadable is an explicit operator action (`magi fold`, or the
158/// equivalent phone route), never something that happens unattended. Every
159/// such skip is counted in the returned `unreadable` and logged through
160/// `tracing::warn` with the parse failure that caused it - silence here is
161/// exactly the failure mode that let 90 of 93 runs sit unfolded with nothing
162/// to show for it.
163///
164/// A run merely written by a *different* schema number is not unreadable: as
165/// long as `run.json` still parses, it folds like any other terminal run (see
166/// the module docs for why the two are different questions).
167///
168/// Runnable statuses and runs newer than the grace period are also left
169/// alone; folding them would throw away work that is still the answer to
170/// somebody's question. `Merged` runs forget their winner's worktree (the
171/// merge already landed it); `Ready` and `Failed` runs keep it.
172pub async fn fold_due(
173 runs: &Path,
174 home: &Path,
175 _worktrees_root: &Path,
176 disk: &Disk,
177 now: Timestamp,
178) -> Result<(usize, usize)> {
179 let mut folded = 0usize;
180 let mut unreadable = 0usize;
181 let mut ids: Vec<String> = std::fs::read_dir(runs)
182 .into_iter()
183 .flatten()
184 .flatten()
185 .filter(|e| e.path().join("run.json").is_file())
186 .map(|e| e.file_name().to_string_lossy().into_owned())
187 .collect();
188 ids.sort_unstable();
189 for id in ids {
190 if crate::daemon::is_working_on(home, &id, now) {
191 continue;
192 }
193 let meta = match read_meta(runs, &id) {
194 Ok(meta) => meta,
195 Err(e) => {
196 unreadable += 1;
197 tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
198 continue;
199 }
200 };
201 if meta.status.resumable() || !due(now, meta.updated_at, disk.fold_grace_secs) {
202 continue;
203 }
204 // `read_meta` already proved the file parses; `read_state` asks for
205 // the rest of the fields `graph::fold_run` needs (worktree paths,
206 // candidates, tally). A schema mismatch alone does not fail this -
207 // see the module docs - so reaching `Err` here means the JSON itself
208 // is broken in a way `read_meta` did not exercise, which is rare but
209 // not impossible (a body truncated between the two fields it reads
210 // and the rest). That must not cost every other run its turn through
211 // this loop, so it is a skip, not a `?`.
212 let mut state = match read_state(runs, &id) {
213 Ok(state) => state,
214 Err(e) => {
215 unreadable += 1;
216 tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
217 continue;
218 }
219 };
220 if state.schema != SCHEMA {
221 tracing::info!(
222 "housekeep: run {id} was written by schema {} (this build speaks {SCHEMA}); \
223 folding it anyway",
224 state.schema
225 );
226 }
227 let drop_winner = state.status == RunStatus::Merged;
228 // One run's fold must not cost every later run its turn. A worktree
229 // another borrower holds, a branch git refuses to delete, a repository
230 // that has since moved: each is a reason this run cannot be folded
231 // now, and none is a reason to stop the pass. Left unfolded, it is
232 // simply due again next time; a `?` here stopped automatic folding
233 // permanently at the first such run (finding R3-1-1 of run 51a3).
234 match crate::graph::fold_run(&mut state, drop_winner, home).await {
235 Ok(_) => folded += 1,
236 Err(e) => tracing::warn!("housekeep: fold {id}: {e:#}"),
237 }
238 }
239 Ok((folded, unreadable))
240}
241
242/// Is `updated` old enough, measured against `now`, that the run may fold?
243///
244/// Pure; the janitor compares against wallclock, tests inject both sides. The
245/// comparison is strict, so a run exactly at the edge of its grace period is
246/// left alone one more pass — the same convention as [`crate::disk::over_limit`].
247pub fn due(now: Timestamp, updated: Timestamp, grace_secs: u64) -> bool {
248 now.duration_since(updated) > SignedDuration::new(grace_secs as i64, 0)
249}
250
251/// The two fields the janitor decides on, read with a serde that tolerates
252/// everything else about the run being unreadable.
253#[derive(Deserialize)]
254struct Meta {
255 status: RunStatus,
256 updated_at: Timestamp,
257}
258
259/// Read `status` and `updated_at` straight off the state file, asking for
260/// nothing else. `Err` when the file is missing, not parseable, or a status in
261/// a version this build does not speak - all of which mean "unreadable".
262fn read_meta(runs: &Path, id: &str) -> Result<Meta> {
263 let path = runs.join(id).join("run.json");
264 let body =
265 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
266 let meta: Meta =
267 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
268 Ok(meta)
269}
270
271/// Read a whole run state from a runs directory, for folding only.
272///
273/// Deliberately more permissive than [`RunState::load`], which this does not
274/// call: `load` backs `--resume` and every hand-driven command, where a
275/// schema this build disagrees with the *meaning* of must refuse outright
276/// rather than resume a review round or a tally against stale semantics
277/// (`RunState::SCHEMA`'s own docs list what has changed meaning at each
278/// bump). Folding recomputes nothing - it only reads worktree paths, branch
279/// names and a tally winner off the struct to remove them - so an old
280/// schema's values are exactly as good here as a current one's; every schema
281/// bump so far has only ever added a field or a variant, never repurposed an
282/// existing one, and serde already fills an added field's default when an
283/// older record has nothing to say about it. What this cannot tolerate, and
284/// what still surfaces as an `Err`, is `run.json` failing to parse at all.
285fn read_state(runs: &Path, id: &str) -> Result<RunState> {
286 let path = runs.join(id).join("run.json");
287 let body =
288 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
289 let state: RunState =
290 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
291 Ok(state)
292}
293
294/// Remove a run that cannot be read: its state directory under `runs` and its
295/// worktree directory under `worktrees_root`.
296///
297/// The state file is the only record of a run's repository and branches, so a
298/// run this unreadable is discarded at the filesystem level - there is no
299/// candidate list to fold first. The worktrees live under
300/// [`crate::run::default_worktree_root`] unless the run's config relocated
301/// them, which an unreadable run cannot tell us; the default location is
302/// removed, and anything the run placed elsewhere is a leftover for whoever
303/// knows where it went.
304///
305/// Deleting a worktree directory by hand leaves its registration in git, and a
306/// registered path cannot be re-`worktree add`-ed until it is pruned - so every
307/// worktree is unregistered from its repository first, best-effort, via the
308/// `gitdir:` link git keeps inside the directory.
309pub async fn fold_unreadable(runs: &Path, worktrees_root: &Path, id: &str) -> Result<Vec<String>> {
310 let resolved = resolve_id_path(runs, id)?;
311 let mut removed = Vec::new();
312 let run_dir = runs.join(&resolved);
313 if run_dir.exists() {
314 std::fs::remove_dir_all(&run_dir)
315 .with_context(|| format!("remove {}", run_dir.display()))?;
316 removed.push(format!("runs/{resolved}"));
317 }
318 let wt = worktrees_root.join(short_of(&resolved));
319 if wt.exists() {
320 crate::git::remove_worktree_from_linked(&wt).await;
321 for e in std::fs::read_dir(&wt).into_iter().flatten().flatten() {
322 crate::git::remove_worktree_from_linked(&e.path()).await;
323 }
324 std::fs::remove_dir_all(&wt).with_context(|| format!("remove {}", wt.display()))?;
325 removed.push(wt.to_string_lossy().into_owned());
326 }
327 Ok(removed)
328}
329
330/// Reclaim worktrees under `worktrees_root` that no run record in `runs`
331/// claims anymore, and return how many were removed.
332///
333/// [`fold_due`] only ever sees a worktree by walking `runs/` first, so a
334/// worktree whose run record is already gone — `magi run rm`, or a record
335/// deleted before its worktree — never enters that loop at all: nothing there
336/// is looking for it. This walks the worktree bay directly instead, and
337/// removes any `<short>` directory that no run id maps to.
338///
339/// Two things must never happen, and this checks both before ever touching a
340/// directory:
341///
342/// - **A worktree bay is never the only kind of thing under `worktrees_root`,
343/// and this must not assume it is.** A hand-placed scratch directory, or
344/// anything else an operator or another tool left in the same bay, has the
345/// same "no run claims it" shape as a genuine orphan but is not one -
346/// [`looks_like_a_worktree_bay`] is the same tag shape [`crate::run::is_run_id`]
347/// already requires of a real run's short id, and anything else is left
348/// alone regardless of what else is true about it.
349/// - **A worktree that was only just created might not have a `run.json` yet
350/// for a reason that has nothing to do with being orphaned.** `Runner::start`
351/// and `Runner::review` both create the worktree before the first
352/// `RunState::save` lands, and that gap - several `git` subprocesses wide -
353/// is invisible to [`crate::daemon::is_working_on_short`] whenever the run
354/// is not being driven through this daemon's own `poll` loop at all (a
355/// `magi review` invocation, for one). A directory whose own modification
356/// time is within `grace_secs` of `now` is left alone on that basis alone,
357/// the same margin [`fold_due`] gives a run before treating it as truly
358/// finished - long enough that no realistic gap between a `worktree add`
359/// and its `run.json` could ever be mistaken for one.
360///
361/// The one failure this must never cause is deleting the worktree of a run
362/// that is genuinely in flight. [`crate::daemon::is_working_on_short`] is the
363/// same liveness check [`fold_due`] trusts everywhere else in this module,
364/// checked by short id because there is no full id to compare here; when it
365/// cannot tell, this leaves the directory alone. Best-effort like the rest of
366/// housekeeping: one directory git or the filesystem refuses to give up is a
367/// `tracing::warn`, not a reason to abandon the rest of the pass.
368pub async fn fold_orphaned_worktrees(
369 runs: &Path,
370 worktrees_root: &Path,
371 home: &Path,
372 grace_secs: u64,
373 now: Timestamp,
374) -> usize {
375 let known: std::collections::HashSet<String> = std::fs::read_dir(runs)
376 .into_iter()
377 .flatten()
378 .flatten()
379 .map(|e| e.file_name().to_string_lossy().into_owned())
380 .filter(|name| crate::run::is_run_id(name))
381 .map(|id| short_of(&id).to_owned())
382 .collect();
383
384 let mut folded = 0usize;
385 for entry in std::fs::read_dir(worktrees_root)
386 .into_iter()
387 .flatten()
388 .flatten()
389 {
390 if !entry.path().is_dir() {
391 continue;
392 }
393 let short = entry.file_name().to_string_lossy().into_owned();
394 if !looks_like_a_worktree_bay(&short) {
395 continue;
396 }
397 if known.contains(&short) || crate::daemon::is_working_on_short(home, &short, now) {
398 continue;
399 }
400 let wt = entry.path();
401 if !stale_enough(&wt, grace_secs, now) {
402 continue;
403 }
404 crate::git::remove_worktree_from_linked(&wt).await;
405 for e in std::fs::read_dir(&wt).into_iter().flatten().flatten() {
406 crate::git::remove_worktree_from_linked(&e.path()).await;
407 }
408 match std::fs::remove_dir_all(&wt) {
409 Ok(()) => folded += 1,
410 Err(e) => tracing::warn!(
411 "housekeep: remove orphaned worktree {}: {e:#}",
412 wt.display()
413 ),
414 }
415 }
416 folded
417}
418
419/// Does `name` have the shape a run's own worktree bay is named with: the
420/// same 4-character alphanumeric tag [`crate::run::is_run_id`] requires of a
421/// full id's trailing block (see [`short_of`])?
422///
423/// Anything else under `worktrees_root` is not a bay this function reclaims
424/// at all, claimed or not - answering "does a run claim this?" about a
425/// directory that was never a run's worktree in the first place is exactly
426/// the wrong question to ask before deleting it.
427fn looks_like_a_worktree_bay(name: &str) -> bool {
428 name.len() == 4 && name.bytes().all(|b| b.is_ascii_alphanumeric())
429}
430
431/// Is `dir`'s own modification time old enough, against `grace_secs` and
432/// `now`, that its emptiness of a run record can be trusted rather than
433/// caught mid-creation?
434///
435/// A directory this pass cannot stat at all - a race with its own removal, a
436/// permission error - is treated as not yet stale: unreadable metadata is not
437/// evidence of anything, and the janitor already keeps rather than deletes
438/// whenever it cannot tell (see the module docs).
439///
440/// `grace_secs` is floored at [`MIN_ORPHAN_AGE_SECS`] regardless of what the
441/// caller passes: `0` is a documented, legitimate value for
442/// [`crate::config::Disk::fold_grace_secs`] (`due`'s own "always due" case),
443/// because that grace answers a policy question the operator owns - how long
444/// a *known, finished* run's worktree lingers before cleanup. Whether an
445/// orphan worktree is actually a race with `Runner::review`'s `git worktree
446/// add` landing before its `run.json` is not a policy question, and must not
447/// collapse to zero just because the operator turned the other grace off -
448/// that would defeat the very check meant to catch it.
449fn stale_enough(dir: &Path, grace_secs: u64, now: Timestamp) -> bool {
450 let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) else {
451 return false;
452 };
453 let Ok(ts) = Timestamp::try_from(modified) else {
454 return false;
455 };
456 due(now, ts, grace_secs.max(MIN_ORPHAN_AGE_SECS))
457}
458
459/// The floor under [`stale_enough`]'s grace, independent of
460/// [`crate::config::Disk::fold_grace_secs`].
461///
462/// Ample next to the race it guards: the gap between `Runner::start` or
463/// `Runner::review` creating a worktree and the first `RunState::save`
464/// landing is a handful of `git` subprocess calls, not minutes - but the
465/// janitor cannot tell "still mid-setup" from "orphaned" by any other signal
466/// for a run that never registers with `daemon::Status` at all (a `magi
467/// review` invocation, for one), so this is generous on purpose rather than
468/// tuned to the observed case.
469const MIN_ORPHAN_AGE_SECS: u64 = 5 * 60;
470
471/// Resolve an id or prefix against an explicit runs directory, exactly the way
472/// [`crate::run::resolve_id`] does against the global home.
473fn resolve_id_path(runs: &Path, prefix: &str) -> Result<String> {
474 // Keyed on the directory, not on a readable state file: the record this
475 // route exists to remove may be a lone `run.json.tmp` from a save that
476 // ran out of disk, and that is precisely the one a human needs a way to
477 // clear (see `crate::run::list_ids`).
478 if runs.join(prefix).is_dir() && crate::run::is_run_id(prefix) {
479 return Ok(prefix.to_owned());
480 }
481 let mut hits: Vec<String> = Vec::new();
482 for e in std::fs::read_dir(runs).into_iter().flatten().flatten() {
483 if !e.path().is_dir() {
484 continue;
485 }
486 let id = e.file_name().to_string_lossy().into_owned();
487 if crate::run::is_run_id(&id) && (id.starts_with(prefix) || id.ends_with(prefix)) {
488 hits.push(id);
489 }
490 }
491 match hits.len() {
492 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
493 0 => bail!("no run matches `{prefix}`"),
494 _ => bail!(
495 "`{prefix}` matches {} runs: {}",
496 hits.len(),
497 hits.join(", ")
498 ),
499 }
500}
501
502/// `magi fold`'s recovery path for a run whose worktrees are already gone —
503/// so [`crate::graph::fold_run`] removed nothing — but whose `run.json` still
504/// lists active seats nobody is left to answer for: no live daemon claims the
505/// run, and every one of those seats has overrun its own timeout (see
506/// [`RunState::active_all_overrun`]). Clearing them and failing the run is
507/// what lets it be deleted afterward — [`RunState::ensure_can_delete`] only
508/// ever checks whether a live daemon is working on the run and whether its
509/// candidates are folded, not `status`, but a run stuck `implementing`
510/// forever with an empty worktree still reads as unresolved everywhere else
511/// (`magi show`, the deck, the phone) until this runs.
512///
513/// Returns `false` without changing anything when a live daemon still claims
514/// the run, or when some active seat has not actually overrun its budget yet
515/// — a run that is merely between waves must never be guessed at.
516pub fn clear_abandoned_active(state: &mut RunState, home: &Path, now: Timestamp) -> Result<bool> {
517 if crate::daemon::is_working_on(home, &state.id, now) || !state.active_all_overrun(now) {
518 return Ok(false);
519 }
520 state.abandon("fold");
521 state.save_under(home)?;
522 // The seat that asked is gone for good now - the same door
523 // `graph::Runner::settle_questions` closes the moment `status` lands
524 // somewhere non-resumable, see that method's own doc. Without this, an
525 // open question the abandoned seat left behind would keep badging the
526 // operator until the next daemon startup's `abandon_settled_questions`
527 // pass happened to notice it, or forever if nothing is running `magi
528 // serve` at all.
529 if let Err(e) = Questions::at(home.join("questions")).settle_run(&state.id, state.status) {
530 tracing::warn!("abandon questions for {}: {e:#}", state.id);
531 }
532 Ok(true)
533}
534
535/// Delete files from the shared build cache until it fits its cap — but only
536/// while nobody live is registered as using it. [`crate::cache::maintenance_prune`]
537/// takes out the same lease a build would, so a prune can never race a
538/// compile in flight (this run's own, another run's, or a human's `magi
539/// review`) into deleting a file that build still needs. `Ok(None)` when the
540/// cache is in use right now; the next pass catches it once the borrower
541/// releases it, the same way a cap of `0` or a missing `CARGO_TARGET_DIR`
542/// already meant "nothing to do this time" here.
543pub fn prune_cache(home: &Path, cache: &Path, limit_bytes: u64) -> Result<Option<Prune>> {
544 crate::cache::maintenance_prune(home, cache, limit_bytes)
545}
546
547/// [`prune_cache`], but resolving the operator's opt-out and missing
548/// `CARGO_TARGET_DIR` first — the same two checks [`housekeep`]'s idle pass
549/// makes before ever measuring the cache, factored out so
550/// [`crate::daemon`]'s between-runs check (see the module's own doc for why
551/// congestion can make "idle" arrive too rarely to matter) makes them
552/// identically rather than growing its own copy that could drift. `Ok(None)`
553/// covers a cap of `0` (see the module docs on `cache_limit_bytes`), a config
554/// that renders no `CARGO_TARGET_DIR` to aggregate at all, and a cache
555/// currently in use (see [`prune_cache`]).
556pub fn prune_cache_if_over_limit(
557 cfg: &crate::config::Config,
558 home: &Path,
559) -> Result<Option<Prune>> {
560 if cfg.disk.cache_limit_bytes == 0 {
561 return Ok(None);
562 }
563 let Some(cache) = cfg.cache_dir() else {
564 return Ok(None);
565 };
566 prune_cache(home, &cache, cfg.disk.cache_limit_bytes)
567}
568
569/// The cache's path, size and cap, for `magi cache show` and the health view.
570/// `None` when the config declares no `CARGO_TARGET_DIR` to aggregate.
571///
572/// A cap of `0` means the operator opted out of pruning; the size is then
573/// reported but never acted on.
574pub fn cache_report(cfg: &crate::config::Config) -> Option<(PathBuf, u64, u64)> {
575 let cache = cfg.cache_dir()?;
576 Some((
577 cache.clone(),
578 cache_size(&cache),
579 cfg.disk.cache_limit_bytes,
580 ))
581}
582
583/// Size in bytes of the shared build cache.
584pub fn cache_size(cache: &Path) -> u64 {
585 dir_size(cache)
586}
587
588#[cfg(test)]
589mod tests {
590 use super::*;
591 use crate::config::Disk;
592 use std::fs;
593
594 fn ts(s: &str) -> Timestamp {
595 s.parse().expect("rfc3339")
596 }
597
598 fn block_on<F: std::future::Future>(f: F) -> F::Output {
599 tokio::runtime::Runtime::new().expect("runtime").block_on(f)
600 }
601
602 #[test]
603 fn a_run_is_due_after_its_grace_and_not_before() {
604 let now = ts("2026-09-05T00:00:00Z");
605 let grace = 600;
606 let old = now - SignedDuration::new(601, 0);
607 let fresh = now - SignedDuration::new(599, 0);
608 assert!(due(now, old, grace));
609 assert!(!due(now, fresh, grace));
610 // Exactly at the edge: not yet due.
611 let edge = now - SignedDuration::new(600, 0);
612 assert!(!due(now, edge, grace));
613 // A zero grace folds everything, ever.
614 assert!(due(now, old, 0));
615 }
616
617 #[test]
618 fn the_meta_reader_is_tolerant_of_everything_except_the_deciders() {
619 let dir = tempfile::tempdir().unwrap();
620 let runs = dir.path().join("runs");
621 let id = "20260905-000000-abcd";
622 std::fs::create_dir_all(runs.join(id)).unwrap();
623 std::fs::write(
624 runs.join(id).join("run.json"),
625 r#"{"schema": 99, "id": "20260905-000000-abcd", "updated_at": "2026-09-05T00:00:00Z", "status": "ready", "junk_from_another_build": [1, 2, 3]}"#,
626 )
627 .unwrap();
628 let meta = read_meta(&runs, id).expect("readable");
629 assert_eq!(meta.status, RunStatus::Ready);
630 assert_eq!(meta.updated_at, ts("2026-09-05T00:00:00Z"));
631 assert!(read_meta(&runs, "nope").is_err(), "missing file unreadable");
632 std::fs::write(runs.join(id).join("run.json"), "not json at all").unwrap();
633 assert!(read_meta(&runs, id).is_err(), "garbage unreadable");
634 }
635
636 #[test]
637 fn fold_unreadable_releases_run_dir_and_worktrees() {
638 let dir = tempfile::tempdir().unwrap();
639 let runs = dir.path().join("runs");
640 let wt = dir.path().join("wt");
641 let id = "20260905-000000-abcd";
642 std::fs::create_dir_all(runs.join(id)).unwrap();
643 std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
644 std::fs::create_dir_all(wt.join("abcd")).unwrap();
645 std::fs::write(wt.join("abcd").join("leftover"), b"x").unwrap();
646
647 let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold");
648 assert_eq!(removed.len(), 2);
649 assert!(!runs.join(id).exists(), "run dir gone");
650 assert!(!wt.join("abcd").exists(), "worktrees gone");
651
652 // A prefix resolves like `run::resolve_id` does.
653 std::fs::create_dir_all(runs.join(id)).unwrap();
654 std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
655 std::fs::create_dir_all(wt.join("abcd")).unwrap();
656 std::fs::write(wt.join("abcd").join("leftover"), b"x").unwrap();
657 let removed = block_on(fold_unreadable(&runs, &wt, "20260905")).expect("by prefix");
658 assert_eq!(removed.len(), 2);
659 // Once gone, `id` cannot be resolved at all - same as `run::resolve_id`
660 // on an id nothing on disk matches - so a repeat pass errors rather
661 // than silently reporting nothing removed.
662 assert!(
663 block_on(fold_unreadable(&runs, &wt, id)).is_err(),
664 "a run already gone cannot be resolved again"
665 );
666 }
667
668 #[test]
669 fn prune_cache_sheds_the_oldest_generation_until_it_fits() {
670 let home = tempfile::tempdir().unwrap();
671 let dir = tempfile::tempdir().unwrap();
672 // Same size, different age: only the age decides, and the newest
673 // generation - the one the next build reuses - is what survives.
674 fs::write(dir.path().join("old"), b"xx").unwrap();
675 fs::write(dir.path().join("new"), b"yy").unwrap();
676 touch(&dir.path().join("old"), 1_000_000);
677 touch(&dir.path().join("new"), 2_000_000);
678
679 let out = prune_cache(home.path(), dir.path(), 2)
680 .expect("prune")
681 .expect("the cache is free");
682 assert_eq!(out.files, 1, "one deletion is enough to reach the cap");
683 assert_eq!(out.remaining, 2);
684 assert!(!dir.path().join("old").exists(), "the older file went");
685 assert!(dir.path().join("new").exists(), "the newer one stayed");
686
687 // A whole generation shares one timestamp tick, so the tie has to be
688 // decided too: largest first, which reaches the cap in the fewest
689 // deletions. Left to `read_dir` and an unstable sort this deleted
690 // both files on Linux and one on Windows.
691 let tied = tempfile::tempdir().unwrap();
692 fs::write(tied.path().join("big"), b"xxxx").unwrap();
693 fs::write(tied.path().join("small"), b"yy").unwrap();
694 touch(&tied.path().join("big"), 1_000_000);
695 touch(&tied.path().join("small"), 1_000_000);
696 let out = prune_cache(home.path(), tied.path(), 2)
697 .expect("prune")
698 .expect("the cache is free");
699 assert_eq!(out.files, 1, "the big one alone gets under the cap");
700 assert_eq!(out.remaining, 2);
701 assert!(tied.path().join("small").exists());
702 }
703
704 #[test]
705 fn prune_cache_if_over_limit_resolves_the_opt_outs_before_ever_measuring() {
706 let home = tempfile::tempdir().unwrap();
707 let dir = tempfile::tempdir().unwrap();
708 fs::write(dir.path().join("big"), vec![0u8; 10]).unwrap();
709
710 let mut cfg = crate::config::Config::default();
711 cfg.verify.gate = vec![format!(
712 "CARGO_TARGET_DIR={} cargo make check",
713 dir.path().display()
714 )];
715
716 // A cap of `0` is the operator's opt-out: never measured, never
717 // pruned, regardless of what is actually on disk.
718 cfg.disk.cache_limit_bytes = 0;
719 assert_eq!(
720 prune_cache_if_over_limit(&cfg, home.path()).unwrap(),
721 None,
722 "a zero cap must not even look at the directory"
723 );
724 assert!(dir.path().join("big").exists());
725
726 // No `CARGO_TARGET_DIR` in either verify command: nothing to
727 // aggregate, so there is nothing to prune either.
728 let mut no_cache = crate::config::Config::default();
729 no_cache.disk.cache_limit_bytes = 1;
730 assert_eq!(
731 prune_cache_if_over_limit(&no_cache, home.path()).unwrap(),
732 None
733 );
734
735 // Over the cap and configured: pruned exactly like `prune_cache`
736 // itself would.
737 cfg.disk.cache_limit_bytes = 1;
738 let pruned = prune_cache_if_over_limit(&cfg, home.path())
739 .unwrap()
740 .expect("a real cache dir over its cap prunes");
741 assert_eq!(pruned.files, 1);
742 assert!(!dir.path().join("big").exists());
743 }
744
745 /// Pin a file's mtime, so a test asserts the policy and not the runner's
746 /// timestamp granularity.
747 fn touch(path: &Path, secs: u64) {
748 let f = fs::File::options().write(true).open(path).unwrap();
749 f.set_times(fs::FileTimes::new().set_modified(
750 std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs),
751 ))
752 .unwrap();
753 }
754
755 /// The disk-full casualty: a run whose first save left `run.json.tmp` and
756 /// nothing else. It has to be clearable, or the record is permanent.
757 #[test]
758 fn fold_unreadable_clears_a_run_whose_state_never_landed() {
759 let dir = tempfile::tempdir().unwrap();
760 let runs = dir.path().join("runs");
761 let wt = dir.path().join("wt");
762 let id = "20260904-014540-88c0";
763 std::fs::create_dir_all(runs.join(id)).unwrap();
764 std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
765
766 let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold by id");
767 assert_eq!(removed, vec![format!("runs/{id}")]);
768 assert!(!runs.join(id).exists(), "record gone");
769
770 // And by prefix, the way the deck and the phone address a run.
771 std::fs::create_dir_all(runs.join(id)).unwrap();
772 std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
773 assert!(
774 block_on(fold_unreadable(&runs, &wt, "88c0")).is_ok(),
775 "by prefix"
776 );
777
778 // A directory under `runs` that is not a run is never a fold target.
779 std::fs::create_dir_all(runs.join("scratch")).unwrap();
780 assert!(
781 block_on(fold_unreadable(&runs, &wt, "scratch")).is_err(),
782 "a stray directory is not a run"
783 );
784 }
785
786 #[test]
787 fn fold_due_folds_terminal_runs_of_any_schema_but_leaves_genuinely_unreadable_ones() {
788 let dir = tempfile::tempdir().unwrap();
789 let runs = dir.path().join("runs");
790 let wt = dir.path().join("wt");
791 let home = dir.path().to_path_buf();
792 let disk = Disk::default();
793 let now = ts("2026-09-05T00:00:00Z");
794
795 // 1. Runnable (judging): never folded, however old.
796 let judging = "20260801-000000-0001";
797 write_meta(&runs, judging, "judging", "2026-08-01T00:00:00Z");
798
799 // 2. Finished but fresh: grace not elapsed. Within the default 6h
800 // grace of `now`, so `fold_due` must stop at the freshness check
801 // and never even reach `read_state` - `write_meta`'s minimal JSON
802 // would fail that full parse anyway, and this case exists to
803 // prove freshness is why the run survives, not an accident of the
804 // fixture being unparseable as a whole `RunState`.
805 let ready_fresh = "20260904-220000-0002";
806 write_meta(&runs, ready_fresh, "ready", "2026-09-04T22:00:00Z");
807
808 // 3. Genuinely unreadable: broken JSON, not merely an unfamiliar
809 // schema number. Left alone and counted - this is the one case
810 // automatic housekeeping must never touch (see `fold_due`'s docs);
811 // discarding it is an explicit operator action, not something a
812 // background pass does.
813 let garbage = "20260901-000000-0004";
814 std::fs::create_dir_all(runs.join(garbage)).unwrap();
815 std::fs::write(runs.join(garbage).join("run.json"), "not json").unwrap();
816 std::fs::create_dir_all(wt.join("0004")).unwrap();
817
818 // 4. Finished, well past grace, current schema: the ordinary case
819 // `fold_due` has always acted on.
820 let due_ready = due_run(&runs, &wt, "20260801-000000-ffff", SCHEMA);
821
822 // 5. Finished, well past grace, but written by a schema number this
823 // build no longer matches - the defect this task exists to fix.
824 // It still parses cleanly, so only the version number differs, and
825 // that alone must not block folding.
826 let due_old_schema = due_run(&runs, &wt, "20260801-000000-eeee", SCHEMA - 1);
827
828 let (folded, unreadable) =
829 block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
830 assert_eq!(
831 folded, 2,
832 "both due, parseable runs fold regardless of their schema number"
833 );
834 assert_eq!(
835 unreadable, 1,
836 "only the run with broken JSON counts as unreadable"
837 );
838 assert!(runs.join(judging).exists(), "runnable never folded");
839 assert!(runs.join(ready_fresh).exists(), "fresh never folded");
840 assert!(runs.join(garbage).exists(), "unreadable record kept");
841 assert!(wt.join("0004").exists(), "unreadable worktree kept");
842 assert!(
843 runs.join(&due_ready).exists(),
844 "folding drops worktrees, not the record"
845 );
846 assert!(
847 runs.join(&due_old_schema).exists(),
848 "an old-schema record survives its fold exactly like a current one"
849 );
850 // `graph::fold_run` saves the state it just folded back to disk. That
851 // write must land under this test's own `runs` - the argument it
852 // passed to `fold_due`, not the process-global `run::home` - or a
853 // fold that landed somewhere else entirely would still be counted
854 // above as one of the two `folded` runs.
855 for id in [&due_ready, &due_old_schema] {
856 let saved = read_meta(&runs, id).expect("folded run still parses");
857 assert_ne!(
858 saved.updated_at,
859 ts("2026-08-01T00:00:00Z"),
860 "fold_run must have saved the updated state back through the \
861 `runs` directory this test passed to fold_due"
862 );
863 }
864 }
865
866 /// `[disk] auto_fold = false` must leave the janitor's fold-and-reclaim
867 /// passes completely inert - a due run's worktree and record both
868 /// survive exactly as if `housekeep` had never run at all. Cache pruning
869 /// is a separate opt-out (`cache_limit_bytes`) and stays disabled here
870 /// too, so this test is only ever about `auto_fold`.
871 #[tokio::test]
872 async fn housekeep_leaves_everything_alone_when_auto_fold_is_disabled() {
873 let dir = tempfile::tempdir().unwrap();
874 let runs = dir.path().join("runs");
875 let wt = dir.path().join("wt");
876 let home = dir.path().to_path_buf();
877 crate::run::set_home(dir.path().to_path_buf());
878
879 let due_id = due_run(&runs, &wt, "20260801-000000-abcd", SCHEMA);
880 std::fs::create_dir_all(wt.join("orphan").join("cand-A")).unwrap();
881
882 let mut cfg = crate::config::Config::default();
883 cfg.disk.auto_fold = false;
884 cfg.disk.cache_limit_bytes = 0;
885
886 let out = housekeep(&cfg, &home, &wt, &dir.path().join("repo"), Timestamp::now()).await;
887
888 assert_eq!(out.folded, 0);
889 assert_eq!(out.unreadable, 0);
890 assert_eq!(out.orphaned_worktrees, 0);
891 assert!(
892 runs.join(&due_id).exists(),
893 "a due run's record survives untouched"
894 );
895 assert!(
896 wt.join("orphan").exists(),
897 "an orphaned worktree survives untouched: the reclaim pass never ran"
898 );
899 }
900
901 #[test]
902 fn fold_orphaned_worktrees_removes_only_worktrees_no_run_claims_and_none_in_flight() {
903 let dir = tempfile::tempdir().unwrap();
904 let runs = dir.path().join("runs");
905 let wt = dir.path().join("wt");
906 let home = dir.path().to_path_buf();
907
908 // A run record exists for this one: its worktree is claimed, not
909 // orphaned, however old the record.
910 write_meta(
911 &runs,
912 "20260801-000000-aaaa",
913 "ready",
914 "2026-08-01T00:00:00Z",
915 );
916 std::fs::create_dir_all(wt.join("aaaa").join("cand-A")).unwrap();
917
918 // No run record at all, and nobody is working on it: this is the
919 // leftover `fold_due` can never see, because it only ever walks
920 // `runs/`.
921 std::fs::create_dir_all(wt.join("bbbb").join("cand-A")).unwrap();
922
923 // No run record either, but a live daemon status names a run with
924 // this short id - the save-timing gap between the daemon claiming a
925 // task and `RunState::new` writing its first `run.json`. Must survive
926 // untouched.
927 std::fs::create_dir_all(wt.join("cccc")).unwrap();
928
929 // Not shaped like a run's short id at all - a scratch directory an
930 // operator or another tool left in the same bay - so it is never a
931 // reclaim target regardless of what runs claim it or not.
932 std::fs::create_dir_all(wt.join("scratch")).unwrap();
933
934 // `now` pushed comfortably past `MIN_ORPHAN_AGE_SECS`, so a zero
935 // grace - the same "always due" escape hatch `due` itself documents
936 // - still reclaims once a worktree is genuinely old, without faking
937 // an mtime: real directory creation just above is already in the
938 // past relative to this `now`, by design rather than by timing.
939 let now = Timestamp::now() + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
940 let mut status = crate::daemon::Status::new();
941 status.current = vec![crate::daemon::Current {
942 task: "20260905-000000-t111".to_owned(),
943 run: "20260905-000000-cccc".to_owned(),
944 }];
945 status.updated_at = now;
946 crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
947
948 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
949 assert_eq!(
950 folded, 1,
951 "only the truly orphaned, idle, bay-shaped worktree is removed"
952 );
953 assert!(wt.join("aaaa").exists(), "claimed by a run record");
954 assert!(!wt.join("bbbb").exists(), "orphaned and idle: reclaimed");
955 assert!(wt.join("cccc").exists(), "a run in flight is never touched");
956 assert!(
957 wt.join("scratch").exists(),
958 "not shaped like a worktree bay, so never a reclaim target"
959 );
960 }
961
962 /// The gap this closes: `Runner::review` (`magi review`) creates the
963 /// worktree with `git worktree add` before `RunState::save` ever writes a
964 /// `run.json`, and that path never runs through the daemon's own `poll`
965 /// loop at all, so `daemon::Status` never names it either. Without a
966 /// grace window, a janitor pass landing in that gap would read the
967 /// worktree as an orphan nothing is waiting on and delete a review still
968 /// being set up.
969 #[test]
970 fn fold_orphaned_worktrees_leaves_a_freshly_created_bay_alone() {
971 let dir = tempfile::tempdir().unwrap();
972 let runs = dir.path().join("runs");
973 let wt = dir.path().join("wt");
974 let home = dir.path().to_path_buf();
975
976 std::fs::create_dir_all(wt.join("dddd").join("under-review")).unwrap();
977
978 let now = Timestamp::now();
979 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 6 * 60 * 60, now));
980 assert_eq!(
981 folded, 0,
982 "too fresh to tell apart from a run still being set up"
983 );
984 assert!(wt.join("dddd").exists());
985 }
986
987 /// A fresh open question on `run`, stored and handed back for assertions.
988 fn open_question(store: &Questions, run: &str) -> crate::ask::Question {
989 let mut q = crate::ask::Question::new(
990 run.to_owned(),
991 "implement".to_owned(),
992 "impl-A".to_owned(),
993 "Which storage backend should the cache use?".to_owned(),
994 String::new(),
995 vec!["SQLite".to_owned(), "Redis".to_owned()],
996 );
997 store.put(&mut q).unwrap();
998 q
999 }
1000
1001 /// The exact ghost the phone showed: a run that already finished, with a
1002 /// question its dead seat asked still sitting `open` because it reached
1003 /// that status before `graph::Runner::settle_questions` existed (or
1004 /// missed it in the crash window `daemon::reclaim_orphaned_running`
1005 /// covers). This sweep is the second door to the same fact.
1006 #[test]
1007 fn a_finished_runs_open_question_is_swept_up() {
1008 let dir = tempfile::tempdir().unwrap();
1009 let runs = dir.path().join("runs");
1010 let store = Questions::at(dir.path().join("questions"));
1011
1012 let failed = "20260908-205802-c9eb";
1013 write_meta(&runs, failed, "failed", "2026-09-08T20:58:02Z");
1014 let failed_q = open_question(&store, failed);
1015
1016 let merged = "20260908-205501-ca67";
1017 write_meta(&runs, merged, "merged", "2026-09-08T20:55:01Z");
1018 let merged_q = open_question(&store, merged);
1019
1020 let n = abandon_settled_questions(&store, &runs);
1021 assert_eq!(n, 2, "both dead runs' questions are swept in one pass");
1022
1023 for (id, run) in [(&failed_q.id, failed), (&merged_q.id, merged)] {
1024 let back = store.get(id).unwrap();
1025 assert!(!back.status.open(), "{run} is done; nobody reads an answer");
1026 assert!(back.detail.contains(run), "{}", back.detail);
1027 }
1028 }
1029
1030 #[test]
1031 fn a_still_alive_runs_open_question_survives_the_sweep() {
1032 let dir = tempfile::tempdir().unwrap();
1033 let runs = dir.path().join("runs");
1034 let store = Questions::at(dir.path().join("questions"));
1035
1036 // `Blocked` and `Stalled` are `RunStatus::resumable`: the run can
1037 // still be picked back up, so its question may yet get a real
1038 // answer. A run still mid-competition is even more obviously alive.
1039 for (id, status) in [
1040 ("20260908-000000-b10c", "blocked"),
1041 ("20260908-000000-5ta1", "stalled"),
1042 ("20260908-000000-jud6", "judging"),
1043 ] {
1044 write_meta(&runs, id, status, "2026-09-08T00:00:00Z");
1045 let q = open_question(&store, id);
1046
1047 let n = abandon_settled_questions(&store, &runs);
1048 assert_eq!(n, 0, "{status} run is not done; nothing to sweep");
1049 assert!(
1050 store.get(&q.id).unwrap().status.open(),
1051 "{status} run's question must still be waiting"
1052 );
1053 }
1054 }
1055
1056 #[test]
1057 fn the_sweep_leaves_an_answered_question_and_an_unreadable_run_alone() {
1058 let dir = tempfile::tempdir().unwrap();
1059 let runs = dir.path().join("runs");
1060 let store = Questions::at(dir.path().join("questions"));
1061
1062 // Already decided: a sweep must never revisit it, whatever the run
1063 // that asked went on to become.
1064 let done = "20260908-000000-answ";
1065 write_meta(&runs, done, "failed", "2026-09-08T00:00:00Z");
1066 let mut answered = open_question(&store, done);
1067 answered
1068 .answer(crate::ask::Answer::Choice("SQLite".to_owned()))
1069 .unwrap();
1070 store.put(&mut answered).unwrap();
1071
1072 // No `run.json` at all for this one - deleted, or never landed.
1073 let gone = "20260908-000000-gone";
1074 let orphan = open_question(&store, gone);
1075
1076 assert_eq!(abandon_settled_questions(&store, &runs), 0);
1077 assert_eq!(
1078 store.get(&answered.id).unwrap().status,
1079 crate::ask::QuestionStatus::Answered,
1080 "a real answer is never overwritten by a sweep"
1081 );
1082 assert!(
1083 store.get(&orphan.id).unwrap().status.open(),
1084 "a run this sweep cannot read is left exactly as it was, not guessed at"
1085 );
1086 }
1087
1088 /// A grace of `0` is a legitimate, documented value for the operator's
1089 /// own `Disk::fold_grace_secs` - `due`'s "always due" case - but the
1090 /// freshness check this guards is not that policy, and must not collapse
1091 /// to it: a `0` handed straight through would reclaim a worktree the
1092 /// instant it exists, exactly the race `fold_orphaned_worktrees_leaves_a_
1093 /// freshly_created_bay_alone` exists to rule out, just with the operator
1094 /// having turned the other grace off instead of leaving it at its
1095 /// default.
1096 #[test]
1097 fn fold_orphaned_worktrees_floors_a_zero_grace_at_the_race_safe_minimum() {
1098 let dir = tempfile::tempdir().unwrap();
1099 let runs = dir.path().join("runs");
1100 let wt = dir.path().join("wt");
1101 let home = dir.path().to_path_buf();
1102
1103 std::fs::create_dir_all(wt.join("eeee").join("under-review")).unwrap();
1104
1105 // Too fresh, even with the grace argument at zero.
1106 let now = Timestamp::now();
1107 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
1108 assert_eq!(
1109 folded, 0,
1110 "a zero grace must not defeat the race-safety floor"
1111 );
1112 assert!(wt.join("eeee").exists());
1113
1114 // Once genuinely past the floor, a zero grace reclaims it - the
1115 // floor is a minimum, not a replacement policy that never fires.
1116 let later = now + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
1117 let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, later));
1118 assert_eq!(folded, 1, "old enough now, regardless of the zero grace");
1119 assert!(!wt.join("eeee").exists());
1120 }
1121
1122 #[test]
1123 fn clear_abandoned_active_only_acts_once_dead_and_overrun() {
1124 let dir = tempfile::tempdir().unwrap();
1125 // Harmless if another test in this binary already pinned the global
1126 // home first (see `run::set_home`'s own doc): this test only checks
1127 // the in-memory mutation `clear_abandoned_active` makes, never a
1128 // write that landed under this exact directory.
1129 crate::run::set_home(dir.path().to_path_buf());
1130 let home = dir.path().to_path_buf();
1131 let now = ts("2026-09-14T12:00:00Z");
1132 let overrun_seat = || crate::run::ActiveSeat {
1133 node: "implement".to_owned(),
1134 started_at: now - SignedDuration::new(21_000, 0),
1135 timeout_secs: 3_600,
1136 attempt: 0,
1137 task: None,
1138 command: None,
1139 index: None,
1140 total: None,
1141 };
1142
1143 let mut state = RunState::new(
1144 PathBuf::from("/repo"),
1145 "main".to_owned(),
1146 "abc1234".to_owned(),
1147 "fixture".to_owned(),
1148 crate::config::Config::default(),
1149 );
1150 state.status = RunStatus::Implementing;
1151 state.active.insert("impl-A".to_owned(), overrun_seat());
1152
1153 // A seat still within its own budget: not provably dead yet, so this
1154 // must change nothing.
1155 let mut fresh = state.clone();
1156 fresh.active.insert(
1157 "impl-B".to_owned(),
1158 crate::run::ActiveSeat {
1159 node: "implement".to_owned(),
1160 started_at: now,
1161 timeout_secs: 3_600,
1162 attempt: 0,
1163 task: None,
1164 command: None,
1165 index: None,
1166 total: None,
1167 },
1168 );
1169 assert!(!clear_abandoned_active(&mut fresh, &home, now).unwrap());
1170 assert!(!fresh.active.is_empty());
1171 assert_eq!(fresh.status, RunStatus::Implementing);
1172
1173 let store = Questions::at(home.join("questions"));
1174 let q = open_question(&store, &state.id);
1175
1176 assert!(clear_abandoned_active(&mut state, &home, now).unwrap());
1177 assert!(state.active.is_empty());
1178 assert_eq!(state.status, RunStatus::Failed);
1179 assert!(
1180 !store.get(&q.id).unwrap().status.open(),
1181 "the abandoned seat's own open question must not keep badging the \
1182 operator until some later daemon startup notices it"
1183 );
1184 }
1185
1186 /// Write a whole `run.json` that magi can read, over the given state.
1187 fn write_meta(runs: &Path, id: &str, status: &str, updated_at: &str) {
1188 let day = &updated_at[..10];
1189 std::fs::create_dir_all(runs.join(id)).unwrap();
1190 let body = format!(
1191 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}}"#
1192 );
1193 std::fs::write(runs.join(id).join("run.json"), body).unwrap();
1194 }
1195
1196 /// Write a fully-formed, `Ready`, well-past-grace `run.json` tagged with
1197 /// an arbitrary schema number - so a test can write one this build's own
1198 /// `RunState::new` could never produce on its own. Returns the id.
1199 ///
1200 /// `wt` becomes this run's `graph.worktree_root`: left at the config
1201 /// default, `RunState::worktree_root` falls through to
1202 /// `run::default_worktree_root` - the operator's real `~/wt/magi` - and
1203 /// `graph::fold_run`'s second sweep would then `read_dir` and remove
1204 /// worktrees there instead of anything this test owns.
1205 fn due_run(runs: &Path, wt: &Path, id: &str, schema: u32) -> String {
1206 let mut config = crate::config::Config::default();
1207 config.graph.worktree_root = Some(wt.to_path_buf());
1208 let mut state = RunState::new(
1209 PathBuf::from("/nonexistent/repo"),
1210 "main".to_owned(),
1211 "0000000000000000000000000000000000000000".to_owned(),
1212 String::new(),
1213 config,
1214 );
1215 state.id = id.to_owned();
1216 state.status = RunStatus::Ready;
1217 state.updated_at = ts("2026-08-01T00:00:00Z");
1218 let mut value = serde_json::to_value(&state).unwrap();
1219 value["schema"] = serde_json::json!(schema);
1220 std::fs::create_dir_all(runs.join(id)).unwrap();
1221 std::fs::write(
1222 runs.join(id).join("run.json"),
1223 serde_json::to_string_pretty(&value).unwrap(),
1224 )
1225 .unwrap();
1226 id.to_owned()
1227 }
1228}