Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-architecture-mv/blob/main/tools/ops/spark-cleanup # aien-architecture-mv Canonical architecture for the AIEN ecosystem: flows, boundaries, ADRs, and the map from design to implementation repositories. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-architecture-mv / tools / ops / spark-cleanup` 1163 lines ยท 70297 bytes Raw Blame History 1 #!/usr/bin/env bash 2 # spark-cleanup: reclaim regenerable disk space on the Spark, safely. 3 # 4 # Dry run by default. Pass --apply to delete. Every action (and every skip with 5 # its reason) is logged to ~/.local/state/spark-cleanup/.log. 6 # 7 # Classes (run in this order): 8 # 1 build outputs: cargo target dirs (CACHEDIR.TAG + debug/release) under 9 # ~/workspace, ~/.claude/jobs, ~/.cache; CI judge lanes under 10 # /var/lib/aien-run/target (only while the CI lane lock is free) and 11 # renamed *.stale-* dirs there. 12 # 1s per-SHA CI dirs /var/lib/aien-run/target///: the newest 13 # SHA per lane stays, the per-SHA lock (else the lane lock) must be free, 14 # size is logged, never a reason to keep or remove. Reported as its own 15 # class so dry-classes can hold it dry ("1s") while class 1 stays live. 16 # Any entry removed (or kept unsaved by class 5) above SPARK_CLEANUP_BIG_ALARM 17 # bytes (default 5 GiB) is named in one ALARM line at the end of the run. 18 # 2 git worktrees under ~/workspace: untouched 24 h, HEAD present in ~/git 19 # (reachable from a ref of a bare repository there; a push to some other 20 # remote does not count), and no unsaved bytes. A plain `git status` is 21 # not that check: untracked and ignored files hidden by 22 # status.showUntrackedFiles, and skip-worktree or assume-unchanged edits, 23 # keep the worktree. A nested repository keeps it too: a checkout (a path 24 # named .git) or a bare repository of any name, found by its shape 25 # (HEAD, objects/ and refs/), for example .lake/packages/dep. A worktree a 26 # claim names is kept, with the claims read as --landed reads them (below). 27 # -> git worktree remove + prune. 28 # 3 docker dangling images and build cache. 29 # 4 caches: ~/.cargo/registry/cache files unread 30 d, rustup toolchains 30 # not default and not named by any rust-toolchain file, ~/.cache entries 31 # untouched 7 d (huggingface excluded). 32 # 5 /tmp entries untouched 2 d, not named by RESUME.md/lock. An entry holding a 33 # git repository (itself, nested or bare) goes only when every repository in 34 # it is saved in ~/git as class 8 means it (refs, submodule commits, no 35 # unsaved files); else "class5 SKIP unsaved". A locked linked worktree stays 36 # ("class5 SKIP locked"): its main clone keeps the record. Size never decides. 37 # dry-classes file: ~/.config/spark-cleanup/dry-classes 38 # 6 journald vacuum to 2G. 39 # 7 models: REPORT ONLY. Never deletes. Use the manual procedure in the 40 # handoff (write repo id + revision to ~/models/DELETED.md first). 41 # 8 leftover-copy ALARM: REPORT ONLY. Never deletes. Git clones and 42 # worktrees under ~/workspace, ~/work and ~/.claude/jobs with nothing 43 # written for 3 days and nothing open, each given one kind: 44 # leftover clean, every ref (branches, stash, tags, remote-tracking; 45 # HEAD only for a linked worktree) in a bare repo of ~/git, 46 # nested repositories and submodule commits in ~/git too, 47 # nothing ignored but build output: a finished task left its copy 48 # unstored a ref, nested repository or submodule commit not in ~/git 49 # dirty uncommitted, untracked, skip-worktree or assume-unchanged 50 # changes (bytes or the executable bit), ignored files that 51 # are not build output, or any of these inside a nested 52 # repository. status.showUntrackedFiles is forced on 53 # unreadable git cannot read it (broken worktree, other owner): never "leftover" 54 # plus model weight files over 1 GiB with one link (.safetensors .gguf 55 # .pt .pth): copies, not links. ~/git is searched with nested folders; 56 # an empty store is its own loud ALARM. Under --apply it runs after the 57 # quiet lock is released, with its own lock; the low-space trigger 58 # (--if-below) and --only skip it. When the total reaches 59 # SPARK_CLEANUP_LEFTOVER_ALARM_GB (whole GB, default 1) an --apply run 60 # posts one line to the team board (SPARK_CLEANUP_BOARD, default 61 # ~/handoffs/BOARD.md), and only when the set of copies changed since 62 # its last post (~/.local/state/spark-cleanup/class8-posted). 63 # 64 # Landing mode (spark-cleanup --landed REPO, REPO = a store name such as omega-mv): 65 # run detached by store-post-update, the post-update hook every ~/git store 66 # repository gets through core.hooksPath, after every landing. It looks at the 67 # class 8 copies (~/workspace, ~/work, ~/.claude/jobs; never /tmp or ~/handoffs) 68 # whose remote URL names REPO or whose HEAD has a root commit of the store's 69 # REPO.git. These stay: 70 # main clones: a folder directly in ~/workspace with a real .git folder whose 71 # name has no '-' or is a repository's name (a store .git or 72 # -mv.git, or the last part of one of its remote URLs) 73 # protected copies 74 # claimed copies: a CLAIM line on the board (SPARK_CLEANUP_BOARD) or in 75 # ~/handoffs/hive/CLAIMS.md (SPARK_CLEANUP_CLAIMS), dated in the last 76 # SPARK_CLEANUP_CLAIM_DAYS days (default 14) or not dated at all, and not 77 # followed by a RELEASE line of the same lane (a CLAIM line whose lane 78 # cannot be read is never released), names the copy, a folder above it or 79 # a path inside it; or a locked worktree. A claim of a whole copy folder 80 # (~/workspace, ~/work, ~/.claude/jobs) or of a folder above one (~) is 81 # not used: it is an ALARM in the log every run and one board line per set. 82 # A missing claim file is skipped; one that cannot be read is an ALARM 83 # copies a running process has open (looked at again just before removal) 84 # saved (class 8 leftover: every ref, nested and submodule commit in ~/git, 85 # nothing unsaved) and no file outside .git written for 86 # SPARK_CLEANUP_LANDED_IDLE_H hours (default 6): removed (git worktree 87 # remove + prune for a linked worktree, rm for a clone); single-link bytes 88 # freed are logged 89 # unsaved, idle SPARK_CLEANUP_LANDED_ARCHIVE_D days (default 3): archived to 90 # SPARK_CLEANUP_ARCHIVE (default ~/archive/agent-work)/.tar.zst, the 91 # entry count and contents (tar -d) checked against the copy, then removed and replaced by /ARCHIVED.txt with 92 # the restore command. A linked worktree's archive also holds its record in 93 # the main clone and a bundle of a HEAD not in ~/git. Build output (ignored 94 # target/, build/, node_modules/, .lake/, ... and cargo targets, each only 95 # when no repository is inside) is left out and named in ARCHIVED.txt. When 96 # the archive's disk has less free space than the copy without build output 97 # plus SPARK_CLEANUP_ARCHIVE_RESERVE_GB (whole GB, default 20) the copy stays, 98 # with an ALARM line 99 # anything else stays, with the reason in the log. A copy kept for a reason 100 # that passes (open, claimed, written recently, no room to archive) is listed 101 # in ~/.local/state/spark-cleanup/landed-pending and looked at again at the 102 # next landing of any repository 103 # All output goes to the log; the exit status is always 0. It waits for a 104 # running spark-cleanup instead of skipping, and runs under quiet-build. 105 # 106 # Hard rules applied to every candidate: 107 # - skipped if any running process has a file open in it, or uses it as 108 # cwd or exe (from /proc and lsof, collected once at start) 109 # - skipped if anything inside was modified in the last --age-hours (6 h; 110 # 24 h for worktrees, 2 days for /tmp, 7 days for ~/.cache) 111 # - skipped if the path looks like evidence, receipts, handoffs, 112 # yardsticks, ~/.local/state, or another user's home 113 # - the whole of ~/work/hive/uxl-brief-`20261113`/FourBit is skipped, 114 # including a cargo target inside it. That tree is not a cache this 115 # program is allowed to judge or to name for removal 116 # - a verified cargo target under ~/handoffs/hive/factory-bays may be 117 # removed: it is rebuildable build output. evidence, receipts, keys, 118 # bundles and jsonl under that tree stay. Nothing else under ~/handoffs 119 # is removed 120 # - skipped if its name is in the protected list (active agent names) 121 # 122 # Usage: 123 # spark-cleanup dry run, classes 1-6 and 8 124 # spark-cleanup --apply delete 125 # spark-cleanup --landed REPO after a landing of REPO (see above) 126 # spark-cleanup --apply --if-below 20 only run if free space < 20 % 127 # spark-cleanup --apply --only DIR [--only DIR] end of session: only 128 # target dirs / worktrees at or under DIR 129 # spark-cleanup --classes 1,2 choose classes 130 set -uo pipefail 131 132 # Run politely: go through quiet-build so we never start (or run) during a 133 # quiet-measure measurement. quiet-build waits for pending measurements, then 134 # holds /tmp/aien-quiet.lock shared for the whole run. 135 QB="$HOME/.local/bin/quiet-build" 136 # a landing hook: under quiet-build (no wait under 10 % free), status 0 whatever happens 137 if [ -z "${SPARK_CLEANUP_QUIET:-}" ] && [ -x "$QB" ] && [[ " $* " == *" --landed "* ]]; then 138 export SPARK_CLEANUP_QUIET=1 139 _p=${SPARK_CLEANUP_TEST_FREE_PCT:-$(df -B1 --output=size,avail / | tail -1 | awk '{printf "%d", $2*100/$1}')} 140 if [ "$_p" -ge 10 ]; then "$QB" "$0" "$@"; else "$0" "$@"; fi 141 exit 0 142 fi 143 if [ -z "${SPARK_CLEANUP_QUIET:-}" ] && [ -x "$QB" ] && [[ " $* " == *" --apply "* ]]; then 144 export SPARK_CLEANUP_QUIET=1 145 # cheap pre-check so a caller passing --if-below does not queue behind 146 # measurements when there is nothing to do; under 10 % free it is an 147 # emergency and skips the quiet wait (a full disk breaks measurements too) 148 _ib=""; _prev="" 149 for _a in "$@"; do [ "$_prev" = "--if-below" ] && _ib="$_a"; _prev="$_a"; done 150 _p=${SPARK_CLEANUP_TEST_FREE_PCT:-$(df -B1 --output=size,avail / | tail -1 | awk '{printf "%d", $2*100/$1}')} 151 if [ -n "$_ib" ] && [ "$_p" -ge "$_ib" ]; then 152 mkdir -p "$HOME/.local/state/spark-cleanup" 153 echo "$(date +%FT%T) free ${_p}% >= ${_ib}%, nothing to do" >> "$HOME/.local/state/spark-cleanup/$(date +%F).log" 154 exit 0 155 fi 156 # Deleting classes run first (under the shared quiet lock unless free space is 157 # under 10 %). Class 8 only reads and its scan is long, so it always runs after 158 # them, alone, holding neither the quiet lock nor run.lock, in this same process 159 # tree (a service's oneshot keeps its main process alive). 160 _cl=""; _prev="" 161 for _a in "$@"; do [ "$_prev" = "--classes" ] && _cl="$_a"; _prev="$_a"; done 162 if [ "$_cl" = 8 ]; then _rc=0 # only class 8 asked for: no deleting run, no quiet wait 163 elif [ "$_p" -ge 10 ]; then SPARK_CLEANUP_SKIP8=1 "$QB" "$0" "$@"; _rc=$? 164 else SPARK_CLEANUP_SKIP8=1 "$0" "$@"; _rc=$?; fi 165 SPARK_CLEANUP_ONLY8=1 "$0" "$@" 166 exit $_rc 167 fi 168 169 APPLY=0 170 CLASSES="" 171 IF_BELOW="" 172 AGE_H=6 173 ONLY=() 174 LANDED="" 175 PROTECT_DEFAULT="omega-cascade omega-w4b omega-prefill omega-flashnext omega-dflash omega-symbolic sc-cascade sc-batch sc-docmem sc-dflash sc-flashnext sc-skipped sc-alpha-docs omega-alpha m1-passport" 176 PROTECT="${SPARK_CLEANUP_PROTECT:-$PROTECT_DEFAULT}" 177 178 usage() { sed -n '2,/^set -uo pipefail/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; exit "${1:-0}"; } 179 while [ $# -gt 0 ]; do 180 case "$1" in 181 --apply) APPLY=1 ;; 182 --landed) LANDED="${2:-}"; APPLY=1; CLASSES=landed; shift ;; 183 --dry-run) APPLY=0 ;; 184 --classes) CLASSES="$2"; shift ;; 185 --if-below) IF_BELOW="$2"; shift ;; 186 --age-hours) AGE_H="$2"; shift ;; 187 --only) ONLY+=("$(readlink -f "$2")"); shift ;; 188 -h|--help) usage 0 ;; 189 *) echo "unknown arg: $1" >&2; usage 2 ;; 190 esac 191 shift 192 done 193 if [ -z "$CLASSES" ]; then 194 if [ ${#ONLY[@]} -gt 0 ]; then CLASSES="1,2" 195 elif [ -n "$IF_BELOW" ]; then CLASSES="1,2,3,4,5,6" # low-space trigger: reclaim only, no alarm scan 196 else CLASSES="1,2,3,4,5,6,8"; fi 197 fi 198 # set by the quiet-build wrapper above: the locked run skips class 8, the run after it does only class 8 199 if [ -n "${SPARK_CLEANUP_SKIP8:-}" ]; then CLASSES=$(tr ',' '\n' <<<"$CLASSES" | grep -vx 8 | paste -sd, -); fi 200 if [ -n "${SPARK_CLEANUP_ONLY8:-}" ]; then 201 case ",$CLASSES," in *,8,*) CLASSES=8 ;; *) exit 0 ;; esac 202 fi 203 204 H="$HOME" 205 STATE="$H/.local/state/spark-cleanup" 206 mkdir -p "$STATE" 207 LOG="$STATE/$(date +%F).log" 208 # landing mode writes only to the log: the hook that starts it is detached 209 [ -n "$LANDED" ] && exec >/dev/null 2>>"$LOG" 210 log() { printf '%s %s\n' "$(date +%FT%T)" "$*" | tee -a "$LOG"; } 211 # no scratch folder, no run: every class writes its lists there, and an empty path would put them at / 212 if ! TMPD=$(mktemp -d "${TMPDIR:-/tmp}/spark-cleanup.XXXXXX" 2>>"$LOG") || [ ! -d "$TMPD" ]; then 213 log "ALARM cannot create a scratch folder under ${TMPDIR:-/tmp} (missing, full or unwritable): nothing checked, nothing removed" 214 echo "spark-cleanup: cannot create a scratch folder under ${TMPDIR:-/tmp}" >&2 215 [ -n "$LANDED" ] && exit 0 216 exit 1 217 fi 218 trap 'rm -rf "$TMPD"' EXIT 219 MODE=$([ -n "$LANDED" ] && echo "LANDED $LANDED" || { [ $APPLY = 1 ] && echo APPLY || echo DRY-RUN; }) 220 221 free_bytes() { df -B1 --output=avail / | tail -1 | tr -d ' '; } 222 free_pct() { df -B1 --output=size,avail / | tail -1 | awk '{printf "%d", $2*100/$1}'; } 223 human() { awk -v b="$1" 'BEGIN{ printf "%.1fG", b/1e9 }'; } 224 225 C8MAX_H="${SPARK_CLEANUP_CLASS8_MAX_H:-6}" 226 if ! [[ "$C8MAX_H" =~ ^[0-9]+$ ]]; then log "ALARM bad SPARK_CLEANUP_CLASS8_MAX_H='$C8MAX_H' (whole hours expected); using 6"; C8MAX_H=6; fi 227 # no size cap decides a removal (standing rule: no hard caps); an entry removed or kept that is 228 # bigger than this many bytes is named in one ALARM line at the end of the run so someone looks 229 BIG_ALARM="${SPARK_CLEANUP_BIG_ALARM:-`5368709120`}" 230 if ! [[ "$BIG_ALARM" =~ ^[0-9]+$ ]]; then log "ALARM bad SPARK_CLEANUP_BIG_ALARM='$BIG_ALARM' (whole bytes expected); using `5368709120`"; BIG_ALARM=`5368709120`; fi 231 BIG=() 232 big_note() { [ "${2:-0}" -gt "$BIG_ALARM" ] && BIG+=("$1 $(human "$2") ($3)"); return 0; } 233 # one run at a time 234 # a dry class 8 run (a person or reviewer looking) has its own lock and never touches the 235 # --apply run's marks, so it cannot block, or raise a false alarm about, the daily scan 236 if [ "$CLASSES" = 8 ]; then exec 9>"$STATE/class8$( [ $APPLY = 1 ] || echo -dry).lock"; else exec 9>"$STATE/run.lock"; fi 237 if [ -n "$LANDED" ]; then 238 # a landing waits for the run before it: skipping would leave this landing's copies for the next one. 239 # No cap on the wait (standing rule); a wait past SPARK_CLEANUP_LOCK_WAIT_MIN minutes (default 30) is 240 # named on the board once, then the wait goes on 241 if ! flock -n 9; then 242 _lw="${SPARK_CLEANUP_LOCK_WAIT_MIN:-30}"; [[ "$_lw" =~ ^[0-9]+$ ]] || _lw=30 243 echo "$(date +%FT%T) landed $LANDED: waiting for run.lock (another spark-cleanup run holds it)" >> "$LOG" 244 if ! flock -w $((_lw*60)) 9; then 245 echo "$(date +%FT%T) landed ALARM $LANDED: still waiting for run.lock after $_lw min" >> "$LOG" 246 printf '%s ALARM spark-cleanup to all: the cleanup for the landing of %s has waited %s min for run.lock (holder: %s); see %s.\n' "$(date -u +%FT%H:%MZ)" "$LANDED" "$_lw" "$(fuser "$STATE/run.lock" 2>/dev/null | tr -s ' ' | sed 's/^ //')" "$LOG" >> "${SPARK_CLEANUP_BOARD:-$H/handoffs/BOARD.md}" 247 flock 9 248 fi 249 fi 250 elif ! flock -n 9; then 251 echo "spark-cleanup already running" >&2 252 if [ "$CLASSES" = 8 ]; then 253 # a class 8 scan still running: say so in the log, and alarm once if it has run past the threshold 254 _st=$( [ $APPLY = 1 ] && cat "$STATE/class8.started" 2>/dev/null); _now=$(date +%s); _max=$(( C8MAX_H * 3600 )) 255 echo "$(date +%FT%T) class8 SKIP: a class 8 scan started $( [ -n "$_st" ] && echo "$(( (_now-_st)/60 )) min ago" || echo "at an unknown time") still holds class8.lock" >> "$LOG" 256 if [ $APPLY = 1 ] && [ -n "$_st" ] && [ $((_now-_st)) -gt "$_max" ] && [ "$(cat "$STATE/class8-stale-posted" 2>/dev/null)" != "$_st" ]; then 257 echo "$(date +%FT%T) class8 ALARM scan running longer than $C8MAX_H h (threshold SPARK_CLEANUP_CLASS8_MAX_H); the leftover-copy alarm is stale" >> "$LOG" 258 printf '%s ALARM spark-cleanup class8 to all: the leftover-copy scan started %s has run longer than %s h, so its alarm is stale; see %s.\n' "$(date -u +%FT%H:%MZ)" "$(date -d @"$_st" -u +%FT%H:%MZ)" "$C8MAX_H" "$LOG" >> "${SPARK_CLEANUP_BOARD:-$H/handoffs/BOARD.md}" && echo "$_st" > "$STATE/class8-stale-posted" 259 fi 260 fi 261 exit 0 262 fi 263 if [ "$CLASSES" = 8 ] && [ $APPLY = 1 ]; then 264 # the previous scan was killed (service timeout, crash) if it started and never wrote its finish mark 265 _st=$(cat "$STATE/class8.started" 2>/dev/null) 266 if [ -n "$_st" ] && [ "$(cat "$STATE/class8.finished" 2>/dev/null)" != "$_st" ]; then 267 log "class8 ALARM the previous leftover-copy scan (started $(date -d @"$_st" +%FT%T)) did not finish; its alarm was never written" 268 [ "$(cat "$STATE/class8-stale-posted" 2>/dev/null)" != "$_st" ] && printf '%s ALARM spark-cleanup class8 to all: the leftover-copy scan started %s did not finish (killed or crashed), so no alarm came from it; see %s.\n' "$(date -u +%FT%H:%MZ)" "$(date -d @"$_st" -u +%FT%H:%MZ)" "$LOG" >> "${SPARK_CLEANUP_BOARD:-$H/handoffs/BOARD.md}" && echo "$_st" > "$STATE/class8-stale-posted" 269 fi 270 fi 271 272 if [ -n "$IF_BELOW" ]; then 273 p=$(free_pct) 274 if [ "$p" -ge "$IF_BELOW" ]; then 275 echo "$(date +%FT%T) free ${p}% >= ${IF_BELOW}%, nothing to do" >> "$LOG" 276 exit 0 277 fi 278 log "free ${p}% < ${IF_BELOW}%: low-space trigger" 279 fi 280 SUDO="sudo -n" 281 $SUDO true 2>/dev/null || SUDO="" 282 283 START_FREE=$(free_bytes) 284 TOTAL=0 285 log "=== spark-cleanup $MODE classes=$CLASSES only=${ONLY[*]:-all} free=$(human "$START_FREE") ($(free_pct)%)" 286 287 # ---- in-use set: cwd, exe, root, open fds and mmaps of every process ---- 288 INUSE="$TMPD/inuse" 289 collect_inuse() { 290 # test hook: a fixed in-use list instead of scanning every process on the machine 291 if [ -n "${SPARK_CLEANUP_TEST_INUSE_FILE:-}" ]; then 292 if [ "$H" = "$(getent passwd "$(id -un)" | cut -d: -f6)" ]; then 293 log "ALARM SPARK_CLEANUP_TEST_INUSE_FILE is set on the real home: ignored, the machine-wide in-use scan runs" 294 else 295 log "test hook: in-use list read from $SPARK_CLEANUP_TEST_INUSE_FILE (scratch home $H)" 296 sort -u "$SPARK_CLEANUP_TEST_INUSE_FILE" > "$INUSE"; return 297 fi 298 fi 299 { 300 for p in /proc/[0-9]*; do 301 $SUDO readlink "$p/cwd" "$p/exe" "$p/root" 2>/dev/null 302 $SUDO find "$p/fd" -mindepth 1 -maxdepth 1 -exec readlink {} + 2>/dev/null 303 $SUDO awk '$6 ~ /^\// {print $6}' "$p/maps" 2>/dev/null 304 done 305 $SUDO lsof -nP -Fn 2>/dev/null | sed -n 's/^n//p' 306 } | sed 's/ (deleted)$//' | grep '^/' | grep -vx / | sort -u > "$INUSE" 307 } 308 collect_inuse 309 # class 5 reads /tmp; the test suite points it at a scratch folder, never on the real home 310 TMPROOT=/tmp 311 if [ -n "${SPARK_CLEANUP_TEST_TMPROOT:-}" ]; then 312 if [ "$H" = "$(getent passwd "$(id -un)" | cut -d: -f6)" ]; then 313 log "ALARM SPARK_CLEANUP_TEST_TMPROOT is set on the real home: ignored, class 5 reads /tmp" 314 else 315 TMPROOT="${SPARK_CLEANUP_TEST_TMPROOT%/}"; log "test hook: class 5 reads $TMPROOT instead of /tmp (scratch home $H)" 316 fi 317 fi 318 in_use() { # $1 = dir; true if any in-use path is the dir or below it 319 grep -qxF -- "$1" "$INUSE" && return 0 320 grep -qF -- "$1/" "$INUSE" 321 } 322 recent() { # $1 dir, $2 minutes: true if anything inside changed recently 323 [ -n "$($SUDO find "$1" -xdev -mmin "-$2" -print -quit 2>/dev/null)" ] 324 } 325 size_of() { $SUDO du -sxb -- "$1" 2>/dev/null | cut -f1; } 326 protected_path() { 327 case "$1" in 328 "$H"/work/hive/uxl-brief-`20261113`/FourBit|"$H"/work/hive/uxl-brief-`20261113`/FourBit/*) return 0 ;; 329 "$H"/handoffs/hive/factory-bays/*) 330 # Allow verified Cargo build caches under factory-bays; protect everything else in handoffs 331 is_cargo_target "$1" || return 0 332 case "$1" in */evidence|*/evidence/*|*/receipts*|*/keys*|*/bundles*|*.jsonl) return 0 ;; esac 333 ;; 334 */evidence|*/evidence/*|*/receipts*|*/handoffs*|*/yardsticks*|"$H"/.local/state*) return 0 ;; 335 /home/drake|/home/drake/*|/home/atlas|/home/atlas/*|/home/aienalpha|/home/aienalpha/*) return 0 ;; 336 /var/lib/aienos-region*|*/keys*|*/bundles*|*.jsonl) return 0 ;; 337 esac 338 case "$1" in "$H"/*|/var/lib/aien-run/*|/tmp/*) ;; *) return 0 ;; esac 339 local b n 340 for n in $PROTECT; do 341 for b in "/$n" "/$n/"; do case "$1/" in *"$b"*) return 0 ;; esac; done 342 done 343 return 1 344 } 345 under_only() { 346 [ ${#ONLY[@]} -eq 0 ] && return 0 347 local o; for o in "${ONLY[@]}"; do case "$1/" in "$o"/*) return 0 ;; esac; done 348 return 1 349 } 350 want() { case ",$CLASSES," in *",$1,"*) return 0 ;; esac; return 1; } 351 352 # "pushed" means present in the git store Interplane serves (~/git/.git), 353 # not merely on some remote: a push to a scratch bare repo or a GitHub mirror 354 # leaves no copy where the team reads code from. 355 GITSTORE="${SPARK_CLEANUP_GITSTORE:-$H/git}" 356 # git status must not rewrite a copy's index: that write would make the copy look 357 # recently touched and hide it from the idle checks of the next run 358 export GIT_OPTIONAL_LOCKS=0 359 # every bare repository in the store, nested ones included (the store has folders of them) 360 mapfile -t STORE_REPOS < <(find "$GITSTORE" -maxdepth 4 -type d -name '*.git' -prune 2>/dev/null | sort) 361 [ ${#STORE_REPOS[@]} -gt 0 ] && rm -f "$STATE/store-empty-posted" 362 if [ ${#STORE_REPOS[@]} -eq 0 ] && { want 2 || want 5 || want 8; }; then 363 log "ALARM git store $GITSTORE holds no bare repositories: class 2 keeps every worktree, class 5 every /tmp git copy, and class 8 calls every copy unstored until it is fixed" 364 [ $APPLY = 1 ] && [ ${#ONLY[@]} -eq 0 ] && [ ! -e "$STATE/store-empty-posted" ] && touch "$STATE/store-empty-posted" && printf '%s ALARM spark-cleanup to all: the git store %s holds no bare repositories; nothing can be checked as saved. See %s.\n' "$(date -u +%FT%H:%MZ)" "$GITSTORE" "$LOG" >> "${SPARK_CLEANUP_BOARD:-$H/handoffs/BOARD.md}" 365 fi 366 declare -A STORE_HIT=() 367 in_git_store() { # $1 commit sha; true if a ref of a bare repo in the store reaches it (answer cached per sha) 368 local b 369 case "${STORE_HIT[$1]:-}" in 1) return 0 ;; 0) return 1 ;; esac 370 for b in "${STORE_REPOS[@]}"; do 371 git -C "$b" cat-file -e "$1^{commit}" 2>/dev/null || continue 372 if [ -n "$(git -C "$b" for-each-ref --contains "$1" --count=1 2>/dev/null)" ]; then STORE_HIT[$1]=1; return 0; fi 373 done 374 STORE_HIT[$1]=0; return 1 375 } 376 repo_heads() { # $1 repo dir: HEAD, plus every ref (branches, stash, tags AND remote-tracking) 377 # of a repository that owns its refs. A commit that exists only as a remote-tracking ref is not saved. 378 # A linked worktree (git dir differs from the common dir) shares its refs with the main clone, 379 # which is judged on its own, so only its HEAD is its work. A submodule or separate-git-dir 380 # checkout also has a .git file, but owns its refs: all of them count. 381 # Exit 1 when git cannot read the repository. 382 local gd cd 383 git -C "$1" rev-parse --verify -q 'HEAD^{commit}' 2>/dev/null || git -C "$1" rev-parse --git-dir >/dev/null 2>&1 || return 1 384 gd=$(git -C "$1" rev-parse --path-format=absolute --git-dir 2>/dev/null) || return 1 385 cd=$(git -C "$1" rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || return 1 386 [ "$gd" != "$cd" ] && return 0 387 git -C "$1" for-each-ref --format='%(objectname) %(refname)' 2>/dev/null | awk '{print $1}' 388 } 389 # 0 and a one-line reason when the copy holds bytes a plain `git status --porcelain` can hide 390 # or any other unsaved change. Forces untracked and ignored files on. Compares skip-worktree 391 # (S) and assume-unchanged (h) files with the index, which status does not show: bytes, the 392 # executable bit and symlink-ness. Then checks every checkout nested inside the copy (in 393 # ignored folders too) the same way; $2 set means "this is a nested one, do not descend". 394 copy_unsaved() { 395 local s rc line path flag idx wt meta mode d why 396 s=$(git -C "$1" -c status.showUntrackedFiles=all status --porcelain=v1 --untracked-files=all --ignored=matching 2>/dev/null) 397 rc=$? 398 if [ "$rc" -ne 0 ]; then echo "git status failed"; return 0; fi 399 line=$(printf '%s\n' "$s" | grep -vE '^!! |^$' | head -1 || true) 400 if [ -n "$line" ]; then echo "uncommitted or untracked changes"; return 0; fi 401 line=$(printf '%s\n' "$s" | grep '^!! ' | grep -vE "$BUILD_JUNK_RE" | head -1 || true) 402 if [ -n "$line" ]; then echo "ignored files that are not build output (${line#!! })"; return 0; fi 403 while IFS= read -r -d '' line; do 404 flag=${line:0:1} 405 case "$flag" in S|s|h) ;; *) continue ;; esac 406 meta=${line%%$'\t'*}; path=${line#*$'\t'} 407 read -r _ mode idx _ <<<"$meta" 408 [ "$mode" = 160000 ] && continue # a submodule: judged as a nested repository 409 if [ ! -e "$1/$path" ] && [ ! -L "$1/$path" ]; then echo "skip-worktree path missing ($path)"; return 0; fi 410 case "$mode" in 411 120000) 412 [ -L "$1/$path" ] || { echo "skip-worktree or assume-unchanged symlink replaced ($path)"; return 0; } 413 wt=$(printf '%s' "$(readlink "$1/$path")" | git -C "$1" hash-object --stdin 2>/dev/null) || { echo "skip-worktree path cannot be read ($path)"; return 0; } 414 ;; 415 100644|100755) 416 if [ -L "$1/$path" ] || [ ! -f "$1/$path" ]; then echo "skip-worktree or assume-unchanged file replaced ($path)"; return 0; fi 417 if (( 0$(stat -c %a -- "$1/$path") & 0100 )); then [ "$mode" = 100755 ]; else [ "$mode" = 100644 ]; fi \ 418 || { echo "skip-worktree or assume-unchanged file executable bit differs from the saved copy ($path)"; return 0; } 419 wt=$(git -C "$1" hash-object -- "$1/$path" 2>/dev/null) || { echo "skip-worktree path cannot be read ($path)"; return 0; } 420 ;; 421 *) echo "skip-worktree path has unknown mode $mode ($path)"; return 0 ;; 422 esac 423 if [ "$idx" != "$wt" ]; then echo "skip-worktree or assume-unchanged file differs from the saved copy ($path)"; return 0; fi 424 done < <(git -C "$1" ls-files -v -s -z -- 2>/dev/null || true) 425 [ -n "${2:-}" ] && return 1 426 while IFS= read -r d; do 427 [ -e "$d/.git" ] || continue # a bare repository has no files to lose; its refs are checked by nested_unstored 428 if why=$(copy_unsaved "$d" nested); then echo "nested repository has unsaved files ($d: $why)"; return 0; fi 429 done < <(each_nested_repo "$1") 430 return 1 431 } 432 # Prints each repository inside $1, not $1 itself. A checkout is the parent of a 433 # path named .git. A bare repository is found by its shape whatever its name 434 # (.lake/packages/dep, vendor, dep.git): a folder holding a HEAD file, objects/ and refs/. 435 each_nested_repo() { 436 local g dir 437 while IFS= read -r g; do 438 [ -n "$g" ] || continue 439 case "$g" in 440 */.git) printf '%s\n' "${g%/.git}" ;; 441 *) 442 dir=${g%/HEAD} 443 [ -d "$dir/objects" ] && [ -d "$dir/refs" ] && printf '%s\n' "$dir" 444 ;; 445 esac 446 done < <(find "$1" -xdev -path "$1/.git" -prune -o -name .git -print -prune -o -type f -name HEAD -print 2>/dev/null) 447 } 448 # 0 and a one-line reason when a repository inside the copy, or a submodule commit, is not in ~/git. 449 # Looks in ignored folders and .lake too, and at bare repositories there. Those folders are build 450 # junk only when they hold no unsaved commit. 451 nested_unstored() { 452 local dir sha heads 453 while IFS= read -r dir; do 454 [ -n "$dir" ] || continue 455 if ! heads=$(repo_heads "$dir"); then echo "nested repository cannot be read ($dir)"; return 0; fi 456 while read -r sha; do 457 [ -n "$sha" ] || continue 458 if ! in_git_store "$sha"; then echo "nested repository has $sha not in ~/git ($dir)"; return 0; fi 459 done <<<"$(printf '%s\n' "$heads" | sort -u)" 460 done < <(each_nested_repo "$1") 461 if git -C "$1" rev-parse --is-inside-work-tree >/dev/null 2>&1; then 462 while read -r sha; do 463 [ -n "$sha" ] || continue 464 if ! in_git_store "$sha"; then echo "submodule commit $sha not in ~/git"; return 0; fi 465 done < <(git -C "$1" ls-tree -r HEAD 2>/dev/null | awk '$2=="commit" {print $3}') 466 fi 467 return 1 468 } 469 BUILD_JUNK_RE='^!! (.*/)?(target|build|node_modules|__pycache__|\.pytest_cache|\.mypy_cache|zig-cache|zig-out|\.zig-cache|\.lake|venv|\.venv)/?$|\.pyc$' 470 471 # classes listed in ~/.config/spark-cleanup/dry-classes (comma list, e.g. "5") or 472 # SPARK_CLEANUP_DRY_CLASSES only log WOULD-REMOVE, even under --apply 473 DRY_CLASSES="${SPARK_CLEANUP_DRY_CLASSES:-$(cat "$H/.config/spark-cleanup/dry-classes" 2>/dev/null)}" 474 REFUSED=0 DRYTOTAL=0 475 remove_dir() { # $1 class, $2 path, $3 reason-safe ; optional $4 lockfile 476 local c="$1" d="$2" why="$3" lf="${4:-}" sz 477 # paranoia: never remove a shallow or root-ish path; a top-level /tmp entry 478 # (depth 2) is the one shallow path class 5 exists to remove 479 local depth; depth=$(awk -F/ '{print NF-1}' <<<"$d") 480 case "$d" in /tmp/?*) [ "$depth" -eq 2 ] && depth=3 ;; esac 481 if [ "$depth" -lt 3 ] || [ "$d" = "$H" ]; then REFUSED=$((REFUSED+1)); return; fi 482 sz=$(size_of "$d"); sz=${sz:-0} 483 big_note "$d" "$sz" "class$c $([ $APPLY = 1 ] && echo removed || echo would-remove)" 484 if [ $APPLY = 1 ] && case ",${DRY_CLASSES// /}," in *",$c,"*) false ;; *) true ;; esac; then 485 if [ -n "$lf" ]; then 486 flock -n "$lf" $SUDO rm -rf --one-file-system -- "$d" || { log "class$c SKIP lock-taken $d"; return; } 487 else 488 rm -rf --one-file-system -- "$d" 2>/dev/null || $SUDO rm -rf --one-file-system -- "$d" 489 fi 490 log "class$c REMOVED $(human "$sz") $d ($why)" 491 elif [ $APPLY = 1 ]; then 492 log "class$c WOULD-REMOVE $(human "$sz") $d ($why) [dry-class]" 493 DRYTOTAL=$((DRYTOTAL + sz)); return 494 else 495 log "class$c WOULD-REMOVE $(human "$sz") $d ($why)" 496 fi 497 TOTAL=$((TOTAL + sz)) 498 } 499 500 # ---------------- class 1: build outputs ---------------- 501 is_cargo_target() { 502 [ -f "$1/CACHEDIR.TAG" ] && grep -q `8a477f597d28d172789f06886806bc55` "$1/CACHEDIR.TAG" 2>/dev/null && 503 { [ -d "$1/debug" ] || [ -d "$1/release" ] || [ -f "$1/.rustc_info.json" ]; } 504 } 505 class1() { 506 local list="$TMPD/c1" d prev="" lf min_age scan_machine=1 507 # A scratch-home test must not walk the machine's /tmp or CI lanes. The same 508 # switch on the real home is ignored, so it cannot turn those scans off there. 509 if [ -n "${SPARK_CLEANUP_OFFLINE:-}" ] && [ "$H" != "$(getent passwd "$(id -un)" | cut -d: -f6)" ]; then 510 scan_machine=0 511 log "class1 SKIP offline scratch home: not scanning /tmp/sweep or /var/lib/aien-run" 512 fi 513 { 514 find "$H/workspace" -maxdepth 5 -name CACHEDIR.TAG -printf '%h\n' 2>/dev/null 515 find "$H/work" -maxdepth 6 -name CACHEDIR.TAG -printf '%h\n' 2>/dev/null 516 [ "$scan_machine" = 1 ] && find /tmp/sweep -maxdepth 5 -name CACHEDIR.TAG -printf '%h\n' 2>/dev/null 517 find "$H/handoffs/hive/factory-bays" -maxdepth 6 -name CACHEDIR.TAG -printf '%h\n' 2>/dev/null 518 find "$H/.claude/jobs" -maxdepth 7 -name CACHEDIR.TAG -printf '%h\n' 2>/dev/null 519 find "$H/.cache" -maxdepth 3 -name CACHEDIR.TAG -printf '%h\n' 2>/dev/null 520 } | sort -u > "$list" 521 while read -r d; do 522 # skip nested tags inside a target we already listed 523 if [ -n "$prev" ] && case "$d/" in "$prev"/*) true ;; *) false ;; esac; then continue; fi 524 prev="$d" 525 [ -L "$d" ] && continue 526 is_cargo_target "$d" || continue 527 [ -n "$(each_nested_repo "$d" | head -1)" ] && { log "class1 SKIP has-git $d"; continue; } 528 under_only "$d" || continue 529 if protected_path "$d"; then log "class1 SKIP protected $d"; continue; fi 530 if in_use "$d" || in_use "$(dirname "$d")"; then log "class1 SKIP in-use $d"; continue; fi 531 min_age=$((AGE_H*60)) 532 case "$d" in "$H"/work/*|/tmp/sweep/*|"$H"/handoffs/hive/factory-bays/*) [ "$min_age" -lt 1440 ] && min_age=1440 ;; esac 533 if recent "$d" "$min_age"; then log "class1 SKIP modified<$((min_age/60))h $d"; continue; fi 534 remove_dir 1 "$d" "cargo target, idle $((min_age/60))h, nothing open" 535 done < "$list" 536 537 # CI judge lanes: /var/lib/aien-run/target//; only with the lane lock free 538 [ "$scan_machine" = 1 ] || return 539 [ ${#ONLY[@]} -gt 0 ] && return 540 [ -n "$SUDO" ] || { log "class1 SKIP aien-run (no sudo)"; return; } 541 local LK="$H/.local/state/aien-local-ci/locks/target" 542 for d in $($SUDO find /var/lib/aien-run/target -mindepth 3 -maxdepth 3 -type d -name '*.stale-*' 2>/dev/null); do 543 if in_use "$d"; then log "class1 SKIP in-use $d"; continue; fi 544 if recent "$d" $((AGE_H*60)); then log "class1 SKIP modified<${AGE_H}h $d"; continue; fi 545 remove_dir 1 "$d" "renamed stale CI build dir, cargo no longer uses it" 546 done 547 # per-SHA CI dirs (class "1s"): //<40-hex sha>, each with its own 548 # lock file; older SHAs that have none fall back to the lane lock 549 local lane s sl newest ssz 550 for lane in $($SUDO find /var/lib/aien-run/target -mindepth 2 -maxdepth 2 -type d 2>/dev/null); do 551 newest=$($SUDO find "$lane" -mindepth 1 -maxdepth 1 -type d -regextype posix-extended -regex '.*/[0-9a-f]{40}' -printf '%T@ %p\n' 2>/dev/null | sort -n | tail -1 | cut -d' ' -f2-) 552 [ -n "$newest" ] || continue 553 log "class1s KEEP newest-in-lane $newest" 554 for s in $($SUDO find "$lane" -mindepth 1 -maxdepth 1 -type d -regextype posix-extended -regex '.*/[0-9a-f]{40}' 2>/dev/null); do 555 [ "$s" = "$newest" ] && continue 556 sl="$LK/$(tr / _ <<<"$s").lock" 557 [ -e "$sl" ] || sl="$LK/$(tr / _ <<<"$lane").lock" 558 [ -e "$sl" ] || { log "class1s SKIP no-lock $s"; continue; } 559 if ! flock -n "$sl" true; then log "class1s SKIP lock-busy $s"; continue; fi 560 if in_use "$s"; then log "class1s SKIP in-use $s"; continue; fi 561 if recent "$s" $((AGE_H*60)); then log "class1s SKIP modified<${AGE_H}h $s"; continue; fi 562 ssz=$(size_of "$s"); ssz=${ssz:-0} 563 log "class1s SIZE $(human "$ssz") $s" 564 remove_dir 1s "$s" "per-SHA CI build output, not newest in lane, lock free, idle ${AGE_H}h" "$sl" 565 done 566 done 567 for d in $($SUDO find /var/lib/aien-run/target -mindepth 2 -maxdepth 2 -type d 2>/dev/null); do 568 lf="$LK/$(tr / _ <<<"$d").lock" 569 [ -e "$lf" ] || { log "class1 SKIP no-lane-lock $d"; continue; } 570 if ! flock -n "$lf" true; then log "class1 SKIP lane-busy $d"; continue; fi 571 if in_use "$d"; then log "class1 SKIP in-use $d"; continue; fi 572 if recent "$d" $((AGE_H*60)); then log "class1 SKIP modified<${AGE_H}h $d"; continue; fi 573 local k 574 for k in $($SUDO find "$d" -mindepth 1 -maxdepth 1 -type d \( -name debug -o -name release -o -name 'mutants*' -o -name '*-mutants' -o -name 'debug.*' -o -name 'release.*' \) 2>/dev/null); do 575 remove_dir 1 "$k" "CI lane build output, lane lock free, idle ${AGE_H}h" "$lf" 576 done 577 done 578 } 579 580 # ---------------- class 2: worktrees ---------------- 581 class2() { 582 local repo wt line 583 claim_paths "${SPARK_CLEANUP_BOARD:-$H/handoffs/BOARD.md}" "${SPARK_CLEANUP_CLAIMS:-$H/handoffs/hive/CLAIMS.md}" > "$TMPD/c2claims" 584 [ -s "$TMPD/rootclaims" ] && log "class2 ALARM claim of a whole copy folder not used: $(sort -u "$TMPD/rootclaims" | tr '\t\n' ' ;')" 585 for repo in $(find "$H/workspace" -maxdepth 2 -name .git -type d -printf '%h\n' 2>/dev/null); do 586 git -C "$repo" worktree list --porcelain 2>/dev/null | awk -v main="$repo" ' 587 /^worktree /{p=substr($0,10); lk=0} 588 /^locked/{lk=1} 589 /^$/{ if (p!=main) print lk"\t"p; p="" } 590 END{ if (p!="" && p!=main) print lk"\t"p }' > "$TMPD/wt" 591 while IFS=$'\t' read -r lk wt; do 592 [ -d "$wt" ] || continue 593 case "$wt" in "$H"/workspace/*|"$H"/.claude/jobs/*) ;; *) continue ;; esac 594 under_only "$wt" || continue 595 [ "$lk" = 1 ] && { log "class2 SKIP locked $wt"; continue; } 596 if claimed "$wt" "$TMPD/c2claims"; then log "class2 SKIP claimed $wt"; continue; fi 597 if protected_path "$wt"; then log "class2 SKIP protected $wt"; continue; fi 598 if in_use "$wt"; then log "class2 SKIP in-use $wt"; continue; fi 599 if recent "$wt" 1440; then log "class2 SKIP modified<24h $wt"; continue; fi 600 local why 601 why=$(copy_unsaved "$wt") || true 602 if [ -n "$why" ]; then log "class2 SKIP unsaved ($why) $wt"; continue; fi 603 local inner; inner=$(each_nested_repo "$wt" | head -1) 604 if [ -n "$inner" ]; then log "class2 SKIP nested-repo (${inner%/.git}) $wt"; continue; fi 605 local head 606 head=$(git -C "$wt" rev-parse --verify -q 'HEAD^{commit}' 2>/dev/null) 607 if [ -z "$head" ] || ! in_git_store "$head" >/dev/null; then log "class2 SKIP not-in-git-store $wt"; continue; fi 608 local sz; sz=$(size_of "$wt"); sz=${sz:-0} 609 if [ $APPLY = 1 ]; then 610 if git -C "$repo" worktree remove "$wt" 2>>"$LOG"; then 611 log "class2 REMOVED $(human "$sz") $wt (clean, HEAD in ~/git, idle 24h)"; TOTAL=$((TOTAL+sz)) 612 else 613 log "class2 FAILED git worktree remove $wt" 614 fi 615 else 616 log "class2 WOULD-REMOVE $(human "$sz") $wt (clean, HEAD in ~/git, idle 24h)"; TOTAL=$((TOTAL+sz)) 617 fi 618 done < "$TMPD/wt" 619 [ $APPLY = 1 ] && git -C "$repo" worktree prune 2>/dev/null 620 done 621 } 622 623 # ---------------- class 3: docker ---------------- 624 class3() { 625 [ -n "$SUDO" ] || { log "class3 SKIP no sudo"; return; } 626 command -v docker >/dev/null || return 627 if [ $APPLY = 1 ]; then 628 local b a; b=$(free_bytes) 629 $SUDO docker image prune -f >>"$LOG" 2>&1 630 $SUDO docker builder prune -f >>"$LOG" 2>&1 631 a=$(free_bytes); log "class3 REMOVED docker dangling images + build cache, df delta $(human $((a-b)))" 632 TOTAL=$((TOTAL + a - b)) 633 else 634 log "class3 WOULD-RUN docker image prune -f; docker builder prune -f" 635 $SUDO docker system df 2>/dev/null | tee -a "$LOG" 636 fi 637 } 638 639 # ---------------- class 4: caches and toolchains ---------------- 640 class4() { 641 local d f sz n 642 # cargo registry tarballs not read in 30 days (cargo re-downloads on demand) 643 if [ -d "$H/.cargo/registry/cache" ]; then 644 sz=$(find "$H/.cargo/registry/cache" -type f -name '*.crate' -atime +30 -printf '%s\n' | awk '{s+=$1}END{print s+0}') 645 if [ $APPLY = 1 ]; then find "$H/.cargo/registry/cache" -type f -name '*.crate' -atime +30 -delete; fi 646 log "class4 $([ $APPLY = 1 ] && echo REMOVED || echo WOULD-REMOVE) $(human "$sz") ~/.cargo/registry/cache crates unread 30d" 647 TOTAL=$((TOTAL+sz)) 648 fi 649 # rustup toolchains: keep default, stable, nightly, anything referenced or in use 650 if command -v rustup >/dev/null; then 651 local refs def 652 def=$(rustup default 2>/dev/null | awk '{print $1}') 653 refs=$(find "$H/workspace" -maxdepth 3 \( -name rust-toolchain -o -name rust-toolchain.toml \) -not -path '*/target/*' 2>/dev/null | 654 xargs -r grep -hoE '[0-9]+\.[0-9]+(\.[0-9]+)?|nightly[-0-9]*' 2>/dev/null | sort -u) 655 for d in "$H"/.rustup/toolchains/*; do 656 n=$(basename "$d"); local v=${n%%-aarch64*}; v=${v%%-x86_64*} 657 case "$v" in stable|nightly|beta) continue ;; esac 658 [ "$n" = "$def" ] && continue 659 grep -qxF "$v" <<<"$refs" && continue 660 if in_use "$d"; then log "class4 SKIP in-use $d"; continue; fi 661 if [ $APPLY = 1 ]; then 662 sz=$(size_of "$d"); rustup toolchain uninstall "$n" >>"$LOG" 2>&1 && { log "class4 REMOVED $(human "$sz") toolchain $n (no rust-toolchain file names it)"; TOTAL=$((TOTAL+sz)); } 663 else 664 sz=$(size_of "$d"); log "class4 WOULD-REMOVE $(human "$sz") toolchain $n (no rust-toolchain file names it)"; TOTAL=$((TOTAL+sz)) 665 fi 666 done 667 fi 668 # ~/.cache entries untouched for 7 days (huggingface holds models: class 7) 669 for d in "$H"/.cache/*; do 670 [ -e "$d" ] || continue 671 case "$(basename "$d")" in huggingface|pip|uv) continue ;; esac 672 if in_use "$d"; then log "class4 SKIP in-use $d"; continue; fi 673 if recent "$d" $((7*1440)); then continue; fi 674 remove_dir 4 "$d" "cache, untouched 7d" 675 done 676 } 677 678 # ---------------- class 5: /tmp ---------------- 679 # 0 and one line saying what, when a git repository in $1 ($1 itself included, nested ones 680 # and bare ones of any name too) holds something not saved in ~/git: the class 8 test of 681 # refs, submodule commits and unsaved files, repository by repository 682 repos_unsaved() { 683 local r heads sha why 684 while IFS= read -r r; do 685 [ -n "$r" ] || continue 686 if ! heads=$(repo_heads "$r"); then echo "git cannot read $r"; return 0; fi 687 while read -r sha; do 688 [ -n "$sha" ] || continue 689 in_git_store "$sha" || { echo "ref $sha of $r not in ~/git"; return 0; } 690 done < <(sort -u <<<"$heads") 691 [ -e "$r/.git" ] || continue 692 while read -r sha; do 693 [ -n "$sha" ] || continue 694 in_git_store "$sha" || { echo "submodule commit $sha of $r not in ~/git"; return 0; } 695 done < <(git -C "$r" ls-tree -r HEAD 2>/dev/null | awk '$2=="commit" {print $3}') 696 if why=$(copy_unsaved "$r" nested); then echo "$why in $r"; return 0; fi 697 done < <({ [ -e "$1/.git" ] || { [ -f "$1/HEAD" ] && [ -d "$1/objects" ] && [ -d "$1/refs" ]; }; } && printf '%s\n' "$1"; each_nested_repo "$1") 698 return 1 699 } 700 class5() { 701 local d sz why named="$TMPD/c5named" 702 # /tmp paths a worker's RESUME.md or a lock file names stay, however old 703 { find "$H/handoffs" -maxdepth 3 -name 'RESUME*.md' -type f -print0 2>/dev/null 704 find "$TMPROOT" -maxdepth 1 -name '*.lock' -type f -size -64k -print0 2>/dev/null 705 } | xargs -0r grep -ohaE "$TMPROOT/[A-Za-z0-9._+-]+" 2>/dev/null | sed 's#[.]*$##' | sort -u > "$named" 706 for d in "$TMPROOT"/* "$TMPROOT"/.[!.]*; do 707 [ -e "$d" ] || continue 708 # lock/slot/admit files (q36-extra uses .lock1/.lock2/.admit) and every aien-q36 marker stay: 709 # deleting a flock file while a holder has it open breaks mutual exclusion 710 case "$(basename "$d")" in systemd-private-*|.X11-unix|.ICE-unix|.XIM-unix|.font-unix|.Test-unix|tmux-*|ssh-*|snap-private-tmp|aien-quiet*|aien-gb10.lock|aien-q36*|cxo|*.lock|*.lock[0-9]*|*.admit|*.pid) continue ;; esac 711 [ -S "$d" ] && continue 712 if in_use "$d"; then continue; fi 713 if recent "$d" $((2*1440)); then continue; fi 714 if protected_path "$d"; then log "class5 SKIP protected $d"; continue; fi 715 if [ -f "$d/.git" ] && [ -e "$(git -C "$d" rev-parse --path-format=absolute --git-dir 2>/dev/null)/locked" ]; then log "class5 SKIP locked $d"; continue; fi 716 if grep -qxF -- "$d" "$named"; then log "class5 SKIP named-by-resume-or-lock $d"; continue; fi 717 # a git copy in /tmp is removed only when everything in it is saved in ~/git 718 if [ -d "$d" ] && why=$(repos_unsaved "$d"); then 719 sz=$(size_of "$d"); sz=${sz:-0} 720 log "class5 SKIP unsaved ($why) $(human "$sz") $d"; big_note "$d" "$sz" "class5 kept: unsaved" 721 continue 722 fi 723 remove_dir 5 "$d" "/tmp entry untouched 2d, nothing open, every git repository in it saved in ~/git" 724 done 725 } 726 727 # ---------------- class 6: journald ---------------- 728 class6() { 729 [ -n "$SUDO" ] || return 730 if [ $APPLY = 1 ]; then 731 local b a; b=$(free_bytes) 732 $SUDO journalctl --vacuum-size=2G >>"$LOG" 2>&1 733 a=$(free_bytes); log "class6 REMOVED journal vacuum to 2G, df delta $(human $((a-b)))"; TOTAL=$((TOTAL+a-b)) 734 else 735 log "class6 WOULD-RUN journalctl --vacuum-size=2G ($($SUDO journalctl --disk-usage 2>/dev/null | grep -oE '[0-9.]+[KMGT]'))" 736 fi 737 } 738 739 # ---------------- class 7: models (report only) ---------------- 740 class7() { 741 local d keep="qwen3.8-27b-fp8-`017b9c7a` qwen3.8-27b-fp8-`017b9c7a`.layouts qwen3-30b-a3b-instruct-2507-fp8 qwen3.8-27b-dflash2-`50307d4c`" 742 for d in "$H"/models/*/; do 743 d=${d%/}; local n; n=$(basename "$d") 744 grep -qw -- "$n" <<<"$keep" && continue 745 log "class7 REPORT $(human "$(size_of "$d")") $d $(in_use "$d" && echo IN-USE) (manual only; record repo+revision in ~/models/DELETED.md first)" 746 done 747 } 748 749 # ---------------- class 8: leftover copies (ALARM, report only) ---------------- 750 # Agents must delete their own copies when their task is done (omega-harness rule 751 # clean-up-after-yourself). This class finds the ones that did not. It never deletes. 752 # The --landed mode removes or archives the same copies, one landed repository at a time. 753 754 # Every task copy under the roots ($@), one per line, sorted. A repository inside one 755 # already listed (handled or skipped later) belongs to that copy; a linked worktree (its 756 # .git file points into some clone's .git/worktrees/) is its own task copy wherever it 757 # sits: agents' isolated worktrees live inside the main clones. 758 copy_list() { 759 local r up inner 760 local -A root=() 761 while read -r r; do 762 case "$r/" in "$GITSTORE"/*) continue ;; esac 763 up="${r%/*}"; inner=0 764 while [ "${#up}" -gt "${#H}" ]; do [ -n "${root[$up]:-}" ] && { inner=1; break; }; up="${up%/*}"; done 765 if [ $inner = 1 ] && ! grep -qs '^gitdir: .*/\.git/worktrees/' "$r/.git"; then continue; fi 766 root[$r]=1 767 printf '%s\n' "$r" 768 done < <(find "$@" -xdev -maxdepth 6 \( -name node_modules -o -name target -o -name .lake -o -name venv -o -name .venv \) -prune \ 769 -o -name .git -print -prune 2>/dev/null | sed 's#/\.git$##' | sort) 770 } 771 # main clones are shared reference copies: class 8 still checks them and reports work at risk in one, but a 772 # clean one is a SKIP line, not a "remove it" alarm; --landed never touches them. A main clone is a folder 773 # directly in ~/workspace with a real .git folder whose name either has no '-' (the standing rules' form, 774 # ~/workspace/) or is the name of a repository: a bare repository in the store (~/git/**/.git or 775 # -mv.git) or the last part of one of its remote URLs (with or without -mv). So ~/workspace/omega-harness, 776 # aien-architecture (store aien-architecture-mv.git) and aien-factory are main clones; a task folder named 777 # - is not. 778 declare -A STORE_NAME=() 779 for _b in "${STORE_REPOS[@]}"; do _b=${_b##*/}; _b=${_b%.git}; STORE_NAME[$_b]=1; STORE_NAME[${_b%-mv}]=1; done 780 is_main_clone() { 781 local n k u 782 [ -d "$1/.git" ] || return 1 783 case "$1" in "$H"/workspace/*/*) return 1 ;; "$H"/workspace/*) ;; *) return 1 ;; esac 784 n=${1##*/} 785 case "$n" in *-*) ;; *) return 0 ;; esac 786 [ -n "${STORE_NAME[$n]:-}" ] && return 0 787 while read -r k u; do 788 u=${u%/}; u=${u%.git}; u=${u##*[/:]} 789 [ "$u" = "$n" ] || [ "${u%-mv}" = "$n" ] && return 0 790 done < <(git -C "$1" config --get-regexp '^remote\..*\.url$' 2>/dev/null) 791 return 1 792 } 793 class8() { 794 local r n=0 bytes=0 kind why sz heads bad dirty ign f t0; t0=$(date +%s) 795 local idle_min=$((3*1440)) 796 local roots=() ; for r in "$H/workspace" "$H/work" "$H/.claude/jobs"; do [ -d "$r" ] && roots+=("$r"); done 797 [ ${#roots[@]} -gt 0 ] || return 0 798 # start mark for the --apply scan only (written here, after every early exit that is not a failure) 799 local marks=0; [ "$CLASSES" = 8 ] && [ $APPLY = 1 ] && marks=1 800 [ $marks = 1 ] && date +%s > "$STATE/class8.started" 801 local mainskip=0 main 802 : > "$TMPD/c8kinds"; : > "$TMPD/c8dirs" 803 copy_list "${roots[@]}" > "$TMPD/c8" 804 while read -r r; do 805 main=0; is_main_clone "$r" && main=1 806 protected_path "$r" && continue 807 in_use "$r" && continue 808 recent "$r" "$idle_min" && continue 809 # anything git cannot answer is "unreadable", never "leftover": an unanswered check is not a saved copy 810 if ! heads=$(repo_heads "$r"); then 811 kind=unreadable; why="git cannot read it (broken worktree, missing main clone, other owner): check by hand before anything is removed" 812 else 813 bad=0 814 while read -r f; do [ -n "$f" ] && ! in_git_store "$f" && bad=$((bad+1)); done <<<"$(sort -u <<<"$heads")" 815 local nest uns 816 nest=$(nested_unstored "$r") || true 817 uns=$(copy_unsaved "$r") || true 818 if [ "$bad" -gt 0 ]; then kind=unstored; why="$bad ref(s) not in ~/git (branch, stash, tag or remote-tracking): land the work or archive it" 819 elif [ -n "$nest" ]; then kind=unstored; why="$nest" 820 elif [ -n "$uns" ]; then kind=dirty; why="$uns" 821 elif [ -f "$r/.git" ]; then kind=leftover; why="clean linked worktree, its HEAD in ~/git (its branches live in the main clone and are not judged here), only build output ignored: finished work left its copy, remove it" 822 else kind=leftover; why="clean, every ref in ~/git, nested commits in ~/git, only build output ignored: finished work left its copy, archive and remove it"; fi 823 fi 824 if [ $main = 1 ] && [ "$kind" = leftover ]; then log "class8 SKIP main-clone $r (clean, every local ref in ~/git)"; mainskip=$((mainskip+1)); continue; fi 825 [ $main = 1 ] && why="main clone: $why" 826 sz=$(size_of "$r"); sz=${sz:-0} 827 log "class8 ALARM $kind-copy $(human "$sz") $r (idle 3d+, nothing open; $why)" 828 echo "$kind $r" >> "$TMPD/c8kinds"; echo "$r" >> "$TMPD/c8dirs" 829 n=$((n+1)); bytes=$((bytes+sz)) 830 done < "$TMPD/c8" 831 # model weights: a file with one link is a copy (a hard link from ~/models is a link); a file inside 832 # a copy reported above is already in that copy's size, so it is named but not added again 833 find "${roots[@]}" -xdev -type f -links 1 -size +1G \( -name '*.safetensors' -o -name '*.gguf' -o -name '*.pt' -o -name '*.pth' \) -print 2>/dev/null > "$TMPD/c8m" 834 while read -r f; do 835 [ -n "$f" ] || continue 836 protected_path "$f" && continue 837 sz=$(stat -c %s -- "$f" 2>/dev/null); sz=${sz:-0} 838 local inside=0 d; while read -r d; do [ -n "$d" ] && case "$f" in "$d"/*) inside=1; break ;; esac; done < "$TMPD/c8dirs" 839 log "class8 ALARM model-copy $(human "$sz") $f (model weights copied, not linked: keep one copy under ~/models and link to it$( [ $inside = 1 ] && echo '; inside a copy above, not counted twice'))" 840 echo "model $f" >> "$TMPD/c8kinds" 841 n=$((n+1)); [ $inside = 1 ] || bytes=$((bytes+sz)) 842 done < "$TMPD/c8m" 843 local thr_gb="${SPARK_CLEANUP_LEFTOVER_ALARM_GB:-1}" 844 if ! [[ "$thr_gb" =~ ^[0-9]+$ ]]; then 845 log "class8 ALARM bad SPARK_CLEANUP_LEFTOVER_ALARM_GB='$thr_gb' (whole GB expected); using 1"; thr_gb=1 846 fi 847 log "class8 total: $n copies, $(human "$bytes") ($(cut -d' ' -f1 "$TMPD/c8kinds" | sort | uniq -c | awk '{printf "%s%s %s", (NR>1?", ":""), $2, $1}')) (alarm threshold ${thr_gb}G); clean main clones skipped: $mainskip" 848 log "class8 scan took $(( ($(date +%s) - t0) / 60 )) min" 849 [ $marks = 1 ] && cp "$STATE/class8.started" "$STATE/class8.finished" 2>/dev/null 850 # one board line when the set of copies changes, not on every run 851 local sig last; sig=$(sort "$TMPD/c8kinds" | sha256sum | cut -c1-16); last=$(cat "$STATE/class8-posted" 2>/dev/null) 852 if [ "$n" -gt 0 ] && [ "$bytes" -ge $((thr_gb*`1000000000`)) ] && [ $APPLY = 1 ] && [ ${#ONLY[@]} -eq 0 ]; then 853 if [ "$sig" = "$last" ]; then 854 log "class8 board line not repeated: same set of copies as the last post ($sig)" 855 else 856 local board="${SPARK_CLEANUP_BOARD:-$H/handoffs/BOARD.md}" 857 printf '%s ALARM spark-cleanup class8 to all: %d agent copies left behind, %s (finished tasks that did not delete their copies, work not in ~/git, unreadable copies, or copied model weights). Each line: %s. Owners: save it as the clean-up rule says (landed, or a bundle in your lane records), then delete the copy; a copy whose owner has gone is archived to ~/archive/agent-work/.tar.zst first.\n' \ 858 "$(date -u +%FT%H:%MZ)" "$n" "$(human "$bytes")" "$LOG" >> "$board" && echo "$sig" > "$STATE/class8-posted" 859 fi 860 fi 861 } 862 863 # ---------------- --landed REPO: remove or archive that repository's finished copies ---------------- 864 LANDED_IDLE_H="${SPARK_CLEANUP_LANDED_IDLE_H:-6}" 865 LANDED_ARCHIVE_D="${SPARK_CLEANUP_LANDED_ARCHIVE_D:-3}" 866 CLAIM_DAYS="${SPARK_CLEANUP_CLAIM_DAYS:-14}" 867 ARCHIVE="${SPARK_CLEANUP_ARCHIVE:-$H/archive/agent-work}" 868 ARCHIVE_RESERVE_GB="${SPARK_CLEANUP_ARCHIVE_RESERVE_GB:-20}" 869 LANDED_ROOTS="" LKEEP=0 LREMOVED=0 LARCHIVED=0 LVIA="" 870 lkeep() { log "landed KEEP $1 ($2)$LVIA"; LKEEP=$((LKEEP+1)); } 871 # kept for a reason that passes: looked at again at the next landing of any repository ($STATE/landed-pending) 872 lwait() { lkeep "$@"; printf '%s\n' "$1" >> "$TMPD/pending.new"; } 873 # allocated bytes of the files only this folder holds (hard links elsewhere free nothing) 874 single_link_bytes() { $SUDO find "$1" -xdev -type f -links 1 -printf '%b\n' 2>/dev/null | awk '{s+=$1} END {printf "%d", s*512}'; } 875 # true when nothing outside .git folders changed for $2 minutes and find read the whole copy: 876 # a landing writes only inside .git (remote-tracking refs), so the copy it came from still counts as idle 877 idle_outside_git() { 878 local out; out=$($SUDO find "$1" -xdev -name .git -prune -o -mmin "-$2" -print -quit 2>/dev/null) || return 1 879 [ -z "$out" ] 880 } 881 # the main working folder of a git common dir (a bare main repository is its own) 882 main_of() { case "$1" in */.git) printf '%s\n' "${1%/.git}" ;; *) printf '%s\n' "$1" ;; esac; } 883 # true when a remote URL of the copy names the repository, or HEAD has a root commit of ~/git/**/.git 884 copy_matches_repo() { # $1 copy, $2 repository name 885 local k u c 886 while read -r k u; do 887 u=${u%/}; u=${u%.git} 888 [ "${u##*[/:]}" = "$2" ] && return 0 889 done < <(git -C "$1" config --get-regexp '^remote\..*\.url$' 2>/dev/null) 890 [ -n "$LANDED_ROOTS" ] || return 1 891 while read -r c; do 892 [ -n "$c" ] && grep -qxF -- "$c" <<<"$LANDED_ROOTS" && return 0 893 done < <(git -C "$1" rev-list --max-parents=0 HEAD 2>/dev/null) 894 return 1 895 } 896 # claimed: a CLAIM line (board or ~/handoffs/hive/CLAIMS.md, last CLAIM_DAYS days) names the copy, a folder 897 # above it or a path inside it, on a path boundary; or its worktree is locked. $2 holds one claimed absolute 898 # path per line (claim_paths below). 899 claimed() { # $1 copy, $2 file of claimed paths 900 local p 901 while read -r p; do 902 [ -n "$p" ] || continue 903 case "$1/" in "$p"/*) return 0 ;; esac 904 case "$p/" in "$1"/*) return 0 ;; esac 905 done < "$2" 906 [ -f "$1/.git" ] && [ -e "$(git -C "$1" rev-parse --path-format=absolute --git-dir 2>/dev/null)/locked" ] && return 0 907 return 1 908 } 909 # CLAIM lines still in force, as "laneline": dated in the last CLAIM_DAYS days (or undated), and not 910 # followed by a RELEASE line of the same lane (later in the same file, or later by its stamp in the other 911 # file). The lane is the first word next to CLAIM/RELEASE, harness names (omp, claude, ...) skipped: 912 # " CLAIM omp LaneX ...", " LaneX CLAIM ...", " LaneX (DRA-1) CLAIM ...", " | CLAIM | LaneX | ...". 913 # A CLAIM line whose lane cannot be read is never released. A claim file that does not exist is skipped (awk 914 # stops at a file it cannot open, which would lose the claims of the other file); one that exists but cannot 915 # be read is an ALARM. 916 live_claims() { # $@ claim files 917 local cutoff f files=() 918 for f in "$@"; do 919 if [ -r "$f" ]; then files+=("$f"); elif [ -e "$f" ]; then log "ALARM claim file cannot be read: $f"; fi 920 done 921 [ ${#files[@]} -gt 0 ] || return 0 922 cutoff=$(date -u -d "$CLAIM_DAYS days ago" +%FT%H:%M) 923 awk -v c="$cutoff" ' 924 function word(t) { gsub(/[:,]+$/, "", t); return t } 925 { 926 s = $0; sub(/^- /, "", s); gsub(/\*/, "", s) 927 n = split(s, w, /[ \t|]+/); k = 0; ts = "" 928 for (i = 1; i <= n; i++) { 929 if (w[i] == "") continue 930 if (k == 0 && ts == "" && w[i] ~ /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/) { ts = substr(w[i], 1, 16); continue } 931 if (w[i] ~ /^(omp|claude|codex|opencode|gemini)$/) continue 932 t[++k] = w[i]; if (k == 3) break 933 } 934 kind = ""; lane = "" 935 if (t[1] == "CLAIM" || t[1] == "RELEASE") { kind = t[1]; lane = word(t[2]) } 936 else if (t[2] == "CLAIM" || t[2] == "RELEASE") { kind = t[2]; lane = word(t[1]) } 937 else if ((t[3] == "CLAIM" || t[3] == "RELEASE") && t[2] ~ /^\(/) { kind = t[3]; lane = word(t[1]) } 938 else if ($0 ~ /(^|[^A-Za-z])CLAIM([^A-Za-z]|$)/) kind = "CLAIM" 939 delete t 940 if (kind == "CLAIM") { m++; cf[m] = FILENAME; cn[m] = FNR; ct[m] = ts; cl[m] = lane; cs[m] = $0 } 941 else if (kind == "RELEASE" && lane != "") { r++; rf[r] = FILENAME; rn[r] = FNR; rt[r] = ts; rl[r] = lane } 942 } 943 END { 944 for (i = 1; i <= m; i++) { 945 if (ct[i] != "" && ct[i] < c) continue 946 gone = 0 947 for (j = 1; j <= r && !gone; j++) { 948 if (cl[i] == "" || rl[j] != cl[i]) continue 949 if (rf[j] == cf[i]) gone = rn[j] > cn[i] 950 else gone = rt[j] != "" && ct[i] != "" && rt[j] > ct[i] 951 } 952 if (!gone) printf "%s\t%s\n", (cl[i] == "" ? "?" : cl[i]), cs[i] 953 } 954 }' "${files[@]}" 2>/dev/null 955 } 956 # every path a live CLAIM line names, absolute, without trailing punctuation: ~/x, $HOME/x and /home//x. 957 # A claim of a whole copy folder (~/workspace, ~/work, ~/.claude/jobs) or of a folder above one (~, ~/.claude) 958 # would keep every copy there: it is not used, and goes to $TMPD/rootclaims as "lanepath" for one ALARM. 959 claim_paths() { # $@ claim files 960 local lane line p q root 961 : > "$TMPD/rootclaims" 962 live_claims "$@" | while IFS=$'\t' read -r lane line; do 963 grep -oE "(~|\\\$HOME|$H)/[^[:space:]\"'\`<>|,;()]*" <<<"$line" \ 964 | sed -E "s#^(~|\\\$HOME)/#$H/#; s#[].:!?*]+\$##; s#/+\$##" \ 965 | while read -r p; do 966 case "$p" in "$H"|"$H"/*) ;; *) continue ;; esac 967 root=0 968 for q in "$H/workspace" "$H/work" "$H/.claude/jobs"; do 969 case "$q/" in "$p"/*) root=1 ;; esac 970 done 971 if [ "$root" = 1 ]; then printf '%s\t%s\n' "$lane" "$p" >> "$TMPD/rootclaims"; else printf '%s\n' "$p"; fi 972 done 973 done | sort -u 974 } 975 deep_enough() { [ "$(awk -F/ '{print NF-1}' <<<"$1")" -ge 3 ] && [ "$1" != "$H" ]; } 976 landed_remove() { # $1 copy, $2 git dir, $3 common dir: saved and idle 977 local r="$1" sz 978 deep_enough "$r" || { REFUSED=$((REFUSED+1)); lkeep "$r" "too shallow to remove"; return; } 979 sz=$(single_link_bytes "$r") 980 if [ "$2" != "$3" ]; then 981 git -C "$(main_of "$3")" worktree remove "$r" >>"$LOG" 2>&1 || { lkeep "$r" "git worktree remove refused it (message above)"; return; } 982 git -C "$(main_of "$3")" worktree prune >>"$LOG" 2>&1 983 else 984 rm -rf --one-file-system -- "$r" 2>/dev/null || $SUDO rm -rf --one-file-system -- "$r" 985 fi 986 if [ -e "$r" ]; then log "landed ALARM $r partly removed: everything in it was saved, look at what is left"; return; fi 987 log "landed REMOVED $(human "$sz") $r (saved: every ref and nested commit in ~/git, nothing unsaved, idle ${LANDED_IDLE_H} h+; $sz single-link bytes)$LVIA" 988 LREMOVED=$((LREMOVED+1)); TOTAL=$((TOTAL+sz)) 989 big_note "$r" "$sz" "landed removed" 990 } 991 # build output inside a copy, left out of its archive (rebuildable; copy_unsaved does not count it as 992 # unsaved either): ignored folders BUILD_JUNK_RE names and cargo targets (CACHEDIR.TAG). A folder with 993 # a repository inside is not build output. Prints absolute paths, none inside another. 994 build_output() { # $1 copy 995 local p 996 { git -C "$1" -c status.showUntrackedFiles=all status --porcelain=v1 --untracked-files=all --ignored=matching 2>/dev/null \ 997 | grep '^!! ' | grep -E "$BUILD_JUNK_RE" | sed 's/^!! //; s#/$##' | while IFS= read -r p; do printf '%s/%s\n' "$1" "$p"; done 998 find "$1" -xdev -name .git -prune -o -name CACHEDIR.TAG -printf '%h\n' 2>/dev/null \ 999 | while IFS= read -r p; do is_cargo_target "$p" && printf '%s\n' "$p"; done 1000 } | sort -u | while IFS= read -r p; do 1001 [ -d "$p" ] && [ ! -L "$p" ] || continue # single *.pyc files stay in 1002 [ "$p" != "$1" ] || continue 1003 [ -e "$p/.git" ] && continue 1004 [ -n "$(each_nested_repo "$p" | head -1)" ] && continue 1005 printf '%s\n' "$p" 1006 done | awk 'NR == 1 || index($0, prev "/") != 1 { print; prev = $0 }' 1007 } 1008 landed_archive() { # $1 copy, $2 git dir, $3 common dir, $4 what is unsaved 1009 local r="$1" gd="$2" cd="$3" why="$4" name a stage brel="" head="" f sz sha na ns ps 1010 local members=("${1#/}") nots=() skip=() skipn=0 skipb=0 p need room 1011 deep_enough "$r" || { REFUSED=$((REFUSED+1)); lkeep "$r" "too shallow to archive"; return; } 1012 mkdir -p "$ARCHIVE" || { lkeep "$r" "unsaved ($why); cannot create $ARCHIVE"; return; } 1013 name=$(basename "$r"); a="$ARCHIVE/$name.tar.zst" 1014 [ -e "$a" ] && a="$ARCHIVE/$name-$(date +%Y%m%dT%H%M%S).tar.zst" 1015 [ -e "$a" ] && { lkeep "$r" "unsaved ($why); archive name $a taken"; return; } 1016 # build output stays out; the free space must hold what goes in and still leave the reserve 1017 while IFS= read -r p; do [ -n "$p" ] && skip+=("$p"); done < <(build_output "$r") 1018 for p in "${skip[@]}"; do 1019 skipn=$((skipn + $(cd / && $SUDO find "${p#/}" 2>/dev/null | wc -l))) 1020 sz=$(size_of "$p"); skipb=$((skipb + ${sz:-0})) 1021 done 1022 sz=$(size_of "$r"); need=$(( ${sz:-0} - skipb + ARCHIVE_RESERVE_GB*`1000000000` )) 1023 room=$(df -B1 --output=avail "$ARCHIVE" 2>/dev/null | tail -1 | tr -d ' ') 1024 if ! [[ "$room" =~ ^[0-9]+$ ]] || [ "$room" -lt "$need" ]; then 1025 log "landed ALARM not enough free space to archive $r: need $(human "$need") (the copy without build output, plus a ${ARCHIVE_RESERVE_GB}G reserve), $ARCHIVE has $(human "${room:-0}")" 1026 lwait "$r" "unsaved ($why); not enough free space to archive"; return 1027 fi 1028 stage=$(mktemp -d "$TMPD/stage.XXXXXX") 1029 if [ "$gd" != "$cd" ]; then 1030 # a linked worktree: its record in the main clone goes into the archive too, and a HEAD that no 1031 # ~/git repository holds goes in as a bundle (removing the worktree drops the only ref to it) 1032 members+=("${gd#/}") 1033 head=$(git -C "$r" rev-parse -q --verify 'HEAD^{commit}' 2>/dev/null) 1034 if [ -n "$head" ] && ! in_git_store "$head"; then 1035 while read -r f; do [ -n "$f" ] && in_git_store "$f" && nots+=("^$f"); done < <(git -C "$r" for-each-ref --format='%(objectname)' refs/heads refs/remotes 2>/dev/null | sort -u) 1036 brel="${r#/}.HEAD.bundle"; mkdir -p "$stage/$(dirname "$brel")" 1037 git -C "$r" bundle create "$stage/$brel" HEAD "${nots[@]}" >>"$LOG" 2>&1 || { lkeep "$r" "unsaved ($why); bundle of HEAD failed"; return; } 1038 fi 1039 fi 1040 local tarargs=(--anchored --no-wildcards); for p in "${skip[@]}"; do tarargs+=("--exclude=${p#/}"); done 1041 tarargs+=(-C / "${members[@]}"); [ -n "$brel" ] && tarargs+=(-C "$stage" "$brel") 1042 $SUDO tar -cf - "${tarargs[@]}" 2>>"$LOG" | zstd -q -T4 -10 -o "$a" 2>>"$LOG" 1043 ps=("${PIPESTATUS[@]}") 1044 if [ "${ps[0]}" != 0 ] || [ "${ps[1]}" != 0 ] || ! zstd -tq "$a" 2>>"$LOG"; then 1045 rm -f "$a"; lkeep "$r" "unsaved ($why); archive failed (tar ${ps[0]}, zstd ${ps[1]})"; return 1046 fi 1047 na=$(zstd -dc "$a" | tar -tf - | wc -l) 1048 ns=$(cd / && $SUDO find "${members[@]}" 2>/dev/null | wc -l); ns=$((ns - skipn)); [ -n "$brel" ] && ns=$((ns+1)) 1049 if [ "$na" != "$ns" ]; then rm -f "$a"; lkeep "$r" "unsaved ($why); archive holds $na entries, the copy $ns"; return; fi 1050 # contents too: every member's bytes, size, mode and time against the copy (the bundle is in the stage) 1051 local tardiff=(-C /); [ -n "$brel" ] && tardiff=(--exclude="$brel" -C /) 1052 if ! zstd -dc "$a" | $SUDO tar -df - "${tardiff[@]}" >>"$LOG" 2>&1; then 1053 rm -f "$a"; lkeep "$r" "unsaved ($why); archive differs from the copy (tar -d)"; return 1054 fi 1055 sz=$(single_link_bytes "$r"); sha=$(sha256sum "$a" | cut -d' ' -f1) 1056 rm -rf --one-file-system -- "$r" 2>/dev/null || $SUDO rm -rf --one-file-system -- "$r" 1057 if [ -e "$r" ]; then log "landed ALARM $r archived to $a but not fully removed: look at what is left"; return; fi 1058 [ "$gd" != "$cd" ] && git -C "$(main_of "$cd")" worktree prune >>"$LOG" 2>&1 1059 mkdir -p "$r" 1060 { 1061 echo "Archived $(date -u +%FT%TZ) by spark-cleanup --landed $LANDED: unsaved work, nothing written for ${LANDED_ARCHIVE_D} days or more." 1062 echo "why: $why" 1063 echo "archive: $a" 1064 echo "sha256: $sha" 1065 echo "entries: $na" 1066 if [ -n "$brel" ]; then 1067 # the bundle goes into the main clone first: once the worktree record is back, its HEAD names 1068 # a commit the clone lacks and git refuses to unbundle into a repository with a broken HEAD 1069 echo "restore: cd / && zstd -dc '$a' | tar -xf - '$brel' && git -C '$(main_of "$cd")' bundle unbundle '/$brel' >/dev/null && zstd -dc '$a' | tar -xf - && rm '/$brel' '$r/ARCHIVED.txt'" 1070 echo "note: HEAD $head was in no ~/git repository; the archive holds it as a bundle that the restore line puts back into the main clone. If the main clone is gone, clone it from ~/git first." 1071 else 1072 echo "restore: cd / && zstd -dc '$a' | tar -xf - && rm '$r/ARCHIVED.txt'" 1073 fi 1074 [ "$gd" != "$cd" ] && echo "worktree: the archive also puts back its record $gd in the main clone $(main_of "$cd")" 1075 [ ${#skip[@]} -gt 0 ] && echo "left out: build output, rebuild it after a restore: ${skip[*]}" 1076 } > "$r/ARCHIVED.txt" 1077 log "landed ARCHIVED $(human "$sz") $r -> $a (unsaved: $why; $na entries, sha256 $sha, $sz single-link bytes; build output left out: ${#skip[@]} folder(s), $skipn entries)$LVIA" 1078 LARCHIVED=$((LARCHIVED+1)); TOTAL=$((TOTAL+sz)) 1079 } 1080 landed() { 1081 local repo="${LANDED%.git}" r b gd cd heads bad f nest uns n v why 1082 if ! [[ "$repo" =~ ^[A-Za-z0-9_][A-Za-z0-9._-]*$ ]]; then log "landed ALARM bad repository name '$LANDED': nothing done"; return; fi 1083 for v in LANDED_IDLE_H:6 LANDED_ARCHIVE_D:3 CLAIM_DAYS:14 ARCHIVE_RESERVE_GB:20; do 1084 n=${v%%:*} 1085 [[ "${!n}" =~ ^[0-9]+$ ]] || { log "landed ALARM bad SPARK_CLEANUP_$n='${!n}' (whole number expected); using ${v#*:}"; printf -v "$n" '%s' "${v#*:}"; } 1086 done 1087 if [ ${#STORE_REPOS[@]} -eq 0 ]; then log "landed ALARM git store $GITSTORE holds no bare repositories: nothing can be checked as saved, nothing done"; return; fi 1088 for b in "${STORE_REPOS[@]}"; do [ "${b##*/}" = "$repo.git" ] && LANDED_ROOTS+="$(git -C "$b" rev-list --max-parents=0 --all 2>/dev/null)"$'\n'; done 1089 [ -n "${LANDED_ROOTS//$'\n'/}" ] || { LANDED_ROOTS=""; log "landed: no $repo.git with commits in $GITSTORE; copies matched by remote URL only"; } 1090 local roots=(); for r in "$H/workspace" "$H/work" "$H/.claude/jobs"; do [ -d "$r" ] && roots+=("$r"); done 1091 [ ${#roots[@]} -gt 0 ] || { log "landed $repo: no copy folders"; return; } 1092 local board="${SPARK_CLEANUP_BOARD:-$H/handoffs/BOARD.md}" sig rc 1093 claim_paths "$board" "${SPARK_CLEANUP_CLAIMS:-$H/handoffs/hive/CLAIMS.md}" > "$TMPD/claims" 1094 log "landed: $(wc -l < "$TMPD/claims") claimed path(s) from CLAIM lines of the last $CLAIM_DAYS days not released" 1095 # a claim of a whole copy folder is not used; it is said in the log every run and on the board once per set 1096 if [ -s "$TMPD/rootclaims" ]; then 1097 rc=$(sort -u "$TMPD/rootclaims" | awk -F'\t' '{printf "%s%s names %s", (NR>1 ? "; " : ""), $1, $2}') 1098 log "landed ALARM CLAIM of a whole copy folder not used (it would keep every copy there): $rc" 1099 sig=$(sort -u "$TMPD/rootclaims" | sha256sum | cut -c1-16) 1100 if [ "$sig" = "$(cat "$STATE/rootclaims-posted" 2>/dev/null)" ]; then 1101 log "landed: root-claim board line not repeated ($sig)" 1102 # the line says "claim" in lower case: an upper-case CLAIM word would make it read as a CLAIM itself 1103 elif ( flock -w 30 8 || exit 1 1104 printf '%s ALARM spark-cleanup --landed to all: a claim line names a whole copy folder, which would keep every copy there from the landing clean-up, so it is not used: %s. Claim the copy'"'"'s own folder (e.g. ~/work/), or post RELEASE when done. Log: %s\n' \ 1105 "$(date -u +%FT%H:%MZ)" "$rc" "$LOG" >> "$board" ) 8>>"$board.lock"; then 1106 echo "$sig" > "$STATE/rootclaims-posted" 1107 fi 1108 fi 1109 # copies kept at an earlier landing for a reason that passes (recent, open, claimed, unsaved but recent, 1110 # no room to archive) are looked at again at every landing, of any repository 1111 local pending="$STATE/landed-pending" via 1112 : > "$TMPD/pending.new" 1113 [ -s "$pending" ] && log "landed: $(wc -l < "$pending") copy(ies) kept at an earlier landing looked at again ($pending)" 1114 copy_list "${roots[@]}" > "$TMPD/landed" 1115 while read -r r; do 1116 case "$r/" in /tmp/*|"$H"/handoffs/*) continue ;; esac 1117 if copy_matches_repo "$r" "$repo"; then via="" 1118 elif [ -s "$pending" ] && grep -qxF -- "$r" "$pending"; then via=" [kept at an earlier landing]" 1119 else continue 1120 fi 1121 LVIA=$via 1122 if is_main_clone "$r"; then lkeep "$r" "main clone"; continue; fi 1123 if protected_path "$r"; then lkeep "$r" "protected"; continue; fi 1124 if in_use "$r"; then lwait "$r" "open by a running process"; continue; fi 1125 if claimed "$r" "$TMPD/claims"; then lwait "$r" "claimed on the board or a locked worktree"; continue; fi 1126 if ! idle_outside_git "$r" $((LANDED_IDLE_H*60)); then lwait "$r" "written in the last ${LANDED_IDLE_H} h"; continue; fi 1127 if ! heads=$(repo_heads "$r"); then lkeep "$r" "git cannot read it: check by hand"; continue; fi 1128 gd=$(git -C "$r" rev-parse --path-format=absolute --git-dir 2>/dev/null) && cd=$(git -C "$r" rev-parse --path-format=absolute --git-common-dir 2>/dev/null) \ 1129 || { lkeep "$r" "git cannot read it: check by hand"; continue; } 1130 if [ "$gd" = "$cd" ] && [ "$(git -C "$r" worktree list --porcelain 2>/dev/null | grep -c '^worktree ')" -gt 1 ]; then 1131 lwait "$r" "other worktrees hang off this clone"; continue 1132 fi 1133 bad=0 1134 while read -r f; do [ -n "$f" ] && ! in_git_store "$f" && bad=$((bad+1)); done <<<"$(sort -u <<<"$heads")" 1135 nest=$(nested_unstored "$r") || true 1136 uns=$(copy_unsaved "$r") || true 1137 # the in-use set was collected at the start of the run: look again just before removing anything 1138 collect_inuse 1139 if in_use "$r"; then lwait "$r" "open by a running process (fresh look before removal)"; continue; fi 1140 if [ "$bad" = 0 ] && [ -z "$nest" ] && [ -z "$uns" ]; then landed_remove "$r" "$gd" "$cd"; continue; fi 1141 if [ "$bad" -gt 0 ]; then why="$bad ref(s) not in ~/git"; elif [ -n "$nest" ]; then why="$nest"; else why="$uns"; fi 1142 if ! idle_outside_git "$r" $((LANDED_ARCHIVE_D*1440)); then lwait "$r" "unsaved ($why), written in the last ${LANDED_ARCHIVE_D} d"; continue; fi 1143 landed_archive "$r" "$gd" "$cd" "$why" 1144 done < "$TMPD/landed" 1145 LVIA="" 1146 sort -u "$TMPD/pending.new" > "$pending.tmp" && mv "$pending.tmp" "$pending" 1147 log "landed $repo done: removed $LREMOVED, archived $LARCHIVED, kept $LKEEP; $(human "$TOTAL") of single-link files freed; $(wc -l < "$pending") kept copy(ies) to look at again at the next landing ($pending)" 1148 } 1149 [ -n "$LANDED" ] && landed 1150 1151 for c in 1 2 3 4 5 6 7 8; do 1152 want $c || continue 1153 b=$(free_bytes) 1154 "class$c" 1155 [ $APPLY = 1 ] && log "class$c done: df free $(human "$b") -> $(human "$(free_bytes)")" 1156 done 1157 1158 [ ${#BIG[@]} -gt 0 ] && log "ALARM entries over $(human "$BIG_ALARM") (SPARK_CLEANUP_BIG_ALARM=$BIG_ALARM bytes): $(printf '%s; ' "${BIG[@]}")look at why they grew" 1159 [ "$REFUSED" -gt 0 ] && log "REFUSED $REFUSED shallow paths (depth < 3); none removed" 1160 [ "$DRYTOTAL" -gt 0 ] && log "dry-classes ${DRY_CLASSES}: would-free $(human "$DRYTOTAL"), nothing removed for them" 1161 END_FREE=$(free_bytes) 1162 log "=== done $MODE: $( [ $APPLY = 1 ] && echo freed || echo would-free ) $(human "$TOTAL") (measured); df free $(human "$START_FREE") -> $(human "$END_FREE") ($(free_pct)%)" 1163 [ -n "$LANDED" ] && exit 0