use crate::{
config::ScanConfig,
domain::{DiscoveryFilters, EffectiveScanPolicy, ScanRequest, ScanScope},
error::AppError,
};
use std::{
fs,
path::{Path, PathBuf},
time::Duration,
};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GlobalDiscoveryPolicy {
pub roots: Vec<PathBuf>,
pub global_only_prunes: Vec<PathBuf>,
pub managed_tool_prunes: Vec<PathBuf>,
}
pub fn resolve(request: ScanRequest, config: &ScanConfig) -> Result<EffectiveScanPolicy, AppError> {
if request.full {
return Ok(EffectiveScanPolicy {
recency: Duration::from_secs(config.recency_seconds),
scope: ScanScope::Global(global_discovery_policy().roots),
discovery_filters: DiscoveryFilters::Active {
ignore: config.ignore.clone(),
unignore: config.unignore.clone(),
},
});
}
let explicit = request.cli_root.or_else(|| config.root.clone());
let (scope, discovery_filters) = if let Some(root) = explicit {
let m = fs::symlink_metadata(&root).map_err(|e| AppError::InvalidRoot {
path: root.display().to_string(),
reason: e.to_string(),
})?;
if !m.is_dir() || m.file_type().is_symlink() || path_is_symlink(&root) {
return Err(AppError::InvalidRoot {
path: root.display().to_string(),
reason: "expected a real directory".into(),
});
}
(ScanScope::Explicit(root), DiscoveryFilters::Bypassed)
} else {
(
ScanScope::Routine(routine_roots(config.learned_root_retention_days as u16)),
DiscoveryFilters::Active {
ignore: config.ignore.clone(),
unignore: config.unignore.clone(),
},
)
};
Ok(EffectiveScanPolicy {
recency: Duration::from_secs(config.recency_seconds),
scope,
discovery_filters,
})
}
pub fn routine_seed_candidates(home: &Path) -> Vec<PathBuf> {
[
"Projects",
"projects",
"Developer",
"dev",
"Code",
"code",
"src",
"repos",
"Repos",
"GitHub",
"github",
"workspace",
"workspaces",
]
.iter()
.map(|name| home.join(name))
.collect()
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RootProvenance {
Explicit,
Automatic,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AutomaticOmission {
NotFound(PathBuf),
NonDirectory(PathBuf),
NotMaintainable(PathBuf),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AutomaticBlock {
pub path: PathBuf,
pub reason: String,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ClassifiedRoots {
pub admitted: Vec<PathBuf>,
pub omitted: Vec<AutomaticOmission>,
pub blocked: Vec<AutomaticBlock>,
}
impl ClassifiedRoots {
pub fn omitted_paths(&self) -> Vec<PathBuf> {
self.omitted
.iter()
.map(|o| match o {
AutomaticOmission::NotFound(p)
| AutomaticOmission::NonDirectory(p)
| AutomaticOmission::NotMaintainable(p) => p.clone(),
})
.collect()
}
pub fn omission_diagnostics(&self) -> Vec<String> {
let mut groups: std::collections::BTreeMap<&str, Vec<&PathBuf>> =
std::collections::BTreeMap::new();
for omission in &self.omitted {
let (reason, path) = match omission {
AutomaticOmission::NotFound(path) => ("unavailable", path),
AutomaticOmission::NonDirectory(path) => ("non-directory", path),
AutomaticOmission::NotMaintainable(path) => ("non-maintainable", path),
};
groups.entry(reason).or_default().push(path);
}
groups
.into_iter()
.map(|(reason, mut paths)| {
paths.sort();
let examples = paths
.iter()
.take(3)
.map(|path| {
path.display()
.to_string()
.chars()
.filter(|ch| !ch.is_control())
.take(200)
.collect::<String>()
})
.collect::<Vec<_>>();
let sample = if examples.is_empty() {
String::new()
} else {
format!("; examples: {}", examples.join(", "))
};
format!("omitting {} {reason} learned root(s){sample}", paths.len())
})
.collect()
}
}
pub fn classify_cleanup_roots(entries: CleanupCandidates) -> Result<ClassifiedRoots, AppError> {
let home = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf());
classify_cleanup_roots_with_home(entries, home.as_deref())
}
fn path_is_symlink(path: &Path) -> bool {
if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
return true;
}
let mut spelling = path.as_os_str().to_string_lossy().into_owned();
loop {
let trimmed = spelling.trim_end_matches(['/', '\\']).to_owned();
if trimmed.ends_with("/.") || trimmed.ends_with("\\.") {
spelling = trimmed[..trimmed.len() - 1].to_owned();
continue;
}
spelling = trimmed;
break;
}
if !spelling.is_empty()
&& fs::symlink_metadata(&spelling).is_ok_and(|m| m.file_type().is_symlink())
{
return true;
}
false
}
fn classify_cleanup_roots_with_home(
entries: CleanupCandidates,
home: Option<&Path>,
) -> Result<ClassifiedRoots, AppError> {
let mut out = ClassifiedRoots::default();
for (path, provenance) in entries {
match (fs::symlink_metadata(&path), provenance) {
(Ok(meta), RootProvenance::Explicit) => {
if !meta.is_dir() || meta.file_type().is_symlink() || path_is_symlink(&path) {
return Err(AppError::InvalidRoot {
path: path.display().to_string(),
reason: "expected a real directory".into(),
});
}
out.admitted.push(path);
}
(Ok(meta), RootProvenance::Automatic) => {
if meta.file_type().is_symlink() || path_is_symlink(&path) {
out.blocked.push(AutomaticBlock {
path: path.clone(),
reason: format!(
"automatic root {} is a symlink; refusing to follow or omit",
path.display()
),
});
} else if meta.is_dir() {
if crate::discovery_state::automatic_root_is_maintainable(&path, home) {
out.admitted.push(path);
} else if let Err(error) = fs::read_dir(&path) {
out.blocked.push(AutomaticBlock {
path: path.clone(),
reason: format!(
"cannot establish coverage of non-maintainable automatic root {}: {error}",
path.display()
),
});
} else {
out.omitted.push(AutomaticOmission::NotMaintainable(path));
}
} else {
out.omitted.push(AutomaticOmission::NonDirectory(path));
}
}
(Err(e), RootProvenance::Explicit) => {
return Err(AppError::InvalidRoot {
path: path.display().to_string(),
reason: e.to_string(),
});
}
(Err(e), RootProvenance::Automatic) => {
if e.kind() == std::io::ErrorKind::NotFound
&& crate::discovery_state::automatic_root_is_maintainable(&path, home)
{
out.omitted.push(AutomaticOmission::NotFound(path));
} else if e.kind() == std::io::ErrorKind::NotFound {
out.omitted.push(AutomaticOmission::NotMaintainable(path));
} else if e.kind() == std::io::ErrorKind::PermissionDenied {
out.blocked.push(AutomaticBlock {
path: path.clone(),
reason: format!("cannot access automatic root {}: {e}", path.display()),
});
} else {
out.blocked.push(AutomaticBlock {
path: path.clone(),
reason: format!(
"indeterminate filesystem state for automatic root {}: {e}",
path.display()
),
});
}
}
}
}
out.admitted.sort();
out.admitted.dedup();
Ok(out)
}
pub fn recheck_admission_premise(
admitted: &[PathBuf],
omitted: &[AutomaticOmission],
) -> Option<(PathBuf, String)> {
let home = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf());
for omission in omitted {
let (path, must_stay_absent) = match omission {
AutomaticOmission::NotFound(p) => (p, true),
AutomaticOmission::NonDirectory(p) => (p, false),
AutomaticOmission::NotMaintainable(p) => (p, false),
};
match fs::symlink_metadata(path) {
Ok(meta) if matches!(omission, AutomaticOmission::NotMaintainable(_)) => {
if crate::discovery_state::automatic_root_is_maintainable(path, home.as_deref()) {
return Some((
path.clone(),
format!(
"previously omitted root {} is now maintainable; ownership scope changed",
path.display()
),
));
}
if meta.file_type().is_symlink() {
return Some((
path.clone(),
format!("omitted root {} became a symlink", path.display()),
));
}
}
Ok(meta) if meta.file_type().is_symlink() => {
return Some((
path.clone(),
format!(
"skipped root {} reappeared as a symlink; ownership boundary is unproven",
path.display()
),
));
}
Ok(meta) if meta.is_dir() => {
return Some((
path.clone(),
format!(
"skipped root {} reappeared as a directory; ownership boundary is unproven",
path.display()
),
));
}
Ok(_) if must_stay_absent => {
return Some((
path.clone(),
format!(
"skipped root {} reappeared; ownership boundary is unproven",
path.display()
),
));
}
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
return Some((
path.clone(),
format!(
"skipped root {} is now unreadable ({e}); ownership boundary is unproven",
path.display()
),
));
}
}
}
for path in admitted {
match fs::symlink_metadata(path) {
Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => {}
Ok(_) => {
return Some((
path.clone(),
format!(
"admitted root {} changed type; ownership proof is stale",
path.display()
),
));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Some((
path.clone(),
format!(
"admitted root {} disappeared; ownership proof is stale",
path.display()
),
));
}
Err(e) => {
return Some((
path.clone(),
format!(
"admitted root {} is now unreadable ({e}); ownership proof is stale",
path.display()
),
));
}
}
}
None
}
pub type CleanupCandidates = Vec<(PathBuf, RootProvenance)>;
pub fn full_cleanup_roots(
reconciliation_code: i32,
state: Option<crate::discovery_state::DiscoveryState>,
) -> Result<(CleanupCandidates, Option<u64>), AppError> {
if reconciliation_code != 0 {
return Err(AppError::Config(format!(
"full reconciliation reported an incomplete scan (exit {reconciliation_code}); \
no cleanup commands were run against its unproven learned roots"
)));
}
let Some(state) = state else {
return Err(AppError::Config(
"full reconciliation produced no fresh generation; \
no cleanup commands were run against stale learned roots"
.into(),
));
};
let generation = state.last_full_at;
let entries = state
.learned_roots
.into_iter()
.map(|r| (r.path, RootProvenance::Automatic))
.collect();
Ok((entries, generation))
}
pub fn routine_cleanup_candidates(
home: &Path,
retention_days: u16,
load: crate::discovery_state::StateLoad,
) -> (CleanupCandidates, Option<String>) {
let mut entries: CleanupCandidates = routine_seed_candidates(home)
.into_iter()
.filter(|p| fs::symlink_metadata(p).is_ok())
.map(|p| (p, RootProvenance::Automatic))
.collect();
let warning = match load {
crate::discovery_state::StateLoad::Loaded(state) => {
let now = crate::discovery_state::now_seconds();
entries.extend(
state
.learned_roots
.into_iter()
.filter(|r| {
retention_days == 0
|| now < r.last_project_seen_at
|| now.saturating_sub(r.last_project_seen_at)
<= u64::from(retention_days) * 86400
})
.map(|r| (r.path, RootProvenance::Automatic)),
);
None
}
load => load.diagnostic(),
};
(entries, warning)
}
fn routine_roots(retention_days: u16) -> Vec<PathBuf> {
let Some(home) = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf()) else {
return Vec::new();
};
let (roots, warning) = routine_roots_from_state(
&home,
retention_days,
crate::discovery_state::load_default(),
);
if let Some(warning) = warning {
eprintln!("cargo-cleanme: {warning}; using seed/configured Routine roots");
}
roots
}
fn routine_roots_from_state(
home: &Path,
retention_days: u16,
load: crate::discovery_state::StateLoad,
) -> (Vec<PathBuf>, Option<String>) {
let mut roots: Vec<PathBuf> = routine_seed_candidates(home)
.into_iter()
.filter(|p| p.is_dir())
.collect();
let warning = match load {
crate::discovery_state::StateLoad::Loaded(state) => {
let now = crate::discovery_state::now_seconds();
roots.extend(
state
.learned_roots
.into_iter()
.filter(|r| {
crate::discovery_state::automatic_root_is_maintainable(&r.path, Some(home))
&& (retention_days == 0
|| now < r.last_project_seen_at
|| now.saturating_sub(r.last_project_seen_at)
<= u64::from(retention_days) * 86400)
})
.map(|r| r.path),
);
None
}
load => load.diagnostic(),
};
(canonical_dedup_roots(roots), warning)
}
#[cfg(unix)]
pub fn global_discovery_policy() -> GlobalDiscoveryPolicy {
compose_global_policy(unix_policy(
cfg!(target_os = "macos"),
cfg!(target_os = "linux"),
cfg!(target_os = "macos") && Path::new("/usr/local").is_dir(),
))
}
#[cfg(unix)]
fn compose_global_policy(platform: GlobalDiscoveryPolicy) -> GlobalDiscoveryPolicy {
let protected: Vec<PathBuf> = platform
.roots
.iter()
.filter(|root| {
platform
.global_only_prunes
.iter()
.any(|prune| prune != *root && root.starts_with(prune))
})
.cloned()
.collect();
GlobalDiscoveryPolicy {
roots: canonical_dedup_roots_protecting(platform.roots, &protected),
global_only_prunes: platform.global_only_prunes,
managed_tool_prunes: managed_rust_prunes(),
}
}
#[cfg(unix)]
fn unix_policy(macos: bool, linux: bool, usr_local_present: bool) -> GlobalDiscoveryPolicy {
let mut roots = vec![PathBuf::from("/")];
let global_only_prunes = if macos {
if usr_local_present {
roots.push(PathBuf::from("/usr/local"));
}
["/System", "/dev", "/bin", "/sbin", "/usr"]
.map(PathBuf::from)
.to_vec()
} else if linux {
["/proc", "/sys", "/dev", "/run"]
.map(PathBuf::from)
.to_vec()
} else {
Vec::new()
};
GlobalDiscoveryPolicy {
roots,
global_only_prunes,
managed_tool_prunes: Vec::new(),
}
}
#[cfg(windows)]
pub fn global_discovery_policy() -> GlobalDiscoveryPolicy {
use windows_sys::Win32::{
Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives},
System::WindowsProgramming::{DRIVE_FIXED, DRIVE_REMOVABLE},
};
let mask = unsafe { GetLogicalDrives() };
let roots = (0..26)
.filter_map(|i| {
if mask & (1 << i) == 0 {
return None;
}
let letter = char::from(b'A' + i as u8);
let path = format!("{letter}:\\");
let wide: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
let kind = unsafe { GetDriveTypeW(wide.as_ptr()) };
(kind == DRIVE_FIXED || kind == DRIVE_REMOVABLE).then(|| PathBuf::from(path))
})
.collect();
GlobalDiscoveryPolicy {
roots: canonical_dedup_roots(roots),
global_only_prunes: Vec::new(),
managed_tool_prunes: managed_rust_prunes(),
}
}
fn lexical_identity(path: &Path) -> PathBuf {
if !path.is_absolute() {
return path.to_path_buf();
}
let mut out = PathBuf::from(std::path::MAIN_SEPARATOR_STR);
for component in path.components() {
match component {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
out.pop();
}
other => out.push(other.as_os_str()),
}
}
out
}
fn canonical_dedup_roots(roots: Vec<PathBuf>) -> Vec<PathBuf> {
canonical_dedup_roots_protecting(roots, &[])
}
fn canonical_dedup_roots_protecting(roots: Vec<PathBuf>, protected: &[PathBuf]) -> Vec<PathBuf> {
let mut identified: Vec<(PathBuf, PathBuf)> = roots
.into_iter()
.map(|root| match fs::canonicalize(&root) {
Ok(canonical) => (canonical.clone(), canonical),
Err(_) => (lexical_identity(&root), root),
})
.collect();
identified.sort();
identified.dedup_by(|a, b| a.0 == b.0);
let mut collapsed: Vec<(PathBuf, PathBuf)> = Vec::new();
for (identity, root) in identified {
if protected.contains(&identity)
|| !collapsed
.iter()
.any(|(parent, _): &(PathBuf, PathBuf)| identity.starts_with(parent))
{
collapsed.push((identity, root));
}
}
collapsed.into_iter().map(|(_, root)| root).collect()
}
fn managed_rust_prunes() -> Vec<PathBuf> {
crate::discovery::effective_rustup_home()
.into_iter()
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::ScanConfig;
use tempfile::tempdir;
#[test]
#[cfg(unix)]
fn macos_global_policy_prunes_protected_usr_and_enumerates_usr_local() {
let policy = compose_global_policy(unix_policy(true, false, true));
assert!(policy.global_only_prunes.contains(&PathBuf::from("/usr")));
assert!(
policy.roots.contains(&PathBuf::from("/usr/local")),
"the /usr/local exception root must survive composition, got {:?}",
policy.roots
);
assert!(policy.roots.contains(&PathBuf::from("/")));
assert!(
!policy
.global_only_prunes
.contains(&PathBuf::from("/Library"))
);
assert!(
!policy
.global_only_prunes
.contains(&PathBuf::from("/Applications"))
);
}
#[test]
#[cfg(unix)]
fn a_root_inside_a_global_prune_survives_the_collapse_as_its_own_root() {
let roots = vec![
PathBuf::from("/"),
PathBuf::from("/usr/local"),
PathBuf::from("/usr/local/bin"),
];
let composed = canonical_dedup_roots_protecting(roots, &[PathBuf::from("/usr/local")]);
assert!(composed.contains(&PathBuf::from("/")));
assert!(composed.contains(&PathBuf::from("/usr/local")));
assert!(!composed.contains(&PathBuf::from("/usr/local/bin")));
let plain = canonical_dedup_roots(vec![PathBuf::from("/"), PathBuf::from("/usr/local")]);
assert_eq!(plain, vec![PathBuf::from("/")]);
}
#[test]
#[cfg(unix)]
fn linux_global_policy_keeps_the_existing_pseudo_filesystem_prunes() {
let policy = unix_policy(false, true, false);
for path in ["/proc", "/sys", "/dev", "/run"] {
assert!(policy.global_only_prunes.contains(&PathBuf::from(path)));
}
assert!(!policy.global_only_prunes.contains(&PathBuf::from("/usr")));
}
#[test]
fn cli_root_wins_and_bypasses_filters() {
let d = tempdir().unwrap();
let cli = d.path().to_path_buf();
let configured = PathBuf::from("/tmp");
let c = ScanConfig {
root: Some(configured),
ignore: vec!["/tmp/*".into()],
unignore: vec![PathBuf::from("/tmp/keep")],
..Default::default()
};
let p = resolve(
ScanRequest {
cli_root: Some(cli.clone()),
full: false,
},
&c,
)
.unwrap();
assert_eq!(p.scope, ScanScope::Explicit(cli));
assert_eq!(p.discovery_filters, DiscoveryFilters::Bypassed);
assert_eq!(p.recency, Duration::from_secs(300));
}
#[test]
fn configured_root_wins_over_global() {
let d = tempdir().unwrap();
let c = ScanConfig {
root: Some(d.path().into()),
..Default::default()
};
assert!(matches!(
resolve(
ScanRequest {
cli_root: None,
full: false
},
&c
)
.unwrap()
.scope,
ScanScope::Explicit(_)
));
}
#[test]
fn full_resolution_ignores_a_configured_root() {
let d = tempdir().unwrap();
let c = ScanConfig {
root: Some(d.path().to_path_buf()),
..Default::default()
};
let p = resolve(
ScanRequest {
cli_root: None,
full: true,
},
&c,
)
.unwrap();
assert!(
matches!(p.scope, ScanScope::Global(_)),
"a configured scan.root must not narrow a Full scan: {:?}",
p.scope
);
assert_ne!(p.scope, ScanScope::Explicit(d.path().to_path_buf()));
}
#[test]
fn maintenance_scope_is_routine_without_a_configured_root() {
let c = ScanConfig::default();
assert!(c.root.is_none());
let p = resolve(
ScanRequest {
cli_root: None,
full: false,
},
&c,
)
.unwrap();
assert!(matches!(p.scope, ScanScope::Routine(_)), "{:?}", p.scope);
}
#[test]
fn routine_state_errors_fall_back_to_seeds_with_one_warning() {
let d = tempdir().unwrap();
let seed = d.path().join("Projects");
fs::create_dir(&seed).unwrap();
let states = [
crate::discovery_state::StateLoad::RecoverableInvalid(
crate::discovery_state::StateProblem::Invalid {
path: d.path().join("state.json"),
detail: "invalid schema 0".into(),
},
),
crate::discovery_state::StateLoad::UnsupportedNewer {
path: d.path().join("state.json"),
schema: 99,
current: crate::discovery_state::CURRENT_SCHEMA,
},
];
for state in states {
let (roots, warning) = routine_roots_from_state(d.path(), 30, state);
assert_eq!(roots, vec![fs::canonicalize(&seed).unwrap()]);
assert!(warning.is_some());
}
}
#[test]
fn automatic_roots_classify_by_provenance_and_explicit_roots_stay_strict() {
let d = tempdir().unwrap();
let real = d.path().join("present");
fs::create_dir(&real).unwrap();
let missing = d.path().join("deleted-worktree");
assert!(!missing.exists());
let file = d.path().join("regular-file");
fs::write(&file, b"not a directory").unwrap();
let classified = classify_cleanup_roots_with_home(
vec![
(real.clone(), RootProvenance::Automatic),
(missing.clone(), RootProvenance::Automatic),
(file.clone(), RootProvenance::Automatic),
],
Some(d.path()),
)
.unwrap();
assert_eq!(classified.admitted, vec![real.clone()]);
assert!(classified.blocked.is_empty());
assert_eq!(classified.omitted.len(), 2);
assert!(
classified
.omitted
.contains(&AutomaticOmission::NotFound(missing))
);
assert!(
classified
.omitted
.contains(&AutomaticOmission::NonDirectory(file))
);
for bad in [d.path().join("nope"), d.path().join("regular-file")] {
let Err(crate::error::AppError::InvalidRoot { .. }) = classify_cleanup_roots(vec![
(real.clone(), RootProvenance::Automatic),
(bad, RootProvenance::Explicit),
]) else {
panic!("explicit defects must stay fatal");
};
}
}
#[test]
#[cfg(unix)]
fn symlinked_automatic_roots_block_and_are_never_followed_or_omitted() {
let d = tempdir().unwrap();
let target = d.path().join("target");
fs::create_dir(&target).unwrap();
let link = d.path().join("link-to-dir");
std::os::unix::fs::symlink(&target, &link).unwrap();
let broken = d.path().join("broken-link");
std::os::unix::fs::symlink(d.path().join("nowhere"), &broken).unwrap();
assert!(link.is_dir());
for sym in [&link, &broken] {
let classified =
classify_cleanup_roots(vec![(sym.clone(), RootProvenance::Automatic)]).unwrap();
assert!(
classified.admitted.is_empty(),
"a symlink is never admitted"
);
assert!(
classified.omitted.is_empty(),
"a symlink is never positive absence"
);
assert_eq!(classified.blocked.len(), 1);
}
let Err(crate::error::AppError::InvalidRoot { .. }) =
classify_cleanup_roots(vec![(link, RootProvenance::Explicit)])
else {
panic!("explicit symlink must be fatal");
};
}
#[test]
#[cfg(unix)]
fn trailing_slash_symlink_roots_classify_like_plain_symlinks() {
let d = tempdir().unwrap();
let target = d.path().join("target");
fs::create_dir(&target).unwrap();
let link = d.path().join("link-to-dir");
std::os::unix::fs::symlink(&target, &link).unwrap();
let slashed = PathBuf::from(format!("{}/", link.display()));
let Err(crate::error::AppError::InvalidRoot { .. }) =
classify_cleanup_roots(vec![(slashed.clone(), RootProvenance::Explicit)])
else {
panic!("explicit symlink with trailing slash must be fatal");
};
let classified =
classify_cleanup_roots(vec![(slashed, RootProvenance::Automatic)]).unwrap();
assert!(classified.admitted.is_empty());
assert!(classified.omitted.is_empty());
assert_eq!(classified.blocked.len(), 1);
let with_dot = PathBuf::from(format!("{}/.", link.display()));
assert!(path_is_symlink(&with_dot));
let classified =
classify_cleanup_roots(vec![(with_dot, RootProvenance::Automatic)]).unwrap();
assert_eq!(classified.blocked.len(), 1);
}
#[test]
fn admission_premise_recheck_detects_reappearance_and_disappearance() {
let d = tempdir().unwrap();
let admitted = d.path().join("admitted");
fs::create_dir(&admitted).unwrap();
let skipped = d.path().join("skipped");
assert!(!skipped.exists());
let check = |admitted: &PathBuf, omission: &AutomaticOmission| {
recheck_admission_premise(
std::slice::from_ref(admitted),
std::slice::from_ref(omission),
)
};
let absent = AutomaticOmission::NotFound(skipped.clone());
assert!(check(&admitted, &absent).is_none());
fs::create_dir(&skipped).unwrap();
assert!(check(&admitted, &absent).is_some());
let file = d.path().join("file-skip");
fs::write(&file, b"x").unwrap();
let nondir = AutomaticOmission::NonDirectory(file.clone());
assert!(check(&admitted, &nondir).is_none());
fs::remove_file(&file).unwrap();
assert!(check(&admitted, &nondir).is_none());
fs::create_dir(&file).unwrap();
assert!(check(&admitted, &nondir).is_some());
fs::remove_dir(&file).unwrap();
fs::remove_dir(&skipped).unwrap();
fs::remove_dir(&admitted).unwrap();
let (path, _) = check(&admitted, &absent).expect("must flag");
assert_eq!(path, admitted);
}
#[test]
fn full_cleanup_consumes_only_a_fresh_in_memory_generation() {
let state = || crate::discovery_state::DiscoveryState {
schema_version: crate::discovery_state::CURRENT_SCHEMA,
last_full_at: Some(77),
learned_roots: vec![crate::discovery_state::LearnedRoot {
path: PathBuf::from("/work/a"),
last_project_seen_at: 77,
}],
..Default::default()
};
assert!(full_cleanup_roots(0, None).is_err());
assert!(full_cleanup_roots(1, Some(state())).is_err());
let (entries, generation) = full_cleanup_roots(0, Some(state())).unwrap();
assert_eq!(
entries,
vec![(PathBuf::from("/work/a"), RootProvenance::Automatic)]
);
assert_eq!(generation, Some(77));
}
#[test]
#[cfg(unix)]
fn cleanup_candidates_preserve_symlinked_seed_identity_for_admission() {
let home = tempdir().unwrap();
let seed_name = "Developer";
let seed = home.path().join(seed_name);
fs::create_dir(&seed).unwrap();
let target = home.path().join("real-target");
fs::create_dir(&target).unwrap();
fs::remove_dir(&seed).unwrap();
std::os::unix::fs::symlink(&target, &seed).unwrap();
assert!(seed.is_dir(), "premise: is_dir follows the seed symlink");
let (entries, _) =
routine_cleanup_candidates(home.path(), 30, crate::discovery_state::StateLoad::Missing);
assert!(
entries.contains(&(seed.clone(), RootProvenance::Automatic)),
"candidates must carry the link, not its target: {entries:?}"
);
let classified = classify_cleanup_roots(entries).unwrap();
assert!(classified.admitted.is_empty());
assert_eq!(classified.blocked.len(), 1);
assert_eq!(classified.blocked[0].path, seed);
}
#[test]
fn missing_transient_roots_classify_as_non_maintainable_not_unavailable() {
let d = tempdir().unwrap();
let home = d.path();
let missing_transient = home.join(".codex/worktrees/dead-session-id");
let missing_cache = home.join("Library/Caches/Homebrew/cargo_cache");
let missing_durable = home.join("Developer/vanished-project");
for p in [&missing_transient, &missing_cache, &missing_durable] {
assert!(!p.exists(), "premise: nothing created");
}
let classified = classify_cleanup_roots_with_home(
vec![
(missing_transient.clone(), RootProvenance::Automatic),
(missing_cache.clone(), RootProvenance::Automatic),
(missing_durable.clone(), RootProvenance::Automatic),
],
Some(home),
)
.unwrap();
assert!(classified.blocked.is_empty());
assert!(classified.admitted.is_empty());
assert!(
classified
.omitted
.contains(&AutomaticOmission::NotMaintainable(missing_transient)),
"deleted worktree must be non-maintainable: {:?}",
classified.omitted
);
assert!(
classified
.omitted
.contains(&AutomaticOmission::NotMaintainable(missing_cache)),
"emptied platform cache must be non-maintainable: {:?}",
classified.omitted
);
assert!(
classified
.omitted
.contains(&AutomaticOmission::NotFound(missing_durable)),
"deleted durable project stays unavailable: {:?}",
classified.omitted
);
}
#[test]
fn omission_diagnostics_group_reasons_and_bound_path_samples() {
let mut classified = ClassifiedRoots::default();
for index in (0..100).rev() {
classified
.omitted
.push(AutomaticOmission::NotFound(PathBuf::from(format!(
"/home/user/.codex/worktrees/{index}"
))));
}
classified
.omitted
.push(AutomaticOmission::NonDirectory(PathBuf::from(
"/home/user/projects/file",
)));
let diagnostics = classified.omission_diagnostics();
assert_eq!(
diagnostics.len(),
2,
"each omission reason gets one summary"
);
assert!(diagnostics[0].starts_with("omitting 1 non-directory learned root(s)"));
assert!(diagnostics[1].starts_with("omitting 100 unavailable learned root(s)"));
assert!(diagnostics[1].contains("/home/user/.codex/worktrees/0"));
assert!(diagnostics[1].contains("/home/user/.codex/worktrees/1"));
assert!(diagnostics[1].contains("/home/user/.codex/worktrees/10"));
assert!(!diagnostics[1].contains("/home/user/.codex/worktrees/11"));
assert!(diagnostics.iter().all(|line| line.len() < 700));
}
}