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

chadtmiller.com/local.sweep-agent-builds.plist

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
5 files · 0 comments
History
Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>local.sweep-agent-builds</string>
	<key>ProgramArguments</key>
	<array>
		<string>/bin/sh</string>
		<string>__HOME__/.local/bin/sweep-agent-builds</string>
	</array>
	<key>StartInterval</key>
	<integer>3600</integer>
	<key>RunAtLoad</key>
	<true/>
	<key>ProcessType</key>
	<string>Background</string>
	<key>LowPriorityIO</key>
	<true/>
	<key>Nice</key>
	<integer>10</integer>
	<key>StandardErrorPath</key>
	<string>__HOME__/Library/Logs/sweep-agent-builds.err</string>
</dict>
</plist>
local.sweep-targets.plist 35 lines · 945 B Raw
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>EnvironmentVariables</key>
	<dict>
		<key>PATH</key>
		<string>/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin</string>
	</dict>
	<key>Label</key>
	<string>local.sweep-targets</string>
	<key>LowPriorityIO</key>
	<true/>
	<key>Nice</key>
	<integer>10</integer>
	<key>ProcessType</key>
	<string>Background</string>
	<key>ProgramArguments</key>
	<array>
		<string>__HOME__/.local/bin/sweep-targets</string>
		<string>--delete</string>
	</array>
	<key>StandardErrorPath</key>
	<string>__HOME__/Library/Logs/sweep-targets.log</string>
	<key>StandardOutPath</key>
	<string>__HOME__/Library/Logs/sweep-targets.log</string>
	<key>StartCalendarInterval</key>
	<dict>
		<key>Hour</key>
		<integer>4</integer>
		<key>Minute</key>
		<integer>0</integer>
	</dict>
</dict>
</plist>
README.md 153 lines · 8.7 KB Raw

Sweeping coding-agent build output on macOS

Coding agents working in git worktrees leave a lot behind: finished worktrees nobody removes, cargo target dirs, node_modules, Xcode DerivedData, scratch dirs in /tmp. These two launchd jobs clean that up once nothing has used it for a while. The only files they delete that git doesn't also keep are build output, dependencies and scratch.

JobRunsDeletes
sweep-agent-buildshourly, and at loginfinished worktrees, scratch dirs in /tmp, cargo target dirs, Xcode DerivedData, and node_modules in idle worktrees
sweep-targets --deletedaily at 04:00cargo target dirs anywhere under the folders you give it

The defaults cover herdr worktrees (~/.herdr/worktrees) and Claude Code worktrees (<repo>/.claude/worktrees) for repos kept in ~/code. Globs that match nothing are skipped, so point them at wherever your agents put worktrees (see Configure).

sweep-agent-builds

It looks at four lists of shell globs:

