claude-code-hooks
Writes, tests, registers and debugs Claude Code hooks (PreToolUse, PostToolUse, SessionStart, Stop) that turn a rule the model keeps breaking into a hard gate
Install / Use
npx skills add daymade/claude-code-skills --skill claude-code-hooksInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
Development & EngineeringSupported Platforms
Tags
Our assessment of claude-code-hooks
claude-code-hooks scores 84/100 on our quality scale, 2898th of 4,698 Development & Engineering skills we index.
Its SKILL.md is 92 KB long, well organised into 27 sections with 9 code examples: long enough that it reads more like full documentation than a focused instruction file, which agents can find harder to follow.
With 1,426 GitHub stars, it is one of the more widely adopted skills in the catalogue.
Maintenance, license and trust
- The repository was last updated about 2 months ago, so claude-code-hooks is actively maintained.
- Our last check on 2026-10-14 found the source still online.
- It is released under the MIT license, a permissive license that allows use, modification and commercial use with attribution.
- Its trust signals score 100/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
Safety scan
No issues foundOur scan of the whole file found no instruction hijacking, hidden characters, credential access, data exfiltration or destructive commands. An AI review of the same text found nothing harmful.
AI review by kimi-k2.7-code on 2026-10-03. Automated pattern scan on 2026-10-03. It catches known dangerous patterns, not every risk — read a skill before letting an agent act on it.
claude-code-hooks compared with similar skills
All 4 of these similar skills score higher than claude-code-hooks; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| claude-code-hooks (this skill)by daymade | 84 | 1.4k | 53d ago | SKILL.md |
| taste-skillby Leonxlnx | 100 | 116.8k | 8d ago | CLAUDE.md |
| ai-job-searchby ai-job-search-dev | 100 | 72.1k | today | CLAUDE.md |
| claude-howtoby luongnv89 | 100 | 47.3k | 2d ago | CLAUDE.md |
| lobehubby lobehub | 100 | 85.6k | today | MCP Server |
Frequently asked questions
- How do I install claude-code-hooks?
- Run
npx skills add daymade/claude-code-skills --skill claude-code-hooks. The install tabs above show the steps for each supported agent. - Which AI agents does claude-code-hooks work with?
- It is written for Claude Code, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is claude-code-hooks safe to use?
- Our scan of the whole file found no instruction hijacking, hidden characters, credential access, data exfiltration or destructive commands. An AI review of the same text found nothing harmful. It is MIT-licensed and scores 100/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is claude-code-hooks still maintained?
- The repository was last updated about 2 months ago, so claude-code-hooks is actively maintained.
Skill content
View source on GitHubname: claude-code-hooks description: >- Writes, tests, registers and debugs Claude Code hooks (PreToolUse, PostToolUse, SessionStart, Stop) that turn a rule the model keeps breaking into a hard gate. Use when the user wants to block or intercept a tool call, add a guard rail, fix a misfiring hook, or says 拦截 / 守卫 / 钩子 — including "make it stop doing X".
Claude Code Hooks
Claude Code fires hooks at tool-call boundaries. A hook is a shell command that receives a JSON event on stdin and, for blocking hooks, decides via its exit code whether the tool call proceeds. This is the only mechanism that structurally stops a behavior — a prose rule in CLAUDE.md is a suggestion the completion drive can override; a hook is a wall.
When a hook is the right tool (and when it isn't)
Write a hook when a rule keeps getting violated even though it's already written down. The tell: you added the prose rule, it read clearly, and the behavior recurred anyway — because at the moment of action, attention is 100% on "get the thing done" and the reminder loses. That recurrence is the signal to move the rule from prose (advisory) to a hook (enforced). Governance rule of thumb: Tier-0 irreversible action + only prose, no hook → it should be a hook. (Tier-0 here = an action whose damage cannot be undone from inside the session: destroying uncommitted work, pushing secrets to a remote, deleting files, publishing something outward. The test is reversibility, not severity.)
Do not reach for a hook when: the rule has never actually recurred (don't pre-build guards for hypothetical mistakes — cost with no proven benefit), or the "rule" is a judgment call with no mechanical signature (a hook can only match tokens/patterns; it can't judge whether a design is good).
If the symptom is “it keeps reviewing / waiting / retrying,” do not assume the answer is another hook. First complete the Loop Contract in rule 7 and read pitfall #36. The loop may be created entirely by an agent repeatedly applying a prose rule.
Hook types and what the exit code means
| Type | Fires | Exit 0 | Exit 2 | Other |
|---|---|---|---|---|
| PreToolUse | before a tool runs | allow | block the call (stderr → shown to model as guidance) | any other exit = "non-blocking error" → the call proceeds — but only while stdout carries no valid JSON. Claude Code reads JSON output on every exit code, and valid JSON overrides the code entirely. The skeletons here print nothing on stdout, so their fail-open reasoning holds; add a permissionDecision payload and the exit code stops being the decision |
| PostToolUse | after a tool ran | quiet unless it prints a hookSpecificOutput JSON on stdout — that is how context injection works, and it happens at exit 0 | feedback to the model (can't un-run the tool) | — |
| SessionStart | session begins | proceed | cannot block — stderr shows the user a hook-error notice, Claude never sees it, the session starts anyway | exit 0 anyway: not because a non-zero would block (it can't), but because anything non-zero puts a <hook> hook error in the user's transcript on every single session start. Takes a matcher on how the session started — startup, resume, clear, compact, fork |
| Stop (+ SubagentStop) | the model is about to finish responding | let it stop | block the stop — forces the model to keep going (stderr → fed back as the reason) | loop safety: the hook checks stop_hook_active (necessary, not sufficient — rule 7). The harness's consecutive-block ceiling (default 8) is not a general backstop — its counter resets on any continuation that executed tools, so it never arrives for a hook whose remediation involves tool calls, which is most of them (#27). Carry your own bound. All Stop hooks for an event run in parallel — one block round can carry several hooks' feedback |
- PreToolUse is the workhorse for stopping a tool call — the four types in this
table are the ones this file teaches, not the complete set of blockable events, and
the official hooks reference (docs.claude.com / code.claude.com, not the
references/files in this bundle — those cover only the four types above) now lists many more blockable events, includingUserPromptSubmit,PreCompact,TeammateIdle, and task and config events. If what you need to gate is not a tool call, look there before forcing it onto PreToolUse.matcherselects the tool (Bash,Agent,WebFetch, …) — and how it is matched depends on the characters you use: a matcher containing only letters, digits,_,-, spaces,,and|is compared as an exact string (or a|/,-separated list of exact strings); anything else is treated as an unanchored JavaScript regex. Both directions bite silently —Edit.*also matchesNotebookEdit(anchor it^Edit$), whilemcp__memorymatches nothing because it is all exact-match characters and no tool is named exactly that (you wantmcp__memory__.*). Matching is case-sensitive. Exit 2 blocks and the hook's stderr becomes the message the model sees — so put the why and the correct alternative there, not just "blocked". - PostToolUse can't undo, but it can inject authoritative context so a later hallucination can't stand (e.g. re-read the real git HEAD after a commit and surface it — the model can't "believe it committed" against injected truth).
- SessionStart is for health checks of the guard rails themselves — silent when healthy, warn on breakage, always exit 0. Note why: it is not that a non-zero exit would block the session (it cannot), but that it would print a hook-error notice at every session start until someone fixes it — a check that cries wolf on startup is a check people learn to scroll past.
set -euo pipefailvsset -uo pipefail— pick by contract, and know there are two ways to keep an always-exit-0 contract. A hook that may block (PreToolUse) wants-e: an unexpected failure aborting the script is survivable, because the caller treats a non-0/2 exit as "proceed". A hook whose contract is ALWAYS exit 0 (PostToolUse injectors, SessionStart checks) has two honest shapes: (a) drop-eand||-guard every risky command — with-eon, onegrepthat legitimately finds nothing kills the hook mid-way and the CLI surfaces a bareFailed with non-blocking status code(pitfall #8, Pattern E's shape); or (b) keep-eand addtrap 'exit 0' ERRso any failure still converts to exit 0 while-ekeeps guarding the plumbing (git-commit-headcheck's production shape, Pattern D). Either is correct; what you cannot do is-ealone with no trap and no||-guards. Rule of thumb:-efor hooks that decide; for hooks that report, drop-eor trap it (pitfall #8).- Stop is the odd one out, and the one most often reached for by mistake:
it's the only hook type that can react to what the model itself just
generated (its own reply text). Every other hook type — including
UserPromptSubmit, which sounds like a plausible place to police "what gets said" — only ever sees the user's input; it structurally cannot see the model's own current-turn output (that claim holds — this is still the right reason to route such a rule to Stop). That guarantee, however, does not extend to proving the.promptfield always originated from a keystroke: a background task-notification's own report text can populate it too, and so can a teammate's or another session's message — no field in the stdin JSON marks the difference, only the wrapper tag the text opens with — #30. A rule like "the model must not invent a shorthand name for something it hasn't verified" belongs on Stop; put it onUserPromptSubmitinstead and it will (a) never once catch what it was built for, since that text never flows through that event, and (b) false-block the user's own unrelated typing whenever it happens to contain the trigger pattern. This is a category mistake, not a tuning problem — no amount of regex refinement on the wrong event fixes it. Full contract (last_assistant_messagevstranscript_path, the anti-loop check) in Pattern E in references/hook_patterns.md. - Stop has two block channels with identical loop protections — pick by
intent, and make the first (only) block carry everything.
decision: "block"+reason, or plain exit 2 + stderr, shows as a hook error — for hard gates ("this must not stand").hookSpecificOutput.additionalContextshows as neutral "Stop hook feedback" with no error notification — for coaching and reminders the model should weigh, not gates. Both count toward the same consecutive-block ceiling from the table above, so the choice is tone, not safety. What that means for message design: a blocked retry round (stop_hook_active: true) is let through with whatever violations remain — so a Stop guard gets exactly one informed bite. (The ceiling reinforces this only when your remediation is "rewrite the reply"; if it involves tool calls the counter resets and the ceiling never lands — #27. Either way the one-bite conclusion holds, because it rests on the latch, not on the ceiling.) Report all findings in that one block (a guard that prints only the first loses the rest permanently — pitfall #17), and write the message as an escape manual naming the exact acceptable fix, not a verdict — the model converges in one round or it burns the cap guessing. v2.1.145+ inputsbackground_tasks/session_cronslet a blocking hook tell "the session is done" from "the session is merely paused waiting for background work" — blocking a pause forces pointless continuations and wastes the same cap.
Full runnable skeletons: references/hook_patterns.md.
The skeleton (PreToolUse Bash guard)
#!/usr/bin/env bash
set -euo pipefail
IFS= read -rd '' INPUT || true # builtin; NOT $(cat) — see below
# 0-fork fast path: a builtin `case` on the raw JSON, BEFORE paying for python3.
# Your guard runs on EVERY matching tool call, so the irrelevant path is the one
# that has to be cheap. Keep this filter BROADER than what you actually block and
# never flag-level — it answers "is this even about X", nothing finer (#22).
case "$INPUT" in *TRIGGER*) ;; *) exit 0 ;; esac
TOOL=$(printf '%s' "$INPUT" | python3 -c "import sys,json;print(json.load(sys.stdin).get('tool_name',''))" 2>/dev/null||echo "")
[ "$TOOL" != "Bash" ] && exit 0 # only guard the tool you mean to
CMD=$(printf '%s' "$INPUT" | python3 -c "import sys,json;print(json.load(sys.stdin).get('tool_input',{}).get('command',''))" 2>/dev/null||echo "")
[ -z "$CMD" ] && exit 0
printf '%s' "$CMD" | grep -qw 'TRIGGER' || exit 0 # precise relevance check
# ... precise detection here ...
if <command actually does the banned thing>; then
echo "BLOCKED: ... WHY ... USE INSTEAD: ..." >&2 # stderr = the guidance shown
exit 2
fi
exit 0
Why the first two lines are not stylistic. INPUT=$(cat) plus each
printf … | python3 -c … costs forks on every call this hook matches, including
the ones it has nothing to say about. A fleet of ~13 Bash-matcher hooks × parallel
sessions × sub-second tool cadence turned that into a sustained 40–200 forks/sec of
pure guard overhead and put Gatekeeper at the top of an all-day CPU ranking with no
runaway process anywhere — the fleet was fine; the irrelevant path's per-call cost
was the bug (#22, with the per-guard conversion recipe and its measured floor).
Three caveats before you copy the case line anywhere else — the first one is the
difference between a fast path and a by
Truncated for display — read the full file on GitHub.
Related Skills
taste-skill
116.8kAgent skills that give coding agents taste: art direction, reference images and a browser check instead of generic AI pages
ai-job-search
72.1kThe job search that runs on your machine. AI job application framework built on Claude Code: evaluate postings, tailor CVs, write cover letters, prep interviews. Fork it and own it.
claude-howto
47.3kA visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.
lobehub
85.6k🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
