The deletion guard that stopped crying wolf
Our agents asked before every delete, so we learned to click Allow. Then we found a chained delete that never asked at all.
Our agents delete files constantly: compiled Python, logs, scratch output. Occasionally the
target is something that can't come back: a database, a .env file, a key, a data
directory with no other copy. This issue is about the hook that
is supposed to tell those apart, and the two ways our first version failed at it.
The symptom: a guard everyone had stopped reading
The first guard was simple. It was a Claude Code PreToolUse hook on shell commands, and
it returned ask for every deletion it saw. Deleting a .pyc? Ask. Deleting a log?
Ask. Deleting a database? Ask, in exactly the same dialog.
You can guess how that went. When almost every prompt is harmless, the one that isn't gets the same reflexive Allow as the rest. The guard was technically doing its job and practically doing nothing. It had trained us to approve.
That was the slow failure. The fast one was worse.
What the pipe test showed
A hook is just a script that reads a JSON description of the tool call on stdin and prints a decision. So you can test one without an agent: pipe it a fake command and read what comes back. We did that with a line like this:
echo cleaning && rm -rf <data dir>
The hook printed nothing. No prompt at all. A recursive delete of one of our data directories would have run without a single question.
We didn't theorize about it. We piped it in, watched it pass, and then read the code to find out why.
The cause: a "safe" pattern matched the whole command
The old hook had a list of patterns meant to recognize commands that only read or print,
so a grep that mentioned rm in its search string wouldn't trigger a prompt. One of
those patterns was, in effect, ^(echo|printf|cat).
The bug was where it was applied. The hook tested that pattern against the entire
command string, not against each command in it. echo cleaning && rm -rf <data dir>
starts with echo, so the whole line was waved through as harmless output. Everything
after the && was never examined.
Any guard that classifies a command line as one unit has this hole. Shell lines are
compound. &&, ||, ;, |, & and plain newlines all start a new command, and each one
needs its own verdict.
Why it hid
Two things kept this out of sight.
- A noisy guard looks like a working guard. It prompted constantly, so nobody asked whether it ever stayed silent when it shouldn't. The noise was the camouflage.
- The dialog didn't say which prompts were the hook's. We wanted to check whether the
hook's explanation, the
permissionDecisionReasonit returns, reached the person deciding. In the version we ran (Claude Code 2.1.117), the permission dialog showed its title ("Allow this bash command?"), the command text, and the calling tool's owndescriptionfield. It did not show the hook's reason, the hook'ssystemMessage, or a label saying which hook had asked. The hooks documentation describes the reason as shown to the user forask, so we reported what we saw.
That second check needed care to mean anything. rm isn't on our permission allowlist, so
an rm command prompts whether or not a hook is involved, and you can't tell who asked. The
repro had to use a command the allowlist auto-approves (we used find, allowed by a
Bash(find:*) rule). Any prompt on that can only come from the hook.
The fix: three tiers, decided per command
The replacement guard sorts every deletion target into one of three buckets:
| Verdict | Decision | What lands here |
|---|---|---|
| Safe | silent allow | .py, .pyc, .log, .out, .err, .tmp, .bak, .md, .txt, and calls to our reversible trash script |
| Protected | deny, no dialog |
.db, .sqlite, .parquet, keys and certificates, any .env* file, and paths under our data directories |
| Unknown | ask |
everything else: $VARS, globs, bare directories, recursive deletes, git clean, inline shutil.rmtree |
The classifier, rewritten generically:
PROTECTED = (".db", ".sqlite", ".parquet", ".pem", ".key")
SAFE = (".py", ".pyc", ".log", ".out", ".tmp", ".bak", ".md", ".txt")
def classify(path):
base = os.path.basename(path.rstrip("/")).lower()
if is_env_file(base) or under_protected_dir(path):
return "PROTECTED"
if base.endswith(PROTECTED):
return "PROTECTED"
# Only once protected is ruled out:
if any(ch in path for ch in "$*?`"):
return "UNKNOWN" # can't resolve it, so don't guess
if base.endswith(SAFE):
return "SAFE"
return "UNKNOWN" # fail closed, never open
And the decision, made over every subcommand, never the whole line:
found = [classify(t) for sub in split_commands(cmd)
for t in deletion_targets(sub)]
if "PROTECTED" in found:
decide("deny")
elif "UNKNOWN" in found:
decide("ask")
# else: print nothing, exit 0, and the delete just runs
A few rules inside that took more than one try:
- Protected is tested first.
rm $DB.dbcontains a variable, but it's obviously a database. Checking for "unresolvable" first would report a vague "unresolved variable" and bury the reason that matters. - Recursive demotes safe. With
-r, the blast radius can reach past the named file, so a recursive flag turns a Safe verdict into Unknown. - The splitter respects quotes, so a
;inside a string doesn't create a fake command. Commands sent oversshare unwrapped and classified too, becausessh host "rm -rf ..."hides a real deletion inside an argument. find -deleteis judged by its-namepattern.find . -name '*.db' -deletementions no database path anywhere else.- A parser crash becomes Unknown. An exception in the hook must never quietly allow a delete.
The point of the Safe tier isn't convenience. It's what makes the remaining prompts worth reading. Widening the safe list is the only way to make the guard quieter, and that's on purpose: quieting it should be a deliberate edit, not a default.
The guard blocked its own commit
The new guard's first real action was to block the commit that added it.
The commit message, passed to git commit through a heredoc, described the old bug by
quoting a recursive delete of a data directory. A fail-closed parser reading command text
can't tell a command from a sentence about a command, so it saw a deletion and stopped.
The fix: strip heredoc bodies before parsing. They're data, not commands. The line with
the << stays, because that line does run. There's one exception. A heredoc piped into a
shell (<<EOF | bash) really does execute, so those bodies are kept and checked. We
verified that bypass stays closed.
This generalizes. Any guard that pattern-matches command text will false-positive on
documentation about commands. If your agents write commit messages, issues or notes about
rm, and ours do constantly, plan for it on day one.
Why permission rules can't do this
The obvious question is whether plain permission rules could do this instead.
Claude Code's Bash(...) rules do accept * globs, and deny rules are checked per
subcommand, so a rule like deny: Bash(rm *.db) really would catch
echo x && rm foo.db.
But the globs match command text, not resolved paths. Each of these deletes data and
none of them contains the string .db:
rm -rf <data dir>
rm <data dir>/*
rm $DBFILE
find . -name '*.db' -delete
ssh host "rm ..."
A rule can only see what the command says. A hook can look at what it targets. That's why the enforcement lives in a hook.
Why "ask" can't carry a warning
This is the design decision we'd most want you to take away.
In the version we ran, a hook's ask looked exactly like every routine permission
prompt: same title, same buttons, no reason shown. You can't make one prompt look louder
than another. So an ask on a database was indistinguishable from the dozen harmless
prompts around it. That is the reflex-approve failure the guard exists to prevent.
What about the tool's description field, which the dialog does show? The agent being
guarded writes that. It's worthless as a guardrail.
So the protected tier is deny. A deny has no Allow button, and its reason is delivered to
the agent, which relays it in chat, where it shows in full. The reason names the file and
why it can't be recovered, then tells the agent not to try again with a reworded command, a
different tool, a glob, a variable or a remote shell, because the block is on the
target, not the phrasing. If the deletion is really wanted, there's a reversible trash
script (files stay recoverable for three days), or a person can run the delete outside the
agent.
If the dialog starts showing hook reasons, we'll revisit. Until then, deny is the only
decision that can carry a message.
The part that matters for agents
A person who's told "don't do that" usually remembers. An agent often doesn't, and the deletion guard caught one pattern that kept coming back.
When launching a remote job, an agent chained an rm -f of a completion marker file onto
the launch command, to "reset" it first. We asked it to stop. Fifteen days later it did
it again, for a marker file that didn't even exist yet, because it
was the job's first run. That command sat in a permission dialog for about two hours,
because nothing in the dialog explained why it was waiting or what the delete was for. It
was rejected.
A delete buried in a compound launch line never gets reviewed on its own. So the guard now
denies any deletion, even a Safe one, in a command that also launches a job
(nohup, systemd-run, Start-Process, disown and our own job wrappers). "It's just an
empty marker file" isn't an exemption. The deny reason gives the agent the alternative:
launches stay purely additive, and each run gets its own uniquely named marker, so
nothing ever needs clearing first. We checked seven cases before turning it on, including
launch plus a safe delete (deny), the safe delete alone (allow), and the launch alone
(allow).
Two operational notes:
- Hook scripts are re-read on every call. Only the
settings.jsonregistration is cached at startup. Editing the script takes effect immediately, but changing the registration needs a restart. - One copy, under version control. The guard is registered once at user level, so it covers every repo and every session, and the script lives in a git repo of its own, because a user-level hook still needs a history.
If you only take one thing
Pipe echo x && rm -rf <something you care about> into your deletion hook today. If it
comes back silent, your guard is judging the first word of the line. Then sort your
prompts: if most of them are harmless, the dangerous ones are being approved on reflex,
and the cure is fewer prompts, not more.
Next issue: job leases, or how one agent stopped another from shutting down a machine it was still using, and why CPU load is not a busy signal.
Reply to this email if you've hit something like this. We read every reply.
Get the next one by email: subscribe to Boternal Field Notes.