DEV Community

Cover image for Not Every Rule Belongs in CLAUDE.md: When a Script or Hook Is Better
PromptMaster
PromptMaster

Posted on AI-assisted

Not Every Rule Belongs in CLAUDE.md: When a Script or Hook Is Better

You have a line in your CLAUDE.md that says "Never edit existing migrations." Claude Code follows it. Almost always. Then one afternoon it "fixes" a column type directly in 0007_add_orders.sql, and you spend an hour untangling a database that no longer matches its history.

The usual reaction is to make the line louder. Anthropic's Claude Code best practices say adding IMPORTANT probably won't fix it: either the file is long enough that the line gets lost, or it's a rule that can't have exceptions, and that kind of rule belongs in a hook.

In an earlier article I covered what to cut from a long CLAUDE.md. This one is about the lines worth keeping that still fail you: should each one stay a sentence, become a script, or become a hook?

Why a sentence can't guarantee anything

The memory docs are direct about this: Claude treats CLAUDE.md files "as context, not enforced configuration." The best-practices page splits every instruction into two kinds:

  • Non-deterministic. You write it, the model reads it and decides what to do. Your prompt, CLAUDE.md and skills are in this group. Claude usually follows them, but there's no guarantee.
  • Deterministic. You configure it, and Claude Code (the harness) applies it every time. Hooks, deny rules and managed settings are in this group.

The same page says that most of the time you want Claude to decide, because almost every guideline has exceptions. So the goal isn't to turn your file into hooks. It's to find the few rules where "almost always" isn't good enough.

The three-way test

For each line in your CLAUDE.md, ask three questions in order.

1. Does it have exceptions? "Prefer named exports", "use the error helpers in src/lib/errors.ts". These are guidelines, and you want Claude to use judgment. Keep them in CLAUDE.md. The best-practices page uses "Prefer named exports" as its example of a rule that should not become a hook.

2. Is it a procedure with exact steps? "Before committing, run the linter, then the type checker, then the unit tests, and if the API changed, regenerate the client." That's a sequence of commands written as prose. Claude has to read it, remember it and type it correctly every time. Turn it into a script, and leave one line in CLAUDE.md that names the script.

3. Must it always (or never) happen, with zero exceptions? "Never edit an existing migration." "Never touch .env." "Don't finish until the type check passes." If a single miss costs you real time, make it a hook, so the outcome no longer depends on what the model remembers.

A handy signal from the docs: if you keep adding emphasis to a CLAUDE.md line and Claude still misses it, that line is a candidate for a hook. And the reverse: if you have hooks for things that are only preferences, delete them and let Claude decide.

Step 1: Turn procedures into a script

Here's the kind of block that grows in a CLAUDE.md over time:

## Before you finish
- Run `pnpm lint`
- Then run `pnpm tsc --noEmit`
- Then run `pnpm test --run`
- If you changed anything in src/api, run `pnpm gen:client` first
- Fix every error before saying you're done
Enter fullscreen mode Exit fullscreen mode

Move the commands into a file the whole team can run:

#!/bin/bash
# scripts/check.sh: the one command that says "this change is ready"
set -e
pnpm lint
pnpm tsc --noEmit
pnpm test --run
Enter fullscreen mode Exit fullscreen mode

And replace the block with a single line:

- Run `./scripts/check.sh` before you say a change is done.
Enter fullscreen mode Exit fullscreen mode

(The commands are an example for a pnpm/TypeScript project. Use whatever your project actually runs.)

The line costs less context in every session, the steps can't drift because there's one copy and it's code, and the same script works for you, for CI and, in a moment, for a hook. The best-practices page puts it this way: if your repo already has a check like this, the single most useful line in your CLAUDE.md is the command that runs it.

Step 2: Turn "never" rules into a PreToolUse hook

A PreToolUse hook runs before a tool call and can block it. According to the hooks guide, Claude Code passes the tool call as JSON on the script's stdin. If the script exits with code 2, the call is blocked and whatever it wrote to stderr goes back to Claude as feedback, so it can adjust. Exit code 0 means no objection, and the normal permission flow applies.

The guide includes an example that blocks edits to protected files such as .env. Here's a variation for the migrations rule. It blocks edits to migration files that already exist, but still lets Claude create a new one, because "add a new migration" is exactly what you want it to do instead:

#!/bin/bash
# .claude/hooks/protect-migrations.sh
# Block edits to migration files that already exist. New migrations are allowed.
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

