Skip to content
PRAXIS

G.32Guides · Practice guide

Claude Code Hooks Examples and a CLAUDE.md Template That Actually Gets Followed

Working Claude Code hook examples that block destructive commands, a CLAUDE.md template, and a three-layer rule for what to ask, gate and enforce.

A precise grid of white facade panels, an illustrative image for rules built into a system.

By Praxis Consulting. Written with a finance and consulting background. Educational content; not affiliated with or endorsed by Anthropic. Setting names change between versions, so check the official documentation before relying on any detail below.

Most Claude Code setups fail in the same way: the rules live in a text file, the model follows them most of the time, and the one time it does not is the time that matters. The fix is not a longer instruction file. It is knowing which rules to ask for, which to gate and which to enforce. This page gives you the model, a working hook, and a CLAUDE.md template.

The three layers

  1. Ask. CLAUDE.md, agent charters and skills. The model usually follows them. Right for style, conventions and procedure.
  2. Gate. Permission rules that allow or deny tools and command patterns. Right for anything you have decided in advance.
  3. Enforce. Hooks: your own code that runs on every matching tool call and can refuse. Right for anything that must never happen.

A preference like "use named exports" is layer 1. "Never read the production .env" belongs in layers 2 and 3 as well as in the file. Putting a hard rule only in layer 1 is the most common mistake we see.

A CLAUDE.md template that gets followed

Four sections cover most repositories.

# Project: <name>

One sentence on what this is and who uses it.

## Commands
- Install: `<cmd>`
- Test (run before saying anything is done): `<cmd>`
- Lint/format: `<cmd>`
- Run locally: `<cmd>`

## Layout
- `src/` application code; `tests/` mirrors `src/`
- `scripts/` one-off tooling, safe to read, ask before running

## Conventions
- <the three conventions a new hire would get wrong, with one example each>

## Rules
- Never edit generated files in `dist/`. Change the source and rebuild.
- Do not add a dependency without saying why in the reply.
- Prefer a small diff. If a change touches more than five files, stop and propose a plan first.

## Done means
Tests pass, lint is clean, and the reply lists what was run and what the output was.

Why it works: the commands are real, each rule can be checked against a diff, and "Done means" turns "I think it works" into "this command printed this". Write each rule so a reviewer could say whether it was followed. "Run pytest -q before finishing" beats "write good tests". Add a clause of reasoning to a rule and the model can apply it to cases you did not foresee.

Hook example: block the commands that are hard to undo

A PreToolUse hook receives the event as JSON on standard input. Exit code 2 blocks the call and sends your stderr to the model. This one refuses force pushes, hard resets, piped installers, sudo, destructive SQL and recursive deletes outside a short list of safe directories.

#!/usr/bin/env python3
"""PreToolUse hook for the Bash tool. Blocks a short list of commands that are
hard to undo. Exit code 2 blocks the call and sends stderr back to the model.

This is a seatbelt, not a security boundary: a determined command can be
rephrased past a regex. Pair it with permission rules and a sandbox."""
import json, re, sys

RULES = [
    (r"\bgit\s+push\b.*(--force\b|--force-with-lease\b|\s-f\b)", "force push"),
    (r"\bgit\s+reset\s+--hard\b", "git reset --hard discards uncommitted work"),
    (r"\bgit\s+clean\s+-[a-zA-Z]*f", "git clean -f deletes untracked files"),
    (r"\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(ba|z)?sh\b", "piping a download into a shell"),
    (r"\bchmod\s+-R\s+777\b", "recursive world-writable permissions"),
    (r"\bsudo\b", "sudo"),
    (r"\b(DROP|TRUNCATE)\s+(TABLE|DATABASE)\b", "destructive SQL"),
    (r">\s*/dev/sd[a-z]\b|\bmkfs\b|\bdd\s+if=", "raw disk write"),
]

SAFE_RM_TARGETS = ("tmp", "build", "dist", "node_modules", ".cache", "__pycache__")

