cd /news/ai-agents/claude-code-hooks-tutorial-turn-your… · home › topics › ai-agents › article
[ARTICLE · art-177612] src=besydr.com ↗ pub= topic=ai-agents verified=true sentiment=· neutral

Claude Code hooks tutorial: turn your rules into checks

A tutorial published on Claude Code hooks shows developers how to register commands that run at fixed lifecycle points — UserPromptSubmit, PreToolUse and Stop — to turn stated rules into checks the agent cannot skip, with three worked Python 3 examples: re-injecting a standing-rules file into every prompt, denying a forbidden command, and sending the agent back to work before a turn ends. The tutorial notes that a hook's exit code decides the outcome — exit 0 applies the JSON it printed, exit 2 blocks the action, and any other exit is a non-blocking error that lets the action proceed, so a crashing hook does not protect the developer. Hooks are configured in ~/.claude/settings.json for every project or .claude/settings.json for one project, and the tutorial cautions that the prompt-context hook is advice rather than enforcement because the agent can still ignore the rule.

recommendation

Enforce agent rules with hooks rather than prompt text: re-inject standing rules via UserPromptSubmit and block forbidden tool calls with exit code 2 in PreToolUse, since other exit codes let the action run.

more in playbook: Working with AI coding agents
by read10 min views1 publishedNov 28, 2026
Claude Code hooks tutorial: turn your rules into checks
Image: Besydr (auto-discovered)

Claude Code hooks are commands you register once that run at fixed points in a session: before your prompt is processed, before a tool call — one action the agent takes, such as a shell command or a file edit — runs, and when the agent stops. They are where a rule you stated becomes something the agent cannot skip. This tutorial builds three small hooks: one that repeats your rules with every prompt, one that denies a forbidden command, and one that sends the agent back to work before the turn ends. The last sections show what hooks alone do not fix, with numbers from our benchmark, and what Besydr adds on top.

You need Claude Code installed and a rule you are tired of repeating. The examples use Python 3; any language that reads JSON from standard input works.

What hooks are #

Hooks in Claude Code are user-defined commands that Claude Code runs automatically at points in its lifecycle. The primary purpose of hooks in Claude Code is control at the moment an action happens: add context before the model reads a prompt, deny a tool call before it runs, or continue a turn that ended too early.

A hook configuration has three levels: an event (when it fires), a matcher (which calls it applies to), and a handler (the command that runs). Hooks live in a JSON settings file:

File Scope
~/.claude/settings.json Every project on your machine
.claude/settings.json One project; can be committed to the repo

When a hook finishes, its exit code decides what happens: exit 0 applies whatever JSON it printed, exit 2 blocks the action, and any other exit is a non-blocking error — the action goes ahead. That last rule matters: a hook that crashes does not protect you.

The full event list and JSON schemas are in the Claude Code hooks documentation; the quickstart guide has more Claude Code hooks examples.

The three events that carry rules #

Most rule enforcement needs three events:

Event When it fires What your hook can do
UserPromptSubmit Before Claude processes your prompt Add context beside the prompt, or block the prompt
PreToolUse After a tool call is built, before it runs Allow, deny, ask, or rewrite the call
Stop When the agent finishes responding Let it stop, or send it back with a reason

The matcher names the tool, such as Bash for shell commands.

Example one: a rule in every prompt #

A rule you state once is advice the model may forget. This hook reads a rules file and adds it to the agent's context with every prompt. Because the text is added again each time, a compaction of the conversation — Claude Code folding old messages into a summary — cannot drop it.

  1. Save your rules in .claude/standing-rules.md , one per line:
never push to main
run only the test files that cover your change
  1. Save this script as .claude/hooks/repeat-rules.py :
#!/usr/bin/env python3
import json, os, pathlib
rules = pathlib.Path(os.environ["CLAUDE_PROJECT_DIR"]) / ".claude/standing-rules.md"
if rules.exists():
    print(json.dumps({
        "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": "Standing rules from the developer:\n" + rules.read_text()
        }
    }))
  1. Register it in .claude/settings.json :
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command", "command": "python3 ${CLAUDE_PROJECT_DIR}/.claude/hooks/repeat-rules.py" }
        ]
      }
    ]
  }
}
  1. Open a new Claude Code session and send any prompt. Expected result: the rules reach the agent as a system reminder beside your prompt. The reminder is not shown in the chat; claude --debug confirms delivery.

This hook is advice, not enforcement: the agent reads the rule and can still ignore it. The next example closes that gap.

Example two: a command the agent cannot run #

A PreToolUse hook sees every matching tool call before it runs and can deny it. This one denies a push to main and gives the agent your sentence as the reason.

  1. Save this script as .claude/hooks/deny-push.py :
#!/usr/bin/env python3
import json, re, sys
call = json.load(sys.stdin)
cmd = call.get("tool_input", {}).get("command", "")
if call.get("tool_name") == "Bash" and re.search(r"git\s+push\b.*\bmain\b", cmd):
    print(json.dumps({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": "The developer said: never push to main."
        }
    }))
  1. Register it with a matcher on Bash :
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "python3 ${CLAUDE_PROJECT_DIR}/.claude/hooks/deny-push.py" }
        ]
      }
    ]
  }
}
  1. Ask the agent to push to main. Expected result: the call is denied, the agent reads the reason, and it chooses another action or asks you.

