Skip to main content

magi/
cache.rs

1//! Durable ownership of the shared Cargo build cache (`CARGO_TARGET_DIR`).
2//!
3//! One cache, many borrowers: an implement wave's candidates, a review
4//! round's E2E, the final gate, a human's `magi review` invoked by hand — all
5//! of them may point `CARGO_TARGET_DIR` at the same directory, sometimes from
6//! *different* worktrees, sometimes from a different `magi run` entirely. Two
7//! failures came out of sharing it with no ownership record at all:
8//!
9//! - A read-only reviewer seat that inherited `CARGO_TARGET_DIR` tried to
10//!   write into it, was refused by its own sandbox, and reported the refusal
11//!   as a defect in the code under review rather than a property of its own
12//!   seat. See `graph::wave`, which now only hands the variable to a seat
13//!   that [`crate::agent::Invocation::allow_write`] actually permits to use.
14//! - Two source trees building the same package name/version into one
15//!   `CARGO_TARGET_DIR` in sequence can leave a stale artifact from the
16//!   *older* worktree looking fresh to Cargo, and a later `cargo test` runs
17//!   binaries compiled from source nobody is looking at. [`ensure_fresh`]
18//!   selectively `cargo clean -p`s the workspace's own packages — never the
19//!   downloaded dependency graph — the moment the recorded source identity
20//!   for a cache directory changes.
21//!
22//! Both are consequences of one missing fact: *who is using this cache right
23//! now, and against which source*. This module is that fact, made durable
24//! (a JSON file per cache directory, surviving a process restart) and cheap
25//! to ask (`classify`, `in_use`, `inventory`).
26//!
27//! ## Reclaiming a dead owner
28//!
29//! Liveness is [`crate::proc::pid_alive`] — the same conservative check
30//! [`crate::daemon::sweep_stale_claims`] uses for the queue's own claim
31//! locks: every uncertain outcome reads as alive, and a lease whose file
32//! cannot even be parsed is never reclaimed automatically ([`Status::Unknown`]).
33//! This is deliberately the same policy as the queue's `.lock` files, not a
34//! new one — a bare lock file was never trusted alone there either; it is
35//! always paired with a liveness check.
36//!
37//! Process cleanup additionally holds an OS output lease through termination of
38//! managed tool descendants. Admission and destructive maintenance check that
39//! lease too: reclaiming a dead JSON owner alone does not permit deleting or
40//! reusing outputs still owned by cleanup.
41
42use std::path::{Path, PathBuf};
43use std::time::Duration;
44
45use anyhow::{Context as _, Result, bail};
46use jiff::Timestamp;
47use serde::{Deserialize, Serialize};
48
49use crate::proc::{self, Quiet as _};
50
51/// Who is holding, or wants, a cache directory.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct Owner {
54    /// The run this borrow belongs to.
55    pub run: String,
56    /// The graph node, e.g. `implement`, `review`, `gate`.
57    pub node: String,
58    /// Seat key, or a fixed label for a borrow that is not seat-shaped
59    /// (`"e2e"`, `"gate"`, `"janitor"`).
60    pub seat: String,
61    /// Process id of the magi process holding the lease — never the spawned
62    /// agent CLI or `cargo` child, both of which end well before this
63    /// process's own async task returns and releases the guard.
64    pub pid: u32,
65    /// The worktree the borrower is building from, for the report and for
66    /// [`ensure_fresh`]'s identity comparison.
67    pub worktree: String,
68    /// The commit the borrower is building, same purpose as `worktree`.
69    pub head: String,
70}
71
72impl Owner {
73    /// An owner for the current process.
74    #[must_use]
75    pub fn here(run: &str, node: &str, seat: &str, worktree: &Path, head: &str) -> Owner {
76        Owner {
77            run: run.to_owned(),
78            node: node.to_owned(),
79            seat: seat.to_owned(),
80            pid: std::process::id(),
81            worktree: worktree.display().to_string(),
82            head: head.to_owned(),
83        }
84    }
85}
86
87/// One held lease, as written to disk.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89struct LeaseFile {
90    /// The literal cache path, kept alongside the owner so [`inventory`] can
91    /// report it without reversing the filename — the filename is a lossy
92    /// slug, not the path itself.
93    cache_dir: String,
94    owner: Owner,
95    acquired_at: Timestamp,
96}
97
98/// Where a cache directory's classification lands.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Status {
101    /// No lease file, or one whose owner is confirmed gone.
102    Free,
103    /// A live owner holds it.
104    Active(Owner),
105    /// A lease file names an owner whose pid is confirmed gone. Reclaimable.
106    Stale(Owner),
107    /// A lease file exists but could not be trusted — unreadable or
108    /// unparseable. Never reclaimed automatically; a human decides.
109    Unknown,
110}
111
112/// Why [`try_acquire`] did not hand back a [`Guard`].
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum Busy {
115    /// Held by a confirmed-live owner.
116    Active(Owner),
117    /// A lease is present but could not be trusted.
118    Unknown,
119    /// Lost a race with another acquirer; the caller should just try again.
120    Contended,
121    /// A process cleanup owner still protects the cache outputs.
122    Outputs,
123}
124
125impl Busy {
126    /// One line for an event log or an error message.
127    #[must_use]
128    pub fn describe(&self) -> String {
129        match self {
130            Busy::Active(o) => format!(
131                "held by run {} node {} seat {} (pid {})",
132                o.run, o.node, o.seat, o.pid
133            ),
134            Busy::Unknown => {
135                "an unreadable lease is present; refusing to guess who holds it".to_owned()
136            }
137            Busy::Outputs => {
138                "cache outputs are still owned by running tools or process cleanup".to_owned()
139            }
140            Busy::Contended => "lost a race for the lease; retrying".to_owned(),
141        }
142    }
143}
144
145/// A held lease. Releases on drop, so a panicking or early-returning caller
146/// never leaves the cache permanently marked busy — the same guarantee
147/// [`crate::queue::Claim`] gives the task queue's own lock file.
148#[derive(Debug)]
149pub struct Guard {
150    path: PathBuf,
151    released: bool,
152    outputs: Option<crate::retention::OutputLease>,
153}
154
155impl Guard {
156    fn new(path: PathBuf) -> Guard {
157        Guard {
158            path,
159            released: false,
160            outputs: None,
161        }
162    }
163
164    /// Release explicitly. Equivalent to dropping the guard; spelled out for
165    /// call sites where "the build finished, release now" reads better than
166    /// waiting for scope exit.
167    pub fn release(mut self) {
168        self.do_release();
169    }
170
171    fn do_release(&mut self) {
172        if !self.released {
173            let _ = std::fs::remove_file(&self.path);
174            self.released = true;
175        }
176    }
177}
178
179impl Drop for Guard {
180    fn drop(&mut self) {
181        self.do_release();
182    }
183}
184
185/// The directory leases live under, inside the magi home — never inside the
186/// cache directory itself, so [`crate::disk::prune_dir`]'s oldest-first sweep
187/// of the cache can never delete a lease file it does not know exists.
188fn leases_dir(home: &Path) -> PathBuf {
189    home.join("cache-leases")
190}
191
192/// A stable, filesystem-safe name for one cache directory's lease file.
193/// Human-legible prefix (so a directory listing is self-explanatory) plus a
194/// hash suffix (so two paths that sanitize to the same prefix — unlikely,
195/// but not impossible on a long path — never collide).
196fn slug(cache_dir: &Path) -> String {
197    if let Some(id) = crate::build_target::generation(cache_dir) {
198        return format!("isolated-{id}");
199    }
200    let norm = normalize(cache_dir);
201    let mut readable: String = norm
202        .chars()
203        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
204        .collect();
205    readable.truncate(80);
206    use std::hash::{Hash, Hasher};
207    let mut hasher = std::collections::hash_map::DefaultHasher::new();
208    norm.hash(&mut hasher);
209    format!("{readable}-{:08x}", hasher.finish() as u32)
210}
211
212/// Best-effort canonical form of a cache path, for hashing only — never
213/// shown to a human, who gets the literal path out of the lease file's own
214/// `cache_dir` field instead. Falls back to the literal string when the
215/// directory does not exist yet, so a lease can be taken before the first
216/// build creates it.
217fn normalize(p: &Path) -> String {
218    std::fs::canonicalize(p)
219        .map(|p| p.display().to_string())
220        .unwrap_or_else(|_| p.display().to_string())
221        .replace('\\', "/")
222        .to_ascii_lowercase()
223}
224
225fn lease_path(home: &Path, cache_dir: &Path) -> PathBuf {
226    leases_dir(home).join(format!("{}.json", slug(cache_dir)))
227}
228
229fn identity_path(home: &Path, cache_dir: &Path) -> PathBuf {
230    leases_dir(home).join(format!("{}.identity.json", slug(cache_dir)))
231}
232
233fn catalog_path(home: &Path, cache_dir: &Path) -> PathBuf {
234    leases_dir(home).join(format!("{}.catalog.json", slug(cache_dir)))
235}
236
237/// A cache directory magi has leased before, remembered past the point its
238/// lease file is gone.
239///
240/// A lease file's whole reason to exist is contention, and [`Guard::release`]
241/// deletes it the moment nobody holds it — correctly, since a stale lock file
242/// left lying around is exactly the bug this module exists to avoid repeating
243/// (see the module docs on the queue's own `.lock` files). But that means a
244/// cache directory nobody is actively borrowing is, from a lease file alone,
245/// indistinguishable from one magi never touched: both read as
246/// [`Status::Free`]. `magi-land6`, `magi-land7` and `magi-landtimedout` — idle
247/// Cargo caches worth tens of gigabytes each, found only by a manual sweep of
248/// `Temp` during the 2026-09-12 recovery — are exactly this: real, orphaned,
249/// magi-managed caches that [`inventory`] could not see because nothing was
250/// still holding them. This record is what closes that gap: written on every
251/// successful acquire, never deleted by [`Guard`], so a cleanup surface can
252/// still find and size a cache days after the last borrower let go of it.
253#[derive(Debug, Clone, Serialize, Deserialize)]
254struct CatalogRecord {
255    cache_dir: String,
256    last_owner: Owner,
257    last_used_at: Timestamp,
258}
259
260/// Remember `cache_dir` as one magi has leased, for [`inventory`] to find
261/// after the lease itself is gone. Best-effort: a write that fails costs a
262/// future cleanup listing one entry, never the acquire this rides along
263/// with — an operator missing an inventory row is a much smaller problem than
264/// a build that failed to get its cache.
265fn record_catalog(home: &Path, cache_dir: &Path, owner: &Owner) {
266    let path = catalog_path(home, cache_dir);
267    let record = CatalogRecord {
268        cache_dir: cache_dir.display().to_string(),
269        last_owner: owner.clone(),
270        last_used_at: Timestamp::now(),
271    };
272    let Ok(body) = serde_json::to_string_pretty(&record) else {
273        return;
274    };
275    let tmp = path.with_extension("json.tmp");
276    if std::fs::write(&tmp, &body).is_ok() {
277        let _ = std::fs::rename(&tmp, &path);
278    }
279}
280
281/// Read whatever JSON is at `path` as a [`CatalogRecord`], or `None` when it
282/// is missing or does not parse — an unreadable catalog entry costs
283/// [`inventory`] one row, not a wrong answer about who owns anything, since
284/// ownership is always decided from the lease file, never the catalog.
285fn read_catalog(path: &Path) -> Option<CatalogRecord> {
286    let body = std::fs::read_to_string(path).ok()?;
287    serde_json::from_str(&body).ok()
288}
289
290/// Read whatever JSON is at `path` as a [`LeaseFile`], or `None` when it is
291/// missing or does not parse.
292fn read_lease(path: &Path) -> Option<LeaseFile> {
293    let body = std::fs::read_to_string(path).ok()?;
294    serde_json::from_str(&body).ok()
295}
296
297/// Best-effort read of just the `cache_dir` field, for [`inventory`] to
298/// report a path even when the rest of the record — the owner — does not
299/// parse. A corrupt lease is still evidence of *which* directory is in a
300/// state nobody can vouch for.
301fn peek_cache_dir(path: &Path) -> Option<String> {
302    let body = std::fs::read_to_string(path).ok()?;
303    let value: serde_json::Value = serde_json::from_str(&body).ok()?;
304    value
305        .get("cache_dir")
306        .and_then(|v| v.as_str())
307        .map(str::to_owned)
308}
309
310/// Classify the lease at `path`, using the real process-liveness query.
311fn classify(path: &Path) -> Status {
312    classify_with(path, proc::pid_alive)
313}
314
315/// [`classify`] with its process-liveness query supplied by the caller —
316/// mirrors [`crate::daemon::sweep_stale_claims_with`], which exists for the
317/// identical reason: a real "confirmed dead" pid cannot be produced portably
318/// from a test (an out-of-range value reads as *unavailable*, not dead, to
319/// `tasklist`/`kill -0`, and the conservative policy those already apply -
320/// correctly - treats an unavailable query as alive). Production code always
321/// goes through [`classify`]; this is what a test calls directly to assert
322/// the classification logic against an injected answer instead.
323fn classify_with<F: Fn(u32) -> bool>(path: &Path, alive: F) -> Status {
324    if !path.exists() {
325        return Status::Free;
326    }
327    let Some(lease) = read_lease(path) else {
328        return Status::Unknown;
329    };
330    let this_process = std::process::id();
331    if lease.owner.pid == this_process || alive(lease.owner.pid) {
332        Status::Active(lease.owner)
333    } else {
334        Status::Stale(lease.owner)
335    }
336}
337
338/// Write a brand-new lease file, atomically — `create_new` refuses to
339/// overwrite an existing one, exactly like [`crate::queue::Queue::claim`]'s
340/// task lock, which this mirrors on purpose rather than inventing a second
341/// exclusion primitive in the same codebase.
342fn write_new(
343    path: &Path,
344    cache_dir: &Path,
345    owner: &Owner,
346    retry: crate::lock_file::Retry,
347) -> std::io::Result<()> {
348    write_lease(retry.create(path)?, cache_dir, owner)
349}
350
351fn write_lease(mut f: std::fs::File, cache_dir: &Path, owner: &Owner) -> std::io::Result<()> {
352    use std::io::Write as _;
353    let lease = LeaseFile {
354        cache_dir: cache_dir.display().to_string(),
355        owner: owner.clone(),
356        acquired_at: Timestamp::now(),
357    };
358    let body = serde_json::to_string_pretty(&lease).unwrap_or_default();
359    f.write_all(body.as_bytes())?;
360    Ok(())
361}
362
363/// What [`try_acquire`] returned.
364pub enum AcquireOutcome {
365    /// The lease is now held by the caller.
366    Acquired(Guard),
367    /// Somebody else has it, or its state could not be trusted.
368    Busy(Busy),
369}
370
371/// Take the lease for `cache_dir` if nobody live holds it, reclaiming a
372/// stale one first. One attempt — a caller that wants to wait uses
373/// [`wait_for`], which is this in a loop bounded by a budget.
374pub fn try_acquire(home: &Path, cache_dir: &Path, owner: &Owner) -> Result<AcquireOutcome> {
375    let Ok(_outputs) = crate::retention::OutputLease::cache(home, cache_dir, true) else {
376        return Ok(AcquireOutcome::Busy(Busy::Outputs));
377    };
378    try_acquire_with(home, cache_dir, owner, proc::pid_alive)
379}
380
381/// Take both cache ownership and exclusive output ownership for a destructive
382/// maintenance operation. Refuses while process cleanup still owns descendants.
383pub fn try_acquire_maintenance(
384    home: &Path,
385    cache_dir: &Path,
386    owner: &Owner,
387) -> Result<AcquireOutcome> {
388    crate::build_target::check_prune(home, cache_dir)?;
389    let Ok(outputs) = crate::retention::OutputLease::cache(home, cache_dir, true) else {
390        return Ok(AcquireOutcome::Busy(Busy::Outputs));
391    };
392    match try_acquire_with(home, cache_dir, owner, proc::pid_alive)? {
393        AcquireOutcome::Acquired(mut guard) => {
394            guard.outputs = Some(outputs);
395            Ok(AcquireOutcome::Acquired(guard))
396        }
397        busy => Ok(busy),
398    }
399}
400
401/// [`try_acquire`] with its process-liveness query supplied by the caller —
402/// see [`classify_with`] for why this split exists.
403fn try_acquire_with<F: Fn(u32) -> bool + Copy>(
404    home: &Path,
405    cache_dir: &Path,
406    owner: &Owner,
407    alive: F,
408) -> Result<AcquireOutcome> {
409    try_acquire_before(
410        home,
411        cache_dir,
412        owner,
413        alive,
414        crate::lock_file::Retry::new(None),
415    )
416}
417
418fn try_acquire_before<F: Fn(u32) -> bool + Copy>(
419    home: &Path,
420    cache_dir: &Path,
421    owner: &Owner,
422    alive: F,
423    retry: crate::lock_file::Retry,
424) -> Result<AcquireOutcome> {
425    let dir = leases_dir(home);
426    std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
427    let path = dir.join(format!("{}.json", slug(cache_dir)));
428
429    // Two attempts: the first is the common case (free, or held by someone
430    // live); the second only runs after reclaiming a confirmed-stale lease,
431    // so this can never loop more than once per call — a caller that keeps
432    // losing the race to genuinely live contenders is exactly what `Busy`
433    // reports back, not something this function spins on.
434    for _ in 0..2 {
435        let result = write_new(&path, cache_dir, owner, retry);
436        if let Some(outcome) = acquire_result(home, &path, cache_dir, owner, alive, result)? {
437            return Ok(outcome);
438        }
439    }
440    Ok(AcquireOutcome::Busy(Busy::Contended))
441}
442
443// Shared stale/conflict handling; only opening the file is retried.
444fn acquire_result(
445    home: &Path,
446    path: &Path,
447    cache_dir: &Path,
448    owner: &Owner,
449    alive: impl Fn(u32) -> bool + Copy,
450    result: std::io::Result<()>,
451) -> Result<Option<AcquireOutcome>> {
452    match result {
453        Ok(()) => {
454            record_catalog(home, cache_dir, owner);
455            return Ok(Some(AcquireOutcome::Acquired(Guard::new(path.to_owned()))));
456        }
457        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
458        Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
459    }
460    match classify_with(path, alive) {
461        Status::Free => {}
462        Status::Stale(_) => {
463            let _ = std::fs::remove_file(path);
464        }
465        Status::Active(o) => return Ok(Some(AcquireOutcome::Busy(Busy::Active(o)))),
466        Status::Unknown => return Ok(Some(AcquireOutcome::Busy(Busy::Unknown))),
467    }
468    Ok(None)
469}
470
471async fn try_acquire_async(
472    home: &Path,
473    cache_dir: &Path,
474    owner: &Owner,
475    retry: crate::lock_file::Retry,
476    cancel: &(dyn Fn() -> bool + Sync),
477) -> Result<Option<AcquireOutcome>> {
478    let Ok(_outputs) = crate::retention::OutputLease::cache(home, cache_dir, true) else {
479        return Ok(Some(AcquireOutcome::Busy(Busy::Outputs)));
480    };
481    let dir = leases_dir(home);
482    std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
483    let path = dir.join(format!("{}.json", slug(cache_dir)));
484    for _ in 0..2 {
485        let opened = retry
486            .run_async_unless(
487                || {
488                    std::fs::OpenOptions::new()
489                        .write(true)
490                        .create_new(true)
491                        .open(&path)
492                },
493                cancel,
494            )
495            .await;
496        let result = match opened {
497            Ok(Some(file)) => write_lease(file, cache_dir, owner),
498            Ok(None) => return Ok(None),
499            Err(error) => Err(error),
500        };
501        if let Some(outcome) =
502            acquire_result(home, &path, cache_dir, owner, proc::pid_alive, result)?
503        {
504            return Ok(Some(outcome));
505        }
506    }
507    Ok(Some(AcquireOutcome::Busy(Busy::Contended)))
508}
509
510/// Is `cache_dir` in use right now — held by a live owner, or in a state
511/// nobody can vouch for? The conservative half of the janitor's prune guard:
512/// [`Status::Unknown`] refuses exactly like [`Status::Active`], because a
513/// lease this process cannot read is not evidence the directory is free.
514#[must_use]
515pub fn in_use(home: &Path, cache_dir: &Path) -> bool {
516    let path = lease_path(home, cache_dir);
517    matches!(classify(&path), Status::Active(_) | Status::Unknown)
518        || crate::retention::OutputLease::cache(home, cache_dir, true).is_err()
519}
520
521/// Prefix of a resource machine hold. `triage` uses it when rechecking
522/// availability; the prefix alone does not establish an elapsed timeout.
523pub const RESOURCE_HOLD: &str = "[resource] ";
524
525/// A proven elapsed cache wait, distinct from cancellation and I/O errors.
526#[derive(Debug)]
527pub struct WaitTimeout(pub String);
528
529impl std::fmt::Display for WaitTimeout {
530    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531        f.write_str(&self.0)
532    }
533}
534
535impl std::error::Error for WaitTimeout {}
536
537/// Acquire the lease for `cache_dir`, waiting out contention rather than
538/// failing on the first busy owner — but never past `budget`, and the wait
539/// comes out of that same budget rather than a second, unbounded one. A
540/// caller already has a node timeout; this is that timeout, not a new clock
541/// next to it, which is what keeps a wait from becoming the "無期限待機"
542/// AGENTS.md's own build-cache section warns is never acceptable. The error
543/// on timeout names who is still holding it, for the event this gets logged
544/// into.
545pub async fn wait_for(
546    home: &Path,
547    cache_dir: &Path,
548    owner: &Owner,
549    budget: Duration,
550    poll: Duration,
551) -> Result<Guard> {
552    match wait_for_unless(home, cache_dir, owner, budget, poll, &|| false).await? {
553        Some(g) => Ok(g),
554        None => bail!("the wait for the build cache was cancelled"),
555    }
556}
557
558/// [`wait_for`] that also gives up, with `Ok(None)`, as soon as `cancel`
559/// returns true. `cancel` is checked at each contention poll and before and
560/// after delete-pending sleeps, so a park request does not wait out the budget. The
561/// lease is never held on that path: nothing was acquired.
562pub async fn wait_for_unless(
563    home: &Path,
564    cache_dir: &Path,
565    owner: &Owner,
566    budget: Duration,
567    poll: Duration,
568    cancel: &(dyn Fn() -> bool + Sync),
569) -> Result<Option<Guard>> {
570    let start = std::time::Instant::now();
571    // Delete-pending retries share the whole resource wait budget; the helper
572    // checks cancellation before and after each retry sleep.
573    let retry = crate::lock_file::Retry::new(Some(start + budget));
574    loop {
575        let Some(acquired) = try_acquire_async(home, cache_dir, owner, retry, cancel).await? else {
576            return Ok(None);
577        };
578        match acquired {
579            AcquireOutcome::Acquired(g) => return Ok(Some(g)),
580            AcquireOutcome::Busy(busy) => {
581                if cancel() {
582                    return Ok(None);
583                }
584                let elapsed = start.elapsed();
585                if elapsed >= budget {
586                    return Err(WaitTimeout(format!(
587                        "timed out after {}s waiting for the build cache at {} ({})",
588                        budget.as_secs(),
589                        cache_dir.display(),
590                        busy.describe()
591                    ))
592                    .into());
593                }
594                tokio::time::sleep(poll.min(budget - elapsed)).await;
595            }
596        }
597    }
598}
599
600/// One cache directory's state, for `a0fc`'s capacity/cleanup inventory (and
601/// `magi cache show`, eventually). Every lease file on disk is reported —
602/// including ones this process itself does not want to touch — because the
603/// question this answers is "what is registered right now", not "what can I
604/// safely act on".
605#[derive(Debug, Clone)]
606pub struct Entry {
607    /// The literal cache path this entry describes.
608    pub cache_dir: String,
609    /// What [`classify`] made of the lease registered against it.
610    pub status: EntryStatus,
611}
612
613/// [`Entry::status`]'s possible values.
614#[derive(Debug, Clone)]
615pub enum EntryStatus {
616    /// Held by a confirmed-live owner.
617    Active(Owner),
618    /// Present, but the owner is confirmed gone — safe to reclaim.
619    Stale(Owner),
620    /// Present, but unreadable — never assume safe to reclaim.
621    Unknown,
622    /// No live lease right now — the borrower released it cleanly — but the
623    /// catalog remembers this path was leased before, by the owner named
624    /// here. Safe to reclaim: nothing holds it, and nothing has to guess that
625    /// from the lease file's mere absence, which is indistinguishable from a
626    /// path magi never touched (see [`CatalogRecord`]'s doc).
627    Idle(Owner),
628    /// Tools or their independent cleanup owner retain an OS output lease.
629    /// The attached owner is the last recorded cache borrower.
630    Outputs(Owner),
631}
632
633/// Every cache directory magi knows about under `home`, whether or not
634/// anything holds it right now. A lease file reports the current borrower;
635/// once released it is gone (by design — see [`Guard::release`]), so a
636/// directory nobody is borrowing is reported from the catalog instead,
637/// carrying its last known owner rather than nothing at all. There is
638/// nothing here for a directory this process has never leased: `inventory`
639/// answers "what has magi registered", not "what looks like a build cache".
640#[must_use]
641pub fn inventory(home: &Path) -> Vec<Entry> {
642    let mut entries = inventory_with(home, proc::pid_alive);
643    for entry in &mut entries {
644        if let EntryStatus::Idle(owner) | EntryStatus::Stale(owner) = &entry.status
645            && crate::retention::OutputLease::cache(home, Path::new(&entry.cache_dir), true)
646                .is_err()
647        {
648            entry.status = EntryStatus::Outputs(owner.clone());
649        }
650    }
651    entries
652}
653
654/// [`inventory`] with its process-liveness query supplied by the caller —
655/// see [`classify_with`] for why this split exists.
656fn inventory_with<F: Fn(u32) -> bool + Copy>(home: &Path, alive: F) -> Vec<Entry> {
657    let dir = leases_dir(home);
658    let Ok(rd) = std::fs::read_dir(&dir) else {
659        return Vec::new();
660    };
661    let mut out = Vec::new();
662    for entry in rd.flatten() {
663        let path = entry.path();
664        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
665            continue;
666        };
667        if !name.ends_with(".json")
668            || name.ends_with(".identity.json")
669            || name.ends_with(".catalog.json")
670        {
671            continue;
672        }
673        let status = match classify_with(&path, alive) {
674            Status::Free => continue,
675            Status::Active(o) => EntryStatus::Active(o),
676            Status::Stale(o) => EntryStatus::Stale(o),
677            Status::Unknown => EntryStatus::Unknown,
678        };
679        // A lease so corrupted that not even its `cache_dir` field can be
680        // read still has to be findable: the lease file's own name is a
681        // one-way slug of the path it was for, so the file itself - not the
682        // path it can no longer name - is what a human or `a0fc` gets
683        // pointed at.
684        let cache_dir = peek_cache_dir(&path)
685            .unwrap_or_else(|| format!("(unreadable lease file: {})", path.display()));
686        out.push(Entry { cache_dir, status });
687    }
688
689    // Second pass: a cache directory whose lease was cleanly released is
690    // still registered, in the catalog, as long as its lease file has not
691    // been reacquired since. Skip anything the first pass already reported —
692    // a live or stale lease always outranks a catalog record, which only
693    // ever describes the *last* borrower, not the current one.
694    if let Ok(rd) = std::fs::read_dir(&dir) {
695        for entry in rd.flatten() {
696            let path = entry.path();
697            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
698                continue;
699            };
700            let Some(stem) = name.strip_suffix(".catalog.json") else {
701                continue;
702            };
703            if dir.join(format!("{stem}.json")).exists() {
704                continue;
705            }
706            if let Some(record) = read_catalog(&path) {
707                out.push(Entry {
708                    cache_dir: record.cache_dir,
709                    status: EntryStatus::Idle(record.last_owner),
710                });
711            }
712        }
713    }
714
715    out.sort_by(|a, b| a.cache_dir.cmp(&b.cache_dir));
716    out
717}
718
719/// Prune `cache_dir` to `limit`, but only while holding the lease — a prune
720/// that raced a live build would delete files a compile in flight still
721/// needs, on top of confusing whatever built them about why its own output
722/// vanished. `Ok(None)` when the cache is in use right now; that is not an
723/// error, it is the janitor's next pass catching it once the borrower is
724/// done. Never touches a lease file itself — they live outside `cache_dir`
725/// (see [`leases_dir`]), so [`crate::disk::prune_dir`]'s own sweep can never
726/// reach one.
727pub fn maintenance_prune(
728    home: &Path,
729    cache_dir: &Path,
730    limit: u64,
731) -> Result<Option<crate::disk::Prune>> {
732    maintenance_prune_keeping(home, cache_dir, limit, 0)
733}
734
735/// [`maintenance_prune`] that never takes the cache below `keep` bytes
736/// ([`crate::disk::prune_dir_keeping`]): the reserve pressure collection keeps
737/// of a build cache while free space is at or above the admission floor and
738/// below the collection threshold. The
739/// inventory the bound is checked against is the one taken here, under the
740/// lease and the Cargo locks.
741pub fn maintenance_prune_keeping(
742    home: &Path,
743    cache_dir: &Path,
744    limit: u64,
745    keep: u64,
746) -> Result<Option<crate::disk::Prune>> {
747    let owner = Owner {
748        run: "maintenance".to_owned(),
749        node: "prune".to_owned(),
750        seat: "janitor".to_owned(),
751        pid: std::process::id(),
752        worktree: String::new(),
753        head: String::new(),
754    };
755    match try_acquire_maintenance(home, cache_dir, &owner)? {
756        AcquireOutcome::Busy(_) => Ok(None),
757        AcquireOutcome::Acquired(guard) => {
758            let _cargo = crate::retention::cargo_locks(cache_dir)?;
759            let result = crate::disk::prune_dir_keeping(cache_dir, limit, keep)?;
760            guard.release();
761            Ok(Some(result))
762        }
763    }
764}
765
766/// The source a build against a cache directory was last known to come from.
767/// Compared by [`needs_refresh`] on every acquire, so a cache directory that
768/// only ever sees one worktree/head pair never pays a clean it does not need.
769#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
770pub struct Identity {
771    /// The worktree the build ran from.
772    pub worktree: String,
773    /// The commit it built.
774    pub head: String,
775}
776
777impl Identity {
778    /// Build an identity from a worktree path and the commit it is at.
779    #[must_use]
780    pub fn new(worktree: &Path, head: &str) -> Identity {
781        Identity {
782            worktree: worktree.display().to_string(),
783            head: head.to_owned(),
784        }
785    }
786}
787
788/// Has the source building against `cache_dir` changed since the last record?
789/// True (needs a refresh) whenever nothing was ever recorded — the
790/// conservative default for a cache directory this process has not tracked
791/// before.
792#[must_use]
793pub fn needs_refresh(home: &Path, cache_dir: &Path, current: &Identity) -> bool {
794    let path = identity_path(home, cache_dir);
795    let Ok(body) = std::fs::read_to_string(path) else {
796        return true;
797    };
798    match serde_json::from_str::<Identity>(&body) {
799        Ok(recorded) => &recorded != current,
800        Err(_) => true,
801    }
802}
803
804/// Persist `identity` as the last known source for `cache_dir`.
805pub fn record_identity(home: &Path, cache_dir: &Path, identity: &Identity) -> Result<()> {
806    let path = identity_path(home, cache_dir);
807    if let Some(parent) = path.parent() {
808        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
809    }
810    let body = serde_json::to_string_pretty(identity).context("serialize cache identity")?;
811    let tmp = path.with_extension("json.tmp");
812    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
813    std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
814    Ok(())
815}
816
817/// Forget the recorded source identity for `cache_dir`, so the next
818/// [`ensure_fresh`] call cannot skip its clean on the strength of a stale
819/// match.
820///
821/// For a builder that does not itself have one coherent (worktree, head) to
822/// record - an implement or fix wave, where several different worktrees
823/// deliberately share the cache concurrently - there is nothing correct to
824/// write in place of the old identity. Removing the record is still correct:
825/// it costs the next tracked caller ([`ensure_fresh`] at `e2e`/`gate`) one
826/// clean it might not have strictly needed, in exchange for never trusting a
827/// match against a write this module never observed. Best-effort: a stale
828/// record surviving a failed removal is no worse than the record this
829/// replaces.
830pub fn invalidate_identity(home: &Path, cache_dir: &Path) {
831    let _ = std::fs::remove_file(identity_path(home, cache_dir));
832}
833
834/// Parse `cargo metadata --no-deps`'s JSON for the names of packages defined
835/// in the workspace itself — never a dependency, which is exactly the
836/// distinction that keeps a freshness fix from also discarding a downloaded
837/// crate's compiled artifacts on every worktree switch. Pure, so the parse
838/// is tested against fixture text without a `cargo` on the test machine.
839#[must_use]
840pub fn parse_workspace_package_names(metadata_json: &str) -> Vec<String> {
841    let Ok(value) = serde_json::from_str::<serde_json::Value>(metadata_json) else {
842        return Vec::new();
843    };
844    value
845        .get("packages")
846        .and_then(|p| p.as_array())
847        .map(|packages| {
848            packages
849                .iter()
850                .filter_map(|p| p.get("name").and_then(|n| n.as_str()))
851                .map(str::to_owned)
852                .collect()
853        })
854        .unwrap_or_default()
855}
856
857/// Every `--manifest-path` the given verify commands pass, in order of first
858/// appearance, without duplicates. Understands `--manifest-path X` and
859/// `--manifest-path=X`, with `'` / `"` quoting. Pure.
860#[must_use]
861pub fn extract_manifest_paths(commands: &[String]) -> Vec<PathBuf> {
862    const KEY: &str = "--manifest-path";
863    let mut out: Vec<PathBuf> = Vec::new();
864    for command in commands {
865        let mut rest = command.as_str();
866        while let Some(at) = rest.find(KEY) {
867            rest = &rest[at + KEY.len()..];
868            let value = if let Some(r) = rest.strip_prefix('=') {
869                r
870            } else if rest.starts_with(char::is_whitespace) {
871                rest.trim_start()
872            } else {
873                continue;
874            };
875            let value = if let Some(s) = value.strip_prefix('\'') {
876                s.split('\'').next().unwrap_or("")
877            } else if let Some(s) = value.strip_prefix('"') {
878                s.split('"').next().unwrap_or("")
879            } else {
880                let end = value.find(char::is_whitespace).unwrap_or(value.len());
881                &value[..end]
882            };
883            if !value.is_empty() {
884                let path = PathBuf::from(value);
885                if !out.contains(&path) {
886                    out.push(path);
887                }
888            }
889        }
890    }
891    out
892}
893
894/// Where cargo is asked about the workspace's own packages.
895#[derive(Debug, Clone, PartialEq, Eq)]
896pub enum Target {
897    /// The worktree root, as before (no `--manifest-path`).
898    Root,
899    /// A manifest named by a verify command, resolved against the worktree.
900    Manifest(PathBuf),
901}
902
903/// Decide which manifests `cargo metadata` / `cargo clean -p` run against: the
904/// root when it has a `Cargo.toml`, plus every verify-named manifest that
905/// exists. Nothing at all is a valid answer (no crate, or one the commands do
906/// not name). Pure apart from `exists`.
907fn plan_targets(
908    worktree: &Path,
909    manifests: &[PathBuf],
910    exists: impl Fn(&Path) -> Result<bool>,
911) -> Result<Vec<Target>> {
912    let mut targets = Vec::new();
913    if exists(&worktree.join("Cargo.toml"))? {
914        targets.push(Target::Root);
915    }
916    for m in manifests {
917        let full = if m.is_absolute() {
918            m.clone()
919        } else {
920            worktree.join(m)
921        };
922        if exists(&full)? {
923            targets.push(Target::Manifest(full));
924        } else {
925            tracing::warn!(
926                manifest = %m.display(),
927                "build cache: --manifest-path from a verify command does not exist; skipped"
928            );
929        }
930    }
931    Ok(targets)
932}
933
934/// Existence of a file: only NotFound counts as "no"; any other I/O error
935/// propagates so an unreadable tree is never mistaken for an empty one.
936fn file_exists(path: &Path) -> Result<bool> {
937    match std::fs::metadata(path) {
938        Ok(m) => Ok(m.is_file()),
939        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
940        Err(e) => Err(e).with_context(|| format!("stat {}", path.display())),
941    }
942}
943
944/// Selectively invalidate the workspace's own compiled artifacts in
945/// `cache_dir` — `cargo clean -p <name> --target-dir <cache_dir>` for every
946/// package `cargo metadata` reports as local to `worktree`, never a bare
947/// `cargo clean` (which would throw away every dependency's compile too).
948/// Returns `None` when there is no manifest to ask (no cargo is spawned).
949/// Real subprocess execution: never called from a test, only from
950/// [`ensure_fresh`] in the running binary.
951fn refresh_stale_packages(
952    worktree: &Path,
953    cache_dir: &Path,
954    manifests: &[PathBuf],
955    isolated: bool,
956) -> Result<Option<Vec<String>>> {
957    let targets = plan_targets(worktree, manifests, file_exists)?;
958    if targets.is_empty() {
959        return Ok(None);
960    }
961    let mut all = Vec::new();
962    let mut failed = Vec::new();
963    for target in &targets {
964        let manifest_arg = match target {
965            Target::Root => None,
966            Target::Manifest(m) => Some(m),
967        };
968        let mut cmd = if isolated {
969            crate::build_target::command::cargo(cache_dir)?
970        } else {
971            std::process::Command::new("cargo")
972        };
973        if !isolated {
974            crate::build_target::command::clear_std(&mut cmd)?;
975        }
976        cmd.args(["metadata", "--no-deps", "--format-version", "1"]);
977        if let Some(m) = manifest_arg {
978            cmd.arg("--manifest-path").arg(m);
979        }
980        let meta = cmd
981            .current_dir(worktree)
982            .quiet()
983            .output()
984            .context("run `cargo metadata`")?;
985        if !meta.status.success() {
986            bail!(
987                "cargo metadata failed: {}",
988                String::from_utf8_lossy(&meta.stderr)
989            );
990        }
991        let names = parse_workspace_package_names(&String::from_utf8_lossy(&meta.stdout));
992        for name in &names {
993            let mut clean = if isolated {
994                crate::build_target::command::cargo(cache_dir)?
995            } else {
996                std::process::Command::new("cargo")
997            };
998            clean.arg("clean").arg("-p").arg(name);
999            if let Some(m) = manifest_arg {
1000                clean.arg("--manifest-path").arg(m);
1001            }
1002            if !isolated {
1003                crate::build_target::command::clear_std(&mut clean)?;
1004                clean.arg("--target-dir").arg(cache_dir);
1005            }
1006            let out = clean
1007                .current_dir(worktree)
1008                .quiet()
1009                .output()
1010                .with_context(|| format!("cargo clean -p {name}"))?;
1011            if !out.status.success() {
1012                // A failure here — a Windows test executable still holding its
1013                // own file open is the case the evidence log records — means the
1014                // stale artifact this was meant to remove may still be sitting
1015                // in `cache_dir`. Collecting it rather than only warning is what
1016                // lets `ensure_fresh` refuse to record the new identity: the
1017                // next reuse must not be told this cache is confirmed to match
1018                // `identity` when a piece of the *previous* one could not be
1019                // proven gone.
1020                failed.push(format!(
1021                    "{name}: {}",
1022                    String::from_utf8_lossy(&out.stderr).trim()
1023                ));
1024            }
1025        }
1026        for n in names {
1027            if !all.contains(&n) {
1028                all.push(n);
1029            }
1030        }
1031    }
1032    if !failed.is_empty() {
1033        bail!(
1034            "cargo clean -p failed for {} package(s): {}",
1035            failed.len(),
1036            failed.join("; ")
1037        );
1038    }
1039    Ok(Some(all))
1040}
1041
1042/// What cargo itself writes into a target directory it creates.
1043const CACHEDIR_TAG: &str = "Signature: 8a477f597d28d172789f06886806bc55\n\
1044# This file is a cache directory tag created by cargo.\n\
1045# For information about cache directory tags see https://bford.info/cachedir/\n";
1046
1047/// Recreate `CACHEDIR.TAG` in a cargo target directory that lost it, so
1048/// `cargo clean -p` stops refusing. Returns whether a tag was written.
1049///
1050/// Heals caches an older prune already broke. Safe because the caller holds the
1051/// lease, `cache_dir` is the directory magi itself handed cargo as its target,
1052/// and it is only done when `.rustc_info.json` proves cargo has built there — a
1053/// misconfigured path is never dressed up as a cargo target. An existing tag is
1054/// never touched (`create_new`), and a missing directory is left for cargo.
1055fn restore_cachedir_tag(cache_dir: &Path) -> Result<bool> {
1056    use std::io::Write as _;
1057    if !cache_dir.is_dir() || !cache_dir.join(".rustc_info.json").is_file() {
1058        return Ok(false);
1059    }
1060    let tag = cache_dir.join("CACHEDIR.TAG");
1061    match std::fs::OpenOptions::new()
1062        .write(true)
1063        .create_new(true)
1064        .open(&tag)
1065    {
1066        Ok(mut f) => {
1067            f.write_all(CACHEDIR_TAG.as_bytes())
1068                .with_context(|| format!("write {}", tag.display()))?;
1069            Ok(true)
1070        }
1071        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
1072        Err(e) => Err(e).with_context(|| format!("create {}", tag.display())),
1073    }
1074}
1075
1076/// Guarantee that a build against `cache_dir` from `(worktree, head)` never
1077/// silently reuses another source's compiled output: clean the workspace's
1078/// own packages out of the cache when the recorded identity disagrees, then
1079/// record the new one. A no-op — no subprocess spawned — when the identity
1080/// already matches, which is the common case once a cache directory settles
1081/// on one worktree for a while.
1082///
1083/// Called with the lease already held: this is a mutation of the cache
1084/// directory's contents, and it must never race a concurrent build the same
1085/// way a plain `cargo clean` run by hand would not.
1086pub fn ensure_fresh(
1087    home: &Path,
1088    cache_dir: &Path,
1089    identity: &Identity,
1090    manifests: &[PathBuf],
1091) -> Result<()> {
1092    ensure_fresh_with(home, cache_dir, identity, manifests, false)
1093}
1094
1095pub(crate) fn ensure_fresh_with(
1096    home: &Path,
1097    cache_dir: &Path,
1098    identity: &Identity,
1099    manifests: &[PathBuf],
1100    isolated: bool,
1101) -> Result<()> {
1102    match restore_cachedir_tag(cache_dir) {
1103        Ok(true) => tracing::info!(
1104            cache = %cache_dir.display(),
1105            "build cache: restored a missing CACHEDIR.TAG"
1106        ),
1107        Ok(false) => {}
1108        // Not fatal: `cargo clean -p` below reports the real consequence.
1109        Err(e) => tracing::warn!(error = %e, "build cache: could not restore CACHEDIR.TAG"),
1110    }
1111    if needs_refresh(home, cache_dir, identity) {
1112        let worktree = PathBuf::from(&identity.worktree);
1113        match refresh_stale_packages(&worktree, cache_dir, manifests, isolated)? {
1114            Some(cleaned) => tracing::info!(
1115                ?cleaned,
1116                cache = %cache_dir.display(),
1117                "build cache: source identity changed; cleaned the workspace's own packages before reuse"
1118            ),
1119            None => {
1120                // No Cargo.toml at the root and none named by a verify
1121                // command: there is nothing to clean by name, and a crate
1122                // we could not locate may have left stale output behind, so
1123                // the identity is not vouched for either.
1124                tracing::warn!(
1125                    cache = %cache_dir.display(),
1126                    "build cache: no Cargo manifest found for the freshness check; skipping the package clean"
1127                );
1128                invalidate_identity(home, cache_dir);
1129                return Ok(());
1130            }
1131        }
1132    }
1133    record_identity(home, cache_dir, identity)
1134}
1135
1136#[cfg(test)]
1137mod tests {
1138    use super::*;
1139
1140    fn owner(pid: u32) -> Owner {
1141        Owner {
1142            run: "r1".to_owned(),
1143            node: "gate".to_owned(),
1144            seat: "gate".to_owned(),
1145            pid,
1146            worktree: "/w".to_owned(),
1147            head: "deadbeef".to_owned(),
1148        }
1149    }
1150
1151    #[test]
1152    fn a_missing_cachedir_tag_is_restored_only_for_a_cargo_target() {
1153        let t = tempfile::TempDir::new().expect("temp");
1154        let cache = t.path().join("cache");
1155        assert!(!restore_cachedir_tag(&cache).expect("missing dir"));
1156        assert!(!cache.exists(), "a missing directory is left for cargo");
1157
1158        std::fs::create_dir_all(&cache).expect("mkdir");
1159        assert!(!restore_cachedir_tag(&cache).expect("no rustc info"));
1160        assert!(!cache.join("CACHEDIR.TAG").exists());
1161
1162        std::fs::write(cache.join(".rustc_info.json"), "{}").expect("info");
1163        assert!(restore_cachedir_tag(&cache).expect("restore"));
1164        let body = std::fs::read_to_string(cache.join("CACHEDIR.TAG")).expect("tag");
1165        assert_eq!(
1166            body.lines().next(),
1167            Some("Signature: 8a477f597d28d172789f06886806bc55")
1168        );
1169
1170        std::fs::write(cache.join("CACHEDIR.TAG"), "custom").expect("custom");
1171        assert!(!restore_cachedir_tag(&cache).expect("existing"));
1172        assert_eq!(
1173            std::fs::read_to_string(cache.join("CACHEDIR.TAG")).expect("tag"),
1174            "custom"
1175        );
1176    }
1177
1178    #[test]
1179    fn an_uncontended_lease_is_acquired_and_freed_on_release() {
1180        let home = tempfile::TempDir::new().expect("temp");
1181        let cache = home.path().join("cache");
1182        let this = std::process::id();
1183        match try_acquire(home.path(), &cache, &owner(this)).expect("acquire") {
1184            AcquireOutcome::Acquired(g) => {
1185                assert!(in_use(home.path(), &cache), "held while the guard lives");
1186                g.release();
1187            }
1188            AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1189        }
1190        assert!(!in_use(home.path(), &cache), "freed after release");
1191    }
1192
1193    #[test]
1194    fn a_lease_held_by_a_live_pid_is_reported_active_and_refuses_a_second_acquire() {
1195        let home = tempfile::TempDir::new().expect("temp");
1196        let cache = home.path().join("cache");
1197        let this = std::process::id();
1198        // Acquire as one owner, then try again as a different one — same
1199        // live pid (this test process), different run/seat, which is exactly
1200        // "another owner, still alive" without needing to fork a process.
1201        let _first =
1202            try_acquire(home.path(), &cache, &owner(this)).expect("first acquire succeeds");
1203        let mut second_owner = owner(this);
1204        second_owner.run = "r2".to_owned();
1205        match try_acquire(home.path(), &cache, &second_owner).expect("no io error") {
1206            AcquireOutcome::Busy(Busy::Active(held_by)) => assert_eq!(held_by.run, "r1"),
1207            other => panic!("expected Busy::Active, got a different outcome: {other:?}"),
1208        }
1209        assert!(in_use(home.path(), &cache));
1210    }
1211
1212    impl std::fmt::Debug for AcquireOutcome {
1213        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1214            match self {
1215                AcquireOutcome::Acquired(_) => write!(f, "Acquired"),
1216                AcquireOutcome::Busy(b) => write!(f, "Busy({b:?})"),
1217            }
1218        }
1219    }
1220
1221    #[test]
1222    fn a_lease_whose_pid_is_gone_is_stale_and_reclaimed_by_the_next_acquirer() {
1223        let home = tempfile::TempDir::new().expect("temp");
1224        let cache = home.path().join("cache");
1225        // Liveness is injected rather than asked of the real OS - a "known
1226        // dead" pid cannot be produced portably (see `classify_with`'s doc):
1227        // an out-of-range value reads as *unavailable* to `tasklist`, not
1228        // dead, and the conservative policy then reports it alive, which is
1229        // exactly what made this test flaky before this fix.
1230        let dead_owner = owner(999_999);
1231        let path = lease_path(home.path(), &cache);
1232        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1233        write_new(
1234            &path,
1235            &cache,
1236            &dead_owner,
1237            crate::lock_file::Retry::new(None),
1238        )
1239        .expect("seed a stale lease");
1240        assert_eq!(
1241            classify_with(&path, |_| false),
1242            Status::Stale(dead_owner.clone())
1243        );
1244
1245        match try_acquire_with(home.path(), &cache, &owner(std::process::id()), |_| false)
1246            .expect("acquire")
1247        {
1248            AcquireOutcome::Acquired(_) => {}
1249            other => panic!("stale lease should have been reclaimed: {other:?}"),
1250        }
1251    }
1252
1253    #[test]
1254    fn an_unreadable_lease_is_unknown_and_never_reclaimed() {
1255        let home = tempfile::TempDir::new().expect("temp");
1256        let cache = home.path().join("cache");
1257        let path = lease_path(home.path(), &cache);
1258        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1259        std::fs::write(&path, b"not json").unwrap();
1260        assert_eq!(classify(&path), Status::Unknown);
1261        assert!(in_use(home.path(), &cache), "unknown counts as in use");
1262        match try_acquire(home.path(), &cache, &owner(std::process::id())).expect("no io error") {
1263            AcquireOutcome::Busy(Busy::Unknown) => {}
1264            other => panic!("expected Busy::Unknown, got {other:?}"),
1265        }
1266    }
1267
1268    #[tokio::test]
1269    async fn waiting_for_a_busy_lease_times_out_within_its_own_budget() {
1270        let home = tempfile::TempDir::new().expect("temp");
1271        let cache = home.path().join("cache");
1272        let _held = try_acquire(home.path(), &cache, &owner(std::process::id()))
1273            .expect("acquire")
1274            .pipe();
1275        let mut waiter = owner(std::process::id());
1276        waiter.run = "r2".to_owned();
1277        let started = std::time::Instant::now();
1278        let err = wait_for(
1279            home.path(),
1280            &cache,
1281            &waiter,
1282            Duration::from_millis(150),
1283            Duration::from_millis(20),
1284        )
1285        .await
1286        .expect_err("still held, must time out");
1287        assert!(started.elapsed() < Duration::from_secs(2), "bounded wait");
1288        assert!(
1289            err.to_string().contains("r1"),
1290            "names the current holder: {err}"
1291        );
1292    }
1293
1294    #[tokio::test]
1295    async fn a_wait_succeeds_as_soon_as_the_lease_is_released() {
1296        let home = tempfile::TempDir::new().expect("temp");
1297        let cache = home.path().join("cache");
1298        let guard =
1299            match try_acquire(home.path(), &cache, &owner(std::process::id())).expect("acquire") {
1300                AcquireOutcome::Acquired(g) => g,
1301                AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1302            };
1303        let home_path = home.path().to_path_buf();
1304        let cache_path = cache.clone();
1305        let mut waiter = owner(std::process::id());
1306        waiter.run = "r2".to_owned();
1307        let wait = tokio::spawn(async move {
1308            wait_for(
1309                &home_path,
1310                &cache_path,
1311                &waiter,
1312                Duration::from_secs(5),
1313                Duration::from_millis(10),
1314            )
1315            .await
1316        });
1317        tokio::time::sleep(Duration::from_millis(50)).await;
1318        guard.release();
1319        let acquired = wait.await.expect("task").expect("acquire after release");
1320        acquired.release();
1321    }
1322
1323    #[test]
1324    fn inventory_reports_active_stale_and_unknown_but_not_free() {
1325        let home = tempfile::TempDir::new().expect("temp");
1326        let active_cache = home.path().join("active");
1327        let stale_cache = home.path().join("stale");
1328        let unknown_cache = home.path().join("unknown");
1329
1330        let _held =
1331            try_acquire(home.path(), &active_cache, &owner(std::process::id())).expect("acquire");
1332        let stale_path = lease_path(home.path(), &stale_cache);
1333        std::fs::create_dir_all(stale_path.parent().unwrap()).unwrap();
1334        write_new(
1335            &stale_path,
1336            &stale_cache,
1337            &owner(999_999),
1338            crate::lock_file::Retry::new(None),
1339        )
1340        .unwrap();
1341        let unknown_path = lease_path(home.path(), &unknown_cache);
1342        std::fs::write(&unknown_path, b"garbage").unwrap();
1343
1344        // Liveness injected as `false` for everyone but this test process -
1345        // see `a_lease_whose_pid_is_gone_is_stale_and_reclaimed_by_the_next_acquirer`
1346        // for why the real OS query cannot portably produce a "confirmed
1347        // dead" answer.
1348        let entries = inventory_with(home.path(), |pid| pid == std::process::id());
1349        assert_eq!(entries.len(), 3, "{entries:?}");
1350        let by_dir = |dir: &Path| {
1351            entries
1352                .iter()
1353                .find(|e| e.cache_dir == dir.display().to_string())
1354                .unwrap_or_else(|| panic!("no entry for {}", dir.display()))
1355        };
1356        assert!(matches!(
1357            by_dir(&active_cache).status,
1358            EntryStatus::Active(_)
1359        ));
1360        assert!(matches!(by_dir(&stale_cache).status, EntryStatus::Stale(_)));
1361        // A lease this corrupted cannot name its own `cache_dir` - the point
1362        // of this third case - so it is found by status instead of by path,
1363        // and its reported path must still point somewhere a human can act
1364        // on: the lease file itself.
1365        let unknown = entries
1366            .iter()
1367            .find(|e| matches!(e.status, EntryStatus::Unknown))
1368            .unwrap_or_else(|| panic!("no Unknown entry: {entries:?}"));
1369        assert!(
1370            unknown
1371                .cache_dir
1372                .contains(&unknown_path.display().to_string()),
1373            "{unknown:?}"
1374        );
1375    }
1376
1377    #[test]
1378    fn a_released_lease_is_reported_idle_from_the_catalog_not_dropped_entirely() {
1379        let home = tempfile::TempDir::new().expect("temp");
1380        let cache = home.path().join("cache");
1381        let this = std::process::id();
1382
1383        match try_acquire(home.path(), &cache, &owner(this)).expect("acquire") {
1384            AcquireOutcome::Acquired(g) => g.release(),
1385            AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1386        }
1387
1388        // The lease file is gone - `in_use` reads this path as free - but the
1389        // catalog written on acquire must still name it as a cache magi once
1390        // leased, exactly the gap the 2026-09-12 recovery evidence found:
1391        // an orphaned cache indistinguishable from one that never existed.
1392        assert!(!in_use(home.path(), &cache));
1393        let entries = inventory_with(home.path(), |pid| pid == this);
1394        let entry = entries
1395            .iter()
1396            .find(|e| e.cache_dir == cache.display().to_string())
1397            .unwrap_or_else(|| panic!("no entry for a released cache: {entries:?}"));
1398        match &entry.status {
1399            EntryStatus::Idle(o) => assert_eq!(o.run, "r1"),
1400            other => panic!("expected Idle, got {other:?}"),
1401        }
1402    }
1403
1404    #[test]
1405    fn reacquiring_a_released_cache_reports_active_not_idle() {
1406        let home = tempfile::TempDir::new().expect("temp");
1407        let cache = home.path().join("cache");
1408        let this = std::process::id();
1409        match try_acquire(home.path(), &cache, &owner(this)).expect("acquire") {
1410            AcquireOutcome::Acquired(g) => g.release(),
1411            AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1412        }
1413        let _held = try_acquire(home.path(), &cache, &owner(this)).expect("reacquire");
1414        let entries = inventory_with(home.path(), |pid| pid == this);
1415        assert_eq!(
1416            entries.len(),
1417            1,
1418            "the catalog row must not duplicate the live lease: {entries:?}"
1419        );
1420        assert!(matches!(entries[0].status, EntryStatus::Active(_)));
1421    }
1422
1423    #[test]
1424    fn maintenance_prune_refuses_a_cache_a_live_owner_holds() {
1425        let home = tempfile::TempDir::new().expect("temp");
1426        let cache = home.path().join("cache");
1427        std::fs::create_dir_all(&cache).unwrap();
1428        std::fs::write(cache.join("big"), vec![0u8; 100]).unwrap();
1429        let _held = try_acquire(home.path(), &cache, &owner(std::process::id())).expect("acquire");
1430
1431        let result = maintenance_prune(home.path(), &cache, 1).expect("no io error");
1432        assert!(
1433            result.is_none(),
1434            "must not prune while a live owner holds it"
1435        );
1436        assert!(cache.join("big").exists(), "nothing was deleted");
1437    }
1438
1439    #[test]
1440    fn maintenance_prune_acts_once_the_cache_is_free_and_releases_after() {
1441        let home = tempfile::TempDir::new().expect("temp");
1442        let cache = home.path().join("cache");
1443        std::fs::create_dir_all(&cache).unwrap();
1444        std::fs::write(cache.join("big"), vec![0u8; 100]).unwrap();
1445
1446        let pruned = maintenance_prune(home.path(), &cache, 1)
1447            .expect("no io error")
1448            .expect("cache was free");
1449        assert!(pruned.freed > 0);
1450        assert!(
1451            !in_use(home.path(), &cache),
1452            "the maintenance lease was released"
1453        );
1454    }
1455
1456    #[test]
1457    fn identity_drift_is_detected_once_and_then_settles() {
1458        let home = tempfile::TempDir::new().expect("temp");
1459        let cache = home.path().join("cache");
1460        let a = Identity {
1461            worktree: "/w/a".to_owned(),
1462            head: "aaaa".to_owned(),
1463        };
1464        let b = Identity {
1465            worktree: "/w/b".to_owned(),
1466            head: "bbbb".to_owned(),
1467        };
1468        assert!(
1469            needs_refresh(home.path(), &cache, &a),
1470            "nothing recorded yet"
1471        );
1472        record_identity(home.path(), &cache, &a).expect("record");
1473        assert!(
1474            !needs_refresh(home.path(), &cache, &a),
1475            "same identity, no refresh needed"
1476        );
1477        assert!(needs_refresh(home.path(), &cache, &b), "different source");
1478        record_identity(home.path(), &cache, &b).expect("record");
1479        assert!(!needs_refresh(home.path(), &cache, &b));
1480    }
1481
1482    #[test]
1483    fn invalidating_forgets_a_recorded_identity_so_the_next_check_refreshes() {
1484        let home = tempfile::TempDir::new().expect("temp");
1485        let cache = home.path().join("cache");
1486        let a = Identity {
1487            worktree: "/w/a".to_owned(),
1488            head: "aaaa".to_owned(),
1489        };
1490        record_identity(home.path(), &cache, &a).expect("record");
1491        assert!(!needs_refresh(home.path(), &cache, &a));
1492
1493        // An untracked writer (an implement/fix wave, which shares the cache
1494        // across several worktrees at once and so has no single identity of
1495        // its own to record) touched the cache in between; the next tracked
1496        // caller must not trust the old match anymore.
1497        invalidate_identity(home.path(), &cache);
1498        assert!(
1499            needs_refresh(home.path(), &cache, &a),
1500            "invalidation must not be skippable by asking about the same identity again"
1501        );
1502
1503        // Invalidating a cache directory nothing ever recorded is a no-op,
1504        // not an error.
1505        invalidate_identity(home.path(), &home.path().join("never-recorded"));
1506    }
1507
1508    #[test]
1509    fn workspace_package_names_are_read_from_cargo_metadata_json() {
1510        let fixture = r#"{
1511            "packages": [
1512                {"name": "magi", "version": "0.1.0"},
1513                {"name": "magi-cli", "version": "0.1.0"}
1514            ],
1515            "workspace_members": []
1516        }"#;
1517        let mut names = parse_workspace_package_names(fixture);
1518        names.sort();
1519        assert_eq!(names, vec!["magi".to_owned(), "magi-cli".to_owned()]);
1520        assert_eq!(
1521            parse_workspace_package_names("not json"),
1522            Vec::<String>::new()
1523        );
1524        assert_eq!(parse_workspace_package_names("{}"), Vec::<String>::new());
1525    }
1526
1527    #[test]
1528    fn slugs_are_stable_and_filesystem_safe() {
1529        let a = slug(Path::new(r"C:\Users\op\Temp\magi-target"));
1530        let b = slug(Path::new(r"C:\Users\op\Temp\magi-target"));
1531        assert_eq!(a, b, "same input, same slug");
1532        assert!(
1533            a.chars()
1534                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
1535            "filesystem-safe: {a}"
1536        );
1537    }
1538
1539    #[test]
1540    fn busy_active_describes_the_holder() {
1541        let b = Busy::Active(owner(123));
1542        let s = b.describe();
1543        assert!(
1544            s.contains("r1") && s.contains("gate") && s.contains("123"),
1545            "{s}"
1546        );
1547    }
1548
1549    trait Pipe: Sized {
1550        fn pipe(self) -> Guard;
1551    }
1552    impl Pipe for AcquireOutcome {
1553        fn pipe(self) -> Guard {
1554            match self {
1555                AcquireOutcome::Acquired(g) => g,
1556                AcquireOutcome::Busy(b) => panic!("expected Acquired, got Busy({b:?})"),
1557            }
1558        }
1559    }
1560
1561    fn cmds(v: &[&str]) -> Vec<String> {
1562        v.iter().map(|s| (*s).to_owned()).collect()
1563    }
1564
1565    #[test]
1566    fn manifest_paths_are_read_in_every_spelling() {
1567        let got = extract_manifest_paths(&cmds(&[
1568            "cargo test --manifest-path tools/a/Cargo.toml",
1569            "cargo build --manifest-path=tools/b/Cargo.toml --release",
1570            "cargo fmt --manifest-path 'q q/Cargo.toml'",
1571            "cargo clippy --manifest-path \"d/Cargo.toml\" && cargo test --manifest-path tools/a/Cargo.toml",
1572        ]));
1573        let want: Vec<PathBuf> = [
1574            "tools/a/Cargo.toml",
1575            "tools/b/Cargo.toml",
1576            "q q/Cargo.toml",
1577            "d/Cargo.toml",
1578        ]
1579        .iter()
1580        .map(PathBuf::from)
1581        .collect();
1582        assert_eq!(got, want);
1583        assert!(extract_manifest_paths(&cmds(&["cargo test", "cd x && cargo test"])).is_empty());
1584    }
1585
1586    #[test]
1587    fn plan_targets_covers_blog_root_both_and_none() {
1588        let w = Path::new("/w");
1589        let only = |set: &'static [&'static str]| {
1590            move |p: &Path| Ok(set.iter().any(|s| p == Path::new(s)))
1591        };
1592        let m = vec![PathBuf::from("tools/postprocess/Cargo.toml")];
1593        let blog = plan_targets(w, &m, only(&["/w/tools/postprocess/Cargo.toml"])).unwrap();
1594        assert_eq!(
1595            blog,
1596            vec![Target::Manifest(PathBuf::from(
1597                "/w/tools/postprocess/Cargo.toml"
1598            ))]
1599        );
1600        let root = plan_targets(w, &[], only(&["/w/Cargo.toml"])).unwrap();
1601        assert_eq!(root, vec![Target::Root]);
1602        let both = plan_targets(
1603            w,
1604            &m,
1605            only(&["/w/Cargo.toml", "/w/tools/postprocess/Cargo.toml"]),
1606        )
1607        .unwrap();
1608        assert_eq!(both.len(), 2);
1609        assert_eq!(both[0], Target::Root);
1610        assert!(plan_targets(w, &m, only(&[])).unwrap().is_empty());
1611        assert!(plan_targets(w, &[], only(&[])).unwrap().is_empty());
1612    }
1613
1614    #[test]
1615    fn a_repo_without_a_reachable_manifest_passes_untouched() {
1616        let home = tempfile::TempDir::new().expect("temp");
1617        let wt = tempfile::TempDir::new().expect("temp");
1618        // Only a nested crate, which no verify command names.
1619        std::fs::create_dir_all(wt.path().join("sub")).unwrap();
1620        std::fs::write(wt.path().join("sub/Cargo.toml"), "").unwrap();
1621        let cache = home.path().join("cache");
1622        std::fs::create_dir_all(&cache).unwrap();
1623        std::fs::write(cache.join("artifact"), "x").unwrap();
1624        let old = Identity {
1625            worktree: "/w/old".to_owned(),
1626            head: "old".to_owned(),
1627        };
1628        record_identity(home.path(), &cache, &old).unwrap();
1629        let id = Identity::new(wt.path(), "head");
1630        ensure_fresh(home.path(), &cache, &id, &[]).expect("must not fail");
1631        assert_eq!(
1632            std::fs::read_to_string(cache.join("artifact")).unwrap(),
1633            "x"
1634        );
1635        assert!(
1636            needs_refresh(home.path(), &cache, &old),
1637            "identity was invalidated, not recorded"
1638        );
1639        assert!(needs_refresh(home.path(), &cache, &id));
1640    }
1641}