~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/3n3htqbv63wba

Clean up after coding agents on macOS: remove finished git worktrees and sweep stale build output (cargo targets, node_modules, DerivedData, /tmp) with two launchd jobs

0
0
main
267 lines · 10.1 KB Raw History
#!/bin/sh
# sweep-agent-builds: deletes the build output and scratch space coding agents
# leave behind, once nothing under it has changed for a while and no process
# has it open. Source files are never touched. macOS; run hourly by launchd
# (local.sweep-agent-builds.plist). DRY_RUN=1 only logs what it would delete.
#
# What it looks at: lists of shell globs, one per line. Edit the defaults
# below, or set them in the environment (the plist's EnvironmentVariables).
# A glob matching nothing is skipped, so unused defaults are harmless.
#
#   SWEEP_WORKTREES  agent worktrees, each a git checkout. A finished one is
#                    removed whole (see below). In the rest, cargo target
#                    dirs at its root (target*) go once stale, and
#                    node_modules (up to 4 levels deep) go once the whole
#                    worktree is idle and no dev server runs in it.
#   SWEEP_TARGETS    cargo target dirs kept outside any worktree
#   SWEEP_SCRATCH    scratch dirs (agents' temp builds, screenshots, sims)
#   SWEEP_CACHES     other build caches, any dir
#
# Ages are minutes since the newest file under a dir changed. Below
# SWEEP_LOW_DISK_GB free, the shorter ages apply.
#
# A worktree is removed (git worktree remove; its branch stays, so
# `git worktree add <path> <branch>` brings it back) only when all hold:
#   - it is a linked worktree, not a repository's main checkout
#   - it is on a branch, not a detached HEAD
#   - nothing is uncommitted or untracked, and every ignored file in it is
#     one SWEEP_DISPOSABLE names (build output, caches), not a .env or a
#     local database
#   - no process has a file open in it or works in it
#   - no commit, checkout or file change in it for SWEEP_WORKTREE_DAYS days
#   - herdr, if installed, does not have it open as a workspace (if herdr
#     cannot say, nothing in that repository is removed)
# SWEEP_WORKTREE_DAYS=0 never removes a worktree.
set -u

uid=$(/usr/bin/id -u)

