Instructions in CLAUDE.md are context that Claude tries to follow, but hooks are commands that run every time, regardless of what the model decides. A new deep-dive published on November 2, 2026, by Homingo Learn explains how to leverage this distinction to enforce hard constraints in Claude Code. While the model might 'forget' or misinterpret a rule about not touching .env files, a PreToolUse hook will block the operation with certainty. This shift from advisory prompts to executable enforcement is critical for production-grade AI agent workflows.
The Architecture of Control
Hooks operate at specific lifecycle points: PreToolUse (before a call), PostToolUse (after success), Stop (when Claude finishes a reply), and SessionStart/End. The system reads JSON from standard input, containing session IDs, working directories, and tool inputs. The hook responds via exit codes or JSON stdout. An exit code of 0 allows the action, while exit code 2 blocks it, sending stderr to Claude as the reason. This binary logic ensures that policy violations are caught mechanically, not probabilistically.
Practical Enforcement Examples
The guide provides five concrete Python-based examples. One uses PreToolUse to block edits to protected files like package-lock.json or anything in a .git directory. Another restricts a subagentβs Bash commands to a strict allow-list, rejecting shell metacharacters like pipes or semicolons to prevent command injection. A particularly powerful Stop hook runs npm test before allowing Claude to finish its turn; if tests fail, it blocks the stop, injects the error output as context, and forces Claude to fix the code, retrying up to three times.
Debugging and Best Practices
Configuration lives in settings.json files, either globally in ~/.claude/ or per-project in .claude/. The article warns that exit code 1 only logs an error and does not block; developers must use exit 2 or return a JSON permissionDecision of 'deny'. It also highlights common pitfalls, such as shell profiles echoing text that breaks JSON parsing, or slow hooks on hot events like PostToolUse. For hard limits, the author recommends combining hooks with permission rules and Bash sandboxing, as string checks alone can be bypassed.
Key Takeaways
- Use CLAUDE.md for judgment and hooks for mandatory rules.
- Exit code 2 blocks actions; exit code 1 does not.
- Stop hooks can force test-fix loops before Claude ends a turn.
- Always use absolute paths in hooks to ensure consistency across projects.
The Bottom Line
If your AI agent can break it, you need a hook to stop it. Reliance on model compliance is a vulnerability; deterministic enforcement is the only way to scale agentic coding safely.