You wrote your agent a rule, but it doesn't follow it and keeps making the same mistake
I don't repeat the rule as text: when the agent is about to run the wrong command, a hook denies it and names the command to run instead. I only add a deny where the move has to change, because every deny costs the agent one more step; and I test that the path it suggests actually gets through.
beforefixed after a warning: 36%
afterstopped after a deny: 95% · test the suggested path separately
set the rule up not as a warning but as a hook that denies the wrong command and names the one to run instead; only for mistakes that can't be undone or are expensiveText for your agent · 58 lines
Situation: you wrote your agent a rule (CLAUDE.md, the prompt, or a warning printed by a hook), but the agent keeps making the same move.
Why: the agent reads a warning but usually doesn't change its move; a deny fixes it. In my setup (Claude Code, Nov 1–12, 34,053 hook events), when a hook let an action through and printed a warning and the agent then tried the same action again, it corrected course 36% of the time; when the hook denied the action, 95% of the time. The warning rate comes from a single warning hook, the deny rate from nine deny hooks. A context note added for the agent before a command runs didn't stop the command: with a small model, the expensive command still ran in 3 out of 3 trials.
A deny stops the move but doesn't always get the suggested path chosen: in the trial, the deny stopped the agent in 3 out of 3 runs and got the suggested command chosen in 1. If the suggested path is denied by another rule, the agent makes up a path; in my setup one deny was also denying the very read it suggested.
A deny isn't free: the denied tool call is generated again from scratch (a file being written is written again), and every deny costs the agent one more model step. The hook runs on every matching tool call: if it slows down, every agent waits; if it crashes, they all stop. If a deny asks for something the agent can't actually produce (a rationale, a source, "I tested it"), the agent makes it up to get past the deny.
Do:
(1–4 are for your own rule. If you don't have a rule yet and only want to try the method, set it up with the example rule in 5.)
1. Try the hook-free paths first; the first one that works wins, and no hook gets installed:
a. Do you have text of your own that contradicts the rule or teaches the mistake (an old line in CLAUDE.md, an example command a script prints)? Fix that; don't put a hook on top of it.
b. If the command or script that makes the mistake is yours, put the deny there (the script fails on the wrong argument and says what's right), not in a hook that runs on every tool call.
c. If the mistake already announces itself (a compiler error, the command's error exit), don't add a hook; the agent sees it and fixes it.
2. Can the mistake be recognized from the input of a single tool call (command text, file path, content)? Don't put a hook on a mistake that can't be recognized from the input, like "didn't think it through".
3. Deny, warn, or nothing:
- If the mistake can't be undone (deleting, publishing, overwriting a shared branch) → deny.
- If it can be undone and announces itself later → no hook.
- In between, weigh it: deny ⟺ precision × (0.95 − 0.36) × cost of a missed mistake > one extra model step. Precision is the share of the calls the hook fires on that are actually wrong; on a hook that also fires on correct moves, a deny is expensive, so narrow the match first.
- If you do write a warning, write the outcome, not the rule ("this command took 40 s and wrote 2 GB"). Don't print a rule sentence or "read this file": the agent doesn't open the address, and a copied rule goes stale when the real rule changes.
4. The deny message has two parts, the denied command and the exact command to use instead, for example:
DENIED: git push --force → git push --force-with-lease · does not overwrite what someone else pushed
If the replacement isn't written, the agent makes up its own path. The replacement command must already exist on the agent's machine: don't put a tool that needs installing in the deny message.
5. Install (Claude Code, inside the project; needs jq: command -v jq, otherwise brew install jq). The three leading spaces on the blocks below are this list's indentation; remove them when writing the files. The example carries a single rule: "don't overwrite a shared branch with --force". For your own rule, change only the `yanlis` pattern and the deny message.
.claude/hooks/kural.sh:
#!/bin/sh
command -v jq >/dev/null 2>&1 || { echo "kural.sh: jq not found, the hook cannot decide" >&2; exit 2; }
cmd=$(jq -r '.tool_input.command // empty')
log="$(dirname "$0")/kural.log"
yanlis='(^|[;&|(])[[:space:]]*([A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*[[:space:]]+)*git[[:space:]]+push([[:space:]]+[^;&|]*)?[[:space:]](--force|-[A-Za-z]*f[A-Za-z]*)([[:space:];&|)]|$)'
if printf '%s' "$cmd" | grep -Eq "$yanlis"; then
printf '%s\tdeny\n' "$(date +%FT%T)" >> "$log"
jq -n '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"DENIED: git push --force → git push --force-with-lease · does not overwrite what someone else pushed"}}'
exit 0
fi
.claude/settings.json (if it already exists, add this under hooks):
{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"sh \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/kural.sh","timeout":5}]}]}}
Keep the log file out of the repo: printf '\n.claude/hooks/kural.log\n' >> .gitignore (the leading blank line keeps it from sticking to the last rule when .gitignore doesn't end with a newline)
Keep the matcher narrow ("matcher": "Bash"). The log never records the command text (a command line can carry secrets), only the time and the decision.
Verify:
- A helper that feeds a fake event to the hook. Run it at the project root (where the .claude folder is); run the definition and the calls in the same command (every tool call opens a new shell). The helper calls the hook with the command written in settings.json.
ev() { command -v jq >/dev/null || { echo "no jq"; return 1; }; k=$(jq -r '.hooks.PreToolUse[].hooks[] | (.command // "") | select(test("kural[.]sh"))' .claude/settings.json | head -1); [ -n "$k" ] || { echo "kural.sh is not in settings.json"; return 1; }; jq -nc --arg c "$1" '{tool_name:"Bash",tool_input:{command:$c}}' | CLAUDE_PROJECT_DIR="$PWD" sh -c "$k"; echo "exit $?"; }
- Matcher: jq -r '.hooks.PreToolUse[] | select(any(.hooks[]; (.command // "") | test("kural[.]sh"))) | .matcher' .claude/settings.json → Bash (capital B; if it says "bash", Claude Code never calls the hook). This line only reads settings.json; the three lines below test the hook itself.
- Read the three lines together:
ev 'git push --force' → JSON containing "deny", then «exit 0»
ev 'git push --force-with-lease' → only «exit 0» (the path the deny suggests must get through the hook)
ev 'git push' → only «exit 0»
If you see any number other than «exit 0», the hook is broken.
- Nearest neighbors. Should be denied: ev 'git push -f origin main' · ev 'git push -fu origin main' · ev 'git push origin main --force' · ev 'cd repo && git push --force' · ev 'GIT_TRACE=1 git push --force' · ev 'git push origin "$(git branch --show-current)" --force'. Should pass: ev 'git push -u origin feature' · ev 'echo git push --force' · ev 'git commit -m "never push --force"' · ev 'git push origin main && rm -f x'. Read these two groups together too: "Should pass" alone also holds for a hook that lets everything through, "Should be denied" alone for one that denies everything. A known false deny in this version: the pattern doesn't see quotes, so a «git push --force» inside quotes that comes at the start of a line or after ; & | ( is denied too: ev 'git commit -m "fix; git push --force is banned"' → "deny".
- Escapes, deliberately left open; each prints only «exit 0», with no deny: ev 'git -C repo push --force' · ev 'git push origin +main' · ev 'sudo git push --force' · ev 'command git push --force' · ev 'git push origin main 2>&1 --force' · ev 'git push --mirror' · ev "$(printf 'git push \\\n--force')" (a command split across lines with a backslash) · printf 'git push --force\n' > gonder.sh; ev 'sh gonder.sh'; rm gonder.sh (a script that contains it). This line doesn't test the hook; it shows what isn't closed. The list is an example, not a complete one: the hook only sees the command text, line by line. If an escape would be costly, don't grow the hook; put the deny on the mistake itself (step 1b). In this example: block force-pushes to the branch on the remote (branch protection); that block works regardless of the hook and the agent.
- Duration: time sh .claude/hooks/kural.sh </dev/null → under 0.2 seconds (sh prints «real», zsh prints «total»). This line measures only how long the hook takes, not whether it's correct: it prints a small number even when the hook file is missing; if you see «No such file» next to it, the file isn't there. If the hook reads files, goes out to the network, or starts processes, the time grows; the "timeout": 5 in settings.json cuts the hook off at that second and the command runs.
- Delete the lines your manual runs left: rm -f .claude/hooks/kural.log
- Live: at the project root, claude -p 'run git push --force --dry-run' (--dry-run sends nothing to the remote), then cat .claude/hooks/kural.log → a «deny» line, and Claude's answer names git push --force-with-lease: the hook runs inside Claude Code and its deny reaches the agent.
Don't:
- Don't move every rule into a hook: every deny adds a step for the agent, every hook adds latency to every call.
- Don't copy the rule's text into the hook; write only the outcome and the path to use instead.
- Don't use a deny to ask for something the agent can make up, like a rationale, a source, or "did you test it".
- Don't grow the hook by adding every spelling that slips through to the pattern: the bigger the pattern, the more it denies correct commands too.Also in: If you work with many agents