~ 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
153 lines · 8.7 KB Raw History
# 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.

| Job | Runs | Deletes |
|---|---|---|
| `sweep-agent-builds` | hourly, and at login | finished worktrees, scratch dirs in `/tmp`, cargo `target` dirs, Xcode DerivedData, and `node_modules` in idle worktrees |
| `sweep-targets --delete` | daily at 04:00 | cargo `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](#configure)).

## sweep-agent-builds

It looks at four lists of shell globs:

| Variable | Default | Swept 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

```sh
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:

```sh
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:

```xml
<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.

| Variable | Script | Default |
|---|---|---|
| `SWEEP_WORKTREES`, `SWEEP_TARGETS`, `SWEEP_SCRATCH`, `SWEEP_CACHES` | sweep-agent-builds | see above |
| `SWEEP_TMP_MIN`, `SWEEP_BUILD_MIN` | sweep-agent-builds | 1440, 4320 (minutes) |
| `SWEEP_LOW_DISK_GB`, `SWEEP_LOW_TMP_MIN`, `SWEEP_LOW_BUILD_MIN` | sweep-agent-builds | 20, 360, 1440 |
| `SWEEP_WORKTREE_DAYS` | sweep-agent-builds | 7 (0: never remove worktrees) |
| `SWEEP_DISPOSABLE` | sweep-agent-builds | build output and cache names, space-separated shell patterns; see the script |
| `SWEEP_LOG` | sweep-agent-builds | `~/Library/Logs/sweep-agent-builds.log` |
| `SWEEP_ROOTS` | sweep-targets | `~/code:~/.herdr/worktrees` |
| `SWEEP_DAYS` | sweep-targets | 3 |

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

## Uninstall

```sh
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:

```toml
# ~/.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`.