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