# Set a list to empty to skip that kind.
SWEEP_WORKTREES=${SWEEP_WORKTREES-"
$HOME/.herdr/worktrees/*/*
$HOME/code/*/.claude/worktrees/*
"}
SWEEP_TARGETS=${SWEEP_TARGETS-"
$HOME/.cache/*target*
$HOME/.herdr/target*
$HOME/.herdr/worktrees/*/target*
"}
SWEEP_SCRATCH=${SWEEP_SCRATCH-"
/private/tmp/*
/private/tmp/claude-$uid/*
"}
SWEEP_CACHES=${SWEEP_CACHES-"
$HOME/Library/Developer/Xcode/DerivedData/*
"}
# Names (shell patterns) of ignored files and dirs a worktree may lose.
SWEEP_DISPOSABLE=${SWEEP_DISPOSABLE-"
node_modules target* dist build out coverage
.next .turbo .vite .astro .svelte-kit .parcel-cache .cache .gradle
DerivedData .derivedData __pycache__ .pytest_cache .mypy_cache .ruff_cache
.DS_Store *.tsbuildinfo *.d.ts *.log
"}

TMP_MIN=${SWEEP_TMP_MIN:-1440}           # 1 day
BUILD_MIN=${SWEEP_BUILD_MIN:-4320}       # 3 days
LOW_DISK_GB=${SWEEP_LOW_DISK_GB:-20}
LOW_TMP_MIN=${SWEEP_LOW_TMP_MIN:-360}    # 6 hours
LOW_BUILD_MIN=${SWEEP_LOW_BUILD_MIN:-1440}
WORKTREE_DAYS=${SWEEP_WORKTREE_DAYS:-7}
DRY_RUN=${DRY_RUN:-0}
LOG=${SWEEP_LOG:-$HOME/Library/Logs/sweep-agent-builds.log}

log() { printf '%s %s\n' "$(/bin/date '+%F %T')" "$*" >> "$LOG"; }

free_gb() { /bin/df -k "$HOME" | /usr/bin/awk 'NR==2{print int($4/1048576)}'; }

before=$(free_gb)
if [ "$before" -lt "$LOW_DISK_GB" ]; then
  TMP_MIN=$LOW_TMP_MIN BUILD_MIN=$LOW_BUILD_MIN
fi

open_paths=$(/usr/bin/mktemp -t sweep-open)
busy_cwds=$(/usr/bin/mktemp -t sweep-cwd)
candidates=$(/usr/bin/mktemp -t sweep-dirs)
worktrees=$(/usr/bin/mktemp -t sweep-wts)
herdr_open=$(/usr/bin/mktemp -t sweep-herdr)
trap '/bin/rm -f "$open_paths" "$busy_cwds" "$candidates" "$worktrees" "$herdr_open"' EXIT
{ /usr/sbin/lsof -Fn +c0 2>/dev/null; /usr/sbin/lsof -d cwd -Fn 2>/dev/null; } |
  /usr/bin/awk '/^n\//{print substr($0,2)}' | /usr/bin/sort -u > "$open_paths"
# Working dirs of everything but idle shells: a dev server's cwd marks its
# worktree busy even though it holds no file in node_modules open.
/usr/sbin/lsof -d cwd -Fcn 2>/dev/null |
  /usr/bin/awk '/^c/{c=substr($0,2)} /^n\//{if (c !~ /^-?(zsh|bash|sh|fish|login)$/) print substr($0,2)}' |
  /usr/bin/sort -u > "$busy_cwds"

# each LIST: the real (not symlinked) dirs LIST's globs match, one per line.
each() {
  (
    IFS='
'
    for p in $1; do
      p=${p%/}
      [ -d "$p" ] && [ ! -L "$p" ] && printf '%s\n' "$p"
    done
  )
}

is_cargo_target() {
  [ -f "$1/CACHEDIR.TAG" ] || [ -f "$1/.rustc_info.json" ] ||
    [ -f "$1/debug/.cargo-lock" ] || [ -f "$1/release/.cargo-lock" ]
}

# worktree_idle WT MINUTES: no source file under WT changed in MINUTES
# minutes (dependencies, build output and .git excluded) and no non-shell
# process works in it. Files only: deleting a node_modules or target dir,
# as this script does, touches the dir that held it.
worktree_idle() {
  if /usr/bin/grep -qxF "$1" "$busy_cwds" || /usr/bin/grep -qF "$1/" "$busy_cwds"; then
    return 1
  fi
  [ -z "$(/usr/bin/find "$1" \( -name node_modules -o -name 'target*' -o -name .git \
    -o -name .next -o -name dist \) -prune -o -type f -mmin -"$2" -print -quit 2>/dev/null)" ]
}

freed_kb=0

# disposable NAME: whether an ignored file or dir of this name may be lost.
disposable() {
  (
    set -f
    for g in $SWEEP_DISPOSABLE; do
      case "$1" in $g) exit 0 ;; esac
    done
    exit 1
  )
}

# keep_reason WT: what in WT removing it would lose, or nothing.
keep_reason() {
  st=$(/usr/bin/git -C "$1" status --porcelain --ignored 2>/dev/null) || {
    echo "git status failed"; return
  }
  printf '%s\n' "$st" | while IFS= read -r line; do
    case "$line" in
      '') ;;
      '!! '*)
        p=${line#!! }; p=${p%/}
        disposable "${p##*/}" || { echo "ignored $p"; break; } ;;
      *) echo "uncommitted ${line#???}"; break ;;
    esac
  done
}

herdr=$(command -v herdr 2>/dev/null) || herdr=$HOME/.local/bin/herdr
[ -x "$herdr" ] || herdr=

# herdr_has_open WT COMMON: whether herdr has WT open as a workspace, or
# cannot say. COMMON is its repository's git dir: one query per repository.
herdr_has_open() {
  [ -n "$herdr" ] || return 1
  if ! /usr/bin/awk -F'\t' -v c="$2" '$1 == c {f = 1} END {exit !f}' "$herdr_open"; then
    # "ok" first, then the open paths. No "ok" when herdr gave no list (not
    # running, not a repository): jq prints nothing for no input, fails on
    # an error reply.
    if list=$("$herdr" worktree list --cwd "$1" 2>/dev/null |
      /usr/bin/jq -r '"ok", (.result.worktrees[] | select(.open_workspace_id) | .path)' 2>/dev/null) &&
      [ "$(printf '%s\n' "$list" | /usr/bin/head -1)" = ok ]; then
      printf '%s\t\n' "$2" >> "$herdr_open"
      printf '%s\n' "$list" | /usr/bin/sed 1d | while IFS= read -r p; do
        printf '%s\t%s\n' "$2" "$p"
      done >> "$herdr_open"
    else
      printf '%s\t?\n' "$2" >> "$herdr_open"
    fi
  fi
  /usr/bin/awk -F'\t' -v c="$2" -v w="$1" '$1 == c && ($2 == w || $2 == "?") {f = 1} END {exit !f}' "$herdr_open"
}