VariableDefaultSwept after
SWEEP_WORKTREES~/.herdr/worktrees/*/*, ~/code/*/.claude/worktrees/*target* at a worktree's root: 3 days. node_modules (up to 4 deep): 3 days, and only when the whole worktree is idle
SWEEP_TARGETS~/.cache/*target*, ~/.herdr/target*, ~/.herdr/worktrees/*/target*3 days
SWEEP_SCRATCH/private/tmp/*, /private/tmp/claude-<uid>/*1 day
SWEEP_CACHES~/Library/Developer/Xcode/DerivedData/*3 days

A directory is deleted only if:

  • no process has a file open under it (lsof),
  • nothing under it changed within the age above, and
  • for cargo dirs, it carries Cargo's marker (CACHEDIR.TAG, .rustc_info.json or a .cargo-lock).

A worktree counts as idle when no source file in it changed in 3 days (ignoring node_modules, target*, .git, .next, dist) and no process other than a shell has its working directory there. A running dev server or watcher therefore keeps its node_modules. Only dirs with a .git entry count as worktrees. In /tmp it never deletes com.apple.*, powerlog, android-*, tmux-* or claude-<uid> itself.

Finished worktrees

Before sweeping inside worktrees, it removes whole worktrees that are done, with git worktree remove. The branch stays, so git worktree add <path> <branch> brings one back. A worktree is removed only when all of these hold:

  • it is a linked worktree (its .git is a file), never a repository's main checkout
  • it is on a branch that exists, not a detached HEAD
  • git status shows nothing uncommitted or untracked
  • every ignored file or dir in it is named in SWEEP_DISPOSABLE (build output and caches such as node_modules, target*, dist, *.tsbuildinfo). An ignored .env, local database or keystore keeps the worktree.
  • no process has a file open in it or its working directory there
  • no commit or checkout (its HEAD and reflog) and no file change for SWEEP_WORKTREE_DAYS days (default 7)
  • if herdr is installed, herdr worktree list doesn't show it open as a workspace. If herdr cannot answer (not running, say), nothing in that repository is removed.

Removing a worktree whose branch was never pushed loses nothing: the branch and its commits live in the main repository. Set SWEEP_WORKTREE_DAYS=0 to never remove worktrees.

When free disk space drops under 20 GB, the ages shrink to 6 hours for /tmp and 1 day for everything else.

Each run appends a line to ~/Library/Logs/sweep-agent-builds.log, plus one deleted <K> <path> or removed worktree <K> <path> (branch <name>) line per removal:

2026-11-29 09:29:46 done: free 162G -> 162G, freed 0G (tmp 1440m, builds 4320m)

DRY_RUN=1 sweep-agent-builds writes would delete … and would remove worktree … lines instead, plus kept worktree (<reason>) <path> for each idle worktree it keeps and why, such as (ignored .env) or (uncommitted src/main.rs). That shows which names to add to SWEEP_DISPOSABLE for your repos.

sweep-targets

A wider pass, for cargo only. It searches every folder in SWEEP_ROOTS (colon-separated; default ~/code:~/.herdr/worktrees) for target dirs, at any depth, skipping node_modules, .git and DerivedData. It keeps a target dir unless all of these hold:

  • it has Cargo's marker (CACHEDIR.TAG or .rustc_info.json)
  • git tracks nothing inside it
  • no process has a file open inside it
  • nothing in its top three levels changed in SWEEP_DAYS days (default 3)

Without arguments it only reports (would remove …); --delete removes. If lsof lists nothing, it aborts instead of guessing. Output goes to ~/Library/Logs/sweep-targets.log, trimmed to its last 2000 lines.

Install

git clone knotless://chadtmiller.com/3n3htqbv63wba sweep && cd sweep
mkdir -p ~/.local/bin ~/Library/LaunchAgents ~/Library/Logs
install -m 755 sweep-agent-builds sweep-targets ~/.local/bin/

# launchd does not expand ~ or $HOME, so the plists carry a placeholder
for p in local.sweep-agent-builds.plist local.sweep-targets.plist; do
  sed "s|__HOME__|$HOME|g" "$p" > ~/Library/LaunchAgents/"$p"
  launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/"$p"
done

sweep-agent-builds runs as soon as it is loaded (RunAtLoad), so do a dry run of both before the launchctl step:

DRY_RUN=1 ~/.local/bin/sweep-agent-builds && grep -E 'would|kept' ~/Library/Logs/sweep-agent-builds.log
~/.local/bin/sweep-targets            # report only

launchctl list | grep sweep shows whether they are loaded; the middle column is the last exit status.

If lsof sees too little, give /bin/sh and /bin/bash Full Disk Access. Without open-file information sweep-targets refuses to run, but sweep-agent-builds could delete a dir that is in use.

Configure

Either edit the defaults at the top of each script, or set the variables in the job's plist so the script stays as published. launchd expands neither ~ nor $HOME, so write __HOME__ and let the install sed fill it in. Separate globs with newlines:

<key>EnvironmentVariables</key>
<dict>
	<key>SWEEP_WORKTREES</key>
	<string>__HOME__/src/*/.claude/worktrees/*
__HOME__/.my-agent/worktrees/*/*</string>
	<key>SWEEP_BUILD_MIN</key>
	<string>2880</string>
</dict>

Write paths without symlinks (/private/tmp, not /tmp): lsof reports real paths, and a busy dir reached through a symlink would not be recognized as busy. An empty list (<string></string>) skips that kind.

VariableScriptDefault
SWEEP_WORKTREES, SWEEP_TARGETS, SWEEP_SCRATCH, SWEEP_CACHESsweep-agent-buildssee above
SWEEP_TMP_MIN, SWEEP_BUILD_MINsweep-agent-builds1440, 4320 (minutes)
SWEEP_LOW_DISK_GB, SWEEP_LOW_TMP_MIN, SWEEP_LOW_BUILD_MINsweep-agent-builds20, 360, 1440
SWEEP_WORKTREE_DAYSsweep-agent-builds7 (0: never remove worktrees)
SWEEP_DISPOSABLEsweep-agent-buildsbuild output and cache names, space-separated shell patterns; see the script
SWEEP_LOGsweep-agent-builds~/Library/Logs/sweep-agent-builds.log
SWEEP_ROOTSsweep-targets~/code:~/.herdr/worktrees
SWEEP_DAYSsweep-targets3

After changing a plist, reload it with launchctl bootout gui/$(id -u)/<label> followed by launchctl bootstrap gui/$(id -u) <plist>.

Uninstall

launchctl bootout gui/$(id -u)/local.sweep-agent-builds
launchctl bootout gui/$(id -u)/local.sweep-targets
rm ~/Library/LaunchAgents/local.sweep-{agent-builds,targets}.plist \
   ~/.local/bin/sweep-{agent-builds,targets}

Smaller cargo builds in agent worktrees

The sweeps only delete stale output; worktrees agents are still using keep a full target each. Cargo reads .cargo/config.toml from every parent dir, so one file above your agents' worktrees shrinks every build there without touching your own checkouts:

# ~/.herdr/worktrees/.cargo/config.toml
[build]
incremental = false

[profile.dev]
debug = "line-tables-only"

[profile.test]
debug = "line-tables-only"

