Skip to main content

magi/
retention.rs

1//! Bounded reclamation of retained attempts and Cargo outputs. Source recovery
2//! and build eviction have separate authority: evicting a target never retires a run.
3mod copies;
4pub mod reconcile;
5
6pub(crate) fn has_archived_seats(home: &Path, state: &RunState) -> Result<bool> {
7    let artifacts = home.join("runs").join(&state.id).join("artifacts");
8    if !artifacts.try_exists()? {
9        return Ok(false);
10    }
11    ensure!(
12        plain_dir(&artifacts) && artifacts.canonicalize()? == artifacts,
13        "noncanonical artifacts"
14    );
15    for (i, entry) in std::fs::read_dir(artifacts)?.enumerate() {
16        ensure!(i < 4096, "eviction record inspection limit exceeded");
17        let name = entry?.file_name();
18        let name = name.to_string_lossy();
19        if name.starts_with("eviction-") && name.ends_with(".json") {
20            return Ok(true);
21        }
22    }
23    Ok(false)
24}
25
26/// Re-materialize evicted read seats before execution can consume their paths.
27/// Caller owns the run's driver/owner leases and repository coordination.
28pub(crate) async fn restore_execution_seats(
29    home: &Path,
30    state: &RunState,
31    coordination: Option<&crate::repo_lock::SeatLease>,
32) -> Result<()> {
33    copies::restore_execution_seats(home, state, coordination).await
34}
35
36/// Read the binary diff after verifying its independent source archive.
37pub async fn source_diff(evidence: &Path) -> Result<Vec<u8>> {
38    crate::fold_evidence::validate_snapshot(evidence).await?;
39    Ok(std::fs::read(evidence.join("change.patch"))?)
40}
41
42/// Restore immutable checkout evidence into a new inspection repository.
43pub async fn restore_source(evidence: &Path, destination: &Path) -> Result<()> {
44    crate::fold_evidence::restore_snapshot(evidence, destination).await
45}
46
47/// Historical scan observations, independent of archive readability or deletion authority.
48pub fn seat_inspections(home: &Path, id: &str) -> Result<Vec<String>> {
49    ensure!(crate::run::is_run_id(id), "invalid run id");
50    copies::seat_inspections(home, id)
51}
52
53/// List archived checkout tips for a run, validating their durable evidence.
54pub async fn seat_evidence(home: &Path, id: &str) -> Result<Vec<String>> {
55    copies::seat_evidence(home, id).await
56}
57
58/// Validated archived heads and seat labels for the run's evidence browser.
59pub async fn seat_heads(
60    home: &Path,
61    id: &str,
62) -> Result<std::collections::BTreeMap<String, String>> {
63    copies::seat_heads(home, id).await
64}
65
66/// Read a recorded seat's diff without relying on its checkout or Git objects.
67pub async fn seat_diff(home: &Path, id: &str, head: &str) -> Result<Vec<u8>> {
68    copies::seat_diff(home, id, head).await
69}
70
71/// Restore a recorded checkout tip without changing run or recovery authority.
72pub async fn restore_seat(home: &Path, id: &str, head: &str, destination: &Path) -> Result<()> {
73    copies::restore_seat(home, id, head, destination).await
74}
75
76use crate::{
77    git,
78    proc::Quiet as _,
79    run::{Liveness, RunState},
80};
81use anyhow::{Context, Result, ensure};
82use jiff::Timestamp;
83use serde::{Deserialize, Serialize};
84use std::{
85    fs::{File, OpenOptions},
86    path::{Path, PathBuf},
87};
88
89/// An OS lease on a worktree's outputs, independent of repository coordination.
90/// Kept by the process cleanup owner until descendants terminate, including
91/// reparented tools retaining the inherited liveness witness.
92#[derive(Debug)]
93pub(crate) struct OutputLease {
94    _file: std::sync::Arc<OutputFile>,
95    _activity: bool,
96}
97
98#[derive(Debug)]
99struct OutputFile(File);
100
101impl std::ops::Deref for OutputFile {
102    type Target = File;
103    fn deref(&self) -> &File {
104        &self.0
105    }
106}
107
108#[cfg(unix)]
109impl Drop for OutputFile {
110    fn drop(&mut self) {
111        use std::os::fd::AsRawFd;
112        // SAFETY: the final shared owner releases this live descriptor's lock.
113        unsafe {
114            libc::flock(self.0.as_raw_fd(), libc::LOCK_UN);
115        }
116    }
117}
118
119/// A source's output lease is held by a live writer, reader or reclaimer.
120/// Typed so that a fold can tell "someone is using it" from a real failure;
121/// the text is what operators and `copies::inspection_outcome` already read.
122#[derive(Debug)]
123pub(crate) struct OutputsInUse(PathBuf);
124
125impl std::fmt::Display for OutputsInUse {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        write!(
128            f,
129            "output lease: outputs are in use or being reclaimed: {}",
130            self.0.display()
131        )
132    }
133}
134
135impl std::error::Error for OutputsInUse {}
136
137/// A lock call that failed for a reason other than somebody holding the lock
138/// (`ENOLCK`, `EINTR`, a permission error): a failure of its own. Typed so the
139/// fold boundary reports it as `failed`, not as an unproven source.
140#[derive(Debug)]
141pub(crate) struct LockCallFailed {
142    what: String,
143    source: std::io::Error,
144}
145
146impl LockCallFailed {
147    pub(crate) fn new(what: String, source: std::io::Error) -> Self {
148        Self { what, source }
149    }
150}
151
152impl std::fmt::Display for LockCallFailed {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        write!(f, "lock call failed: {}: {}", self.what, self.source)
155    }
156}
157
158impl std::error::Error for LockCallFailed {
159    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
160        Some(&self.source)
161    }
162}
163
164impl OutputLease {
165    #[cfg(unix)]
166    pub(crate) fn descriptor(&self) -> std::os::fd::RawFd {
167        use std::os::fd::AsRawFd;
168        self._file.as_raw_fd()
169    }
170
171    /// A separate exclusive lock prevents nested/concurrent pre-clean operations.
172    pub(crate) fn pre_clean(dir: &Path) -> Result<Self> {
173        let file = OpenOptions::new()
174            .create(true)
175            .truncate(false)
176            .read(true)
177            .write(true)
178            .open(dir.join("magi-pre-clean.lock"))?;
179        crate::pr_head::try_lock_file(&file)
180            .context("pre-clean already running; retry after descendants terminate")?;
181        Ok(Self {
182            _file: std::sync::Arc::new(OutputFile(file)),
183            _activity: false,
184        })
185    }
186
187    pub(crate) fn duplicate(&self) -> Self {
188        Self {
189            _file: std::sync::Arc::clone(&self._file),
190            _activity: false,
191        }
192    }
193
194    pub(crate) fn borrow(worktree: &Path) -> Result<Option<Self>> {
195        if !worktree.join(".git").is_file() {
196            return Ok(None);
197        }
198        Self::take(worktree, false).map(Some)
199    }
200    pub(crate) fn cache(home: &Path, cache: &Path, exclusive: bool) -> Result<Self> {
201        use std::hash::{Hash, Hasher};
202        let mut hash = std::collections::hash_map::DefaultHasher::new();
203        let mut normalized = cache.to_owned();
204        let mut missing = Vec::new();
205        while !normalized.exists() {
206            let Some(name) = normalized.file_name() else {
207                break;
208            };
209            missing.push(name.to_owned());
210            if !normalized.pop() {
211                break;
212            }
213        }
214        normalized = normalized.canonicalize().unwrap_or(normalized);
215        for part in missing.into_iter().rev() {
216            normalized.push(part);
217        }
218        normalized.hash(&mut hash);
219        let dir = home.join("cache-leases");
220        std::fs::create_dir_all(&dir)?;
221        Self::lock(
222            &dir.join(format!("outputs-{:x}.lock", hash.finish())),
223            exclusive,
224        )
225    }
226    /// Reserve headroom once per volume while admitting a managed writer.
227    /// These are estimates, not filesystem quotas. The ordinary emergency
228    /// monitor remains necessary for writes exceeding the reservation.
229    pub(crate) fn admit(home: &Path, paths: &[PathBuf], min_free: u64) -> Result<Vec<Self>> {
230        #[cfg(unix)]
231        return Self::admit_isolated(home, paths, min_free);
232        #[cfg(not(unix))]
233        {
234            let _ = (home, paths, min_free);
235            Ok(Vec::new())
236        }
237    }
238
239    #[cfg(any(unix, windows))]
240    pub(crate) fn admit_isolated(
241        home: &Path,
242        paths: &[PathBuf],
243        min_free: u64,
244    ) -> Result<Vec<Self>> {
245        Self::admit_with(home, paths, min_free, crate::disk::managed_free_bytes)
246    }
247
248    #[cfg(any(unix, windows))]
249    pub(crate) fn admit_with(
250        home: &Path,
251        paths: &[PathBuf],
252        min_free: u64,
253        free_bytes: impl Fn(&Path) -> Result<u64>,
254    ) -> Result<Vec<Self>> {
255        #[cfg(unix)]
256        use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
257        #[cfg(windows)]
258        use std::os::windows::fs::OpenOptionsExt;
259        if min_free == 0 {
260            return Ok(Vec::new());
261        }
262        const RESERVE: u64 = 1024 * 1024 * 1024;
263        std::fs::create_dir_all(home)?;
264        let dir = home.canonicalize()?.join("disk-admission");
265        std::fs::create_dir_all(&dir)?;
266        ensure!(
267            plain_dir(&dir) && dir.canonicalize()? == dir,
268            "disk admission directory is not canonical"
269        );
270        let mut devices = std::collections::BTreeSet::new();
271        let mut reservations = Vec::new();
272        for path in paths {
273            let probe = path
274                .ancestors()
275                .find(|p| p.exists())
276                .context("disk admission path missing")?;
277            #[cfg(unix)]
278            let device = std::fs::metadata(probe)?.dev();
279            #[cfg(windows)]
280            let device = windows_volume(probe)?;
281            if !devices.insert(device) {
282                continue;
283            }
284            let open = |path: &Path| -> Result<File> {
285                let mut opts = OpenOptions::new();
286                opts.read(true).write(true).create(true).truncate(false);
287                #[cfg(unix)]
288                opts.custom_flags(libc::O_NOFOLLOW);
289                #[cfg(windows)]
290                opts.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
291                let file = opts.open(path)?;
292                #[cfg(windows)]
293                {
294                    use std::os::windows::fs::MetadataExt as _;
295                    ensure!(
296                        file.metadata()?.file_attributes() & 0x400 == 0,
297                        "disk admission lock is a reparse point"
298                    );
299                }
300                Ok(file)
301            };
302            // Explicitly unlock on return. A concurrent fork can briefly
303            // inherit this descriptor before exec closes it; closing only the
304            // parent's copy would leave the namespace spuriously busy.
305            let admission = Self {
306                _file: std::sync::Arc::new(OutputFile(open(&dir.join(format!("{device}.lock")))?)),
307                _activity: false,
308            };
309            let started = std::time::Instant::now();
310            loop {
311                match crate::pr_head::try_lock_file(&admission._file) {
312                    Ok(()) => break,
313                    Err(error)
314                        if lock_contended(&error)
315                            && started.elapsed() < std::time::Duration::from_secs(1) =>
316                    {
317                        std::thread::sleep(std::time::Duration::from_millis(5));
318                    }
319                    Err(error) => {
320                        return Err(error)
321                            .context("disk admission busy or unavailable; retry without dispatch");
322                    }
323                }
324            }
325            let mut active = 0u64;
326            let mut available = None;
327            for slot in 0..1024 {
328                let file = dir.join(format!("{device}-{slot}.reserve"));
329                if !file.exists() {
330                    if available.is_none() {
331                        available = Some(file);
332                    }
333                    continue;
334                }
335                let file = open(&file)?;
336                match crate::pr_head::try_lock_file(&file) {
337                    Ok(()) if available.is_none() => {
338                        available = Some(dir.join(format!("{device}-{slot}.reserve")))
339                    }
340                    Ok(()) => {}
341                    Err(_) => active = active.saturating_add(RESERVE),
342                }
343            }
344            let free = free_bytes(probe)?;
345            let required = min_free.saturating_add(active).saturating_add(RESERVE);
346            ensure!(
347                free >= required,
348                "disk admission blocked: {free} bytes free; floor {min_free}, active writer reservations {active}, next writer reservation {RESERVE} bytes (estimates, not quotas)"
349            );
350            let file = open(&available.context("disk admission reservation slots exhausted")?)?;
351            crate::pr_head::try_lock_file(&file)?;
352            reservations.push(Self {
353                _file: std::sync::Arc::new(OutputFile(file)),
354                _activity: false,
355            });
356        }
357        Ok(reservations)
358    }
359
360    #[cfg(not(any(unix, windows)))]
361    pub(crate) fn admit_isolated(
362        _home: &Path,
363        _paths: &[PathBuf],
364        _min_free: u64,
365    ) -> Result<Vec<Self>> {
366        anyhow::bail!("disk admission is unavailable on this platform")
367    }
368
369    pub(crate) fn take(worktree: &Path, exclusive: bool) -> Result<Self> {
370        let out = std::process::Command::new("git")
371            .args(["rev-parse", "--absolute-git-dir"])
372            .current_dir(worktree)
373            .quiet()
374            .output()?;
375        ensure!(
376            out.status.success(),
377            "cannot identify output lease directory"
378        );
379        let dir = PathBuf::from(String::from_utf8(out.stdout)?.trim());
380        Self::lock(&dir.join("magi-output.lock"), exclusive)
381    }
382    pub(crate) fn lock(path: &Path, exclusive: bool) -> Result<Self> {
383        let file = OpenOptions::new()
384            .create(true)
385            .truncate(false)
386            .read(true)
387            .write(true)
388            .open(path)
389            .with_context(|| format!("output lease: open {}", path.display()))?;
390        #[cfg(unix)]
391        {
392            use std::os::fd::AsRawFd;
393            let mode = if exclusive {
394                libc::LOCK_EX
395            } else {
396                libc::LOCK_SH
397            };
398            // SAFETY: live file descriptor, no retained pointers.
399            if unsafe { libc::flock(file.as_raw_fd(), mode | libc::LOCK_NB) } != 0 {
400                let error = std::io::Error::last_os_error();
401                // Contention is somebody else using the outputs; any other
402                // failure of the lock call (ENOLCK, EINTR, ...) is not.
403                if error.kind() == std::io::ErrorKind::WouldBlock {
404                    return Err(OutputsInUse(path.to_owned()).into());
405                }
406                return Err(error)
407                    .with_context(|| format!("output lease: lock {}", path.display()));
408            }
409        }
410        #[cfg(windows)]
411        {
412            use std::os::windows::io::AsRawHandle as _;
413            if !crate::chat_watch::windows::lock_file_mode(file.as_raw_handle(), true, exclusive)? {
414                return Err(OutputsInUse(path.to_owned()).into());
415            }
416        }
417        #[cfg(not(any(unix, windows)))]
418        let _ = exclusive;
419        if !exclusive {
420            // Empty legacy/maintenance-only leases carry no activity witness.
421            file.set_len(1)?;
422            file.set_modified(std::time::SystemTime::now())
423                .with_context(|| format!("record output activity {}", path.display()))?;
424        }
425        Ok(Self {
426            _file: std::sync::Arc::new(OutputFile(file)),
427            _activity: !exclusive,
428        })
429    }
430}
431
432#[cfg(any(unix, windows))]
433fn lock_contended(error: &std::io::Error) -> bool {
434    matches!(
435        error.kind(),
436        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
437    ) || cfg!(windows) && error.raw_os_error() == Some(33)
438}
439
440#[cfg(windows)]
441fn windows_volume(path: &Path) -> Result<u128> {
442    use std::os::windows::ffi::OsStrExt as _;
443    #[link(name = "kernel32")]
444    unsafe extern "system" {
445        fn GetVolumePathNameW(path: *const u16, mount: *mut u16, length: u32) -> i32;
446        fn GetVolumeNameForVolumeMountPointW(mount: *const u16, name: *mut u16, length: u32)
447        -> i32;
448    }
449    let path: Vec<_> = path
450        .canonicalize()?
451        .as_os_str()
452        .encode_wide()
453        .chain(Some(0))
454        .collect();
455    let mut mount = vec![0u16; 32_768];
456    let mut name = [0u16; 64];
457    // The buffers are valid for these Win32 calls and the input is NUL-terminated.
458    if unsafe { GetVolumePathNameW(path.as_ptr(), mount.as_mut_ptr(), mount.len() as u32) } == 0
459        || unsafe {
460            GetVolumeNameForVolumeMountPointW(mount.as_ptr(), name.as_mut_ptr(), name.len() as u32)
461        } == 0
462    {
463        return Err(std::io::Error::last_os_error()).context("identify disk admission volume");
464    }
465    let end = name
466        .iter()
467        .position(|&c| c == 0)
468        .context("invalid volume name")?;
469    let name = String::from_utf16(&name[..end])?;
470    let id = name
471        .strip_prefix(r"\\?\Volume{")
472        .and_then(|s| s.strip_suffix("}\\"))
473        .context("volume has no stable GUID")?;
474    ensure!(
475        id.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-'),
476        "invalid volume GUID"
477    );
478    Ok(u128::from_str_radix(&id.replace('-', ""), 16)?)
479}
480
481#[cfg(all(test, windows))]
482#[test]
483fn isolated_windows_reservations_share_the_actual_volume_budget() {
484    let home = tempfile::tempdir().unwrap();
485    let first = home.path().join("first checkout");
486    let second = home.path().join("second 日本語 checkout");
487    std::fs::create_dir(&first).unwrap();
488    std::fs::create_dir(&second).unwrap();
489    let reserve =
490        |paths: &[PathBuf]| OutputLease::admit_with(home.path(), paths, 1, |_| Ok(1 + (1 << 30)));
491    let writer = reserve(&[first, second.clone()]).unwrap();
492    let err = reserve(std::slice::from_ref(&second)).unwrap_err();
493    assert!(
494        err.to_string()
495            .contains("active writer reservations 1073741824")
496    );
497    drop(writer);
498    assert!(reserve(&[second]).is_ok());
499}
500
501#[cfg(unix)]
502impl Drop for OutputLease {
503    fn drop(&mut self) {
504        if self._activity
505            && let Err(error) = self._file.set_modified(std::time::SystemTime::now())
506        {
507            // If release time cannot be recorded, retain a nonempty invalid
508            // witness rather than trusting the old acquisition timestamp.
509            let _ = self._file.set_len(2);
510            tracing::warn!("could not record output lease release activity: {error}");
511        }
512    }
513}
514
515#[derive(Default, Debug, Serialize, Deserialize)]
516#[serde(default)]
517pub(crate) struct Report {
518    pub checked_at: Option<Timestamp>,
519    pub limit_bytes: u64,
520    pub reclaim_budget_bytes: u64,
521    /// Logical inventory, including protected and unproven data.
522    pub measured_bytes: u64,
523    /// Logical bytes unlinked, not a measurement of physical disk recovery.
524    pub freed_bytes: u64,
525    pub measured_allocated_file_bytes: Option<u64>,
526    /// Candidates proven under locks in this pass; uninspected data is excluded.
527    pub proven_reclaimable_bytes: u64,
528    /// Estimated allocated blocks recoverable if every proven link is removed.
529    /// Inodes with links outside the candidate set contribute zero.
530    pub proven_reclaimable_allocated_bytes: Option<u64>,
531    pub protected_or_unproven_bytes: u64,
532    /// Deduplicated allocated file blocks whose final link was unlinked. Open
533    /// descriptors and shared extents can prevent an equivalent physical gain.
534    pub estimated_released_allocated_bytes: Option<u64>,
535    /// Observed free-space change on the home volume; concurrent writes, clones
536    /// and deferred reclamation mean this is not attributable to this sweep.
537    pub observed_home_free_change_bytes: Option<i64>,
538    pub retired: usize,
539    pub evicted_copies: usize,
540    pub source_scan: Option<serde_json::Value>,
541    pub removed_empty_roots: usize,
542    pub source_unlinked_logical_bytes: u64,
543    pub source_unlinked_allocated_bytes: Option<u64>,
544    pub source_evidence_added_logical_bytes: u64,
545    pub source_evidence_added_allocated_bytes: Option<u64>,
546    pub retained: Vec<String>,
547    pub failures: Vec<String>,
548}
549
550#[cfg(unix)]
551fn allocated_inventory(
552    root: &Path,
553    seen: &mut std::collections::BTreeSet<(u64, u64)>,
554) -> Result<u64> {
555    use std::os::unix::fs::MetadataExt;
556    ensure!(
557        plain_dir(root) && root.canonicalize()? == root,
558        "allocated inventory root is not canonical"
559    );
560    let mut dirs = vec![root.to_owned()];
561    let mut bytes = 0u64;
562    while let Some(dir) = dirs.pop() {
563        for entry in std::fs::read_dir(dir)? {
564            let path = entry?.path();
565            let metadata = std::fs::symlink_metadata(&path)?;
566            if metadata.is_dir() {
567                dirs.push(path);
568            } else if metadata.is_file() && seen.insert((metadata.dev(), metadata.ino())) {
569                bytes = bytes.saturating_add(metadata.blocks().saturating_mul(512));
570            }
571        }
572    }
573    Ok(bytes)
574}
575
576#[derive(Default)]
577struct ReleasedAllocation {
578    #[cfg(unix)]
579    files: std::collections::BTreeMap<PathBuf, (u64, u64, u64, u64)>,
580    #[cfg(unix)]
581    removed: std::collections::BTreeMap<(u64, u64), u64>,
582}
583
584impl ReleasedAllocation {
585    fn of(paths: &[PathBuf]) -> Result<Self> {
586        #[cfg(unix)]
587        {
588            use std::os::unix::fs::MetadataExt;
589            let mut files = std::collections::BTreeMap::new();
590            for path in paths {
591                let m = std::fs::symlink_metadata(path)?;
592                ensure!(m.is_file(), "allocation candidate is not regular");
593                files.insert(
594                    path.clone(),
595                    (m.dev(), m.ino(), m.nlink(), m.blocks().saturating_mul(512)),
596                );
597            }
598            Ok(Self {
599                files,
600                removed: Default::default(),
601            })
602        }
603        #[cfg(not(unix))]
604        {
605            let _ = paths;
606            Ok(Self::default())
607        }
608    }
609    fn reclaimable_allocated_bytes(&self) -> Option<u64> {
610        #[cfg(unix)]
611        {
612            let mut inodes = std::collections::BTreeMap::new();
613            for &(device, inode, links, blocks) in self.files.values() {
614                let entry = inodes
615                    .entry((device, inode))
616                    .or_insert((0u64, links, blocks));
617                entry.0 += 1;
618            }
619            Some(
620                inodes
621                    .values()
622                    .filter(|(count, links, _)| count == links)
623                    .fold(0u64, |sum, (_, _, blocks)| sum.saturating_add(*blocks)),
624            )
625        }
626        #[cfg(not(unix))]
627        {
628            None
629        }
630    }
631
632    fn unlinked(&mut self, path: &Path) -> Option<u64> {
633        #[cfg(unix)]
634        {
635            let (device, inode, links, blocks) = self.files[path];
636            let removed = self.removed.entry((device, inode)).or_default();
637            *removed += 1;
638            Some(if *removed == links { blocks } else { 0 })
639        }
640        #[cfg(not(unix))]
641        {
642            let _ = path;
643            None
644        }
645    }
646}
647
648fn plain_dir(path: &Path) -> bool {
649    std::fs::symlink_metadata(path).is_ok_and(|m| m.is_dir() && !m.file_type().is_symlink())
650}
651
652pub(crate) fn read_seat(path: &Path) -> bool {
653    path.file_name()
654        .and_then(|s| s.to_str())
655        .is_some_and(|name| {
656            ["review-", "judge-", "advisor-"].iter().any(|prefix| {
657                name.strip_prefix(prefix)
658                    .is_some_and(|n| n.parse::<usize>().is_ok_and(|n| n > 0))
659            })
660        })
661}
662
663/// Old run records outlive their checkout and output directories. Only an
664/// absent path means nothing to reclaim; inaccessible paths remain errors.
665fn run_paths_missing(state: &RunState) -> Result<bool> {
666    for path in [state.worktree_root(), state.repo.clone()] {
667        match std::fs::metadata(&path) {
668            Ok(_) => {}
669            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(true),
670            Err(e) => return Err(e).with_context(|| format!("inspect {}", path.display())),
671        }
672    }
673    Ok(false)
674}
675
676/// Enumerate actual registered worktrees, not just candidates in run.json.
677pub(crate) async fn worktrees(state: &RunState) -> Result<Vec<PathBuf>> {
678    let root = state.worktree_root();
679    if !plain_dir(&root) {
680        return Ok(Vec::new());
681    }
682    let list = git::git(&state.repo, &["worktree", "list", "--porcelain"]).await?;
683    registered_worktrees(state, &list)
684}
685
686fn registered_worktrees(state: &RunState, list: &str) -> Result<Vec<PathBuf>> {
687    let root = state.worktree_root();
688    if !plain_dir(&root) {
689        return Ok(Vec::new());
690    }
691    let root = root.canonicalize()?;
692    let mut paths = Vec::new();
693    for path in list.lines().filter_map(|l| l.strip_prefix("worktree ")) {
694        let path = PathBuf::from(path);
695        #[cfg(windows)]
696        let path = if plain_dir(&path) {
697            git::canonical_output_path(path.to_str().context("non UTF-8 registration")?)?
698        } else {
699            continue;
700        };
701        if plain_dir(&path)
702            && path.parent() == Some(root.as_path())
703            && path.canonicalize()? == path
704            && path.join(".git").is_file()
705        {
706            paths.push(path);
707        }
708    }
709    Ok(paths)
710}
711
712/// Recognize Cargo's generated directory, never merely an ignored directory.
713/// Unknown root entries are retained; cache identity/profile paths fail closed.
714async fn cargo_target(worktree: &Path) -> Result<PathBuf> {
715    validate_cargo_target(worktree, false).await
716}
717
718async fn validate_cargo_target(worktree: &Path, allow_missing_tag: bool) -> Result<PathBuf> {
719    let target = worktree.join("target");
720    ensure!(plain_dir(&target), "target absent or not a plain directory");
721    ensure!(target.canonicalize()? == target, "target path changed");
722    ensure!(
723        git::git(worktree, &["ls-files", "--", "target"])
724            .await?
725            .is_empty(),
726        "tracked target contents"
727    );
728    ensure!(
729        git::git_raw(worktree, &["check-ignore", "--quiet", "target/"])
730            .await?
731            .ok(),
732        "target is not ignored"
733    );
734    cache_tag(&target, allow_missing_tag)?;
735    let path = target.join(".rustc_info.json");
736    plain_file(&path, "rustc identity")?;
737    let info: serde_json::Value = serde_json::from_slice(
738        &std::fs::read(&path).with_context(|| format!("read rustc identity {}", path.display()))?,
739    )
740    .with_context(|| format!("parse rustc identity {}", path.display()))?;
741    ensure!(
742        info.get("rustc_fingerprint").is_some(),
743        "unknown Cargo identity {}",
744        path.display()
745    );
746    if allow_missing_tag && !target.join("CACHEDIR.TAG").exists() {
747        ensure!(
748            info.get("rustc_fingerprint")
749                .is_some_and(serde_json::Value::is_u64)
750                && info
751                    .get("outputs")
752                    .and_then(serde_json::Value::as_object)
753                    .is_some_and(|outputs| outputs.values().any(|output| {
754                        output.get("success").and_then(serde_json::Value::as_bool) == Some(true)
755                            && output
756                                .get("stdout")
757                                .and_then(serde_json::Value::as_str)
758                                .is_some_and(|stdout| stdout.starts_with("rustc "))
759                            && output
760                                .get("stderr")
761                                .is_some_and(serde_json::Value::is_string)
762                    }))
763                && info
764                    .get("successes")
765                    .is_some_and(serde_json::Value::is_object),
766            "missing-tag rustc identity structure invalid: {}",
767            path.display()
768        );
769        let mut profiles = 0;
770        for profile in ["debug", "release"] {
771            let dir = target.join(profile);
772            if !dir.exists() {
773                continue;
774            }
775            profile_output_dirs(&dir, true)?;
776            plain_file(&dir.join(".cargo-lock"), "missing-tag Cargo lock")?;
777            profiles += 1;
778        }
779        ensure!(
780            profiles > 0,
781            "missing-tag proof: no Cargo profile in {}",
782            target.display()
783        );
784    }
785    for name in ["debug", "release"] {
786        let path = target.join(name);
787        match std::fs::symlink_metadata(&path) {
788            Ok(metadata) => ensure!(
789                metadata.is_dir() && path.canonicalize()? == path,
790                "profile validation: not a plain directory: {}",
791                path.display()
792            ),
793            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
794            Err(error) => {
795                return Err(error)
796                    .with_context(|| format!("profile validation: inspect {}", path.display()));
797            }
798        }
799    }
800    Ok(target)
801}
802
803fn plain_file(path: &Path, stage: &str) -> Result<()> {
804    let meta = std::fs::symlink_metadata(path)
805        .with_context(|| format!("{stage}: inspect {}", path.display()))?;
806    ensure!(
807        meta.is_file() && path.canonicalize()? == path,
808        "{stage}: not a plain file: {}",
809        path.display()
810    );
811    Ok(())
812}
813
814fn cache_tag(target: &Path, allow_missing: bool) -> Result<()> {
815    let path = target.join("CACHEDIR.TAG");
816    match std::fs::symlink_metadata(&path) {
817        Err(error) if allow_missing && error.kind() == std::io::ErrorKind::NotFound => {
818            return Ok(());
819        }
820        result => {
821            result.with_context(|| format!("cache tag: inspect {}", path.display()))?;
822        }
823    }
824    plain_file(&path, "cache tag")?;
825    let tag = std::fs::read_to_string(&path)
826        .with_context(|| format!("cache tag: read {}", path.display()))?;
827    ensure!(
828        tag.starts_with("Signature: 8a477f597d28d172789f06886806bc55"),
829        "unknown Cargo cache tag: {}",
830        path.display()
831    );
832    Ok(())
833}
834
835/// Observe compiler metadata and artifacts under the output and Cargo locks.
836/// Unknown contents never become deletion authority. Unreadable timestamps or
837/// a future timestamp retain outputs, even when the configured grace is zero.
838fn output_age(target: &Path, now: Timestamp, grace: u64) -> Result<()> {
839    let mut dirs = vec![target.to_owned()];
840    let mut entries = 0;
841    while let Some(dir) = dirs.pop() {
842        for entry in std::fs::read_dir(&dir)
843            .with_context(|| format!("output activity: list {}", dir.display()))?
844        {
845            let path = entry?.path();
846            entries += 1;
847            ensure!(
848                entries <= 100_000,
849                "output activity inventory too large: {}",
850                target.display()
851            );
852            let metadata = std::fs::symlink_metadata(&path)
853                .with_context(|| format!("output activity: inspect {}", path.display()))?;
854            if metadata.is_dir() {
855                // Only supported Cargo profiles supply execution evidence.
856                if dir != target
857                    || matches!(
858                        path.file_name().and_then(|s| s.to_str()),
859                        Some("debug" | "release")
860                    )
861                {
862                    dirs.push(path);
863                }
864            } else if metadata.is_file()
865                && (dir != target || path.file_name().is_some_and(|n| n == ".rustc_info.json"))
866            {
867                let at =
868                    Timestamp::try_from(metadata.modified().with_context(|| {
869                        format!("output activity: modified {}", path.display())
870                    })?)?;
871                ensure!(
872                    crate::clean::due(now, at, grace),
873                    "output activity within grace period: {} modified {at} (now {now}, grace {grace}s)",
874                    path.display()
875                );
876            }
877        }
878    }
879    Ok(())
880}
881
882pub(crate) fn artifact_signature(path: &Path) -> Result<bool> {
883    use std::io::Read as _;
884    let mut header = [0; 8];
885    let n = File::open(path)?.read(&mut header)?;
886    let header = &header[..n];
887    Ok(header.starts_with(b"\x7fELF")
888        || header.starts_with(b"!<arch>\n")
889        || header.starts_with(b"rust\0\0\0")
890        || header.starts_with(b"MZ\x90\0")
891        || [
892            [0xfe, 0xed, 0xfa, 0xce],
893            [0xce, 0xfa, 0xed, 0xfe],
894            [0xfe, 0xed, 0xfa, 0xcf],
895            [0xcf, 0xfa, 0xed, 0xfe],
896            [0xca, 0xfe, 0xba, 0xbe],
897            [0xca, 0xfe, 0xba, 0xbf],
898        ]
899        .iter()
900        .any(|magic| header.starts_with(magic)))
901}
902
903/// Enumerate only known Cargo output locations. A v2 unit's `out` is not
904/// wholesale compiler authority: callers must still prove each file by dep-info
905/// and signature. In particular, build-script output is never traversed.
906fn profile_output_dirs(profile: &Path, require_proof: bool) -> Result<Vec<PathBuf>> {
907    let mut present = std::collections::BTreeSet::new();
908    for path in [
909        profile.to_owned(),
910        profile.join("deps"),
911        profile.join(".fingerprint"),
912        profile.join("build"),
913    ] {
914        match std::fs::symlink_metadata(&path) {
915            Ok(_) => {
916                ensure!(
917                    plain_dir(&path) && path.canonicalize()? == path,
918                    "Cargo profile proof: {} is not a plain directory",
919                    path.display()
920                );
921                present.insert(path);
922            }
923            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
924            Err(e) => return Err(e.into()),
925        }
926    }
927    if !present.contains(profile) {
928        return Ok(Vec::new());
929    }
930    let deps = present.contains(&profile.join("deps"));
931    let fingerprint = present.contains(&profile.join(".fingerprint"));
932    let mut dirs = vec![profile.to_owned()];
933    if deps || fingerprint {
934        ensure!(
935            !require_proof || (deps && fingerprint),
936            "incomplete Cargo v1 profile proof"
937        );
938        if deps {
939            dirs.push(profile.join("deps"));
940        }
941        // v1 build-script directories have flat <package>-<hash> names;
942        // a nested v2 package directory must not silently mix layouts.
943        if present.contains(&profile.join("build")) {
944            for entry in std::fs::read_dir(profile.join("build"))? {
945                let path = entry?.path();
946                if plain_dir(&path) {
947                    for entry in std::fs::read_dir(&path)? {
948                        ensure!(
949                            !entry?.file_name().to_str().is_some_and(unit_hash),
950                            "mixed Cargo profile layouts"
951                        );
952                    }
953                }
954            }
955        }
956    } else if present.contains(&profile.join("build")) {
957        let mut units = 0;
958        for package in std::fs::read_dir(profile.join("build"))? {
959            let package = package?.path();
960            let meta = std::fs::symlink_metadata(&package)?;
961            ensure!(
962                !meta.file_type().is_symlink(),
963                "Cargo v2 package is a symlink: {}",
964                package.display()
965            );
966            if !meta.is_dir() {
967                ensure!(!require_proof, "Cargo v2 package is not a directory");
968                continue;
969            }
970            ensure!(
971                package.canonicalize()? == package,
972                "Cargo v2 package is not a plain directory"
973            );
974            let mut package_units = 0;
975            for unit in std::fs::read_dir(&package)? {
976                let unit = unit?.path();
977                let meta = std::fs::symlink_metadata(&unit)?;
978                ensure!(
979                    !meta.file_type().is_symlink(),
980                    "Cargo v2 unit is a symlink: {}",
981                    unit.display()
982                );
983                // Reclamation only: a non-hash or incomplete unit is not a
984                // rustc unit, so it is retained while complete ones still
985                // count. The missing-tag proof demands every unit be valid.
986                let structured = meta.is_dir()
987                    && unit
988                        .file_name()
989                        .and_then(|n| n.to_str())
990                        .is_some_and(unit_hash)
991                    && unit.canonicalize()? == unit
992                    && ["fingerprint", "out"].iter().all(|name| {
993                        let path = unit.join(name);
994                        plain_dir(&path) && path.canonicalize().is_ok_and(|p| p == path)
995                    });
996                // A completed build-script run unit has no invoked.timestamp;
997                // it is a known structure but its output never gets authority.
998                if structured && v2_run_script_unit(&unit) {
999                    continue;
1000                }
1001                let complete = structured
1002                    && plain_file(
1003                        &unit.join("fingerprint/invoked.timestamp"),
1004                        "Cargo unit fingerprint",
1005                    )
1006                    .is_ok();
1007                if !complete {
1008                    ensure!(!require_proof, "invalid or incomplete Cargo v2 unit");
1009                    continue;
1010                }
1011                dirs.push(unit.join("out"));
1012                units += 1;
1013                package_units += 1;
1014                ensure!(units <= 4096, "Cargo unit inventory too large");
1015            }
1016            ensure!(
1017                package_units > 0 || !require_proof,
1018                "empty Cargo v2 package"
1019            );
1020        }
1021        ensure!(units > 0 || !require_proof, "missing Cargo v2 units");
1022    } else {
1023        ensure!(!require_proof, "missing Cargo profile proof");
1024    }
1025    Ok(dirs)
1026}
1027
1028// A build-script run unit: fingerprint holds exactly a plain
1029// `run-build-script-*` file with its json sibling, and no timestamp.
1030fn v2_run_script_unit(unit: &Path) -> bool {
1031    let fp = unit.join("fingerprint");
1032    if std::fs::symlink_metadata(fp.join("invoked.timestamp")).is_ok() {
1033        return false;
1034    }
1035    let Ok(entries) = std::fs::read_dir(&fp) else {
1036        return false;
1037    };
1038    for entry in entries.flatten() {
1039        let path = entry.path();
1040        let name = path.file_name().unwrap_or_default().to_string_lossy();
1041        if name.starts_with("run-build-script-")
1042            && path.extension().is_none()
1043            && plain_file(&path, "Cargo run fingerprint").is_ok()
1044            && plain_file(&path.with_extension("json"), "Cargo run fingerprint json").is_ok()
1045        {
1046            return true;
1047        }
1048    }
1049    false
1050}
1051
1052// A unit directory may also contain arbitrary build-script products. Only
1053// lib/bin rustc fingerprints matching this dep-info stem confer output authority.
1054fn v2_compiler_dep_info(dir: &Path, dep_info: &Path) -> Result<bool> {
1055    let unit = dir.parent().context("Cargo unit parent")?;
1056    let hash = unit.file_name().unwrap_or_default().to_string_lossy();
1057    let stem = dep_info.file_stem().unwrap_or_default().to_string_lossy();
1058    for entry in std::fs::read_dir(unit.join("fingerprint"))? {
1059        let path = entry?.path();
1060        let name = path.file_name().unwrap_or_default().to_string_lossy();
1061        // Cargo hashes library filenames but v2 binaries use the crate name
1062        // directly; the containing unit directory supplies their disambiguation.
1063        let library = name
1064            .strip_prefix("lib-")
1065            .is_some_and(|name| stem == format!("{}-{hash}", name.replace('-', "_")));
1066        let binary = name
1067            .strip_prefix("bin-")
1068            .is_some_and(|name| stem == name.replace('-', "_"));
1069        if library || binary {
1070            plain_file(&path, "Cargo compiler fingerprint")?;
1071            plain_file(
1072                &path.with_extension("json"),
1073                "Cargo compiler fingerprint json",
1074            )?;
1075            plain_file(
1076                &path.with_file_name(format!(
1077                    "dep-{}",
1078                    path.file_name().unwrap().to_string_lossy()
1079                )),
1080                "Cargo compiler fingerprint dep-info",
1081            )?;
1082            return Ok(true);
1083        }
1084    }
1085    Ok(false)
1086}
1087
1088fn unit_hash(name: &str) -> bool {
1089    name.len() == 16 && name.bytes().all(|b| b.is_ascii_hexdigit())
1090}
1091
1092/// Legacy tags identify a cache, not ownership of every file inside it.
1093/// Only direct rustc outputs named by dep-info may be reclaimed. Build-script
1094/// output, incremental caches, unknown files and the manifests themselves stay.
1095fn declared_outputs(target: &Path) -> Result<Vec<PathBuf>> {
1096    let mut outputs = std::collections::BTreeSet::new();
1097    for profile in ["debug", "release"] {
1098        for dir in profile_output_dirs(&target.join(profile), false)? {
1099            if !plain_dir(&dir) || dir.canonicalize()? != dir {
1100                continue;
1101            }
1102            for entry in std::fs::read_dir(&dir)? {
1103                let path = entry?.path();
1104                if path.extension().is_none_or(|ext| ext != "d")
1105                    || !std::fs::symlink_metadata(&path)?.is_file()
1106                    || std::fs::metadata(&path)?.len() > 1024 * 1024
1107                    || path.canonicalize()? != path
1108                {
1109                    continue;
1110                }
1111                if dir.file_name().is_some_and(|name| name == "out")
1112                    && !v2_compiler_dep_info(&dir, &path)?
1113                {
1114                    continue;
1115                }
1116                let body = std::fs::read_to_string(&path)?;
1117                for line in body.lines() {
1118                    let Some((names, dependencies)) = line.split_once(": ") else {
1119                        continue;
1120                    };
1121                    if dependencies.trim().is_empty() {
1122                        continue;
1123                    }
1124                    // Rustc escapes spaces and backslashes in Make paths.
1125                    // Unsupported Make syntax fails closed for that record.
1126                    let mut words = Vec::new();
1127                    let mut word = String::new();
1128                    let mut escaped = false;
1129                    for c in names.chars() {
1130                        if escaped {
1131                            word.push(c);
1132                            escaped = false;
1133                        } else if c == '\\' {
1134                            escaped = true;
1135                        } else if c.is_whitespace() {
1136                            if !word.is_empty() {
1137                                words.push(std::mem::take(&mut word));
1138                            }
1139                        } else {
1140                            word.push(c);
1141                        }
1142                    }
1143                    if escaped || word.contains(['$', '%']) {
1144                        continue;
1145                    }
1146                    if !word.is_empty() {
1147                        words.push(word);
1148                    }
1149                    for name in words {
1150                        let output = PathBuf::from(name);
1151                        let stem = path.file_stem().unwrap_or_default().to_string_lossy();
1152                        let output_stem = output.file_stem().unwrap_or_default().to_string_lossy();
1153                        let artifact_name =
1154                            output_stem == stem || output_stem == format!("lib{stem}");
1155                        let artifact_kind = output.extension().is_none_or(|ext| {
1156                            matches!(
1157                                ext.to_str(),
1158                                Some(
1159                                    "rlib"
1160                                        | "rmeta"
1161                                        | "so"
1162                                        | "dylib"
1163                                        | "a"
1164                                        | "lib"
1165                                        | "dll"
1166                                        | "exe"
1167                                        | "pdb"
1168                                )
1169                            )
1170                        });
1171                        if artifact_name
1172                            && artifact_kind
1173                            && output.parent() == Some(dir.as_path())
1174                            && output.extension().is_none_or(|ext| ext != "d")
1175                            && std::fs::symlink_metadata(&output).is_ok_and(|m| m.is_file())
1176                            && output.canonicalize().is_ok_and(|p| p == output)
1177                            && artifact_signature(&output)?
1178                        {
1179                            outputs.insert(output);
1180                        }
1181                    }
1182                }
1183            }
1184        }
1185    }
1186    Ok(outputs.into_iter().collect())
1187}
1188
1189#[derive(Serialize, Deserialize)]
1190struct CargoResidue {
1191    target: PathBuf,
1192    files: std::collections::BTreeMap<PathBuf, Vec<u8>>,
1193}
1194
1195// Keep the exact metadata as historical evidence. An old proof cannot adopt
1196// newly added files, changed metadata, symlinks or a different worktree.
1197fn residue_files(
1198    target: &Path,
1199    outputs: &[PathBuf],
1200) -> Result<std::collections::BTreeMap<PathBuf, Vec<u8>>> {
1201    let mut files = std::collections::BTreeMap::new();
1202    let mut dirs = vec![target.to_owned()];
1203    let mut bytes = 0usize;
1204    let mut entries = 0usize;
1205    while let Some(dir) = dirs.pop() {
1206        for entry in std::fs::read_dir(dir)? {
1207            let path = entry?.path();
1208            entries += 1;
1209            ensure!(entries <= 4096, "residue inventory too large");
1210            let metadata = std::fs::symlink_metadata(&path)?;
1211            ensure!(
1212                !metadata.file_type().is_symlink(),
1213                "symlink in Cargo residue"
1214            );
1215            if metadata.is_dir() {
1216                dirs.push(path);
1217            } else {
1218                ensure!(metadata.is_file(), "non-file in Cargo residue");
1219                if outputs.contains(&path) {
1220                    continue;
1221                }
1222                ensure!(metadata.len() <= 1024 * 1024, "residue file too large");
1223                let body = std::fs::read(&path)?;
1224                bytes = bytes.saturating_add(body.len());
1225                ensure!(bytes <= 8 * 1024 * 1024, "residue inventory too large");
1226                files.insert(path.strip_prefix(target)?.to_owned(), body);
1227            }
1228        }
1229    }
1230    Ok(files)
1231}
1232
1233fn residue_proof(home: &Path, id: &str, worktree: &Path) -> Result<PathBuf> {
1234    Ok(home
1235        .join("runs")
1236        .join(id)
1237        .join("build-residue")
1238        .join(worktree.file_name().context("missing worktree name")?))
1239}
1240
1241// Artifact eviction tolerates unrelated root data. Whole-target removal must
1242// still reject it, including empty directories absent from the file inventory.
1243fn residue_root(target: &Path) -> Result<()> {
1244    for entry in std::fs::read_dir(target)? {
1245        let name = entry?.file_name();
1246        ensure!(
1247            matches!(
1248                name.to_str(),
1249                Some("debug" | "release" | "CACHEDIR.TAG" | ".rustc_info.json")
1250            ),
1251            "unrecognized Cargo residue root entry"
1252        );
1253    }
1254    Ok(())
1255}
1256
1257fn record_residue(home: &Path, id: &str, target: &Path, outputs: &[PathBuf]) -> Result<()> {
1258    cache_tag(target, false)?;
1259    residue_root(target)?;
1260    let files = residue_files(target, outputs)?;
1261    for (relative, body) in &files {
1262        let path = target.join(relative);
1263        let identity = matches!(relative.to_str(), Some("CACHEDIR.TAG" | ".rustc_info.json"));
1264        let lock = matches!(
1265            relative.to_str(),
1266            Some("debug/.cargo-lock" | "release/.cargo-lock")
1267        ) && body.is_empty();
1268        let dep_info = path.extension().is_some_and(|ext| ext == "d")
1269            && outputs.iter().any(|output| {
1270                output.parent() == path.parent()
1271                    && (output.file_stem() == path.file_stem()
1272                        || output.file_stem().is_some_and(|stem| {
1273                            stem.to_string_lossy()
1274                                == format!(
1275                                    "lib{}",
1276                                    path.file_stem().unwrap_or_default().to_string_lossy()
1277                                )
1278                        }))
1279            });
1280        ensure!(identity || lock || dep_info, "unproven Cargo residue");
1281    }
1282    let proof = residue_proof(home, id, target.parent().context("missing worktree")?)?;
1283    std::fs::create_dir_all(proof.parent().context("missing proof directory")?)?;
1284    let tmp = proof.with_extension("tmp");
1285    std::fs::write(
1286        &tmp,
1287        serde_json::to_vec(&CargoResidue {
1288            target: target.to_owned(),
1289            files,
1290        })?,
1291    )?;
1292    std::fs::rename(tmp, proof)?;
1293    Ok(())
1294}
1295
1296pub(crate) async fn verify_residue(home: &Path, id: &str, worktree: &Path) -> Result<Vec<File>> {
1297    let target = cargo_target(worktree).await?;
1298    residue_root(&target)?;
1299    let locks = cargo_locks(&target)?;
1300    let proof: CargoResidue =
1301        serde_json::from_slice(&std::fs::read(residue_proof(home, id, worktree)?)?)?;
1302    ensure!(
1303        proof.target == target && proof.files == residue_files(&target, &[])?,
1304        "Cargo residue changed or contains unproven files"
1305    );
1306    Ok(locks)
1307}
1308
1309/// Supplemental exclusion for Cargo builds launched outside the managed seats.
1310pub(crate) fn cargo_locks(target: &Path) -> Result<Vec<File>> {
1311    let mut held = Vec::new();
1312    for (profile, name) in ["debug", "release"].into_iter().flat_map(|profile| {
1313        [".cargo-lock", ".cargo-build-lock", ".cargo-artifact-lock"].map(|name| (profile, name))
1314    }) {
1315        let lock = target.join(profile).join(name);
1316        match std::fs::symlink_metadata(&lock) {
1317            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
1318            result => {
1319                result.with_context(|| format!("Cargo lock: inspect {}", lock.display()))?;
1320            }
1321        }
1322        {
1323            plain_file(&lock, "Cargo lock")?;
1324            let file = OpenOptions::new()
1325                .read(true)
1326                .write(true)
1327                .open(&lock)
1328                .with_context(|| format!("Cargo lock: open {}", lock.display()))?;
1329            crate::pr_head::try_lock_file(&file).map_err(|error| {
1330                let held = error.kind() == std::io::ErrorKind::WouldBlock
1331                    || cfg!(windows) && error.raw_os_error() == Some(33);
1332                if held {
1333                    anyhow::Error::new(error)
1334                        .context(format!("Cargo build is active: {}", lock.display()))
1335                } else {
1336                    anyhow::Error::new(LockCallFailed::new(
1337                        format!("Cargo lock {}", lock.display()),
1338                        error,
1339                    ))
1340                }
1341            })?;
1342            held.push(file);
1343        }
1344    }
1345    Ok(held)
1346}
1347
1348/// All repositories share one cap and one per-pass deletion budget. The report
1349/// survives a restart and explains every skipped run/target or failed operation.
1350pub(crate) async fn sweep(home: &Path, disk: &crate::config::Disk, now: Timestamp) -> Report {
1351    let home = home.to_owned();
1352    let disk = disk.clone();
1353    // Asked on the caller's thread: the pass itself runs on a blocking one.
1354    let containment = containment_available();
1355    let runtime = tokio::runtime::Handle::current();
1356    tokio::task::spawn_blocking(move || {
1357        runtime.block_on(sweep_inner_on(&home, &disk, now, containment))
1358    })
1359    .await
1360    .unwrap_or_else(|e| Report {
1361        failures: vec![format!("retention worker failed: {e}")],
1362        ..Report::default()
1363    })
1364}
1365
1366#[derive(Default, Serialize, Deserialize)]
1367struct Measurement {
1368    at: Option<Timestamp>,
1369    bytes: u64,
1370}
1371
1372/// What a pass records when the platform cannot contain a build's descendants.
1373/// Not removable by configuration: deleting outputs without that containment
1374/// could race a live compile.
1375const UNSUPPORTED_PLATFORM: &str = "Automatic output reclamation requires Unix process containment";
1376
1377/// Whether this platform can contain a build's descendants (Unix process
1378/// groups). Tests may turn it off for the calling thread.
1379fn containment_available() -> bool {
1380    #[cfg(test)]
1381    if let Some(forced) = NO_CONTAINMENT.with(std::cell::Cell::get) {
1382        return forced;
1383    }
1384    cfg!(unix)
1385}
1386
1387#[cfg(test)]
1388thread_local! {
1389    static NO_CONTAINMENT: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1390}
1391
1392/// Makes [`sweep`] behave, for the calling thread, as on a platform without
1393/// process containment, until dropped.
1394#[cfg(test)]
1395pub(crate) struct WithoutContainment;
1396
1397#[cfg(test)]
1398impl WithoutContainment {
1399    pub(crate) fn new() -> Self {
1400        NO_CONTAINMENT.with(|forced| forced.set(Some(false)));
1401        Self
1402    }
1403}
1404
1405#[cfg(test)]
1406impl Drop for WithoutContainment {
1407    fn drop(&mut self) {
1408        NO_CONTAINMENT.with(|forced| forced.set(None));
1409    }
1410}
1411
1412/// Persist the pass report (`retention.json`). A refusal is reported through
1413/// the same file as a completed pass, so a platform where reclamation is off
1414/// says so instead of leaving no report at all.
1415///
1416/// Every publication stages into its own uniquely named file and replaces
1417/// `retention.json` by rename, so two passes publishing at once (housekeeping
1418/// and disk-pressure workers overlap across an idle/busy transition, and a
1419/// platform that refuses reclamation takes no `retention.lock`) can neither
1420/// truncate nor rename each other's staging file: the report on disk is always
1421/// one complete report.
1422fn save_report(home: &Path, report: &Report) {
1423    if let Err(e) = publish_report(home, report) {
1424        tracing::warn!("retention report could not be saved: {e:#}");
1425    }
1426}
1427
1428const STAGING_PREFIX: &str = "retention.json.";
1429const STAGING_SUFFIX: &str = ".tmp";
1430/// A staging file this much older than a publication is the leftover of a
1431/// process that died between writing and renaming it.
1432const STAGING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
1433
1434/// Remove this report's staging files (including the single shared name earlier
1435/// builds used) that were last written more than `max_age` ago. Best effort.
1436fn remove_stale_staging(home: &Path, max_age: std::time::Duration) {
1437    for entry in std::fs::read_dir(home).into_iter().flatten().flatten() {
1438        let name = entry.file_name();
1439        let name = name.to_string_lossy();
1440        if !(name.starts_with(STAGING_PREFIX) && name.ends_with(STAGING_SUFFIX)) {
1441            continue;
1442        }
1443        let stale = entry
1444            .metadata()
1445            .and_then(|meta| meta.modified())
1446            .ok()
1447            .and_then(|written| written.elapsed().ok())
1448            .is_some_and(|age| age > max_age);
1449        if stale {
1450            let _ = std::fs::remove_file(entry.path());
1451        }
1452    }
1453}
1454
1455/// A new, uniquely named staging file, created exclusively: a name left by a
1456/// dead process with the same id is skipped, never written through.
1457fn create_staging(home: &Path) -> Result<(PathBuf, std::fs::File)> {
1458    static STAGED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1459    create_staging_numbered(home, &mut || {
1460        STAGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1461    })
1462}
1463
1464/// [`create_staging`] with the sequence of numbers supplied by `next`.
1465fn create_staging_numbered(
1466    home: &Path,
1467    next: &mut dyn FnMut() -> u64,
1468) -> Result<(PathBuf, std::fs::File)> {
1469    for _ in 0..64 {
1470        let tmp = home.join(format!(
1471            "{STAGING_PREFIX}{}-{}{STAGING_SUFFIX}",
1472            std::process::id(),
1473            next()
1474        ));
1475        match OpenOptions::new().write(true).create_new(true).open(&tmp) {
1476            Ok(file) => return Ok((tmp, file)),
1477            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
1478            Err(e) => return Err(e).with_context(|| format!("create {}", tmp.display())),
1479        }
1480    }
1481    anyhow::bail!("no unused staging name for the retention report")
1482}
1483
1484fn publish_report(home: &Path, report: &Report) -> Result<()> {
1485    use std::io::Write as _;
1486    remove_stale_staging(home, STAGING_MAX_AGE);
1487    let body = serde_json::to_vec_pretty(report)?;
1488    let (tmp, mut file) = create_staging(home)?;
1489    let published = file.write_all(&body).and_then(|()| {
1490        drop(file);
1491        std::fs::rename(&tmp, home.join("retention.json"))
1492    });
1493    if published.is_err() {
1494        let _ = std::fs::remove_file(&tmp);
1495    }
1496    Ok(published?)
1497}
1498
1499/// The pass itself, with the platform capability injected, so the refusal is
1500/// testable on a platform that has the capability.
1501async fn sweep_inner_on(
1502    home: &Path,
1503    disk: &crate::config::Disk,
1504    now: Timestamp,
1505    unix_containment: bool,
1506) -> Report {
1507    let mut report = Report {
1508        checked_at: Some(now),
1509        limit_bytes: disk.worktree_limit_bytes,
1510        reclaim_budget_bytes: disk.worktree_reclaim_bytes,
1511        ..Report::default()
1512    };
1513    if !unix_containment {
1514        report.failures.push(UNSUPPORTED_PLATFORM.into());
1515        save_report(home, &report);
1516        return report;
1517    }
1518    let Ok(_janitor) = OutputLease::lock(&home.join("retention.lock"), true) else {
1519        return report;
1520    };
1521    let mut targets = Vec::new();
1522    let mut under_pressure = false;
1523    let mut registrations = std::collections::HashMap::new();
1524    let measurements_path = home.join("output-measurements.json");
1525    let mut measurements: std::collections::BTreeMap<PathBuf, Measurement> =
1526        std::fs::read(&measurements_path)
1527            .ok()
1528            .and_then(|b| serde_json::from_slice(&b).ok())
1529            .unwrap_or_default();
1530    let mut observed = std::collections::BTreeSet::new();
1531    let mut ids: Vec<_> = std::fs::read_dir(home.join("runs"))
1532        .into_iter()
1533        .flatten()
1534        .flatten()
1535        .map(|e| e.file_name().to_string_lossy().into_owned())
1536        .collect();
1537    ids.sort();
1538    for id in ids {
1539        if !crate::run::is_run_id(&id) {
1540            continue;
1541        }
1542        let state = match RunState::load_under(&id, home) {
1543            Ok(state) => state,
1544            Err(e) => {
1545                report
1546                    .retained
1547                    .push(format!("{id}: unreadable run ownership: {e:#}"));
1548                continue;
1549            }
1550        };
1551        if disk.worktree_limit_bytes == 0 {
1552            continue;
1553        }
1554        match run_paths_missing(&state) {
1555            Ok(true) => continue,
1556            Ok(false) => {}
1557            Err(e) => {
1558                report.failures.push(format!("{id}: {e:#}"));
1559                continue;
1560            }
1561        }
1562        let list = match registrations.entry(state.repo.clone()) {
1563            std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
1564            std::collections::hash_map::Entry::Vacant(entry) => {
1565                match git::git(&state.repo, &["worktree", "list", "--porcelain"]).await {
1566                    Ok(list) => entry.insert(list),
1567                    Err(e) => {
1568                        // The checkout may disappear after the inventory check.
1569                        // Do not confuse a missing Git executable with that case.
1570                        if matches!(run_paths_missing(&state), Ok(true)) {
1571                            continue;
1572                        }
1573                        report.failures.push(format!("{id}: {e:#}"));
1574                        continue;
1575                    }
1576                }
1577            }
1578        };
1579        let paths = match registered_worktrees(&state, list) {
1580            Ok(paths) => paths,
1581            Err(e) => {
1582                report.failures.push(format!("{id}: {e:#}"));
1583                continue;
1584            }
1585        };
1586        for path in paths {
1587            if !path.join("target").exists() {
1588                continue;
1589            }
1590            let target = path.join("target");
1591            observed.insert(target.clone());
1592            let pressure =
1593                crate::disk::free_bytes(&path).map_or(true, |free| free < disk.min_free_bytes);
1594            under_pressure |= pressure;
1595            let measurement = measurements.entry(target).or_default();
1596            if pressure
1597                || measurement
1598                    .at
1599                    .is_none_or(|at| crate::clean::due(now, at, 300))
1600            {
1601                measurement.bytes = crate::disk::dir_size(&path.join("target"));
1602                measurement.at = Some(now);
1603            }
1604            let size = measurement.bytes;
1605            report.measured_bytes = report.measured_bytes.saturating_add(size);
1606            targets.push((state.output_activity(), id.clone(), path, size));
1607        }
1608    }
1609    if under_pressure {
1610        // Inventory sizes prioritize scarce-space recovery only; deletion authority
1611        // and budget accounting come from declared outputs measured under locks.
1612        targets.sort_by_key(|t| (std::cmp::Reverse(t.3), t.0));
1613    } else {
1614        targets.sort_by_key(|t| t.0);
1615    }
1616    let free_before = crate::disk::free_bytes(home).ok();
1617    #[cfg(unix)]
1618    {
1619        let mut seen = std::collections::BTreeSet::new();
1620        report.measured_allocated_file_bytes = Some(0);
1621        report.estimated_released_allocated_bytes = Some(0);
1622        report.proven_reclaimable_allocated_bytes = Some(0);
1623        for (_, _, path, _) in &targets {
1624            report.measured_allocated_file_bytes = report
1625                .measured_allocated_file_bytes
1626                .zip(allocated_inventory(&path.join("target"), &mut seen).ok())
1627                .map(|(a, b)| a.saturating_add(b));
1628        }
1629    }
1630    let mut remaining = report.measured_bytes;
1631    let pressure_paths: Vec<_> = targets.iter().map(|t| t.2.clone()).collect();
1632    let mut deletion_started = false;
1633    let mut oversized_started = false;
1634    for (updated, id, path, _) in targets {
1635        if disk.worktree_limit_bytes == 0
1636            || remaining <= disk.worktree_limit_bytes
1637                && crate::disk::free_bytes(&path).is_ok_and(|free| free >= disk.min_free_bytes)
1638        {
1639            report.retained.push(format!("{id}: output reclamation disabled or aggregate usage and free space are within policy"));
1640            continue;
1641        }
1642        if oversized_started || report.freed_bytes >= disk.worktree_reclaim_bytes {
1643            report
1644                .retained
1645                .push(format!("{id}: per-pass byte budget spent"));
1646            continue;
1647        }
1648        let result = async {
1649            ensure!(
1650                crate::clean::due(now, updated, disk.fold_grace_secs),
1651                "execution activity within grace period: {updated} (now {now}, grace {}s)", disk.fold_grace_secs
1652            );
1653            let _owner = crate::pr_head::owner_lock(home, &id)?;
1654            let state = RunState::load_under(&id, home)?;
1655            ensure!(
1656                state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
1657                    == Liveness::Dead,
1658                "run live or ownership unknown"
1659            );
1660            ensure!(crate::clean::due(now, state.output_activity(), disk.fold_grace_secs), "execution activity after inventory: {}", state.output_activity());
1661            let _driver = crate::driver::maintenance(home, &id)?;
1662            let _outputs = OutputLease::take(&path, true)?;
1663            ensure!(
1664                worktrees(&state).await?.contains(&path),
1665                "worktree registration changed"
1666            );
1667            let target = validate_cargo_target(&path, true).await
1668                .with_context(|| format!("stage validate-target: {}", path.join("target").display()))?;
1669            let _cargo = cargo_locks(&target)
1670                .with_context(|| format!("stage cargo-locks: {}", target.display()))?;
1671            // Cargo may have finished between identity inspection and locking.
1672            // Revalidate the same authority with all writers excluded.
1673            validate_cargo_target(&path, true).await
1674                .with_context(|| format!("stage validate-target (locked): {}", target.display()))?;
1675            let lease_meta = _outputs._file.metadata().context("output lease activity: metadata")?;
1676            if lease_meta.len() > 0 {
1677                ensure!(lease_meta.len() == 1, "output lease activity witness is unreadable or incomplete for {}", path.display());
1678                let lease_at = Timestamp::try_from(lease_meta.modified().context("output lease activity: modified")?)?;
1679                ensure!(crate::clean::due(now, lease_at, disk.fold_grace_secs),
1680                    "output lease activity within grace period: {lease_at} (now {now}, grace {}s)", disk.fold_grace_secs);
1681            }
1682            output_age(&target, now, disk.fold_grace_secs)
1683                .with_context(|| format!("stage output-age: {}", target.display()))?;
1684            let mut outputs = declared_outputs(&target)
1685                .with_context(|| format!("stage declared-outputs: {}", target.display()))?;
1686            let incremental = match crate::incremental::candidates(&path) {
1687                Ok(candidates) => candidates,
1688                Err(error) => {
1689                    report.retained.push(format!("{id}: incremental cache retained: {error:#}"));
1690                    crate::incremental::Reclaim::default()
1691                }
1692            };
1693            let incremental_files = incremental.files.clone();
1694            outputs.extend(incremental_files.iter().cloned());
1695            outputs.sort();
1696            outputs.dedup();
1697            ensure!(!outputs.is_empty(), "no dep-info-proven outputs or provenance-proven incremental caches; legacy incremental/build and unknown files retained");
1698            let sizes = outputs.iter().map(|p| std::fs::metadata(p).map(|m| m.len())
1699                .with_context(|| format!("stage measure: {}", p.display())))
1700                .collect::<Result<Vec<_>>>()?;
1701            let current_size = sizes.iter().fold(0u64, |bytes, size| bytes.saturating_add(*size));
1702            report.proven_reclaimable_bytes = report.proven_reclaimable_bytes.saturating_add(current_size);
1703            let mut allocation = ReleasedAllocation::of(&outputs)?;
1704            report.proven_reclaimable_allocated_bytes = report.proven_reclaimable_allocated_bytes
1705                .zip(allocation.reclaimable_allocated_bytes()).map(|(a, b)| a.saturating_add(b));
1706            let exceeds_budget = current_size > disk.worktree_reclaim_bytes.saturating_sub(report.freed_bytes);
1707            // 予算は1回の削除量を抑えるもので、大きな出力を永久に保持するためではない。
1708            // 正の予算では最初の削除対象だけ超過を許し、その後は予算消費済みとする。
1709            // 途中で失敗しても再度許可しないよう、例外は削除開始時に消費する。
1710            ensure!(!deletion_started || !exceeds_budget,
1711                "declared outputs exceed remaining per-pass byte budget");
1712            // Record adoption before deletion; interrupted deletion is revalidated
1713            // on the next pass. No source file or branch is modified.
1714            let ledger = home.join("runs").join(&id).join("build-outputs.json");
1715            std::fs::write(
1716                &ledger,
1717                serde_json::to_vec(
1718                    &serde_json::json!({"target":target,"bytes":current_size,"at":now,"action":"reclaim-declared-outputs","identity":if target.join("CACHEDIR.TAG").exists() { "cache-tag" } else { "rustc-profile-dep-info" },"files":outputs}),
1719                )?,
1720            ).with_context(|| format!("stage ledger: {}", ledger.display()))?;
1721            // Unknown leftovers still permit artifact-only eviction, but never
1722            // authorize retirement. Only a complete proven residue is adopted.
1723            if !incremental_files.is_empty() {
1724                report.retained.push(format!("{id}: incremental proof does not authorize retirement"));
1725            } else if let Err(error) = record_residue(home, &id, &target, &outputs) {
1726                report.retained.push(format!("{id}: residue not adopted for retirement: {error:#}"));
1727            }
1728            ensure!(worktrees(&state).await?.contains(&path),
1729                "worktree registration changed before deletion");
1730            deletion_started = true;
1731            oversized_started = exceeds_budget;
1732            measurements.remove(&target);
1733            for (output, size) in outputs.iter().zip(sizes) {
1734                std::fs::remove_file(output).with_context(|| format!("stage remove: {}", output.display()))?;
1735                report.estimated_released_allocated_bytes = report.estimated_released_allocated_bytes
1736                    .zip(allocation.unlinked(output)).map(|(a, b)| a.saturating_add(b));
1737                // Preserve actual progress even if a later removal fails.
1738                report.freed_bytes = report.freed_bytes.saturating_add(size);
1739                remaining = remaining.saturating_sub(size);
1740            }
1741            incremental.finish().context("finish incremental reclamation")?;
1742            report.retained.push(format!("{id}: unmanifested files and Cargo metadata retained"));
1743            Ok::<_, anyhow::Error>(())
1744        }
1745        .await;
1746        if let Err(e) = result {
1747            report.retained.push(format!(
1748                "{id}/{}: {e:#}",
1749                path.file_name().unwrap_or_default().to_string_lossy()
1750            ));
1751        }
1752    }
1753    measurements.retain(|path, _| observed.contains(path));
1754    if let Ok(body) = serde_json::to_vec(&measurements)
1755        && let Err(e) = std::fs::write(&measurements_path, body)
1756    {
1757        report.failures.push(format!("output measurements: {e}"));
1758    }
1759    copies::evict(home, disk, now, &mut report).await;
1760    retire_empty(home, disk, now, &mut report).await;
1761    report.protected_or_unproven_bytes = report
1762        .measured_bytes
1763        .saturating_sub(report.proven_reclaimable_bytes);
1764    let pressure_remaining = pressure_paths
1765        .iter()
1766        .any(|path| crate::disk::free_bytes(path).map_or(true, |free| free < disk.min_free_bytes));
1767    if !report.failures.is_empty()
1768        || disk.worktree_limit_bytes > 0
1769            && (remaining > disk.worktree_limit_bytes || pressure_remaining)
1770    {
1771        let details = report
1772            .retained
1773            .iter()
1774            .filter(|reason| {
1775                !reason.contains("within policy")
1776                    && !reason.ends_with("unmanifested files and Cargo metadata retained")
1777            })
1778            .take(4)
1779            .chain(report.failures.iter().take(2))
1780            .cloned()
1781            .collect::<Vec<_>>()
1782            .join("; ");
1783        crate::notices::raise_in(
1784            home,
1785            crate::notices::Notice::warn(
1786                "disk:retention",
1787                format!(
1788                    "Retention remains blocked by the disk cap, free-space floor or inspection failures (logical inventory {}B, proven reclaimable {}B, protected or unproven {}B, unlinked {}B). {} Retained/held targets: {details}. Inspect the cleanup report for active owners, retained recovery sources and failures.",
1789                    report.measured_bytes,
1790                    report.proven_reclaimable_bytes,
1791                    report.protected_or_unproven_bytes,
1792                    report.freed_bytes,
1793                    if report.proven_reclaimable_bytes == 0 {
1794                        "No inspected contents have deletion authority."
1795                    } else {
1796                        "Authorized reclamation was insufficient; remaining protections and budgets still apply."
1797                    }
1798                ),
1799            ),
1800        );
1801    }
1802    report.observed_home_free_change_bytes = free_before
1803        .zip(crate::disk::free_bytes(home).ok())
1804        .map(|(before, after)| {
1805            (i128::from(after) - i128::from(before))
1806                .clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
1807        });
1808    save_report(home, &report);
1809    tracing::info!(
1810        measured_bytes = report.measured_bytes,
1811        freed_bytes = report.freed_bytes,
1812        retired = report.retired,
1813        retained = report.retained.len(),
1814        failures = report.failures.len(),
1815        "retained worktree cleanup"
1816    );
1817    for reason in report.retained.iter().chain(&report.failures) {
1818        tracing::debug!(%reason, "worktree retained");
1819    }
1820    report
1821}
1822
1823async fn retire_empty(
1824    home: &Path,
1825    disk: &crate::config::Disk,
1826    now: Timestamp,
1827    report: &mut Report,
1828) {
1829    if !disk.auto_fold {
1830        return;
1831    }
1832    let queue = crate::queue::Queue::at(home.join("queue"));
1833    let questions = crate::ask::Questions::at(home.join("questions"));
1834    let open = questions.list_for_effects();
1835    for listed in queue.list() {
1836        let Ok(_claim) = queue.claim(&listed.id) else {
1837            continue;
1838        };
1839        let Ok(task) = queue.get(&listed.id) else {
1840            continue;
1841        };
1842        if open
1843            .iter()
1844            .any(|q| (q.run == task.id || task.blocked_by.contains(&q.id)) && q.status.open())
1845        {
1846            report.retained.push(format!(
1847                "{}: task has an unanswered owner decision",
1848                task.id
1849            ));
1850            continue;
1851        }
1852        let sources: Vec<_> = task
1853            .runs
1854            .iter()
1855            .collect::<std::collections::BTreeSet<_>>()
1856            .into_iter()
1857            .cloned()
1858            .collect();
1859        let mut useful = Vec::new();
1860        let mut selected = Vec::new();
1861        let mut public = Vec::new();
1862        let mut unreadable = false;
1863        for id in &sources {
1864            let Ok(state) = RunState::load_under(id, home) else {
1865                unreadable = true;
1866                continue;
1867            };
1868            if state.released() || state.retired_to.is_some() {
1869                continue;
1870            }
1871            if task.pr_recovery.is_some() && state.pr_recovery == task.pr_recovery {
1872                selected.push(state.clone());
1873            }
1874            if state.pr.is_some() && state.pr_taken_over_by.is_none() {
1875                public.push(state.clone());
1876            }
1877            if state.candidates.iter().any(|c| c.commits > 0 && !c.empty) {
1878                useful.push(state);
1879            }
1880        }
1881        // Prefer a durable owner-approved selection, then one existing PR
1882        // owner, then an unambiguous useful source. Distinct historical changes
1883        // without an owner selection cannot be resolved by creation time.
1884        let pool = if !selected.is_empty() {
1885            selected
1886        } else if !public.is_empty() {
1887            public
1888        } else {
1889            useful
1890        };
1891        if unreadable || pool.len() != 1 {
1892            report.retained.push(format!(
1893                "{}: recovery authority is ambiguous or history is unreadable; {} sources retained",
1894                task.id,
1895                sources.len()
1896            ));
1897            continue;
1898        }
1899        let authority = &pool[0];
1900        if authority.candidates.is_empty() {
1901            continue;
1902        }
1903        let latest = &authority.id;
1904        for id in &sources {
1905            if id == latest || report.retired >= 5 {
1906                continue;
1907            }
1908            if let Ok(state) = RunState::load_under(id, home)
1909                && state.retired_to.as_ref() == Some(latest)
1910                && worktrees(&state).await.is_ok_and(|paths| paths.is_empty())
1911            {
1912                continue;
1913            }
1914            let result = async {
1915                ensure!(
1916                    !task
1917                        .resume_override
1918                        .as_ref()
1919                        .is_some_and(|pin| pin.pinned_run.as_ref() == Some(id)),
1920                    "operator-pinned recovery run"
1921                );
1922                ensure!(
1923                    !task.replacement.as_ref().is_some_and(|pin| pin.run == *id),
1924                    "selected replacement recovery source"
1925                );
1926                let _owner = crate::pr_head::owner_lock(home, id)?;
1927                let mut state = RunState::load_under(id, home)?;
1928                ensure!(
1929                    state.repo == authority.repo,
1930                    "repository differs from recovery authority"
1931                );
1932                ensure!(
1933                    !crate::pr_recovery::explicit_sources_retained(home, id),
1934                    "explicitly retained recovery source"
1935                );
1936                ensure!(
1937                    state.liveness_under(home, crate::daemon::is_working_on(home, id, now))
1938                        == Liveness::Dead,
1939                    "run live or ownership unknown"
1940                );
1941                let _driver = crate::driver::maintenance(home, id)?;
1942                ensure!(
1943                    crate::clean::due(now, state.updated_at, disk.fold_grace_secs),
1944                    "within grace period"
1945                );
1946                ensure!(
1947                    !open.iter().any(|q| q.run == *id && q.status.open()),
1948                    "unanswered owner decision"
1949                );
1950                ensure!(
1951                    state.pr.is_none()
1952                        && state.pr_head.is_none()
1953                        && state.pr_recovery.is_none()
1954                        && state.land_approval.is_none()
1955                        && state.merge_decision.is_none()
1956                        && state.reviews.is_empty()
1957                        && state.recovery.is_none()
1958                        && state.candidate_preservation.is_empty()
1959                        && state.interrupted_implementations.is_empty()
1960                        && !state.released(),
1961                    "PR ownership or recovery checkpoint"
1962                );
1963                let proof = prove_empty(home, &state, latest).await?;
1964                commit_retirement(home, &queue, &task, &mut state, latest, &sources, now)?;
1965                // Durable retirement precedes removal. A crash retries removal
1966                // using the same proof; it cannot make this attempt resumable.
1967                for path in &proof.paths {
1968                    ensure!(
1969                        git::worktree_remove_clean(&state.repo, path).await?,
1970                        "Git refused clean worktree removal"
1971                    );
1972                }
1973                Ok::<_, anyhow::Error>(())
1974            }
1975            .await;
1976            match result {
1977                Ok(()) => report.retired += 1,
1978                Err(e) => report.retained.push(format!("{id}: {e:#}")),
1979            }
1980        }
1981    }
1982}
1983
1984struct EmptyProof {
1985    paths: Vec<PathBuf>,
1986    _outputs: Vec<OutputLease>,
1987    _cargo: Vec<File>,
1988}
1989
1990// Compare actual source bytes with the original tree independently of index
1991// stat caches, assume-unchanged flags, sparse checkout and fsmonitor hints.
1992pub(crate) async fn tracked_base(worktree: &Path, base: &str) -> Result<()> {
1993    let tree = git::git(worktree, &["ls-tree", "-r", "--full-tree", "-z", base]).await?;
1994    let mut files = Vec::new();
1995    let mut blobs = Vec::new();
1996    for record in tree.split('\0').filter(|s| !s.is_empty()) {
1997        let (header, name) = record.split_once('\t').context("unknown tree record")?;
1998        let parts: Vec<_> = header.split_whitespace().collect();
1999        ensure!(
2000            parts.len() == 3 && matches!(parts[0], "100644" | "100755") && parts[1] == "blob",
2001            "unsupported tracked source kind"
2002        );
2003        let path = worktree.join(name);
2004        let meta = std::fs::symlink_metadata(&path)?;
2005        ensure!(
2006            meta.is_file() && !meta.file_type().is_symlink() && path.canonicalize()? == path,
2007            "noncanonical tracked source"
2008        );
2009        #[cfg(unix)]
2010        {
2011            use std::os::unix::fs::PermissionsExt as _;
2012            ensure!(
2013                (meta.permissions().mode() & 0o111 != 0) == (parts[0] == "100755"),
2014                "tracked executable mode differs from original base"
2015            );
2016        }
2017        path.to_str().context("non UTF-8 source")?;
2018        files.push(git::path_arg(&path));
2019        blobs.push(parts[2].to_owned());
2020    }
2021    for (paths, expected) in files.chunks(64).zip(blobs.chunks(64)) {
2022        let mut args = vec!["hash-object", "--no-filters", "--"];
2023        args.extend(paths.iter().map(String::as_str));
2024        let actual = git::git(worktree, &args).await?;
2025        ensure!(
2026            actual.lines().eq(expected.iter().map(String::as_str)),
2027            "tracked bytes differ from original base"
2028        );
2029    }
2030    Ok(())
2031}
2032
2033async fn prove_empty(home: &Path, state: &RunState, authority: &str) -> Result<EmptyProof> {
2034    let id = &state.id;
2035    let paths = worktrees(state).await?;
2036    let mut guards = Vec::new();
2037    let mut cargo_guards = Vec::new();
2038    for path in &paths {
2039        guards.push(OutputLease::take(path, true)?);
2040        ensure!(
2041            git::rev_parse(path, "HEAD").await? == state.base_commit,
2042            "unique or unrecorded commits"
2043        );
2044        ensure!(
2045            git::git(
2046                path,
2047                &[
2048                    "--no-optional-locks",
2049                    "status",
2050                    "--porcelain",
2051                    "--untracked-files=all"
2052                ]
2053            )
2054            .await?
2055            .is_empty(),
2056            "tracked or untracked source changes"
2057        );
2058        ensure!(
2059            git::git(
2060                path,
2061                &[
2062                    "--no-optional-locks",
2063                    "status",
2064                    "--porcelain",
2065                    "--untracked-files=all",
2066                    "--ignored",
2067                    "--",
2068                    ".",
2069                    ":(exclude)target"
2070                ]
2071            )
2072            .await?
2073            .is_empty(),
2074            "source changes, ignored files or build outputs"
2075        );
2076        tracked_base(path, &state.base_commit).await?;
2077        match std::fs::symlink_metadata(path.join("target")) {
2078            Ok(_) => cargo_guards.extend(verify_residue(home, id, path).await?),
2079            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
2080            Err(error) => return Err(error.into()),
2081        }
2082        for checkpoint in [
2083            "rebase-merge",
2084            "rebase-apply",
2085            "sequencer",
2086            "BISECT_LOG",
2087            "REVERT_HEAD",
2088            "AUTO_MERGE",
2089            "MERGE_MSG",
2090            "CHERRY_PICK_HEAD",
2091            "MERGE_HEAD",
2092            "REBASE_HEAD",
2093        ] {
2094            let location = git::git(
2095                path,
2096                &[
2097                    "rev-parse",
2098                    "--path-format=absolute",
2099                    "--git-path",
2100                    checkpoint,
2101                ],
2102            )
2103            .await?;
2104            ensure!(
2105                matches!(std::fs::symlink_metadata(location.trim()), Err(e) if e.kind() == std::io::ErrorKind::NotFound),
2106                "retained Git recovery metadata: {checkpoint}"
2107            );
2108        }
2109        // Git also initializes ORIG_HEAD when creating a worktree.
2110        // Only an origin outside the base is a recovery source.
2111        let origin_path = git::git(
2112            path,
2113            &[
2114                "rev-parse",
2115                "--path-format=absolute",
2116                "--git-path",
2117                "ORIG_HEAD",
2118            ],
2119        )
2120        .await?;
2121        match std::fs::symlink_metadata(origin_path.trim()) {
2122            Ok(meta) => {
2123                ensure!(
2124                    meta.is_file() && !meta.file_type().is_symlink(),
2125                    "unknown ORIG_HEAD artifact"
2126                );
2127                git::rev_parse(path, "ORIG_HEAD")
2128                    .await
2129                    .context("unreadable ORIG_HEAD")?;
2130            }
2131            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2132            Err(e) => return Err(e.into()),
2133        }
2134        if let Ok(original) = git::rev_parse(path, "ORIG_HEAD").await {
2135            ensure!(
2136                git::git_raw(
2137                    path,
2138                    &["merge-base", "--is-ancestor", &original, &state.base_commit]
2139                )
2140                .await?
2141                .ok(),
2142                "ORIG_HEAD retains commits outside the original base"
2143            );
2144        }
2145        let heads = git::git(path, &["reflog", "show", "--format=%H", "HEAD"]).await?;
2146        for head in heads.lines().collect::<std::collections::BTreeSet<_>>() {
2147            ensure!(
2148                git::git_raw(
2149                    path,
2150                    &["merge-base", "--is-ancestor", head, &state.base_commit]
2151                )
2152                .await?
2153                .ok(),
2154                "worktree reflog retains commits outside the original base"
2155            );
2156        }
2157        for checkpoint in ["CHERRY_PICK_HEAD", "MERGE_HEAD", "REBASE_HEAD"] {
2158            ensure!(
2159                !git::git_raw(path, &["rev-parse", "--verify", checkpoint])
2160                    .await?
2161                    .ok(),
2162                "unfinished Git operation"
2163            );
2164        }
2165    }
2166    // Missing worktrees cannot establish that unrecorded prep edits
2167    // were empty. Recorded candidates must also point at the base.
2168    if paths.is_empty() && state.retired_to.as_deref() == Some(authority) {
2169        return Ok(EmptyProof {
2170            paths,
2171            _outputs: guards,
2172            _cargo: cargo_guards,
2173        });
2174    }
2175    ensure!(!paths.is_empty(), "no worktrees to prove empty");
2176    for candidate in &state.candidates {
2177        ensure!(
2178            (paths.contains(&candidate.worktree)
2179                || state.retired_to.as_deref() == Some(authority) && !candidate.worktree.exists())
2180                && git::rev_parse(&state.repo, &candidate.branch).await? == state.base_commit,
2181            "candidate recovery source"
2182        );
2183    }
2184    let pattern = format!("refs/heads/magi/{}/", state.short());
2185    let branches = git::git(
2186        &state.repo,
2187        &["for-each-ref", "--format=%(objectname)", &pattern],
2188    )
2189    .await?;
2190    ensure!(
2191        branches.lines().all(|head| head == state.base_commit),
2192        "unrecorded candidate branch changes"
2193    );
2194    Ok(EmptyProof {
2195        paths,
2196        _outputs: guards,
2197        _cargo: cargo_guards,
2198    })
2199}
2200
2201/// The only task-write critical section in retirement. All Git proof and
2202/// deletion happens outside it, under the run's owner/driver/output leases.
2203/// Atomic task writes make the earlier snapshot consistent; this final compare
2204/// rejects every intervening owner selection, hold, edit or history update.
2205fn commit_retirement(
2206    home: &Path,
2207    queue: &crate::queue::Queue,
2208    expected: &crate::queue::Task,
2209    state: &mut RunState,
2210    authority: &str,
2211    sources: &[String],
2212    now: Timestamp,
2213) -> Result<()> {
2214    let _write = queue.lock_task(&expected.id)?;
2215    let current = queue.get(&expected.id)?;
2216    ensure!(
2217        serde_json::to_value(&current)? == serde_json::to_value(expected)?,
2218        "task changed during retirement proof; retaining worktrees for the current owner decision"
2219    );
2220    ensure!(
2221        !current
2222            .resume_override
2223            .as_ref()
2224            .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&state.id))
2225            && !current
2226                .replacement
2227                .as_ref()
2228                .is_some_and(|pin| pin.run == state.id),
2229        "current owner selected this recovery source"
2230    );
2231    ensure!(
2232        !crate::pr_recovery::explicit_sources_retained(home, &state.id),
2233        "explicitly retained recovery source"
2234    );
2235    ensure!(
2236        !crate::ask::Questions::at(home.join("questions"))
2237            .list_for_effects()
2238            .iter()
2239            .any(|q| q.status.open()
2240                && (q.run == state.id
2241                    || q.run == current.id
2242                    || current.blocked_by.contains(&q.id))),
2243        "owner decision arrived during retirement proof"
2244    );
2245    let dir = home.join("recovery-lineages");
2246    std::fs::create_dir_all(&dir)?;
2247    let tmp = dir.join(format!("{}.tmp", current.id));
2248    let lineage = serde_json::json!({"task":current.id,"authority":authority,"sources":sources,
2249        "selection":current.pr_recovery,"task_updated_at":current.updated_at,"at":now});
2250    std::fs::write(&tmp, serde_json::to_vec_pretty(&lineage)?)?;
2251    std::fs::rename(tmp, dir.join(format!("{}.json", current.id)))?;
2252    state.retired_to = Some(authority.to_owned());
2253    state.event(
2254        "retention",
2255        format!(
2256            "empty attempt retired to {authority}; recovery sources: {}",
2257            sources.join(", ")
2258        ),
2259    );
2260    state.save_under(home)?;
2261    // No Git command or worktree removal may be added before this guard drops.
2262    Ok(())
2263}
2264
2265/// Wait for the emergency reserve to be exhausted. The normal floor requests
2266/// a checkpoint first; half the floor stops owned writers before node completion.
2267/// A failed measurement also closes admission rather than allowing blind writes.
2268pub(crate) async fn emergency(paths: Vec<PathBuf>, min_free: u64, isolated: bool) -> String {
2269    let measure = if isolated {
2270        crate::disk::managed_free_bytes
2271    } else {
2272        crate::disk::free_bytes
2273    };
2274    if min_free == 0 {
2275        return std::future::pending().await;
2276    }
2277    loop {
2278        for path in &paths {
2279            let existing = path.ancestors().find(|p| p.exists()).unwrap_or(path);
2280            match measure(existing) {
2281                Ok(free) if free >= min_free / 2 => {}
2282                Ok(free) => {
2283                    return format!(
2284                        "disk pressure: {free} bytes free; stopping owned writers to preserve the emergency reserve"
2285                    );
2286                }
2287                Err(e) => return format!("disk pressure: free space measurement failed: {e:#}"),
2288            }
2289        }
2290        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
2291    }
2292}
2293
2294#[cfg(all(test, unix))]
2295mod tests {
2296    use super::*;
2297    use crate::{
2298        config::{Config, Disk},
2299        queue::{Source, Task},
2300        run::{Candidate, RunStatus},
2301    };
2302
2303    struct Fx {
2304        _temp: tempfile::TempDir,
2305        home: PathBuf,
2306        repo: PathBuf,
2307        bay: PathBuf,
2308        base: String,
2309    }
2310    impl Fx {
2311        async fn new() -> Self {
2312            let temp = tempfile::tempdir().unwrap();
2313            let root = temp.path().canonicalize().unwrap();
2314            let home = root.join("home");
2315            let repo = root.join("repo");
2316            let bay = root.join("worktrees");
2317            std::fs::create_dir_all(&repo).unwrap();
2318            std::fs::create_dir_all(home.join("runs")).unwrap();
2319            git::git(&repo, &["init", "-b", "main"]).await.unwrap();
2320            git::git(&repo, &["config", "user.name", "Fixture"])
2321                .await
2322                .unwrap();
2323            git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
2324                .await
2325                .unwrap();
2326            git::git(&repo, &["config", "commit.gpgsign", "false"])
2327                .await
2328                .unwrap();
2329            std::fs::write(repo.join(".gitignore"), "target/\nscratch/\n").unwrap();
2330            std::fs::write(repo.join("source"), "base\n").unwrap();
2331            git::git(&repo, &["add", "."]).await.unwrap();
2332            git::git(&repo, &["commit", "-m", "fixture"]).await.unwrap();
2333            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
2334            Self {
2335                _temp: temp,
2336                home,
2337                repo,
2338                bay,
2339                base,
2340            }
2341        }
2342        async fn run(&self, tag: &str, useful: bool) -> RunState {
2343            let mut cfg = Config::default();
2344            cfg.graph.worktree_root = Some(self.bay.clone());
2345            let mut state = RunState::new(
2346                self.repo.clone(),
2347                "main".into(),
2348                self.base.clone(),
2349                "task".into(),
2350                cfg,
2351            );
2352            state.id = format!("20260101-000000-{tag}");
2353            state.status = RunStatus::Blocked;
2354            state.driver_exited = true;
2355            let wt = state.worktree_root().join("cand-A");
2356            let branch = format!("magi/{tag}/A");
2357            git::worktree_add_branch(&self.repo, &wt, &branch, &self.base)
2358                .await
2359                .unwrap();
2360            if useful {
2361                std::fs::write(wt.join("source"), tag).unwrap();
2362                git::git(&wt, &["add", "."]).await.unwrap();
2363                git::git(&wt, &["commit", "-m", "candidate change"])
2364                    .await
2365                    .unwrap();
2366            }
2367            state.candidates.push(Candidate {
2368                index: 0,
2369                label: 'A',
2370                agent: "fixture".into(),
2371                branch,
2372                worktree: wt,
2373                summary: String::new(),
2374                stat: String::new(),
2375                files: usize::from(useful),
2376                commits: usize::from(useful),
2377                empty: !useful,
2378                failed: None,
2379                verified_noop: None,
2380                duration_ms: 0,
2381                folded: false,
2382            });
2383            state.save_under(&self.home).unwrap();
2384            state
2385        }
2386        fn disk() -> Disk {
2387            Disk {
2388                worktree_limit_bytes: 1,
2389                worktree_reclaim_bytes: 1024 * 1024,
2390                fold_grace_secs: 0,
2391                min_free_bytes: 0,
2392                ..Disk::default()
2393            }
2394        }
2395        fn target(wt: &Path) {
2396            let target = wt.join("target");
2397            std::fs::create_dir_all(target.join("debug")).unwrap();
2398            let mut artifact = [1; 200];
2399            artifact[..4].copy_from_slice(b"\x7fELF");
2400            std::fs::write(target.join("debug/output"), artifact).unwrap();
2401            let output = target
2402                .join("debug/output")
2403                .display()
2404                .to_string()
2405                .replace('\\', "\\\\")
2406                .replace(' ', "\\ ");
2407            std::fs::write(target.join("debug/output.d"), format!("{output}: source\n")).unwrap();
2408            std::fs::write(target.join("debug/.cargo-lock"), "").unwrap();
2409            std::fs::write(
2410                target.join("CACHEDIR.TAG"),
2411                "Signature: 8a477f597d28d172789f06886806bc55\n",
2412            )
2413            .unwrap();
2414            std::fs::write(
2415                target.join(".rustc_info.json"),
2416                "{\"rustc_fingerprint\":123}",
2417            )
2418            .unwrap();
2419        }
2420        fn now() -> Timestamp {
2421            Timestamp::now() + jiff::SignedDuration::from_secs(2)
2422        }
2423        fn task(&self, runs: &[RunState]) -> Task {
2424            let mut task = Task::new(
2425                "fixture".into(),
2426                "task".into(),
2427                self.repo.clone(),
2428                Source::Human,
2429            );
2430            task.runs = runs.iter().map(|s| s.id.clone()).collect();
2431            crate::queue::Queue::at(self.home.join("queue"))
2432                .put(&mut task)
2433                .unwrap();
2434            task
2435        }
2436    }
2437
2438    /// A fold that is refused for the rule under test: the record is there and
2439    /// readable (the arrangement was saved in `home`), so a refusal that says
2440    /// `record gone` or `unreadable` would be the fixture's mistake, not the
2441    /// rule's. Returns the error for the caller to assert on.
2442    async fn refused(state: &mut RunState, home: &Path) -> anyhow::Error {
2443        use crate::graph::FoldRefusal;
2444        let error = crate::graph::fold_run(state, true, home)
2445            .await
2446            .expect_err("the fold is refused");
2447        assert!(
2448            !matches!(
2449                error.downcast_ref::<FoldRefusal>(),
2450                Some(FoldRefusal::RecordGone | FoldRefusal::Unreadable(_))
2451            ),
2452            "refused for the wrong reason: {error:#}"
2453        );
2454        error
2455    }
2456
2457    #[cfg(unix)]
2458    #[tokio::test]
2459    async fn incremental_only_reclamation_preserves_legacy_and_unknown_data() {
2460        let f = Fx::new().await;
2461        let state = f.run("ca01", true).await;
2462        let wt = &state.candidates[0].worktree;
2463        let generation = crate::incremental::tests::generate(wt);
2464        // Remove dep-info authority: incremental proof must be independent.
2465        assert!(!declared_outputs(&wt.join("target")).unwrap().is_empty());
2466        for dir in profile_output_dirs(&wt.join("target/debug"), true).unwrap() {
2467            for entry in std::fs::read_dir(dir).unwrap() {
2468                let path = entry.unwrap().path();
2469                if path.extension().is_some_and(|x| x == "d") {
2470                    std::fs::remove_file(path).unwrap();
2471                }
2472            }
2473        }
2474        assert!(declared_outputs(&wt.join("target")).unwrap().is_empty());
2475        assert_eq!(
2476            sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes,
2477            0,
2478            "live generation is protected"
2479        );
2480        drop(generation);
2481        let candidates = crate::incremental::candidates(wt).unwrap();
2482        let logical: u64 = candidates
2483            .files
2484            .iter()
2485            .map(|p| std::fs::metadata(p).unwrap().len())
2486            .sum();
2487        let unknown = candidates.files[0].parent().unwrap().join("operator-note");
2488        std::fs::write(&unknown, "retain unknown data").unwrap();
2489        drop(candidates);
2490        let refused = sweep(&f.home, &Fx::disk(), Fx::now()).await;
2491        assert_eq!(refused.freed_bytes, 0, "{refused:?}");
2492        assert!(
2493            refused
2494                .retained
2495                .iter()
2496                .any(|s| s.contains("provenance mismatch"))
2497        );
2498        std::fs::remove_file(&unknown).unwrap();
2499        let legacy = wt.join("target/debug/incremental/legacy-session");
2500        std::fs::create_dir(&legacy).unwrap();
2501        // Even compiler-authored bytes do not retroactively confer ownership.
2502        let candidates = crate::incremental::candidates(wt).unwrap();
2503        let bin = candidates
2504            .files
2505            .iter()
2506            .find(|p| p.extension().is_some_and(|x| x == "bin"))
2507            .unwrap();
2508        std::fs::copy(bin, legacy.join("query-cache.bin")).unwrap();
2509        drop(candidates);
2510        let cargo = cargo_locks(&wt.join("target")).unwrap();
2511        assert_eq!(sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes, 0);
2512        drop(cargo);
2513        let outputs = OutputLease::borrow(wt).unwrap().unwrap();
2514        assert_eq!(sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes, 0);
2515        drop(outputs);
2516        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
2517        assert_eq!(report.freed_bytes, logical, "{report:?}");
2518        assert_eq!(report.proven_reclaimable_bytes, logical);
2519        assert!(report.measured_bytes > logical);
2520        assert_eq!(
2521            report.protected_or_unproven_bytes,
2522            report.measured_bytes - logical
2523        );
2524        #[cfg(unix)]
2525        {
2526            assert!(report.estimated_released_allocated_bytes.unwrap() > 0);
2527            assert!(
2528                report.measured_allocated_file_bytes.unwrap()
2529                    >= report.estimated_released_allocated_bytes.unwrap()
2530            );
2531        }
2532        assert!(report.observed_home_free_change_bytes.is_some());
2533        assert!(legacy.join("query-cache.bin").is_file());
2534        assert!(wt.join("src/lib.rs").is_file());
2535        assert_eq!(report.retired, 0);
2536    }
2537
2538    #[cfg(unix)]
2539    #[tokio::test]
2540    async fn incremental_and_deps_links_account_for_retained_third_link() {
2541        use std::os::unix::fs::MetadataExt;
2542        let f = Fx::new().await;
2543        let state = f.run("ca02", true).await;
2544        let wt = &state.candidates[0].worktree;
2545        let generation = crate::incremental::tests::generate(wt);
2546        drop(generation);
2547        let candidates = crate::incremental::candidates(wt).unwrap();
2548        let objects = candidates
2549            .files
2550            .iter()
2551            .filter(|p| p.extension().is_some_and(|x| x == "o"))
2552            .take(2)
2553            .cloned()
2554            .collect::<Vec<_>>();
2555        assert_eq!(
2556            objects.len(),
2557            2,
2558            "fixture must produce real incremental objects"
2559        );
2560        let mut outputs = candidates.files.clone();
2561        drop(candidates);
2562        let target = wt.join("target");
2563        assert!(!declared_outputs(&target).unwrap().is_empty());
2564        let generated_dirs = profile_output_dirs(&target.join("debug"), true).unwrap();
2565        // The directory Cargo itself wrote its dep-info into (v1 `deps`, v2 unit
2566        // `out`): the links below go there, so the real layout is exercised.
2567        let mut output_dir = None;
2568        for dir in &generated_dirs {
2569            for entry in std::fs::read_dir(dir).unwrap() {
2570                let path = entry.unwrap().path();
2571                if path.extension().is_some_and(|x| x == "d") {
2572                    std::fs::remove_file(path).unwrap();
2573                    if dir != &generated_dirs[0] {
2574                        output_dir = Some(dir.clone());
2575                    }
2576                }
2577            }
2578        }
2579        let output_dir = output_dir.expect("Cargo generated no recognised output directory");
2580        // Cargo also leaves hard-linked object outputs beside the dep-info.
2581        // Remove those fixture outputs so the only external links are the
2582        // ones below.
2583        for entry in std::fs::read_dir(&output_dir).unwrap() {
2584            let path = entry.unwrap().path();
2585            if path.is_file() {
2586                std::fs::remove_file(path).unwrap();
2587            }
2588        }
2589        // v2 outputs need a dep-info stem matching a compiler fingerprint of
2590        // their unit; v1 has no such rule.
2591        let stem = if output_dir.file_name().is_some_and(|n| n == "out") {
2592            let unit = output_dir.parent().unwrap();
2593            let hash = unit.file_name().unwrap().to_string_lossy().into_owned();
2594            let name = std::fs::read_dir(unit.join("fingerprint"))
2595                .unwrap()
2596                .filter_map(|e| e.unwrap().file_name().into_string().ok())
2597                .find_map(|n| {
2598                    n.strip_prefix("lib-")
2599                        .filter(|n| !n.contains('.'))
2600                        .map(str::to_owned)
2601                })
2602                .expect("Cargo unit has a lib fingerprint");
2603            format!("{}-{hash}", name.replace('-', "_"))
2604        } else {
2605            "link".to_owned()
2606        };
2607        // One dep-info file may declare several outputs; the names differ only
2608        // by the optional `lib` prefix the artifact check accepts.
2609        let mut declared = Vec::new();
2610        for (index, object) in objects.iter().enumerate() {
2611            assert_eq!(std::fs::metadata(object).unwrap().nlink(), 1);
2612            let dep = output_dir.join(if index == 0 {
2613                stem.clone()
2614            } else {
2615                format!("lib{stem}")
2616            });
2617            std::fs::hard_link(object, &dep).unwrap();
2618            declared.push(dep.display().to_string());
2619            outputs.push(dep);
2620        }
2621        std::fs::write(
2622            output_dir.join(format!("{stem}.d")),
2623            format!("{}: src/lib.rs\n", declared.join(" ")),
2624        )
2625        .unwrap();
2626        let retained = wt.join("retained-input");
2627        std::fs::hard_link(&objects[1], &retained).unwrap();
2628        let sentinel = std::fs::read(&retained).unwrap();
2629        let logical: u64 = outputs
2630            .iter()
2631            .map(|p| std::fs::metadata(p).unwrap().len())
2632            .sum();
2633        let mut seen = std::collections::BTreeSet::new();
2634        let retained_meta = std::fs::metadata(&retained).unwrap();
2635        let retained_inode = (retained_meta.dev(), retained_meta.ino());
2636        let mut expected = 0u64;
2637        for output in &outputs {
2638            let m = std::fs::metadata(output).unwrap();
2639            let inode = (m.dev(), m.ino());
2640            if inode != retained_inode && seen.insert(inode) {
2641                expected += m.blocks() * 512;
2642            }
2643        }
2644        assert!(expected > 0);
2645        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
2646        assert_eq!(report.proven_reclaimable_bytes, logical, "{report:?}");
2647        assert_eq!(report.freed_bytes, logical, "{report:?}");
2648        assert_eq!(report.proven_reclaimable_allocated_bytes, Some(expected));
2649        assert_eq!(report.estimated_released_allocated_bytes, Some(expected));
2650        assert!(outputs.iter().all(|p| !p.exists()));
2651        assert_eq!(std::fs::read(retained).unwrap(), sentinel);
2652        assert!(wt.join("src/lib.rs").is_file());
2653    }
2654
2655    #[tokio::test]
2656    async fn retention_notice_explains_unproven_inventory_and_live_owner() {
2657        let f = Fx::new().await;
2658        let state = f.run("ca03", true).await;
2659        let wt = &state.candidates[0].worktree;
2660        Fx::target(wt);
2661        std::fs::remove_file(wt.join("target/debug/output")).unwrap();
2662        let unknown = wt.join("target/debug/operator-note");
2663        std::fs::write(&unknown, vec![1; 4096]).unwrap();
2664        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
2665        assert_eq!(report.proven_reclaimable_bytes, 0);
2666        #[cfg(unix)]
2667        assert_eq!(report.proven_reclaimable_allocated_bytes, Some(0));
2668        assert!(report.protected_or_unproven_bytes >= 4096);
2669        let message = || {
2670            crate::notices::Notices::at(f.home.join("notifications"))
2671                .list()
2672                .into_iter()
2673                .find(|n| n.key == "disk:retention")
2674                .unwrap()
2675                .message
2676        };
2677        let notice = message();
2678        assert!(notice.contains("proven reclaimable 0B"), "{notice}");
2679        assert!(notice.contains("protected or unproven"), "{notice}");
2680        assert!(
2681            notice.contains("legacy incremental/build and unknown files retained"),
2682            "{notice}"
2683        );
2684        let owner = crate::pr_head::owner_lock(&f.home, &state.id).unwrap();
2685        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
2686        assert_eq!(report.freed_bytes, 0);
2687        let notice = message();
2688        assert!(notice.contains(&state.id), "{notice}");
2689        assert!(
2690            notice.contains("lock") || notice.contains("owner"),
2691            "{notice}"
2692        );
2693        drop(owner);
2694        assert_eq!(std::fs::read(unknown).unwrap(), vec![1; 4096]);
2695    }
2696
2697    #[tokio::test]
2698    async fn real_cargo_build_holds_the_target_against_reclamation() {
2699        let f = Fx::new().await;
2700        let state = f.run("ca02", true).await;
2701        let wt = &state.candidates[0].worktree;
2702        Fx::target(wt);
2703        std::fs::create_dir(wt.join("src")).unwrap();
2704        std::fs::write(
2705            wt.join("Cargo.toml"),
2706            "[package]\nname='live-cache-fixture'\nversion='0.1.0'\nedition='2021'\n[workspace]\n",
2707        )
2708        .unwrap();
2709        std::fs::write(wt.join("src/lib.rs"), "pub fn answer() -> usize { 42 }\n").unwrap();
2710        std::fs::write(
2711            wt.join("build.rs"),
2712            r#"fn main() {
2713            println!("cargo:rerun-if-env-changed=FIXTURE_READY");
2714            let Ok(ready) = std::env::var("FIXTURE_READY") else { return };
2715            let release = std::env::var("FIXTURE_RELEASE").unwrap();
2716            std::fs::write(ready, "ready").unwrap();
2717            let start = std::time::Instant::now();
2718            while !std::path::Path::new(&release).exists() {
2719                assert!(start.elapsed().as_secs() < 120, "fixture was not released");
2720                std::thread::sleep(std::time::Duration::from_millis(10));
2721            }
2722        }"#,
2723        )
2724        .unwrap();
2725        let ready = wt.join("ready");
2726        let release = wt.join("release");
2727        let mut cargo = tokio::process::Command::new("cargo");
2728        cargo.env_clear();
2729        cargo.env(
2730            "PATH",
2731            crate::build_target::command::standalone_fixture_path().unwrap(),
2732        );
2733        for key in ["HOME", "RUSTUP_HOME"] {
2734            if let Some(value) = std::env::var_os(key) {
2735                cargo.env(key, value);
2736            }
2737        }
2738        cargo
2739            .current_dir(wt)
2740            .env("RUSTUP_TOOLCHAIN", "stable")
2741            .env("CARGO_HOME", f._temp.path().join("cargo-home"))
2742            .env("CARGO_INCREMENTAL", "1")
2743            .args(["build", "--offline", "--jobs", "1", "--target-dir"])
2744            .arg(wt.join("target"));
2745        // Compile before timing the active-build handshake. Under a parallel
2746        // gate, even this tiny fixture's first compiler startup can exceed the
2747        // readiness window; compilation speed is not what this test verifies.
2748        let warm = cargo.output().await.unwrap();
2749        assert!(
2750            warm.status.success(),
2751            "fixture compilation failed: {}",
2752            String::from_utf8_lossy(&warm.stderr)
2753        );
2754        let log_path = f._temp.path().join("live-cargo.stderr");
2755        let mut child = cargo
2756            .env("FIXTURE_READY", &ready)
2757            .env("FIXTURE_RELEASE", &release)
2758            .stdout(std::process::Stdio::null())
2759            .stderr(std::fs::File::create(&log_path).unwrap())
2760            .kill_on_drop(true)
2761            .spawn()
2762            .unwrap();
2763        let readiness = tokio::time::timeout(std::time::Duration::from_secs(60), async {
2764            while !ready.exists() {
2765                if let Some(status) = child.try_wait().unwrap() {
2766                    return Err(format!("fixture exited before readiness: {status}"));
2767                }
2768                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2769            }
2770            Ok(())
2771        })
2772        .await;
2773        let arrived = matches!(readiness, Ok(Ok(())));
2774        let report = if arrived {
2775            Some(sweep(&f.home, &Fx::disk(), Fx::now()).await)
2776        } else {
2777            None
2778        };
2779        // Release and join our build before making assertions, including on failure.
2780        std::fs::write(release, "release").unwrap();
2781        let status = tokio::time::timeout(std::time::Duration::from_secs(60), child.wait()).await;
2782        if status.is_err() {
2783            child.kill().await.unwrap();
2784            child.wait().await.unwrap();
2785        }
2786        assert!(
2787            arrived,
2788            "fixture build never reached its active build script: {readiness:?}\n{}",
2789            std::fs::read_to_string(&log_path).unwrap()
2790        );
2791        assert!(
2792            status.unwrap().unwrap().success(),
2793            "fixture build failed: {}",
2794            std::fs::read_to_string(&log_path).unwrap()
2795        );
2796        let report = report.unwrap();
2797        assert_eq!(report.freed_bytes, 0, "{report:?}");
2798        assert!(
2799            report
2800                .retained
2801                .iter()
2802                .any(|s| s.contains("Cargo build is active")),
2803            "{report:?}"
2804        );
2805        assert!(wt.join("target/debug/output").is_file());
2806        assert!(crate::disk::dir_size(&wt.join("target/debug/incremental")) > 0);
2807    }
2808
2809    #[cfg(unix)]
2810    #[test]
2811    fn allocated_accounting_deduplicates_links_and_requires_the_last_link() {
2812        let temp = tempfile::tempdir().unwrap();
2813        let a = temp.path().join("a");
2814        let b = temp.path().join("b");
2815        let outside = temp.path().join("retained-input");
2816        std::fs::write(&a, vec![1; 65536]).unwrap();
2817        std::fs::hard_link(&a, &b).unwrap();
2818        std::fs::hard_link(&a, &outside).unwrap();
2819        let mut seen = Default::default();
2820        let blocks = allocated_inventory(&temp.path().canonicalize().unwrap(), &mut seen).unwrap();
2821        assert!(blocks > 0);
2822        let mut accounting = ReleasedAllocation::of(&[a.clone(), b.clone()]).unwrap();
2823        std::fs::remove_file(&a).unwrap();
2824        assert_eq!(accounting.unlinked(&a), Some(0));
2825        std::fs::remove_file(&b).unwrap();
2826        assert_eq!(accounting.unlinked(&b), Some(0));
2827        assert_eq!(std::fs::read(&outside).unwrap().len(), 65536);
2828        let mut accounting = ReleasedAllocation::of(std::slice::from_ref(&outside)).unwrap();
2829        std::fs::remove_file(&outside).unwrap();
2830        assert_eq!(accounting.unlinked(&outside), Some(blocks));
2831    }
2832
2833    #[cfg(unix)]
2834    #[test]
2835    fn relative_admission_home_matches_absolute_home_and_retains_symlink_checks() {
2836        let temp = tempfile::tempdir_in(".").unwrap();
2837        let home = PathBuf::from(temp.path().file_name().unwrap()).join("state");
2838        assert!(home.is_relative());
2839        let paths = vec![std::env::current_dir().unwrap()];
2840        let gib = 1024 * 1024 * 1024;
2841        let reservation = OutputLease::admit_with(&home, &paths, 8 * gib, |_| Ok(9 * gib)).unwrap();
2842        assert!(
2843            OutputLease::admit_with(&home.canonicalize().unwrap(), &paths, 8 * gib, |_| Ok(
2844                9 * gib
2845            ))
2846            .is_err()
2847        );
2848        drop(reservation);
2849        assert!(OutputLease::admit_with(&home, &paths, 8 * gib, |_| Ok(9 * gib)).is_ok());
2850        let bad = temp.path().join("symlink-state");
2851        std::fs::create_dir(&bad).unwrap();
2852        std::os::unix::fs::symlink(
2853            home.canonicalize().unwrap().join("disk-admission"),
2854            bad.join("disk-admission"),
2855        )
2856        .unwrap();
2857        assert!(OutputLease::admit_with(&bad, &paths, 8 * gib, |_| Ok(9 * gib)).is_err());
2858    }
2859
2860    #[cfg(unix)]
2861    #[test]
2862    fn concurrent_disk_admission_reserves_once_per_volume_until_release() {
2863        let temp = tempfile::tempdir().unwrap();
2864        let home = temp.path().canonicalize().unwrap();
2865        let paths = vec![home.clone(), home.join("not-created-yet")];
2866        let gib = 1024 * 1024 * 1024;
2867        let floor = 8 * gib;
2868        let first = OutputLease::admit_with(&home, &paths, floor, |_| Ok(floor + gib)).unwrap();
2869        assert_eq!(first.len(), 1);
2870        let blocked =
2871            OutputLease::admit_with(&home, &paths, floor, |_| Ok(floor + gib)).unwrap_err();
2872        assert!(blocked.to_string().contains("active writer reservations"));
2873        let second =
2874            OutputLease::admit_with(&home, &paths, floor, |_| Ok(floor + 2 * gib)).unwrap();
2875        drop(first);
2876        assert!(OutputLease::admit_with(&home, &paths, floor, |_| Ok(floor + gib)).is_err());
2877        drop(second);
2878        assert!(OutputLease::admit_with(&home, &paths, floor, |_| Ok(floor + gib)).is_ok());
2879        assert!(
2880            OutputLease::admit_with(&home, &paths, floor, |_| anyhow::bail!("unmeasured")).is_err()
2881        );
2882    }
2883
2884    #[cfg(unix)]
2885    #[test]
2886    fn simultaneous_writers_cannot_spend_the_same_volume_headroom() {
2887        let temp = tempfile::tempdir().unwrap();
2888        let home = temp.path().canonicalize().unwrap();
2889        let barrier = std::sync::Barrier::new(2);
2890        let gib = 1024 * 1024 * 1024;
2891        let results = std::thread::scope(|scope| {
2892            let threads: Vec<_> = (0..2)
2893                .map(|_| {
2894                    scope.spawn(|| {
2895                        barrier.wait();
2896                        OutputLease::admit_with(&home, std::slice::from_ref(&home), 100, |_| {
2897                            Ok(100 + gib)
2898                        })
2899                    })
2900                })
2901                .collect();
2902            threads
2903                .into_iter()
2904                .map(|thread| thread.join().unwrap())
2905                .collect::<Vec<_>>()
2906        });
2907        assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 1);
2908        assert!(
2909            results
2910                .iter()
2911                .filter_map(|r| r.as_ref().err())
2912                .all(|e| e.to_string().contains("active writer reservations"))
2913        );
2914    }
2915
2916    #[tokio::test]
2917    async fn sweep_reclaims_real_cargo_outputs_and_preserves_source_and_unknown_files() {
2918        real_cargo_fixture(false).await;
2919    }
2920
2921    #[tokio::test]
2922    async fn missing_tag_from_precreated_target_reclaims_only_real_cargo_artifacts() {
2923        real_cargo_fixture(true).await;
2924    }
2925
2926    async fn real_cargo_fixture(precreate: bool) {
2927        let f = Fx::new().await;
2928        let state = f.run("ca00", true).await;
2929        let wt = &state.candidates[0].worktree;
2930        let source = "fn main() { println!(\"retained fixture\"); }\n";
2931        std::fs::create_dir(wt.join("src")).unwrap();
2932        std::fs::write(wt.join("src/main.rs"), source).unwrap();
2933        std::fs::write(
2934            wt.join("Cargo.toml"),
2935            "[package]\nname = \"retained-fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[workspace]\n",
2936        )
2937        .unwrap();
2938        if precreate {
2939            std::fs::create_dir_all(wt.join("target/magi-tools")).unwrap();
2940        }
2941        let mut cargo = std::process::Command::new("cargo");
2942        cargo.env_clear();
2943        cargo.env(
2944            "PATH",
2945            crate::build_target::command::standalone_fixture_path().unwrap(),
2946        );
2947        for key in ["HOME", "RUSTUP_HOME"] {
2948            if let Some(value) = std::env::var_os(key) {
2949                cargo.env(key, value);
2950            }
2951        }
2952        let build = cargo
2953            .current_dir(wt)
2954            .env("RUSTUP_TOOLCHAIN", "stable")
2955            .env("CARGO_HOME", f._temp.path().join("cargo-home"))
2956            .env("CARGO_INCREMENTAL", "0")
2957            .arg("--config")
2958            .arg(format!(
2959                "build.build-dir={}",
2960                serde_json::to_string(&wt.join("target")).unwrap()
2961            ))
2962            .args([
2963                "build",
2964                "--offline",
2965                "--release",
2966                "--jobs",
2967                "1",
2968                "--target-dir",
2969            ])
2970            .arg(wt.join("target"))
2971            .output()
2972            .unwrap();
2973        assert!(
2974            build.status.success(),
2975            "{}",
2976            String::from_utf8_lossy(&build.stderr)
2977        );
2978        assert_eq!(wt.join("target/CACHEDIR.TAG").exists(), !precreate);
2979        if precreate {
2980            // Cargo leaves pre-existing target roots untagged on subsequent builds too.
2981            let again = cargo.output().unwrap();
2982            assert!(
2983                again.status.success(),
2984                "{}",
2985                String::from_utf8_lossy(&again.stderr)
2986            );
2987            assert!(!wt.join("target/CACHEDIR.TAG").exists());
2988            assert!(cargo_target(wt).await.is_err());
2989        }
2990        git::git(wt, &["add", "Cargo.toml", "Cargo.lock", "src"])
2991            .await
2992            .unwrap();
2993        git::git(wt, &["commit", "-m", "real Cargo fixture"])
2994            .await
2995            .unwrap();
2996        let artifact = wt.join("target/release/retained-fixture");
2997        assert!(artifact.is_file());
2998        let unknown = wt.join("target/release/operator-note");
2999        std::fs::write(&unknown, "keep this note\n").unwrap();
3000
3001        let target = wt.join("target");
3002        let mut preserved = std::collections::BTreeMap::new();
3003        for relative in [
3004            "tmp/sentinel",
3005            "magi-tools/sentinel",
3006            "lifecycle-client-check.log",
3007        ] {
3008            let path = target.join(relative);
3009            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3010            std::fs::write(&path, format!("retain {relative}\n")).unwrap();
3011            preserved.insert(path.clone(), std::fs::read(path).unwrap());
3012        }
3013        // Even genuine compiler bytes and valid dep-info outside supported
3014        // profiles cannot expand the deletion inventory.
3015        let decoy = target.join("magi-tools/retained-fixture");
3016        std::fs::copy(&artifact, &decoy).unwrap();
3017        let dep_info = decoy.with_extension("d");
3018        std::fs::write(&dep_info, format!("{}: src/main.rs\n", decoy.display())).unwrap();
3019        for path in [
3020            decoy,
3021            dep_info,
3022            wt.join("Cargo.toml"),
3023            wt.join("Cargo.lock"),
3024        ] {
3025            preserved.insert(path.clone(), std::fs::read(path).unwrap());
3026        }
3027        let supported_dirs = profile_output_dirs(&target.join("release"), true).unwrap();
3028        let proven = declared_outputs(&target).unwrap();
3029        assert!(
3030            proven
3031                .iter()
3032                .any(|path| path.parent() != Some(target.join("release").as_path())),
3033            "both uplifted and unit/deps binary references must be proven: {proven:?}"
3034        );
3035
3036        let out = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3037        assert!(out.freed_bytes > 0, "{out:?}");
3038        for (path, bytes) in preserved {
3039            assert_eq!(std::fs::read(&path).unwrap(), bytes, "{}", path.display());
3040        }
3041        assert!(!artifact.exists(), "{out:?}");
3042        assert_eq!(
3043            std::fs::read_to_string(wt.join("src/main.rs")).unwrap(),
3044            source
3045        );
3046        assert_eq!(
3047            std::fs::read_to_string(&unknown).unwrap(),
3048            "keep this note\n"
3049        );
3050        assert_eq!(std::fs::read_to_string(wt.join("source")).unwrap(), "ca00");
3051        let ledger: serde_json::Value = serde_json::from_slice(
3052            &std::fs::read(
3053                f.home
3054                    .join("runs")
3055                    .join(&state.id)
3056                    .join("build-outputs.json"),
3057            )
3058            .unwrap(),
3059        )
3060        .unwrap();
3061        assert_eq!(
3062            ledger["identity"],
3063            if precreate {
3064                "rustc-profile-dep-info"
3065            } else {
3066                "cache-tag"
3067            }
3068        );
3069        if precreate {
3070            assert!(!target.join("CACHEDIR.TAG").exists());
3071            assert!(verify_residue(&f.home, &state.id, wt).await.is_err());
3072        }
3073        let deleted: Vec<PathBuf> = serde_json::from_value(ledger["files"].clone()).unwrap();
3074        assert!(deleted.contains(&artifact));
3075        assert_eq!(deleted, proven);
3076        for path in deleted {
3077            assert!(!path.exists());
3078            assert!(supported_dirs.contains(&path.parent().unwrap().to_owned()));
3079        }
3080        assert!(!residue_proof(&f.home, &state.id, wt).unwrap().exists());
3081    }
3082
3083    fn missing_tag_target(wt: &Path) {
3084        Fx::target(wt);
3085        let target = wt.join("target");
3086        std::fs::remove_file(target.join("CACHEDIR.TAG")).unwrap();
3087        for subdir in ["debug/deps", "debug/.fingerprint"] {
3088            std::fs::create_dir_all(target.join(subdir)).unwrap();
3089        }
3090        std::fs::write(target.join(".rustc_info.json"),
3091            r#"{"rustc_fingerprint":123,"outputs":{"1":{"success":true,"stdout":"rustc fixture","stderr":""}},"successes":{}}"#).unwrap();
3092    }
3093
3094    // Synthetic v2 coverage runs even on toolchains that still produce v1.
3095    fn v2_target(wt: &Path) -> PathBuf {
3096        missing_tag_target(wt);
3097        let target = wt.join("target");
3098        std::fs::remove_dir(target.join("debug/deps")).unwrap();
3099        std::fs::remove_dir(target.join("debug/.fingerprint")).unwrap();
3100        let unit = target.join("debug/build/fixture/0123456789abcdef");
3101        let out = unit.join("out");
3102        std::fs::create_dir_all(&out).unwrap();
3103        std::fs::create_dir(unit.join("fingerprint")).unwrap();
3104        for name in [
3105            "lib-fixture",
3106            "lib-fixture.json",
3107            "dep-lib-fixture",
3108            "invoked.timestamp",
3109        ] {
3110            std::fs::write(unit.join("fingerprint").join(name), "fixture").unwrap();
3111        }
3112        let artifact = out.join("libfixture-0123456789abcdef.rlib");
3113        std::fs::copy(target.join("debug/output"), &artifact).unwrap();
3114        std::fs::write(
3115            out.join("fixture-0123456789abcdef.d"),
3116            format!("{}: source\n", artifact.display()),
3117        )
3118        .unwrap();
3119        artifact
3120    }
3121
3122    #[tokio::test]
3123    async fn missing_tag_v2_proves_only_compiler_units_and_preserves_retained_links() {
3124        let f = Fx::new().await;
3125        let state = f.run("bc01", true).await;
3126        let wt = &state.candidates[0].worktree;
3127        let artifact = v2_target(wt);
3128        let unknown = artifact.parent().unwrap().join("operator-note");
3129        std::fs::write(&unknown, "retain").unwrap();
3130        // A valid binary and dep-info in arbitrary build-script output are not authority.
3131        let script_unit = wt.join("target/debug/build/fixture/fedcba9876543210");
3132        let script = script_unit.join("out");
3133        std::fs::create_dir_all(&script).unwrap();
3134        std::fs::create_dir(script_unit.join("fingerprint")).unwrap();
3135        std::fs::write(script_unit.join("fingerprint/invoked.timestamp"), "fixture").unwrap();
3136        let decoy = script.join("libfixture-fedcba9876543210.rlib");
3137        std::fs::copy(&artifact, &decoy).unwrap();
3138        std::fs::write(
3139            script.join("fixture-fedcba9876543210.d"),
3140            format!("{}: source\n", decoy.display()),
3141        )
3142        .unwrap();
3143        // Cargo uplifts the same inode from the unit into the profile root.
3144        let uplift = wt.join("target/debug/libfixture.rlib");
3145        std::fs::hard_link(&artifact, &uplift).unwrap();
3146        std::fs::write(
3147            wt.join("target/debug/fixture.d"),
3148            format!("{}: source\n", uplift.display()),
3149        )
3150        .unwrap();
3151        let bin_unit = wt.join("target/debug/build/fixture/1111111111111111");
3152        std::fs::create_dir_all(bin_unit.join("out")).unwrap();
3153        std::fs::create_dir(bin_unit.join("fingerprint")).unwrap();
3154        for name in [
3155            "bin-fixture",
3156            "bin-fixture.json",
3157            "dep-bin-fixture",
3158            "invoked.timestamp",
3159        ] {
3160            std::fs::write(bin_unit.join("fingerprint").join(name), "fixture").unwrap();
3161        }
3162        let bin = bin_unit.join("out/fixture");
3163        std::fs::hard_link(wt.join("target/debug/output"), &bin).unwrap();
3164        std::fs::write(
3165            bin.with_extension("d"),
3166            format!("{}: source\n", bin.display()),
3167        )
3168        .unwrap();
3169        let retained = wt.join("retained-link");
3170        std::fs::hard_link(&artifact, &retained).unwrap();
3171        use std::os::unix::fs::MetadataExt;
3172        let expected_allocation = std::fs::metadata(wt.join("target/debug/output"))
3173            .unwrap()
3174            .blocks()
3175            * 512;
3176        let sentinel = std::fs::read(&retained).unwrap();
3177        let first = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3178        assert_eq!(first.freed_bytes, 800, "{first:?}");
3179        assert!(!bin.exists());
3180        assert_eq!(
3181            first.estimated_released_allocated_bytes,
3182            Some(expected_allocation)
3183        );
3184        assert_eq!(std::fs::read(&retained).unwrap(), sentinel);
3185        assert!(retained.is_file());
3186        assert!(unknown.is_file());
3187        assert!(decoy.is_file());
3188        assert!(!artifact.exists());
3189        // Unlinking proven names must never remove the retained reference's bytes.
3190        assert_eq!(std::fs::metadata(retained).unwrap().len(), 200);
3191    }
3192
3193    #[tokio::test]
3194    async fn missing_tag_v2_accepts_completed_build_script_run_units() {
3195        let f = Fx::new().await;
3196        let state = f.run("bc02", true).await;
3197        let wt = &state.candidates[0].worktree;
3198        let artifact = v2_target(wt);
3199        let run = wt.join("target/debug/build/fixture/2222222222222222");
3200        std::fs::create_dir_all(run.join("out")).unwrap();
3201        std::fs::create_dir(run.join("fingerprint")).unwrap();
3202        for name in [
3203            "run-build-script-build-script-build",
3204            "run-build-script-build-script-build.json",
3205        ] {
3206            std::fs::write(run.join("fingerprint").join(name), "fixture").unwrap();
3207        }
3208        // Build-script output carries no deletion authority.
3209        let decoy = run.join("out/libdecoy-2222222222222222.rlib");
3210        std::fs::copy(&artifact, &decoy).unwrap();
3211        std::fs::write(
3212            run.join("out/decoy-2222222222222222.d"),
3213            format!("{}: source\n", decoy.display()),
3214        )
3215        .unwrap();
3216        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3217        assert!(report.freed_bytes > 0, "{report:?}");
3218        assert!(!artifact.exists());
3219        assert!(decoy.is_file());
3220    }
3221
3222    #[tokio::test]
3223    async fn missing_tag_v2_rejects_incomplete_mixed_and_symlinked_layouts() {
3224        for invalid in [
3225            "build",
3226            "deps",
3227            ".fingerprint",
3228            "out",
3229            "fingerprint",
3230            "hash",
3231            "mixed",
3232            "unit-fingerprint",
3233            "compiler-fingerprint",
3234            "absent-out",
3235        ] {
3236            let f = Fx::new().await;
3237            let state = f.run("bc02", true).await;
3238            let wt = &state.candidates[0].worktree;
3239            let artifact = v2_target(wt);
3240            let unit = artifact.parent().unwrap().parent().unwrap();
3241            let profile = wt.join("target/debug");
3242            match invalid {
3243                "mixed" => {
3244                    std::fs::create_dir(profile.join("deps")).unwrap();
3245                    std::fs::create_dir(profile.join(".fingerprint")).unwrap();
3246                }
3247                "hash" => {
3248                    std::fs::rename(unit, unit.with_file_name("unknown")).unwrap();
3249                }
3250                "unit-fingerprint" => {
3251                    std::fs::remove_file(unit.join("fingerprint/invoked.timestamp")).unwrap();
3252                }
3253                "compiler-fingerprint" => {
3254                    std::fs::remove_file(unit.join("fingerprint/lib-fixture.json")).unwrap();
3255                }
3256                "absent-out" => {
3257                    std::fs::remove_dir_all(unit.join("out")).unwrap();
3258                }
3259                name => {
3260                    let path = if matches!(name, "out" | "fingerprint") {
3261                        unit.join(name)
3262                    } else {
3263                        profile.join(name)
3264                    };
3265                    if path.exists() {
3266                        std::fs::remove_dir_all(&path).unwrap();
3267                    }
3268                    std::os::unix::fs::symlink(&f.repo, &path).unwrap();
3269                }
3270            }
3271            let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3272            assert_eq!(report.freed_bytes, 0, "{invalid}: {report:?}");
3273            assert!(!report.retained.is_empty(), "{invalid}: {report:?}");
3274        }
3275    }
3276
3277    #[tokio::test]
3278    async fn bookkeeping_flushes_do_not_extend_artifact_grace_including_legacy_records() {
3279        for legacy in [false, true] {
3280            let f = Fx::new().await;
3281            let mut state = f.run("ac00", true).await;
3282            Fx::target(&state.candidates[0].worktree);
3283            let original = state.updated_at;
3284            let now = Fx::now() + jiff::SignedDuration::from_secs(7200);
3285            if legacy {
3286                let path = f.home.join("runs").join(&state.id).join("run.json");
3287                let mut value = serde_json::to_value(&state).unwrap();
3288                value.as_object_mut().unwrap().remove("output_activity_at");
3289                std::fs::write(path, serde_json::to_vec(&value).unwrap()).unwrap();
3290                state = RunState::load_under(&state.id, &f.home).unwrap();
3291                assert_eq!(state.output_activity(), original);
3292            }
3293            let age = state.output_activity();
3294            for offset in [30, 20, 10] {
3295                state
3296                    .save_under_at(&f.home, now - jiff::SignedDuration::from_secs(offset))
3297                    .unwrap();
3298                state = RunState::load_under(&state.id, &f.home).unwrap();
3299                assert_eq!(state.output_activity(), age);
3300            }
3301            let mut disk = Fx::disk();
3302            disk.fold_grace_secs = 3600;
3303            let report = sweep(&f.home, &disk, now).await;
3304            assert_eq!(report.freed_bytes, 200, "legacy={legacy}: {report:?}");
3305        }
3306    }
3307
3308    #[tokio::test]
3309    async fn recent_execution_outputs_and_released_output_leases_retain_artifacts() {
3310        for evidence in [
3311            "execution",
3312            "artifact",
3313            "dep-info",
3314            "fingerprint",
3315            "lease",
3316            "future",
3317        ] {
3318            let f = Fx::new().await;
3319            let mut state = f.run("ac01", true).await;
3320            let wt = state.candidates[0].worktree.clone();
3321            missing_tag_target(&wt);
3322            let now = Fx::now() + jiff::SignedDuration::from_secs(7200);
3323            let recent = now - jiff::SignedDuration::from_secs(10);
3324            match evidence {
3325                "execution" => {
3326                    state.note_output_activity(recent);
3327                    state.save_under_at(&f.home, recent).unwrap();
3328                }
3329                "lease" => {
3330                    let lease = OutputLease::borrow(&wt).unwrap().unwrap();
3331                    let file = lease._file.try_clone().unwrap();
3332                    drop(lease);
3333                    file.set_modified(std::time::SystemTime::from(recent))
3334                        .unwrap();
3335                }
3336                _ => {
3337                    let relative = match evidence {
3338                        "dep-info" => "debug/output.d",
3339                        "fingerprint" => "debug/.fingerprint/invoked.timestamp",
3340                        _ => "debug/output",
3341                    };
3342                    let path = wt.join("target").join(relative);
3343                    let file = OpenOptions::new()
3344                        .write(true)
3345                        .create(true)
3346                        .truncate(false)
3347                        .open(path)
3348                        .unwrap();
3349                    let at = if evidence == "future" {
3350                        now + jiff::SignedDuration::from_secs(10)
3351                    } else {
3352                        recent
3353                    };
3354                    file.set_modified(std::time::SystemTime::from(at)).unwrap();
3355                }
3356            }
3357            let mut disk = Fx::disk();
3358            disk.fold_grace_secs = 3600;
3359            let report = sweep(&f.home, &disk, now).await;
3360            assert_eq!(report.freed_bytes, 0, "{evidence}: {report:?}");
3361            assert!(
3362                report.retained.iter().any(|s| s.contains("grace period")
3363                    || s.contains("execution activity after inventory")),
3364                "{evidence}: {report:?}"
3365            );
3366            let aged = now + jiff::SignedDuration::from_secs(7200);
3367            let report = sweep(&f.home, &disk, aged).await;
3368            assert_eq!(report.freed_bytes, 200, "{evidence}: {report:?}");
3369        }
3370    }
3371
3372    #[tokio::test]
3373    async fn missing_tag_proof_preserves_locks_unknown_files_and_retirement_boundary() {
3374        let f = Fx::new().await;
3375        let state = f.run("ac02", true).await;
3376        let wt = &state.candidates[0].worktree;
3377        missing_tag_target(wt);
3378        let target = wt.join("target");
3379        let unknown = target.join("debug/notes");
3380        std::fs::write(&unknown, "operator data").unwrap();
3381        for lock in [".cargo-lock", ".cargo-build-lock", ".cargo-artifact-lock"] {
3382            let path = target.join("debug").join(lock);
3383            let file = OpenOptions::new()
3384                .create(true)
3385                .truncate(false)
3386                .read(true)
3387                .write(true)
3388                .open(&path)
3389                .unwrap();
3390            crate::pr_head::try_lock_file(&file).unwrap();
3391            let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3392            assert_eq!(report.freed_bytes, 0, "{lock}: {report:?}");
3393            assert!(
3394                report
3395                    .retained
3396                    .iter()
3397                    .any(|s| s.contains(path.to_str().unwrap())),
3398                "{report:?}"
3399            );
3400        }
3401        let owner = crate::pr_head::owner_lock(&f.home, &state.id).unwrap();
3402        assert_eq!(sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes, 0);
3403        drop(owner);
3404        let driver = crate::driver::maintenance(&f.home, &state.id).unwrap();
3405        assert_eq!(sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes, 0);
3406        drop(driver);
3407        let output = OutputLease::borrow(wt).unwrap().unwrap();
3408        assert_eq!(sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes, 0);
3409        drop(output);
3410        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3411        assert_eq!(report.freed_bytes, 200, "{report:?}");
3412        assert_eq!(std::fs::read_to_string(unknown).unwrap(), "operator data");
3413        assert!(!target.join("CACHEDIR.TAG").exists());
3414        assert!(!residue_proof(&f.home, &state.id, wt).unwrap().exists());
3415        assert!(verify_residue(&f.home, &state.id, wt).await.is_err());
3416        assert_eq!(sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes, 0);
3417    }
3418
3419    #[tokio::test]
3420    async fn missing_tag_partial_reclamation_can_resume_without_adopting_residue() {
3421        let f = Fx::new().await;
3422        let state = f.run("ac04", true).await;
3423        let wt = &state.candidates[0].worktree;
3424        missing_tag_target(wt);
3425        let target = wt.join("target");
3426        let first = target.join("debug/output");
3427        let second = target.join("debug/second");
3428        std::fs::copy(&first, &second).unwrap();
3429        std::fs::write(
3430            second.with_extension("d"),
3431            format!("{}: source\n", second.display()),
3432        )
3433        .unwrap();
3434        let outputs = declared_outputs(&target).unwrap();
3435        assert_eq!(outputs.len(), 2);
3436        // Simulate interruption after durable adoption and one successful unlink.
3437        std::fs::write(f.home.join("runs").join(&state.id).join("build-outputs.json"),
3438            serde_json::to_vec(&serde_json::json!({"target":target,"files":outputs,"action":"reclaim-declared-outputs"})).unwrap()).unwrap();
3439        std::fs::remove_file(first).unwrap();
3440        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3441        assert_eq!(report.freed_bytes, 200, "{report:?}");
3442        assert!(!second.exists());
3443        assert!(second.with_extension("d").exists());
3444        assert!(!residue_proof(&f.home, &state.id, wt).unwrap().exists());
3445    }
3446
3447    #[tokio::test]
3448    async fn missing_tag_proof_rejects_invalid_identity_structure_and_symlinks() {
3449        for invalid in [
3450            "identity",
3451            "deps",
3452            "fingerprint",
3453            "lock",
3454            "dep-info",
3455            "tag-symlink",
3456            "bad-tag",
3457        ] {
3458            let f = Fx::new().await;
3459            let state = f.run("ac03", true).await;
3460            let wt = &state.candidates[0].worktree;
3461            missing_tag_target(wt);
3462            let target = wt.join("target");
3463            match invalid {
3464                "identity" => std::fs::write(
3465                    target.join(".rustc_info.json"),
3466                    r#"{"rustc_fingerprint":123}"#,
3467                )
3468                .unwrap(),
3469                "deps" | "fingerprint" => {
3470                    let path = target.join("debug").join(if invalid == "deps" {
3471                        "deps"
3472                    } else {
3473                        ".fingerprint"
3474                    });
3475                    std::fs::remove_dir(&path).unwrap();
3476                    std::os::unix::fs::symlink(&f.repo, path).unwrap();
3477                }
3478                "lock" => {
3479                    std::fs::remove_file(target.join("debug/.cargo-lock")).unwrap();
3480                }
3481                "dep-info" => std::fs::write(target.join("debug/output.d"), "").unwrap(),
3482                "tag-symlink" => {
3483                    std::os::unix::fs::symlink(target.join("absent"), target.join("CACHEDIR.TAG"))
3484                        .unwrap()
3485                }
3486                "bad-tag" => std::fs::write(target.join("CACHEDIR.TAG"), "unknown").unwrap(),
3487                _ => unreachable!(),
3488            }
3489            let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3490            assert_eq!(report.freed_bytes, 0, "{invalid}: {report:?}");
3491            assert!(target.join("debug/output").is_file());
3492        }
3493    }
3494
3495    #[tokio::test]
3496    async fn sweep_budget_oversized_target_makes_progress_without_a_second_deletion() {
3497        let f = Fx::new().await;
3498        let first = f.run("ba00", true).await;
3499        let second = f.run("ba01", true).await;
3500        for state in [&first, &second] {
3501            Fx::target(&state.candidates[0].worktree);
3502        }
3503        let mut disk = Fx::disk();
3504        disk.worktree_reclaim_bytes = 100;
3505        let out = sweep(&f.home, &disk, Fx::now()).await;
3506        assert_eq!(out.freed_bytes, 200, "{out:?}");
3507        assert!(
3508            out.retained
3509                .contains(&format!("{}: per-pass byte budget spent", second.id)),
3510            "{out:?}"
3511        );
3512        assert!(
3513            !first.candidates[0]
3514                .worktree
3515                .join("target/debug/output")
3516                .exists()
3517        );
3518        assert!(
3519            second.candidates[0]
3520                .worktree
3521                .join("target/debug/output")
3522                .exists()
3523        );
3524        assert_eq!(sweep(&f.home, &disk, Fx::now()).await.freed_bytes, 200);
3525    }
3526
3527    #[tokio::test]
3528    async fn sweep_budget_pressure_prioritizes_largest_over_oldest() {
3529        let f = Fx::new().await;
3530        let small = f.run("bb00", true).await;
3531        let large = f.run("bb01", true).await;
3532        for state in [&small, &large] {
3533            Fx::target(&state.candidates[0].worktree);
3534        }
3535        let output = large.candidates[0].worktree.join("target/debug/output");
3536        std::fs::OpenOptions::new()
3537            .write(true)
3538            .open(&output)
3539            .unwrap()
3540            .set_len(1000)
3541            .unwrap();
3542        let mut disk = Fx::disk();
3543        disk.worktree_reclaim_bytes = 300;
3544        disk.min_free_bytes = u64::MAX;
3545        // Pressure must trigger reclamation even when aggregate usage is below cap.
3546        disk.worktree_limit_bytes = u64::MAX;
3547        let out = sweep(&f.home, &disk, Fx::now()).await;
3548        assert_eq!(out.freed_bytes, 1000, "{out:?}");
3549        assert!(!output.exists());
3550        assert!(
3551            small.candidates[0]
3552                .worktree
3553                .join("target/debug/output")
3554                .exists()
3555        );
3556    }
3557
3558    #[tokio::test]
3559    async fn sweep_budget_zero_remaining_and_inventory_are_distinct() {
3560        let f = Fx::new().await;
3561        let first = f.run("bc00", true).await;
3562        let second = f.run("bc01", true).await;
3563        for state in [&first, &second] {
3564            Fx::target(&state.candidates[0].worktree);
3565        }
3566        // Non-declared Cargo data must not determine whether outputs fit.
3567        std::fs::create_dir_all(
3568            first.candidates[0]
3569                .worktree
3570                .join("target/debug/incremental"),
3571        )
3572        .unwrap();
3573        std::fs::write(
3574            first.candidates[0]
3575                .worktree
3576                .join("target/debug/incremental/cache"),
3577            [0; 1000],
3578        )
3579        .unwrap();
3580        let mut disk = Fx::disk();
3581        disk.worktree_reclaim_bytes = 0;
3582        assert_eq!(sweep(&f.home, &disk, Fx::now()).await.freed_bytes, 0);
3583        disk.worktree_reclaim_bytes = 300;
3584        let out = sweep(&f.home, &disk, Fx::now()).await;
3585        assert_eq!(out.freed_bytes, 200, "{out:?}");
3586        assert!(
3587            !first.candidates[0]
3588                .worktree
3589                .join("target/debug/output")
3590                .exists()
3591        );
3592        assert!(
3593            second.candidates[0]
3594                .worktree
3595                .join("target/debug/output")
3596                .exists()
3597        );
3598        assert!(
3599            out.retained
3600                .iter()
3601                .any(|r| r.contains("declared outputs exceed"))
3602        );
3603    }
3604
3605    #[tokio::test]
3606    async fn sweep_budget_exception_preserves_grace_liveness_and_locks() {
3607        let f = Fx::new().await;
3608        let mut protected = f.run("bd00", true).await;
3609        let later = f.run("bd01", true).await;
3610        for state in [&protected, &later] {
3611            Fx::target(&state.candidates[0].worktree);
3612        }
3613        let mut disk = Fx::disk();
3614        disk.worktree_reclaim_bytes = 100;
3615        disk.fold_grace_secs = 3600;
3616        let out = sweep(&f.home, &disk, Fx::now()).await;
3617        assert_eq!(out.freed_bytes, 0);
3618        assert!(
3619            out.retained
3620                .iter()
3621                .any(|r| r.contains("within grace period"))
3622        );
3623        disk.fold_grace_secs = 0;
3624        protected.driver_exited = false;
3625        protected.driver_pid = Some(std::process::id());
3626        protected.driver_started_at = crate::proc::process_started_at(std::process::id());
3627        protected
3628            .save_under_at(&f.home, protected.updated_at)
3629            .unwrap();
3630        let out = sweep(&f.home, &disk, Fx::now()).await;
3631        assert!(
3632            out.retained
3633                .iter()
3634                .any(|r| r.contains("run live or ownership unknown"))
3635        );
3636        assert_eq!(
3637            out.freed_bytes, 200,
3638            "live target must not consume exception: {out:?}"
3639        );
3640        let output = protected.candidates[0].worktree.join("target/debug/output");
3641        assert!(output.exists());
3642        protected.driver_exited = true;
3643        protected.save_under(&f.home).unwrap();
3644        let owner = crate::pr_head::owner_lock(&f.home, &protected.id).unwrap();
3645        assert_eq!(sweep(&f.home, &disk, Fx::now()).await.freed_bytes, 0);
3646        assert!(output.exists());
3647        drop(owner);
3648        let cargo = cargo_locks(&protected.candidates[0].worktree.join("target")).unwrap();
3649        assert_eq!(sweep(&f.home, &disk, Fx::now()).await.freed_bytes, 0);
3650        assert!(output.exists());
3651        drop(cargo);
3652        let lease = OutputLease::take(&protected.candidates[0].worktree, true).unwrap();
3653        assert_eq!(sweep(&f.home, &disk, Fx::now()).await.freed_bytes, 0);
3654        assert!(output.exists());
3655        drop(lease);
3656        assert_eq!(sweep(&f.home, &disk, Fx::now()).await.freed_bytes, 200);
3657        assert!(!output.exists());
3658    }
3659
3660    #[tokio::test]
3661    async fn sweep_skips_missing_run_paths_and_reclaims_other_runs() {
3662        for remove_root in [true, false] {
3663            let f = Fx::new().await;
3664            let stale = Fx::new().await;
3665            let mut missing = stale.run("aa00", false).await;
3666            Fx::target(&missing.candidates[0].worktree);
3667            missing.save_under(&f.home).unwrap();
3668            if remove_root {
3669                std::fs::remove_dir_all(missing.worktree_root()).unwrap();
3670                // An existing non-repository proves the absent root is checked
3671                // before querying Git, even when no registrations are cached.
3672                std::fs::remove_dir_all(stale.repo.join(".git")).unwrap();
3673            } else {
3674                std::fs::remove_dir_all(&stale.repo).unwrap();
3675            }
3676            let healthy = f.run("aa01", false).await;
3677            Fx::target(&healthy.candidates[0].worktree);
3678
3679            let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3680            assert!(report.failures.is_empty(), "{report:?}");
3681            assert_eq!(report.freed_bytes, 200, "{report:?}");
3682            assert!(
3683                !healthy.candidates[0]
3684                    .worktree
3685                    .join("target/debug/output")
3686                    .exists()
3687            );
3688            if !remove_root {
3689                // Without the repository, ownership cannot be validated.
3690                assert!(
3691                    missing.candidates[0]
3692                        .worktree
3693                        .join("target/debug/output")
3694                        .exists()
3695                );
3696            }
3697        }
3698    }
3699
3700    #[tokio::test]
3701    async fn sweep_skips_missing_candidate_checkout_and_reclaims_later_runs() {
3702        let f = Fx::new().await;
3703        let mut missing = f.run("aa00", false).await;
3704        Fx::target(&missing.candidates[0].worktree);
3705        missing.repo = missing.candidates[0].worktree.clone();
3706        missing.save_under(&f.home).unwrap();
3707        std::fs::remove_dir_all(&missing.repo).unwrap();
3708        assert!(missing.worktree_root().is_dir());
3709        assert!(f.repo.is_dir());
3710
3711        let healthy = f.run("aa01", false).await;
3712        Fx::target(&healthy.candidates[0].worktree);
3713
3714        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3715        assert!(report.failures.is_empty(), "{report:?}");
3716        assert_eq!(report.freed_bytes, 200, "{report:?}");
3717        assert!(
3718            !healthy.candidates[0]
3719                .worktree
3720                .join("target/debug/output")
3721                .exists()
3722        );
3723    }
3724
3725    #[tokio::test]
3726    async fn sweep_reports_invalid_repository_and_still_reclaims_later_runs() {
3727        let f = Fx::new().await;
3728        let broken = Fx::new().await;
3729        let mut invalid = broken.run("aa00", false).await;
3730        Fx::target(&invalid.candidates[0].worktree);
3731        invalid.save_under(&f.home).unwrap();
3732        std::fs::remove_dir_all(broken.repo.join(".git")).unwrap();
3733        let healthy = f.run("aa01", false).await;
3734        Fx::target(&healthy.candidates[0].worktree);
3735
3736        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
3737        assert_eq!(report.failures.len(), 1, "{report:?}");
3738        assert!(report.failures[0].starts_with(&format!("{}:", invalid.id)));
3739        assert_eq!(report.freed_bytes, 200, "{report:?}");
3740        assert!(
3741            !healthy.candidates[0]
3742                .worktree
3743                .join("target/debug/output")
3744                .exists()
3745        );
3746        assert!(
3747            invalid.candidates[0]
3748                .worktree
3749                .join("target/debug/output")
3750                .exists()
3751        );
3752    }
3753
3754    async fn reconciliation_plan(f: &Fx, task: &Task, source: &RunState) -> serde_json::Value {
3755        let path = reconcile::run(&f.home, &task.id, &source.id, None)
3756            .await
3757            .unwrap();
3758        serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
3759    }
3760
3761    #[tokio::test]
3762    async fn reconciliation_standing_chat_applies_the_owners_request_without_a_phrase() {
3763        use crate::{
3764            chat_control::{Operation, dispatch},
3765            talk::{self, Talks},
3766        };
3767        let f = Fx::new().await;
3768        let source = f.run("ae00", true).await;
3769        let clean = f.run("ae01", false).await;
3770        let queue = crate::queue::Queue::at(f.home.join("queue"));
3771        let talks = Talks::at(f.home.join("talks"));
3772        let open_talk = |id: &str| -> talk::Talk {
3773            let mut conversation = serde_json::from_value(serde_json::json!({
3774                "schema":1,"id":id,"repo":f.repo,"agent":"worker","status":"open","turns":[],
3775                "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
3776                "seat":crate::agent::SeatState::new("talk","worker",1)
3777            }))
3778            .unwrap();
3779            talks.put(&mut conversation).unwrap();
3780            conversation
3781        };
3782        let conversation = open_talk("talk-owner");
3783        let other = open_talk("talk-other");
3784        // A task this chat did not file: the owner's request covers it too.
3785        let task = f.task(&[source.clone(), clean.clone()]);
3786        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
3787        let operation = |apply: Option<&str>| Operation::ReconcileRetention {
3788            task: task.id.clone(),
3789            authority: source.id.clone(),
3790            apply: apply.map(str::to_owned),
3791        };
3792        // A plan saved outside the chat is not applied through it.
3793        let legacy_path = reconcile::run(&f.home, &task.id, &source.id, None)
3794            .await
3795            .unwrap();
3796        let legacy: serde_json::Value =
3797            serde_json::from_slice(&std::fs::read(legacy_path).unwrap()).unwrap();
3798        let legacy_id = legacy["id"].as_str().unwrap();
3799        assert!(
3800            dispatch(
3801                &queue,
3802                &f.home,
3803                &talks,
3804                &conversation.id,
3805                operation(Some(legacy_id))
3806            )
3807            .await
3808            .is_err()
3809        );
3810        let summary = dispatch(&queue, &f.home, &talks, &conversation.id, operation(None))
3811            .await
3812            .unwrap();
3813        assert!(summary.contains("Complete review summary"));
3814        assert!(summary.contains(&source.id) && summary.contains(&clean.id));
3815        let root = f.home.join("retention-reconciliations");
3816        let displayed: serde_json::Value =
3817            serde_json::from_str(summary.split_once('\n').unwrap().1).unwrap();
3818        let id = displayed["plan"].as_str().unwrap();
3819        let dir = root.join(id);
3820        let plan: serde_json::Value =
3821            serde_json::from_slice(&std::fs::read(dir.join("plan.json")).unwrap()).unwrap();
3822        assert_eq!(plan["version"], 2);
3823        assert!(clean.candidates[0].worktree.exists());
3824        assert!(!dir.join("approved.json").exists());
3825        // The plan stays bound to the conversation it was saved for.
3826        assert!(
3827            dispatch(&queue, &f.home, &talks, &other.id, operation(Some(id)))
3828                .await
3829                .is_err()
3830        );
3831        assert!(!dir.join("approved.json").exists());
3832        // No owner phrase or quote: the request itself applies the plan. An
3833        // interruption after the durable fence keeps the audit for a retry.
3834        let error = reconcile::interrupt_chat_after_fence(
3835            &f.home,
3836            &task,
3837            id,
3838            reconcile::ChatRequest {
3839                talks: &talks,
3840                conversation: &conversation.id,
3841            },
3842        )
3843        .await
3844        .unwrap_err();
3845        assert!(
3846            error.to_string().contains("simulated interruption"),
3847            "{error:#}"
3848        );
3849        assert!(clean.candidates[0].worktree.exists());
3850        assert!(dir.join("approved.json").exists());
3851        dispatch(
3852            &queue,
3853            &f.home,
3854            &talks,
3855            &conversation.id,
3856            operation(Some(id)),
3857        )
3858        .await
3859        .unwrap();
3860        assert!(!clean.candidates[0].worktree.exists());
3861        assert!(source.candidates[0].worktree.exists());
3862        let audit: serde_json::Value =
3863            serde_json::from_slice(&std::fs::read(dir.join("approved.json")).unwrap()).unwrap();
3864        assert_eq!(audit["version"], 2);
3865        assert_eq!(
3866            audit["owner"],
3867            serde_json::json!({"conversation": conversation.id})
3868        );
3869        dispatch(
3870            &queue,
3871            &f.home,
3872            &talks,
3873            &conversation.id,
3874            operation(Some(id)),
3875        )
3876        .await
3877        .unwrap();
3878    }
3879
3880    #[tokio::test]
3881    async fn reconciliation_proves_unmeasured_startup_candidates_empty() {
3882        let f = Fx::new().await;
3883        let source = f.run("af00", true).await;
3884        let mut clean = f.run("af01", false).await;
3885        let mut dirty = f.run("af02", false).await;
3886        for state in [&mut clean, &mut dirty] {
3887            state.status = RunStatus::Prep;
3888            state.prep_complete = Some(false);
3889            state.candidates[0].empty = false;
3890            state.save_under(&f.home).unwrap();
3891        }
3892        std::fs::write(dirty.candidates[0].worktree.join("source"), "unsaved work").unwrap();
3893        let task = f.task(&[source.clone(), clean.clone(), dirty.clone()]);
3894        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
3895        let plan = reconciliation_plan(&f, &task, &source).await;
3896        let selected: Vec<_> = plan["candidates"]
3897            .as_array()
3898            .unwrap()
3899            .iter()
3900            .filter(|e| e["selected"] == true)
3901            .collect();
3902        assert_eq!(selected.len(), 1, "{plan:#}");
3903        assert_eq!(selected[0]["run"], clean.id);
3904        reconcile::run(&f.home, &task.id, &source.id, plan["id"].as_str())
3905            .await
3906            .unwrap();
3907        assert!(!clean.candidates[0].worktree.exists());
3908        assert!(dirty.candidates[0].worktree.exists());
3909        assert!(
3910            RunState::load_under(&dirty.id, &f.home)
3911                .unwrap()
3912                .retired_to
3913                .is_none()
3914        );
3915    }
3916
3917    #[tokio::test]
3918    async fn reconciliation_blanket_retention_selected_source_and_repeated_batches() {
3919        let f = Fx::new().await;
3920        let mut source = f.run("aa00", true).await;
3921        let alternative = f.run("aa01", true).await;
3922        let head = git::rev_parse(&f.repo, &source.candidates[0].branch)
3923            .await
3924            .unwrap();
3925        source.reviewed_commits = Some(vec![head.clone()]);
3926        source.save_under(&f.home).unwrap();
3927        let mut runs = vec![source.clone(), alternative.clone()];
3928        for i in 2..14 {
3929            runs.push(f.run(&format!("aa{i:02}"), false).await);
3930        }
3931        let mut task = f.task(&runs);
3932        task.pr_recovery = Some(crate::pr_recovery::Selection {
3933            url: "https://example.invalid/pull/1".into(),
3934            branch: "selected".into(),
3935            head: head.clone(),
3936            source_head: Some(head.clone()),
3937            source_run: Some(source.id.clone()),
3938            source_proof: None,
3939            disposition: Some(crate::pr_recovery::Disposition::Land),
3940            instruction: task.instruction.clone(),
3941            approved_at: Timestamp::now(),
3942        });
3943        source.pr_recovery = task.pr_recovery.clone();
3944        source.save_under(&f.home).unwrap();
3945        runs[0] = source.clone();
3946        crate::queue::Queue::at(f.home.join("queue"))
3947            .put(&mut task)
3948            .unwrap();
3949        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
3950        let task_before = serde_json::to_value(&task).unwrap();
3951        let mut report = Report::default();
3952        retire_empty(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
3953        assert_eq!(
3954            report.retired, 0,
3955            "automatic cleanup must still refuse blanket markers"
3956        );
3957        assert!(
3958            report
3959                .retained
3960                .iter()
3961                .any(|reason| reason.contains("explicitly retained"))
3962        );
3963        let mut total = 0;
3964        for expected in [5, 5, 2, 0] {
3965            let plan = reconciliation_plan(&f, &task, &source).await;
3966            let selected: Vec<_> = plan["candidates"]
3967                .as_array()
3968                .unwrap()
3969                .iter()
3970                .filter(|e| e["selected"] == true)
3971                .collect();
3972            assert_eq!(selected.len(), expected, "{plan:#}");
3973            for e in &selected {
3974                assert!(
3975                    RunState::load_under(e["run"].as_str().unwrap(), &f.home)
3976                        .unwrap()
3977                        .retired_to
3978                        .is_none()
3979                );
3980            }
3981            let operation = plan["id"].as_str().unwrap();
3982            for _ in 0..2 {
3983                reconcile::run(&f.home, &task.id, &source.id, Some(operation))
3984                    .await
3985                    .unwrap();
3986            }
3987            total += expected;
3988        }
3989        assert_eq!(total, 12);
3990        for run in &runs {
3991            let dir = f.home.join("runs").join(&run.id);
3992            assert!(dir.join("run.json").exists());
3993            assert!(dir.join("retain-recovery-sources").exists());
3994            assert!(
3995                git::branch_exists(&f.repo, &run.candidates[0].branch)
3996                    .await
3997                    .unwrap()
3998            );
3999        }
4000        assert!(source.candidates[0].worktree.exists());
4001        assert!(alternative.candidates[0].worktree.exists());
4002        assert_eq!(
4003            git::rev_parse(&f.repo, &source.candidates[0].branch)
4004                .await
4005                .unwrap(),
4006            head
4007        );
4008        assert_eq!(
4009            serde_json::to_value(
4010                crate::queue::Queue::at(f.home.join("queue"))
4011                    .get(&task.id)
4012                    .unwrap()
4013            )
4014            .unwrap(),
4015            task_before
4016        );
4017        assert_eq!(
4018            runs.iter()
4019                .filter(|r| RunState::load_under(&r.id, &f.home)
4020                    .unwrap()
4021                    .retired_to
4022                    .is_none())
4023                .count(),
4024            2
4025        );
4026    }
4027
4028    #[tokio::test]
4029    async fn reconciliation_refuses_live_dirty_ignored_unknown_and_git_checkpoints() {
4030        let f = Fx::new().await;
4031        let source = f.run("ab00", true).await;
4032        let mut runs = vec![source.clone()];
4033        for i in 1..9 {
4034            runs.push(f.run(&format!("ab{i:02}"), false).await);
4035        }
4036        std::fs::write(runs[1].candidates[0].worktree.join("source"), "dirty").unwrap();
4037        std::fs::write(runs[2].candidates[0].worktree.join("untracked"), "source").unwrap();
4038        std::fs::create_dir(runs[3].candidates[0].worktree.join("scratch")).unwrap();
4039        std::fs::write(
4040            runs[3].candidates[0].worktree.join("scratch/source"),
4041            "ignored source",
4042        )
4043        .unwrap();
4044        std::fs::write(
4045            runs[4].worktree_root().join("unknown"),
4046            "unregistered source",
4047        )
4048        .unwrap();
4049        let checkpoint = git::git(
4050            &runs[5].candidates[0].worktree,
4051            &[
4052                "rev-parse",
4053                "--path-format=absolute",
4054                "--git-path",
4055                "sequencer",
4056            ],
4057        )
4058        .await
4059        .unwrap();
4060        std::fs::create_dir(checkpoint.trim()).unwrap();
4061        runs[6].driver_exited = false;
4062        runs[6].driver_pid = Some(std::process::id());
4063        runs[6].driver_started_at = crate::proc::process_started_at(std::process::id());
4064        runs[6].save_under(&f.home).unwrap();
4065        runs[7].driver_exited = false;
4066        runs[7].driver_pid = None;
4067        runs[7].driver_claimed = None; // Legacy record without first-claim evidence.
4068        runs[7].save_under(&f.home).unwrap();
4069        assert_eq!(runs[7].liveness_under(&f.home, false), Liveness::Unknown);
4070
4071        let hidden = &runs[8].candidates[0].worktree;
4072        git::git(hidden, &["update-index", "--assume-unchanged", "source"])
4073            .await
4074            .unwrap();
4075        std::fs::write(hidden.join("source"), "hidden dirty implementation").unwrap();
4076        assert!(
4077            git::git(hidden, &["status", "--porcelain"])
4078                .await
4079                .unwrap()
4080                .is_empty()
4081        );
4082        let task = f.task(&runs);
4083        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
4084        let plan = reconciliation_plan(&f, &task, &source).await;
4085        assert!(
4086            plan["candidates"]
4087                .as_array()
4088                .unwrap()
4089                .iter()
4090                .all(|e| e["selected"] == false),
4091            "{plan:#}"
4092        );
4093        for run in &runs {
4094            assert!(run.candidates[0].worktree.exists());
4095        }
4096    }
4097
4098    #[tokio::test]
4099    async fn reconciliation_stale_plans_and_changed_markers_fail_closed() {
4100        let f = Fx::new().await;
4101        let source = f.run("ac00", true).await;
4102        let empty = f.run("ac01", false).await;
4103        let task = f.task(&[source.clone(), empty.clone()]);
4104        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
4105        let plan = reconciliation_plan(&f, &task, &source).await;
4106        std::fs::write(
4107            f.home.join("runs").join(&source.id).join("new-report"),
4108            "new review checkpoint",
4109        )
4110        .unwrap();
4111        assert!(
4112            reconcile::run(&f.home, &task.id, &source.id, plan["id"].as_str())
4113                .await
4114                .is_err()
4115        );
4116        assert!(empty.candidates[0].worktree.exists());
4117        assert!(
4118            RunState::load_under(&empty.id, &f.home)
4119                .unwrap()
4120                .retired_to
4121                .is_none()
4122        );
4123        let marker = f
4124            .home
4125            .join("runs")
4126            .join(&empty.id)
4127            .join("retain-recovery-sources");
4128        std::fs::write(&marker, "different owner").unwrap();
4129        let plan = reconciliation_plan(&f, &task, &source).await;
4130        assert!(
4131            plan["candidates"]
4132                .as_array()
4133                .unwrap()
4134                .iter()
4135                .all(|e| e["selected"] == false)
4136        );
4137    }
4138
4139    #[tokio::test]
4140    async fn reconciliation_recovers_interrupted_state_staging_in_a_batch() {
4141        for partial in [false, true] {
4142            let f = Fx::new().await;
4143            let source = f.run("ab10", true).await;
4144            let first = f.run("ab11", false).await;
4145            let second = f.run("ab12", false).await;
4146            let task = f.task(&[source.clone(), first.clone(), second.clone()]);
4147            crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
4148            let plan = reconciliation_plan(&f, &task, &source).await;
4149            let id = plan["id"].as_str().unwrap();
4150            let staging = f.home.join("runs").join(&second.id).join("run.json.tmp");
4151            // Matching bytes without this operation's fence are not trusted.
4152            std::fs::write(&staging, b"").unwrap();
4153            assert!(
4154                reconcile::run(&f.home, &task.id, &source.id, Some(id))
4155                    .await
4156                    .is_err()
4157            );
4158            assert!(staging.exists());
4159            std::fs::remove_file(&staging).unwrap();
4160            let error = reconcile::interrupt_during_state_save(&f.home, &task, id, partial)
4161                .await
4162                .unwrap_err();
4163            assert!(
4164                error.to_string().contains("before run state rename"),
4165                "{error:#}"
4166            );
4167            assert!(
4168                RunState::load_under(&first.id, &f.home)
4169                    .unwrap()
4170                    .retired_to
4171                    .is_some()
4172            );
4173            assert!(
4174                RunState::load_under(&second.id, &f.home)
4175                    .unwrap()
4176                    .retired_to
4177                    .is_none()
4178            );
4179            assert!(first.candidates[0].worktree.exists());
4180            assert!(second.candidates[0].worktree.exists());
4181            let interrupted = std::fs::read(&staging).unwrap();
4182            // An unrelated file must survive a refused retry unchanged.
4183            std::fs::write(&staging, b"unrelated recovery source").unwrap();
4184            assert!(
4185                reconcile::run(&f.home, &task.id, &source.id, Some(id))
4186                    .await
4187                    .is_err()
4188            );
4189            assert_eq!(
4190                std::fs::read(&staging).unwrap(),
4191                b"unrelated recovery source"
4192            );
4193            std::fs::write(&staging, interrupted).unwrap();
4194            reconcile::run(&f.home, &task.id, &source.id, Some(id))
4195                .await
4196                .unwrap();
4197            assert!(!staging.exists());
4198            assert!(!first.candidates[0].worktree.exists());
4199            assert!(!second.candidates[0].worktree.exists());
4200            assert_eq!(
4201                RunState::load_under(&second.id, &f.home)
4202                    .unwrap()
4203                    .retired_to,
4204                Some(source.id)
4205            );
4206        }
4207    }
4208
4209    #[tokio::test]
4210    async fn reconciliation_resumes_only_its_exact_durable_fence() {
4211        let f = Fx::new().await;
4212        let source = f.run("ad00", true).await;
4213        let empty = f.run("ad01", false).await;
4214        let task = f.task(&[source.clone(), empty.clone()]);
4215        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
4216        let plan = reconciliation_plan(&f, &task, &source).await;
4217        let id = plan["id"].as_str().unwrap();
4218        assert!(
4219            reconcile::interrupt_after_fence(&f.home, &task, id)
4220                .await
4221                .is_err()
4222        );
4223        assert!(empty.candidates[0].worktree.exists());
4224        assert_eq!(
4225            RunState::load_under(&empty.id, &f.home)
4226                .unwrap()
4227                .retired_to
4228                .as_ref(),
4229            Some(&source.id)
4230        );
4231        reconcile::run(&f.home, &task.id, &source.id, Some(id))
4232            .await
4233            .unwrap();
4234        assert!(!empty.candidates[0].worktree.exists());
4235        // Model an interrupted removal: restore precisely the approved base worktree.
4236        git::worktree_add_branch(
4237            &f.repo,
4238            &empty.candidates[0].worktree,
4239            "restore-empty",
4240            &f.base,
4241        )
4242        .await
4243        .unwrap();
4244        // Recreated Git administration differs from approval and is refused.
4245        assert!(
4246            reconcile::run(&f.home, &task.id, &source.id, Some(id))
4247                .await
4248                .is_err()
4249        );
4250        assert!(empty.candidates[0].worktree.exists());
4251        let mut changed = RunState::load_under(&empty.id, &f.home).unwrap();
4252        changed.prep_failure = Some("new owner edit".into());
4253        changed.save_under(&f.home).unwrap();
4254        assert!(
4255            reconcile::run(&f.home, &task.id, &source.id, Some(id))
4256                .await
4257                .is_err()
4258        );
4259    }
4260
4261    #[tokio::test]
4262    async fn reconciliation_checks_prep_intent_reflogs_and_unknown_run_fields() {
4263        let f = Fx::new().await;
4264        let source = f.run("ae00", true).await;
4265        let mut prep = f.run("ae01", false).await;
4266        let candidate = prep.candidates.pop().unwrap();
4267        prep.event("prep-intent", serde_json::json!({"branch":candidate.branch,"worktree":candidate.worktree,"start":f.base,"picks":[]}).to_string());
4268        prep.save_under(&f.home).unwrap();
4269        let reset = f.run("ae02", false).await;
4270        let wt = &reset.candidates[0].worktree;
4271        std::fs::write(wt.join("source"), "unique hidden in reflog").unwrap();
4272        git::git(wt, &["add", "."]).await.unwrap();
4273        git::git(wt, &["commit", "-m", "unique implementation"])
4274            .await
4275            .unwrap();
4276        git::git(wt, &["reset", "--hard", &f.base]).await.unwrap();
4277        let unknown = f.run("ae03", false).await;
4278        let unknown_path = f.home.join("runs").join(&unknown.id).join("run.json");
4279        let mut raw: serde_json::Value =
4280            serde_json::from_slice(&std::fs::read(&unknown_path).unwrap()).unwrap();
4281        raw["unknown_checkpoint"] = serde_json::json!({"source":"retain"});
4282        std::fs::write(unknown_path, serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
4283        let task = f.task(&[source.clone(), prep.clone(), reset.clone(), unknown.clone()]);
4284        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
4285        let plan = reconciliation_plan(&f, &task, &source).await;
4286        let selected: Vec<_> = plan["candidates"]
4287            .as_array()
4288            .unwrap()
4289            .iter()
4290            .filter(|e| e["selected"] == true)
4291            .collect();
4292        assert_eq!(selected.len(), 1, "{plan:#}");
4293        assert_eq!(selected[0]["run"], prep.id);
4294        reconcile::run(&f.home, &task.id, &source.id, plan["id"].as_str())
4295            .await
4296            .unwrap();
4297        assert!(!candidate.worktree.exists());
4298        assert!(reset.candidates[0].worktree.exists());
4299        assert!(unknown.candidates[0].worktree.exists());
4300    }
4301
4302    #[tokio::test]
4303    async fn cap_reclaims_blocked_candidates_and_landing_reviewers_across_repositories() {
4304        let f = Fx::new().await;
4305        let mut state = f.run("aaaa", true).await;
4306        let candidate = state.candidates[0].worktree.clone();
4307        std::fs::write(candidate.join("source"), "uncommitted work").unwrap();
4308        Fx::target(&candidate);
4309        for seat in ["review-1", "review-2"] {
4310            let wt = state.worktree_root().join(seat);
4311            git::worktree_add_detached(&f.repo, &wt, &f.base)
4312                .await
4313                .unwrap();
4314            Fx::target(&wt);
4315        }
4316        state.status = RunStatus::Landing;
4317        state.save_under(&f.home).unwrap();
4318        let second = Fx::new().await;
4319        let other = second.run("bbbb", true).await;
4320        // A global store may contain repositories with different worktree roots.
4321        let mut imported = other.clone();
4322        imported.save_under(&f.home).unwrap();
4323        Fx::target(&other.candidates[0].worktree);
4324        let guard = OutputLease::borrow(&candidate).unwrap().unwrap();
4325        let out = sweep(&f.home, &Fx::disk(), Fx::now()).await;
4326        assert!(
4327            candidate.join("target/debug/output").exists(),
4328            "active writer protected"
4329        );
4330        assert!(
4331            !state
4332                .worktree_root()
4333                .join("review-1/target/debug/output")
4334                .exists()
4335        );
4336        assert!(
4337            !state
4338                .worktree_root()
4339                .join("review-2/target/debug/output")
4340                .exists()
4341        );
4342        assert!(
4343            !other.candidates[0]
4344                .worktree
4345                .join("target/debug/output")
4346                .exists()
4347        );
4348        assert!(out.freed_bytes >= 600);
4349        drop(guard);
4350        let out = sweep(&f.home, &Fx::disk(), Fx::now()).await;
4351        assert!(out.freed_bytes >= 200);
4352        assert_eq!(
4353            std::fs::read_to_string(candidate.join("source")).unwrap(),
4354            "uncommitted work"
4355        );
4356        assert!(
4357            git::branch_exists(&f.repo, &state.candidates[0].branch)
4358                .await
4359                .unwrap()
4360        );
4361    }
4362
4363    #[tokio::test]
4364    async fn dep_info_reclamation_preserves_unmanifested_nested_files() {
4365        let f = Fx::new().await;
4366        let state = f.run("cc01", false).await;
4367        let wt = &state.candidates[0].worktree;
4368        Fx::target(wt);
4369        for dir in ["debug", "release", "debug/deps", "debug/build/script/out"] {
4370            let dir = wt.join("target").join(dir);
4371            std::fs::create_dir_all(&dir).unwrap();
4372            std::fs::write(dir.join("notes.txt"), "user evidence").unwrap();
4373        }
4374        // A dep-info dependency is an input, never deletion authority.
4375        let manifest = wt.join("target/debug/output.d");
4376        let output = wt.join("target/debug/output");
4377        std::fs::write(
4378            &manifest,
4379            format!(
4380                "{}: {}\n",
4381                output.display(),
4382                wt.join("target/debug/notes.txt").display()
4383            ),
4384        )
4385        .unwrap();
4386        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
4387        assert_eq!(report.freed_bytes, 200);
4388        assert!(!output.exists());
4389        for dir in ["debug", "release", "debug/deps", "debug/build/script/out"] {
4390            assert_eq!(
4391                std::fs::read_to_string(wt.join("target").join(dir).join("notes.txt")).unwrap(),
4392                "user evidence"
4393            );
4394        }
4395        // Metadata remains available for inspection and future safe rebuilds.
4396        assert!(manifest.exists());
4397        assert!(report.retained.iter().any(|s| s.contains("unmanifested")));
4398        std::fs::write(&output, "user note replacing an old binary").unwrap();
4399        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
4400        assert_eq!(report.freed_bytes, 0);
4401        assert_eq!(
4402            std::fs::read_to_string(&output).unwrap(),
4403            "user note replacing an old binary"
4404        );
4405    }
4406
4407    #[tokio::test]
4408    async fn measurement_cache_expires_and_disabled_eviction_does_not_walk_outputs() {
4409        let f = Fx::new().await;
4410        let state = f.run("cc02", false).await;
4411        let wt = &state.candidates[0].worktree;
4412        Fx::target(wt);
4413        let mut disk = Fx::disk();
4414        disk.worktree_limit_bytes = u64::MAX;
4415        let now = Fx::now();
4416        let first = sweep(&f.home, &disk, now).await;
4417        std::fs::write(wt.join("target/debug/output"), [1; 1000]).unwrap();
4418        assert_eq!(
4419            sweep(&f.home, &disk, now).await.measured_bytes,
4420            first.measured_bytes
4421        );
4422        assert!(
4423            sweep(&f.home, &disk, now + jiff::SignedDuration::from_secs(301))
4424                .await
4425                .measured_bytes
4426                > first.measured_bytes
4427        );
4428        disk.worktree_limit_bytes = 0;
4429        assert_eq!(sweep(&f.home, &disk, now).await.measured_bytes, 0);
4430    }
4431
4432    #[tokio::test]
4433    async fn unfinished_source_fold_reports_its_retention_reason() {
4434        let f = Fx::new().await;
4435        let mut source = f.run("cc03", true).await;
4436        let task = f.task(&[source.clone()]);
4437        let error = crate::graph::fold_run(&mut source, true, &f.home)
4438            .await
4439            .unwrap_err();
4440        assert!(error.to_string().contains(&task.id));
4441        assert!(source.candidates[0].worktree.exists());
4442        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
4443        let error = crate::graph::fold_run(&mut source, true, &f.home)
4444            .await
4445            .unwrap_err();
4446        assert!(error.to_string().contains("explicitly retained"));
4447    }
4448
4449    #[tokio::test]
4450    async fn confirmed_merged_source_folds_while_task_is_held_but_retention_still_wins() {
4451        let f = Fx::new().await;
4452        let mut source = f.run("cc04", true).await;
4453        let mut task = f.task(&[source.clone()]);
4454        task.hold_manual(Some("queue settlement pending".into()));
4455        let queue = crate::queue::Queue::at(f.home.join("queue"));
4456        queue.put(&mut task).unwrap();
4457        source.merge = Some(crate::run::MergeOutcome {
4458            mode: crate::config::MergeMode::Pr,
4459            ok: true,
4460            detail: "confirmed merged".into(),
4461            empty: false,
4462        });
4463        // Publication success and terminal labels alone are insufficient.
4464        for status in [RunStatus::Ready, RunStatus::Failed, RunStatus::Superseded] {
4465            // Each label is saved with the confirmed merge, so the fold decides
4466            // on it under its locks; the refusal is the queue's retention
4467            // reason, which names the task, not a missing record.
4468            source.status = status;
4469            source.save_under(&f.home).unwrap();
4470            let error = refused(&mut source, &f.home).await;
4471            assert!(
4472                matches!(
4473                    error.downcast_ref::<crate::graph::FoldRefusal>(),
4474                    Some(crate::graph::FoldRefusal::Retained(reason)) if reason.contains(&task.id)
4475                ),
4476                "{status:?}: {error:#}"
4477            );
4478            assert!(source.candidates[0].worktree.exists());
4479        }
4480        git::git(
4481            &f.repo,
4482            &["merge", "--ff-only", &source.candidates[0].branch],
4483        )
4484        .await
4485        .unwrap();
4486        git::git(&f.repo, &["update-ref", "refs/remotes/origin/main", "HEAD"])
4487            .await
4488            .unwrap();
4489        source.status = RunStatus::Merged;
4490        source.save_under(&f.home).unwrap();
4491        assert!(crate::pr_recovery::source_retention_reason(&f.home, &source).is_none());
4492        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
4493        assert!(
4494            crate::graph::fold_run(&mut source, true, &f.home)
4495                .await
4496                .unwrap_err()
4497                .to_string()
4498                .contains("explicitly retained")
4499        );
4500        // The fixture's explicit marker is removed only to exercise ordinary
4501        // confirmed-merge cleanup; no production cleanup removes such markers.
4502        std::fs::remove_file(
4503            f.home
4504                .join("runs")
4505                .join(&source.id)
4506                .join("retain-recovery-sources"),
4507        )
4508        .unwrap();
4509        let (folded, unreadable) = crate::clean::fold_due(
4510            &f.home.join("runs"),
4511            &f.home,
4512            &f.bay,
4513            &Fx::disk(),
4514            Fx::now(),
4515        )
4516        .await
4517        .unwrap();
4518        assert_eq!((folded, unreadable), (1, 0));
4519        assert!(!source.candidates[0].worktree.exists());
4520        let evidence = f
4521            .home
4522            .join("runs")
4523            .join(&source.id)
4524            .join("artifacts/fold-evidence");
4525        let names: Vec<_> = std::fs::read_dir(evidence)
4526            .unwrap()
4527            .map(|entry| entry.unwrap().file_name())
4528            .collect();
4529        assert_eq!(names, [std::ffi::OsString::from("manifest.json")]);
4530        assert_eq!(
4531            queue.get(&task.id).unwrap().status,
4532            crate::queue::TaskStatus::Held
4533        );
4534    }
4535
4536    #[tokio::test]
4537    async fn merged_fold_skips_proven_squash_and_archives_unpublished_sources() {
4538        for variant in ["exact", "partial", "checkpoint", "loser", "reviewer"] {
4539            let f = Fx::new().await;
4540            let mut state = f.run("cc06", true).await;
4541            let candidate = state.candidates[0].clone();
4542            let intermediate = git::rev_parse(&candidate.worktree, "HEAD").await.unwrap();
4543            std::fs::write(candidate.worktree.join("second"), [0, 1, 255, 42]).unwrap();
4544            git::rescue_commit(&candidate.worktree, "second candidate change")
4545                .await
4546                .unwrap();
4547            let head = git::rev_parse(&candidate.worktree, "HEAD").await.unwrap();
4548            state.tally = Some(crate::run::Tally {
4549                first_choice: Default::default(),
4550                borda: Default::default(),
4551                winner: 'A',
4552                rankings: 0,
4553                unanimous_initial: true,
4554                deliberated: false,
4555                changed_votes: 0,
4556                unanimous_final: true,
4557                tie_break: None,
4558                judges: 0,
4559                present: 0,
4560                quorum: 0,
4561                met_quorum: true,
4562                uncontested: Some("fixture".into()),
4563            });
4564            // A reviewer pinned to an intermediate candidate commit must also
4565            // be reclaimable, although neither commit ID lands in the squash.
4566            let reviewer = state.worktree_root().join("review-1");
4567            git::worktree_add_detached(&f.repo, &reviewer, &intermediate)
4568                .await
4569                .unwrap();
4570            // Concurrent base changes and later base advances prevent a mere
4571            // equality check against the current base tree from passing.
4572            std::fs::write(f.repo.join("unrelated-before"), "base advance").unwrap();
4573            git::rescue_commit(&f.repo, "advance before squash")
4574                .await
4575                .unwrap();
4576            let published = if variant == "partial" {
4577                &intermediate
4578            } else {
4579                &head
4580            };
4581            git::git(&f.repo, &["merge", "--squash", published])
4582                .await
4583                .unwrap();
4584            git::git(&f.repo, &["commit", "-m", "squash candidate"])
4585                .await
4586                .unwrap();
4587            let squash = git::rev_parse(&f.repo, "HEAD").await.unwrap();
4588            assert!(
4589                !git::git_raw(&f.repo, &["merge-base", "--is-ancestor", &head, &squash])
4590                    .await
4591                    .unwrap()
4592                    .ok()
4593            );
4594            std::fs::write(f.repo.join("unrelated-after"), "later base advance").unwrap();
4595            git::rescue_commit(&f.repo, "advance after squash")
4596                .await
4597                .unwrap();
4598            git::git(&f.repo, &["update-ref", "refs/remotes/origin/main", "HEAD"])
4599                .await
4600                .unwrap();
4601            if matches!(variant, "checkpoint" | "reviewer") {
4602                // A reset hides unique work from HEAD, but not its reflog.
4603                std::fs::write(reviewer.join("unpublished"), "reviewer checkpoint").unwrap();
4604                git::rescue_commit(&reviewer, "unpublished checkpoint")
4605                    .await
4606                    .unwrap();
4607                if variant == "checkpoint" {
4608                    git::git(&reviewer, &["reset", "--hard", &intermediate])
4609                        .await
4610                        .unwrap();
4611                }
4612            }
4613            if variant == "loser" {
4614                let mut loser = candidate.clone();
4615                loser.label = 'B';
4616                loser.branch = "magi/cc06/B".into();
4617                loser.worktree = state.worktree_root().join("cand-B");
4618                git::worktree_add_branch(&f.repo, &loser.worktree, &loser.branch, &f.base)
4619                    .await
4620                    .unwrap();
4621                std::fs::write(loser.worktree.join("unique"), "losing candidate").unwrap();
4622                git::rescue_commit(&loser.worktree, "independent loser")
4623                    .await
4624                    .unwrap();
4625                state.candidates.push(loser);
4626            }
4627            state.status = RunStatus::Merged;
4628            state.merge = Some(crate::run::MergeOutcome {
4629                mode: crate::config::MergeMode::Pr,
4630                ok: true,
4631                detail: "candidate A squash merged".into(),
4632                empty: false,
4633            });
4634            state.save_under(&f.home).unwrap();
4635            let review_head = git::rev_parse(&reviewer, "HEAD").await.unwrap();
4636            let result = crate::graph::fold_run(&mut state, true, &f.home).await;
4637            result.unwrap();
4638            assert!(
4639                !candidate.worktree.exists() && !reviewer.exists(),
4640                "{variant}"
4641            );
4642            assert!(
4643                !git::branch_exists(&f.repo, &candidate.branch)
4644                    .await
4645                    .unwrap()
4646            );
4647            let artifacts = f
4648                .home
4649                .join("runs")
4650                .join(&state.id)
4651                .join("artifacts/fold-evidence");
4652            assert_eq!(
4653                artifacts.join(format!("{head}.patch")).exists(),
4654                variant == "partial",
4655                "only a partially published winner needs evidence: {variant}"
4656            );
4657            assert_eq!(
4658                artifacts.join(format!("{intermediate}.patch")).exists(),
4659                variant == "partial",
4660                "squash proof also covers intermediate reviewer tips: {variant}"
4661            );
4662            let patches: Vec<_> = std::fs::read_dir(&artifacts)
4663                .unwrap()
4664                .map(|entry| entry.unwrap().path())
4665                .filter(|path| path.extension().is_some_and(|ext| ext == "patch"))
4666                .collect();
4667            let expected = match variant {
4668                "partial" => 2,
4669                "loser" | "reviewer" => 1,
4670                _ => 0,
4671            };
4672            assert_eq!(patches.len(), expected, "{variant}");
4673            if variant == "loser" {
4674                assert!(
4675                    std::fs::read_to_string(&patches[0])
4676                        .unwrap()
4677                        .contains("losing candidate")
4678                );
4679            }
4680            assert!(artifacts.join("manifest.json").exists());
4681            if variant == "reviewer" {
4682                assert!(
4683                    std::fs::read_to_string(artifacts.join(format!("{review_head}.patch")))
4684                        .unwrap()
4685                        .contains("reviewer checkpoint")
4686                );
4687            }
4688            crate::graph::fold_run(&mut state, true, &f.home)
4689                .await
4690                .unwrap();
4691        }
4692    }
4693
4694    #[tokio::test]
4695    async fn merged_fold_missing_review_source_preserves_artifacts_and_retries() {
4696        for missing in [true, false] {
4697            let f = Fx::new().await;
4698            let mut state = f.run("cc05", true).await;
4699            // A fetched base exists, but these local review changes were not
4700            // incorporated by ancestry, so their recovery evidence is required.
4701            git::git(
4702                &f.repo,
4703                &["update-ref", "refs/remotes/origin/main", &f.base],
4704            )
4705            .await
4706            .unwrap();
4707            let candidate = state.candidates[0].clone();
4708            if !missing {
4709                std::fs::write(f.repo.join("base-advance"), "new base").unwrap();
4710                git::rescue_commit(&f.repo, "advance base before rebase")
4711                    .await
4712                    .unwrap();
4713                git::git(&candidate.worktree, &["rebase", "main"])
4714                    .await
4715                    .unwrap();
4716                // Match the runner's post-rebase synchronization, which
4717                // clears the merge backend's transient AUTO_MERGE checkpoint.
4718                git::sync_to_head(&candidate.worktree).await.unwrap();
4719            }
4720            let head = git::rev_parse(&candidate.worktree, "HEAD").await.unwrap();
4721            // Model review-only state: no implementation-time snapshot exists.
4722            state.reviewed_commits = Some(Vec::new());
4723            state.candidates[0].worktree = state.worktree_root().join("under-review");
4724            git::git(
4725                &f.repo,
4726                &[
4727                    "worktree",
4728                    "move",
4729                    candidate.worktree.to_str().unwrap(),
4730                    state.candidates[0].worktree.to_str().unwrap(),
4731                ],
4732            )
4733            .await
4734            .unwrap();
4735            let reviewer = state.worktree_root().join("review-1");
4736            git::worktree_add_detached(&f.repo, &reviewer, &head)
4737                .await
4738                .unwrap();
4739            // A reset/rebase can leave unpublished recovery history. It must
4740            // not keep any remaining owned worktree alive indefinitely.
4741            std::fs::write(reviewer.join("obsolete"), "old history").unwrap();
4742            git::rescue_commit(&reviewer, "old review history")
4743                .await
4744                .unwrap();
4745            git::git(&reviewer, &["reset", "--hard", &head])
4746                .await
4747                .unwrap();
4748            if missing {
4749                std::fs::remove_dir_all(&state.candidates[0].worktree).unwrap();
4750            }
4751            let run_dir = f.home.join("runs").join(&state.id);
4752            let artifacts = run_dir.join("artifacts");
4753            std::fs::create_dir_all(&artifacts).unwrap();
4754            std::fs::write(artifacts.join("review.json"), "review findings").unwrap();
4755            if missing {
4756                std::fs::write(artifacts.join("cand-A.patch"), "original snapshot").unwrap();
4757            }
4758            state.status = RunStatus::Merged;
4759            state.merge = Some(crate::run::MergeOutcome {
4760                mode: crate::config::MergeMode::Pr,
4761                ok: true,
4762                detail: "confirmed squash merge".into(),
4763                empty: false,
4764            });
4765            state.save_under(&f.home).unwrap();
4766            // Unexpected external paths remain protected, even if absent. A
4767            // fold decides on the record it reads under its locks, so the
4768            // arranged record is the one on disk, not only the one in memory.
4769            let owned = state.candidates[0].worktree.clone();
4770            state.candidates[0].worktree = f.home.join("missing-external");
4771            state.save_under(&f.home).unwrap();
4772            assert!(
4773                crate::graph::fold_run(&mut state, true, &f.home)
4774                    .await
4775                    .unwrap_err()
4776                    .to_string()
4777                    .contains("outside the inventoried")
4778            );
4779            state.candidates[0].worktree = owned;
4780            state.save_under(&f.home).unwrap();
4781            // A live output borrower blocks the entire preflight.
4782            let guard = OutputLease::borrow(&reviewer).unwrap().unwrap();
4783            refused(&mut state, &f.home).await;
4784            assert!(reviewer.exists());
4785            drop(guard);
4786            // Failure to persist evidence must not cause partial removal.
4787            let evidence = artifacts.join("fold-evidence");
4788            std::fs::write(&evidence, "blocked").unwrap();
4789            refused(&mut state, &f.home).await;
4790            assert!(reviewer.exists());
4791            std::fs::remove_file(&evidence).unwrap();
4792            std::fs::create_dir_all(&evidence).unwrap();
4793            let oversized = evidence.join("capacity-fixture");
4794            std::fs::File::create(&oversized)
4795                .unwrap()
4796                .set_len(64 * 1024 * 1024)
4797                .unwrap();
4798            refused(&mut state, &f.home).await;
4799            assert!(reviewer.exists());
4800            std::fs::remove_file(oversized).unwrap();
4801            // Ignored recovery files and unfinished Git operations still hold
4802            // all sources, even for a confirmed merge.
4803            std::fs::create_dir_all(reviewer.join("scratch")).unwrap();
4804            std::fs::write(reviewer.join("scratch/recovery"), "keep").unwrap();
4805            refused(&mut state, &f.home).await;
4806            std::fs::remove_dir_all(reviewer.join("scratch")).unwrap();
4807            let checkpoint = git::git(&reviewer, &["rev-parse", "--git-path", "CHERRY_PICK_HEAD"])
4808                .await
4809                .unwrap();
4810            std::fs::write(&checkpoint, &head).unwrap();
4811            refused(&mut state, &f.home).await;
4812            std::fs::remove_file(checkpoint).unwrap();
4813            let (folded, unreadable) = crate::clean::fold_due(
4814                &f.home.join("runs"),
4815                &f.home,
4816                &f.bay,
4817                &Fx::disk(),
4818                Fx::now(),
4819            )
4820            .await
4821            .unwrap();
4822            if folded != 1 {
4823                panic!(
4824                    "normal cleanup failed: {:#}",
4825                    crate::graph::fold_run(&mut state, true, &f.home)
4826                        .await
4827                        .unwrap_err()
4828                );
4829            }
4830            assert_eq!((folded, unreadable), (1, 0));
4831            assert!(!reviewer.exists() && !state.candidates[0].worktree.exists());
4832            state = RunState::load_under(&state.id, &f.home).unwrap();
4833            assert!(state.candidates[0].folded);
4834            let manifest = std::fs::read(evidence.join("manifest.json")).unwrap();
4835            crate::graph::fold_run(&mut state, true, &f.home)
4836                .await
4837                .unwrap();
4838            assert_eq!(
4839                std::fs::read(evidence.join("manifest.json")).unwrap(),
4840                manifest
4841            );
4842            git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
4843                .await
4844                .unwrap();
4845            git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
4846            assert!(
4847                !git::git_raw(&f.repo, &["cat-file", "-e", &head])
4848                    .await
4849                    .unwrap()
4850                    .ok()
4851            );
4852            // Restore the modified file into a fresh repository from artifact
4853            // bytes alone; no original commit or blob is consulted.
4854            let manifest: serde_json::Value = serde_json::from_slice(&manifest).unwrap();
4855            let old_blob = manifest[format!("head-{head}")]["base_blobs"][0]
4856                .as_str()
4857                .unwrap();
4858            let recovered = f.home.join("recovered");
4859            std::fs::create_dir_all(&recovered).unwrap();
4860            git::git(&recovered, &["init"]).await.unwrap();
4861            std::fs::write(
4862                recovered.join("source"),
4863                std::fs::read(evidence.join(format!("blob-{old_blob}"))).unwrap(),
4864            )
4865            .unwrap();
4866            git::git(
4867                &recovered,
4868                &[
4869                    "apply",
4870                    evidence.join(format!("{head}.patch")).to_str().unwrap(),
4871                ],
4872            )
4873            .await
4874            .unwrap();
4875            assert_eq!(
4876                std::fs::read_to_string(recovered.join("source")).unwrap(),
4877                "cc05"
4878            );
4879            assert!(
4880                !std::fs::read(evidence.join(format!("{head}.patch")))
4881                    .unwrap()
4882                    .is_empty()
4883            );
4884            assert_eq!(
4885                std::fs::read_to_string(artifacts.join("review.json")).unwrap(),
4886                "review findings"
4887            );
4888            if missing {
4889                assert_eq!(
4890                    std::fs::read_to_string(artifacts.join("cand-A.patch")).unwrap(),
4891                    "original snapshot"
4892                );
4893            } else {
4894                assert!(!artifacts.join("cand-A.patch").exists());
4895            }
4896            assert!(run_dir.join("run.json").exists());
4897        }
4898    }
4899
4900    #[tokio::test]
4901    async fn slow_retirement_proof_allows_task_updates_and_aborts_on_new_owner_pin() {
4902        use std::os::unix::fs::PermissionsExt as _;
4903        let f = Fx::new().await;
4904        let source = f.run("dd03", true).await;
4905        let empty = f.run("dd04", false).await;
4906        let task = f.task(&[source, empty.clone()]);
4907        let entered = f.repo.join("proof-entered");
4908        let release = f.repo.join("proof-release");
4909        let hook = f.repo.join("proof-monitor");
4910        std::fs::write(&hook, format!(
4911            "#!/bin/sh\n: > '{}'\nwhile ! test -f '{}'; do sleep 0.01; done\nprintf 'probe\\0'\n",
4912            entered.display(), release.display())).unwrap();
4913        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
4914        git::git(
4915            &f.repo,
4916            &["config", "core.fsmonitor", hook.to_str().unwrap()],
4917        )
4918        .await
4919        .unwrap();
4920        struct ReleaseProof(PathBuf);
4921        impl Drop for ReleaseProof {
4922            fn drop(&mut self) {
4923                let _ = std::fs::write(&self.0, "continue");
4924            }
4925        }
4926        let _release_on_panic = ReleaseProof(release.clone());
4927        let home = f.home.clone();
4928        let sweep = tokio::spawn(async move {
4929            let mut report = Report::default();
4930            retire_empty(&home, &Fx::disk(), Fx::now(), &mut report).await;
4931            report
4932        });
4933        // These are deadlock watchdogs, not speed assertions. The proof stays
4934        // blocked until the task update completes, even on a loaded runner.
4935        let watchdog = std::time::Duration::from_secs(60);
4936        tokio::time::timeout(watchdog, async {
4937            while !entered.exists() {
4938                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4939            }
4940        })
4941        .await
4942        .expect("Git retirement proof did not enter the blocking hook");
4943        let queue = crate::queue::Queue::at(f.home.join("queue"));
4944        let mut selected = queue.get(&task.id).unwrap();
4945        selected.resume_override = Some(crate::queue::OperatorResume {
4946            question_id: "during-slow-proof".into(),
4947            at: Fx::now(),
4948            conductor_rehold: None,
4949            forced: false,
4950            pinned_run: Some(empty.id.clone()),
4951        });
4952        let mut update = tokio::task::spawn_blocking(move || queue.put(&mut selected));
4953        // The proof is released only after the update returns, so correctness
4954        // is decided by ordering, not speed. The 60-second bound only detects
4955        // a writer blocked behind the proof; it is not a performance threshold.
4956        let updated_while_blocked = match tokio::time::timeout(watchdog, &mut update).await {
4957            Ok(result) => {
4958                result.unwrap().unwrap();
4959                true
4960            }
4961            Err(_) => {
4962                std::fs::write(&release, "continue").unwrap();
4963                update.await.unwrap().unwrap();
4964                false
4965            }
4966        };
4967        std::fs::write(release, "continue").unwrap();
4968        let report = tokio::time::timeout(watchdog, sweep)
4969            .await
4970            .expect("Git retirement proof did not finish after release")
4971            .unwrap();
4972        assert!(
4973            updated_while_blocked,
4974            "task writers must not wait behind Git retirement proof"
4975        );
4976        assert_eq!(report.retired, 0);
4977        assert!(report.retained.iter().any(|r| r.contains("task changed")));
4978        assert!(empty.candidates[0].worktree.exists());
4979        assert!(
4980            RunState::load_under(&empty.id, &f.home)
4981                .unwrap()
4982                .retired_to
4983                .is_none()
4984        );
4985    }
4986
4987    #[tokio::test]
4988    async fn retirement_commit_rechecks_task_after_unlocked_proof_and_preserves_new_pin() {
4989        let f = Fx::new().await;
4990        let source = f.run("dd01", true).await;
4991        let mut empty = f.run("dd02", false).await;
4992        let expected = f.task(&[source.clone(), empty.clone()]);
4993        let queue = crate::queue::Queue::at(f.home.join("queue"));
4994        let _claim = queue.claim(&expected.id).unwrap();
4995        // The proof holds run/output leases, never the task write lock.
4996        let _owner = crate::pr_head::owner_lock(&f.home, &empty.id).unwrap();
4997        let _driver = crate::driver::maintenance(&f.home, &empty.id).unwrap();
4998        let _outputs = OutputLease::take(&empty.candidates[0].worktree, true).unwrap();
4999        let mut selected = queue.get(&expected.id).unwrap();
5000        selected.resume_override = Some(crate::queue::OperatorResume {
5001            question_id: "new-owner-decision".into(),
5002            at: Fx::now(),
5003            conductor_rehold: None,
5004            forced: false,
5005            pinned_run: Some(empty.id.clone()),
5006        });
5007        queue.put(&mut selected).unwrap();
5008        let error = commit_retirement(
5009            &f.home,
5010            &queue,
5011            &expected,
5012            &mut empty,
5013            &source.id,
5014            &expected.runs,
5015            Fx::now(),
5016        )
5017        .unwrap_err();
5018        assert!(error.to_string().contains("task changed"));
5019        assert!(
5020            RunState::load_under(&empty.id, &f.home)
5021                .unwrap()
5022                .retired_to
5023                .is_none()
5024        );
5025        assert!(empty.candidates[0].worktree.exists());
5026        assert_eq!(
5027            queue
5028                .get(&expected.id)
5029                .unwrap()
5030                .resume_override
5031                .unwrap()
5032                .pinned_run,
5033            Some(empty.id.clone())
5034        );
5035        assert!(
5036            !f.home
5037                .join("recovery-lineages")
5038                .join(format!("{}.json", expected.id))
5039                .exists()
5040        );
5041        // Re-reading the new snapshot must not bypass its explicit pin either.
5042        assert!(
5043            commit_retirement(
5044                &f.home,
5045                &queue,
5046                &selected,
5047                &mut empty,
5048                &source.id,
5049                &selected.runs,
5050                Fx::now()
5051            )
5052            .unwrap_err()
5053            .to_string()
5054            .contains("selected this recovery source")
5055        );
5056    }
5057
5058    #[tokio::test]
5059    async fn cargo_owners_and_driver_resumes_are_protected_with_retained_root_data() {
5060        let f = Fx::new().await;
5061        let state = f.run("cccc", false).await;
5062        let wt = &state.candidates[0].worktree;
5063        Fx::target(wt);
5064        std::fs::write(wt.join("target/notes"), "user file").unwrap();
5065        std::os::unix::fs::symlink(f.repo.join("source"), wt.join("target/debug/link")).unwrap();
5066        assert!(
5067            !declared_outputs(&wt.join("target"))
5068                .unwrap()
5069                .contains(&wt.join("target/debug/link"))
5070        );
5071        std::fs::remove_file(wt.join("target/debug/link")).unwrap();
5072        let cargo = cargo_locks(&wt.join("target")).unwrap();
5073        let out = sweep(&f.home, &Fx::disk(), Fx::now()).await;
5074        assert_eq!(out.freed_bytes, 0);
5075        assert!(out.retained.iter().any(|s| s.contains("Cargo build")));
5076        drop(cargo);
5077        let driver = crate::driver::maintenance(&f.home, &state.id).unwrap();
5078        let out = sweep(&f.home, &Fx::disk(), Fx::now()).await;
5079        assert_eq!(out.freed_bytes, 0);
5080        drop(driver);
5081        let exclusive = OutputLease::take(wt, true).unwrap();
5082        assert!(
5083            OutputLease::borrow(wt).is_err(),
5084            "resume cannot start a writer during cleanup"
5085        );
5086        drop(exclusive);
5087        assert!(sweep(&f.home, &Fx::disk(), Fx::now()).await.freed_bytes > 0);
5088        assert_eq!(
5089            std::fs::read(wt.join("target/notes")).unwrap(),
5090            b"user file"
5091        );
5092    }
5093
5094    #[tokio::test]
5095    async fn root_leftovers_allow_eviction_but_keep_empty_attempts_registered() {
5096        for leftover in ["tmp", "magi-tools", "lifecycle-client-check.log"] {
5097            let f = Fx::new().await;
5098            let source = f.run("aa10", true).await;
5099            let empty = f.run("aa11", false).await;
5100            f.task(&[source, empty.clone()]);
5101            let wt = &empty.candidates[0].worktree;
5102            Fx::target(wt);
5103            let path = wt.join("target").join(leftover);
5104            if leftover.ends_with(".log") {
5105                std::fs::write(&path, "keep log\n").unwrap();
5106            } else {
5107                // Empty unknown directories are not present in residue_files.
5108                std::fs::create_dir(&path).unwrap();
5109            }
5110            let mut disk = Fx::disk();
5111            disk.auto_fold = true;
5112            let report = sweep(&f.home, &disk, Fx::now()).await;
5113            assert_eq!(report.freed_bytes, 200, "{report:?}");
5114            assert_eq!(report.retired, 0, "{report:?}");
5115            assert!(!wt.join("target/debug/output").exists());
5116            assert!(!residue_proof(&f.home, &empty.id, wt).unwrap().exists());
5117            assert!(path.exists());
5118            if leftover.ends_with(".log") {
5119                assert_eq!(std::fs::read(&path).unwrap(), b"keep log\n");
5120            }
5121            assert_eq!(std::fs::read(wt.join("source")).unwrap(), b"base\n");
5122            assert!(worktrees(&empty).await.unwrap().contains(wt));
5123            assert!(
5124                git::branch_exists(&f.repo, &empty.candidates[0].branch)
5125                    .await
5126                    .unwrap()
5127            );
5128            assert!(
5129                RunState::load_under(&empty.id, &f.home)
5130                    .unwrap()
5131                    .retired_to
5132                    .is_none()
5133            );
5134        }
5135    }
5136
5137    #[tokio::test]
5138    async fn residue_proof_rejects_new_unknown_root_entries_including_empty_directories() {
5139        let f = Fx::new().await;
5140        let state = f.run("aa12", false).await;
5141        let wt = &state.candidates[0].worktree;
5142        Fx::target(wt);
5143        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
5144        assert_eq!(report.freed_bytes, 200, "{report:?}");
5145        assert!(verify_residue(&f.home, &state.id, wt).await.is_ok());
5146        for name in ["tmp", "magi-tools", "log"] {
5147            let path = wt.join("target").join(name);
5148            std::fs::create_dir(&path).unwrap();
5149            assert!(verify_residue(&f.home, &state.id, wt).await.is_err());
5150            std::fs::remove_dir(path).unwrap();
5151        }
5152        assert!(verify_residue(&f.home, &state.id, wt).await.is_ok());
5153    }
5154
5155    #[tokio::test]
5156    async fn target_identity_and_known_profiles_still_fail_closed_with_root_leftovers() {
5157        for invalid in [
5158            "tag",
5159            "identity",
5160            "tracked",
5161            "profile-file",
5162            "profile-symlink",
5163            "identity-symlink",
5164        ] {
5165            let f = Fx::new().await;
5166            let state = f.run("aa13", false).await;
5167            let wt = &state.candidates[0].worktree;
5168            Fx::target(wt);
5169            std::fs::create_dir(wt.join("target/tmp")).unwrap();
5170            let target = wt.join("target");
5171            match invalid {
5172                "tag" => std::fs::write(target.join("CACHEDIR.TAG"), "not Cargo").unwrap(),
5173                "identity" => std::fs::write(target.join(".rustc_info.json"), "{}").unwrap(),
5174                "tracked" => {
5175                    git::git(wt, &["add", "-f", "target/debug/output"])
5176                        .await
5177                        .unwrap();
5178                }
5179                "profile-file" => {
5180                    std::fs::write(target.join("release"), "keep").unwrap();
5181                }
5182                "profile-symlink" => {
5183                    std::os::unix::fs::symlink(target.join("debug"), target.join("release"))
5184                        .unwrap();
5185                }
5186                "identity-symlink" => {
5187                    std::fs::rename(target.join(".rustc_info.json"), target.join("saved-info"))
5188                        .unwrap();
5189                    std::os::unix::fs::symlink(
5190                        target.join("saved-info"),
5191                        target.join(".rustc_info.json"),
5192                    )
5193                    .unwrap();
5194                }
5195                _ => unreachable!(),
5196            }
5197            let before = std::fs::read(target.join("debug/output")).unwrap();
5198            let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
5199            assert_eq!(report.freed_bytes, 0, "{invalid}: {report:?}");
5200            assert_eq!(std::fs::read(target.join("debug/output")).unwrap(), before);
5201            assert!(target.join("tmp").is_dir());
5202        }
5203    }
5204
5205    #[tokio::test]
5206    async fn reclaimed_cargo_residue_allows_retirement_only_while_exact_and_unowned() {
5207        let f = Fx::new().await;
5208        let source = f.run("0000", true).await;
5209        let empty = f.run("0001", false).await;
5210        let changed = f.run("0002", false).await;
5211        let unknown = f.run("0003", false).await;
5212        let unproven = f.run("0004", false).await;
5213        f.task(&[
5214            source.clone(),
5215            empty.clone(),
5216            changed.clone(),
5217            unknown.clone(),
5218            unproven.clone(),
5219        ]);
5220        for run in [&empty, &changed, &unknown] {
5221            Fx::target(&run.candidates[0].worktree);
5222        }
5223        let reviewer = empty.worktree_root().join("review-1");
5224        git::worktree_add_detached(&f.repo, &reviewer, &f.base)
5225            .await
5226            .unwrap();
5227        Fx::target(&reviewer);
5228        let mut disk = Fx::disk();
5229        disk.auto_fold = false;
5230        let report = sweep(&f.home, &disk, Fx::now()).await;
5231        assert_eq!(report.freed_bytes, 800, "{report:?}");
5232        let wt = &empty.candidates[0].worktree;
5233        assert!(wt.join("target/debug/output.d").exists());
5234        assert!(!wt.join("target/debug/output").exists());
5235        let proof_path = residue_proof(&f.home, &empty.id, wt).unwrap();
5236        let proof: CargoResidue =
5237            serde_json::from_slice(&std::fs::read(&proof_path).unwrap()).unwrap();
5238        assert_eq!(
5239            proof.files[Path::new("debug/output.d")],
5240            std::fs::read(wt.join("target/debug/output.d")).unwrap()
5241        );
5242        std::fs::write(
5243            changed.candidates[0].worktree.join("target/debug/output.d"),
5244            "owner notes",
5245        )
5246        .unwrap();
5247        std::fs::write(
5248            unknown.candidates[0].worktree.join("target/debug/notes"),
5249            "keep",
5250        )
5251        .unwrap();
5252        Fx::target(&unproven.candidates[0].worktree);
5253        std::fs::remove_file(unproven.candidates[0].worktree.join("target/debug/output")).unwrap();
5254        disk.auto_fold = true;
5255        let locks = cargo_locks(&wt.join("target")).unwrap();
5256        let mut report = Report::default();
5257        retire_empty(&f.home, &disk, Fx::now(), &mut report).await;
5258        assert_eq!(report.retired, 0, "{report:?}");
5259        assert!(
5260            report
5261                .retained
5262                .iter()
5263                .any(|reason| reason.contains("Cargo build"))
5264        );
5265        drop(locks);
5266        retire_empty(&f.home, &disk, Fx::now(), &mut report).await;
5267        assert_eq!(report.retired, 1, "{report:?}");
5268        assert!(!wt.exists());
5269        assert!(!reviewer.exists());
5270        assert!(
5271            residue_proof(&f.home, &empty.id, &reviewer)
5272                .unwrap()
5273                .exists()
5274        );
5275        assert!(
5276            proof_path.exists(),
5277            "metadata evidence outlives the worktree"
5278        );
5279        assert_eq!(
5280            RunState::load_under(&empty.id, &f.home).unwrap().retired_to,
5281            Some(source.id)
5282        );
5283        for run in [&changed, &unknown, &unproven] {
5284            assert!(run.candidates[0].worktree.exists());
5285            assert!(
5286                RunState::load_under(&run.id, &f.home)
5287                    .unwrap()
5288                    .retired_to
5289                    .is_none()
5290            );
5291        }
5292    }
5293
5294    #[tokio::test]
5295    async fn empty_backlog_retires_to_useful_older_source_in_bounded_idempotent_passes() {
5296        let f = Fx::new().await;
5297        let source = f.run("0000", true).await;
5298        let source_head = git::rev_parse(&f.repo, &source.candidates[0].branch)
5299            .await
5300            .unwrap();
5301        let mut runs = vec![source.clone()];
5302        for n in 1..=12 {
5303            runs.push(f.run(&format!("{n:04}"), false).await);
5304        }
5305        let dirty = runs[1].candidates[0].worktree.clone();
5306        std::fs::write(dirty.join("unrecorded"), "preparation changes").unwrap();
5307        let ignored = runs[2].candidates[0].worktree.clone();
5308        std::fs::create_dir(ignored.join("scratch")).unwrap();
5309        std::fs::write(ignored.join("scratch/note"), "keep").unwrap();
5310        // A missing candidate array does not prove that an unrecorded worktree
5311        // is empty: discovery must inspect Git and the worktree itself.
5312        runs[1].candidates.clear();
5313        runs[1].save_under(&f.home).unwrap();
5314        let task = f.task(&runs);
5315        let mut total = 0;
5316        for _ in 0..4 {
5317            let mut report = Report::default();
5318            retire_empty(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
5319            assert!(report.retired <= 5);
5320            total += report.retired;
5321        }
5322        assert_eq!(total, 10);
5323        assert!(dirty.exists());
5324        assert!(ignored.exists());
5325        assert_eq!(
5326            git::rev_parse(&f.repo, &source.candidates[0].branch)
5327                .await
5328                .unwrap(),
5329            source_head
5330        );
5331        let retired = RunState::load_under(&runs[3].id, &f.home).unwrap();
5332        assert_eq!(retired.retired_to.as_ref(), Some(&source.id));
5333        assert!(crate::pr_head::ensure_owner_record(&retired, Some(&retired)).is_err());
5334        let mut released = task.clone();
5335        released.release();
5336        assert_eq!(
5337            crate::daemon::unfinished_run_with(&released.runs, released.short(), |id| {
5338                RunState::load_under(id, &f.home)
5339            }),
5340            Some(source.id.clone())
5341        );
5342
5343        assert!(
5344            f.home
5345                .join("runs")
5346                .join(&retired.id)
5347                .join("run.json")
5348                .exists()
5349        );
5350        assert!(
5351            f.home
5352                .join("recovery-lineages")
5353                .join(format!("{}.json", task.id))
5354                .exists()
5355        );
5356    }
5357
5358    #[tokio::test]
5359    async fn distinct_candidates_and_explicitly_retained_sources_are_never_discarded() {
5360        let f = Fx::new().await;
5361        let a = f.run("dddd", true).await;
5362        let b = f.run("eeee", true).await;
5363        let empty = f.run("ffff", false).await;
5364        let task = f.task(&[a.clone(), b.clone(), empty.clone()]);
5365        assert!(
5366            crate::pr_recovery::source_retention_reason(&f.home, &a).is_some(),
5367            "unfinished queue history protects older source branches from ordinary folding"
5368        );
5369        let mut prior = a.clone();
5370        assert!(
5371            crate::graph::fold_run(&mut prior, true, &f.home)
5372                .await
5373                .unwrap_err()
5374                .to_string()
5375                .contains(&task.id)
5376        );
5377        let mut report = Report::default();
5378        retire_empty(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
5379        assert_eq!(report.retired, 0);
5380        assert!(report.retained.iter().any(|r| r.contains("ambiguous")));
5381        crate::pr_recovery::retain_sources(&task, &f.home).unwrap();
5382        Fx::target(&a.candidates[0].worktree);
5383        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
5384        assert!(
5385            report.freed_bytes > 0,
5386            "source retention does not retain regenerable outputs"
5387        );
5388        assert!(a.candidates[0].worktree.exists());
5389        assert!(b.candidates[0].worktree.exists());
5390        assert!(empty.candidates[0].worktree.exists());
5391    }
5392
5393    #[tokio::test]
5394    async fn decisions_checkpoints_and_partial_retirement_remain_safe() {
5395        let f = Fx::new().await;
5396        let authority = f.run("p000", true).await;
5397        let question_run = f.run("p001", false).await;
5398        let mut checkpoint = f.run("p002", false).await;
5399        checkpoint.land_approval = Some(crate::run::LandApproval {
5400            question: "pending".into(),
5401            head: f.base.clone(),
5402        });
5403        checkpoint.save_under(&f.home).unwrap();
5404        let retained = f.run("p003", false).await;
5405        std::fs::write(
5406            f.home
5407                .join("runs")
5408                .join(&retained.id)
5409                .join("retain-recovery-sources"),
5410            "owner",
5411        )
5412        .unwrap();
5413        let mut partial = f.run("p004", false).await;
5414        let reviewer = partial.worktree_root().join("review-1");
5415        git::worktree_add_detached(&f.repo, &reviewer, &f.base)
5416            .await
5417            .unwrap();
5418        // Model a crash after the retirement fence but only one removal.
5419        partial.retired_to = Some(authority.id.clone());
5420        partial.save_under(&f.home).unwrap();
5421        assert!(
5422            git::worktree_remove_clean(&f.repo, &partial.candidates[0].worktree)
5423                .await
5424                .unwrap()
5425        );
5426        let git_checkpoint = f.run("p005", false).await;
5427        let location = git::git(
5428            &git_checkpoint.candidates[0].worktree,
5429            &[
5430                "rev-parse",
5431                "--path-format=absolute",
5432                "--git-path",
5433                "sequencer",
5434            ],
5435        )
5436        .await
5437        .unwrap();
5438        std::fs::create_dir(location.trim()).unwrap();
5439        let mut preservation = f.run("p006", false).await;
5440        preservation
5441            .candidate_preservation
5442            .insert('A', "pending preservation".into());
5443        preservation.save_under(&f.home).unwrap();
5444        let task = f.task(&[
5445            preservation.clone(),
5446            git_checkpoint.clone(),
5447            authority.clone(),
5448            question_run.clone(),
5449            checkpoint.clone(),
5450            retained.clone(),
5451            partial.clone(),
5452        ]);
5453        let questions = crate::ask::Questions::at(f.home.join("questions"));
5454        let mut question = crate::ask::Question::new(
5455            question_run.id.clone(),
5456            "implement".into(),
5457            "fixture".into(),
5458            "owner decision".into(),
5459            String::new(),
5460            vec!["keep".into()],
5461        );
5462        questions.put(&mut question).unwrap();
5463        let mut report = Report::default();
5464        retire_empty(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
5465        assert_eq!(report.retired, 1, "{report:?}");
5466        assert!(!reviewer.exists());
5467        for state in [
5468            &question_run,
5469            &checkpoint,
5470            &retained,
5471            &git_checkpoint,
5472            &preservation,
5473        ] {
5474            assert!(state.candidates[0].worktree.exists());
5475            assert!(
5476                RunState::load_under(&state.id, &f.home)
5477                    .unwrap()
5478                    .retired_to
5479                    .is_none()
5480            );
5481        }
5482        assert!(questions.get(&question.id).unwrap().status.open());
5483        assert_eq!(
5484            crate::queue::Queue::at(f.home.join("queue"))
5485                .get(&task.id)
5486                .unwrap()
5487                .status,
5488            task.status
5489        );
5490    }
5491
5492    #[tokio::test]
5493    async fn preservation_schema_migration_remains_distinct_from_retirement() {
5494        let f = Fx::new().await;
5495        let mut state = f.run("p007", false).await;
5496        state.schema = 15;
5497        state.save_under(&f.home).unwrap();
5498        let native = RunState::load_under(&state.id, &f.home).unwrap();
5499        assert_eq!(native.schema, crate::run::SCHEMA);
5500        assert!(native.candidate_preservation.is_empty());
5501        assert!(native.retired_to.is_none());
5502        state.schema = 14;
5503        state.save_under(&f.home).unwrap();
5504        let mut legacy = RunState::load_under(&state.id, &f.home).unwrap();
5505        assert!(legacy.candidate_preservation.contains_key(&'A'));
5506        legacy.save_under(&f.home).unwrap();
5507        let restored = RunState::load_under(&state.id, &f.home).unwrap();
5508        assert_eq!(
5509            restored.candidate_preservation,
5510            legacy.candidate_preservation
5511        );
5512    }
5513
5514    #[tokio::test]
5515    async fn cache_cleanup_excludes_process_cleanup_and_missing_path_aliases() {
5516        let f = Fx::new().await;
5517        let cache = f.repo.join("cache");
5518        let guard = OutputLease::cache(&f.home, &cache, false).unwrap();
5519        std::fs::create_dir_all(&cache).unwrap();
5520        assert!(OutputLease::cache(&f.home, &cache, true).is_err());
5521        assert!(
5522            crate::cache::maintenance_prune(&f.home, &cache, 1)
5523                .unwrap()
5524                .is_none()
5525        );
5526        drop(guard);
5527        assert!(OutputLease::cache(&f.home, &cache, true).is_ok());
5528    }
5529
5530    #[tokio::test]
5531    async fn launcher_death_does_not_release_live_tool_output_reservations() {
5532        let f = Fx::new().await;
5533        let run = f.run("abcd", false).await;
5534        let wt = &run.candidates[0].worktree;
5535        let mut helper = tokio::process::Command::new(std::env::current_exe().unwrap());
5536        helper
5537            .quiet()
5538            .args(["--exact", "seat_process::tests::crashed_launcher_helper"])
5539            .env("MAGI_TEST_CRASHED_LAUNCHER", &f.home)
5540            .env("MAGI_TEST_WORKTREE", wt)
5541            .stdin(std::process::Stdio::null())
5542            .stdout(std::process::Stdio::null())
5543            .stderr(std::process::Stdio::null())
5544            .kill_on_drop(true);
5545        assert!(
5546            tokio::time::timeout(std::time::Duration::from_secs(8), helper.status())
5547                .await
5548                .unwrap()
5549                .unwrap()
5550                .success()
5551        );
5552        let pid: i32 = std::fs::read_to_string(f.home.join("tool.pid"))
5553            .unwrap()
5554            .trim()
5555            .parse()
5556            .unwrap();
5557        struct KillTool(i32);
5558        impl Drop for KillTool {
5559            fn drop(&mut self) {
5560                // SAFETY: PID belongs to the bounded helper above.
5561                unsafe { libc::kill(self.0, libc::SIGKILL) };
5562            }
5563        }
5564        let tool = KillTool(pid);
5565        assert!(OutputLease::take(wt, true).is_err());
5566        assert!(OutputLease::cache(&f.home, &f.home.join("cache"), true).is_err());
5567        drop(tool);
5568        tokio::time::timeout(std::time::Duration::from_secs(5), async {
5569            loop {
5570                if OutputLease::take(wt, true).is_ok()
5571                    && OutputLease::cache(&f.home, &f.home.join("cache"), true).is_ok()
5572                {
5573                    break;
5574                }
5575                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
5576            }
5577        })
5578        .await
5579        .unwrap();
5580    }
5581
5582    #[tokio::test]
5583    async fn orphaned_tool_keeps_output_and_cache_leases_after_cli_exit() {
5584        let f = Fx::new().await;
5585        let run = f.run("abcd", false).await;
5586        let wt = &run.candidates[0].worktree;
5587        let cache = f.repo.join("cache");
5588        std::fs::create_dir(&cache).unwrap();
5589        for (cancel, clear_owner) in [(false, true), (true, true), (false, false), (true, false)] {
5590            let pid_file = f.repo.join(format!("orphan-{cancel}-{clear_owner}"));
5591            let mut cmd = tokio::process::Command::new(std::env::current_exe().unwrap());
5592            cmd.quiet()
5593                .args(["--exact", "seat_process::tests::orphan_tool_helper"])
5594                .env("MAGI_TEST_ORPHAN_PID", &pid_file)
5595                .stdin(std::process::Stdio::null())
5596                .stdout(std::process::Stdio::null())
5597                .stderr(std::process::Stdio::null())
5598                .kill_on_drop(true);
5599            if clear_owner {
5600                cmd.env("MAGI_TEST_CLEAR_OWNER", "1");
5601            } else {
5602                cmd.env("MAGI_TEST_CLOSE_FDS", "1");
5603            }
5604            let gib = 1024 * 1024 * 1024;
5605            let mut leases = vec![
5606                OutputLease::borrow(wt).unwrap().unwrap(),
5607                OutputLease::cache(&f.home, &cache, false).unwrap(),
5608            ];
5609            leases.extend(
5610                OutputLease::admit_with(
5611                    &f.home,
5612                    std::slice::from_ref(wt),
5613                    8 * gib,
5614                    |_| Ok(9 * gib),
5615                )
5616                .unwrap(),
5617            );
5618            let mut running = crate::seat_process::Running::spawn(cmd, None, leases).unwrap();
5619            assert!(
5620                tokio::time::timeout(std::time::Duration::from_secs(5), running.child().wait())
5621                    .await
5622                    .unwrap()
5623                    .unwrap()
5624                    .success()
5625            );
5626            let pid: i32 = std::fs::read_to_string(pid_file).unwrap().parse().unwrap();
5627            struct KillTool(Option<i32>);
5628            impl Drop for KillTool {
5629                fn drop(&mut self) {
5630                    // SAFETY: PID from our helper; kill also bounds panic paths.
5631                    if let Some(pid) = self.0 {
5632                        unsafe { libc::kill(pid, libc::SIGKILL) };
5633                    }
5634                }
5635            }
5636            let mut tool = KillTool(Some(pid));
5637            // The CLI has already exited and cannot supply a parent-tree
5638            // relationship. Either the witness or inherited environment must
5639            // retain ownership; test each independently.
5640            assert!(OutputLease::take(wt, true).is_err());
5641            let finish = if cancel {
5642                drop(running);
5643                None
5644            } else {
5645                Some(tokio::spawn(async move { running.finish().await }))
5646            };
5647            if clear_owner {
5648                tokio::time::sleep(std::time::Duration::from_millis(150)).await;
5649                assert!(crate::proc::pid_alive(pid as u32));
5650                assert!(OutputLease::take(wt, true).is_err(), "cancel={cancel}");
5651                assert!(OutputLease::cache(&f.home, &cache, true).is_err());
5652                assert!(
5653                    OutputLease::admit_with(&f.home, std::slice::from_ref(wt), 8 * gib, |_| Ok(
5654                        9 * gib
5655                    ))
5656                    .is_err(),
5657                    "orphan still owns its disk reservation"
5658                );
5659                assert!(
5660                    crate::cache::maintenance_prune(&f.home, &cache, 0)
5661                        .unwrap()
5662                        .is_none()
5663                );
5664                if let Some(finish) = &finish {
5665                    assert!(!finish.is_finished());
5666                }
5667                // Witness-only ownership waits for natural/external tool exit.
5668                unsafe { libc::kill(pid, libc::SIGKILL) };
5669            }
5670            if let Some(finish) = finish {
5671                tokio::time::timeout(std::time::Duration::from_secs(5), finish)
5672                    .await
5673                    .unwrap()
5674                    .unwrap();
5675            }
5676            tokio::time::timeout(std::time::Duration::from_secs(5), async {
5677                loop {
5678                    if OutputLease::take(wt, true).is_ok()
5679                        && OutputLease::cache(&f.home, &cache, true).is_ok()
5680                        && OutputLease::admit_with(
5681                            &f.home,
5682                            std::slice::from_ref(wt),
5683                            8 * gib,
5684                            |_| Ok(9 * gib),
5685                        )
5686                        .is_ok()
5687                    {
5688                        // Token-owned orphans must be stopped by cleanup itself.
5689                        if !clear_owner {
5690                            assert!(!crate::proc::pid_alive(pid as u32));
5691                        }
5692                        break;
5693                    }
5694                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
5695                }
5696            })
5697            .await
5698            .unwrap();
5699            tool.0 = None;
5700        }
5701    }
5702
5703    #[tokio::test]
5704    async fn cancellation_keeps_output_and_cache_ownership_until_tools_terminate() {
5705        let f = Fx::new().await;
5706        let run = f.run("abcd", false).await;
5707        let wt = &run.candidates[0].worktree;
5708        let cache = f.repo.join("cache");
5709        std::fs::create_dir(&cache).unwrap();
5710        let pid_file = f.repo.join("child-pid");
5711        let mut cmd = tokio::process::Command::new("sh");
5712        cmd.args([
5713            "-c",
5714            r#"sleep 30 &
5715               printf '%s\n' "$!" > "$CHILD_PID_FILE.tmp" &&
5716               mv "$CHILD_PID_FILE.tmp" "$CHILD_PID_FILE" &&
5717               wait"#,
5718        ])
5719        .quiet()
5720        .env("CHILD_PID_FILE", &pid_file)
5721        .process_group(0)
5722        .kill_on_drop(true);
5723        let running = crate::seat_process::Running::spawn(
5724            cmd,
5725            None,
5726            vec![
5727                OutputLease::borrow(wt).unwrap().unwrap(),
5728                OutputLease::cache(&f.home, &cache, false).unwrap(),
5729            ],
5730        )
5731        .unwrap();
5732        tokio::time::timeout(std::time::Duration::from_secs(5), async {
5733            while !pid_file.exists() {
5734                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
5735            }
5736        })
5737        .await
5738        .unwrap();
5739        assert!(OutputLease::take(wt, true).is_err());
5740        assert!(
5741            crate::cache::maintenance_prune(&f.home, &cache, 0)
5742                .unwrap()
5743                .is_none()
5744        );
5745        let pid: u32 = std::fs::read_to_string(pid_file)
5746            .unwrap()
5747            .trim()
5748            .parse()
5749            .unwrap();
5750        drop(running);
5751        tokio::time::timeout(std::time::Duration::from_secs(10), async {
5752            loop {
5753                if let Ok(guard) = OutputLease::take(wt, true) {
5754                    assert!(
5755                        !crate::proc::pid_alive(pid),
5756                        "output lock released before tool death"
5757                    );
5758                    drop(guard);
5759                    break;
5760                }
5761                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
5762            }
5763        })
5764        .await
5765        .unwrap();
5766        assert!(OutputLease::cache(&f.home, &cache, true).is_ok());
5767    }
5768
5769    #[tokio::test]
5770    async fn emergency_pressure_closes_writes_and_zero_floor_opts_out() {
5771        let f = Fx::new().await;
5772        let reason = tokio::time::timeout(
5773            std::time::Duration::from_secs(2),
5774            emergency(vec![f.repo.clone()], u64::MAX, false),
5775        )
5776        .await
5777        .unwrap();
5778        assert!(reason.contains("disk pressure"));
5779        assert!(
5780            tokio::time::timeout(
5781                std::time::Duration::from_millis(10),
5782                emergency(vec![f.repo.clone()], 0, false)
5783            )
5784            .await
5785            .is_err()
5786        );
5787        assert_eq!(
5788            std::fs::read_to_string(f.repo.join("source")).unwrap(),
5789            "base\n"
5790        );
5791    }
5792
5793    #[tokio::test]
5794    async fn automatic_requeues_cannot_refund_failed_input_generation() {
5795        let f = Fx::new().await;
5796        let mut run = f.run("1234", false).await;
5797        run.prep_failure = Some("cherry-pick conflict".into());
5798        let mut task = f.task(std::slice::from_ref(&run));
5799        let inputs = crate::queue::recovery_inputs(&run.sources);
5800        for _ in 0..108 {
5801            task.recovery_failed(&run);
5802            task.requeue();
5803            assert_eq!(task.attempts, 0);
5804        }
5805        let bytes = serde_json::to_vec(&task).unwrap();
5806        let mut restored: Task = serde_json::from_slice(&bytes).unwrap();
5807        assert!(
5808            restored
5809                .recovery_exhausted(&run.base_commit, &inputs, 2)
5810                .is_some()
5811        );
5812        assert!(
5813            restored
5814                .recovery_exhausted("different-base", &inputs, 2)
5815                .is_none()
5816        );
5817        let original_base = run.base_commit.clone();
5818        run.base_commit = "different-base".into();
5819        restored.recovery_failed(&run);
5820        assert!(
5821            restored
5822                .recovery_exhausted(&original_base, &inputs, 2)
5823                .is_some(),
5824            "returning to old inputs does not replenish their budget"
5825        );
5826        assert!(
5827            restored
5828                .recovery_exhausted(&run.base_commit, &inputs, 2)
5829                .is_none()
5830        );
5831        restored.release_operator("test-owner", None);
5832        assert!(
5833            restored
5834                .recovery_exhausted(&run.base_commit, &inputs, 2)
5835                .is_none()
5836        );
5837    }
5838    async fn inactive_source(f: &Fx, tag: &str, useful: bool) -> RunState {
5839        let mut state = f.run(tag, useful).await;
5840        state.status = RunStatus::Superseded;
5841        state.save_under(&f.home).unwrap();
5842        state
5843    }
5844
5845    fn historical_review(state: &mut RunState, head: &str) {
5846        state.reviews.push(
5847            serde_json::from_value(serde_json::json!({
5848                "round": state.reviews.len() + 1, "head": head, "reviews": []
5849            }))
5850            .unwrap(),
5851        );
5852    }
5853
5854    async fn reviewer(f: &Fx, state: &RunState, head: &str) -> PathBuf {
5855        let path = state.worktree_root().join("review-1");
5856        git::worktree_add_detached(&f.repo, &path, head)
5857            .await
5858            .unwrap();
5859        path
5860    }
5861
5862    #[tokio::test]
5863    async fn source_eviction_separates_run_authority_from_read_seats() {
5864        for status in [RunStatus::Superseded, RunStatus::Ready, RunStatus::Merged] {
5865            let f = Fx::new().await;
5866            let mut state = inactive_source(&f, "ef01", true).await;
5867            state.status = status;
5868            state.pr = Some(
5869                serde_json::from_value(serde_json::json!({
5870                    "url":"https://example.invalid/pull/1", "number":1, "state":"merged",
5871                    "checks":"green", "round":1, "rounds":1
5872                }))
5873                .unwrap(),
5874            );
5875            state.pr_head = Some(state.candidates[0].branch.clone());
5876            state.pr_merged_head = Some(f.base.clone());
5877            state.recovery = Some(
5878                serde_json::from_value(serde_json::json!({
5879                    "from_run": "20260101-000000-abcd", "generation": 1,
5880                    "mode": "full-review"
5881                }))
5882                .unwrap(),
5883            );
5884            state.pr_recovery = Some(
5885                serde_json::from_value(serde_json::json!({
5886                    "url": "https://example.invalid/pull/1", "branch": "public",
5887                    "head": f.base, "source_run": state.id,
5888                    "instruction": "keep implementation", "approved_at": Fx::now()
5889                }))
5890                .unwrap(),
5891            );
5892            state.save_under(&f.home).unwrap();
5893            let review = reviewer(&f, &state, &f.base).await;
5894            let mut other = inactive_source(&f, "ef02", true).await;
5895            other.pr_recovery = state.pr_recovery.clone();
5896            other.save_under(&f.home).unwrap();
5897            let mut task = f.task(&[state.clone(), other]);
5898            task.pr_recovery = state.pr_recovery.clone();
5899            crate::queue::Queue::at(f.home.join("queue"))
5900                .put(&mut task)
5901                .unwrap();
5902            let run_path = f.home.join("runs").join(&state.id).join("run.json");
5903            let before = std::fs::read(&run_path).unwrap();
5904            let task_before = serde_json::to_value(&task).unwrap();
5905            let mut report = Report::default();
5906            copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
5907            assert_eq!(report.evicted_copies, 1, "{status:?}: {report:?}");
5908            assert!(!review.exists());
5909            assert!(state.candidates[0].worktree.exists());
5910            assert!(
5911                git::branch_exists(&f.repo, &state.candidates[0].branch)
5912                    .await
5913                    .unwrap()
5914            );
5915            assert_eq!(std::fs::read(&run_path).unwrap(), before);
5916            assert_eq!(
5917                serde_json::to_value(
5918                    crate::queue::Queue::at(f.home.join("queue"))
5919                        .get(&task.id)
5920                        .unwrap()
5921                )
5922                .unwrap(),
5923                task_before
5924            );
5925        }
5926    }
5927
5928    #[tokio::test]
5929    async fn source_eviction_retains_own_paths_and_unfinished_continuations() {
5930        for kind in ["own-path", "active-seat", "paused-session"] {
5931            let f = Fx::new().await;
5932            let mut state = inactive_source(&f, "ef03", true).await;
5933            let review = reviewer(&f, &state, &f.base).await;
5934            let expected = match kind {
5935                "own-path" => {
5936                    state.attachments.push(review.join("source"));
5937                    "run.attachments[0]"
5938                }
5939                "active-seat" => {
5940                    state.active.insert(
5941                        "review-1".into(),
5942                        serde_json::from_value(serde_json::json!({
5943                            "node":"review", "started_at":Fx::now(), "timeout_secs":60
5944                        }))
5945                        .unwrap(),
5946                    );
5947                    "continuation lease"
5948                }
5949                _ => {
5950                    state.status = RunStatus::Blocked;
5951                    state.parked = true;
5952                    let mut seat = crate::agent::SeatState::new("review-1", "fixture", 1);
5953                    seat.turns = 2;
5954                    seat.captured_session = Some("saved-session".into());
5955                    state.seats.insert("review-1".into(), seat);
5956                    "resume contract"
5957                }
5958            };
5959            state.save_under(&f.home).unwrap();
5960            let mut report = Report::default();
5961            copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
5962            assert_eq!(report.evicted_copies, 0, "{kind}: {report:?}");
5963            assert!(review.exists());
5964            assert!(
5965                report.retained.iter().any(|r| r.contains(expected)),
5966                "{kind}: {report:?}"
5967            );
5968            // The execution restoration boundary leaves protected existing
5969            // seats and their sessions untouched; prep need not recreate them.
5970            restore_execution_seats(&f.home, &state, None)
5971                .await
5972                .unwrap();
5973            assert_eq!(git::rev_parse(&review, "HEAD").await.unwrap(), f.base);
5974        }
5975    }
5976
5977    #[tokio::test]
5978    async fn source_eviction_distinguishes_historical_cwd_from_question_dependencies() {
5979        for kind in ["waiting", "lease", "historical", "unknown"] {
5980            let f = Fx::new().await;
5981            let state = inactive_source(&f, "ef06", true).await;
5982            let review = reviewer(&f, &state, &f.base).await;
5983            let store = crate::ask::Questions::at(f.home.join("questions"));
5984            let mut question = crate::ask::Question::new(
5985                "20260101-000000-ffff".into(),
5986                "review".into(),
5987                "review-1".into(),
5988                "fixture".into(),
5989                "fixture".into(),
5990                Vec::new(),
5991            );
5992            question.cwd = Some(review.to_string_lossy().into_owned());
5993            if kind != "waiting" {
5994                question.status = crate::ask::QuestionStatus::Abandoned;
5995            }
5996            store.put(&mut question).unwrap();
5997            if kind == "lease" {
5998                store.beat(&question.id, crate::ask::WaiterKind::Daemon);
5999            }
6000            if kind == "unknown" {
6001                let path = store.path_of(&question.id);
6002                let mut raw: serde_json::Value =
6003                    serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
6004                raw["future_cwd_authority"] = serde_json::Value::Null;
6005                std::fs::write(path, serde_json::to_vec(&raw).unwrap()).unwrap();
6006            }
6007            let mut report = Report::default();
6008            copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6009            assert_eq!(
6010                report.evicted_copies,
6011                usize::from(kind == "historical"),
6012                "{kind}: {report:?}"
6013            );
6014            assert_eq!(review.exists(), kind != "historical");
6015            if kind == "waiting" || kind == "lease" {
6016                assert!(
6017                    report
6018                        .retained
6019                        .iter()
6020                        .any(|r| r.contains("question") && r.contains("cwd")),
6021                    "{report:?}"
6022                );
6023            }
6024        }
6025    }
6026
6027    #[tokio::test]
6028    async fn archived_seat_setup_reuses_repository_coordination() {
6029        crate::run::pin_test_home();
6030        let f = Fx::new().await;
6031        let mut state = inactive_source(&f, "ef07", true).await;
6032        let review = reviewer(&f, &state, &f.base).await;
6033        let mut report = Report::default();
6034        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6035        assert_eq!(report.evicted_copies, 1, "{report:?}");
6036        git::acquire_worktree_config(&f.repo).await.unwrap();
6037        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
6038        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
6039        state.config.disk.min_free_bytes = 0;
6040        state.config.worktree.setup = vec![crate::config::SetupStep {
6041            run: Some("touch setup-completed".into()),
6042            ..Default::default()
6043        }];
6044        std::fs::write(f.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
6045        state.config.coordination = Some(crate::config::Coordination {
6046            contract_file: "fixture-contract".into(),
6047            contract_token: "fixture-v1".into(),
6048            lock_file: "fixture-lock".into(),
6049        });
6050        let timeout = std::time::Duration::from_secs(15);
6051        let wait = crate::repo_lock::WaitPolicy::new(timeout, || false);
6052        let lease = crate::repo_lock::SeatLease::operation_with(
6053            &f.repo,
6054            state.config.coordination.as_ref(),
6055            &wait,
6056        )
6057        .await
6058        .unwrap()
6059        .unwrap();
6060        for _ in 0..2 {
6061            tokio::time::timeout(
6062                timeout,
6063                restore_execution_seats(&f.home, &state, Some(&lease)),
6064            )
6065            .await
6066            .expect("restoration must not wait for its own repository operation")
6067            .unwrap();
6068        }
6069        assert!(review.join("setup-completed").is_file());
6070    }
6071
6072    #[tokio::test]
6073    async fn source_eviction_failed_execution_setup_keeps_its_checkpoint() {
6074        let f = Fx::new().await;
6075        let mut state = inactive_source(&f, "ef07", true).await;
6076        let review = reviewer(&f, &state, &f.base).await;
6077        let mut report = Report::default();
6078        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6079        assert_eq!(report.evicted_copies, 1, "{report:?}");
6080        state.config.worktree.setup = vec![crate::config::SetupStep {
6081            run: Some("printf preserved > source; exit 1".into()),
6082            ..Default::default()
6083        }];
6084        state.save_under(&f.home).unwrap();
6085        assert!(
6086            restore_execution_seats(&f.home, &state, None)
6087                .await
6088                .is_err()
6089        );
6090        let marker = f
6091            .home
6092            .join("runs")
6093            .join(&state.id)
6094            .join("artifacts/restore-review-1.pending");
6095        assert!(marker.exists());
6096        assert_eq!(
6097            std::fs::read_to_string(review.join("source")).unwrap(),
6098            "preserved"
6099        );
6100        assert!(
6101            restore_execution_seats(&f.home, &state, None)
6102                .await
6103                .unwrap_err()
6104                .to_string()
6105                .contains("interrupted execution restoration")
6106        );
6107        let mut retry = Report::default();
6108        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut retry).await;
6109        assert_eq!(retry.evicted_copies, 0, "{retry:?}");
6110        assert!(
6111            retry
6112                .retained
6113                .iter()
6114                .any(|r| r.contains("restoration checkpoint")),
6115            "{retry:?}"
6116        );
6117        assert!(marker.exists());
6118        assert_eq!(
6119            std::fs::read_to_string(review.join("source")).unwrap(),
6120            "preserved"
6121        );
6122    }
6123
6124    #[tokio::test]
6125    async fn source_eviction_retains_borrowed_or_promisor_anchor_stores() {
6126        for kind in [
6127            "alternates",
6128            "promisor-config",
6129            "promisor-pack",
6130            "objects-symlink",
6131        ] {
6132            let f = Fx::new().await;
6133            let state = inactive_source(&f, "ef11", true).await;
6134            let review = reviewer(&f, &state, &f.base).await;
6135            let common = crate::repo_lock::common_dir(&f.repo)
6136                .await
6137                .unwrap()
6138                .unwrap();
6139            match kind {
6140                "alternates" => {
6141                    let borrowed = f._temp.path().join("borrowed-objects");
6142                    std::fs::create_dir(&borrowed).unwrap();
6143                    std::fs::write(
6144                        common.join("objects/info/alternates"),
6145                        format!("{}\n", borrowed.display()),
6146                    )
6147                    .unwrap();
6148                }
6149                "promisor-config" => {
6150                    git::git(&f.repo, &["config", "remote.origin.promisor", "true"])
6151                        .await
6152                        .unwrap();
6153                }
6154                "promisor-pack" => {
6155                    std::fs::write(common.join("objects/pack/fixture.promisor"), "").unwrap();
6156                }
6157                _ => {
6158                    let borrowed = f._temp.path().join("borrowed-objects");
6159                    std::fs::rename(common.join("objects"), &borrowed).unwrap();
6160                    std::os::unix::fs::symlink(borrowed, common.join("objects")).unwrap();
6161                }
6162            }
6163            let mut report = Report::default();
6164            copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6165            assert_eq!(report.evicted_copies, 0, "{kind}: {report:?}");
6166            assert!(review.exists());
6167            assert!(
6168                report.retained.iter().any(|r| r.contains("source anchor")),
6169                "{kind}: {report:?}"
6170            );
6171        }
6172    }
6173
6174    #[tokio::test]
6175    async fn source_eviction_bounds_long_shared_history_and_requires_its_retained_anchor() {
6176        let mut f = Fx::new().await;
6177        crate::fold_evidence::fixtures::shared_history(&f.repo, &f.base, 5000).await;
6178        f.base = git::rev_parse(&f.repo, "HEAD").await.unwrap();
6179        assert_eq!(
6180            git::git(&f.repo, &["rev-list", "--count", &f.base])
6181                .await
6182                .unwrap(),
6183            "5001"
6184        );
6185        let state = inactive_source(&f, "ef10", true).await;
6186        let review = reviewer(&f, &state, &f.base).await;
6187        std::fs::write(review.join("source"), "bounded review delta").unwrap();
6188        git::git(&review, &["add", "."]).await.unwrap();
6189        let tree = git::git(&review, &["write-tree"]).await.unwrap();
6190        let head = git::git(
6191            &review,
6192            &["commit-tree", &tree, "-p", &f.base, "-m", "review delta"],
6193        )
6194        .await
6195        .unwrap();
6196        git::git(&review, &["checkout", "--detach", &head])
6197            .await
6198            .unwrap();
6199        let run_file = f.home.join("runs").join(&state.id).join("run.json");
6200        let run_before = std::fs::read(&run_file).unwrap();
6201        let mut report = Report::default();
6202        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6203        assert_eq!(report.evicted_copies, 1, "{report:?}");
6204        assert!(!review.exists());
6205        assert!(state.candidates[0].worktree.exists());
6206        assert!(
6207            git::branch_exists(&f.repo, &state.candidates[0].branch)
6208                .await
6209                .unwrap()
6210        );
6211        assert_eq!(std::fs::read(&run_file).unwrap(), run_before);
6212        let archive = f
6213            .home
6214            .join("runs")
6215            .join(&state.id)
6216            .join("artifacts/source-evidence")
6217            .join(format!("{head}-{}", f.base));
6218        let manifest: serde_json::Value =
6219            serde_json::from_slice(&std::fs::read(archive.join("manifest.json")).unwrap()).unwrap();
6220        assert_eq!(manifest["anchor"], f.base);
6221        assert!(
6222            std::fs::metadata(archive.join("objects.pack"))
6223                .unwrap()
6224                .len()
6225                < 16 * 1024
6226        );
6227        let pin = format!("refs/magi/source-anchors/{}", f.base);
6228        assert_eq!(git::rev_parse(&f.repo, &pin).await.unwrap(), f.base);
6229        git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
6230            .await
6231            .unwrap();
6232        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6233        assert!(
6234            !git::git_raw(&f.repo, &["cat-file", "-e", &head])
6235                .await
6236                .unwrap()
6237                .ok()
6238        );
6239        let other = git::rev_parse(&state.candidates[0].worktree, "HEAD")
6240            .await
6241            .unwrap();
6242        // Missing, moved, symbolic and symlink pins cannot authorize import.
6243        for kind in ["missing", "moved", "symbolic", "symlink"] {
6244            git::git(&f.repo, &["update-ref", "--no-deref", "-d", &pin])
6245                .await
6246                .unwrap();
6247            match kind {
6248                "moved" => {
6249                    git::git(&f.repo, &["update-ref", &pin, &other])
6250                        .await
6251                        .unwrap();
6252                }
6253                "symbolic" => {
6254                    git::git(&f.repo, &["symbolic-ref", &pin, "refs/heads/main"])
6255                        .await
6256                        .unwrap();
6257                }
6258                "symlink" => {
6259                    let common = crate::repo_lock::common_dir(&f.repo)
6260                        .await
6261                        .unwrap()
6262                        .unwrap();
6263                    let target = f._temp.path().join("operator-anchor");
6264                    std::fs::write(&target, format!("{}\n", f.base)).unwrap();
6265                    let file = common.join(&pin);
6266                    std::fs::create_dir_all(file.parent().unwrap()).unwrap();
6267                    std::os::unix::fs::symlink(target, file).unwrap();
6268                }
6269                _ => {}
6270            }
6271            assert!(
6272                restore_execution_seats(&f.home, &state, None)
6273                    .await
6274                    .is_err(),
6275                "{kind}"
6276            );
6277            assert!(!review.exists());
6278            assert!(
6279                !git::git_raw(&f.repo, &["cat-file", "-e", &head])
6280                    .await
6281                    .unwrap()
6282                    .ok()
6283            );
6284            if kind == "symlink" {
6285                let common = crate::repo_lock::common_dir(&f.repo)
6286                    .await
6287                    .unwrap()
6288                    .unwrap();
6289                std::fs::remove_file(common.join(&pin)).unwrap();
6290            } else {
6291                git::git(&f.repo, &["update-ref", "--no-deref", "-d", &pin])
6292                    .await
6293                    .unwrap();
6294            }
6295            git::git(&f.repo, &["update-ref", &pin, &f.base])
6296                .await
6297                .unwrap();
6298        }
6299        // Fixture-only ref deletion proves the pin, rather than an incidental
6300        // main/candidate branch, keeps all shared ancestors through GC.
6301        assert!(
6302            git::worktree_remove_clean(&f.repo, &state.candidates[0].worktree)
6303                .await
6304                .unwrap()
6305        );
6306        git::git(
6307            &f.repo,
6308            &[
6309                "update-ref",
6310                "-d",
6311                &format!("refs/heads/{}", state.candidates[0].branch),
6312            ],
6313        )
6314        .await
6315        .unwrap();
6316        git::git(&f.repo, &["update-ref", "-d", "refs/heads/main"])
6317            .await
6318            .unwrap();
6319        git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
6320            .await
6321            .unwrap();
6322        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6323        assert_eq!(
6324            git::git(&f.repo, &["for-each-ref", "--format=%(refname)"])
6325                .await
6326                .unwrap(),
6327            pin
6328        );
6329        assert_eq!(
6330            git::git(&f.repo, &["rev-list", "--count", &f.base])
6331                .await
6332                .unwrap(),
6333            "5001"
6334        );
6335        restore_execution_seats(&f.home, &state, None)
6336            .await
6337            .unwrap();
6338        assert_eq!(
6339            git::git(&review, &["rev-list", "--count", "HEAD"])
6340                .await
6341                .unwrap(),
6342            "5002"
6343        );
6344        assert_eq!(
6345            git::git(&f.repo, &["rev-parse", "--is-shallow-repository"])
6346                .await
6347                .unwrap(),
6348            "false"
6349        );
6350        git::git(&f.repo, &["fsck", "--full"]).await.unwrap();
6351        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6352        let patch = seat_diff(&f.home, &state.id, &head).await.unwrap();
6353        assert!(String::from_utf8_lossy(&patch).contains("bounded review delta"));
6354        std::fs::remove_dir_all(&f.repo).unwrap();
6355        assert_eq!(seat_diff(&f.home, &state.id, &head).await.unwrap(), patch);
6356        let inspection = f._temp.path().join("shared-history-inspection");
6357        restore_seat(&f.home, &state.id, &head, &inspection)
6358            .await
6359            .unwrap();
6360        assert_eq!(git::rev_parse(&inspection, "HEAD").await.unwrap(), head);
6361        assert_eq!(
6362            git::git(&inspection, &["rev-parse", "--is-shallow-repository"])
6363                .await
6364                .unwrap(),
6365            "true"
6366        );
6367        assert_eq!(
6368            git::git(&inspection, &["log", "--format=%H"])
6369                .await
6370                .unwrap(),
6371            format!("{head}\n{}", f.base)
6372        );
6373        assert!(!inspection.join(".git/objects/info/alternates").exists());
6374        git::git(&inspection, &["fsck", "--full"]).await.unwrap();
6375        git::git(&inspection, &["gc", "--prune=now"]).await.unwrap();
6376    }
6377
6378    #[tokio::test]
6379    async fn source_eviction_retains_tree_only_archives_and_rejects_import_before_writes() {
6380        let f = Fx::new().await;
6381        let state = inactive_source(&f, "ef08", true).await;
6382        let review = reviewer(&f, &state, &f.base).await;
6383        let tree = git::rev_parse(&review, "HEAD^{tree}").await.unwrap();
6384        let parent = git::git(&review, &["commit-tree", &tree, "-m", "U0"])
6385            .await
6386            .unwrap();
6387        let head = git::git(&review, &["commit-tree", &tree, "-p", &parent, "-m", "U1"])
6388            .await
6389            .unwrap();
6390        git::git(&review, &["checkout", "--detach", &head])
6391            .await
6392            .unwrap();
6393        let archive =
6394            crate::fold_evidence::fixtures::tree_only_archive(&state, &f.home, &head).await;
6395        let mut report = Report::default();
6396        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6397        assert_eq!(report.evicted_copies, 0, "{report:?}");
6398        assert!(review.exists());
6399        assert!(
6400            report
6401                .retained
6402                .iter()
6403                .any(|r| r.contains("incomplete archived commit ancestry")),
6404            "{report:?}"
6405        );
6406        // Simulate a historical checkout already removed by the old writer.
6407        assert!(git::worktree_remove_clean(&f.repo, &review).await.unwrap());
6408        git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
6409            .await
6410            .unwrap();
6411        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6412        for oid in [&parent, &head] {
6413            assert!(
6414                !git::git_raw(&f.repo, &["cat-file", "-e", oid])
6415                    .await
6416                    .unwrap()
6417                    .ok()
6418            );
6419        }
6420        let patch = source_diff(&archive).await.unwrap();
6421        assert!(
6422            crate::fold_evidence::import_snapshot(&archive, &f.repo)
6423                .await
6424                .is_err()
6425        );
6426        assert!(
6427            !git::git_raw(&f.repo, &["cat-file", "-e", &head])
6428                .await
6429                .unwrap()
6430                .ok()
6431        );
6432        git::git(&f.repo, &["fsck", "--full"]).await.unwrap();
6433        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6434        let inspection = f._temp.path().join("legacy-tree-inspection");
6435        restore_source(&archive, &inspection).await.unwrap();
6436        assert_eq!(git::git(&inspection, &["write-tree"]).await.unwrap(), tree);
6437        assert!(
6438            !git::git_raw(&inspection, &["rev-parse", "--verify", "HEAD"])
6439                .await
6440                .unwrap()
6441                .ok()
6442        );
6443        git::git(&inspection, &["fsck", "--full"]).await.unwrap();
6444        git::git(&inspection, &["gc", "--prune=now"]).await.unwrap();
6445        assert_eq!(source_diff(&archive).await.unwrap(), patch);
6446        assert!(state.candidates[0].worktree.exists());
6447    }
6448
6449    #[tokio::test]
6450    async fn source_eviction_retains_ancestry_above_expanded_budget() {
6451        let f = Fx::new().await;
6452        let state = inactive_source(&f, "ef09", true).await;
6453        let review = reviewer(&f, &state, &f.base).await;
6454        std::fs::File::create(review.join("ancestor-only"))
6455            .unwrap()
6456            .set_len(64 * 1024 * 1024 + 1)
6457            .unwrap();
6458        git::git(&review, &["add", "."]).await.unwrap();
6459        let parent_tree = git::git(&review, &["write-tree"]).await.unwrap();
6460        let parent = git::git(
6461            &review,
6462            &["commit-tree", &parent_tree, "-m", "large ancestor"],
6463        )
6464        .await
6465        .unwrap();
6466        std::fs::remove_file(review.join("ancestor-only")).unwrap();
6467        git::git(&review, &["add", "."]).await.unwrap();
6468        let tree = git::git(&review, &["write-tree"]).await.unwrap();
6469        let head = git::git(
6470            &review,
6471            &[
6472                "commit-tree",
6473                &tree,
6474                "-p",
6475                &parent,
6476                "-m",
6477                "small final tree",
6478            ],
6479        )
6480        .await
6481        .unwrap();
6482        git::git(&review, &["checkout", "--detach", &head])
6483            .await
6484            .unwrap();
6485        let mut report = Report::default();
6486        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6487        assert_eq!(report.evicted_copies, 0, "{report:?}");
6488        assert!(
6489            report
6490                .retained
6491                .iter()
6492                .any(|r| r.contains("expanded object limit exceeded")),
6493            "{report:?}"
6494        );
6495        assert!(review.exists());
6496        assert!(state.candidates[0].worktree.exists());
6497    }
6498
6499    #[tokio::test]
6500    async fn source_eviction_restores_execution_after_gc_and_preserves_generations() {
6501        let f = Fx::new().await;
6502        let state = inactive_source(&f, "ef04", true).await;
6503        let review = reviewer(&f, &state, &f.base).await;
6504        std::fs::write(review.join("ancestor-only"), "ancestral content").unwrap();
6505        git::git(&review, &["add", "."]).await.unwrap();
6506        let parent_tree = git::git(&review, &["write-tree"]).await.unwrap();
6507        let parent = git::git(
6508            &review,
6509            &["commit-tree", &parent_tree, "-m", "unrelated parent"],
6510        )
6511        .await
6512        .unwrap();
6513        std::fs::remove_file(review.join("ancestor-only")).unwrap();
6514        std::fs::write(review.join("source"), "unrelated review checkpoint").unwrap();
6515        git::git(&review, &["add", "."]).await.unwrap();
6516        let tree = git::git(&review, &["write-tree"]).await.unwrap();
6517        let head = git::git(
6518            &review,
6519            &[
6520                "commit-tree",
6521                &tree,
6522                "-p",
6523                &parent,
6524                "-m",
6525                "unrelated review checkpoint",
6526            ],
6527        )
6528        .await
6529        .unwrap();
6530        git::git(&review, &["checkout", "--detach", &head])
6531            .await
6532            .unwrap();
6533        let mut report = Report::default();
6534        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6535        assert_eq!(report.evicted_copies, 1, "{report:?}");
6536        let ledger = f
6537            .home
6538            .join("runs")
6539            .join(&state.id)
6540            .join("artifacts/eviction-review-1.json");
6541        let original = std::fs::read(&ledger).unwrap();
6542        let diff = seat_diff(&f.home, &state.id, &head).await.unwrap();
6543        assert!(String::from_utf8_lossy(&diff).contains("unrelated review checkpoint"));
6544        git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
6545            .await
6546            .unwrap();
6547        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6548        assert!(
6549            !git::git_raw(&f.repo, &["cat-file", "-e", &head])
6550                .await
6551                .unwrap()
6552                .ok()
6553        );
6554        assert!(
6555            !git::git_raw(&f.repo, &["cat-file", "-e", &parent])
6556                .await
6557                .unwrap()
6558                .ok()
6559        );
6560        assert_eq!(seat_diff(&f.home, &state.id, &head).await.unwrap(), diff);
6561        assert!(
6562            seat_heads(&f.home, &state.id)
6563                .await
6564                .unwrap()
6565                .contains_key(&head)
6566        );
6567        restore_execution_seats(&f.home, &state, None)
6568            .await
6569            .unwrap();
6570        assert_eq!(git::rev_parse(&review, "HEAD").await.unwrap(), head);
6571        assert_eq!(
6572            git::git(&review, &["log", "--format=%H"]).await.unwrap(),
6573            format!("{head}\n{parent}")
6574        );
6575        git::git(&f.repo, &["fsck", "--full"]).await.unwrap();
6576        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6577        let inspection = f._temp.path().join("complete-history-inspection");
6578        restore_seat(&f.home, &state.id, &head, &inspection)
6579            .await
6580            .unwrap();
6581        assert_eq!(
6582            git::git(&inspection, &["log", "--format=%H"])
6583                .await
6584                .unwrap(),
6585            format!("{head}\n{parent}")
6586        );
6587        git::git(&inspection, &["fsck", "--full"]).await.unwrap();
6588        git::git(&inspection, &["gc", "--prune=now"]).await.unwrap();
6589
6590        assert_eq!(git::git(&review, &["write-tree"]).await.unwrap(), tree);
6591        assert!(
6592            !git::git_raw(&review, &["symbolic-ref", "-q", "HEAD"])
6593                .await
6594                .unwrap()
6595                .ok()
6596        );
6597        assert_eq!(
6598            std::fs::read_to_string(review.join("source")).unwrap(),
6599            "unrelated review checkpoint"
6600        );
6601        std::fs::write(review.join("operator-notes"), "keep").unwrap();
6602        assert!(
6603            restore_execution_seats(&f.home, &state, None)
6604                .await
6605                .is_err()
6606        );
6607        assert_eq!(
6608            std::fs::read_to_string(review.join("operator-notes")).unwrap(),
6609            "keep"
6610        );
6611        std::fs::remove_file(review.join("operator-notes")).unwrap();
6612        restore_execution_seats(&f.home, &state, None)
6613            .await
6614            .unwrap();
6615        let mut second = Report::default();
6616        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut second).await;
6617        assert_eq!(second.evicted_copies, 1, "{second:?}");
6618        assert_eq!(std::fs::read(&ledger).unwrap(), original);
6619        assert!(ledger.with_file_name("eviction-review-1-2.json").exists());
6620        // A historical v1 fixture has no explicit base field. Neither schema
6621        // may reinterpret its immutable archive when the owning run advances.
6622        let mut legacy: serde_json::Value = serde_json::from_slice(&original).unwrap();
6623        legacy["version"] = 1.into();
6624        legacy.as_object_mut().unwrap().remove("base");
6625        std::fs::write(&ledger, serde_json::to_vec(&legacy).unwrap()).unwrap();
6626        let mut advanced = state.clone();
6627        advanced.base_commit = git::rev_parse(&state.candidates[0].worktree, "HEAD")
6628            .await
6629            .unwrap();
6630        advanced.save_under(&f.home).unwrap();
6631        assert_eq!(seat_diff(&f.home, &state.id, &head).await.unwrap(), diff);
6632        // Corruption blocks execution before a replacement checkout is made.
6633        let raw: serde_json::Value = serde_json::from_slice(&original).unwrap();
6634        let archive = PathBuf::from(raw["evidence"].as_str().unwrap());
6635        let patch = std::fs::read(archive.join("change.patch")).unwrap();
6636        std::fs::write(archive.join("change.patch"), "corrupt").unwrap();
6637        assert!(
6638            restore_execution_seats(&f.home, &state, None)
6639                .await
6640                .is_err()
6641        );
6642        assert!(!review.exists());
6643        std::fs::write(archive.join("change.patch"), patch).unwrap();
6644        std::fs::create_dir(&review).unwrap();
6645        std::fs::write(review.join("operator-notes"), "keep").unwrap();
6646        assert!(
6647            restore_execution_seats(&f.home, &state, None)
6648                .await
6649                .is_err()
6650        );
6651        assert_eq!(
6652            std::fs::read_to_string(review.join("operator-notes")).unwrap(),
6653            "keep"
6654        );
6655    }
6656
6657    #[tokio::test]
6658    async fn source_eviction_preserves_history_and_restores_binary_modes_after_gc() {
6659        use std::os::unix::fs::PermissionsExt;
6660        let mut f = Fx::new().await;
6661        std::fs::write(f.repo.join("binary"), b"old\0binary\xff").unwrap();
6662        git::git(&f.repo, &["add", "."]).await.unwrap();
6663        git::git(&f.repo, &["commit", "-m", "binary base"])
6664            .await
6665            .unwrap();
6666        f.base = git::rev_parse(&f.repo, "HEAD").await.unwrap();
6667        let mut state = inactive_source(&f, "ec01", true).await;
6668        let candidate = state.candidates[0].worktree.clone();
6669        let earlier = git::rev_parse(&candidate, "HEAD").await.unwrap();
6670        historical_review(&mut state, &earlier);
6671        let review = reviewer(&f, &state, &earlier).await;
6672        std::fs::remove_file(candidate.join("source")).unwrap();
6673        std::fs::write(candidate.join("binary"), b"new\0binary\xfe").unwrap();
6674        std::fs::write(candidate.join("script"), "run\n").unwrap();
6675        std::fs::set_permissions(
6676            candidate.join("script"),
6677            std::fs::Permissions::from_mode(0o755),
6678        )
6679        .unwrap();
6680        git::git(&candidate, &["add", "."]).await.unwrap();
6681        git::git(&candidate, &["commit", "-m", "binary deletion and mode"])
6682            .await
6683            .unwrap();
6684        let head = git::rev_parse(&candidate, "HEAD").await.unwrap();
6685        let tree = git::rev_parse(&candidate, "HEAD^{tree}").await.unwrap();
6686        let base_tree = git::rev_parse(&candidate, &format!("{}^{{tree}}", f.base))
6687            .await
6688            .unwrap();
6689        historical_review(&mut state, &head);
6690        historical_review(&mut state, &head);
6691        state.status = RunStatus::Superseded;
6692        state.save_under(&f.home).unwrap();
6693        let task = f.task(std::slice::from_ref(&state));
6694        let before = serde_json::to_value(&state).unwrap();
6695        git::git(&review, &["reset", "--hard", &head])
6696            .await
6697            .unwrap();
6698        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
6699        assert_eq!(report.evicted_copies, 1, "{report:?}");
6700        assert!(!review.exists());
6701        assert!(candidate.exists(), "selected implementation survives");
6702        assert!(report.source_unlinked_logical_bytes > 0);
6703        assert!(report.source_unlinked_allocated_bytes.is_some());
6704        assert!(report.source_evidence_added_allocated_bytes.is_some());
6705        assert_eq!(
6706            serde_json::to_value(RunState::load_under(&state.id, &f.home).unwrap()).unwrap(),
6707            before
6708        );
6709        assert_eq!(
6710            crate::queue::Queue::at(f.home.join("queue"))
6711                .get(&task.id)
6712                .unwrap()
6713                .runs,
6714            task.runs
6715        );
6716        let archive = f
6717            .home
6718            .join("runs")
6719            .join(&state.id)
6720            .join("artifacts/source-evidence")
6721            .join(format!("{head}-{}", f.base));
6722        let patch = source_diff(&archive).await.unwrap();
6723        assert!(String::from_utf8_lossy(&patch).contains("GIT binary patch"));
6724        assert!(String::from_utf8_lossy(&patch).contains("100755"));
6725        assert!(
6726            git::worktree_remove_clean(&f.repo, &candidate)
6727                .await
6728                .unwrap()
6729        );
6730        git::git(&f.repo, &["branch", "-D", &state.candidates[0].branch])
6731            .await
6732            .unwrap();
6733        git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
6734            .await
6735            .unwrap();
6736        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6737        assert!(
6738            !git::git_raw(&f.repo, &["cat-file", "-e", &head])
6739                .await
6740                .unwrap()
6741                .ok()
6742        );
6743        // Even the remaining base repository is unavailable to the reader.
6744        std::fs::remove_dir_all(&f.repo).unwrap();
6745        assert_eq!(source_diff(&archive).await.unwrap(), patch);
6746        let restored = f._temp.path().join("restored");
6747        restore_source(&archive, &restored).await.unwrap();
6748        assert_eq!(git::git(&restored, &["write-tree"]).await.unwrap(), tree);
6749        assert_eq!(
6750            std::fs::read(restored.join("binary")).unwrap(),
6751            b"new\0binary\xfe"
6752        );
6753        assert!(!restored.join("source").exists());
6754        assert_ne!(
6755            std::fs::metadata(restored.join("script"))
6756                .unwrap()
6757                .permissions()
6758                .mode()
6759                & 0o111,
6760            0
6761        );
6762        assert!(restore_source(&archive, &restored).await.is_err());
6763        // Reconstruct from the archived base plus the displayed binary patch,
6764        // rather than relying only on checking out the archived final tree.
6765        git::git(&restored, &["read-tree", "--reset", "-u", &base_tree])
6766            .await
6767            .unwrap();
6768        let patch_file = f._temp.path().join("saved.patch");
6769        std::fs::write(&patch_file, &patch).unwrap();
6770        git::git(
6771            &restored,
6772            &["apply", "--index", "--binary", patch_file.to_str().unwrap()],
6773        )
6774        .await
6775        .unwrap();
6776        assert_eq!(git::git(&restored, &["write-tree"]).await.unwrap(), tree);
6777        assert_eq!(
6778            std::fs::read(restored.join("binary")).unwrap(),
6779            b"new\0binary\xfe"
6780        );
6781    }
6782
6783    #[tokio::test]
6784    async fn source_eviction_archives_unrelated_tips_and_allows_lineage_references() {
6785        let f = Fx::new().await;
6786        let state = inactive_source(&f, "ec10", true).await;
6787        let review = reviewer(&f, &state, &f.base).await;
6788        let mut successor = inactive_source(&f, "ec11", true).await;
6789        successor.retired_to = Some(state.id.clone());
6790        successor.save_under(&f.home).unwrap();
6791        f.task(&[state.clone(), successor]);
6792
6793        let mut tips = Vec::new();
6794        for contents in ["reflog-only evidence", "ORIG_HEAD-only evidence"] {
6795            std::fs::write(review.join("source"), contents).unwrap();
6796            git::git(&review, &["add", "."]).await.unwrap();
6797            let tree = git::git(&review, &["write-tree"]).await.unwrap();
6798            let tip = git::git(
6799                &review,
6800                &["commit-tree", &tree, "-p", &f.base, "-m", contents],
6801            )
6802            .await
6803            .unwrap();
6804            git::git(&review, &["reset", "--hard", &tip]).await.unwrap();
6805            tips.push(tip);
6806            git::git(&review, &["reset", "--hard", &f.base])
6807                .await
6808                .unwrap();
6809        }
6810        // Keep one tip exclusively in ORIG_HEAD, the other in the HEAD log.
6811        git::git(&review, &["reflog", "delete", "--rewrite", "HEAD@{1}"])
6812            .await
6813            .unwrap();
6814        git::git(&review, &["update-ref", "ORIG_HEAD", &tips[1]])
6815            .await
6816            .unwrap();
6817        let mut report = Report::default();
6818        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
6819        assert_eq!(report.evicted_copies, 1, "{report:?}");
6820        assert!(!review.exists());
6821        git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
6822            .await
6823            .unwrap();
6824        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
6825        for tip in &tips {
6826            assert!(
6827                !git::git_raw(&f.repo, &["cat-file", "-e", tip])
6828                    .await
6829                    .unwrap()
6830                    .ok()
6831            );
6832        }
6833        // The run-oriented interface also works without the source object store.
6834        std::fs::remove_dir_all(&f.repo).unwrap();
6835        let shown = seat_evidence(&f.home, &state.id).await.unwrap();
6836        for (i, tip) in tips.iter().enumerate() {
6837            assert!(
6838                shown
6839                    .iter()
6840                    .any(|row| row.contains(tip) && row.contains("patch_bytes="))
6841            );
6842            let destination = f._temp.path().join(format!("restore-history-{i}"));
6843            restore_seat(&f.home, &state.id, tip, &destination)
6844                .await
6845                .unwrap();
6846            assert_eq!(
6847                std::fs::read_to_string(destination.join("source")).unwrap(),
6848                ["reflog-only evidence", "ORIG_HEAD-only evidence"][i]
6849            );
6850        }
6851        assert!(
6852            restore_seat(
6853                &f.home,
6854                &state.id,
6855                "unknown",
6856                &f._temp.path().join("missing")
6857            )
6858            .await
6859            .is_err()
6860        );
6861    }
6862
6863    #[tokio::test]
6864    async fn source_eviction_revalidates_archive_immediately_before_unlink() {
6865        fn corrupt(path: &Path) -> Result<()> {
6866            let root = path.parent().unwrap();
6867            // Locate the fixture's durable artifact store through its run record
6868            // path supplied below by a test-only hook in the artifact tree.
6869            let marker = root.join("archive-to-corrupt");
6870            let archive = std::fs::read_to_string(&marker)?;
6871            std::fs::write(Path::new(&archive).join("change.patch"), "corrupt")?;
6872            Ok(())
6873        }
6874        let f = Fx::new().await;
6875        let state = inactive_source(&f, "ec12", true).await;
6876        let review = reviewer(&f, &state, &f.base).await;
6877        let archive = f
6878            .home
6879            .join("runs")
6880            .join(&state.id)
6881            .join("artifacts/source-evidence")
6882            .join(format!("{}-{}", f.base, f.base));
6883        std::fs::write(
6884            state.worktree_root().join("archive-to-corrupt"),
6885            archive.to_str().unwrap(),
6886        )
6887        .unwrap();
6888        let mut report = Report::default();
6889        copies::evict_with(&f.home, &Fx::disk(), Fx::now(), &mut report, corrupt).await;
6890        assert_eq!(report.evicted_copies, 0, "{report:?}");
6891        assert!(review.exists());
6892        assert!(
6893            report
6894                .retained
6895                .iter()
6896                .any(|r| r.contains("corrupt snapshot")),
6897            "{report:?}"
6898        );
6899    }
6900
6901    #[tokio::test]
6902    async fn source_eviction_fails_closed_for_dirty_ignored_borrowed_and_authoritative_copies() {
6903        for kind in [
6904            "dirty",
6905            "hidden",
6906            "ignored",
6907            "empty-directory",
6908            "untracked",
6909            "borrowed",
6910            "borrowed-symlink",
6911            "lease",
6912            "owner",
6913            "driver",
6914            "task-pin",
6915            "task-replacement",
6916            "malformed-orig-head",
6917            "grace",
6918            "resumable",
6919            "archive-symlink",
6920            "root-symlink",
6921            "checkpoint",
6922            "symlink",
6923            "retained",
6924            "unreadable",
6925            "unknown-field",
6926            "unknown-task-field",
6927        ] {
6928            let f = Fx::new().await;
6929            let mut state = inactive_source(&f, "ec02", true).await;
6930            let head = git::rev_parse(&state.candidates[0].worktree, "HEAD")
6931                .await
6932                .unwrap();
6933            historical_review(&mut state, &head);
6934            let review = reviewer(&f, &state, &head).await;
6935            let mut output = None;
6936            let mut owner = None;
6937            let mut driver = None;
6938            let mut disk = Fx::disk();
6939            match kind {
6940                "dirty" => std::fs::write(review.join("source"), "notes").unwrap(),
6941                "hidden" => {
6942                    git::git(&review, &["update-index", "--assume-unchanged", "source"])
6943                        .await
6944                        .unwrap();
6945                    std::fs::write(review.join("source"), "notes").unwrap();
6946                }
6947                "ignored" => {
6948                    std::fs::create_dir(review.join("scratch")).unwrap();
6949                    std::fs::write(review.join("scratch/notes"), "notes").unwrap();
6950                }
6951                "empty-directory" => std::fs::create_dir(review.join("owner-notes")).unwrap(),
6952                "untracked" => std::fs::write(review.join("notes"), "notes").unwrap(),
6953                "borrowed" => {
6954                    let mut other = f.run("ec03", true).await;
6955                    other.candidates[0].worktree = review.clone();
6956                    other.save_under(&f.home).unwrap();
6957                }
6958                "borrowed-symlink" => {
6959                    let alias = f._temp.path().join("borrowed-alias");
6960                    std::os::unix::fs::symlink(&review, &alias).unwrap();
6961                    let mut other = f.run("ec03", true).await;
6962                    other.candidates[0].worktree = alias;
6963                    other.save_under(&f.home).unwrap();
6964                }
6965                "lease" => output = OutputLease::borrow(&review).unwrap(),
6966                "owner" => owner = Some(crate::pr_head::owner_lock(&f.home, &state.id).unwrap()),
6967                "driver" => driver = Some(crate::driver::maintenance(&f.home, &state.id).unwrap()),
6968                "task-pin" => {
6969                    let mut task = f.task(std::slice::from_ref(&state));
6970                    task.resume_override = Some(crate::queue::OperatorResume {
6971                        question_id: "fixture-pin".into(),
6972                        at: Fx::now(),
6973                        conductor_rehold: None,
6974                        forced: true,
6975                        pinned_run: Some(state.id.clone()),
6976                    });
6977                    crate::queue::Queue::at(f.home.join("queue"))
6978                        .put(&mut task)
6979                        .unwrap();
6980                }
6981                "task-replacement" => {
6982                    let mut task = f.task(std::slice::from_ref(&state));
6983                    task.replacement = Some(crate::merge_decision::Replacement {
6984                        question: "fixture-replacement".into(),
6985                        run: state.id.clone(),
6986                        pr: "https://example.invalid/pull/1".into(),
6987                        agent: "worker".into(),
6988                        context: String::new(),
6989                    });
6990                    crate::queue::Queue::at(f.home.join("queue"))
6991                        .put(&mut task)
6992                        .unwrap();
6993                }
6994                "malformed-orig-head" => {
6995                    let admin = git::git(&review, &["rev-parse", "--absolute-git-dir"])
6996                        .await
6997                        .unwrap();
6998                    std::fs::write(Path::new(&admin).join("ORIG_HEAD"), "not-an-object-id")
6999                        .unwrap();
7000                }
7001                "grace" => disk.fold_grace_secs = 3600,
7002                "resumable" => state.status = RunStatus::Blocked,
7003                "archive-symlink" => {
7004                    let artifacts = f.home.join("runs").join(&state.id).join("artifacts");
7005                    std::fs::create_dir_all(&artifacts).unwrap();
7006                    let outside = f._temp.path().join("outside");
7007                    std::fs::create_dir(&outside).unwrap();
7008                    std::os::unix::fs::symlink(&outside, artifacts.join("source-evidence"))
7009                        .unwrap();
7010                }
7011                "root-symlink" => {
7012                    let root = state.worktree_root();
7013                    let outside = f._temp.path().join("outside-root");
7014                    std::fs::rename(&root, &outside).unwrap();
7015                    std::os::unix::fs::symlink(&outside, &root).unwrap();
7016                }
7017                "checkpoint" => {
7018                    let admin = git::git(&review, &["rev-parse", "--absolute-git-dir"])
7019                        .await
7020                        .unwrap();
7021                    std::fs::write(Path::new(&admin).join("MERGE_MSG"), "checkpoint").unwrap();
7022                }
7023                "symlink" => {
7024                    std::fs::remove_file(review.join("source")).unwrap();
7025                    std::os::unix::fs::symlink(".gitignore", review.join("source")).unwrap();
7026                }
7027                "retained" => std::fs::write(
7028                    f.home
7029                        .join("runs")
7030                        .join(&state.id)
7031                        .join("retain-recovery-sources"),
7032                    "owner",
7033                )
7034                .unwrap(),
7035                "unreadable" => {
7036                    std::fs::create_dir_all(f.home.join("runs/20260101-000000-ffff")).unwrap();
7037                }
7038                "unknown-field" | "unknown-task-field" => {}
7039                _ => unreachable!(),
7040            }
7041            state.save_under(&f.home).unwrap();
7042            if kind == "unknown-field" {
7043                let path = f.home.join("runs").join(&state.id).join("run.json");
7044                let mut raw: serde_json::Value =
7045                    serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
7046                raw["future_source_owner"] = serde_json::json!({"path": review});
7047                std::fs::write(&path, serde_json::to_vec(&raw).unwrap()).unwrap();
7048            }
7049            if kind == "unknown-task-field" {
7050                let task = f.task(std::slice::from_ref(&state));
7051                let path = crate::queue::Queue::at(f.home.join("queue")).path_of(&task.id);
7052                let mut raw: serde_json::Value =
7053                    serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
7054                raw["future_source_owner"] = serde_json::json!({"path": review});
7055                std::fs::write(&path, serde_json::to_vec(&raw).unwrap()).unwrap();
7056            }
7057            let mut report = Report::default();
7058            copies::evict(&f.home, &disk, Fx::now(), &mut report).await;
7059            assert_eq!(report.evicted_copies, 0, "{kind}: {report:?}");
7060            assert!(review.exists(), "{kind}: {report:?}");
7061            assert!(!report.retained.is_empty(), "{kind}: {report:?}");
7062            drop(output);
7063            drop(owner);
7064            drop(driver);
7065        }
7066    }
7067
7068    #[tokio::test]
7069    async fn source_eviction_reconciles_interruption_and_refuses_corrupt_archives() {
7070        let f = Fx::new().await;
7071        let state = inactive_source(&f, "ec04", true).await;
7072        let review = reviewer(&f, &state, &f.base).await;
7073        let mut report = Report::default();
7074        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7075        assert_eq!(report.evicted_copies, 1, "{report:?}");
7076        let artifacts = f.home.join("runs").join(&state.id).join("artifacts");
7077        let ledger = artifacts.join("eviction-review-1.json");
7078        let mut record: serde_json::Value =
7079            serde_json::from_slice(&std::fs::read(&ledger).unwrap()).unwrap();
7080        record["phase"] = "pending".into();
7081        std::fs::write(&ledger, serde_json::to_vec(&record).unwrap()).unwrap();
7082        let archive = PathBuf::from(record["evidence"].as_str().unwrap());
7083        let pack = std::fs::read(archive.join("objects.pack")).unwrap();
7084        std::fs::write(archive.join("objects.pack"), b"corrupt").unwrap();
7085        let mut blocked = Report::default();
7086        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut blocked).await;
7087        assert!(
7088            blocked
7089                .retained
7090                .iter()
7091                .any(|r| r.contains("corrupt snapshot")),
7092            "{blocked:?}"
7093        );
7094        assert_eq!(
7095            serde_json::from_slice::<serde_json::Value>(&std::fs::read(&ledger).unwrap()).unwrap()
7096                ["phase"],
7097            "pending"
7098        );
7099        assert!(
7100            restore_source(&archive, &f._temp.path().join("bad-restore"))
7101                .await
7102                .is_err()
7103        );
7104        std::fs::write(archive.join("objects.pack"), &pack).unwrap();
7105        let mut retried = Report::default();
7106        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut retried).await;
7107        assert_eq!(
7108            serde_json::from_slice::<serde_json::Value>(&std::fs::read(&ledger).unwrap()).unwrap()
7109                ["phase"],
7110            "evicted"
7111        );
7112        assert_eq!(retried.evicted_copies, 0);
7113        assert!(!review.exists());
7114        // A stopped archive publisher can resume its immutable staging files.
7115        let pending = archive.with_extension("pending");
7116        std::fs::rename(&archive, &pending).unwrap();
7117        assert_eq!(
7118            crate::fold_evidence::snapshot(&state, &f.home, &f.base, 64 * 1024 * 1024)
7119                .await
7120                .unwrap(),
7121            archive
7122        );
7123        assert!(!pending.exists());
7124    }
7125
7126    #[tokio::test]
7127    async fn source_eviction_reclaims_superseded_empty_attempt_without_retiring_lineage() {
7128        let f = Fx::new().await;
7129        let mut empty = inactive_source(&f, "ec05", false).await;
7130        historical_review(&mut empty, &f.base);
7131        empty.status = RunStatus::Superseded;
7132        empty.save_under(&f.home).unwrap();
7133        let source = inactive_source(&f, "ec06", true).await;
7134        let task = f.task(&[empty.clone(), source.clone()]);
7135        let before = serde_json::to_value(&empty).unwrap();
7136        let mut report = Report::default();
7137        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7138        assert_eq!(report.evicted_copies, 1, "{report:?}");
7139        assert!(!empty.candidates[0].worktree.exists());
7140        assert!(source.candidates[0].worktree.exists());
7141        assert!(
7142            git::branch_exists(&f.repo, &empty.candidates[0].branch)
7143                .await
7144                .unwrap()
7145        );
7146        assert_eq!(
7147            serde_json::to_value(RunState::load_under(&empty.id, &f.home).unwrap()).unwrap(),
7148            before
7149        );
7150        let mut retry = Report::default();
7151        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut retry).await;
7152        assert_eq!(retry.removed_empty_roots, 1, "{retry:?}");
7153        assert!(!empty.worktree_root().exists());
7154        assert_eq!(
7155            crate::queue::Queue::at(f.home.join("queue"))
7156                .get(&task.id)
7157                .unwrap()
7158                .runs,
7159            task.runs
7160        );
7161    }
7162    #[tokio::test]
7163    async fn source_eviction_retries_pending_intent_and_exact_missing_registration() {
7164        fn interrupt(_: &Path) -> Result<()> {
7165            anyhow::bail!("fixture interruption before unlink")
7166        }
7167        fn vanish(path: &Path) -> Result<()> {
7168            std::fs::remove_dir_all(path)?;
7169            anyhow::bail!("fixture interruption after checkout unlink")
7170        }
7171        for stage in [
7172            "intent",
7173            "missing-registration",
7174            "changed-admin",
7175            "missing-archive",
7176            "wrong-identity",
7177        ] {
7178            let f = Fx::new().await;
7179            let state = inactive_source(&f, "ec07", true).await;
7180            let review = reviewer(&f, &state, &f.base).await;
7181            let admin = PathBuf::from(
7182                git::git(&review, &["rev-parse", "--absolute-git-dir"])
7183                    .await
7184                    .unwrap(),
7185            );
7186            let mut interrupted = Report::default();
7187            copies::evict_with(
7188                &f.home,
7189                &Fx::disk(),
7190                Fx::now(),
7191                &mut interrupted,
7192                if stage == "missing-registration" || stage == "changed-admin" {
7193                    vanish
7194                } else {
7195                    interrupt
7196                },
7197            )
7198            .await;
7199            assert_eq!(interrupted.evicted_copies, 0, "{stage}: {interrupted:?}");
7200            let ledger = f
7201                .home
7202                .join("runs")
7203                .join(&state.id)
7204                .join("artifacts/eviction-review-1.json");
7205            let record: serde_json::Value =
7206                serde_json::from_slice(&std::fs::read(&ledger).unwrap_or_else(|error| {
7207                    panic!("{stage}: missing pending ledger: {error}; {interrupted:?}")
7208                }))
7209                .unwrap();
7210            assert_eq!(record["phase"], "pending");
7211            if stage == "changed-admin" {
7212                std::fs::write(admin.join("owner-note"), "keep").unwrap();
7213            }
7214            if stage == "missing-archive" {
7215                std::fs::remove_file(
7216                    Path::new(record["evidence"].as_str().unwrap()).join("objects.pack"),
7217                )
7218                .unwrap();
7219            }
7220            if stage == "wrong-identity" {
7221                let head = git::rev_parse(&state.candidates[0].worktree, "HEAD")
7222                    .await
7223                    .unwrap();
7224                let other =
7225                    crate::fold_evidence::snapshot(&state, &f.home, &head, 64 * 1024 * 1024)
7226                        .await
7227                        .unwrap();
7228                let original = Path::new(record["evidence"].as_str().unwrap());
7229                for name in [
7230                    "manifest.json",
7231                    "objects.pack",
7232                    "change.patch",
7233                    "change.index",
7234                ] {
7235                    std::fs::copy(other.join(name), original.join(name)).unwrap();
7236                }
7237            }
7238            let mut retried = Report::default();
7239            copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut retried).await;
7240            let phase =
7241                serde_json::from_slice::<serde_json::Value>(&std::fs::read(&ledger).unwrap())
7242                    .unwrap()["phase"]
7243                    .clone();
7244            if stage == "changed-admin" || stage == "missing-archive" || stage == "wrong-identity" {
7245                assert_eq!(phase, "pending", "{stage}: {retried:?}");
7246                assert!(!retried.retained.is_empty());
7247                if stage == "changed-admin" {
7248                    assert!(admin.join("owner-note").exists());
7249                } else {
7250                    assert!(review.exists());
7251                }
7252            } else {
7253                assert_eq!(phase, "evicted", "{stage}: {retried:?}");
7254                assert!(!review.exists());
7255                assert!(!admin.exists());
7256            }
7257        }
7258    }
7259    fn source_census(home: &Path) -> serde_json::Value {
7260        serde_json::from_slice(&std::fs::read(home.join("source-eviction-cursor")).unwrap())
7261            .unwrap()
7262    }
7263
7264    #[tokio::test]
7265    async fn source_eviction_scan_bounds_missing_root_checkpoints_and_eventually_reclaims() {
7266        let f = Fx::new().await;
7267        let state = inactive_source(&f, "ffff", true).await;
7268        let review = reviewer(&f, &state, &f.base).await;
7269        for i in 0..130 {
7270            let mut old = state.clone();
7271            old.id = format!("20260101-000000-{i:04x}");
7272            old.candidates.clear();
7273            old.save_under(&f.home).unwrap();
7274            // Missing roots with ledger records must still be inspected.
7275            if i == 0 {
7276                let artifacts = f.home.join("runs").join(&old.id).join("artifacts");
7277                std::fs::create_dir_all(&artifacts).unwrap();
7278                std::fs::write(artifacts.join("eviction-review-1.json"), "{}").unwrap();
7279            }
7280        }
7281        // Each invocation reloads the durable cursor. The corrupt ledger uses
7282        // one normal inspection slot; the remaining missing roots use a
7283        // separate 64-entry skip budget, bounding full-census checkpoint writes.
7284        // Repeat through wrap so idle sweeps cannot reintroduce an unbounded pass.
7285        for cycle in 1..=2 {
7286            for (pass, expected_next) in [65, 129, 131].into_iter().enumerate() {
7287                let mut report = Report::default();
7288                copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7289                assert!(report.failures.is_empty(), "{report:?}");
7290                assert_eq!(report.evicted_copies, usize::from(cycle == 1 && pass == 2));
7291                assert_eq!(review.exists(), cycle == 1 && pass < 2);
7292                let census = source_census(&f.home);
7293                assert_eq!(census["current"]["next"], expected_next);
7294                assert_eq!(census["current"]["completed_at"].is_null(), pass < 2);
7295                assert_eq!(census["current"]["number"], cycle);
7296                assert_eq!(
7297                    census["current"]["runs"]["20260101-000000-0000"]["root"]["outcome"],
7298                    "error"
7299                );
7300                assert_eq!(
7301                    census["current"]["runs"]["20260101-000000-0001"]["root"]["detail"],
7302                    "root absent and no eviction records; nothing to reclaim"
7303                );
7304                if pass < 2 {
7305                    let next_id = format!("20260101-000000-{expected_next:04x}");
7306                    assert_eq!(
7307                        census["current"]["runs"][next_id]["root"]["outcome"],
7308                        "not-yet-inspected"
7309                    );
7310                }
7311            }
7312        }
7313    }
7314
7315    #[tokio::test]
7316    async fn source_eviction_scan_reaches_old_seats_despite_empty_roots_and_timestamp_churn() {
7317        let f = Fx::new().await;
7318        let mut state = inactive_source(&f, "ffff", true).await;
7319        let review = reviewer(&f, &state, &f.base).await;
7320        // Empty checkout roots still need ownership checks and consume a
7321        // discovery slot; mutable timestamp ordering must not move the cursor.
7322        let mut history = Vec::new();
7323        for i in 0..130 {
7324            let mut old = state.clone();
7325            old.id = format!("20260101-000000-{i:04x}");
7326            old.candidates.clear();
7327            old.save_under(&f.home).unwrap();
7328            std::fs::create_dir_all(old.worktree_root()).unwrap();
7329            history.push(old);
7330        }
7331        state
7332            .save_under_at(
7333                &f.home,
7334                Timestamp::now() + jiff::SignedDuration::from_secs(10),
7335            )
7336            .unwrap();
7337        for pass in 0..3 {
7338            let mut report = Report::default();
7339            copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7340            assert!(report.failures.is_empty(), "{report:?}");
7341            let census = source_census(&f.home);
7342            assert_eq!(
7343                census["current"]["next"].as_u64().unwrap(),
7344                ((pass + 1) * 64).min(131)
7345            );
7346            if pass < 2 {
7347                assert!(review.exists());
7348                assert!(census["current"]["completed_at"].is_null());
7349                assert_eq!(
7350                    census["current"]["runs"][&state.id]["root"]["outcome"],
7351                    "not-yet-inspected"
7352                );
7353            }
7354            // Reorder the records on disk, including the cursor's former ID.
7355            // Loading a fresh scan on the next invocation models a restart.
7356            for old in history.iter_mut().take(64) {
7357                old.updated_at = Timestamp::now();
7358                old.save_under(&f.home).unwrap();
7359            }
7360            if pass == 1 {
7361                // Reproduce the old cursor's non-progress: moving its timestamp
7362                // before already visited records makes its next 64 slots revisit
7363                // those roots, excluding the eligible tail again. Repeating this
7364                // bookkeeping permutation can keep the tail out indefinitely.
7365                // Anchor the permutation to the saved tail, so a slow scan
7366                // cannot move these records past it as wall-clock time advances.
7367                let older = state.updated_at - jiff::SignedDuration::from_secs(100);
7368                for old in history.iter_mut().take(128) {
7369                    if f.home.join("runs").join(&old.id).exists() {
7370                        old.save_under_at(&f.home, older).unwrap();
7371                    }
7372                }
7373                history[127]
7374                    .save_under_at(&f.home, older - jiff::SignedDuration::from_secs(100))
7375                    .unwrap();
7376                let mut legacy: Vec<_> = history
7377                    .iter()
7378                    .filter(|r| f.home.join("runs").join(&r.id).exists())
7379                    .cloned()
7380                    .collect();
7381                legacy.push(state.clone());
7382                legacy.sort_by_key(|r| r.updated_at);
7383                let index = legacy.iter().position(|r| r.id == history[127].id).unwrap();
7384                let len = legacy.len();
7385                legacy.rotate_left((index + 1) % len);
7386                assert!(legacy.iter().take(64).all(|r| r.id != state.id));
7387            }
7388            if pass == 0 {
7389                std::fs::remove_dir_all(f.home.join("runs").join(&history[64].id)).unwrap();
7390                let mut added = state.clone();
7391                added.id = "20260101-000000-fffe".into();
7392                added.candidates.clear();
7393                added.save_under(&f.home).unwrap();
7394            }
7395        }
7396        assert!(!review.exists());
7397        let census = source_census(&f.home);
7398        assert!(!census["current"]["completed_at"].is_null());
7399        assert_eq!(
7400            census["current"]["runs"][&state.id]["seats"]["review-1"]["outcome"],
7401            "evicted"
7402        );
7403        assert_eq!(
7404            census["current"]["runs"][&history[64].id]["root"]["outcome"],
7405            "error"
7406        );
7407        let mut next = Report::default();
7408        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut next).await;
7409        let wrapped = source_census(&f.home);
7410        assert_eq!(wrapped["current"]["number"], 2);
7411        assert_eq!(wrapped["previous"], census["current"]);
7412        assert!(
7413            wrapped["current"]["runs"]
7414                .get("20260101-000000-fffe")
7415                .is_some()
7416        );
7417    }
7418
7419    #[tokio::test]
7420    async fn source_eviction_scan_resumes_within_run_and_bounds_failed_seats() {
7421        fn fail_one(path: &Path) -> Result<()> {
7422            ensure!(
7423                path.file_name().unwrap() != "review-2",
7424                "injected checkpoint failure"
7425            );
7426            Ok(())
7427        }
7428        let f = Fx::new().await;
7429        let state = inactive_source(&f, "ef20", true).await;
7430        let mut paths = Vec::new();
7431        for i in 1..=8 {
7432            let path = state.worktree_root().join(format!("review-{i}"));
7433            git::worktree_add_detached(&f.repo, &path, &f.base)
7434                .await
7435                .unwrap();
7436            paths.push(path);
7437        }
7438        std::fs::write(paths[2].join("owner-data"), "retain me").unwrap();
7439        let mut first = Report::default();
7440        copies::evict_with(&f.home, &Fx::disk(), Fx::now(), &mut first, fail_one).await;
7441        assert_eq!(first.evicted_copies, 3, "{first:?}");
7442        let census = source_census(&f.home);
7443        let seats = &census["current"]["runs"][&state.id]["seats"];
7444        assert_eq!(census["current"]["after_seat"], "review-5");
7445        assert_eq!(seats["review-2"]["outcome"], "error");
7446        assert_eq!(seats["review-2"]["stage"], "unlink");
7447        assert_eq!(seats["review-3"]["outcome"], "protected");
7448        assert_eq!(seats["review-6"]["outcome"], "not-yet-inspected");
7449        assert!(first.source_unlinked_logical_bytes > 0);
7450        assert!(first.source_evidence_added_logical_bytes > 0);
7451        let mut second = Report::default();
7452        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut second).await;
7453        assert_eq!(second.evicted_copies, 3, "{second:?}");
7454        assert!(paths[1].exists(), "failed seat waits until next cycle");
7455        assert!(paths[2].exists());
7456        assert!(!source_census(&f.home)["current"]["completed_at"].is_null());
7457        let mut third = Report::default();
7458        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut third).await;
7459        assert_eq!(third.evicted_copies, 1, "{third:?}");
7460        assert!(!paths[1].exists());
7461        assert_eq!(
7462            std::fs::read_to_string(paths[2].join("owner-data")).unwrap(),
7463            "retain me"
7464        );
7465        let shown = seat_inspections(&f.home, &state.id).unwrap().join("\n");
7466        assert!(
7467            shown.contains("cycle=1 complete=true review-2 error stage=unlink"),
7468            "{shown}"
7469        );
7470        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
7471        let destination = f.bay.join("restored-scan-seat");
7472        restore_seat(&f.home, &state.id, &f.base, &destination)
7473            .await
7474            .unwrap();
7475        assert_eq!(git::rev_parse(&destination, "HEAD").await.unwrap(), f.base);
7476    }
7477
7478    #[tokio::test]
7479    async fn source_eviction_scan_continues_after_archive_failure_and_busy_output() {
7480        let f = Fx::new().await;
7481        let failed = inactive_source(&f, "ef30", true).await;
7482        let failed_seat = reviewer(&f, &failed, &f.base).await;
7483        let evidence = f
7484            .home
7485            .join("runs")
7486            .join(&failed.id)
7487            .join("artifacts/source-evidence");
7488        std::fs::create_dir_all(&evidence).unwrap();
7489        std::fs::File::create(evidence.join("reserved-evidence"))
7490            .unwrap()
7491            .set_len(64 * 1024 * 1024)
7492            .unwrap();
7493        let state = inactive_source(&f, "ef31", true).await;
7494        let busy = reviewer(&f, &state, &f.base).await;
7495        let available = state.worktree_root().join("review-2");
7496        git::worktree_add_detached(&f.repo, &available, &f.base)
7497            .await
7498            .unwrap();
7499        let output = OutputLease::take(&busy, true).unwrap();
7500        let mut report = Report::default();
7501        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7502        assert_eq!(report.evicted_copies, 1, "{report:?}");
7503        assert!(failed_seat.exists());
7504        assert!(busy.exists());
7505        assert!(!available.exists());
7506        let census = source_census(&f.home);
7507        assert!(!census["current"]["completed_at"].is_null());
7508        assert_eq!(
7509            census["current"]["runs"][&failed.id]["seats"]["review-1"]["outcome"],
7510            "error"
7511        );
7512        assert_eq!(
7513            census["current"]["runs"][&state.id]["seats"]["review-1"]["outcome"],
7514            "protected"
7515        );
7516        drop(output);
7517        let mut retry = Report::default();
7518        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut retry).await;
7519        assert_eq!(retry.evicted_copies, 1, "{retry:?}");
7520        assert!(!busy.exists());
7521        assert!(failed_seat.exists());
7522    }
7523
7524    #[tokio::test]
7525    async fn source_eviction_scan_checkpoint_failure_stops_before_later_seats() {
7526        fn block_checkpoint(path: &Path) -> Result<()> {
7527            let home = path
7528                .parent()
7529                .unwrap()
7530                .parent()
7531                .unwrap()
7532                .parent()
7533                .unwrap()
7534                .join("home");
7535            let cursor = home.join("source-eviction-cursor");
7536            std::fs::rename(&cursor, home.join("saved-cursor"))?;
7537            std::fs::create_dir(&cursor)?;
7538            Ok(())
7539        }
7540        let f = Fx::new().await;
7541        let state = inactive_source(&f, "ef32", true).await;
7542        let first = reviewer(&f, &state, &f.base).await;
7543        let second = state.worktree_root().join("review-2");
7544        git::worktree_add_detached(&f.repo, &second, &f.base)
7545            .await
7546            .unwrap();
7547        let mut report = Report::default();
7548        copies::evict_with(
7549            &f.home,
7550            &Fx::disk(),
7551            Fx::now(),
7552            &mut report,
7553            block_checkpoint,
7554        )
7555        .await;
7556        assert_eq!(report.evicted_copies, 1, "{report:?}");
7557        assert!(!first.exists());
7558        assert!(second.exists());
7559        assert!(
7560            report
7561                .failures
7562                .iter()
7563                .any(|e| e.contains("persist source scan census"))
7564        );
7565        assert_eq!(report.source_scan.as_ref().unwrap()["outcome"], "error");
7566        std::fs::remove_dir(f.home.join("source-eviction-cursor")).unwrap();
7567        std::fs::rename(
7568            f.home.join("saved-cursor"),
7569            f.home.join("source-eviction-cursor"),
7570        )
7571        .unwrap();
7572        let mut retry = Report::default();
7573        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut retry).await;
7574        assert_eq!(retry.evicted_copies, 1, "{retry:?}");
7575        assert!(!second.exists());
7576    }
7577
7578    #[tokio::test]
7579    async fn source_eviction_scan_reports_invalid_cursor_and_global_ownership() {
7580        let f = Fx::new().await;
7581        let state = inactive_source(&f, "ef21", true).await;
7582        let review = reviewer(&f, &state, &f.base).await;
7583        let cursor = f.home.join("source-eviction-cursor");
7584        std::fs::write(&cursor, "broken cursor").unwrap();
7585        let mut report = Report::default();
7586        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7587        assert_eq!(std::fs::read_to_string(&cursor).unwrap(), "broken cursor");
7588        assert_eq!(report.source_scan.as_ref().unwrap()["outcome"], "error");
7589        assert!(review.exists());
7590        // Migrate a valid legacy cursor even if its target no longer exists.
7591        std::fs::write(&cursor, "20260101-000000-abcd").unwrap();
7592        let mut disabled = Fx::disk();
7593        disabled.auto_fold = false;
7594        let mut report = Report::default();
7595        copies::evict(&f.home, &disabled, Fx::now(), &mut report).await;
7596        assert_eq!(report.source_scan.as_ref().unwrap()["outcome"], "disabled");
7597        let record = f.home.join("runs").join(&state.id).join("run.json");
7598        let original = std::fs::read(&record).unwrap();
7599        std::fs::write(&record, "invalid ownership").unwrap();
7600        let mut report = Report::default();
7601        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7602        assert!(
7603            report
7604                .failures
7605                .iter()
7606                .any(|e| e.contains("global run ownership validation"))
7607        );
7608        assert!(review.exists());
7609        std::fs::write(record, original).unwrap();
7610        let mut report = Report::default();
7611        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7612        assert_eq!(report.evicted_copies, 1, "{report:?}");
7613        assert_eq!(source_census(&f.home)["version"], 1);
7614    }
7615
7616    #[tokio::test]
7617    async fn source_eviction_batches_reproducible_seats_without_dropping_task_history() {
7618        let f = Fx::new().await;
7619        let mut runs = Vec::new();
7620        let mut paths = Vec::new();
7621        for tag in ["ec10", "ec11", "ec12", "ec13"] {
7622            let state = inactive_source(&f, tag, true).await;
7623            for name in ["judge-1", "advisor-1"] {
7624                let path = state.worktree_root().join(name);
7625                git::worktree_add_detached(&f.repo, &path, &f.base)
7626                    .await
7627                    .unwrap();
7628                paths.push(path);
7629            }
7630            runs.push(state);
7631        }
7632        let task = f.task(&runs);
7633        let mut report = Report::default();
7634        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7635        assert_eq!(report.evicted_copies, 5, "{report:?}");
7636        let mut next = Report::default();
7637        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut next).await;
7638        assert_eq!(next.evicted_copies, 3, "{next:?}");
7639        assert!(paths.iter().all(|p| !p.exists()));
7640        assert!(runs.iter().all(|r| r.candidates[0].worktree.exists()));
7641        assert_eq!(
7642            crate::queue::Queue::at(f.home.join("queue"))
7643                .get(&task.id)
7644                .unwrap()
7645                .runs,
7646            task.runs
7647        );
7648        let limited = Fx::new().await;
7649        let state = inactive_source(&limited, "ec15", true).await;
7650        let copy = reviewer(&limited, &state, &limited.base).await;
7651        let evidence = limited
7652            .home
7653            .join("runs")
7654            .join(&state.id)
7655            .join("artifacts/source-evidence");
7656        std::fs::create_dir_all(&evidence).unwrap();
7657        let retained = evidence.join("reserved-evidence");
7658        std::fs::File::create(&retained)
7659            .unwrap()
7660            .set_len(64 * 1024 * 1024)
7661            .unwrap();
7662        let mut blocked = Report::default();
7663        copies::evict(&limited.home, &Fx::disk(), Fx::now(), &mut blocked).await;
7664        assert_eq!(blocked.evicted_copies, 0, "{blocked:?}");
7665        assert!(copy.exists());
7666        assert_eq!(
7667            std::fs::metadata(&retained).unwrap().len(),
7668            64 * 1024 * 1024
7669        );
7670        assert!(
7671            blocked
7672                .retained
7673                .iter()
7674                .any(|r| r.contains("per-run storage limit")),
7675            "{blocked:?}"
7676        );
7677    }
7678    #[tokio::test]
7679    async fn source_eviction_migrates_historical_records_without_rewriting_them() {
7680        let f = Fx::new().await;
7681        let mut state = inactive_source(&f, "ec14", true).await;
7682        historical_review(&mut state, &f.base);
7683        historical_review(&mut state, &f.base);
7684        state.status = RunStatus::Superseded;
7685        state.save_under(&f.home).unwrap();
7686        let review = reviewer(&f, &state, &f.base).await;
7687        let task = f.task(std::slice::from_ref(&state));
7688        let path = f.home.join("runs").join(&state.id).join("run.json");
7689        let mut raw: serde_json::Value =
7690            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
7691        raw["schema"] = 10.into();
7692        raw.as_object_mut().unwrap().remove("output_activity_at");
7693        // Historical writers persisted null/empty defaults that current serde
7694        // omits. These are known fields, not unknown recovery authorities.
7695        raw["resource_wait"] = serde_json::Value::Null;
7696        raw["resource_block"] = serde_json::Value::Null;
7697        raw["driver_claimed"] = serde_json::Value::Null;
7698        raw["sources"] = serde_json::json!({"start_from":null,"pick_commits":[]});
7699        // Actual legacy spelling accepted by Graph's serde alias.
7700        let graph = raw["config"]["graph"].as_object_mut().unwrap();
7701        let count = graph.remove("implementers").unwrap();
7702        graph.insert("candidates".into(), count);
7703        let queue = crate::queue::Queue::at(f.home.join("queue"));
7704        let task_path = queue.path_of(&task.id);
7705        let mut task_raw: serde_json::Value =
7706            serde_json::from_slice(&std::fs::read(&task_path).unwrap()).unwrap();
7707        task_raw["sources"] = serde_json::json!({"start_from":null,"pick_commits":[]});
7708        let task_historical = serde_json::to_vec_pretty(&task_raw).unwrap();
7709        std::fs::write(&task_path, &task_historical).unwrap();
7710        let historical = serde_json::to_vec_pretty(&raw).unwrap();
7711        std::fs::write(&path, &historical).unwrap();
7712        let report = sweep(&f.home, &Fx::disk(), Fx::now()).await;
7713        assert_eq!(report.evicted_copies, 1, "{report:?}");
7714        assert!(!review.exists());
7715        assert_eq!(std::fs::read(&path).unwrap(), historical);
7716        assert_eq!(std::fs::read(&task_path).unwrap(), task_historical);
7717        assert!(state.candidates[0].worktree.exists());
7718        assert_eq!(
7719            crate::queue::Queue::at(f.home.join("queue"))
7720                .get(&task.id)
7721                .unwrap()
7722                .runs,
7723            task.runs
7724        );
7725    }
7726    #[tokio::test]
7727    async fn source_eviction_archives_old_only_reflog_oid_after_unrewritten_deletion() {
7728        let f = Fx::new().await;
7729        let state = inactive_source(&f, "ed01", true).await;
7730        let review = reviewer(&f, &state, &f.base).await;
7731        std::fs::write(review.join("old-only"), b"old-only\0binary\xff").unwrap();
7732        git::git(&review, &["add", "."]).await.unwrap();
7733        let tree = git::git(&review, &["write-tree"]).await.unwrap();
7734        let tip = git::git(
7735            &review,
7736            &[
7737                "commit-tree",
7738                &tree,
7739                "-p",
7740                &f.base,
7741                "-m",
7742                "temporary detached source",
7743            ],
7744        )
7745        .await
7746        .unwrap();
7747        git::git(&review, &["checkout", "--detach", &tip])
7748            .await
7749            .unwrap();
7750        git::git(&review, &["checkout", "--detach", &f.base])
7751            .await
7752            .unwrap();
7753        git::git(&review, &["reflog", "delete", "HEAD@{1}"])
7754            .await
7755            .unwrap();
7756        git::git(&review, &["update-ref", "-d", "ORIG_HEAD"])
7757            .await
7758            .unwrap();
7759        let shown = git::git(&review, &["reflog", "show", "--format=%H", "HEAD"])
7760            .await
7761            .unwrap();
7762        assert!(!shown.lines().any(|oid| oid == tip));
7763        let admin = PathBuf::from(
7764            git::git(&review, &["rev-parse", "--absolute-git-dir"])
7765                .await
7766                .unwrap(),
7767        );
7768        let raw = std::fs::read_to_string(admin.join("logs/HEAD")).unwrap();
7769        assert!(raw.lines().any(|line| line.starts_with(&format!("{tip} "))));
7770        fn interrupt(_: &Path) -> Result<()> {
7771            anyhow::bail!("fixture interruption before unlink")
7772        }
7773        let mut pending = Report::default();
7774        copies::evict_with(&f.home, &Fx::disk(), Fx::now(), &mut pending, interrupt).await;
7775        assert!(review.exists());
7776        let ledger = f
7777            .home
7778            .join("runs")
7779            .join(&state.id)
7780            .join("artifacts/eviction-review-1.json");
7781        let complete = std::fs::read(&ledger).unwrap();
7782        let mut incomplete: serde_json::Value = serde_json::from_slice(&complete).unwrap();
7783        incomplete["history"]
7784            .as_object_mut()
7785            .unwrap()
7786            .remove(&tip)
7787            .unwrap();
7788        std::fs::write(&ledger, serde_json::to_vec(&incomplete).unwrap()).unwrap();
7789        let mut blocked = Report::default();
7790        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut blocked).await;
7791        assert!(review.exists());
7792        assert!(
7793            blocked
7794                .retained
7795                .iter()
7796                .any(|reason| reason.contains("incomplete reflog checkpoint")),
7797            "{blocked:?}"
7798        );
7799        std::fs::write(&ledger, complete).unwrap();
7800        let mut report = Report::default();
7801        copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7802        assert_eq!(report.evicted_copies, 1, "{report:?}");
7803        git::git(&f.repo, &["reflog", "expire", "--expire=now", "--all"])
7804            .await
7805            .unwrap();
7806        git::git(&f.repo, &["gc", "--prune=now"]).await.unwrap();
7807        assert!(
7808            !git::git_raw(&f.repo, &["cat-file", "-e", &tip])
7809                .await
7810                .unwrap()
7811                .ok()
7812        );
7813        std::fs::remove_dir_all(&f.repo).unwrap();
7814        let destination = f._temp.path().join("restore-old-only");
7815        restore_seat(&f.home, &state.id, &tip, &destination)
7816            .await
7817            .unwrap();
7818        assert_eq!(
7819            std::fs::read(destination.join("old-only")).unwrap(),
7820            b"old-only\0binary\xff"
7821        );
7822    }
7823
7824    #[tokio::test]
7825    async fn source_eviction_crashed_driver_lease_does_not_block_cleanup_or_retry() {
7826        fn interrupt(_: &Path) -> Result<()> {
7827            anyhow::bail!("fixture interruption before unlink")
7828        }
7829        fn vanish(path: &Path) -> Result<()> {
7830            std::fs::remove_dir_all(path)?;
7831            anyhow::bail!("fixture interruption before unregistration")
7832        }
7833        for stage in ["ordinary", "intent", "missing-registration", "live-driver"] {
7834            let f = Fx::new().await;
7835            let mut state = inactive_source(&f, "ed02", true).await;
7836            state.driver_exited = false;
7837            state.driver_claimed = Some(true);
7838            state.driver_pid = Some(std::process::id());
7839            state.driver_started_at = crate::proc::process_started_at(std::process::id());
7840            state.begin_pass();
7841            state.status = RunStatus::Superseded;
7842            state.save_under(&f.home).unwrap();
7843            let review = reviewer(&f, &state, &f.base).await;
7844            // The same matching identity written by DriverGuard::record, left
7845            // behind when a process exits without its cleanup guard running.
7846            let identity = serde_json::json!({"pid":state.driver_pid,"started_at":state.driver_started_at,
7847                "pass":state.passes.last().unwrap().started_at,"pass_index":state.passes.last().unwrap().index});
7848            std::fs::write(
7849                f.home.join("runs").join(&state.id).join("driver.json"),
7850                serde_json::to_vec(&identity).unwrap(),
7851            )
7852            .unwrap();
7853            let live = if stage == "live-driver" {
7854                Some(crate::driver::maintenance(&f.home, &state.id).unwrap())
7855            } else {
7856                None
7857            };
7858            assert_eq!(
7859                state.liveness_under(&f.home, false),
7860                if live.is_some() {
7861                    Liveness::Live
7862                } else {
7863                    Liveness::Dead
7864                }
7865            );
7866            let mut report = Report::default();
7867            if stage == "intent" || stage == "missing-registration" {
7868                copies::evict_with(
7869                    &f.home,
7870                    &Fx::disk(),
7871                    Fx::now(),
7872                    &mut report,
7873                    if stage == "intent" { interrupt } else { vanish },
7874                )
7875                .await;
7876                assert_eq!(report.evicted_copies, 0, "{stage}: {report:?}");
7877                let mut retry = Report::default();
7878                copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut retry).await;
7879                assert!(!review.exists(), "{stage}: {retry:?}");
7880                let ledger = f
7881                    .home
7882                    .join("runs")
7883                    .join(&state.id)
7884                    .join("artifacts/eviction-review-1.json");
7885                let receipt: serde_json::Value =
7886                    serde_json::from_slice(&std::fs::read(ledger).unwrap()).unwrap();
7887                assert_eq!(receipt["phase"], "evicted", "{stage}: {retry:?}");
7888            } else {
7889                copies::evict(&f.home, &Fx::disk(), Fx::now(), &mut report).await;
7890                assert_eq!(
7891                    report.evicted_copies,
7892                    usize::from(live.is_none()),
7893                    "{stage}: {report:?}"
7894                );
7895                assert_eq!(review.exists(), live.is_some());
7896            }
7897            drop(live);
7898            assert!(
7899                !RunState::load_under(&state.id, &f.home)
7900                    .unwrap()
7901                    .driver_exited
7902            );
7903        }
7904    }
7905}
7906
7907/// Platform-independent: these must run on the platform whose refusal they pin.
7908#[cfg(test)]
7909mod platform_tests {
7910    use super::*;
7911
7912    /// A platform without process containment refuses to reclaim, and says so
7913    /// in the persisted report instead of returning before anything is saved
7914    /// (which left a Windows operator with no `retention.json` at all).
7915    #[tokio::test]
7916    async fn a_platform_without_containment_persists_its_refusal() {
7917        let home = tempfile::tempdir().unwrap();
7918        let report = sweep_inner_on(
7919            home.path(),
7920            &crate::config::Disk::default(),
7921            Timestamp::now(),
7922            false,
7923        )
7924        .await;
7925        assert_eq!(report.failures, [UNSUPPORTED_PLATFORM]);
7926        assert_eq!(report.freed_bytes, 0);
7927        let saved: Report =
7928            serde_json::from_slice(&std::fs::read(home.path().join("retention.json")).unwrap())
7929                .unwrap();
7930        assert_eq!(saved.failures, [UNSUPPORTED_PLATFORM]);
7931        assert!(saved.checked_at.is_some());
7932        assert!(
7933            !home.path().join("retention.lock").exists(),
7934            "a refusal takes no lock and touches no output"
7935        );
7936    }
7937
7938    /// The refusal path publishes without `retention.lock`, so publications
7939    /// must not share a staging file: concurrent ones leave one complete
7940    /// report and nothing behind.
7941    #[test]
7942    fn concurrent_publications_leave_one_complete_report_and_no_staging_files() {
7943        let home = tempfile::tempdir().unwrap();
7944        let reports: Vec<Report> = (0..8)
7945            .map(|n| Report {
7946                failures: vec![format!("pass {n}")],
7947                ..Report::default()
7948            })
7949            .collect();
7950        let published = std::sync::atomic::AtomicUsize::new(0);
7951        std::thread::scope(|scope| {
7952            for report in &reports {
7953                scope.spawn(|| {
7954                    for _ in 0..25 {
7955                        // A rename onto a file another publisher has open may be
7956                        // refused on some platforms; the report on disk stays whole.
7957                        if publish_report(home.path(), report).is_ok() {
7958                            published.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7959                        }
7960                    }
7961                });
7962            }
7963        });
7964        assert!(
7965            published.load(std::sync::atomic::Ordering::Relaxed) >= reports.len(),
7966            "publication must succeed, not only leave a whole file behind"
7967        );
7968        let saved: Report =
7969            serde_json::from_slice(&std::fs::read(home.path().join("retention.json")).unwrap())
7970                .unwrap();
7971        assert!(reports.iter().any(|r| r.failures == saved.failures));
7972        let staged: Vec<_> = std::fs::read_dir(home.path())
7973            .unwrap()
7974            .flatten()
7975            .map(|e| e.file_name().to_string_lossy().into_owned())
7976            .filter(|name| name.ends_with(".tmp"))
7977            .collect();
7978        assert!(staged.is_empty(), "stray staging files: {staged:?}");
7979    }
7980
7981    /// A staging name a dead process left behind is never written through.
7982    #[test]
7983    fn staging_files_are_created_exclusively() {
7984        let home = tempfile::tempdir().unwrap();
7985        let left: Vec<PathBuf> = (0..40)
7986            .map(|n| {
7987                let path = home.path().join(format!(
7988                    "{STAGING_PREFIX}{}-{n}{STAGING_SUFFIX}",
7989                    std::process::id()
7990                ));
7991                std::fs::write(&path, "left by a dead process").unwrap();
7992                path
7993            })
7994            .collect();
7995        // The sequence starts at 0 whatever else this process has staged, so
7996        // the first forty names are guaranteed to collide.
7997        let mut sequence = 0u64..;
7998        let (created, file) =
7999            create_staging_numbered(home.path(), &mut || sequence.next().unwrap()).unwrap();
8000        drop(file);
8001        assert!(!left.contains(&created), "{}", created.display());
8002        assert!(created.ends_with(format!(
8003            "{STAGING_PREFIX}{}-40{STAGING_SUFFIX}",
8004            std::process::id()
8005        )));
8006        for path in left {
8007            assert_eq!(std::fs::read(path).unwrap(), b"left by a dead process");
8008        }
8009    }
8010
8011    /// A staging file of this report that a crash left behind goes at the next
8012    /// publication once it is a day old; a recent one (a publisher in flight)
8013    /// and files that are not this report's are never touched.
8014    #[test]
8015    fn publishing_removes_only_stale_staging_files_of_this_report() {
8016        let home = tempfile::tempdir().unwrap();
8017        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 24 * 60 * 60);
8018        let write = |name: &str, modified: std::time::SystemTime| {
8019            let path = home.path().join(name);
8020            let file = std::fs::File::create(&path).unwrap();
8021            file.set_modified(modified).unwrap();
8022            path
8023        };
8024        let crashed = write("retention.json.4242-7.tmp", old);
8025        let legacy = write("retention.json.tmp", old);
8026        let in_flight = write("retention.json.4243-1.tmp", std::time::SystemTime::now());
8027        let unrelated = write("something-else.tmp", old);
8028        let other = write("retention.json.bak", old);
8029
8030        publish_report(home.path(), &Report::default()).unwrap();
8031
8032        assert!(!crashed.exists());
8033        assert!(!legacy.exists());
8034        assert!(in_flight.exists());
8035        assert!(unrelated.exists());
8036        assert!(other.exists());
8037        assert!(home.path().join("retention.json").is_file());
8038    }
8039}