# Finished worktrees go whole, before anything is swept inside them.
each "$SWEEP_WORKTREES" > "$worktrees"
if [ "$WORKTREE_DAYS" -gt 0 ]; then
  wt_min=$((WORKTREE_DAYS * 1440))
  while IFS= read -r wt; do
    [ -f "$wt/.git" ] || continue  # a main checkout has a .git dir
    /usr/bin/grep -qF "$wt/" "$open_paths" && continue
    /usr/bin/grep -qxF "$wt" "$open_paths" && continue
    gd=$(/usr/bin/git -C "$wt" rev-parse --absolute-git-dir 2>/dev/null) || continue
    [ -z "$(/usr/bin/find "$gd/HEAD" "$gd/logs/HEAD" -mmin -"$wt_min" 2>/dev/null)" ] || continue
    worktree_idle "$wt" "$wt_min" || continue
    branch=$(/usr/bin/git -C "$wt" symbolic-ref -q --short HEAD) || continue
    /usr/bin/git -C "$wt" rev-parse -q --verify HEAD > /dev/null || continue
    common=$(/usr/bin/git -C "$wt" rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || continue
    if herdr_has_open "$wt" "$common"; then
      [ "$DRY_RUN" = 1 ] && log "kept worktree (open in herdr, or herdr cannot say) $wt"
      continue
    fi
    why=$(keep_reason "$wt")
    if [ -n "$why" ]; then
      [ "$DRY_RUN" = 1 ] && log "kept worktree ($why) $wt"
      continue
    fi
    kb=$(/usr/bin/du -sk "$wt" 2>/dev/null | /usr/bin/cut -f1)
    if [ "$DRY_RUN" = 1 ]; then
      log "would remove worktree ${kb:-0}K $wt (branch $branch)"
    elif /usr/bin/git --git-dir="$common" worktree remove "$wt" 2>> "$LOG"; then
      log "removed worktree ${kb:-0}K $wt (branch $branch)"
    else
      log "failed to remove worktree $wt"
      continue
    fi
    freed_kb=$((freed_kb + ${kb:-0}))
  done < "$worktrees"
fi

# Each candidate as "MINUTES DIR".
{
  each "$SWEEP_SCRATCH" | while IFS= read -r d; do
    # System and session dirs that live in /tmp: never scratch.
    case "${d##*/}" in
      com.apple.*|powerlog|android-*|tmux-*|"claude-$uid") continue ;;
    esac
    printf '%s %s\n' "$TMP_MIN" "$d"
  done

  each "$SWEEP_TARGETS" | while IFS= read -r d; do
    is_cargo_target "$d" && printf '%s %s\n' "$BUILD_MIN" "$d"
  done

  each "$SWEEP_CACHES" | while IFS= read -r d; do
    printf '%s %s\n' "$BUILD_MIN" "$d"
  done

  each "$SWEEP_WORKTREES" | while IFS= read -r wt; do
    [ -e "$wt/.git" ] || continue
    for t in "$wt"/target*/; do
      t=${t%/}
      [ -d "$t" ] && [ ! -L "$t" ] && is_cargo_target "$t" && printf '%s %s\n' "$BUILD_MIN" "$t"
    done
    worktree_idle "$wt" "$BUILD_MIN" || continue
    /usr/bin/find "$wt" -maxdepth 4 -type d -name node_modules -prune -print 2>/dev/null |
      while IFS= read -r nm; do printf '%s %s\n' "$BUILD_MIN" "$nm"; done
  done
} > "$candidates"

# sweep DIR MINUTES: delete DIR when no process has anything under it open
# and nothing under it changed in the last MINUTES minutes.
sweep() {
  dir=$1
  if /usr/bin/grep -qxF "$dir" "$open_paths" || /usr/bin/grep -qF "$dir/" "$open_paths"; then
    return 0
  fi
  recent=$(/usr/bin/find "$dir" -mmin -"$2" -print -quit 2>/dev/null) || return 0
  [ -z "$recent" ] || return 0
  kb=$(/usr/bin/du -sk "$dir" 2>/dev/null | /usr/bin/cut -f1)
  if [ "$DRY_RUN" = 1 ]; then
    log "would delete ${kb:-0}K $dir"
  elif /bin/rm -rf "$dir"; then
    log "deleted ${kb:-0}K $dir"
  fi
  freed_kb=$((freed_kb + ${kb:-0}))
}

while read -r minutes dir; do
  sweep "$dir" "$minutes"
done < "$candidates"

log "done: free ${before}G -> $(free_gb)G, $( [ "$DRY_RUN" = 1 ] && echo would\ free || echo freed ) $((freed_kb / 1048576))G (tmp ${TMP_MIN}m, builds ${BUILD_MIN}m)"