Cotton code
385 lines · 20.0 KB · ShellRaw
#!/usr/bin/env bash# Disk guard — keeps the boot disk above a free-space headroom by reclaiming# regenerable build/cache cruft. Safe to run anytime; designed to run unattended# on a schedule (launchd) AND before every CI build.## Why this exists: the build Mac wears three hats — dev box, self-hosted CI# runner, and a multi-worktree workspace — and it carries TWO repos (this one# and the Tinmen monorepo), each generating large *regenerable* artifacts (Xcode# DerivedData, CocoaPods caches, Docker images, per-app build dirs). Everyday# cleaners only sweep zero-work cruft; nothing reclaims the big stuff# automatically, so a tight disk slowly fills until a build dies with ENOSPC.## Modes:#   (default)     threshold-gated: reclaim ONLY when free space < HEADROOM_GB.#                 No-op (and silent) when the disk is healthy — safe to run on a#                 frequent schedule.#   --force       reclaim now regardless of free space (still build-safe).#   --pre-build   reclaim before a build starts (used by CI and by#                 scripts/build-xcframework.sh). The always-safe reclaim runs;#                 the build-affecting wipe runs ONLY when free space is below#                 HEADROOM_GB as well, because above it nothing needs the space#                 and the next build wants its caches.## Build-safety gate: if a build (xcodebuild / cargo / fastlane) is in flight,# the DerivedData, CocoaPods-cache and per-app build-dir wipes are SKIPPED in# EVERY mode, --force and --pre-build included — deleting them mid-build would# corrupt the archive, and the flag a wipe was asked for under does not change# that. Build-agnostic reclaim (Docker prune, old archives, runner scratch,# caches, unavailable sims, pnpm store) still runs in every mode.## Env knobs:#   HEADROOM_GB   reclaim when free space drops below this many GB (default 30)#   LOG_FILE      append-only log path (default ~/.cottondb/disk-guard.log)set -uo pipefail# Mac reclamation uses the same floor and shared-cache-first order as builds,# on a Mac that runs the build policy (scripts/lib/build-policy-state.sh). A Mac# outside the fleet reclaims nothing here: its own disk is its owner's to manage.if [ "$(uname -s)" = Darwin ]; then  HERE_DG="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"  . "$HERE_DG/lib/build-policy-state.sh"  case "$(build_policy_state "$HERE_DG")" in    installed) exec bash "$HERE_DG/mac-build-policy.sh" --path "$HOME" --check ;;    fleet-missing) build_policy_missing_message disk-guard >&2; exit 2 ;;    absent) exit 0 ;;  esacfiHEADROOM_GB="${HEADROOM_GB:-30}"LOG_FILE="${LOG_FILE:-$HOME/.cottondb/disk-guard.log}"MODE="threshold"case "${1:-}" in  --force) MODE="force" ;;  --pre-build) MODE="prebuild" ;;  "") MODE="threshold" ;;  *) echo "usage: disk-guard.sh [--force|--pre-build]" >&2; exit 2 ;;esacREPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"reclaim_paths() { python3 "$REPO_ROOT/scripts/lib/evidence.py" remove "$@" | tee -a "$LOG_FILE"; }# Claims are maintained even on a healthy disk, before the ledger's next pass.# The stable cut cache must outlive the cut's disposable worktrees.bash "$REPO_ROOT/scripts/retain-cut-target.sh" || {  echo "disk-guard: could not retain the persistent cut target" >&2  exit 1}# Preserve dependency sources and binary downloads before any cleanup path.bash "$REPO_ROOT/scripts/retain-swiftpm-cache.sh"# Under launchd the default PATH is /usr/bin:/bin:/usr/sbin:/sbin, so docker,# pod, and pnpm all silently vanish behind their `command -v` guards (a# scheduled Docker prune that never actually ran, for months). Prepend the usual# install locations so scheduled runs see the same tools as a shell.export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/Library/pnpm:$PATH"mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null || truelog() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] disk-guard: $*" | tee -a "$LOG_FILE" >&2; }# How long the deep tier's `du` survey gets before it is stopped and the# reclaim goes on without it.SURVEY_BUDGET_S="${DISK_GUARD_SURVEY_S:-20}"# The twenty largest entries under the paths given, BOUNDED.## WHY THERE IS A BUDGET AND NOT JUST AN EXCLUSION LIST. This survey runs inside# `--pre-build`, which `scripts/build-xcframework.sh` calls while holding the# machine-wide build lock. A `du` that never returns therefore holds that lock# for as long as the waiters' timeout allows, with NOTHING building: on# 2026-09-20 the `ci-ios-mac` job re-entered the lock correctly at 22:10:53,# reached "largest entries (before):" ten seconds later and printed nothing for# fifty-five minutes, until it was SIGTERMed by hand (job 9439). Three agents# and a second CI job queued behind it for 3,121 s, 3,182 s and 4,235 s# (`~/.cache/cottondb/build-lock.log`). 2026-09-14 was the same failure twice,# and the fix that time was to exclude `~/Library/Containers`.## An exclusion list cannot close this: every macOS release adds another# directory a stat can block on (a file provider, a synced folder, a network# mount, an app's sandbox), and the guard finds out by wedging a build Mac. A# BUDGET closes it whatever the path is — and the survey is only a log line, so# losing it costs a reader one `du` they can run by hand while the reclaim it# was printed before still happens.survey_largest() {  local out survey waited=0  out="$(mktemp)"  ( du -xsk "$@" 2>/dev/null \      | sort -rn | head -20 | awk '{ printf "  %6.1fG  %s\n", $1/1048576, $2 }' >"$out" ) &  survey=$!  while kill -0 "$survey" 2>/dev/null && [ "$waited" -lt "$SURVEY_BUDGET_S" ]; do    sleep 1    waited=$(( waited + 1 ))  done  if kill -0 "$survey" 2>/dev/null; then    # The children FIRST — the blocked `du` is one of them, and killing only    # the subshell would leave it running against the same path for ever.    pkill -KILL -P "$survey" 2>/dev/null || true    kill -KILL "$survey" 2>/dev/null || true    wait "$survey" 2>/dev/null || true    log "the survey did not finish in ${SURVEY_BUDGET_S}s and was stopped — reclaiming without it"    log "run \`du -xsk ~/* ~/Library/*\` by hand to see what is big; a path that blocks du is the reason this gave up"    rm -f "$out"    return 0  fi  wait "$survey" 2>/dev/null || true  while IFS= read -r line; do log "$line"; done <"$out"  rm -f "$out"}# Free GB on the boot volume. `/` is a sealed APFS snapshot but its Avail column# reflects the shared container's free space, which is the number that matters.## POSIX `df -Pk`, NOT `df -g`. The Macs' BSD df has `-g`; the Linux runner's GNU# df does not, and there the old line read "0G" on EVERY run — so the deep tier# below, the one that empties sccache and takes every per-branch target, fired# every time this script was reached on that box (19 times on 28 Sep 2026, and# run 613 lost a 17 GB target from under a job in its test phase). A reading# this cannot make is an EMPTY answer, never a zero: the caller refuses to# reclaim on it, because a guard that cannot see the disk must not act on it.free_gb() {  df -Pk / 2>/dev/null | awk 'NR == 2 && $4 ~ /^[0-9]+$/ { printf "%d\n", $4 / 1048576 }'}# What a build in flight looks like in `ps`: Xcode, every cargo that compiles or# runs tests (`cargo nextest` is what the lanes run; `cargo test` what a hand# does; clippy compiles too), and fastlane.build_running() {  pgrep -f 'xcodebuild|cargo build|cargo test|cargo nextest|cargo clippy|fastlane' >/dev/null 2>&1}before="$(free_gb)"if [[ -z "$before" ]]; then  log "cannot read the free space on / (\`df -Pk /\` answered nothing usable) — refusing to reclaim anything"  exit 0fiif [[ "$MODE" == "threshold" ]]; then  if (( before >= HEADROOM_GB )); then    exit 0  # healthy — stay silent so the scheduled tick doesn't spam the log  fi  log "free ${before}G < headroom ${HEADROOM_GB}G — reclaiming"else  log "mode=${MODE} — reclaiming (free ${before}G)"fi# --- Build-agnostic reclaim (always safe, even mid-build) -------------------if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then  log "Docker: prune unused images + build cache"  docker image prune -af >/dev/null 2>&1 || true  docker builder prune -af >/dev/null 2>&1 || truefi# 7 days, not 14: a busy day generates ~1.2 GB of archives on this machine, and# the dSYMs are already uploaded to App Store Connect at build time. (Most lanes# here discard their own archive on the success path anyway — this catches the# ones that failed partway and left theirs behind for debugging.)log "Xcode archives older than 7 days"while IFS= read -r -d '' entry; do reclaim_paths "$entry"; done < <(find "$HOME/Library/Developer/Xcode/Archives" -type d -mtime +7 -prune -print0 2>/dev/null)# Sparkle's appcast generator keeps every update archive it has ever signed,# under a cache directory nothing ever prunes — 6 GB on one Mac. The generator# re-derives what it needs from the archives the release lane still has, so this# is regenerable in the same sense as everything else in this tier.log "Sparkle appcast generator cache"reclaim_paths "$HOME/Library/Caches/Sparkle_generate_appcast"/* 2>/dev/null || truelog "GitHub Actions runner scratch (_temp)"reclaim_paths "$HOME/actions-runner/_work/_temp"/* 2>/dev/null || truelog "Unavailable simulators (broken runtimes)"xcrun simctl delete unavailable >/dev/null 2>&1 || true# Dead-weight caches from tools this repo doesn't use (pnpm won the package# manager; Yarn/Cypress caches only reappear if some other project uses them).log "Yarn + Cypress caches"reclaim_paths "$HOME/Library/Caches/Yarn" "$HOME/Library/Caches/Cypress" 2>/dev/null || trueif command -v brew >/dev/null 2>&1; then  log "Homebrew download cache"  brew cleanup --prune=all -s >/dev/null 2>&1 || truefi# Unreferenced packages in the pnpm content store. Skipped if any pnpm process# is live — pruning mid-install could yank a package the install is linking.if command -v pnpm >/dev/null 2>&1 && ! pgrep -x pnpm >/dev/null 2>&1; then  log "pnpm store prune"  pnpm store prune >/dev/null 2>&1 || truefi# THE PER-BRANCH CARGO TARGET DIRECTORIES, and this tier is where they belong:# the sweep NEVER takes a directory written inside its grace window, so it# cannot reach a build in flight, and a merged branch's 15-25 GB is the largest# regenerable thing on a machine that has been building for a week.## Three rules, and the third is the only one stated in gigabytes: the branch is# gone from origin (which after a squash-merge is every branch that shipped),# nothing has touched it for a fortnight, and then a 60 GB total budget evicted# oldest-first. `scripts/sweep-worktree-targets.sh` carries each one's reason.if [[ -d "$HOME/.cache/cottondb/cargo-target" ]]; then  log "per-branch cargo target directories (dead branch, 14-day age, 60 GB budget)"  bash "$REPO_ROOT/scripts/sweep-worktree-targets.sh" 2>&1 | tee -a "$LOG_FILE" >&2 || truefi# THE DAILY SWEEP rides on this agent: every run asks, and it runs once in 20# hours — build output untouched for 3 days and open by no process, check jobs'# work folders, /tmp's build leftovers, and this account's sccache cap.# `scripts/daily-sweep.sh` says what it never touches.bash "$REPO_ROOT/scripts/daily-sweep.sh" --if-due 2>&1 | tee -a "$LOG_FILE" >&2 || true# --- Build-affecting reclaim (two gates, and BOTH must open) ----------------## This is the only tier that can destroy work in progress, so it asks two# questions before it takes anything.##   1. IS A BUILD IN FLIGHT — in every mode, --pre-build included. The old#      --pre-build exemption assumed "no build is running yet", which is true#      of a machine with one build on it and false of this one: four sessions#      build in parallel worktrees alongside the CI runner. 2026-09-14, 20:59#      on one Mac and 21:09 on another, one session's `build-xcframework.sh`#      ran the pre-build pass and deleted every other session's DerivedData and#      build products mid-run.#   2. IS THE DISK ACTUALLY TIGHT — on a --pre-build run. Those same two runs#      wiped at 397 GB free, against a 30 GB headroom: the space was never#      needed, and the cache it took is what makes the next build incremental.#      --force keeps its meaning and wipes regardless of free space; it is a#      person asking for the space now.MODE_LABEL="$MODE"[[ "$MODE" == "prebuild" ]] && MODE_LABEL="pre-build"if [[ "$MODE" == "prebuild" ]] && (( before >= HEADROOM_GB )); then  log "pre-build: free ${before}G >= headroom ${HEADROOM_GB}G — build products kept"elif build_running; then  log "${MODE_LABEL}: build in flight — build products kept"else  # BOTH DERIVED-DATA ROOTS, because until this change there were two for one  # project: `~/.cache/cottondb/derived`, which the scripts name, and Xcode's  # own `~/Library/Developer/Xcode/DerivedData`, which every xcodebuild that  # named no path fell back to — 22 GB each on one Mac, of the same intermediates.  # Every invocation now names the cache root (`scripts/lib/derived-data.sh`);  # the home one is kept in this list because Xcode.app itself still writes  # there when a person opens the project.  log "Xcode DerivedData (both roots)"  reclaim_paths "$HOME/Library/Developer/Xcode/DerivedData"/* 2>/dev/null || true  reclaim_paths "$HOME/.cache/cottondb/derived"/* 2>/dev/null || true  # CocoaPods cache. Regenerable — pods re-download on the next prebuild — but a  # re-download costs minutes and bandwidth, so it stays threshold-gated rather  # than always-run, and inside the build gate because clearing it mid-`pod  # install` could corrupt the install.  if command -v pod >/dev/null 2>&1; then    log "CocoaPods cache"    pod cache clean --all >/dev/null 2>&1 || true  fi  # This repo has one app, but the same shapes exist in every worktree.  log "iOS/Android build dirs + fastlane output (primary + worktrees)"  for root in "$REPO_ROOT" "$REPO_ROOT"/.worktrees/* "$REPO_ROOT"/.claude/worktrees/*; do    [[ -d "$root/apps" ]] || continue    while IFS= read -r -d '' entry; do reclaim_paths "$entry"; done < <(      find "$root/apps" -type d \( -path "*/ios/build" -o -path "*/android/app/build" -o -path "*/android/build" \) -prune -print0 2>/dev/null)    # `build/<app>/ios/*.ipa` — where fastlane's build_app writes. The lanes    # clean this up themselves on success; a crashed lane does not.    reclaim_paths "$root/build" 2>/dev/null || true  donefiafter="$(free_gb)"# THE SAME REFUSAL FOR THE SECOND READING. Bash arithmetic reads an empty# variable as 0, so a blind `df` here would read as "0G, still below the# headroom" and open the deep tier — sccache and every per-branch target — on# exactly the non-answer the first reading refuses to act on.if [[ -z "$after" ]]; then  log "cannot read the free space on / after the ordinary pass (\`df -Pk /\` answered nothing usable) — no deep reclaim"  exit 0fi# --- Deep reclaim: the tier above was not enough ---------------------------## 2026-09-10, the signing Mac: every pass above ran and the log said# `free 0G -> 1G`; the shipping lane then died in `strip` on ENOSPC (run 2672)# and, once it learned to refuse first, refused at 1 GB (run 2674). Nothing the# tiers above know about was left, and from another machine nobody could see# what WAS there. So when a pre-build or forced run is still below the headroom# it does two more things, in this order:##   1. SAYS WHAT IS BIG — the twenty largest entries under $HOME, its Library#      and Developer trees and ~/.cache — so the run's own log answers the#      question the next person would otherwise need a shell for.#   2. TAKES THE REGENERABLE THINGS IT LEFT ALONE ABOVE, because at this point#      a slow next build beats no build: every Xcode archive (a build in#      flight has not written its archive yet, and every lane that ships#      preserves its dSYMs elsewhere —#      `preserve_dsyms!` in the fastlane lanes), the sccache compile cache#      (`require-free-disk.sh` says to leave it in the ORDINARY case, and this#      is not that case), the per-branch cargo targets other than a `ship-*`#      one a shipping lane is about to build into, iOS DeviceSupport symbols#      and simulator caches. Never the simulators: a PR job's laptop needs them.## Threshold-mode (the launchd tick on a laptop) never reaches this: it is a# build machine's last resort, not a dev box's housekeeping.if [[ "$MODE" != "threshold" ]] && (( after < HEADROOM_GB )); then  log "still ${after}G < headroom ${HEADROOM_GB}G after the ordinary pass — deep reclaim"  log "largest entries (before):"  # NOT the sandbox containers, and NOT the file-provider roots. `du` into  # `~/Library/Containers`, `~/Library/Group Containers`,  # `~/Library/CloudStorage` or `~/Library/Mobile Documents` walks somebody  # else's sandbox or a provider that answers a stat by fetching — which macOS  # answers by BLOCKING the reading process: no error, no CPU, forever.  # `~/Library` itself is skipped because it CONTAINS all four, and its  # children are surveyed one by one below it.  survey=()  for entry in "$HOME"/* "$HOME"/.[!.]* "$HOME"/Library/* "$HOME"/Library/Developer/* \    "$HOME"/Library/Developer/Xcode/* "$HOME"/Library/Developer/CoreSimulator/* \    "$HOME"/.cache/* "$HOME"/.cache/cottondb/* "$HOME"/.cache/cottondb/rust/*; do    case "$entry" in      "$HOME/Library" | "$HOME/Library/Containers" | "$HOME/Library/Group Containers" \        | "$HOME/Library/CloudStorage" | "$HOME/Library/Mobile Documents") continue ;;    esac    [[ -e "$entry" ]] && survey+=("$entry")  done  survey_largest "${survey[@]}"  log "every Xcode archive (dSYMs are preserved by the lane)"  reclaim_paths "$HOME/Library/Developer/Xcode/Archives"/* 2>/dev/null || true  # THE TWO THINGS A LIVE BUILD IS STANDING ON are behind the same gate as the  # tier above: stopping the sccache server under a compile fails every write  # for the rest of that compile, and a per-branch target is where the job's  # binaries ARE. The tier above already said "build in flight — build  # products kept"; this tier used to take both anyway (run 613, 28 Sep 2026).  if build_running; then    log "deep reclaim: build in flight — sccache and the per-branch cargo targets kept"  else    # THE SERVER FIRST, THEN THE CACHE. A bare `rm -rf` here leaves the running    # sccache server pointed at a directory that no longer exists, and it never    # recreates one: every write fails for the life of that server, which    # `SCCACHE_IDLE_TIMEOUT=0` makes "until the Mac reboots". One Mac, 2026-09-22:    # 29,679 cache write errors and a 4.32% hit rate on Rust compiles, from one    # reclaim taken this way. `scripts/reclaim-sccache.sh` stops the server,    # empties the directory and recreates it.    log "sccache compile cache (server stopped first)"    bash "$REPO_ROOT/scripts/reclaim-sccache.sh" 2>&1 | tee -a "$LOG_FILE" >&2 || true    # THROUGH THE SWEEP, never a loop of this script's own. The sweep is the one    # place that knows what a live job looks like — the lock beside the    # directory (`<name>.lock`, held for the whole cargo step by    # `with-cargo-lock.sh`) and the grace window — and `--everything` is its    # spelling of "every regenerable one". This used to be    # `rm -rf targets/*` with neither check, and run 613 (28 Sep 2026) lost a    # 17 GB target, and the test binary inside it, to exactly that line. A    # shipping lane's own `ship-*` directory stays, as before.    targets="$HOME/.cache/cottondb/rust/targets"    if [[ -d "$targets" ]]; then      log "per-branch cargo targets except a shipping lane's own — through the sweep, which keeps a held one"      keep=()      for t in "$targets"/ship-*; do        [[ -d "$t" ]] && keep+=(--keep "$(basename "$t")")      done      bash "$REPO_ROOT/scripts/ci/sweep-cargo-targets.sh" --root "$targets" --everything \        --no-remote --no-legacy --no-dev-target ${keep[@]+"${keep[@]}"} 2>&1 | tee -a "$LOG_FILE" >&2 || true    fi  fi  log "iOS DeviceSupport symbols, simulator caches"  reclaim_paths "$HOME/Library/Developer/Xcode/iOS DeviceSupport"/* 2>/dev/null || true  reclaim_paths "$HOME/Library/Developer/CoreSimulator/Caches"/* 2>/dev/null || true  after="$(free_gb)"filog "done — free ${before}G -> ${after:-?}G"