Incremental caches were about a quarter of all target bytes here, and over 40% of some. Backtraces keep file and line; debuggers lose variable inspection, and repeated rebuilds of the workspace's own crates are a little slower. This overrides a repo's own [profile.dev]. Check it took with cargo build -v in a worktree: rustc should get -C debuginfo=line-tables-only and no -C incremental=. Existing target/*/incremental dirs are no longer read, so they can be deleted.

Notes

  • Both jobs delete cargo targets in worktrees; whichever reaches a stale one first removes it.
  • Both run at low priority (Nice 10, LowPriorityIO, ProcessType Background).
  • A run scheduled while the Mac sleeps happens on wake.
  • Neither reports how big your worktrees are. For that: du -sk ~/.herdr/worktrees/*/ | sort -rn | head.
sweep-agent-builds 267 lines · 10.1 KB Raw
#!/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)"
sweep-targets 99 lines · 3.2 KB Raw
#!/bin/bash
# Reports, or with --delete removes, Cargo target folders nothing has written
# to in SWEEP_DAYS days anywhere under SWEEP_ROOTS. Only build output goes:
# worktrees and source stay.
#
# A folder is kept unless all of these hold:
#   - it is named target and holds Cargo's marker file
#   - git tracks nothing inside it
#   - no process has a file open inside it
#   - nothing in its top three levels changed in SWEEP_DAYS days
#
#   SWEEP_ROOTS  colon-separated dirs to search (default: ~/code and herdr's
#                worktrees; set it to where your repos and worktrees live)
#   SWEEP_DAYS   age in days (default 3)
#
# Run daily by launchd: ~/Library/LaunchAgents/local.sweep-targets.plist
# Log: ~/Library/Logs/sweep-targets.log
set -u

days="${SWEEP_DAYS:-3}"
roots="${SWEEP_ROOTS:-$HOME/code:$HOME/.herdr/worktrees}"

mode=report
case "${1:-}" in
  --delete) mode=delete ;;
  "") ;;
  *) echo "usage: sweep-targets [--delete]" >&2; exit 2 ;;
esac

tmp=$(mktemp -d "${TMPDIR:-/tmp}/sweep-targets.XXXXXX") || exit 1
trap 'rm -rf "$tmp"' EXIT

echo "== $(date '+%Y-%m-%d %H:%M:%S') mode=$mode days=$days"

# lsof exits non-zero on routine warnings, so judge it by what it printed. With
# no list there is no telling what is in use, so nothing is touched.
lsof -Fn 2>/dev/null | grep '^n/' | cut -c2- > "$tmp/open"
if [ ! -s "$tmp/open" ]; then
  echo "aborted: lsof listed no open files"
  exit 1
fi

count=0
total_kb=0
kept=0

IFS=: read -r -a root_list <<< "$roots"
for root in "${root_list[@]}"; do
  [ -d "$root" ] || continue
  # Not walking these is most of the speed: they hold millions of files and
  # no target folder worth sweeping.
  find "$root" \( -name node_modules -o -name .git -o -name .derivedData -o -name DerivedData \) -prune \
    -o -type d -name target -prune -print 2>/dev/null
done > "$tmp/targets"

while IFS= read -r t; do
  [ -e "$t/CACHEDIR.TAG" ] || [ -e "$t/.rustc_info.json" ] || continue

  if grep -qF -- "$t/" "$tmp/open"; then
    kept=$((kept + 1)); continue
  fi
  if [ -n "$(git -C "$(dirname "$t")" ls-files -- target 2>/dev/null | head -1)" ]; then
    echo "kept, tracked by git: $t"
    kept=$((kept + 1)); continue
  fi
  if [ -n "$(find "$t" -maxdepth 3 -mtime "-$days" -print -quit 2>/dev/null)" ]; then
    kept=$((kept + 1)); continue
  fi

  kb=$(du -sk "$t" 2>/dev/null | cut -f1)
  kb=${kb:-0}
  if [ "$mode" = delete ]; then
    # Sizing can take a while: look again in case a build started meanwhile.
    if [ -n "$(find "$t" -maxdepth 3 -mtime "-$days" -print -quit 2>/dev/null)" ]; then
      kept=$((kept + 1)); continue
    fi
    if ! rm -rf "$t"; then
      echo "failed to remove: $t"
      continue
    fi
    verb=removed
  else
    verb="would remove"
  fi
  echo "$verb $((kb / 1024)) MB: $t"
  count=$((count + 1))
  total_kb=$((total_kb + kb))
done < "$tmp/targets"

verb=$([ "$mode" = delete ] && echo removed || echo "would remove")
echo "$verb $count folders, $((total_kb / 1048576)) GB; kept $kept in use or recent"
echo "free: $(df -h "$HOME" | tail -1 | awk '{print $4}')"
echo "== done"

# The log keeps its last 2000 lines.
log="$HOME/Library/Logs/sweep-targets.log"
if [ -f "$log" ] && [ "$(wc -l < "$log")" -gt 4000 ]; then
  tail -n 2000 "$log" > "$tmp/log" && cat "$tmp/log" > "$log"
fi