DEV Community

Vildanden
Vildanden

Posted on

A 15-line PreToolUse hook that stops Claude Code before rm -rf and force-push

Project instructions tell a coding agent what you want. A hook is where you put the few things you never want to depend on the model remembering.

Claude Code runs PreToolUse hooks before a tool call executes. If the hook exits with a blocking status, the call doesn't run and the reason goes back to the agent. That makes it a good place for a short, boring list of "stop and confirm" patterns.

The guard

#!/usr/bin/env python3
import json, re, sys

event = json.load(sys.stdin)
cmd = json.dumps(event.get("tool_input", {}))

patterns = [
    (r"(?i)\brm\s+-[rf]{1,2}\b", "recursive or forced deletion"),
    (r"(?i)git\s+push\b[^\n]*(?:--force|-f)(?:\b|$)", "force push"),
    (r"(?i)git\s+reset\s+--hard", "hard reset"),
    (r"(?i)\b(?:terraform|pulumi)\s+destroy\b", "infrastructure destruction"),
    (r"(?i)\bkubectl\s+delete\b", "cluster deletion"),
    (r"(?i)\b(?:cat|less|head|tail)\b[^\n]*(?:\.env\b|id_rsa|private.?key)", "sensitive-file read"),
]
for pattern, reason in patterns:
    if re.search(pattern, cmd):
        print(f"{reason}: confirm the exact target or use a dry-run.", file=sys.stderr)
        sys.exit(2)
sys.exit(0)
Enter fullscreen mode Exit fullscreen mode

Wire it to the Bash matcher in .claude/settings.json under hooks.PreToolUse, then try one harmless command and one that should trip it. Check your installed Claude Code version's hook docs for the exact exit-code and JSON contract before relying on it.

Why so short

  • Regex is a tripwire, not a sandbox. It catches the common footguns. It won't catch find . -delete or a script that deletes for you. Least-privilege credentials and review still do the real work.
  • Short lists stay maintained. A 60-pattern deny-list gets copy-pasted once and never read again. Six patterns you understand get tuned.
  • The message matters. "Confirm the exact target" nudges the agent toward a narrower command instead of retrying the same one.

Going further

This is one of 13 hooks in the Vildanden Claude Code Ops Pack ($17): write guards for secret-looking paths, a download-to-execute check, a post-tool secret scan, stop and session-end summaries, and six review slash commands. All local Python, no network calls, no credentials.

If you just want project conventions first, the free Agent Config sample has a lean AGENTS.md, CLAUDE.md, and three scoped Cursor rules.

Top comments (0)