TL;DR and verdict
We gave Claude Code real features on our own small TypeScript invoicing API (Claude Code 2.1.294, Opus 5.5, auto mode) and checked the result with a copy-paste detector, typecheck and tests. Then we installed one enforcer per rule: a hook or a setting, not a line in CLAUDE.md.
- With the five rules written as prose in CLAUDE.md, feature A (credit notes) broke none of them: 0 clones, 45 tests passing (34 baseline plus 11), no test was deleted and no config was touched.
- With no rules written, feature B1 (recurring schedules and a CSV export) left 3 exact clones. The invoice body parser was copied into the schedule parser, and a handler's lookup boilerplate was copied into a second handler. Typecheck was green and 47 tests passed. A second pass, B2, left all 3 clones in place.
- With the enforcers installed, we replayed the same prompts. The clone hook fired on the schedules handler (jscpd found 1 clone, baseline 0) and Claude moved the shared check into one method. The new-file hook raised three permission prompts for the schedule modules, answered yes, and one for a utils file, answered no, and nothing was written. On the enum and interface prompt Claude edited nothing and named the lint config and the hook. The stop hook refused a rename made through a shell command with "Rule 4: tests fail. Not done yet." and Claude fixed the two expectations. A shell command on tsconfig.json was denied by the harness.
- Each enforcer was also fed a bad edit by hand: the clone, the lint violations, the red build and the deleted test were all refused.
Verdict: install the stop hook first, then the deny list, which is short. Skip all of it on a throwaway prototype. A hook enforces what one tool call can show. Whether an abstraction is the right one stays your call.
Sourced synthesis
CLAUDE.md is context, not enforced configuration. Claude Code's memory docs say CLAUDE.md and rules are loaded as context, not enforced configuration s2. The best practices page says the same from the other side: CLAUDE.md is for guidelines, and Claude may decide one does not apply. Mandatory behavior belongs in a hook, a deny rule or a managed setting s1.
That gives two kinds of instruction. In the first kind you write a line and the model reads it: a prompt, CLAUDE.md, a skill. In the second kind you configure a check and the harness runs it: a hook, a deny rule, a managed setting s1. The five rules in this pack are all the second kind.
Exit 2 does something different per hook event. On PostToolUse, exit 2 shows stderr to Claude although the tool already ran s3. A PostToolUse warning must exit 2 to reach Claude, because stderr from a hook that exits 0 is never seen s3. On PreToolUse, exit 2 blocks the call even if the hook printed an allow decision s3. On Stop, exit 2 blocks the stop, and whatever the command prints to stderr goes back to Claude as the reason it cannot finish yet s1.
A Stop hook needs a guard and has a cap. Stop hooks receive stop_hook_active, which is true when Claude is already continuing because of a stop hook, so you check it to avoid blocking on a condition that will never resolve s3. The documented guard exits 0 when it is true s18. Claude Code also applies an 8-consecutive-continuation cap, raised with CLAUDE_CODE_STOP_HOOK_BLOCK_CAP s3. The changelog for 2.1.143 says the turn now ends with a warning after 8 consecutive blocks s19.
PreToolUse has four decisions. A PreToolUse hook returns its decision in hookSpecificOutput with four outcomes: allow, deny, ask or defer s3. The new-file hook in this pack answers ask, which puts you back in the loop as a permission prompt. A timed-out PreToolUse hook does not block the call. Since 2.1.295 you can set onFailure: "block" to make it block s3 s19.
The matcher has a blind spot. The Edit|Write matcher fires only on the Edit and Write tools, not on Bash s18. Edits made through Bash can reach a PostToolUse hook in tool_response.bashEditDiff from 2.1.269, behind the setting bashEditDiffEnabled s3 s19.
Deny rules: use Edit(path), and know the limit. A Write(path) deny rule does not match. Use Edit(path), which covers all built-in file-editing tools s4. Deny rules also do not cover a Python or Node script that opens the file itself s4.
Path-scoped rules, and the frontmatter trap. A path-scoped rule loads when Claude uses Read, Write or Edit on a matching file s2. Before 2.1.288, only Read loaded them s19. If the YAML between the markers does not parse, Claude Code ignores the frontmatter and loads the rule as if it had no paths, so it applies everywhere s2.
jscpd catches exact clones only. Run as npx jscpd ., it scans for clones. Default runs report only exact clones, and renamed or near-miss clones are opt-in s20. The default minimum clone size is 50 tokens s20. Our hook lowers it to 30 tokens and 4 lines. In our test, a rewritten near-copy with different lines and the same behavior was not caught.
Why per-edit gates and not a longer CLAUDE.md. SlopCodeBench found that the best agent passes 14.8% of checkpoints. That is a pass rate, not a share of slop. Structural erosion rises in 77% of trajectories and verbosity in 75.5% s6. Agent code is 2.3x more verbose and 2.0x more eroded than 473 open-source Python repositories s6. Explicit quality guidance reduces initial verbosity and erosion by up to a third, without affecting degradation rates s6. Guidance helps the start. A gate on every edit acts on the slope.
The stop hook that "does nothing". A Hacker News thread, "Claude is ignoring stop hooks", shows a script that ended on cat with exit 0. The harness never blocked anything, because blocking needs exit 2 with the reason on stderr s8.
What a hook cannot judge. A Claude Code issue on CLAUDE.md rules not being followed calls PreToolUse hooks a partial stopgap. A hook enforces what one tool call can show. "Is this the right abstraction?" cannot be decided by a hook, and if you disable the hook the behavior returns s7.
Code
Install note: settings.json goes to .claude/settings.json, the four hook scripts to .claude/hooks/, domain.md to .claude/rules/domain.md, and eslint.config.js to the repo root. Add eslint, typescript-eslint and jscpd as devDependencies. Create two baseline files: .claude/jscpd-baseline (the clone count) and .claude/test-baseline (the number of passing tests). The hooks use jq, and the stop hook calls pnpm typecheck and pnpm test, so those scripts must exist in your package.json.
The settings file holds the deny list for rule 5 (tsconfig.json, vitest.config.ts, eslint.config.js and .claude/**) and the hook entries for rules 1 to 4. Put it in .claude/settings.json.
settings.json
{
"permissions": {
"deny": [
"Edit(tsconfig.json)",
"Edit(vitest.config.ts)",
"Edit(eslint.config.js)",
"Edit(.claude/**)"
]
},
"hooks": {
"PreToolUse": [
{ "matcher": "Write", "hooks": [ { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/new-file-ask.sh\"", "timeout": 10 } ] }
],
"PostToolUse": [
{ "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/no-clone.sh\"", "timeout": 60 } ] },
{ "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/lint-edit.sh\"", "timeout": 60 } ] }
],
"Stop": [
{ "hooks": [ { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/done-check.sh\"", "timeout": 120 } ] }
]
}
}
Rule 1, reuse before you write. A PostToolUse hook on Edit|Write. It runs jscpd on src/ after every edit to a .ts file, compares the clone count with the baseline, and exits 2 with the location of the twin when the count goes up. Put it in .claude/hooks/no-clone.sh.
no-clone.sh
#!/usr/bin/env bash
# PostToolUse hook (matcher: Edit|Write). Rule 1: reuse before you write.
# Runs the copy-paste detector on src/ after every edit. A clone that was not
# there at the baseline blocks with the twin's location (exit 2 -> stderr reaches Claude).
set -u
INPUT=$(cat)
FILE=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // empty')
case "$FILE" in *.ts) ;; *) exit 0 ;; esac
cd "$(printf '%s' "$INPUT" | jq -r '.cwd')" || exit 0
BASE=$(cat .claude/jscpd-baseline 2>/dev/null || echo 0)
OUT=$(mktemp -d)
npx --no-install jscpd src --min-lines 4 --min-tokens 30 --reporters json --output "$OUT" --silent >/dev/null 2>&1
COUNT=$(jq '.statistics.total.clones // 0' "$OUT/jscpd-report.json" 2>/dev/null || echo 0)
if [ "$COUNT" -gt "$BASE" ]; then
echo "Rule 1 (reuse before you write): jscpd found $COUNT clone(s), baseline is $BASE. A helper you just wrote already exists:" 1>&2
jq -r '.duplicates[] | " \(.firstFile.name):\(.firstFile.start)-\(.firstFile.end) == \(.secondFile.name):\(.secondFile.start)-\(.secondFile.end)"' "$OUT/jscpd-report.json" 1>&2
echo "Import and reuse the existing one; do not keep both." 1>&2
rm -rf "$OUT"; exit 2
fi
rm -rf "$OUT"; exit 0
Rule 2, no module nobody asked for. A PreToolUse hook on Write. When the path is under src/ and the file does not exist yet, it answers ask with a reason, and Claude Code shows a permission prompt. Put it in .claude/hooks/new-file-ask.sh.
new-file-ask.sh
#!/usr/bin/env bash
# PreToolUse hook (matcher: Write). Rule 2: no module nobody asked for.
# Creating a file that does not exist yet under src/ becomes a permission prompt:
# the human says yes or no, the model does not decide alone.
set -u
INPUT=$(cat)
FILE=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // empty')
CWD=$(printf '%s' "$INPUT" | jq -r '.cwd')
case "$FILE" in "$CWD"/src/*) ;; *) exit 0 ;; esac
[ -e "$FILE" ] && exit 0
REL=${FILE#"$CWD"/}
jq -cn --arg r "Rule 2: new module under src/ ($REL). One new file needs a reason: approve only if the task asked for it, otherwise put the code in the module it belongs to." \
'{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:$r}}'
Rule 3, conventions are lint. A PostToolUse hook on Edit|Write that runs ESLint on the edited .ts file and exits 2 on any error. It lints only and never fixes. Put it in .claude/hooks/lint-edit.sh.
lint-edit.sh
#!/usr/bin/env bash
# PostToolUse hook (matcher: Edit|Write). Rule 3: conventions are lint, not prose.
# Runs ESLint on the file that was just edited; a violation is a lint error at the
# exact line, every edit (exit 2 -> stderr reaches Claude). Lint only, never --fix.
set -u
INPUT=$(cat)
FILE=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // empty')
case "$FILE" in *.ts) ;; *) exit 0 ;; esac
cd "$(printf '%s' "$INPUT" | jq -r '.cwd')" || exit 0
if ! npx --no-install eslint --no-warn-ignored "$FILE" 1>&2; then
echo "Rule 3: the conventions above are enforced by eslint.config.js; fix the file, do not change the config." 1>&2
exit 2
fi
exit 0
The lint rules it runs: type instead of interface, no enum, no any, no I/O or store imports in src/domain/, and no direct store imports in handlers. Put the file at the repo root.
eslint.config.js
// Conventions as lint rules. Run on every edited file by .claude/hooks/lint-edit.sh.
import tseslint from "typescript-eslint";
export default [
{
files: ["src/**/*.ts", "test/**/*.ts"],
languageOptions: { parser: tseslint.parser },
plugins: { "@typescript-eslint": tseslint.plugin },
rules: {
"no-restricted-syntax": [
"error",
{ selector: "TSInterfaceDeclaration", message: "Use `type`, never `interface` (project convention)." },
{ selector: "TSEnumDeclaration", message: "Use a const object or a union type, never `enum` (project convention)." },
],
"@typescript-eslint/no-explicit-any": "error",
},
},
{
files: ["src/domain/**/*.ts"],
rules: { "no-restricted-imports": ["error", { patterns: [
{ group: ["node:fs", "node:http", "fs", "http"], message: "src/domain has no I/O." },
{ group: ["../store/*", "../http/*", "**/store/*", "**/http/*"], message: "src/domain imports nothing from store or http." },
] }] },
},
{
files: ["src/http/handlers/**/*.ts"],
rules: { "no-restricted-imports": ["error", { patterns: [
{ group: ["../../store/*", "**/store/*"], message: "Handlers reach the store through the app context only." },
] }] },
},
];
The words of the conventions live in a path-scoped rule file. It loads only when Claude touches src/domain/. Keep the YAML header valid, or the rule loads everywhere. Put it in .claude/rules/domain.md.
domain.md
---
paths:
- "src/domain/**"
---
# src/domain: pure functions, nothing else
- No I/O here: no `node:fs`, no `node:http`, nothing from `src/store/` or `src/http/`.
- `type`, never `interface`; const objects or union types, never `enum`; no `any`.
- Money is an integer number of cents; reuse `money.ts` (`assertCents`, `formatCents`, `sum`) instead of writing a new helper.
- One new file needs a reason the task gives. No class, factory or generic helper for one caller.
These conventions are checked by ESLint on every edit (`.claude/hooks/lint-edit.sh`).
Rule 4, done means the checks passed. A Stop hook with the stop_hook_active guard. It runs typecheck and tests, compares the passing-test count with .claude/test-baseline, and exits 2 with the failing output while anything is red or a test vanished. Put it in .claude/hooks/done-check.sh.
done-check.sh
#!/usr/bin/env bash
# Stop hook. Rule 4: done means the checks passed.
# Refuses the end of the turn while typecheck or tests are red, or while the test
# count dropped under the baseline (a suite made green by deleting tests is red).
set -u
INPUT=$(cat)
# Guard: when Claude Code is already continuing because of this hook, let it stop.
[ "$(printf '%s' "$INPUT" | jq -r '.stop_hook_active')" = "true" ] && exit 0
cd "$(printf '%s' "$INPUT" | jq -r '.cwd')" || exit 0
# Nothing changed since the last commit: nothing to check.
[ -z "$(git status --porcelain -- src test 2>/dev/null)" ] && exit 0
LOG=$(mktemp)
if ! pnpm --silent typecheck > "$LOG" 2>&1; then
echo "Rule 4: typecheck fails. Not done yet." 1>&2; tail -30 "$LOG" 1>&2; rm -f "$LOG"; exit 2
fi
if ! pnpm --silent test > "$LOG" 2>&1; then
echo "Rule 4: tests fail. Not done yet." 1>&2; grep -v '^\s*$' "$LOG" | tail -30 1>&2; rm -f "$LOG"; exit 2
fi
BASE=$(cat .claude/test-baseline 2>/dev/null || echo 0)
COUNT=$(grep -oE 'Tests +[0-9]+ passed' "$LOG" | grep -oE '[0-9]+' | head -1)
rm -f "$LOG"
if [ -n "$COUNT" ] && [ "$COUNT" -lt "$BASE" ]; then
echo "Rule 4: $COUNT tests passed, the baseline is $BASE. A test disappeared; restore it." 1>&2; exit 2
fi
exit 0
Do this Monday
- Run
claude --versionand check you are on 2.1.288 or later, so path-scoped rules load on Write and Edit s19. - Install
eslint,typescript-eslintandjscpdas devDependencies, and check thatjqis on your PATH. - Copy
done-check.shfirst, create.claude/test-baselinewith your current passing-test count, and add the Stop entry to.claude/settings.json. - Add the
permissions.denylist withEdit(...)lines for your compiler config, test config, lint config and.claude/**. Do not writeWrite(...)lines. - Copy
eslint.config.js, runnpx eslint srcon the untouched repo, and fix or baseline anything before you wire the hook. - Run
npx jscpd src --min-lines 4 --min-tokens 30, write the clone count to.claude/jscpd-baseline, then addno-clone.shandnew-file-ask.sh. - Copy
domain.mdto.claude/rules/, adapt the path to your own folders, and check the YAML header parses. - Replay the gesture each rule was written for and read the refusal. Then hand-edit one file to prove a rule fires.
Measurements
Our run: a small TypeScript invoicing API with 34 tests, Claude Code 2.1.294, Opus 5.5, auto mode, 2026-11-07. Clones counted with jscpd at --min-lines 4 --min-tokens 30.
| Setup | Features given | Clones found by jscpd | Tests passing | What fired |
|---|---|---|---|---|
| Rules as prose in CLAUDE.md | A: credit notes (1 min 21 s) | 0 | 45 (34 baseline + 11) | Nothing to fire. No rule broken |
| No rules written | B1: recurring schedules and CSV export (2 min 27 s) | 3 | 47 (34 + 13) | Nothing installed. 3 new modules, 14 files changed |
| No rules written | B2: cancel endpoint and two CSV exports (about 1 min 30 s) | 3, the same ones | 55 | Nothing installed. Claude extracted src/http/csv.ts and reused it |
| Enforcers on, live replay | B1 again, then the enum refactor, a hurried rename, a hook removal and a tsconfig change | 0 at the end | 54 | Clone hook once (1 clone, baseline 0), 3 new-file prompts plus 1 refused, lint hook never needed, stop hook once, deny once |
| Enforcers on, mechanical test | Hand-made bad edits | 0 on baseline, 1 after pasting a 5-line copy of formatCents |
33 of 34 after deleting one test | Clone hook, new-file ask, lint hook (4 errors), stop hook (build red, test count under baseline) |
Details of the mechanical test. The ESLint config gave 0 problems on the untouched repo. lint-edit.sh on a file with a node:fs import, an interface, an enum and an any reported 4 errors at their lines and exited 2. The clone hook reported domain/money.ts:21 == http/views.ts:5. A path under src/ that did not exist returned ask with the reason. The stop hook said "Rule 4: 33 tests passed, the baseline is 34. A test disappeared; restore it." A rewritten near-copy was not caught by jscpd.
Go further
What we kept out of the five, and where each belongs.
Git hooks and Lefthook. A git hook or a pipeline gate is a valid place for the same checks. It runs when you commit, not while Claude edits, so the feedback comes later. It is a different setup from this pack. If your suite takes minutes, keep the quick part in the stop hook and move the rest to your pipeline.
Agent-level prompt hooks. Hooks that ask a model to judge an edit are not deterministic, so they are not among the five. A rule you can check with a command belongs in a script.
Review commands. /simplify and /code-review are manual. They are useful, but review stays yours, and neither is enforcement.
Vendor incident figures. Vendor reports on incident rates per pull request are a correlation signal, not specific to Claude Code and not measured on our code. We did not use them. Every figure in this pack comes from the sources linked above or from our own run.
A ready-made ruleset. The anti-slop repo is a vendored Oxlint ruleset, with 18 generic rules and 5 Effect rules. It is meant to be vendored, with no official npm package s10. It is a good model for a rule: a lint error at the exact line, every run.
Prose rules. Collections of CLAUDE.md rules are useful for the words of a convention. Keep them in path-scoped rule files, and let a check carry the guarantee.
FAQ
Does a deny rule stop a Python script that writes the file? No. Deny rules do not cover a Python or Node script that opens files itself s4. Anyone with the keys can still edit the file by hand. The deny list stops the agent's built-in edit tools and the obvious shortcuts.
Why does my stop hook never block?
Check the exit code first. Blocking needs exit 2 with the reason on stderr. A script that ends on cat with exit 0 never blocks s8. Then check the guard: if stop_hook_active is true, the hook should exit 0. The cap also ends the turn after 8 consecutive blocks s3.
Does the Edit|Write matcher catch Bash edits?
No. It fires only on the Edit and Write tools, not on Bash s18. Since 2.1.269, a diff of files a Bash command changed can be added to the Bash tool result behind bashEditDiffEnabled s19. Our stop hook still catches the result, because it runs typecheck and tests at the end of the turn.
What about files created through a shell command?
A file created that way is not a Write tool call, so the new-file hook never sees it. Add a Bash matcher if you need to watch for it, or review git status at the end of the turn.
Does the hook undo the edit? No. A PostToolUse hook runs after the tool, which already ran. It shows stderr to Claude with exit 2 s3. Claude then fixes the file. Only the PreToolUse hook and the deny list stop an action before it happens.
AIDive