All posts

11 min readPost 4

Catching an agent's rm -rf: how the delete guard is designed, and what it can and cannot stop

Agent cleanup commands like rm -rf, git clean -fdx, and Remove-Item bypass both the OS Recycle Bin and editor checkpoints. Here is why Obituary's delete guard strictly denies without rewriting, the five-day mistake of conflating detection with verbatim replacement, what 3 million fuzz inputs found in our shell parser, and the exact boundaries the guard cannot cross.

On this page
  1. Deny only, never rewrite silently: rewriting bypasses user permissions
  2. A five-day mistake: conflating "is this a delete?" with "can we rewrite it verbatim?"
  3. Real shell parsing instead of regexes
  4. Why an 18.7 µs check took 3 ms: searching PATH on every git status
  5. What the guard cannot stop

When an AI coding agent cleans up a workspace, it reaches for rm -rf, git clean -fdx, or Remove-Item. Every one of those commands destroys data on the spot without touching the OS Recycle Bin.

Editor-side undo does not cover this gap either. Claude Code's checkpointing documentation states it plainly: checkpoints track edits made through Claude's file-editing tools, not files modified only by Bash commands, leaving shell actions to version control. Yet the scratch scripts, logs, screenshots, and half-finished experiments agents clean up have often never been committed to Git.

Obituary gives files a countdown lifespan and moves expired items into a restorable local graveyard. The delete guard pushes that same graveyard one step earlier in the workflow:

Attached to an agent's pre-execution hook, the delete guard inspects every shell command before it runs, denies destructive deletions outright, and suggests a restorable obit equivalent whenever it can do so safely.

Delete guard flow diagram: an agent runs rm -rf build, Obituary denies without rewriting, the agent retries with obit rm -rf build, the target moves to the graveyard, and obit resurrect puts it back
The full delete-guard path: deny rm -rf before execution, point the agent at an equivalent obit command, move the target into the graveyard, and restore with one command if needed.

Deny only, never rewrite silently: rewriting bypasses user permissions ​

Our first design rewrote commands transparently: the hook would silently turn rm -rf build into obit rm -rf build behind the agent's back. Real-world testing killed that idea immediately:

  • On Claude Code 2.1.317, host permission rules run after the hook mutates the command. If a user explicitly banned rm, silent rewriting converted the command into obit rm and sailed straight past the user's deny rule.
  • On Codex, rewriting a command through a hook required returning an explicit allow, again overriding whatever guardrails the user had configured.

A hook built to protect the user had accidentally turned into a permission-bypass channel.

So the delete guard never mutates commands. It only denies, returning a short, untranslated, declarative English reason naming the safe alternative. The agent issues a fresh tool call, the user's own permission policy evaluates it normally, and the only cost is one extra tool round-trip.

Here is the exact JSON returned when a standard PreToolUse payload hits obit hook claude with the delete guard enabled:

text
$ hook() { printf '{"session_id":"demo","cwd":"C:/obit-demo","hook_event_name":"PreToolUse","tool_name":"%s","tool_input":{"command":"%s"}}' "$1" "$2" | obit hook claude; }

$ hook Bash 'rm -rf build'
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Obituary's delete guard is on: `obit rm -rf build` provides restorable deletion; `obit resurrect` restores graveyard entries."}}

Four graveyard-backed commands mirror the flags and exit codes of their destructive counterparts:

  • obit rm matches GNU rm flags, exit codes, and diagnostics.
  • obit rmdir matches rmdir.
  • obit remove-item accepts PowerShell Remove-Item parameters.
  • obit git-clean previews with git clean -n and buries each reported path individually.

All four funnel through the exact same burial service, refusing protected paths rather than falling back to real deletion. The guard stays off by default until enabled with obit init --guard-rm.

A five-day mistake: conflating "is this a delete?" with "can we rewrite it verbatim?" ​

"Better to miss a command than to over-select targets" is a sound safety rule—we just applied it to the wrong decision for five days.

Across early review rounds, HIGH findings squeezed from opposite directions: missing real deletions versus emitting an equivalent command that buried more files than the original shell command would have touched. Over-selection is far deadlier; for instance, rewriting the first half of rm -r repo || /usr/bin/rm -rf backup into obit rm meant a legitimate refusal on repo could trigger the unguarded permanent rm -rf backup behind ||.

