//! THE LANE LEDGER: EVERYTHING A LANE LEAVES ON A MAC IS CLAIMED, AND ONLY A //! CLAIM IS EVER RELEASED (storage note c7d20613, 10 Oct 2026). //! //! The disks of the development Macs did not fill with build output; they //! filled with things nobody owned — a lane's evidence beside its worktree, //! database rehearsal copies, QA households, scratchpads. A full disk broke a //! build roughly every other day from 17 Sep to 8 Oct, and each time someone //! reclaimed tens of gigabytes by hand, deciding alone what was trash. //! //! So every thing a lane makes is a CLAIM: a path, what it is, the lane and //! session that made it, and the rule that lets it go. A claim is one JSON file //! in this Mac's spool (`~/.cottondb/claims`, written by `scripts/lane-claim.sh` //! at the moment the thing is made, or by the adopt scan below), and the spool //! is the only list a deletion is ever taken from. The synced rows the owner //! reads on the phone are a mirror of it: a row can ask for a drop, but the //! path removed is always the spool's own, so nothing synced can point this //! Mac's remover anywhere else. //! //! A pass ([`pass`]) on the Mac app's own schedule: //! //! 1. forgets claims whose path is gone; //! 2. ADOPTS what a lane left without claiming — under the roots a lane writes //! to, every directory on no claim becomes one: regenerable build output //! under the budget rule; a lane's own caches (its folder, a checkout's //! `.worktrees/*` and `.claude/worktrees/agent-*`) under the budget too, //! with the cargo target inside one a budget claim of its own; a lane's //! series of runs (walk evidence, release-walk runs, cuts) keeping its //! newest [`KEEP_RUNS`]; the copies lanes make (households, database //! copies, kept dSYMs) under the idle hours their makers claim them with; //! a CI runner's run folders (`~//work/*`, never the runner //! itself) keeping its newest [`KEEP_RUNS`], and Xcode's DerivedData under //! the budget, one whose run folder is gone released at once; the home //! sweep's archive (`~/.cache/cottondb/home-sweep-*`) after a week idle; //! and only what no rule can judge (simulators, an agent's scratchpads) //! `owner_only`, shown with its size and never removed by rule. A claim //! adopted before takes the scan's rule as it stands now, and one the scan //! no longer finds is forgotten (its path untouched). A file or folder a //! session left LOOSE at the top of home since this Mac's baseline, that //! no allow-list name and no other scan covers, is adopted as scratch //! under [`LOOSE_IDLE_HOURS`] and listed once on the report //! ([`PassReport::loose`]), for the owner's Feedback; //! 3. measures what has not been measured lately; //! 4. releases what the owner dropped, then what its rule let go (its session //! ended, it sat idle past its hours, newer runs of its series replaced //! it, the CI run that built it is gone), then — while the disk is under this Mac's reserve — budget claims //! least recently touched first, build output before the folder holding it //! at an equal touch. A `session_ends` claim whose session is not known to //! live (ended, or no row names it) is a budget claim too: a lane's cache //! goes by its session while the session lives, then by the budget. //! //! A claim held by a job (a cargo lock naming a live pid, or a running job //! working in it), or touched within [`GRACE_SECS`], is never released by a //! rule; a job running elsewhere on the Mac holds nothing else. An `owner_only` claim is //! released only when the owner drops it. Releasing a folder releases every //! claim inside it (a worktree takes its target with it). A path that is home itself, above //! home, a credential's folder, or a live database's folder is refused outright //! ([`refusal`]), whoever asks. //! //! Everything here is a plan over the filesystem plus executors handed in as //! arguments, so the tests drive it on a temp directory with a fake disk. use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime}; use chrono::{DateTime, SecondsFormat, Utc}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; /// A claim not touched for this long may be released by a rule; one touched /// more recently is in use, whatever its rule says. The cargo sweep's grace, /// for the same reason: a job between checkout and its first write. pub const GRACE_SECS: u64 = 60 * 60; /// How long the owner's Drop stands before it is carried out: a switch asks /// no question, so the first pass that sees it only says so, and a Drop /// switched off again within this keeps the path. pub const DROP_WAIT: Duration = Duration::from_secs(2 * 60); /// How often a claim's size is measured again. A walk of a lane's evidence can /// take minutes, and the owner's page needs gigabytes, not bytes. pub const MEASURE_EVERY: Duration = Duration::from_secs(6 * 60 * 60); /// How many runs of one series a `keep_last` claim keeps: a lane's walk /// evidence, release-walk runs and cuts (architect's survey of one Mac, 10 Oct 2026 /// — walk:board wrote 1.7 GB every 20 minutes, 360 GB by its old rule). pub const KEEP_RUNS: u32 = 3; /// How long a file or folder a session left loose at the top of home stands /// idle before it goes (owner, 10 Oct 2026: sessions write scratch under their /// scratchpad or into Cotton, never loose into `~`). pub const LOOSE_IDLE_HOURS: u32 = 72; /// How long the home sweep's archive (`~/.cache/cottondb/home-sweep-*`, the /// loose files a cleanup parked with an `INDEX.md`) stands idle before it goes /// (coordinator, 10 Oct 2026: a week to look before it goes). pub const SWEEP_IDLE_HOURS: u32 = 168; /// The names at the top of home that are never loose: the coordinator's and /// the lanes' own files, the runner, the checkouts, and the folders macOS and /// its apps make. A `*` stands for any run of characters. Dot-entries are never loose either, and /// what the adopt scan files from home (households, database copies) is /// covered by it. pub const HOME_ALLOWED: &[&str] = &[ "coordinator-handover.md", "ready-to-land.md", "lane-briefs", "mac-ui-helpers", "prod-install-*.sh", "prod-release", "cotton-dsyms", "cotton-frozen-backup", "Code", "CottonDB*", "actions-runner", "Applications", "Desktop", "Documents", "Downloads", "Library", "Movies", "Music", "Pictures", "Public", "Sites", "iCloud Drive*", "OrbStack", ]; /// What a claimed path is. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ClaimKind { Worktree, CargoTarget, Derived, Simulator, Household, Scratch, Evidence, Server, Database, } impl ClaimKind { /// The word the owner's page says. #[must_use] pub fn word(self) -> &'static str { match self { ClaimKind::Worktree => "Worktree", ClaimKind::CargoTarget => "Cargo target", ClaimKind::Derived => "Xcode build data", ClaimKind::Simulator => "Simulator", ClaimKind::Household => "Dev household", ClaimKind::Scratch => "Scratch", ClaimKind::Evidence => "Evidence", ClaimKind::Server => "Server", ClaimKind::Database => "Database copy", } } } /// When a claim lets go of its path. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Rule { /// When the session that made it has ended. SessionEnds, /// When nothing in it has changed for this many hours. IdleHours(u32), /// When the Mac is under its reserve, least recently touched first. BudgetLru, /// When this many newer runs of its series are on the ledger: claims of /// the same kind in the same folder whose rule is `keep_last`, newest by /// when the folder was made (its path breaking a tie). KeepLast(u32), /// Never by rule: only the owner drops it. OwnerOnly, } impl Rule { /// The rule's spelling in a claim file and on the owner's page. #[must_use] pub fn spelled(self) -> String { match self { Rule::SessionEnds => "session_ends".into(), Rule::IdleHours(hours) => format!("idle_hours:{hours}"), Rule::BudgetLru => "budget_lru".into(), Rule::KeepLast(count) => format!("keep_last:{count}"), Rule::OwnerOnly => "owner_only".into(), } } /// A rule as spelled, or `None` for one this build does not know — a /// claim whose rule is unknown is kept, never released. #[must_use] pub fn parse(text: &str) -> Option { match text.trim() { "session_ends" => Some(Rule::SessionEnds), "budget_lru" => Some(Rule::BudgetLru), "owner_only" => Some(Rule::OwnerOnly), other => { let count = |prefix: &str| other.strip_prefix(prefix).and_then(|n| n.parse::().ok()).filter(|n| *n > 0); count("idle_hours:").map(Rule::IdleHours).or_else(|| count("keep_last:").map(Rule::KeepLast)) } } } } /// One claim, as its spool file holds it. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Claim { pub path: PathBuf, pub kind: ClaimKind, /// The lane that made it, or `unclaimed` for one the adopt scan found. pub lane: String, /// The session that made it (its tool's own id), when one did. #[serde(default, skip_serializing_if = "Option::is_none")] pub session: Option, /// The rule as spelled ([`Rule::spelled`]). pub rule: String, pub created_at: String, /// Found by the adopt scan rather than claimed by the lane that made it. #[serde(default)] pub adopted: bool, /// A server's process: it is stopped before its path goes. #[serde(default, skip_serializing_if = "Option::is_none")] pub pid: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub bytes: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub measured_at: Option, /// The newest change anywhere under the path, as last measured. #[serde(default, skip_serializing_if = "Option::is_none")] pub touched_at: Option, /// When a pass first saw the owner's Drop on this claim ([`DROP_WAIT`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub drop_asked_at: Option, } impl Claim { /// The claim's id: the same path is always the same claim, so a lane that /// claims again updates its claim rather than adding a second. #[must_use] pub fn id(&self) -> String { claim_id(&self.path) } /// Its rule, or `None` for one this build does not know. #[must_use] pub fn rule(&self) -> Option { Rule::parse(&self.rule) } fn touched(&self) -> Option { self.touched_at.as_deref().and_then(parse_time) } } /// The id of the claim on `path`. #[must_use] pub fn claim_id(path: &Path) -> String { let digest = Sha256::digest(path.as_os_str().as_encoded_bytes()); format!("claim-{}", hex::encode(&digest[..12])) } /// The spool: one JSON file per claim. #[derive(Debug, Clone)] pub struct Spool { pub dir: PathBuf, } impl Spool { /// `~/.cottondb/claims` — where `scripts/lane-claim.sh` writes too. #[must_use] pub fn at_home(home: &Path) -> Spool { Spool { dir: home.join(".cottondb/claims") } } /// Every readable claim, by id. A file that does not parse is skipped and /// left where it is: it is somebody's claim, and losing it would let its /// path be adopted as unclaimed. #[must_use] pub fn claims(&self) -> BTreeMap { let Ok(entries) = std::fs::read_dir(&self.dir) else { return BTreeMap::new(); }; entries .filter_map(Result::ok) .map(|entry| entry.path()) .filter(|path| path.extension().is_some_and(|ext| ext == "json")) .filter_map(|path| std::fs::read(&path).ok()) .filter_map(|bytes| serde_json::from_slice::(&bytes).ok()) .filter(|claim| claim.path.is_absolute()) .map(|claim| (claim.id(), claim)) .collect() } /// Write `claim` under its id, whole (a temporary file, then a rename). pub fn write(&self, claim: &Claim) -> std::io::Result<()> { std::fs::create_dir_all(&self.dir)?; let id = claim.id(); let staged = self.dir.join(format!(".{id}.json.tmp")); let text = serde_json::to_vec_pretty(claim).map_err(std::io::Error::other)?; std::fs::write(&staged, text)?; std::fs::rename(&staged, self.dir.join(format!("{id}.json"))) } /// `~/.cottondb/ledger.log` — every removal the ledger makes, one line /// before it starts and one when it ends ([`Spool::log`]). Beside the /// spool, so any lane on the Mac can read why a folder went. #[must_use] pub fn log_path(&self) -> PathBuf { self.dir.with_file_name("ledger.log") } /// Append one line to the removal log. A log that cannot be written is /// no reason to stop a pass, so the failure is the caller's to ignore. pub fn log(&self, line: &str) -> std::io::Result<()> { use std::io::Write as _; let path = self.log_path(); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path)?; writeln!(file, "{line}") } /// When this Mac's home baseline was set: what stands at the top of home /// made before it was there before the loose-file guard, never flagged. /// The first pass on a Mac writes it (`/../home-baseline`, the /// moment in full) and answers `None`, so that pass flags nothing. #[must_use] pub fn home_baseline(&self, now: SystemTime) -> Option { let marker = self.dir.with_file_name("home-baseline"); if let Some(since) = std::fs::read_to_string(&marker).ok().and_then(|text| parse_time(text.trim())) { return Some(since); } if let Some(parent) = marker.parent() { let _ = std::fs::create_dir_all(parent); } let _ = std::fs::write(&marker, DateTime::::from(now).to_rfc3339_opts(SecondsFormat::Nanos, true)); None } /// Forget the claim `id`. Every file naming the same path goes, so a file /// a script named by another spelling cannot bring it back. pub fn forget(&self, id: &str) { let Ok(entries) = std::fs::read_dir(&self.dir) else { return; }; for path in entries.filter_map(Result::ok).map(|entry| entry.path()) { let names = std::fs::read(&path) .ok() .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) .is_some_and(|claim| claim.id() == id); if names { let _ = std::fs::remove_file(path); } } } } /// Why `path` may never be removed by this ledger, whoever asks, or `None`. /// /// `home` is the account's home folder; `protected` is every folder that holds /// a live database (this Mac's own data directories), which neither a rule nor /// the owner's drop may take — a copy of one may go, the one in use may not. /// `~/CottonDB`, the real Cotton's folder, is always one of them. #[must_use] pub fn refusal(path: &Path, home: &Path, protected: &[PathBuf]) -> Option<&'static str> { if !path.is_absolute() || path.components().any(|part| matches!(part, std::path::Component::ParentDir)) { return Some("not a plain absolute path"); } // THE DAILY COPIES (architect, 21 Oct 2026): a backup copy never sits // where a cleanup rule can reach it — a folder named CottonDB-backups, any // folder inside one and any folder holding one is refused, on any disk. if holds_backups(path) { return Some("a backup disk's copies"); } let tmp = [Path::new("/tmp"), Path::new("/private/tmp"), Path::new("/private/var/folders")]; let under_home = path.starts_with(home) && path != home; let under_tmp = tmp.iter().any(|root| path.starts_with(root) && path != *root); if !under_home && !under_tmp { return Some("outside the home folder and the temporary folders"); } if path.components().count() <= home.components().count() + 1 && path.starts_with(home.join("Library")) { return Some("the Library folder itself"); } let words = path.to_string_lossy().to_ascii_lowercase(); if [".ssh", "keychain", "credential", "secret", ".gnupg", ".cotton-agent"].iter().any(|word| words.contains(word)) { return Some("a credential's folder"); } // The real Cotton's own folder on any Mac, whichever build is asking: a // development build must never reach it (AGENTS.md). let real = home.join("CottonDB"); for live in protected.iter().chain(std::iter::once(&real)) { if path == live || path.starts_with(live) || live.starts_with(path) { return Some("a live database's folder"); } } None } /// The folder the serving app writes its daily copies into, at a backup /// disk's root (`cotton_server::daily_copies::BACKUPS_FOLDER`). pub const BACKUPS_FOLDER: &str = "CottonDB-backups"; /// Whether `path` is, is inside, or holds a backups folder. fn holds_backups(path: &Path) -> bool { path.components().any(|part| part.as_os_str() == BACKUPS_FOLDER) || std::fs::symlink_metadata(path.join(BACKUPS_FOLDER)).is_ok() } /// Where the adopt scan looks, and what it makes of each directory it finds /// there on no claim. #[derive(Debug, Clone)] pub struct Roots { pub home: PathBuf, /// The temporary folder whose `claude-*/` scratchpads are scanned. pub tmp: PathBuf, /// This user's own temporary folder (`$TMPDIR`), whose `tmp.*` (`mktemp -d`) /// and `simserver-*` folders scripts and simulators leave behind. pub user_tmp: PathBuf, /// The checkouts whose `.worktrees/*` are scanned. pub checkouts: Vec, } impl Roots { /// Every directory a lane may have left, with the claim it is adopted as. #[must_use] pub fn found(&self) -> Vec<(PathBuf, ClaimKind, Rule)> { let cache = self.home.join(".cache/cottondb"); let mut found = Vec::new(); // Regenerable build output: a cold build is all its loss costs. for (dir, kind) in [ ("rust/targets", ClaimKind::CargoTarget), ("cargo-target", ClaimKind::CargoTarget), ("derived", ClaimKind::Derived), ("xcframework", ClaimKind::Derived), ] { for path in children(&cache.join(dir)) { found.push((path, kind, Rule::BudgetLru)); } } for branch in children(&cache.join("ios-smoke")) { for path in children(&branch) { found.push((path, ClaimKind::Evidence, Rule::BudgetLru)); } } // A lane's series of runs keeps its newest few (architect's survey of // one Mac, 10 Oct 2026): walk evidence, and the release walk's runs // beside its build output. for path in children(&cache.join("walks")) { found.push((path, ClaimKind::Evidence, Rule::KeepLast(KEEP_RUNS))); } for path in children(&cache.join("release-walk")) { let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default(); if name.starts_with("run-") { found.push((path, ClaimKind::Evidence, Rule::KeepLast(KEEP_RUNS))); } else if name.starts_with("build-") { found.push((path, ClaimKind::Derived, Rule::BudgetLru)); } else if name == "target" { found.push((path, ClaimKind::CargoTarget, Rule::BudgetLru)); } } // The home sweep's archive: what a cleanup parked from the top of // home, with its INDEX.md, kept a week to look through (coordinator, // 10 Oct 2026) — never a lane folder. for path in children(&cache) { if path.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.starts_with("home-sweep-")) { found.push((path, ClaimKind::Scratch, Rule::IdleHours(SWEEP_IDLE_HOURS))); } } // A lane's own folders — its folder (`~/.cache/cottondb/`), a // checkout's `.worktrees/*` and an agent's `.claude/worktrees/agent-*` // — are never owner_only, and they are NOT a cache with no session: // a lane's folder has a session sitting in it (a coding agent's // process, a tmux pane) and a git worktree registered on its // checkout. So it is adopted `session_ends`, judged by that // liveness ([`Liveness`]): while it lives nothing takes it, and once // it does not the budget may. The cargo target inside it is a budget // claim of its own, so a full Mac takes the build before the work. // (10 Oct 2026: a live, idle lane's worktree went while its session // sat in it.) let special = ["rust", "cargo-target", "derived", "xcframework", "ios-smoke", "ci-simulators", "sccache", "walks", "release-walk"]; let mut lanes: Vec = children(&cache) .into_iter() .filter(|path| { let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default(); !special.contains(&name) && !name.starts_with("home-sweep-") }) .collect(); for checkout in &self.checkouts { lanes.extend(children(&checkout.join(".worktrees"))); lanes.extend( children(&checkout.join(".claude/worktrees")) .into_iter() .filter(|path| path.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.starts_with("agent-"))), ); } for lane in lanes { let targets = build_outputs(&lane); found.push((lane, ClaimKind::Worktree, Rule::SessionEnds)); found.extend(targets.into_iter().map(|target| (target, ClaimKind::CargoTarget, Rule::BudgetLru))); } // The copies lanes make carry the rules their makers claim them with // (owner, 10 Oct 2026: no owner todo for cleanup ever again). Adopted, // a copy has no session to end, so it goes after its idle hours; a // cut is one of a series, the newest few kept. // A CI runner's home (`~/CottonDB-runner`) is the live runner, never a // database copy, though its name reads like one. let runners = self.runner_homes(); for path in children(&self.home) { let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default(); if runners.contains(&path) { continue; } else if name.starts_with("CottonDev-QA-") || name.starts_with("CottonDevHousehold") { found.push((path, ClaimKind::Household, Rule::IdleHours(72))); } else if is_database_copy(name) { found.push((path, ClaimKind::Database, Rule::IdleHours(72))); } } for path in children(&self.home.join("prod-release")) { found.push((path, ClaimKind::Evidence, Rule::KeepLast(KEEP_RUNS))); } for app in children(&self.home.join("cotton-dsyms")) { for path in children(&app) { found.push((path, ClaimKind::Evidence, Rule::IdleHours(720))); } } // A CI runner's run folders (`/work/`): a series, its // newest few kept and never one a running job works in. Nothing else // under the runner — its registration, config and binaries — is // scanned (a build box's cleanup agent, 10 Oct 2026: 96 old runs, 7.1 GB). for runner in &runners { for path in children(&runner.join("work")) { found.push((path, ClaimKind::Scratch, Rule::KeepLast(KEEP_RUNS))); } } // Xcode's DerivedData: regenerable build output, ~2.5 GB left by each // CI run after its work folder is gone (a build box, 10 Oct 2026). One whose // run folder is gone goes at once ([`orphaned`]). for path in children(&self.home.join("Library/Developer/Xcode/DerivedData")) { found.push((path, ClaimKind::Derived, Rule::BudgetLru)); } for path in children(&self.home.join("Library/Developer/CoreSimulator/Devices")) { found.push((path, ClaimKind::Simulator, Rule::OwnerOnly)); } // What `mktemp -d` and the simulator server leave in this user's own // temporary folder: hundreds a week on a busy Mac (one Mac held 193 // and 466 of them, 15 GB). Throwaway, so released by the budget. for path in children(&self.user_tmp) { let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default(); if name.starts_with("tmp.") || name.starts_with("simserver-") { found.push((path, ClaimKind::Scratch, Rule::BudgetLru)); } } // A coding agent's scratchpads: `/claude-/`, one // claim per project folder. for root in children(&self.tmp) { let name = root.file_name().and_then(|name| name.to_str()).unwrap_or_default(); if name.starts_with("claude-") { for path in children(&root) { found.push((path, ClaimKind::Scratch, Rule::OwnerOnly)); } } } found } /// The CI runners' homes in home: a folder holding a runner's /// registration (`.runner`), or named `*-runner` (`~/CottonDB-runner`). #[must_use] pub fn runner_homes(&self) -> Vec { children(&self.home) .into_iter() .filter(|path| { path.join(".runner").is_file() || path.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.ends_with("-runner")) }) .collect() } /// Is this Xcode build data an orphan of a finished CI run — its /// `info.plist` names a workspace inside a runner's `work/` that is /// gone? Build data with no readable `WorkspacePath`, or built anywhere /// else, is no orphan: it stays on the budget. #[must_use] pub fn orphaned(&self, claim: &Claim) -> bool { if claim.kind != ClaimKind::Derived { return false; } let Some(workspace) = std::fs::read_to_string(claim.path.join("info.plist")).ok().and_then(|text| workspace_path(&text)) else { return false; }; self.runner_homes().iter().any(|runner| { let work = runner.join("work"); let Ok(rest) = workspace.strip_prefix(&work) else { return false }; match rest.components().next() { Some(std::path::Component::Normal(id)) => std::fs::symlink_metadata(work.join(id)).is_err(), _ => false, } }) } /// What a session left loose at the top of home since `since`: every file /// or folder made after it (its birth time, else its last change) that is /// no dot-entry, no [`HOME_ALLOWED`] name and nothing [`Roots::found`] /// files (a household, a database copy). Never a symlink. In name order. #[must_use] pub fn loose(&self, since: SystemTime) -> Vec { let Ok(entries) = std::fs::read_dir(&self.home) else { return Vec::new(); }; let mut found: Vec = entries .filter_map(Result::ok) .filter(|entry| { let name = entry.file_name(); let name = name.to_string_lossy(); let Ok(kind) = entry.file_type() else { return false }; let scanned = kind.is_dir() && (name.starts_with("CottonDev-QA-") || name.starts_with("CottonDevHousehold") || is_database_copy(&name)); (kind.is_dir() || kind.is_file()) && !name.starts_with('.') && !name.ends_with(".lock.d") && !home_allowed(&name) && !scanned }) .filter(|entry| { entry .metadata() .ok() .and_then(|meta| meta.created().or_else(|_| meta.modified()).ok()) .is_some_and(|made| made > since) }) .map(|entry| entry.path()) .collect(); found.sort(); found } } /// The `WorkspacePath` an Xcode DerivedData `info.plist` (XML) names, or /// `None` for one that names none or is not XML. fn workspace_path(plist: &str) -> Option { let after = &plist[plist.find("WorkspacePath")? + "WorkspacePath".len()..]; let value = after.trim_start().strip_prefix("")?; let value = &value[..value.find("")?]; let text = value.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&"); let path = PathBuf::from(text.trim()); (path.is_absolute() && !path.components().any(|part| matches!(part, std::path::Component::ParentDir))).then_some(path) } /// Is `name` on [`HOME_ALLOWED`]? fn home_allowed(name: &str) -> bool { HOME_ALLOWED.iter().any(|allowed| match allowed.split_once('*') { Some((head, tail)) => name.len() >= head.len() + tail.len() && name.starts_with(head) && name.ends_with(tail), None => name == *allowed, }) } /// The cargo targets a lane's cache holds where its builds put them: at its /// root, under `crates/`, and the same inside a lane folder's `worktree/`. fn build_outputs(lane: &Path) -> Vec { ["target", "crates/target", "worktree/target", "worktree/crates/target"] .iter() .map(|rest| lane.join(rest)) .filter(|path| std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_dir())) .collect() } /// May a claim of kind `inner` stand inside one of kind `outer`? Only a cargo /// target inside a worktree: build output the budget takes before the work /// around it. Every other claim inside a claim is that claim's. fn nests(outer: ClaimKind, inner: ClaimKind) -> bool { outer == ClaimKind::Worktree && inner == ClaimKind::CargoTarget } /// The `keep_last` claims newer runs of their series replaced: per series (one /// kind in one folder), every claim past its count, newest first by when its /// folder was made, its path breaking a tie. fn superseded(claims: &BTreeMap) -> BTreeSet { /// One run of a series: when it was made, its path, its id, its count. type SeriesRun<'a> = (SystemTime, &'a Path, &'a String, u32); let mut series: BTreeMap<(ClaimKind, PathBuf), Vec>> = BTreeMap::new(); for (id, claim) in claims { if let Some(Rule::KeepLast(count)) = claim.rule() { let folder = claim.path.parent().map(Path::to_path_buf).unwrap_or_default(); series.entry((claim.kind, folder)).or_default().push((made_at(claim), &claim.path, id, count)); } } let mut replaced = BTreeSet::new(); for runs in series.values_mut() { runs.sort_by(|a, b| (b.0, b.1).cmp(&(a.0, a.1))); for (rank, (_, _, id, count)) in runs.iter().enumerate() { if rank >= *count as usize { replaced.insert((*id).clone()); } } } replaced } /// When a claim's folder was made: its birth time on disk (its last change on /// a volume that keeps none), else when it was claimed. An adopted claim's /// `created_at` is when the scan found it, not when its run made it. fn made_at(claim: &Claim) -> SystemTime { std::fs::symlink_metadata(&claim.path) .ok() .and_then(|meta| meta.created().or_else(|_| meta.modified()).ok()) .or_else(|| parse_time(&claim.created_at)) .unwrap_or(SystemTime::UNIX_EPOCH) } /// A folder in the home folder that holds a copy of a database: the moves' /// and rehearsals' clones. The live one is refused by [`refusal`]. fn is_database_copy(name: &str) -> bool { name.starts_with("CottonDB") || name.contains("rehearsal") || name.ends_with("-move") } /// The directories directly under `dir` (never a symlink), in name order. fn children(dir: &Path) -> Vec { let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new(); }; let mut found: Vec = entries .filter_map(Result::ok) .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) .map(|entry| entry.path()) .filter(|path| { let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default(); !name.contains(".partial.") && !name.ends_with(".lock.d") && !name.starts_with('.') }) .collect(); found.sort(); found } /// Is a claim held by a job right now — a cargo target whose /// `.lock.d/pid` names a live pid, or a lock whose pid cannot be read /// (a job between its `mkdir` and its write)? fn held(path: &Path, alive: &dyn Fn(u32) -> bool) -> bool { let mut lock = path.as_os_str().to_owned(); lock.push(".lock.d"); let lock = PathBuf::from(lock); if !lock.is_dir() { return false; } match std::fs::read_to_string(lock.join("pid")).ok().and_then(|text| text.trim().parse::().ok()) { Some(pid) => alive(pid), None => true, } } /// A path's size on disk (allocated blocks, so a sparse or cloned file counts /// what it holds) and the newest change anywhere under it. Symlinks are /// counted as themselves and never followed. #[must_use] pub fn measure(path: &Path) -> (u64, SystemTime) { use std::os::unix::fs::MetadataExt; let mut bytes = 0u64; let mut newest = SystemTime::UNIX_EPOCH; let mut stack = vec![path.to_path_buf()]; while let Some(next) = stack.pop() { let Ok(meta) = std::fs::symlink_metadata(&next) else { continue; }; bytes = bytes.saturating_add(meta.blocks().saturating_mul(512)); if let Ok(modified) = meta.modified() { newest = newest.max(modified); } if meta.is_dir() { if let Ok(entries) = std::fs::read_dir(&next) { stack.extend(entries.filter_map(Result::ok).map(|entry| entry.path())); } } } (bytes, newest) } /// What on this Mac is ALIVE in a folder, read once for a pass. /// /// **A FOLDER SOMETHING LIVES IN IS NEVER REMOVED**, by any rule or by the /// budget, whoever claimed it and however: a lane's worktree has a session /// even when no row names one and nothing in it has changed for a day. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Liveness { /// Every git worktree registered on a checkout and not prunable (its /// folder is there): [`registered_worktrees`]. pub worktrees: Vec, /// The working folder of every live process of this user — a coding /// agent's process, a shell — and of every tmux pane. pub sessions: Vec, /// What is alive could not be read (the process list did not answer, or a /// checkout's git did not list its worktrees): every folder is held for /// this pass, since a folder must never go on a guess that nothing lives /// in it. pub unread: bool, } impl Liveness { /// Why `path` is alive, or `None`: a registered worktree at or inside it, /// or a live process or pane working at or inside it. Never the reverse — /// a process sitting in home does not hold every folder under home. #[must_use] pub fn holds(&self, path: &Path) -> Option<&'static str> { if self.unread { Some("what is alive on this Mac could not be read") } else if self.worktrees.iter().any(|tree| tree.starts_with(path)) { Some("a git worktree is registered in it") } else if self.sessions.iter().any(|dir| dir.starts_with(path)) { Some("a live process or tmux pane works in it") } else { None } } } /// The worktrees `git worktree list --porcelain` names that are registered /// and NOT prunable: each block's `worktree `, unless the block says /// `prunable` (its folder is gone) or `bare`. #[must_use] pub fn registered_worktrees(porcelain: &str) -> Vec { porcelain .split("\n\n") .filter(|block| !block.lines().any(|line| line == "bare" || line == "prunable" || line.starts_with("prunable "))) .filter_map(|block| block.lines().find_map(|line| line.strip_prefix("worktree "))) .map(PathBuf::from) .collect() } /// What became of a session, as this Mac's file says. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SessionFate { Ended, Live, /// No row names it: kept, since a claim must never go on a guess. Unknown, } /// Why a claim was released. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Reason { Dropped, SessionEnded, Idle(u32), /// Newer runs of its series replaced it; the count its series keeps. Superseded(u32), /// Xcode build data whose CI run folder is gone ([`Roots::orphaned`]). Orphaned, Budget, } impl Reason { #[must_use] pub fn words(&self) -> String { match self { Reason::Dropped => "the owner dropped it".into(), Reason::SessionEnded => "its session ended".into(), Reason::Idle(hours) => format!("unchanged for {hours} hours"), Reason::Superseded(1) => "a newer one replaced it".into(), Reason::Superseded(count) => format!("{count} newer ones replaced it"), Reason::Orphaned => "the run that built it is gone".into(), Reason::Budget => "the Mac was under its reserve".into(), } } } /// What a pass hands its executors and reads back from the machine. pub struct Machine<'a> { pub roots: &'a Roots, /// Folders holding a live database ([`refusal`]). pub protected: &'a [PathBuf], pub now: SystemTime, pub reserve_gb: f64, /// Whether a pid is a live process. pub alive: &'a dyn Fn(u32) -> bool, /// Where the jobs running now work: their processes' working folders. A /// claim one of them works in, or inside one of them, is held ([`in_use`]); /// every other claim is measured and released as if no job ran. pub working: &'a [PathBuf], /// What is alive in which folder ([`Liveness`]): a claim it holds is in /// use, whatever its rule. pub live: &'a Liveness, /// What became of a session. pub session: &'a dyn Fn(&str) -> SessionFate, /// The volume's free space now, read again after every release. pub free_gb: &'a mut dyn FnMut() -> f64, /// Remove a claim's path: a directory, or a simulator through its tool. pub remove: &'a mut dyn FnMut(&Claim) -> Result<(), String>, /// Measure a path ([`measure`] on a real Mac). pub measure: &'a mut dyn FnMut(&Path) -> (u64, SystemTime), } /// What one pass did, and every claim it left standing (the rows to mirror). #[derive(Debug, Clone, Default, PartialEq)] pub struct PassReport { pub claims: BTreeMap, pub adopted: Vec, pub released: Vec<(Claim, Reason)>, /// Claims gone from under their spool: forgotten. pub vanished: Vec, /// Adopted claims the scan no longer makes (a folder it now reads as a /// series, or as a cache's parts): forgotten with their paths untouched, /// and their rows taken off the owner's page. pub forgotten: Vec, /// A release that was asked for and refused or failed, with why. pub refused: Vec<(String, String)>, /// Claims the owner dropped that wait out [`DROP_WAIT`] before they go. pub drops_pending: Vec, /// What a session left loose at the top of home, adopted in this pass /// ([`Roots::loose`]): each listed once, since a claim is not flagged /// again. The owner hears of each through Feedback. pub loose: Vec, pub free_before_gb: f64, pub free_after_gb: f64, } impl PassReport { /// The one log line, or `None` when nothing was released or refused. #[must_use] pub fn sentence(&self) -> Option { if self.released.is_empty() && self.refused.is_empty() { return None; } let freed: u64 = self.released.iter().filter_map(|(claim, _)| claim.bytes).sum(); let mut line = format!( "ledger: released {} claim{} (~{:.1} GB) \u{2014} {:.0} GB free, was {:.0}", self.released.len(), if self.released.len() == 1 { "" } else { "s" }, freed as f64 / 1e9, self.free_after_gb, self.free_before_gb, ); if !self.refused.is_empty() { line.push_str(&format!("; {} not released", self.refused.len())); } Some(line) } } /// One pass of the ledger over this Mac. `drops` is every claim id the owner /// asks to drop (from the synced rows), carried out once it has stood /// [`DROP_WAIT`]; `measure_limit` caps how many claims /// are measured in this pass, so a first pass over a full Mac does not hold /// the runner for an hour. pub fn pass(spool: &Spool, machine: &mut Machine<'_>, drops: &BTreeSet, measure_limit: usize) -> PassReport { let mut report = PassReport { free_before_gb: (machine.free_gb)(), ..PassReport::default() }; let mut claims = spool.claims(); // 1. A claim whose path is gone has nothing left to release. let vanished: Vec = claims .iter() .filter(|(_, claim)| std::fs::symlink_metadata(&claim.path).is_err()) .map(|(id, _)| id.clone()) .collect(); for id in &vanished { claims.remove(id); spool.forget(id); } report.vanished = vanished; // 2. Adopt what nobody claimed. A claim adopted before takes the scan's // kind and rule as they stand now: the rule belongs to what the folder // is, and an adopted claim was never its maker's to rule. let stamp = iso(machine.now); let mut found = machine.roots.found(); // What a session left loose in home since this Mac's baseline (none on // the first pass, which sets it): scratch, gone after its idle hours. let loose: BTreeSet = spool.home_baseline(machine.now).map(|since| machine.roots.loose(since)).unwrap_or_default().into_iter().collect(); found.extend(loose.iter().map(|path| (path.clone(), ClaimKind::Scratch, Rule::IdleHours(LOOSE_IDLE_HOURS)))); // An adoption the scan no longer makes (`~/.cache/cottondb/release-walk` // was one lane folder; its runs are a series now) would hold everything // inside it off the ledger: it is forgotten, and its path is not touched. let scanned: BTreeSet = found.iter().map(|(path, _, _)| claim_id(path)).collect(); let stale: Vec = claims .iter() .filter(|(id, claim)| claim.adopted && !scanned.contains(*id)) .map(|(id, _)| id.clone()) .collect(); for id in &stale { claims.remove(id); spool.forget(id); } report.forgotten = stale; for (path, kind, rule) in found { if refusal(&path, &machine.roots.home, machine.protected).is_some() { continue; } if let Some(adopted) = claims.get_mut(&claim_id(&path)).filter(|claim| claim.adopted) { if adopted.rule != rule.spelled() || adopted.kind != kind { adopted.rule = rule.spelled(); adopted.kind = kind; let _ = spool.write(adopted); } continue; } // Inside a claim, or holding one (a lane claims its whole folder; // what it holds is that claim's, never a second listing of it) — // except a cargo target inside a worktree ([`nests`]). let covered = claims.values().any(|claim| { (path.starts_with(&claim.path) && !nests(claim.kind, kind)) || (claim.path.starts_with(&path) && !nests(kind, claim.kind)) }); if covered { continue; } let claim = Claim { path, kind, lane: "unclaimed".into(), session: None, rule: rule.spelled(), created_at: stamp.clone(), adopted: true, pid: None, bytes: None, measured_at: None, touched_at: None, drop_asked_at: None, }; if spool.write(&claim).is_ok() { if loose.contains(&claim.path) { report.loose.push(claim.path.clone()); } report.adopted.push(claim.id()); claims.insert(claim.id(), claim); } } // 3. Measure the claims least recently measured, up to the limit. let mut stale: Vec<(String, Option)> = claims .iter() .map(|(id, claim)| (id.clone(), claim.measured_at.as_deref().and_then(parse_time))) .filter(|(_, at)| at.is_none_or(|at| machine.now.duration_since(at).unwrap_or_default() >= MEASURE_EVERY)) .collect(); stale.sort_by_key(|(_, at)| *at); for (id, _) in stale.into_iter().take(measure_limit) { let Some(claim) = claims.get_mut(&id) else { continue }; let (bytes, touched) = (machine.measure)(&claim.path); claim.bytes = Some(bytes); claim.touched_at = Some(iso(touched)); claim.measured_at = Some(stamp.clone()); let _ = spool.write(claim); } // 4. The owner's drops stand one wait before they are carried out. let mut dropped_now = BTreeSet::new(); for (id, claim) in claims.iter_mut() { let asked = claim.drop_asked_at.as_deref().and_then(parse_time); match (drops.contains(id), asked) { (true, None) => { claim.drop_asked_at = Some(stamp.clone()); let _ = spool.write(claim); report.drops_pending.push(id.clone()); } (true, Some(at)) if machine.now.duration_since(at).unwrap_or_default() >= DROP_WAIT => { dropped_now.insert(id.clone()); } (true, Some(_)) => report.drops_pending.push(id.clone()), (false, Some(_)) => { claim.drop_asked_at = None; let _ = spool.write(claim); } (false, None) => {} } } // 5. Release: the owner's drops, then each rule, then the budget. let mut releases: Vec<(String, Reason)> = Vec::new(); let replaced = superseded(&claims); for (id, claim) in &claims { let reason = if dropped_now.contains(id) { Some(Reason::Dropped) } else if drops.contains(id) { None } else if !in_use(claim, machine) { match claim.rule() { Some(Rule::SessionEnds) => claim .session .as_deref() .filter(|session| (machine.session)(session) == SessionFate::Ended) .map(|_| Reason::SessionEnded), Some(Rule::IdleHours(hours)) => claim .touched() .filter(|touched| machine.now.duration_since(*touched).unwrap_or_default() >= Duration::from_secs(u64::from(hours) * 3600)) .map(|_| Reason::Idle(hours)), Some(Rule::KeepLast(count)) => replaced.contains(id).then_some(Reason::Superseded(count)), Some(Rule::BudgetLru) => machine.roots.orphaned(claim).then_some(Reason::Orphaned), Some(Rule::OwnerOnly) | None => None, } } else { None }; if let Some(reason) = reason { releases.push((id.clone(), reason)); } } for (id, reason) in releases { release(spool, machine, &mut claims, &mut report, &id, reason); } if (machine.free_gb)() < machine.reserve_gb { // Least recently touched first; at an equal touch, build output // before the folder that holds it. let mut budget: Vec<(String, (SystemTime, bool))> = claims .iter() .filter(|(_, claim)| by_budget(claim, machine) && !in_use(claim, machine)) .map(|(id, claim)| { let build = matches!(claim.kind, ClaimKind::CargoTarget | ClaimKind::Derived); (id.clone(), (claim.touched().unwrap_or(SystemTime::UNIX_EPOCH), !build)) }) .collect(); budget.sort_by_key(|(_, order)| *order); for (id, _) in budget { if (machine.free_gb)() >= machine.reserve_gb { break; } release(spool, machine, &mut claims, &mut report, &id, Reason::Budget); } } report.free_after_gb = (machine.free_gb)(); report.claims = claims; report } /// Does the budget take this claim under the reserve? A `budget_lru` claim, /// and a `session_ends` one whose session is not known to live — it ended (a /// release that failed is tried again here), or no row names it: a lane's /// cache goes by its session while that lives, then by the budget, and is /// never kept for ever. fn by_budget(claim: &Claim, machine: &Machine<'_>) -> bool { match claim.rule() { Some(Rule::BudgetLru) => true, Some(Rule::SessionEnds) => claim.session.as_deref().is_none_or(|session| (machine.session)(session) != SessionFate::Live), _ => false, } } /// A claim a rule must not take now: held by a job (its lock, or a running /// job working in it), a server still running, alive ([`Liveness`]: a /// registered git worktree in it, or a live process or tmux pane working in /// it), or touched within the grace (or never measured, so its last touch is /// not known yet). fn in_use(claim: &Claim, machine: &Machine<'_>) -> bool { if held(&claim.path, machine.alive) || claim.pid.is_some_and(|pid| (machine.alive)(pid)) { return true; } if worked_in(&claim.path, machine.working, &machine.roots.home) { return true; } if machine.live.holds(&claim.path).is_some() { return true; } claim .touched() .is_none_or(|touched| machine.now.duration_since(touched).unwrap_or_default() < Duration::from_secs(GRACE_SECS)) } /// Does a running job work in this claim — a working folder inside it, or the /// claim inside a job's working folder (a checkout whose build writes its /// target)? A job working in home itself, or above it, holds nothing by that /// alone: it would hold every claim on the Mac. fn worked_in(path: &Path, working: &[PathBuf], home: &Path) -> bool { working .iter() .any(|dir| dir.starts_with(path) || (!home.starts_with(dir) && path.starts_with(dir))) } fn release( spool: &Spool, machine: &mut Machine<'_>, claims: &mut BTreeMap, report: &mut PassReport, id: &str, reason: Reason, ) { let Some(claim) = claims.get(id).cloned() else { return }; if std::fs::symlink_metadata(&claim.path).is_err() { claims.remove(id); spool.forget(id); report.vanished.push(id.to_string()); return; } if let Some(why) = refusal(&claim.path, &machine.roots.home, machine.protected) { report.refused.push((id.to_string(), why.to_string())); return; } // A server still running is stopped by its lane, never by a guess at // which process it is: its claim waits until the pid is gone. if claim.pid.is_some_and(|pid| (machine.alive)(pid)) { report.refused.push((id.to_string(), "its server is still running".into())); return; } // THE LAST CHECK BEFORE A FOLDER GOES, whatever asked for it — the owner's // drop included: a folder something lives in is not removed. if let Some(why) = machine.live.holds(&claim.path) { report.refused.push((id.to_string(), why.to_string())); return; } // EVERY REMOVAL IS WRITTEN DOWN BEFORE IT STARTS, with its path, claim, // rule and reason, where any lane can read it ([`Spool::log_path`]): a // folder that went with no line saying why is a folder nobody can // account for. let shown = format!( "{} claim={} kind={} lane={} rule={} reason=\"{}\"", claim.path.display(), id, claim.kind.word().to_lowercase().replace(' ', "_"), claim.lane, claim.rule, reason.words(), ); let _ = spool.log(&format!("{} removing {shown}", iso(SystemTime::now()))); let removed = (machine.remove)(&claim); let _ = spool.log(&match &removed { Ok(()) => format!("{} removed {}", iso(SystemTime::now()), claim.path.display()), Err(error) => format!("{} not removed {}: {error}", iso(SystemTime::now()), claim.path.display()), }); match removed { Ok(()) => { // What stood inside it (a worktree's target) went with it. let inside: Vec = claims .iter() .filter(|(other, held)| other.as_str() != id && held.path.starts_with(&claim.path)) .map(|(other, _)| other.clone()) .collect(); for other in inside { if let Some(held) = claims.remove(&other) { spool.forget(&other); report.released.push((held, reason.clone())); } } claims.remove(id); spool.forget(id); report.released.push((claim, reason)); } Err(error) => report.refused.push((id.to_string(), error)), } } /// A moment as the spool and the rows spell it. #[must_use] pub fn iso(at: SystemTime) -> String { DateTime::::from(at).to_rfc3339_opts(SecondsFormat::Secs, true) } fn parse_time(text: &str) -> Option { DateTime::parse_from_rfc3339(text).ok().map(SystemTime::from) } #[cfg(test)] #[path = "ledger_tests.rs"] mod tests;