The evening an Xcode build died with a "not enough disk space" error, I started typing "please free up some space" into Claude Code in my terminal, and my finger stopped just before Enter.
That morning I had read Issue #113389, a report from someone who asked for a disk cleanup and lost things that should never have been touched. My iMac holds build products from my wallpaper apps, Gradle caches from the Android side, and node_modules folders from the websites I run. "Free up some space" told Claude Code nothing about which of those were safe to remove.
The rule I ended up with is short. What can be rebuilt, Claude Code may delete; what cannot, goes on a list for me to decide. What follows is how I turned that sentence into an allowlist and a hook.
Asking for a list first surfaced my Archives folder
My first attempt was simply to ask, before any deletion, for candidates sorted by size. The list that came back was mostly sensible: DerivedData, the Gradle cache, old simulators — and ~/Library/Developer/Xcode/Archives.
For me, Archives is off limits. It holds the dSYMs for versions already shipped to the stores, and I need them to turn crash reports back into readable lines. DerivedData comes back with the next build. An archive of a version I shipped last year cannot be produced again.
I don't think Claude Code judged badly. Sort by size and Archives naturally floats to the top. Whether something can be rebuilt is simply knowledge that lives with whoever runs the project — in my case, an indie developer with no way to recreate old release builds.
Writing down the safe places by one question: can it be rebuilt?
So I wrote the safe places down in advance, using a single test: if this disappears, does one command or one build bring it back?
| Location | Rebuildable? | Handling |
|---|---|---|
| ~/Library/Developer/Xcode/DerivedData | Yes, by building | On the allowlist |
| ~/.gradle/caches | Re-downloaded on next build | Stop the Gradle daemon first |
| node_modules and .next in each project | npm ci plus a build | On the allowlist |
| Unavailable simulators | Removed with the official tool | xcrun simctl, not rm |
| ~/Library/Developer/Xcode/Archives | No | Listed only, never deleted |
I keep rm away from simulators because it lets Xcode's device registry drift from what is on disk; xcrun simctl delete unavailable removes only devices the current Xcode can no longer use. Gradle is similar. Clearing its cache while a daemon is alive can lead to confusing failures on the next build, so ./gradlew --stop comes first.
A hook that stops deletes outside the allowlist
A written list can still slip out of view halfway through a long session, so I gave the list to a PreToolUse hook. It receives each Bash command before it runs, and if a delete targets anything outside the allowlist, it exits with code 2. With exit code 2, stderr goes back to Claude Code, so the reason for the block becomes part of its next decision.
#!/usr/bin/env python3
# ~/.claude/hooks/cleanup_guard.py
# Block delete commands whose targets fall outside "rebuildable" locations
import json, os, re, shlex, sys
HOME = os.path.expanduser("~")
ALLOWED_ROOTS = [
f"{HOME}/Library/Developer/Xcode/DerivedData",
f"{HOME}/.gradle/caches",
]
ALLOWED_DIRNAMES = {"node_modules", ".next"} # only these names, inside projects
DELETE_WORDS = {"rm", "rmdir", "unlink", "trash"}
def block(msg):
print(f"cleanup_guard: {msg}. List it and wait for a human decision.", file=sys.stderr)
sys.exit(2)
def allowed(path):
real = os.path.realpath(os.path.expanduser(path.rstrip("/*")))
if any(real == r or real.startswith(r + "/") for r in ALLOWED_ROOTS):
return True
parts = real.split("/")
return real.startswith(f"{HOME}/Projects/") and any(p in ALLOWED_DIRNAMES for p in parts)
data = json.load(sys.stdin)
cmd = data.get("tool_input", {}).get("command", "")
if not re.search(r"\b(rm|rmdir|unlink|trash)\b|-delete\b", cmd):
sys.exit(0)
if re.search(r"\$\(|\$\{|\$[A-Za-z_]|`", cmd):
block("the delete command contains a variable or command substitution")
try:
tokens = shlex.split(cmd)
except ValueError:
block("could not parse the command")
if "-delete" in tokens:
block("find -delete cannot fix its targets in advance")
# Split on && ; | and only check arguments of segments that start with a delete command
targets, seg = [], []
for tok in tokens + [";"]:
if tok in {"&&", ";", "|", "||"}:
words = [w for w in seg if w != "sudo"]
if words and words[0] in DELETE_WORDS:
targets += [w for w in words[1:] if not w.startswith("-")]
seg = []
else:
seg.append(tok)
for t in targets:
if os.path.islink(os.path.expanduser(t.rstrip("/"))):
block(f"{t} is a symbolic link")
if not allowed(t):
block(f"{t} is outside the allowlist")
sys.exit(0)The hook is registered under hooks in ~/.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "python3 ~/.claude/hooks/cleanup_guard.py" }
]
}
]
}
}Paths are resolved with realpath before comparison because plain string matching misses forms like DerivedData/../Archives, or a link inside an allowed folder that points somewhere else. This is not a full shell parser, and I don't treat it as a guarantee. It is a coarse net meant to fall on the side of stopping whenever things are unclear.
Three stop signals
I narrowed the moments when the hook steps in to three signals:
- The target is outside the allowlist. I haven't confirmed that it can be rebuilt.
- The path contains a variable or command substitution. The scope of the delete isn't known until it runs; an empty variable turning
rm -rf "$DIR/"toward another place is exactly how these accidents happen. - The target is a symbolic link. What it looks like and what actually disappears are different things.
I also added one line to CLAUDE.md about what happens after a signal: "If cleanup_guard blocks you, don't work around it — list the target and its size, then wait." Before that line existed, there was one run where a blocked delete was retried in a different form. A stop only works, I've come to feel, when you also decide what happens after the stop.
What changed once it was running
The way I ask for cleanup has changed. Now it goes in this order:
- First, list candidates and sizes with
du -sh(no deletion) - Delete only the items on that list that sit inside the allowlist
- Everything else, I look at and decide by hand
Asking for the list first isn't about distrusting Claude Code. It is so that I see, at least once, what is about to vanish. That context — which builds I could never recreate — exists only on my side.
I wrote about the same idea for Cowork, where the answer was to move rather than delete (choosing a holding folder before asking Cowork to tidy up). Measuring whether an operation can be undone by its state rather than its name is covered in my notes on auto mode reversibility.
If you try one thing, write down three places on your own machine that come back when deleted. For me, writing those three was the moment it became obvious why Archives had to stay off the list.