Cotton code
920 lines · 49.3 KB · RustRaw
use super::*;use std::cell::RefCell;const HOUR: Duration = Duration::from_secs(3600);/// A home folder on a temp directory, with its spool and scan roots.struct Fixture {    _dir: tempfile::TempDir,    home: PathBuf,    spool: Spool,    roots: Roots,    /// The one instant every `touch` counts back from: two touches of the same age are equal even when a second ticks between them.    now: SystemTime,}fn fixture() -> Fixture {    // Under /tmp itself, whatever $TMPDIR says: a rule refuses anything outside home and the temporary folders, and a    // box whose $TMPDIR is a lane's own folder (/srv/lanes/…) would make every scratch path look like one it refuses.    let dir = tempfile::tempdir_in("/tmp").unwrap();    let home = dir.path().join("home");    std::fs::create_dir_all(&home).unwrap();    let tmp = dir.path().join("tmp");    std::fs::create_dir_all(&tmp).unwrap();    let spool = Spool::at_home(&home);    // Canonical, as the Mac app hands it in (`/private/var/folders/…`).    let user_tmp = dir.path().canonicalize().unwrap().join("T");    std::fs::create_dir_all(&user_tmp).unwrap();    let roots = Roots { home: home.clone(), tmp, user_tmp, checkouts: vec![] };    Fixture { _dir: dir, home, spool, roots, now: SystemTime::now() }}fn make(path: &Path) -> PathBuf {    std::fs::create_dir_all(path).unwrap();    std::fs::write(path.join("bytes"), vec![7u8; 4096]).unwrap();    path.to_path_buf()}fn claim(path: &Path, kind: ClaimKind, rule: &str, session: Option<&str>) -> Claim {    Claim {        path: path.to_path_buf(),        kind,        lane: "lane-a".into(),        session: session.map(str::to_string),        rule: rule.into(),        created_at: "2026-10-01T00:00:00Z".into(),        adopted: false,        pid: None,        bytes: None,        measured_at: None,        touched_at: None,        drop_asked_at: None,    }}/// One pass on a fake disk: `free` GB free, each release adding `freed` GB,/// every path last touched `idle` before now, session `ended` ended.struct Run {    free: f64,    freed: f64,    idle: Duration,    ended: &'static [&'static str],    /// Sessions no row names.    unknown: &'static [&'static str],    alive: &'static [u32],    reserve: f64,    /// Where the jobs running now work.    working: Vec<PathBuf>,    /// What is alive in which folder.    live: Liveness,}impl Default for Run {    fn default() -> Self {        Run { free: 500.0, freed: 10.0, idle: 48 * HOUR, ended: &[], unknown: &[], alive: &[], reserve: 60.0, working: vec![], live: Liveness::default() }    }}fn run(fx: &Fixture, drops: &[&str], config: Run) -> (PassReport, Vec<PathBuf>) {    let now = SystemTime::now();    let free = RefCell::new(config.free);    let removed = RefCell::new(Vec::new());    let alive = |pid: u32| config.alive.contains(&pid);    let session = |id: &str| {        if config.ended.contains(&id) {            SessionFate::Ended        } else if config.unknown.contains(&id) {            SessionFate::Unknown        } else {            SessionFate::Live        }    };    let mut free_gb = || *free.borrow();    let mut remove = |claim: &Claim| {        removed.borrow_mut().push(claim.path.clone());        if claim.path.is_dir() {            std::fs::remove_dir_all(&claim.path).map_err(|error| error.to_string())?;        } else {            std::fs::remove_file(&claim.path).map_err(|error| error.to_string())?;        }        *free.borrow_mut() += config.freed;        Ok(())    };    let idle = config.idle;    let mut measure = |path: &Path| (measure(path).0, now - idle);    let mut machine = Machine {        roots: &fx.roots,        protected: &[],        now,        reserve_gb: config.reserve,        alive: &alive,        working: &config.working,        live: &config.live,        session: &session,        free_gb: &mut free_gb,        remove: &mut remove,        measure: &mut measure,    };    let drops: BTreeSet<String> = drops.iter().map(|id| id.to_string()).collect();    let report = pass(&fx.spool, &mut machine, &drops, usize::MAX);    let removed = removed.into_inner();    (report, removed)}/// RULE: the ledger removes only a path on a claim; a folder outside every claim and every scanned root is never touched, even with the disk under its reserve./// Storage note c7d20613, 10 Oct 2026: deletion is routine only when one list decides it, never an agent alone.#[test]fn nothing_off_the_ledger_is_ever_removed() {    let fx = fixture();    let stray = make(&fx.home.join("Documents/own-work"));    let target = make(&fx.home.join(".cache/cottondb/rust/targets/old-branch"));    let (report, removed) = run(&fx, &[], Run { free: 5.0, freed: 0.0, ..Run::default() });    assert!(stray.exists(), "a folder on no claim and in no scanned root stays");    assert_eq!(removed, vec![target], "only the adopted build output went");    assert!(report.claims.values().all(|claim| claim.path != stray));}/// RULE: an owner_only claim is never released by a rule, however full the disk; only the owner's drop releases it./// Storage note c7d20613: what only the owner can judge is shown with its size and goes on his Drop (copies lanes make and lane caches are not that, since 10 Oct 2026).#[test]fn an_owner_only_claim_goes_only_when_the_owner_drops_it() {    let fx = fixture();    let kept = make(&fx.home.join("keep-this"));    let residue = make(&fx.home.join("Library/Developer/CoreSimulator/Devices/5F2E-0A1B"));    let ended = make(&fx.home.join("scratch-ended"));    fx.spool.write(&claim(&kept, ClaimKind::Evidence, "owner_only", None)).unwrap();    fx.spool.write(&claim(&ended, ClaimKind::Scratch, "owner_only", Some("gone-session"))).unwrap();    let (report, removed) = run(&fx, &[], Run { free: 1.0, freed: 0.0, idle: 9000 * HOUR, ended: &["gone-session"], ..Run::default() });    assert!(removed.is_empty(), "no rule takes an owner_only claim: {removed:?}");    let adopted: Vec<&Claim> = report.claims.values().filter(|claim| claim.adopted).collect();    assert!(adopted.iter().any(|claim| claim.path == residue && claim.lane == "unclaimed" && claim.kind == ClaimKind::Simulator && claim.rule == "owner_only"));    let (report, removed) = run(&fx, &[&claim_id(&kept)], Run::default());    assert!(removed.is_empty(), "a Drop first stands its wait");    assert_eq!(report.drops_pending, vec![claim_id(&kept)]);    age_drop(&fx, &kept);    let (_, removed) = run(&fx, &[&claim_id(&kept)], Run::default());    assert_eq!(removed, vec![kept], "the owner's drop releases it");    assert!(residue.exists() && ended.exists());}/// Make a claim's Drop as old as the wait.fn age_drop(fx: &Fixture, path: &Path) {    let mut c = fx.spool.claims().remove(&claim_id(path)).unwrap();    c.drop_asked_at = Some(iso(SystemTime::now() - DROP_WAIT - Duration::from_secs(1)));    fx.spool.write(&c).unwrap();}/// RULE: the owner's Drop is carried out only after it has stood DROP_WAIT, and a Drop switched off within it keeps the path./// A switch asks no question; the wait is the owner's chance to take an accidental Drop back from the phone.#[test]fn a_drop_switched_off_within_its_wait_keeps_the_path() {    let fx = fixture();    let copy = make(&fx.home.join("CottonDB.v48"));    let id = claim_id(&copy);    run(&fx, &[&id], Run::default());    age_drop(&fx, &copy);    let (_, removed) = run(&fx, &[], Run::default());    assert!(removed.is_empty() && copy.exists());    assert!(fx.spool.claims()[&id].drop_asked_at.is_none(), "switched off, the wait starts again");}/// RULE: a Mac under its reserve releases budget claims least recently touched first until it is back over, and never one a job holds./// Storage note c7d20613: a full Mac must free itself without anyone choosing by hand, and never under a running build.#[test]fn under_the_reserve_budget_claims_go_oldest_first_until_it_is_enough() {    let fx = fixture();    let old = make(&fx.home.join("build/old"));    let newer = make(&fx.home.join("build/newer"));    let held_target = make(&fx.home.join("build/held"));    std::fs::create_dir_all(fx.home.join("build/held.lock.d")).unwrap();    std::fs::write(fx.home.join("build/held.lock.d/pid"), "4242").unwrap();    for path in [&old, &newer, &held_target] {        fx.spool.write(&claim(path, ClaimKind::CargoTarget, "budget_lru", None)).unwrap();    }    // Measured with distinct last touches, oldest first.    for (path, hours) in [(&old, 300u64), (&newer, 100), (&held_target, 500)] {        let mut c = fx.spool.claims().remove(&claim_id(path)).unwrap();        c.touched_at = Some(iso(fx.now - Duration::from_secs(hours * 3600)));        c.measured_at = Some(iso(SystemTime::now()));        fx.spool.write(&c).unwrap();    }    let (report, removed) = run(&fx, &[], Run { free: 55.0, freed: 10.0, alive: &[4242], ..Run::default() });    assert_eq!(removed, vec![old.clone()], "one release was enough, and it was the least recently touched free one");    assert_eq!(report.released[0].1, Reason::Budget);    assert!(newer.exists() && held_target.exists());    // Over the reserve, nothing is released by the budget.    let (_, removed) = run(&fx, &[], Run { free: 200.0, alive: &[4242], ..Run::default() });    assert!(removed.is_empty());}/// RULE: while a job runs, the pass skips only the claims that job works in; every other claim is measured and released by its rule and the budget as if no job ran./// Architect's read, 10 Oct 2026: a Mac that never idles released nothing while any job ran.#[test]fn a_running_job_holds_only_the_claims_it_works_in() {    let fx = fixture();    let checkout = make(&fx.home.join("lanes/busy"));    let target = make(&checkout.join("target"));    let unheld = make(&fx.home.join("lanes/idle/target"));    for path in [&target, &unheld] {        fx.spool.write(&claim(path, ClaimKind::CargoTarget, "budget_lru", None)).unwrap();    }    // The job works in its checkout, whose build writes the target; another works in home itself.    let working = vec![checkout.clone(), fx.home.clone()];    let (report, removed) = run(&fx, &[], Run { free: 10.0, freed: 1.0, working, ..Run::default() });    assert_eq!(removed, vec![unheld.clone()], "the budget releases the claim no job works in, and only it");    assert!(target.exists(), "the running job's target is held");    let held = report.claims.get(&claim_id(&target)).expect("the held claim stays on the ledger");    assert!(held.measured_at.is_some(), "a held claim is still measured");    assert_eq!(report.released.len(), 1);}/// RULE: what `mktemp -d` and the simulator server leave in `$TMPDIR` (`tmp.*`, `simserver-*`) is adopted as budget scratch and released under the reserve; nothing else there is adopted./// One Mac held 193 `tmp.*` and 466 `simserver-*` folders (15 GB) on no claim, 10 Oct 2026.#[test]fn what_mktemp_and_the_simulator_server_leave_is_budget_scratch() {    let fx = fixture();    let leftover = make(&fx.roots.user_tmp.join("tmp.Ab12Cd"));    let server = make(&fx.roots.user_tmp.join("simserver-5f2e"));    let other = make(&fx.roots.user_tmp.join("com.apple.something"));    let (report, removed) = run(&fx, &[], Run { free: 10.0, freed: 1.0, ..Run::default() });    for path in [&leftover, &server] {        assert!(report.adopted.contains(&claim_id(path)), "{} is adopted", path.display());    }    assert!(!report.adopted.contains(&claim_id(&other)), "nothing else in $TMPDIR is adopted");    assert_eq!(removed.len(), 2, "under the reserve both go by the budget");    assert!(other.exists());}#[test]fn a_session_claim_goes_when_its_session_ends_and_an_idle_one_after_its_hours() {    let fx = fixture();    let evidence = make(&fx.home.join("lane/evidence"));    let scratch = make(&fx.home.join("lane/scratch"));    fx.spool.write(&claim(&evidence, ClaimKind::Evidence, "session_ends", Some("s-1"))).unwrap();    fx.spool.write(&claim(&scratch, ClaimKind::Scratch, "idle_hours:72", None)).unwrap();    let (_, removed) = run(&fx, &[], Run { idle: 48 * HOUR, ..Run::default() });    assert!(removed.is_empty(), "a live session and 48 idle hours keep both");    let (report, removed) = run(&fx, &[], Run { idle: 48 * HOUR, ended: &["s-1"], ..Run::default() });    assert_eq!(removed, vec![evidence]);    assert_eq!(report.released[0].1, Reason::SessionEnded);    // Measured again only after MEASURE_EVERY: age the measurement first.    let mut c = fx.spool.claims().remove(&claim_id(&scratch)).unwrap();    c.measured_at = None;    fx.spool.write(&c).unwrap();    let (_, removed) = run(&fx, &[], Run { idle: 80 * HOUR, ..Run::default() });    assert_eq!(removed, vec![scratch]);}#[test]fn a_claim_touched_within_the_grace_is_kept_whatever_its_rule() {    let fx = fixture();    let fresh = make(&fx.home.join("lane/fresh"));    fx.spool.write(&claim(&fresh, ClaimKind::Evidence, "session_ends", Some("s-1"))).unwrap();    let (_, removed) = run(&fx, &[], Run { idle: Duration::from_secs(60), ended: &["s-1"], ..Run::default() });    assert!(removed.is_empty());}/// RULE: the ledger refuses home itself, anything outside home and the temporary folders, a credential's folder, the real data folder and every live database folder — whether a rule or the owner's drop asks./// AGENTS.md: a development build never touches the real Cotton's folder; the 10 Oct removal guard keeps the places that must never be deleted.#[test]fn the_places_that_must_never_go_are_refused_whoever_asks() {    let home = Path::new("/Users/someone");    let live = vec![PathBuf::from("/Users/someone/CottonDev")];    for path in [        "/Users/someone",        "/Users",        "/Applications/CottonDB.app",        "/Users/someone/CottonDB",        "/Users/someone/CottonDB/media",        "/Users/someone/CottonDev/files",        "/Users/someone/.ssh",        "/Users/someone/Library",        "/Users/someone/Library/Keychains/login.keychain-db",        "/Users/someone/.cache/../CottonDB",    ] {        assert!(refusal(Path::new(path), home, &live).is_some(), "{path} must be refused");    }    for path in [        "/Users/someone/CottonDB.moved-20261004T091415Z",        "/Users/someone/cotton-rehearsal",        "/Users/someone/.cache/cottondb/notes4",        "/private/tmp/claude-501/scratch",    ] {        assert_eq!(refusal(Path::new(path), home, &live), None, "{path} may go when its rule or the owner says");    }}/// RULE: a copy a lane made is never owner_only, adopted or claimed — households and database copies go after 72 idle hours, a cut keeps its series' newest 3, kept dSYMs go after 720 — and an owner_only adoption takes the scan's rule next pass./// Owner, 10 Oct 2026: personal data is off the Macs; no owner todo for cleanup ever again (one Mac held 93 owner_only rows).#[test]fn an_adopted_copy_goes_by_its_idle_hours_and_old_adoptions_are_re_ruled() {    let fx = fixture();    let qa = make(&fx.home.join("CottonDev-QA-3c0e65aca"));    let rehearsal = make(&fx.home.join("cotton-rehearsal"));    let cut = make(&fx.home.join("prod-release/1b1e05eb4"));    let dsym = make(&fx.home.join("cotton-dsyms/mac/0.4.11-17"));    // One Mac's shape: the rehearsal adopted owner_only by an earlier build.    let mut old = claim(&rehearsal, ClaimKind::Database, "owner_only", None);    old.lane = "unclaimed".into();    old.adopted = true;    fx.spool.write(&old).unwrap();    let (report, _) = run(&fx, &[], Run { idle: Duration::from_secs(2 * 3600), ..Run::default() });    let rule = |path: &Path| report.claims.get(&claim_id(path)).map(|claim| claim.rule.clone());    assert_eq!(rule(&qa).as_deref(), Some("idle_hours:72"));    assert_eq!(rule(&rehearsal).as_deref(), Some("idle_hours:72"), "the old owner_only adoption is re-ruled");    assert_eq!(rule(&cut).as_deref(), Some("keep_last:3"));    assert_eq!(rule(&dsym).as_deref(), Some("idle_hours:720"));    // A claim its maker wrote keeps the maker's rule.    let made = make(&fx.home.join("CottonDB-move"));    fx.spool.write(&claim(&made, ClaimKind::Database, "session_ends", Some("s-1"))).unwrap();    let (report, _) = run(&fx, &[], Run::default());    assert_eq!(report.claims.get(&claim_id(&made)).map(|claim| claim.rule.as_str()), Some("session_ends"));    // Past its idle hours, the adopted rehearsal and household go by rule.    for path in [&rehearsal, &qa] {        let mut aged = fx.spool.claims().remove(&claim_id(path)).unwrap();        aged.measured_at = None;        fx.spool.write(&aged).unwrap();    }    let (_, removed) = run(&fx, &[], Run { idle: 80 * HOUR, ..Run::default() });    assert!(removed.contains(&rehearsal) && removed.contains(&qa));}#[test]fn the_real_cotton_folder_is_never_adopted_and_a_lanes_own_claim_is_not_listed_twice() {    let fx = fixture();    let real = make(&fx.home.join("CottonDB"));    let lane = make(&fx.home.join(".cache/cottondb/ledger"));    let worktree = make(&lane.join("worktree"));    fx.spool.write(&claim(&lane, ClaimKind::Worktree, "session_ends", Some("s-9"))).unwrap();    let (report, _) = run(&fx, &[&claim_id(&real)], Run::default());    run(&fx, &[&claim_id(&real)], Run::default());    assert!(real.exists(), "a drop asked of the real folder is refused");    assert!(report.claims.values().all(|claim| claim.path != real && claim.path != worktree));    assert_eq!(report.claims.values().filter(|claim| claim.path == lane).count(), 1);}#[test]fn a_claim_whose_path_is_gone_is_forgotten_and_a_rule_unknown_to_this_build_keeps_it() {    let fx = fixture();    let gone = fx.home.join("lane/gone");    let odd = make(&fx.home.join("lane/odd"));    fx.spool.write(&claim(&gone, ClaimKind::Scratch, "session_ends", Some("s"))).unwrap();    fx.spool.write(&claim(&odd, ClaimKind::Scratch, "pull_lands", None)).unwrap();    let (report, removed) = run(&fx, &[], Run { free: 1.0, ended: &["s"], ..Run::default() });    assert_eq!(report.vanished, vec![claim_id(&gone)]);    assert!(removed.is_empty() && odd.exists());    assert!(!fx.spool.claims().contains_key(&claim_id(&gone)));}#[test]fn rules_read_as_they_are_spelled() {    for rule in [Rule::SessionEnds, Rule::IdleHours(24), Rule::BudgetLru, Rule::KeepLast(3), Rule::OwnerOnly] {        assert_eq!(Rule::parse(&rule.spelled()), Some(rule));    }    assert_eq!(Rule::parse("keep_last:3"), Some(Rule::KeepLast(KEEP_RUNS)));    assert_eq!(Rule::parse("idle_hours:0"), None);    assert_eq!(Rule::parse("keep_last:0"), None);    assert_eq!(Rule::parse("whenever"), None);}/// RULE: a claim's id is the first 24 hex of the SHA-256 of its path, exactly as scripts/lane-claim.sh names its file, so a lane's claim and the ledger's are one claim./// The script writes claims and the app reads them; two spellings of one id would list one folder twice and release it by the wrong rule.#[test]fn a_claims_id_is_the_one_lane_claim_sh_writes() {    assert_eq!(claim_id(Path::new("/Users/someone/.cache/cottondb/ledger")), "claim-6b9db5b77f569d346b459dd0");}/// Set a claim's last touch to `hours` ago, measured now (so the pass keeps it).fn touch(fx: &Fixture, path: &Path, hours: u64) {    // One instant for every touch of a test: two touches "at an equal hour"    // read apart by a clock tick across a second were not equal (run 9014).    static AT: std::sync::OnceLock<SystemTime> = std::sync::OnceLock::new();    let at = *AT.get_or_init(SystemTime::now);    let mut c = fx.spool.claims().remove(&claim_id(path)).unwrap();    c.touched_at = Some(iso(at - Duration::from_secs(hours * 3600)));    c.measured_at = Some(iso(SystemTime::now()));    fx.spool.write(&c).unwrap();}/// Make each folder in turn, a moment apart, so their birth times are in order.fn make_in_order(dir: &Path, names: &[&str]) -> Vec<PathBuf> {    names        .iter()        .map(|name| {            std::thread::sleep(Duration::from_millis(20));            make(&dir.join(name))        })        .collect()}/// RULE: a lane's walk evidence keeps its series' newest three runs (keep_last:3): older ones go at once, disk full or not, never one a job works in; adopted and claimed runs are one series./// Architect's survey of one Mac, 10 Oct 2026: walk:board writes 1.7 GB every 20 minutes, a 360 GB backlog under its old idle_hours:72.#[test]fn walk_evidence_keeps_its_newest_three_runs() {    let fx = fixture();    let walks = fx.home.join(".cache/cottondb/walks");    let runs = make_in_order(        &walks,        &["release-20261009T230000Z", "board-20261010T010000Z", "board-20261010T012000Z", "board-20261010T014000Z", "board-20261010T020000Z"],    );    // The oldest was never claimed (adopted into the series); walk-board.sh claimed the rest.    for path in &runs[1..] {        let mut c = claim(path, ClaimKind::Evidence, "keep_last:3", None);        c.lane = "walk".into();        fx.spool.write(&c).unwrap();    }    // A job still works in the oldest claimed run.    let (report, removed) = run(&fx, &[], Run { working: vec![runs[1].clone()], ..Run::default() });    assert_eq!(removed, vec![runs[0].clone()], "over the reserve, the run past the newest three goes, but not the one a job works in");    assert_eq!(report.released[0].1, Reason::Superseded(3));    assert_eq!(report.released[0].1.words(), "3 newer ones replaced it");    assert!(report.claims.values().all(|claim| claim.path != walks), "the walks folder is no lane folder");    let (_, removed) = run(&fx, &[], Run::default());    assert_eq!(removed, vec![runs[1].clone()], "the job gone, it goes too");    assert!(runs[2..].iter().all(|path| path.exists()), "the newest three stay");}/// RULE: a lane's own folders — its ~/.cache/cottondb folder, a checkout's .worktrees/* and .claude/worktrees/agent-* — are adopted session_ends, never owner_only; a session_ends claim nothing lives in and whose session is not live goes by the budget./// Architect's survey of one Mac, 10 Oct 2026: 119 of 150 claims were owner_only, so the sweep never reclaimed a finished lane. Adopted budget_lru until 11 Oct, when a live lane's worktree went (`a_live_worktree_survives_a_pass_under_the_reserve`).#[test]fn a_lanes_cache_goes_by_the_budget_and_is_never_owner_only() {    let mut fx = fixture();    let checkout = fx.home.join("Code/cottondb");    fx.roots.checkouts = vec![checkout.clone()];    let lane = make(&fx.home.join(".cache/cottondb/notes4"));    let worktree = make(&checkout.join(".worktrees/feat-x"));    let agent = make(&checkout.join(".claude/worktrees/agent-a64333dac"));    let not_agent = make(&checkout.join(".claude/worktrees/scratch"));    let unknown = make(&checkout.join(".worktrees/unknown-session"));    let live = make(&checkout.join(".worktrees/live-session"));    // One Mac's shape: the lane folder adopted owner_only by an earlier build.    let mut old = claim(&lane, ClaimKind::Worktree, "owner_only", None);    old.lane = "unclaimed".into();    old.adopted = true;    fx.spool.write(&old).unwrap();    fx.spool.write(&claim(&unknown, ClaimKind::Worktree, "session_ends", Some("s-gone"))).unwrap();    fx.spool.write(&claim(&live, ClaimKind::Worktree, "session_ends", Some("s-live"))).unwrap();    let (report, removed) = run(&fx, &[], Run { unknown: &["s-gone"], ..Run::default() });    assert!(removed.is_empty(), "over the reserve a cache stays");    for path in [&lane, &worktree, &agent] {        let c = report.claims.get(&claim_id(path)).expect("adopted");        assert_eq!((c.kind, c.rule.as_str()), (ClaimKind::Worktree, "session_ends"), "{}", path.display());    }    assert!(!report.claims.contains_key(&claim_id(&not_agent)), "only an agent's worktree is scanned there");    assert_eq!(report.claims[&claim_id(&unknown)].rule, "session_ends", "a maker's claim keeps its rule");    let (_, mut removed) = run(&fx, &[], Run { free: 1.0, freed: 0.0, unknown: &["s-gone"], ..Run::default() });    removed.sort();    let mut expected = vec![lane, worktree, agent, unknown];    expected.sort();    assert_eq!(removed, expected, "under the reserve every cache goes, the one whose session no row names too");    assert!(live.exists() && not_agent.exists(), "a live session's worktree stays");}/// RULE: a cargo target inside a lane's folder or worktree is a budget claim of its own, taken before the work around it at an equal touch; releasing the worktree still takes all of it./// Architect's survey of one Mac, 10 Oct 2026: board's incremental build cache (44 GB) sat inside its lane folder, off the budget.#[test]fn a_lanes_build_cache_is_a_budget_claim_of_its_own() {    let mut fx = fixture();    let checkout = fx.home.join("Code/cottondb");    fx.roots.checkouts = vec![checkout.clone()];    let board = make(&fx.home.join(".cache/cottondb/board"));    let board_target = make(&board.join("worktree/crates/target"));    fx.spool.write(&claim(&board, ClaimKind::Worktree, "session_ends", Some("s-live"))).unwrap();    let feat = make(&checkout.join(".worktrees/feat-x"));    let feat_target = make(&feat.join("target"));    let agent = make(&checkout.join(".claude/worktrees/agent-1"));    let agent_target = make(&agent.join("crates/target"));    let (report, removed) = run(&fx, &[], Run::default());    assert!(removed.is_empty());    for path in [&board_target, &feat_target, &agent_target] {        let c = report.claims.get(&claim_id(path)).expect("a target inside a worktree is adopted");        assert_eq!((c.kind, c.rule.as_str()), (ClaimKind::CargoTarget, "budget_lru"), "{}", path.display());    }    assert!(report.claims.contains_key(&claim_id(&feat)) && report.claims.contains_key(&claim_id(&agent)));    // At an equal touch, the build goes before the worktree that holds it.    for (path, hours) in [(&feat, 300), (&feat_target, 300), (&agent, 100), (&agent_target, 100), (&board_target, 100)] {        touch(&fx, path, hours);    }    let (_, removed) = run(&fx, &[], Run { free: 55.0, freed: 10.0, ..Run::default() });    assert_eq!(removed, vec![feat_target.clone()]);    assert!(feat.exists() && board.join("worktree").exists());    // The least recently touched worktree goes whole, its target with it.    touch(&fx, &agent, 900);    let (report, removed) = run(&fx, &[], Run { free: 55.0, freed: 10.0, ..Run::default() });    assert_eq!(removed, vec![agent.clone()]);    assert!(!agent.exists());    assert!(report.released.iter().any(|(c, why)| c.path == agent_target && *why == Reason::Budget), "its target is released with it");    assert!(report.refused.is_empty() && !report.claims.contains_key(&claim_id(&agent_target)));    assert!(board_target.exists(), "the live lane's target is still on the budget, not taken with anything");}/// RULE: a cut in ~/prod-release and a release-walk run keep their series' newest 3; release-walk's build-* and target are budget build output; an adoption the scan no longer makes is forgotten, its path untouched./// Architect's survey of one Mac, 10 Oct 2026: cuts went by idle_hours:168 and release-walk was one owner_only lane folder.#[test]fn cuts_and_release_walk_runs_keep_their_newest_three() {    let fx = fixture();    let base = fx.home.join(".cache/cottondb/release-walk");    std::fs::create_dir_all(&base).unwrap();    // An earlier build adopted the whole folder as one lane.    let mut old = claim(&base, ClaimKind::Worktree, "owner_only", None);    old.lane = "unclaimed".into();    old.adopted = true;    fx.spool.write(&old).unwrap();    // Named by commit, so only their birth tells which is newest.    let cuts = make_in_order(&fx.home.join("prod-release"), &["f00d1e2e3", "a11b2c3d4", "c22d3e4f5", "b33e4f5a6", "e44f5a6b7"]);    std::fs::write(fx.home.join("prod-release/a11b2c3d4-cut.log"), "log").unwrap();    let runs = make_in_order(&base, &["run-9f4fe8da6-a5sQ", "run-1b1e05eb4-2HB6", "run-041e91caf-AyBk", "run-7aa7df349-dr0H"]);    let build = make(&base.join("build-1b1e05eb492899b90779b6731bba083d7bf7057d"));    let target = make(&base.join("target"));    let (report, mut removed) = run(&fx, &[], Run::default());    assert_eq!(report.forgotten, vec![claim_id(&base)], "the old adoption is forgotten");    assert!(base.exists());    removed.sort();    let mut expected = vec![cuts[0].clone(), cuts[1].clone(), runs[0].clone()];    expected.sort();    assert_eq!(removed, expected, "each series keeps its newest three");    assert!(report.released.iter().all(|(_, why)| *why == Reason::Superseded(3)));    assert!(cuts[2..].iter().chain(&runs[1..]).all(|path| path.exists()));    let rule = |path: &Path| report.claims.get(&claim_id(path)).map(|claim| (claim.kind, claim.rule.clone()));    assert_eq!(rule(&build), Some((ClaimKind::Derived, "budget_lru".into())));    assert_eq!(rule(&target), Some((ClaimKind::CargoTarget, "budget_lru".into())));    assert_eq!(rule(&runs[3]), Some((ClaimKind::Evidence, "keep_last:3".into())));}/// Make each entry at the top of home in turn, a moment apart: a name ending/// `/` a folder, any other a file.fn leave_in_home(fx: &Fixture, names: &[&str]) -> Vec<PathBuf> {    names        .iter()        .map(|name| {            std::thread::sleep(Duration::from_millis(20));            match name.strip_suffix('/') {                Some(folder) => make(&fx.home.join(folder)),                None => {                    let path = fx.home.join(name);                    std::fs::write(&path, "scratch").unwrap();                    path                }            }        })        .collect()}/// RULE: a new non-dot file or folder at the top of ~ that no allow-list name or other scan covers is claimed scratch idle_hours:72 and listed once; one made before the Mac's baseline, an allowed name and a dot-entry are not./// Owner, 10 Oct 2026: sessions write scratch under their scratchpad or into Cotton, never loose into ~; a home sweep parked ~440 loose files per Mac.#[test]fn what_a_session_leaves_loose_in_home_is_claimed_and_listed_once() {    let fx = fixture();    let before = leave_in_home(&fx, &["old-notes.md", "old-out/"]);    // The first pass sets the baseline and flags nothing.    let (report, _) = run(&fx, &[], Run::default());    assert!(report.loose.is_empty(), "the first pass only sets the baseline");    assert!(fx.home.join(".cottondb/home-baseline").is_file());    let left = leave_in_home(        &fx,        &[            "scratch.txt",            "session-out/",            "ready-to-land.md",            "coordinator-handover.md",            "prod-install-0.4.12.sh",            "lane-briefs/",            "mac-ui-helpers/",            "cotton-frozen-backup/",            "Code/",            "Desktop/",            "actions-runner/",            ".zsh_history",            ".hidden-out/",            "CottonDB.v99/",            "CottonDev-QA-1a2b3c/",            "cotton-rehearsal/",        ],    );    let (scratch, out) = (&left[0], &left[1]);    let (report, removed) = run(&fx, &[], Run::default());    assert!(removed.is_empty());    assert_eq!(report.loose, vec![scratch.clone(), out.clone()], "only the two loose entries are listed");    for path in [scratch, out] {        let c = &report.claims[&claim_id(path)];        assert_eq!((c.kind, c.rule.as_str(), c.adopted), (ClaimKind::Scratch, "idle_hours:72", true), "{}", path.display());    }    for path in before.iter().chain(&left[2..13]) {        assert!(!report.claims.contains_key(&claim_id(path)), "{} is not loose", path.display());    }    // The household and the database copies stay the adopt scan's, by their own rules.    for path in &left[13..] {        let c = &report.claims[&claim_id(path)];        assert_ne!(c.kind, ClaimKind::Scratch, "{}", path.display());    }    // A claim now, it is never flagged again.    let (report, _) = run(&fx, &[], Run::default());    assert!(report.loose.is_empty(), "nothing is listed twice");    assert!(report.claims.contains_key(&claim_id(scratch)) && report.claims.contains_key(&claim_id(out)));}/// RULE: a file or folder a session left loose at the top of ~ goes on its own once it has stood 72 idle hours — a plain file removed as a file — and the baseline's older entries stay./// Owner, 10 Oct 2026: sessions write scratch under their scratchpad or into Cotton, never loose into ~; a home sweep parked ~440 loose files per Mac.#[test]fn a_loose_entry_in_home_goes_after_72_idle_hours() {    let fx = fixture();    let before = leave_in_home(&fx, &["kept.md"]);    run(&fx, &[], Run::default());    let left = leave_in_home(&fx, &["scratch.txt", "session-out/"]);    let (_, removed) = run(&fx, &[], Run { idle: 71 * HOUR, ..Run::default() });    assert!(removed.is_empty(), "within its 72 hours it stays");    for path in &left {        let mut c = fx.spool.claims().remove(&claim_id(path)).unwrap();        c.measured_at = None;        fx.spool.write(&c).unwrap();    }    let (report, mut removed) = run(&fx, &[], Run { idle: 73 * HOUR, ..Run::default() });    removed.sort();    assert_eq!(removed, left);    assert!(left.iter().all(|path| !path.exists()), "the file and the folder are gone");    assert!(report.released.iter().all(|(_, why)| *why == Reason::Idle(72)));    assert!(before[0].exists(), "what stood before the baseline stays");}#[test]fn the_home_allow_list_reads_its_patterns() {    for name in ["prod-install-0.4.12.sh", "CottonDB", "CottonDB.v48", "iCloud Drive (Archive)", "Library"] {        assert!(home_allowed(name), "{name}");    }    for name in ["prod-install-0.4.12.txt", "prod-install-", "scratch.txt", "Codex", "library"] {        assert!(!home_allowed(name), "{name}");    }}/// RULE: the home sweep's archive (~/.cache/cottondb/home-sweep-*) is adopted scratch idle_hours:168, never a budget lane folder — an earlier lane adoption is re-ruled — and it goes after a week unchanged./// Coordinator, 10 Oct 2026: the sweep parked ~440 loose files per Mac with an INDEX.md; a week to look before it goes.#[test]fn the_home_sweep_archive_goes_after_a_week_idle() {    let fx = fixture();    let sweep = make(&fx.home.join(".cache/cottondb/home-sweep-20261010"));    std::fs::write(sweep.join("INDEX.md"), "what was parked, and from where").unwrap();    let older = make(&fx.home.join(".cache/cottondb/home-sweep-20261003"));    // An earlier build adopted it as a lane's folder, under the budget.    let mut old = claim(&older, ClaimKind::Worktree, "budget_lru", None);    old.lane = "unclaimed".into();    old.adopted = true;    fx.spool.write(&old).unwrap();    let (report, removed) = run(&fx, &[], Run { free: 1.0, freed: 0.0, idle: 160 * HOUR, ..Run::default() });    assert!(removed.is_empty(), "under the reserve and within its week, the archive stays");    for path in [&sweep, &older] {        let c = &report.claims[&claim_id(path)];        assert_eq!((c.kind, c.rule.as_str(), c.adopted), (ClaimKind::Scratch, "idle_hours:168", true), "{}", path.display());    }    for path in [&sweep, &older] {        let mut c = fx.spool.claims().remove(&claim_id(path)).unwrap();        c.measured_at = None;        fx.spool.write(&c).unwrap();    }    let (report, mut removed) = run(&fx, &[], Run { idle: 170 * HOUR, ..Run::default() });    removed.sort();    assert_eq!(removed, vec![older, sweep], "a week unchanged, it goes");    assert!(report.released.iter().all(|(_, why)| *why == Reason::Idle(SWEEP_IDLE_HOURS)));}/// A CI runner's home as a build box holds it: its registration, config and binaries,/// and `work/` holding one folder per run, made in the order given.fn runner_home(fx: &Fixture, runs: &[&str]) -> (PathBuf, Vec<PathBuf>) {    let runner = make(&fx.home.join("CottonDB-runner"));    std::fs::write(runner.join(".runner"), "{\"uuid\":\"registration\"}").unwrap();    std::fs::write(runner.join("config.yml"), "runner:\n  capacity: 1\n").unwrap();    make(&runner.join("bin"));    let runs = make_in_order(&runner.join("work"), runs);    (runner, runs)}/// RULE: a CI runner's run folders (~/<runner>/work/*) keep their newest 3, never one a job works in; the runner itself, its .runner, config.yml and binaries are never claimed, nor read as a database copy./// A build box's cleanup agent, 10 Oct 2026: ~/CottonDB-runner is the live runner, and its work/ kept 96 old run folders (7.1 GB).#[test]fn a_runners_old_runs_keep_their_newest_three_and_the_runner_is_never_claimed() {    let fx = fixture();    let (runner, runs) = runner_home(&fx, &["1001", "1002", "1003", "1004", "1005"]);    // An earlier build read the runner's name as a database copy's.    let mut old = claim(&runner, ClaimKind::Database, "idle_hours:72", None);    old.lane = "unclaimed".into();    old.adopted = true;    fx.spool.write(&old).unwrap();    // A job still works in the oldest run; the disk is full.    let (report, removed) = run(&fx, &[], Run { free: 1.0, freed: 0.0, idle: 9000 * HOUR, working: vec![runs[0].clone()], ..Run::default() });    assert_eq!(report.forgotten, vec![claim_id(&runner)], "the old adoption of the runner is forgotten");    assert_eq!(removed, vec![runs[1].clone()], "past the newest three, and not the one a job works in");    assert_eq!(report.released[0].1, Reason::Superseded(KEEP_RUNS));    for path in [runner.join(".runner"), runner.join("config.yml"), runner.join("bin"), runs[0].clone()] {        assert!(path.exists(), "{} stays", path.display());    }    assert!(runs[2..].iter().all(|path| path.exists()), "the newest three stay");    for c in report.claims.values() {        assert!(!c.path.starts_with(&runner) || c.path.parent() == Some(&runner.join("work")), "only a run folder is claimed: {}", c.path.display());        assert_eq!((c.kind, c.rule.as_str()), (ClaimKind::Scratch, "keep_last:3"), "{}", c.path.display());    }    let (_, removed) = run(&fx, &[], Run { free: 1.0, freed: 0.0, idle: 9000 * HOUR, ..Run::default() });    assert_eq!(removed, vec![runs[0].clone()], "the job gone, its run goes too");    assert!(runner.join("config.yml").exists() && runner.join(".runner").exists());}/// Xcode's DerivedData entry `name`, its `info.plist` naming `workspace`.fn derived_data(fx: &Fixture, name: &str, workspace: Option<&Path>) -> PathBuf {    let path = make(&fx.home.join("Library/Developer/Xcode/DerivedData").join(name));    if let Some(workspace) = workspace {        let plist = format!(            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>LastAccessedDate</key>\n\t<date>2026-10-10T08:00:00Z</date>\n\t<key>WorkspacePath</key>\n\t<string>{}</string>\n</dict>\n</plist>\n",            workspace.display()        );        std::fs::write(path.join("info.plist"), plist).unwrap();    }    path}/// RULE: Xcode's DerivedData entries are adopted budget_lru build data; one whose info.plist WorkspacePath is inside a runner's work/<id> that is gone goes at once, disk full or not; any other waits for the reserve./// A build box's cleanup agent, 10 Oct 2026: each CI run leaves ~2.5 GB of DerivedData after its work folder is gone.#[test]fn xcode_build_data_is_budget_output_and_a_finished_runs_goes_at_once() {    let fx = fixture();    let (runner, runs) = runner_home(&fx, &["live-run"]);    let orphan = derived_data(&fx, "Cotton-aaa", Some(&runner.join("work/gone-run/apps/Cotton.xcodeproj")));    let live = derived_data(&fx, "Cotton-bbb", Some(&runs[0].join("apps/Cotton.xcodeproj")));    let unread = derived_data(&fx, "Cotton-ccc", None);    let own = derived_data(&fx, "Cotton-ddd", Some(&fx.home.join("Code/cottondb/apps/Cotton.xcodeproj")));    let (report, removed) = run(&fx, &[], Run::default());    assert_eq!(removed, vec![orphan.clone()], "over the reserve, only the finished run's build data goes");    assert_eq!(report.released[0].1, Reason::Orphaned);    assert_eq!(report.released[0].1.words(), "the run that built it is gone");    assert_eq!((report.released[0].0.kind, report.released[0].0.rule.as_str()), (ClaimKind::Derived, "budget_lru"));    for path in [&live, &unread, &own] {        let c = &report.claims[&claim_id(path)];        assert_eq!((c.kind, c.rule.as_str()), (ClaimKind::Derived, "budget_lru"), "{}", path.display());    }    let (_, mut removed) = run(&fx, &[], Run { free: 1.0, freed: 0.0, ..Run::default() });    removed.sort();    assert_eq!(removed, vec![live, unread, own], "under the reserve the rest go by the budget");    assert!(runs[0].exists(), "the run folder itself is no build data");    let home = Path::new("/Users/someone");    assert_eq!(refusal(Path::new("/Users/someone/Library/Developer/Xcode/DerivedData/Cotton-aaa"), home, &[]), None);    assert!(refusal(Path::new("/Users/someone/Library"), home, &[]).is_some());}#[test]fn a_derived_data_plist_names_its_workspace() {    let xml = "<dict><key>WorkspacePath</key>\n\t<string>/Users/m/CottonDB-runner/work/7/A &amp; B.xcodeproj</string></dict>";    assert_eq!(workspace_path(xml), Some(PathBuf::from("/Users/m/CottonDB-runner/work/7/A & B.xcodeproj")));    assert_eq!(workspace_path("bplist00\u{1}binary"), None);    assert_eq!(workspace_path("<key>WorkspacePath</key><string>relative/x</string>"), None);    assert_eq!(workspace_path("<key>WorkspacePath</key><string>/a/../b</string>"), None);}/// RULE: a folder something lives in is never removed — an adopted lane folder holding a registered, non-prunable git worktree, or the working folder of a live process or tmux pane, survives a pass with the Mac under its reserve, survives the owner's Drop, and is adopted `session_ends` (judged by that liveness), never `budget_lru`./// Incident, 10 Oct 2026 18:33Z: the walk lane's worktree `~/.cache/cottondb/statuses` went on a Mac while its session sat in it, alive and idle. A lane's folder is not "a cache with no session".#[test]fn a_live_worktree_survives_a_pass_under_the_reserve() {    let fx = fixture();    let registered = make(&fx.home.join(".cache/cottondb/statuses"));    make(&registered.join("worktree"));    let sat_in = make(&fx.home.join(".cache/cottondb/board"));    let dead = make(&fx.home.join(".cache/cottondb/gone-lane"));    let live = Liveness { worktrees: vec![registered.join("worktree")], sessions: vec![sat_in.join("worktree/crates")], unread: false };    let under = || Run { free: 5.0, freed: 1.0, idle: 240 * HOUR, live: live.clone(), ..Run::default() };    let (report, removed) = run(&fx, &[], under());    assert_eq!(removed, vec![dead.clone()], "only the folder nothing lives in went: {:?}", report.released);    assert!(registered.join("worktree").is_dir() && sat_in.is_dir());    for path in [&registered, &sat_in] {        let claim = &report.claims[&claim_id(path)];        assert_eq!(claim.rule, "session_ends", "a lane folder is adopted by its session, not the budget");        assert_eq!(claim.kind, ClaimKind::Worktree);    }    // The owner's Drop, stood its wait, is refused too — and says why.    let id = claim_id(&registered);    let mut held = fx.spool.claims()[&id].clone();    held.drop_asked_at = Some(iso(SystemTime::now() - DROP_WAIT - HOUR));    fx.spool.write(&held).unwrap();    let (report, removed) = run(&fx, &[&id], under());    assert!(removed.is_empty(), "a live worktree does not go on a drop: {removed:?}");    assert_eq!(report.refused, vec![(id, "a git worktree is registered in it".to_string())]);    // Once nothing lives in it, it is the budget's under the reserve.    let (_, removed) = run(&fx, &[], Run { free: 5.0, freed: 100.0, idle: 240 * HOUR, ..Run::default() });    assert_eq!(removed.len(), 1, "one release clears the reserve: {removed:?}");    // …and with room to spare, an idle lane folder nothing lives in still stays.    let (_, removed) = run(&fx, &[], Run { idle: 240 * HOUR, ..Run::default() });    assert!(removed.is_empty(), "above the reserve nothing takes a lane folder: {removed:?}");}/// RULE: a claim whose session ended is kept while a live process works in its folder — the next session to take a lane's folder inherits the folder, not the last one's ending./// Incident, 10 Oct 2026 18:37Z (the branch that removed it): `~/.cache/cottondb/statuses` was claimed `session_ends` for a session that ended at 13:34Z; the session started in the same folder six seconds later was alive and idle, nothing re-claimed the folder, and the first pass to read the ended row took the folder with its 115 GB target.#[test]fn an_ended_sessions_folder_is_kept_while_the_next_session_works_in_it() {    let fx = fixture();    let lane = make(&fx.home.join(".cache/cottondb/statuses"));    let tree = make(&lane.join("worktree"));    fx.spool.write(&claim(&lane, ClaimKind::Worktree, "session_ends", Some("s-old"))).unwrap();    let sat_in = Liveness { sessions: vec![tree.clone()], ..Liveness::default() };    let (report, removed) = run(&fx, &[], Run { idle: 48 * HOUR, ended: &["s-old"], live: sat_in.clone(), ..Run::default() });    assert!(removed.is_empty(), "a folder a live process works in does not go with the last session: {:?}", report.released);    // Nor under the reserve, where an ended session's claim is the budget's.    let (_, removed) = run(&fx, &[], Run { free: 5.0, freed: 100.0, idle: 48 * HOUR, ended: &["s-old"], live: sat_in, ..Run::default() });    assert!(removed.is_empty(), "nor by the budget: {removed:?}");    // The process gone, the ended session's folder goes as it always did.    let (report, removed) = run(&fx, &[], Run { idle: 48 * HOUR, ended: &["s-old"], ..Run::default() });    assert_eq!(removed, vec![lane]);    assert_eq!(report.released[0].1, Reason::SessionEnded);}/// RULE: when what is alive on the Mac could not be read, a pass removes nothing — a folder never goes on a guess that nothing lives in it.#[test]fn a_pass_that_cannot_read_what_is_alive_removes_nothing() {    let fx = fixture();    let evidence = make(&fx.home.join("lane/evidence"));    fx.spool.write(&claim(&evidence, ClaimKind::Evidence, "session_ends", Some("s-1"))).unwrap();    make(&fx.home.join(".cache/cottondb/rust/targets/old-branch"));    let blind = Liveness { unread: true, ..Liveness::default() };    let (report, removed) = run(&fx, &[], Run { free: 5.0, freed: 100.0, idle: 240 * HOUR, ended: &["s-1"], live: blind, ..Run::default() });    assert!(removed.is_empty(), "nothing goes unseen: {:?}", report.released);}/// RULE: every removal the ledger performs is written to `~/.cottondb/ledger.log` before it starts — its path, claim id, kind, lane, rule and reason — and again when it ends, so any lane can read why a folder went; a pass that removes nothing writes nothing./// Incident, 10 Oct 2026: a worktree went and no line anywhere said what took it.#[test]fn a_removal_writes_its_log_line() {    let fx = fixture();    let (_, removed) = run(&fx, &[], Run::default());    assert!(removed.is_empty());    assert!(!fx.spool.log_path().exists(), "a quiet pass writes no log");    let target = make(&fx.home.join(".cache/cottondb/rust/targets/old-branch"));    let (report, removed) = run(&fx, &[], Run { free: 5.0, freed: 100.0, ..Run::default() });    assert_eq!(removed, vec![target.clone()]);    assert_eq!(report.released.len(), 1);    assert_eq!(fx.spool.log_path(), fx.home.join(".cottondb/ledger.log"));    let log = std::fs::read_to_string(fx.spool.log_path()).unwrap();    let lines: Vec<&str> = log.lines().collect();    assert_eq!(lines.len(), 2, "{log}");    let id = claim_id(&target);    assert!(lines[0].contains(&format!(" removing {} claim={id} kind=cargo_target lane=unclaimed rule=budget_lru reason=\"the Mac was under its reserve\"", target.display())), "{log}");    assert!(lines[1].ends_with(&format!(" removed {}", target.display())), "{log}");}#[test]fn the_registered_worktrees_are_the_ones_whose_folder_is_there() {    let porcelain = "worktree /Users/a/Code/repo\nHEAD abc\nbranch refs/heads/main\n\n\                     worktree /Users/a/.cache/cottondb/board/worktree\nHEAD def\nbranch refs/heads/board\n\n\                     worktree /Users/a/.cache/cottondb/old/worktree\nHEAD 123\ndetached\nprunable gitdir file points to non-existent location\n\n\                     worktree /Users/a/bare.git\nbare\n";    assert_eq!(        registered_worktrees(porcelain),        [PathBuf::from("/Users/a/Code/repo"), PathBuf::from("/Users/a/.cache/cottondb/board/worktree")]    );    let live = Liveness { worktrees: registered_worktrees(porcelain), sessions: vec![PathBuf::from("/Users/a")], unread: false };    assert!(live.holds(Path::new("/Users/a/.cache/cottondb/board")).is_some());    assert!(live.holds(Path::new("/Users/a/.cache/cottondb/old")).is_none(), "a prunable worktree holds nothing");    assert!(live.holds(Path::new("/Users/a/.cache/cottondb/board/worktree/target")).is_none(), "a build inside a live worktree stays the budget's");}/// GUARD (data safety, architect 21 Oct 2026): the ledger never removes a/// backup copy. The serving app's daily copies live in a CottonDB-backups/// folder on a backup disk; a copy where a cleanup rule could reach it is a/// copy that can vanish the day it is needed — so the folder, anything in it/// and anything holding it is refused wherever it sits, home or temporary.#[test]fn guard_the_ledger_never_reaches_a_backups_folder() {    let home = Path::new("/Users/someone");    for path in [        "/Users/someone/CottonDB-backups",        "/Users/someone/CottonDB-backups/0f0f0f0f-0f0f-4f0f-8f0f-0f0f0f0f0f0f/life.20261021.db",        "/Users/someone/.cache/cottondb/old/CottonDB-backups/media",        "/private/tmp/claude-501/CottonDB-backups",        "/Volumes/Cotton SSD/CottonDB-backups",    ] {        assert!(refusal(Path::new(path), home, &[]).is_some(), "{path} must be refused");    }    let disk = tempfile::tempdir().unwrap();    let holder = disk.path().join("old-disk-image");    std::fs::create_dir_all(holder.join("CottonDB-backups")).unwrap();    assert_eq!(refusal(&holder, home, &[]), Some("a backup disk's copies"), "a folder holding one is refused too");}