if [[ "$FILE_PATH" == *migrations/* && -e "$FILE_PATH" ]]; then
  echo "Blocked: $FILE_PATH is an existing migration. Add a new migration file instead of editing this one." >&2
  exit 2
fi

exit 0
Enter fullscreen mode Exit fullscreen mode

Make it executable (chmod +x .claude/hooks/protect-migrations.sh) and register it in .claude/settings.json, using the same structure as the guide's example:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-migrations.sh"
          }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Test the script before you trust it

You don't need a Claude Code session to check the logic. Feed the script the same kind of JSON it will receive and look at the exit code. I did this in a small throwaway project at /tmp/shop with one existing migration, then simulated three tool calls:

for call in "Edit migrations/0007_add_orders.sql" "Write migrations/0008_add_refunds.sql" "Edit src/service.ts"; do
  set -- $call
  echo "--- $1 $2"
  echo "{\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"$1\",\"tool_input\":{\"file_path\":\"$PWD/$2\"}}" | ./.claude/hooks/protect-migrations.sh
  echo "exit code: $?"
done
Enter fullscreen mode Exit fullscreen mode

Output:

--- Edit migrations/0007_add_orders.sql
Blocked: /tmp/shop/migrations/0007_add_orders.sql is an existing migration. Add a new migration file instead of editing this one.
exit code: 2
--- Write migrations/0008_add_refunds.sql
exit code: 0
--- Edit src/service.ts
exit code: 0
Enter fullscreen mode Exit fullscreen mode

The existing migration is blocked with a message Claude can act on; the new migration and the source file go through. This tests the script, not Claude Code itself. Inside a session, the guide suggests running /hooks to confirm the hook is registered, then asking Claude to make the edit you want blocked.

One gap to know about

A hook that matches Edit|Write only sees those tools. The hooks guide points out that Claude can also change files by running shell commands, so a sed -i through the Bash tool wouldn't pass through this script. If you need to catch every change, the guide suggests also matching Bash and checking modified files with git status --porcelain, or adding a Stop hook that scans the working tree once per turn.

Step 3: Turn "don't finish until" into a Stop hook

A Stop hook runs whenever Claude tries to end its turn. If the hook exits with code 2, Claude is sent back to work, and the stderr output becomes the reason. The best-practices page shows this with a type check:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "pnpm tsc --noEmit 1>&2 || exit 2" }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Since you already have scripts/check.sh, you can point the hook at it instead, so the rule lives in one place: "command": "\"$CLAUDE_PROJECT_DIR\"/scripts/check.sh 1>&2 || exit 2". The 1>&2 matters, because it sends the tool output to stderr, where Claude will read it.

Two things to know before you add one. Stop hooks fire whenever Claude finishes responding, not only when a task is complete, so a slow check runs often. And there's a safety cap: per the docs, if the hook blocks eight stops in a row with no tool call in between, Claude Code overrides the next block and ends the turn. A check that can never pass won't trap you in a loop, but it also won't get fixed by itself.

What stays in CLAUDE.md

What's left should be things Claude can't see in the code: commands, conventions that need judgment, gotchas. One line per script, not one per step, and no rule written twice, once as a sentence and once as a hook. Don't overcorrect, either: the docs describe a hook as a tool for a rule with zero exceptions. And hooks are code that runs on your machine, so review them like any script, especially in a repo you didn't write.

A 10-minute checklist

  • Read every line in your CLAUDE.md and tag it: guideline, procedure or never/always rule.
  • Move each multi-step procedure into a script and replace it with one line that names the script.
  • Pick the one or two never/always rules where a single miss really hurts.
  • Write a PreToolUse hook for "never" rules and a Stop hook for "don't finish until" rules.
  • Test each hook script by piping sample JSON into it and checking the exit code.
  • Run /hooks in Claude Code to confirm the hook is registered.
  • Delete the sentence version of any rule a hook now enforces.

Where to go next

If you want the short version of what belongs in the file, the free CLAUDE.md Quick-Start Cheat Sheet covers what to include, what to cut, the one-line test for every line, and a map of the configuration stack beyond CLAUDE.md (slash commands, subagents, hooks, skills and plugins) with a simple framework for when to reach for each, in six pages.

When you're ready to build the whole stack, CLAUDE.md: The Complete Claude Code Configuration Guide has chapters on hooks, subagents, skills, plugins, security and team governance, plus three real-world configuration walkthroughs, the nine most common mistakes and a 30-day plan to build your setup from scratch.

This article was written with the assistance of AI and reviewed by the author. Claude Code behavior is described from Anthropic's official documentation (hooks guide, memory and best-practices pages). The hook script is the author's adaptation of the docs' protected-files example; the output shown is its real output when fed sample JSON in a throwaway project, not output from a Claude Code session. The CLAUDE.md block and check.sh are illustrative examples. PromptMaster guides are independent and not affiliated with or endorsed by Anthropic.

Top comments (0)