Claude Code & Context Engineering

5 Claude Code Hooks That Catch the Mistakes Agents Actually Make

3 November 2026 · Updated 28 November 2026 · 11 min read · by Yang Kai

Five Claude Code hooks that catch real agent mistakes — formatting drift, .env edits, unbuilt 'done' claims — with a copy-ready settings.json config.

Config inside: Copy-ready settings.json hooks config

Contents
  1. The short version
  2. How to think about the five
  3. The config
  4. Hook 1: Block .env edits before they happen
  5. Hook 2: Format on every edit, automatically
  6. Hook 3: Screen shell commands for the known disasters
  7. Hook 4: No build, no "done"
  8. Hook 5: Log what happened
  9. Pitfalls that make people abandon hooks
  10. How we researched this
  11. What to do next

The most damaging agent mistake is rarely dramatic. No deleted database, no leaked key. It is quieter: an agent edits a file, declares the work done, and never runs the build. The change looks right, reads right, and breaks something the deploy catches instead of the session.

Prose instructions do not reliably prevent that. “Always run the build before finishing” can sit in a CLAUDE.md, in exactly the structure recommended in The CLAUDE.md That Actually Works, and an agent under pressure to wrap up can still skip it. That is the class of problem hooks exist for: rules that must happen mechanically, not hopefully.

These are the five hooks worth installing first, each aimed at a mistake agents repeat, with a copy-ready config. The selection and the mechanics follow Anthropic’s official hooks reference, checked in November 2026; the full event map sits in Claude Code hooks by event when you need an event this list does not use.

The short version

Hook Mistake it catches Event
Block .env edits Secrets changed or exposed by an edit PreToolUse
Format on edit Style drift accumulating into noisy diffs PostToolUse
Screen shell commands The known disasters: force-push, recursive delete PreToolUse
No build, no “done” Finished claims with no verification behind them Stop
Log what happened Changes nobody can trace to a session later Stop / PostToolUse

How to think about the five

Together they cover the pattern: protect secrets, keep formatting automatic, stop dangerous commands, verify before “done,” and leave an audit trail. You do not need all five on day one. Start with the two that match your most recent scar.

One caution before the config: hooks run commands on your machine. Only add hooks you understand, keep the scripts simple, and test each one on a throwaway change first. A hook is a command your setup runs automatically at a defined moment — before a tool executes, after an edit, when the agent tries to stop. Think of hooks as the enforcement layer underneath the advice layer: CLAUDE.md persuades, permissions bound what is allowed, and hooks inspect the specific action at the moment it happens.

The config

This is a representative settings.json shape. Adapt the commands to your stack — the examples assume an npm project with Prettier available.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "node .claude/hooks/block-env-edit.js"
          }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "node .claude/hooks/block-dangerous-bash.js"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path // empty' | xargs -r npx prettier --write 2>/dev/null || true"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node .claude/hooks/require-build.js"
          },
          {
            "type": "command",
            "command": "node .claude/hooks/log-session.js"
          }
        ]
      }
    ]
  }
}

The helper scripts are small by design: block-env-edit.js exits with a blocking error when the target path matches .env patterns; block-dangerous-bash.js inspects the proposed command for destructive patterns such as force-pushes or recursive deletes outside the project; require-build.js checks that a build was run after the last edit before allowing the session to end cleanly; log-session.js appends a timestamped summary line to a local log.

One detail in the formatter command is worth understanding, because older versions of this config — and many copied around the community — get it wrong. There is no $CLAUDE_FILE_PATH environment variable in Claude Code. The edited file’s path arrives inside the JSON payload on stdin, in the tool_input.file_path field, which is why the command pipes the payload through jq to extract it. A formatter hook built on the phantom variable formats nothing, silently, forever.

Hook 1: Block .env edits before they happen

Secrets are the one area where “the agent usually remembers” is not good enough. A PreToolUse hook that refuses edits to .env and its variants turns a policy into a wall: the script reads tool_input.file_path from the payload, matches it against your protected patterns (.env, .env.*, key files, credential stores), and exits 2 with a one-line reason Claude can act on — “edits to .env are blocked; ask the user to make this change.”

Match on more than the literal filename. Agents reach secrets through .env.local, through a copy named env.backup, and through Write creating a fresh file rather than Edit changing an old one — which is why the matcher covers both tools and the script, not the matcher, makes the final call on the path.

The boundary should also exist in prose. The same rule written in CLAUDE.md and in the shared layer discussed in AGENTS.md vs CLAUDE.md is defence in depth, because each layer fails differently: prose fails when the agent forgets, the hook fails only when the script does.

Hook 2: Format on every edit, automatically

Formatting arguments waste everyone’s time, and agents produce subtly inconsistent style when they are focused on logic. A PostToolUse hook that runs your formatter on the edited file removes the whole category. The agent stops spending attention on spacing, your diffs get cleaner, and style review becomes a non-event.

Two rules keep this hook invisible. Pick the formatter your project already uses; do not introduce a new one just for the hook. If your stack has no formatter, a linter running with its --fix flag fills the same slot. And make it fail quietly — the || true in the config is deliberate. A formatter that errors on an unusual file should never surface as a session problem, because PostToolUse feedback goes to Claude and a cosmetic complaint there costs attention on every edit. Speed matters for the same reason: this hook runs after every edit, so it formats one file, never the repo.

Hook 3: Screen shell commands for the known disasters

Agents run shell commands constantly, and almost all of them are harmless. The hook’s job is to catch the small set that are not: destructive deletes, force operations on shared branches, and commands that reach outside the project directory.

