Hook regex needs CMD_START and NOT_BACKUP anchors to prevent false positives

When writing regex patterns for Claude Code PreToolUse Bash hooks that match filename operations (rm, mv, chmod), use two precision anchors to prevent false positives:

CMD_START = (?:^|[;&|(]\s*)— anchors to actual shell command position. Without this, a pattern like\b(rm|mv)\s+.*FILE\bwill match the literal string "rm FILE" INSIDE anecho “rm FILE”` call, falsely blocking innocent operations.

NOT_BACKUP = (?![.\w]) — negative lookahead on the protected filename. Without this, \bFILE\.md\b matches inside FILE.md.bak.1776133901 because . is a non-word char that satisfies the \b boundary, falsely blocking legitimate backup cleanup.

Combined usage (from destructive-ops-blocker.py):

CMD_START = r'(?:^|[;&|`(]\s*)'
NOT_BACKUP = r'(?![.\w])'
# Pattern: CMD_START + rm/mv + filename + NOT_BACKUP
(CMD_START + r'(rm|mv)\s+\S*MEMORY\.md' + NOT_BACKUP, 'Memory file')

Test suite required: Every pattern-based hook should include a bottom-of-file test harness with at minimum 10 cases covering BOTH directions — (a) actual dangerous ops still blocked, (b) previously-blocked legitimate ops now allowed (string literals in echo, backup variants, read-only ls/cat operations).

This pattern evolved from a false positive in destructive-ops-blocker.py that blocked legitimate rm protocols.md.bak.* cleanup and echo "rm FILE" test scripts. Apply to ANY future hook that pattern-matches shell commands.

  • docker
  • 2026-04-04-oracle-001-self-architecture-analysis
  • destructive-hook-regex-word-boundary-backup-false-positive
  • salesforce
  • oracle
  • hook-regex-false-positives-require-cmd-start-not-backup-anch
  • hook-regex-cmd-start-not-backup-anchors-required
  • hook-regex-word-boundary-false-positives-on-backups
  • hook-regex-false-positives-cmd-start-not-backup-anchors