Two things to check when a hook does not fire: the matcher must name the tool exactly (Bash, not bash), and the script must print valid JSON or nothing. A script that exits 2 blocks the call and its stderr becomes the reason — a simpler form than JSON for a first hook.

The limit of this approach: a pattern covers only the spellings it matches. This one catches git push origin main; a rephrased command can slip past. Enforcement by pattern is a fence, not a proof.

Example three: one more check before the turn ends #

Claude Code stop hooks run when the agent finishes responding. A Stop hook can send the agent back to work with a reason, which is the mechanism behind a completion check: the turn does not end until a condition holds.

  1. Save this script as .claude/hooks/one-more-check.py :
#!/usr/bin/env python3
import json, sys
state = json.load(sys.stdin)
if not state.get("stop_hook_active"):
    print(json.dumps({
        "decision": "block",
        "reason": "Before you finish: run the test files that cover your change and report the result."
    }))
  1. Register it:
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "python3 ${CLAUDE_PROJECT_DIR}/.claude/hooks/one-more-check.py" }
        ]
      }
    ]
  }
}
  1. Give the agent a task. Expected result: when it first stops, it continues with the reason as its next instruction; when it stops again, the turn ends.

The stop_hook_active field is true when the turn is already continuing because of a stop hook; the script checks it so the loop runs once. Claude Code also caps consecutive continuations at eight, but the count resets each time Claude calls a tool, so a hook that always blocks can still keep a session going.

The policy — what to check before finishing — is yours. The hook only carries the decision.

What hooks alone do not fix #

Advice decays. A study of 20,574 coding-agent sessions in 1,639 repositories (Tang et al., EMNLP 2026) labelled 16,118 episodes where the developer had to push back. The largest group, 38.33% of episodes, was the agent violating an explicit constraint. In command-line sessions the share was 49.49%, against 32.26% in editor sessions. 91.49% of the visible fixes needed the developer to push back.

A rules file helps, and we measured how much. In our Claude Code benchmark, a scripted developer worked on five Python projects and stated each rule once. Per 100 requests, rules from an earlier session were broken:

Setup Rules broken per 100 requests
Claude Code alone 47
Claude Code with a rules file written by hand 11
Claude Code with Besydr, all parts on 4

The hand-written file held all 38 rules of the benchmark, and nobody writes that file by hand. Within one project, Claude Code's own notes kept every rule in every run — the decay is across sessions and projects, where a note filed for one project does not reach the next.

A hook has no memory of its own. It re-reads a file you maintain. Nobody writes that file from your corrections, nobody writes a checklist from your request, and every project needs its own configuration. That is the gap a supervising program fills.

The loop Besydr runs on these hooks #

Besydr (say: besider) is a program that runs beside a coding agent and does two jobs: it supervises the work, and it learns from each session. On Claude Code it connects through the same hooks this tutorial built. One command registers them, on Linux and macOS:

besydr install claude

The command adds Besydr's hooks to ~/.claude/settings.json, keeps your existing settings, and backs the file up first. Open a new session afterwards. What runs at each event:

  • UserPromptSubmit : Besydr repeats your standing rules and the checklist of the current request, and adds lessons that fit the task — rules you stated in earlier sessions, project facts, and short work memos. A prompt gets at most 2,000 tokens of lessons.
  • PreToolUse : a call that conflicts with your words can be denied, with your sentence as the reason. This check is on by default.
  • Stop : a completion check compares the checklist — written from your request before work started — with the tool calls, their results and the diff. Gaps send the agent back to work, up to three times.
  • After the session: Besydr reads the finished session and stores lessons. Every rule must quote a message you wrote.

The benchmark numbers, with their limits:

Per 100 requests Claude Code alone With Besydr
Rules from an earlier session broken 47 4
Corrections the developer typed 47 11
Said done while hidden tests failed, long sessions 11 5

Client cost per request was 10% to 20% lower with Besydr; the agent worked 18% to 25% longer. In a single project on small tasks there was no gain: Claude Code's own notes do the job, and Besydr takes longer.

One honest limit: in the benchmark the check's verdict caught none of the 14 pieces of work that failed the hidden tests. The gain on false "done" came from a question the agent is asked after a passed check — try the edge cases of the request, restore any check you rewrote — not from the verdict. The check is as good as its model, and it is not a code reviewer.

Besydr does not ask clarifying questions and does not fix malformed commands; the introducing post lists what it does not solve. The install page has the command for your platform. The local program is free with octomind; with Claude Code it needs a licence after a trial. You pay once and the program keeps working.

Useful hooks beyond rules #

A few useful Claude Code hooks that are not about rules:

  • PostToolUse : format or lint a file after every edit.
  • Stop orNotification : a desktop notification when a long turn ends.
  • PreToolUse : a log of every shell command, for audit.
  • UserPromptSubmit : block prompts that miss a detail your team requires.

Choosing the best Claude Code hooks for your own work starts with a rule you already repeat by hand. The quickstart guide has ready examples.

Sources and method #

  • The hook examples follow the official hooks reference . Each script was run with the reference's documented sample input, and its output checked against the documented schema; when the hooks fire is as the reference describes.
  • The measured numbers come from our benchmark : 30 runs, Claude Code, five Python projects, two models.
  • The study is Tang et al., EMNLP 2026 ; its shares were read from Table 2.
  • This post was drafted with AI assistance from these sources.
── more in #ai-agents 4 stories · sorted by recency
── more on @claude code 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/claude-code-hooks-tu…] indexed:0 read:10min 2026-11-28 · —