A simple pattern-matching script, maintained as you encounter new cases, is enough. When it blocks, the reason matters as much as the block: exit 2 with “blocked: force-push to main — push to a branch and open a PR instead” on stderr gives Claude a recovery path in the same step. For subtler cases, return the JSON permissionDecision: "deny" form instead, which carries the reason with the decision; the hooks deep dive compares the two mechanisms. You can also narrow when the script runs with the handler’s if field — "if": "Bash(rm *)" fires the hook only for remove commands — but keep the script itself as the authority, since if matching is best-effort.

What happens after a block — the agent explaining and asking before trying a variant — belongs in your instructions, the same pattern noted in Claude Code Skills, Explained for procedures that interact with hooks.

Hook 4: No build, no “done”

This is the hook that addresses the failure in the opening: a Stop hook that verifies the project builds — or, at minimum, that a build ran after the last edit — converts “definition of done” from a hope into a gate. When the check fails, the hook blocks the stop and returns the reason; Claude continues working with that feedback instead of ending the turn.

Keep it fast. On large projects, check for a fresh build output or run the type check instead of a full production build; the point is that verification happened, not which exact command proved it. And build the loop guard in from the start: the Stop payload carries a stop_hook_active flag that is true when Claude is already continuing because a stop hook sent it back. If your script sees that flag and the build is still red for a reason a rebuild cannot fix, it should let the stop through and report, rather than bounce the agent again. Claude Code caps stop-hook continuations at eight in a row, but a hook that reads the flag ends the loop on your terms. This pairs naturally with the lean instruction set from The Context Budget Audit: fewer prose rules, more enforced ones.

Hook 5: Log what happened

The quietest hook and, over months, one of the most valuable. Appending a simple record — date, project, files touched, build result — gives you an audit trail when a change surfaces later and nobody remembers which session made it. A Stop hook that writes one summary line per session is the cheap version; a PostToolUse logger that appends every edit to a JSONL file is the thorough one, and doubles as debugging evidence when another hook misbehaves.

The log also feeds your own reviews: patterns in it show you which mistakes recur, which tells you which hook or skill to write next. That feedback loop matters even more when you delegate, as discussed in Subagents vs One Long Session — subagents run the same configured hooks, so the trail covers delegated work too.

Pitfalls that make people abandon hooks

Over-blocking is the big one. A hook that fires on harmless work trains you to bypass hooks entirely, which is worse than having none. Keep matchers narrow and messages clear: a blocked action should say what was blocked and why, in one line.

Slow hooks are the second killer. If every edit triggers a heavy process, the session drags and the hook gets ripped out by Friday. Format and check quickly, or not at all — and never put a build or a test suite in a per-edit hook; those belong on Stop.

Fail-open guards are the quiet third. Exit code 2 blocks; a crash with any other code does not. A guard script that throws on an unexpected payload shape has just approved everything it was written to stop. Validate the input inside the script, exit 2 when the payload cannot be parsed, and on current Claude Code versions consider onFailure: "block" on the handler, which blocks the action when the hook fails, times out, or cannot start.

Finally, do not duplicate a hook in prose and expect both to be maintained. Once a rule is enforced mechanically, shorten its CLAUDE.md version to a pointer. A production hook set, with the helper scripts, is in the Claude Code Workflow Pack. See also resources and themes for lighter starting points.

How we researched this

meetBlogging is a desk-research site. These five were selected against the failure modes the hooks system is documented to address, and every mechanism described — exit codes, the stdin payload, the stop_hook_active flag, the continuation cap — is stated in Anthropic’s official hooks reference, checked in November 2026. No hook here is presented with invented results; the claim is narrower and checkable: these are the five enforcement points the documentation supports best.

What to do next

Add exactly one hook this week: the .env block if you handle secrets, or the build-before-done check if unverified “done” claims are your recurring pain. Test it on a disposable change, then add the formatter hook. Read The Context Budget Audit afterwards and delete the prose rules your hooks now enforce.

Ready for the full event map and the recipes beyond these five? Claude Code hooks by event covers all 34 events, the hooks deep dive goes into matchers and JSON decisions line by line, and running Claude Code in CI shows where hooks stop and pipeline checks should take over.

FAQ

What is a Claude Code hook? A handler your settings register for an event — PreToolUse, PostToolUse, Stop, and 31 others. Claude Code runs it automatically and can use its output to allow, block, or correct what the agent is doing. Handlers can be shell commands, HTTP endpoints, MCP tool calls, or model-evaluated prompts.

Where do hooks go in settings.json? Under a hooks key, grouped by event, each group with a matcher for which tools it applies to and the handlers to run. Project hooks live in .claude/settings.json; personal ones in ~/.claude/settings.json. The config in this article is complete and copy-ready; start with one hook, not all five.

Can a hook block the agent from doing something? Yes. A PreToolUse hook that exits with code 2 blocks the tool call, and its stderr message is shown to Claude as the reason — which is how the .env guard in this article works. A Stop hook blocks the same way to keep Claude working. Note the one exception: on PermissionRequest events, exit codes are not read as decisions — the hook must return a JSON decision object.

Will hooks slow my sessions down? Barely, if each hook is a fast script. Keep per-edit hooks under a second, avoid network calls, and never put a build or a test suite in a per-edit hook — save those for the Stop event, where they run once per turn.

Category: Claude Code & Context Engineering · Tags: #claude-code #hooks #automation #ai-agents

Next step: this article is part of Claude Code guides, which covers the full topic from first setup to advanced use.

Related guides