To eliminate over-selection, we restricted v1.0.0 to deny only when the guard could produce a verbatim equivalent command. That subset was so narrow that everyday agent cleanup idioms passed right through untouched:

  • rm -rf build && npm run build
  • rm -rf build 2>/dev/null
  • rm -rf build || true
  • rm -rf "$OUT"/*
  • git clean -fdx && npm ci

On 13 November we realized we had welded two independent questions together:

  • Can we emit a drop-in equivalent command? This must stay narrow, because getting it wrong buries unintended files.
  • Does this command delete files? This can deny broadly, because a denial executes nothing and can never over-select.

Commit 12c9d11 separated the two. Any literal rm, rmdir, git clean, or Remove-Item (including aliases) in command position is denied. Only the safe subset gets a drop-in equivalent; everything else explains why no exact equivalent applies and points to obit bury <path> or listing targets before passing explicit operands to obit rm -- <path>:

text
$ hook Bash 'rm -rf build && npm run build'
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Obituary's delete guard is on: `rm` deletes permanently and no exact obit equivalent applies to this command (deletion must be the final command segment). `obit bury <path>...` provides restorable deletion for literal paths, `obit git-clean` for git clean; `obit resurrect` restores graveyard entries. For targets selected at runtime, the safe alternative is to list and review the paths first, then give them as explicit operands to `obit rm -- <path>...`."}}

Real shell parsing instead of regexes ​

Regexes cannot tell an executable command apart from a string argument. Our parser follows real shell grammar:

  • \rm, 'rm', r''m, /usr/bin/rm, and rm.exe all reduce to rm after stripping quotes and path prefixes.
  • git -C x clean skips global git options before inspecting the subcommand.
  • Quoted strings, comments, quoted heredoc bodies, and arguments to other commands (such as echo "rm -rf build") pass through.
  • Dry-run and help invocations (rm --help, git clean -n, Remove-Item -WhatIf) pass through.
  • Command words containing variables, command substitutions, or globs are not treated as literal commands; if the host cannot identify the shell (such as Windows Codex without a declared shell), the guard passes through and logs an audit entry.
  • If Bash parsing fails, detection falls back to a word scan across the command rather than failing open.

Testing five inputs side by side—the first three pass silently, while the PowerShell delete gets an equivalent and find -delete is denied without one:

text
$ hook Bash 'echo \"rm -rf build\"'
$ hook Bash 'rm --help'
$ hook PowerShell 'Remove-Item -Recurse -Force build -WhatIf'
$ hook PowerShell 'Remove-Item -Recurse -Force build'
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Obituary's delete guard is on: `obit remove-item -Recurse -Force build` provides restorable deletion; `obit resurrect` restores graveyard entries."}}
$ hook Bash 'find . -name \"*.tmp\" -delete'
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Obituary's delete guard is on: `find -delete` deletes permanently and no exact obit equivalent applies to this command (unsupported command structure: find). `obit bury <path>...` provides restorable deletion for literal paths, `obit git-clean` for git clean; `obit resurrect` restores graveyard entries. For targets selected at runtime, the safe alternative is to list and review the paths first, then give them as explicit operands to `obit rm -- <path>...`."}}

Replacing a 1,000-line handwritten tokenizer with mvdan.cc/sh and 3 million fuzz runs ​

The initial guard shipped with roughly a thousand lines of handwritten tokenization that took 10 review rounds to harden. On 9 November we swapped the Bash side to mvdan.cc/sh (the parser behind shfmt), keeping only a small static unquoter; on 13 November we walked its full AST across lists, pipes, ||, background jobs, subshells, $(...), backticks, process substitutions, and unquoted heredoc expansions. Because Go lacks an equivalent PowerShell parser, PowerShell retains a handwritten quote-aware scanner that handles curly quotes, script blocks, and $(...).

Fuzzing paid off almost immediately:

  • Seeded with 90 commands asserting that suggested commands differ from the original only in the replaced command word, the fuzzer executed 3,047,091 inputs in 5 minutes.
  • It exposed an odd-backslash line-continuation divergence between our static unquoter and the old tokenizer, which now passes conservatively.
  • It triggered a panic inside an shfmt iterator when the caller halted traversal on error.
  • A 4 MiB string of nested parentheses blew the parser stack, leading to a hard 256-level nesting cap.

Why an 18.7 µs check took 3 ms: searching PATH on every git status ​

Because the pre-execution hook runs on every single shell tool call, it never spawns git, touches the network, or opens the ledger. Yet our benchmarks revealed a two-order-of-magnitude gap:

BenchmarkTime
Single Bash parse and delete-guard decision~18.7 µs
Full in-process pre-hook (including JSON decode, excluding process spawn)~3.0 ms

CPU profiling pointed straight at Windows filesystem calls. On every invocation, the hook searched PATH for obit and checked whether it matched the running binary so it would know whether to print obit or an absolute path in a denial—even when the command was git status and no denial would ever happen.

Terminal output of two delete-guard benchmarks: Bash parse-and-decide takes about 18.7 microseconds, while the full in-process pre-hook takes about 3.0 milliseconds
Raw benchmark output: parsing and classifying a command takes microseconds, while the full pre-hook took milliseconds because of unconditional PATH lookups.

On 22 November we moved executable-path resolution behind the denial branch so ordinary commands like git status never touch PATH.

Paired before-and-after measurements on the same machine dropped ordinary in-process hook time from milliseconds to 15–25 µs, trimming 6 to 11 ms off every hook process while leaving denied deletions unchanged. Both denials and pass-throughs are counted in obit stats and recorded in the audit log so gaps show up in real usage.

What the guard cannot stop ​

Alongside rm, rmdir, git clean, and Remove-Item (and aliases), v1.4.2 added Bash indirect deletions: find -delete, find -exec rm, and xargs rm. The remaining limits are explicit:

The guard inspects shell command text, not what arbitrary binaries do internally; general wrappers like sudo rm or bash -c '...' are not unpacked.

Four environment edge cases stay deliberately out of scope because fixing them would require emulating another runtime inside a native binary (and every one degrades to a restorable burial rather than permanent deletion):

  • Session-scoped PowerShell $WhatIfPreference or $ConfirmPreference variables are invisible to obit remove-item.
  • A directory containing files protected by NTFS deny-delete ACLs resists rm -rf, whereas renaming the whole directory moves them into the graveyard together.
  • Under WSL with the metadata mount option, Linux-side permission bits are not checked by Windows, so obit rm can succeed where Linux rm would fail.
  • Exported shell wrapper functions such as rm() { /usr/bin/rm -i "$@"; } live inside the active shell session, invisible to a hook reading raw command text.

One subtler edge case exists whenever a host forwards a command to a second shell after the hook runs: quoting boundaries can break in transit, turning literal text into live commands. Where a host cannot report which shell will run a command, Obituary declines to install the guard and says so in the capability table. Finally, any process running under your own user account that explicitly tries to evade Obituary can delete files directly—the guard stops mistakes, not hostile code.

All posts