def unsafe_rm(cmd):
    """True if the command has a recursive+force rm with any target outside the safe list."""
    for m in re.finditer(r"\brm\s+((?:-\S+\s+)+)([^;&|\n]*)", cmd):
        flags = m.group(1)
        if not (re.search(r"-\w*[rR]", flags) and re.search(r"-\w*f", flags)):
            continue
        for tgt in m.group(2).split():
            name = tgt.rstrip("/").split("/")[-1]
            if tgt.startswith(("/", "~", "$", "..")) or name not in SAFE_RM_TARGETS:
                return True
    return False

def main():
    try:
        event = json.load(sys.stdin)
    except Exception:
        return 0  # never break the session on malformed input
    if event.get("tool_name") != "Bash":
        return 0
    cmd = (event.get("tool_input") or {}).get("command", "")
    if unsafe_rm(cmd):
        print("Blocked by hook: recursive force delete outside tmp/build/dist/node_modules/.cache. Ask the user.", file=sys.stderr)
        return 2
    for pattern, reason in RULES:
        if re.search(pattern, cmd, re.IGNORECASE):
            print(f"Blocked by hook: {reason}. If this is intended, ask the user to run it.", file=sys.stderr)
            return 2
    return 0

if __name__ == "__main__":
    sys.exit(main())

Register it in .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash",
        "hooks": [ { "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block_dangerous_bash.py" } ] }
    ]
  }
}

Three design points. It fails open: if the hook cannot parse its input it exits 0, so a bug never locks you out. It speaks to the model: the stderr message says what was blocked and what to do instead. And it is tested: pipe a sample event into it and check the exit code.

echo '{"tool_name":"Bash","tool_input":{"command":"git push -f"}}' | python3 .claude/hooks/block_dangerous_bash.py; echo $?

You should see the block message and 2.

What a hook cannot do

A hook matches text, not intent. A script that deletes files internally gets past a check on rm. Treat hooks as a seatbelt, and for unattended runs add isolation: a container or a disposable checkout with no personal credentials, a narrow tool allow-list, a turn limit and timeout, and output written to a branch for a human to review.

Subagents: when they earn their place

There are three good reasons to use a subagent: it keeps a large exploration out of your main context, it can be given only read-only tools, and it can check work independently. The independent check is the most valuable. A verifier that sees only the artifact, the original acceptance criteria and the changed-file list cannot be anchored by the implementer's account of what it did. Ask it one question above all: could this check have failed?

Verification habits

Read the diff, not the summary. Make "done" mean a command ran and printed something. For bug fixes, get a failing test first, then the fix, so you know the test is about the bug. And take any number in a report from tool output, never from the model's arithmetic.

What the full pack adds

The full operator pack covers setup, the CLAUDE.md template and the hook above with registration and test steps, plus three more CLAUDE.md patterns, three agent charters, a skill, four more hooks, a safe-automation checklist, a verification chapter and a troubleshooting table, with a test runner for every script.

Claude Code operator pack

The full pack is available. Get the claude code operator pack. This guide stands on its own without it.

Frequently asked questions

What is a Claude Code hook?

A hook is a command you register in settings.json that runs when a session event happens, such as before a tool call. It receives the event as JSON on standard input and can block the action by exiting with code 2. Because it is your own code, it runs whether or not the model remembers a rule.

What should go in a CLAUDE.md file?

Four things: the real commands to install, test and lint; a short map of where code lives; the conventions a newcomer would get wrong; and a definition of done that requires the reply to list the commands run and the last line of output. Keep it short, because every line competes with the task for the model's attention.

Can a hook stop Claude Code from deleting files or force-pushing?

A PreToolUse hook on the Bash tool can refuse commands that match a pattern, such as git push --force or a recursive delete outside a temp directory. It is a seatbelt rather than a security boundary, because a command can be rephrased, so use a container or disposable checkout for unattended work.

Is it safe to run Claude Code unattended?

Only inside an isolated environment with no personal credentials, a narrow tool allow-list, a turn limit and timeout, output written to a branch or file, and a log you review. Permission rules and hooks reduce risk; isolation bounds it.

When should I use a subagent instead of the main conversation?

Use one to keep a large exploration out of the main context, to give a task only read-only tools, or to get an independent check from an instance that did not see how the work was done. If none of those applies, a subagent only adds a handoff.

Educational content. No result is promised. Review any script before you install it.

Working on something larger than a guide?

Tell us what you are deciding or building, and we will tell you honestly whether we are the right resource.

No obligation · a scoping conversation first