#!/usr/bin/env bash # Bound the PER-BRANCH cargo target directories a developer machine collects. # # scripts/sweep-worktree-targets.sh [--dry-run] [--days N] [--budget-gb N] # [--root DIR] [--keep NAME]... [--no-remote] # # WHY IT EXISTS. Until 2026-09-15 every worktree on a machine pointed # `build.target-dir` at ONE directory, and the price was `cargo-target-guard.sh` # touching every crate root whenever the builder changed worktree — a full # workspace rebuild each time parallel agents alternated. `worktree-new.sh` now # gives each BRANCH its own directory under `~/.cache/cottondb/cargo-target`, # named by the same script CI uses, with sccache as the shared layer and # `CARGO_HOME` still shared. That ends the invalidation and buys the CI lanes' # own problem in exchange: a merged branch's directory is never touched again, # and one of them is 15-25 GB. # # So the same three rules the CI sweep applies (`scripts/ci/ # sweep-cargo-targets.sh`, whose header carries the run numbers behind each) # apply here, on the machine a person actually builds on: # # DEAD — the branch is gone from EVERY remote this checkout has. The union, # not `origin`: `origin` here is a MIRROR that only learns a branch # when a "mirror" pull request brings it over, so asking it alone # answered "dead" for branches that were alive on the host — and on # 2026-09-27 this deleted the cargo target directories of two live # branches, which is two full workspace rebuilds. Every remote is # listed and a branch on ANY of them is live. If NO remote can be # listed the rule is OFF for that run: a network failure must not # read as "every branch is dead". A directory written inside the # grace window is spared anyway — a build may be inside it. # AGE — nothing has touched it within `--days` (default 14). The floor, # for a branch still open on the remote and abandoned in fact. # BUDGET — and LAST, the only rule in gigabytes: measure what survived and # evict LEAST-RECENTLY-USED FIRST until the set fits `--budget-gb` # (default 60), whatever their age. The two rules above are proxies # for size and neither can say "60 GB"; this Mac steady-states above # 300 GB free, so 60 holds three or four warm branches and still # leaves the disk alone. # # WHY THE BUDGET HAS ITS OWN, SHORTER GRACE. The dead-branch and age rules spare # anything written in the last `--grace-mins` (60), and that is right for them: # they are optional deletes, and an hour of slack costs nothing. Applied to the # BUDGET it costs everything — on a Mac running four agent worktrees, every # directory is touched inside any hour, so the budget spared all of them and # never evicted anything. Measured on one Mac, 2026-09-22: 120 GB under the root # against a 60 GB budget, one branch holding 88 GB of it, and a dry run that # skipped three directories for grace and stopped. So the budget uses # `--budget-grace-mins` (10) instead: cargo writes into `target//deps` # and `.fingerprint` as each unit finishes, both inside the two levels this # script reads, so ten minutes of total silence means nothing is building there. # # AND THE BUILD LOCK IS ALWAYS SPARED. `scripts/with-build-lock.sh` records the # target-directory name of the branch its holder is building; while that holder # is alive its directory is kept, whatever its mtime and whatever the budget # says. That is the one case a short grace could get wrong — a long link step # writing nothing for ten minutes inside a build somebody is waiting on. # # WHAT COUNTS AS USED is what it is in the CI sweep: anything modified within # two levels — the directory, its children (`debug/`, `.rustc_info.json`) and # its grandchildren (`debug/deps`, `debug/.fingerprint`), which is where a # build's writes land. A top-level mtime can sit still through a whole build. # # WHAT IT WILL NOT DO. Remove anything that does not RESOLVE inside the root. # Resolving is the point: a directory in there that is a symlink to somebody's # checkout is not ours and `rm -rf` would follow it. The root itself is refused, # and so is a path that merely shares the root's prefix. # # WHO RUNS IT. `scripts/disk-guard.sh`, before every build and on its schedule. # By hand whenever you want the number: `--dry-run` says what would go. # # Env: COTTON_CARGO_TARGET_ROOT (default `~/.cache/cottondb/cargo-target`), # COTTON_WORKTREE_TARGETS_STALE_DAYS (14), COTTON_WORKTREE_TARGETS_BUDGET_GB # (60; 0 turns it off) and its exact sibling COTTON_WORKTREE_TARGETS_BUDGET_KB # (unset; wins when both are given), COTTON_WORKTREE_TARGETS_GRACE_MINS (60), # COTTON_WORKTREE_TARGETS_BUDGET_GRACE_MINS (10), BUILD_LOCK_DIR # (`/tmp/tinmen-build.lock`, read for the branch a live holder is building). # # Guard: `scripts/__tests__/sweep-worktree-targets.test.ts`. set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" ROOT="${COTTON_CARGO_TARGET_ROOT:-$HOME/.cache/cottondb/cargo-target}" DAYS="${COTTON_WORKTREE_TARGETS_STALE_DAYS:-14}" BUDGET_GB="${COTTON_WORKTREE_TARGETS_BUDGET_GB:-60}" # THE SAME RULE IN THE UNIT THE SCRIPT MEASURES IN. `du -sk` answers in KiB and # all the arithmetic below is KiB; `--budget-gb` is the human spelling. The KiB # one is named because a gigabyte is not a size a test fixture can reach, and a # budget test whose fixture cannot exceed the budget proves only that the # eviction loop compiles. BUDGET_KB="${COTTON_WORKTREE_TARGETS_BUDGET_KB:-}" GRACE_MINS="${COTTON_WORKTREE_TARGETS_GRACE_MINS:-60}" # THE BUDGET'S OWN GRACE, AND IT IS SHORTER ON PURPOSE — see the header. BUDGET_GRACE_MINS="${COTTON_WORKTREE_TARGETS_BUDGET_GRACE_MINS:-10}" BUILD_LOCK_DIR="${BUILD_LOCK_DIR:-/tmp/tinmen-build.lock}" DRY_RUN=0 REMOTE=1 KEEP=() while [ $# -gt 0 ]; do case "$1" in --dry-run) DRY_RUN=1; shift ;; --days) DAYS="${2-}"; shift 2 ;; --budget-gb) BUDGET_GB="${2-}"; shift 2 ;; --root) ROOT="${2-}"; shift 2 ;; --keep) KEEP+=("${2-}"); shift 2 ;; --grace-mins) GRACE_MINS="${2-}"; shift 2 ;; --budget-grace-mins) BUDGET_GRACE_MINS="${2-}"; shift 2 ;; --no-remote) REMOTE=0; shift ;; *) echo "usage: sweep-worktree-targets.sh [--dry-run] [--days N] [--budget-gb N] [--root DIR] [--keep NAME]... [--grace-mins N] [--budget-grace-mins N] [--no-remote]" >&2 exit 2 ;; esac done ROOT="${ROOT%/}" # shellcheck source=/dev/null . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/owned-root.sh" refuse_wide_root "the worktree targets root (--root / COTTON_CARGO_TARGET_ROOT)" "$ROOT" for pair in "--days:$DAYS" "--budget-gb:$BUDGET_GB" "--grace-mins:$GRACE_MINS" \ "--budget-grace-mins:$BUDGET_GRACE_MINS" \ ${BUDGET_KB:+"COTTON_WORKTREE_TARGETS_BUDGET_KB:$BUDGET_KB"}; do case "${pair#*:}" in ''|*[!0-9]*) echo "sweep-worktree-targets: ${pair%%:*} wants a whole number, got '${pair#*:}'" >&2 exit 2 ;; esac done log() { echo "[sweep-worktree-targets] $*"; } # THE BRANCH A LIVE BUILD-LOCK HOLDER IS BUILDING, ADDED TO THE KEEP LIST. # `scripts/with-build-lock.sh` writes the holder's pid and — since this change — # the target-directory name of the branch it is building. A holder that is dead # says nothing: the lock directory outlives a crashed build, and honouring a # dead holder's name would pin the largest directory on the disk for ever. for lock_slot in "$BUILD_LOCK_DIR" "${BUILD_LOCK_DIR}.slot-2"; do if [ -f "$lock_slot/pid" ] && [ -f "$lock_slot/target" ]; then lock_pid="$(cat "$lock_slot/pid" 2>/dev/null || true)" lock_target="$(cat "$lock_slot/target" 2>/dev/null || true)" if [ -n "$lock_pid" ] && [ -n "$lock_target" ] && kill -0 "$lock_pid" 2>/dev/null; then KEEP+=("$lock_target") log "$lock_target is the branch pid $lock_pid holds the build lock for — keeping it whatever the rules say" fi fi done if [ ! -d "$ROOT" ]; then log "nothing to sweep under $ROOT — it does not exist yet" exit 0 fi ROOT_REAL="$(cd "$ROOT" && pwd -P)" # `stat` reads an mtime with a DIFFERENT FLAG AND FORMAT on each platform, and # GNU's `%m` is the MOUNT POINT rather than a time — so `stat -c '%m'` succeeds, # answers `/`, every directory sorts equal, and an LRU eviction takes whichever # the glob named first. (That cost `scripts/ci/sweep-cargo-targets.sh` run 2404; # its header has the story.) Decide once, by reading a NUMBER, and refuse to run # at all if neither flavour answers one. if [ -n "$(stat -c '%Y' "$ROOT" 2>/dev/null | tr -dc '0-9')" ] && [ -z "$(stat -c '%Y' "$ROOT" 2>/dev/null | tr -d '0-9\n')" ]; then STAT_MTIME=(stat -c '%Y') elif [ -n "$(stat -f '%m' "$ROOT" 2>/dev/null | tr -dc '0-9')" ] && [ -z "$(stat -f '%m' "$ROOT" 2>/dev/null | tr -d '0-9\n')" ]; then STAT_MTIME=(stat -f '%m') else echo "[sweep-worktree-targets] neither 'stat -c %Y' nor 'stat -f %m' reads an mtime here." >&2 echo "[sweep-worktree-targets] refusing to sweep: the budget evicts oldest-first, and an" >&2 echo "[sweep-worktree-targets] order this script cannot read is an order that deletes the wrong one." >&2 exit 1 fi # Ours only if it RESOLVES inside the root, and is not the root. owns_path() { local p="$1" real parent if [ -d "$p" ] && [ ! -L "$p" ]; then real="$(cd "$p" 2>/dev/null && pwd -P)" || return 1 else parent="$(cd "$(dirname "$p")" 2>/dev/null && pwd -P)" || return 1 real="$parent/$(basename "$p")" fi case "$real" in "$ROOT_REAL"/?*) return 0 ;; *) return 1 ;; esac } used_within_mins() { [ -n "$(find "$1" -maxdepth 2 -mmin "-$2" -print -quit 2>/dev/null)" ] } newest_mtime() { local newest newest="$(find "$1" -maxdepth 2 -exec "${STAT_MTIME[@]}" {} + 2>/dev/null | sort -n | tail -1 || true)" case "$newest" in ''|*[!0-9]*) printf '%s\n' 0 ;; *) printf '%s\n' "$newest" ;; esac } kept() { local name="$1" k for k in ${KEEP[@]+"${KEEP[@]}"}; do [ "$name" = "$k" ] && return 0 done return 1 } remove_target() { local dir="$1" why="$2" [ "$(basename "$dir")" != shared ] || return 1 if [ -L "$dir" ] || ! owns_path "$dir"; then echo "[sweep-worktree-targets] refusing to remove '$dir' — it does not resolve inside $ROOT_REAL" >&2 return 1 fi if evidence_kept "$dir"; then return 1; fi if [ "$DRY_RUN" = 1 ]; then log "would remove $dir — $why" return 0 fi rm -rf "$dir" log "removed $dir — $why" return 0 } # THE BRANCHES THAT STILL EXIST. A name is SANITISED into a directory # (`feat/thing` → `feat-thing`), so the comparison happens on the sanitised # form — which is what `cargo-target-dir.sh` prints, from the same rule. live_names="" have_remote=0 if [ "$REMOTE" = 1 ]; then # EVERY REMOTE, and the HOME one first so its name is what the log says when # only it answers. A branch alive on any remote is alive: the two live # branches whose targets this deleted were on the host and not yet on the # mirror, and a union cannot make that mistake in either direction. # shellcheck source=scripts/lib/host-remote.sh . "$HERE/lib/host-remote.sh" host_remote "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" remotes="$(printf '%s\n' "$HOST_REMOTE"; git remote 2>/dev/null || true)" asked="" answered="" refs="" while IFS= read -r remote; do [ -n "$remote" ] || continue case " $asked " in *" $remote "*) continue ;; esac asked="$asked $remote" one="$(git ls-remote --heads "$remote" 2>/dev/null | awk '{ print $2 }' | sed 's#^refs/heads/##' || true)" if [ -n "$one" ]; then answered="$answered $remote" refs="$refs$one"$'\n' fi done <<<"$remotes" if [ -n "$refs" ]; then have_remote=1 log "live branches read from:$answered" while IFS= read -r ref; do [ -n "$ref" ] || continue live_names="$live_names$(bash "$HERE/ci/cargo-target-dir.sh" --per-ref "$ref" "$ROOT" | xargs basename)"$'\n' done <<<"$refs" else log "no remote could be listed (tried:$asked) — the dead-branch rule is OFF for this run" fi fi survivors=() for dir in "$ROOT"/*; do [ -d "$dir" ] || continue [ -L "$dir" ] && continue name="$(basename "$dir")" if kept "$name"; then continue; fi if [ "$have_remote" = 1 ] && ! grep -qxF "$name" <<<"$live_names"; then if used_within_mins "$dir" "$GRACE_MINS"; then log "$name is not a branch on any remote but was written in the last ${GRACE_MINS} minutes — a build may be inside it; leaving it" else remove_target "$dir" "its branch is gone from every remote (merged or deleted) — nothing will build into it again" || true continue fi fi if ! used_within_mins "$dir" $(( DAYS * 24 * 60 )); then remove_target "$dir" "nothing has touched it for over ${DAYS} days" || true continue fi survivors+=("$dir") done # THE BUDGET, LAST. The rules above are proxies for size and neither can say # "60 GB"; this one can. budget_kb="$BUDGET_KB" [ -n "$budget_kb" ] || budget_kb=$(( BUDGET_GB * 1024 * 1024 )) if [ "$budget_kb" -le 0 ] || [ "${#survivors[@]}" -eq 0 ]; then exit 0 fi total=0 listing="" for dir in ${survivors[@]+"${survivors[@]}"}; do # `|| true`: another session can remove a directory between the loop above # and this measurement, and `set -e` must not turn that race into a failure. size="$(du -sk "$dir" 2>/dev/null | awk '{ print $1 }' || true)" case "$size" in ''|*[!0-9]*) continue ;; esac total=$(( total + size )) listing="$listing$(newest_mtime "$dir") $size $dir"$'\n' done if [ "$total" -le "$budget_kb" ]; then log "$(( total / 1024 )) MB in ${#survivors[@]} branch target(s), inside the $(( budget_kb / 1024 / 1024 )) GB budget" exit 0 fi log "$(( total / 1024 / 1024 )) GB in ${#survivors[@]} branch target(s) against a $(( budget_kb / 1024 / 1024 )) GB budget — evicting oldest first" while IFS= read -r line; do [ -n "$line" ] || continue [ "$total" -le "$budget_kb" ] && break dir="${line#* * }" size="${line#* }"; size="${size%% *}" if used_within_mins "$dir" "$BUDGET_GRACE_MINS"; then log "$(basename "$dir") was written in the last ${BUDGET_GRACE_MINS} minutes — a build is inside it; leaving it" continue fi if remove_target "$dir" "the branch targets were over the $(( budget_kb / 1024 / 1024 )) GB budget"; then total=$(( total - size )) fi done <<<"$(printf '%s' "$listing" | sort -n)" # SAY SO WHEN THE BUDGET COULD NOT BE MET. A sweep that spared everything and # exited 0 reads exactly like a sweep that had nothing to do, and that silence # is how the root reached 120 GB against a 60 GB budget without anyone noticing. if [ "$total" -gt "$budget_kb" ]; then log "still $(( total / 1024 / 1024 )) GB against the $(( budget_kb / 1024 / 1024 )) GB budget — everything left is building, kept, or held by the build lock" fi