/meta:create-hookfrom meta
Author, review and debug Claude Code hooks: entries under `hooks` in settings.json, a plugin's hooks/hooks.json, or skill and agent frontmatter. Use when the user wants something to happen automatically on a Claude Code event, such as blocking a command, formatting files after edits, injecting context at session start, notifying when Claude finishes or auditing config changes, or names an event such as PreToolUse, PostToolUse, Stop, SessionStart or UserPromptSubmit. Also use when a hook does not fire, does not block, loops or breaks JSON parsing, and for matcher and `if` patterns, exit codes, permissionDecision, additionalContext and the choice between command, http, mcp_tool, prompt and agent hooks, even if the user does not say "hook". Skills and subagents on their own belong to the sibling create-skill and create-agent skills.
Ships in meta. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You author, review and debug Claude Code hooks. The deliverable is a hook configuration, plus any handler script, that fires at the right lifecycle point, makes the correct decision, and has been shown to block what it should block and allow what it should allow. A hook that exits 0 when it should exit 2 looks exactly like a working hook, so nothing counts as done until a test has exercised the blocking path.
Copy this checklist into your reply and tick it off as you go. If a step fails, return to the step named in brackets rather than moving on.
Hook progress:
- [ ] 0. Intent captured: what always happens, at which moment, and what failure means
- [ ] 1. Event chosen, and confirmed it can make that decision (if not, return to 0)
- [ ] 2. Location chosen (settings, plugin hooks.json, or skill/agent frontmatter)
- [ ] 3. Configuration and handler written, matcher and `if` as narrow as possible
- [ ] 4. Decision contract checked against the event
- [ ] 5. Tested on stdin with should-block and should-allow inputs, then in a real session (if it fails, return to 3 or 4)
- [ ] 6. Iterated until every test case passes
- [ ] 7. Saved, and for a plugin, validated and installed
A hook is a deterministic interception of Claude Code's lifecycle, and three things decide whether it works.
PostToolUse cannot block, because the tool has already run.
PermissionRequest fires only when a permission prompt would appear, so it never sees calls a rule or the permission mode already allows.
Stop fires every time Claude finishes responding, not only when the task is done.if filters on tool name and arguments together.
Keep both as narrow as possible, because a broad matcher adds a process spawn to every matching call and activates the handler on calls it was not written for.decision, hookSpecificOutput.permissionDecision or hookSpecificOutput.decision.behavior.
Claude Code ignores fields an event does not recognise, so a hook with the wrong contract runs, reports nothing and does nothing.You are an advisor, not an assistant. Your job is to improve the user's design for this hook, not to implement the first matcher they describe.
[Likely] or [Guessing], mainly for harness behaviour you have not verified with a stdin test or a real session: whether an event fires inside a subagent, how two hooks' updatedInput combine, how a matcher treats an MCP tool name.jq failure swallowed by || true, a fallback that allows the call when the script errors.
A guard that fails open must be named as such, never presented as protection.Hooks produce little prose, but Claude and the user read it on every trigger: denial reasons, additionalContext, systemMessage and script comments.
Write it in British English, in plain sentences in the active voice, with no em-dashes.
additionalContext states facts ("The deployment target is production"), not imperatives, because imperative text injected mid-conversation can trip Claude's prompt-injection defences.Four sibling skills cover Claude Code's authoring primitives and instruction files, and they ship together in the meta plugin:
meta:create-hook (this skill): deterministic interception of a lifecycle event.meta:create-skill: context that loads on demand into the parent conversation.meta:create-agent: a subagent with its own context window, tool scope and return contract.meta:create-instructions: CLAUDE.md files and the .claude/rules/ directory, which Claude Code does not enforce.When the job needs a sibling primitive, invoke the sibling through the Skill tool and hand over what you have gathered (event, matcher, if, decision contract, handler type), so it does not repeat its own intake.
A hook packaged in a skill's hooks: frontmatter needs meta:create-skill for the wrapping SKILL.md.
A hook scoped to a subagent needs meta:create-agent, but a plugin agent ignores hooks: frontmatter, so a plugin's agent-specific hook goes in hooks/hooks.json with a SubagentStart or tool matcher instead.
A hook replaces asking Claude to remember a rule, so the question is always what should happen regardless of what Claude decides. Extract what you can from the conversation, then ask in one batched message only for the gaps:
PostToolUse to block, so confirm the event against Phase 1 before drafting.Some requests are not hooks. A static convention belongs in CLAUDE.md. A blanket allow or deny of a tool belongs in a permission rule, which needs no script and cannot fail open. A procedure Claude follows on request belongs in a skill.
Wait for confirmation before drafting. If the user has already answered these, say so and proceed.
Events fire at three cadences, and cost compounds with cadence.
| Cadence | Events | Blocking events and how |
|---|---|---|
| Once per session | SessionStart, Setup, SessionEnd | None |
| Once per turn | UserPromptSubmit, UserPromptExpansion, Stop, StopFailure, PreCompact, PostCompact, TeammateIdle | UserPromptSubmit (the prompt never reaches Claude), UserPromptExpansion, Stop (keeps Claude working), PreCompact, TeammateIdle |
| Per tool call | PreToolUse, PermissionRequest, PermissionDenied, PostToolUse, PostToolUseFailure, PostToolBatch, SubagentStart, SubagentStop, TaskCreated, TaskCompleted | PreToolUse (the place to stop a tool call), PermissionRequest (JSON decision.behavior only, exit 2 is not honoured), PostToolBatch, SubagentStop, TaskCreated, TaskCompleted |
| Standalone | Notification, MessageDisplay, InstructionsLoaded, ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove, PreModelSwitch, PostModelSwitch, Elicitation, ElicitationResult | ConfigChange (not policy settings), WorktreeCreate, WorktreeRemove, PreModelSwitch, Elicitation, ElicitationResult |
Hooks from settings, managed policy and plugins also fire for tool calls inside subagents, with agent_id and agent_type in the input.
A per-tool-call hook runs inside the agentic loop, so a slow one compounds over a long session.
Mark expensive work async: true, or asyncRewake: true to report a failure back to Claude later.
Read ${CLAUDE_SKILL_DIR}/references/events.md for what each event's matcher filters on, which events ignore matchers, and each event's input fields.
| Location | Scope | Ships with |
|---|---|---|
~/.claude/settings.json | All your projects | Nothing, machine-local |
.claude/settings.json | One project | The repository |
.claude/settings.local.json | One project, one developer | Nothing, gitignored |
| Managed policy settings | Organisation | Admin deployment |
<plugin>/hooks/hooks.json | Wherever the plugin is enabled | The plugin |
Skill hooks: frontmatter | From the skill's first invocation to the end of the session | The skill |
Subagent hooks: frontmatter | While that subagent runs | The agent file |
When the working repository is a plugin marketplace (it has .claude-plugin/marketplace.json at the root), a requested hook becomes a plugin: plugins/<plugin>/hooks/hooks.json plus its scripts, referenced through the CLAUDE_PLUGIN_ROOT placeholder.
A skill's frontmatter hook stays registered for the rest of the session once the skill has run, so it suits a rule the skill switches on, and once: true removes it after its first successful run.
A subagent's frontmatter hook is removed when the subagent finishes, but a plugin agent ignores hooks: frontmatter, so plugin hooks always go in hooks/hooks.json.
Claude Code watches settings files and normally picks up edits without a restart.
In an interactive session, settings hooks wait until the workspace trust dialog is accepted, while -p runs treat the folder as trusted.
A configuration nests three levels: the event, a matcher group, and one or more handlers.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(git push *)",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-push.sh"
}
]
}
]
}
}
The matcher rules break most often:
_, -, spaces, , and | is an exact name or a list separated by | or ,, and anything else is an unanchored JavaScript regex.
So mcp__github matches no tool and the whole server needs mcp__github__.*, while Edit.* also matches NotebookEdit unless written ^Edit$.mcp__plugin_<plugin>_<server>__<tool>, so a matcher on the bare server key never fires for them.bash matches nothing.if takes one permission rule such as Bash(git push *) or Edit(*.ts), and is honoured only on tool events.
On any other event a handler with if never runs.if strips leading VAR=value assignments and checks every subcommand, including those inside $() and backticks, so npm test && git push triggers Bash(git push *).
When Claude Code cannot tell which commands a Bash input runs, the handler runs anyway.
Put the filter in if rather than in the script, so the process is not spawned for unrelated calls.if is best-effort filtering, and Anthropic's reference says to enforce a hard allow or deny with a permission rule rather than a hook.Handler scripts follow four rules:
CLAUDE_PROJECT_DIR or CLAUDE_PLUGIN_ROOT placeholder, written in braces with a leading dollar sign in the configuration, never a bare relative path.
Prefer exec form ("command" plus an "args" array), which passes each argument without a shell, and quote the placeholder in shell form.
This file names the placeholders without braces because Claude Code expands braced CLAUDE_* variables in a loaded SKILL.md, and the reference files show them in full.uv run and PEP 723 inline metadata, never the system interpreter or a global pip install.chmod +x every script, because a missing or non-executable script is a non-blocking error and the action proceeds.Read ${CLAUDE_SKILL_DIR}/references/handlers.md for the five handler types and their fields, environment variables, async, CLAUDE_ENV_FILE, how parallel handlers combine, and script skeletons.
Read ${CLAUDE_SKILL_DIR}/references/templates.md for complete worked configurations.
Exit codes come first, because they are the most common silent failure.
| Exit code | Effect |
|---|---|
0 | The action proceeds, and stdout is parsed as JSON if present |
2 | Blocking error on events that can block, and no JSON field can override it. The blocking message is the JSON reason if there is one, otherwise stderr |
| Anything else | Non-blocking error: the action proceeds and the transcript shows a hook error, unless stdout holds valid JSON, which then decides the outcome alone |
exit 1 with plain-text output does not block, whatever Unix convention suggests.
WorktreeCreate and WorktreeRemove fail on any non-zero exit, and PermissionRequest ignores exit 2 entirely.
Pick one style per hook: exit codes alone, or exit 0 with JSON.
When the hook needs structured output, use the pattern the event reads:
| Events | Where the decision goes |
|---|---|
PreToolUse | hookSpecificOutput.permissionDecision: allow, deny, ask or defer, with permissionDecisionReason |
PermissionRequest | hookSpecificOutput.decision.behavior: allow or deny |
UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact | Top-level decision: "block" with reason |
TeammateIdle, TaskCreated, TaskCompleted | Exit 2, or {"continue": false, "stopReason": "..."} to stop entirely |
PreToolUse call, the most restrictive wins: deny, then defer, then ask, then allow.
defer only works in -p mode.PreToolUse command, http or mcp_tool hook that hits its timeout renders no decision and the tool call proceeds, so a slow guard fails open.allow cannot override a deny rule in settings or managed policy.
Hooks tighten permissions but cannot loosen them.Stop or SubagentStop hook that blocks must read stop_hook_active from its input and exit 0 when it is true.
Claude Code overrides a block after eight consecutive continuations, but a hook that relies on that cap wastes eight turns on a condition that may never clear.additionalContext from earlier turns is replayed from the transcript on resume, not recomputed, so live values such as a commit SHA go stale.Read ${CLAUDE_SKILL_DIR}/references/decisions.md for the effect of exit 2 on every event, the universal JSON fields, updatedInput, updatedPermissions, updatedToolOutput and where additionalContext lands.
A hook is not finished until a test has exercised both paths. Test the handler alone first, because a real session hides why a hook did nothing.
VAR=value, a chained &&, an absolute path to the binary, a quoted argument.printf '%s' '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git push origin main"}}' \
| "$CLAUDE_PROJECT_DIR"/.claude/hooks/guard-push.sh
echo "exit: $?"
${CLAUDE_SKILL_DIR}/assets/acceptance-template.sh to <plugin>/tests/acceptance.sh, fill in the case arrays, and run it after every change to the handler./hooks, confirm the hook is listed under the right event with the right matcher and source, and validate the JSON if it is missing.
For a plugin, run claude --plugin-dir plugins/<plugin> and check the hook is listed with the plugin as its source.additionalContext, confirm Claude uses the injected text in its next reply.claude --debug-file <path>, or claude --debug and read ~/.claude/debug/<session-id>.txt, and set CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose to see matcher counts.
A hook that cannot start (a mistyped path, a missing chmod +x) shows as Failed with non-blocking status code and leaves a guard silently disabled.claude plugin eval loads the plugin's hooks in every run, so a case can compare Claude's behaviour with and without the plugin; read meta:create-skill's evaluation reference for the case format.A prompt or agent handler has no deterministic output, so run it against several inputs in each direction and report the disagreements rather than a single passing run.
if scope, exit code, JSON shape or handler logic.Settings hooks take effect within the session.
A plugin hook needs the plugin's marketplace entry, claude plugin validate plugins/<plugin>, and an install to confirm it resolves, because validate checks the schema and not whether a script path exists.
Before committing project hooks, review what the scripts can reach: a hook runs with the user's permissions, and project hooks become trusted code once a teammate accepts the workspace-trust dialog.
When a hook misbehaves after release, read ${CLAUDE_SKILL_DIR}/references/troubleshooting.md.
PreToolUse to block a tool call, never PostToolUse)..* for an MCP server prefix, and uses the scoped name for a plugin's MCP server.if is used only on tool events, with one rule per handler.exit 2 or the event's JSON field, never exit 1 with plain text.CLAUDE_PROJECT_DIR or CLAUDE_PLUGIN_ROOT placeholder (exec form, or quoted in shell form), are executable, and keep stdout for JSON only.uv run with PEP 723 metadata.Stop and SubagentStop hooks check stop_hook_active.additionalContext follow the voice rules, and a guard that fails open on script error says so.async or asyncRewake.allowedEnvVars.claude plugin validate passes, the acceptance script passes, and an install succeeded.| Prohibited | Reason |
|---|---|
| Presenting a hook as a guard without a passing should-block test | An untested guard that exits 1 looks identical to a working one |
exit 1 or a non-2xx HTTP response to enforce a policy | Both are non-blocking, so the action proceeds |
|| true, set +e or a catch-all that makes a guard exit 0 on error | Turns a broken guard into a silent allow |
| Hard-coding secrets in a hook command, script or HTTP header | Hook configs are committed and shared, and header values belong in allowedEnvVars |
| Hooks that send prompts, transcripts or tool input to an external URL without the user's explicit agreement | It publishes the user's data, and may carry personal data (DSGVO) |
Editing managed policy settings or setting disableAllHooks without being asked | Disables protections the user or organisation relies on |
| Committing or pushing from this skill | Hand over to the user's commit workflow |
${CLAUDE_SKILL_DIR}/references/events.md: the event catalogue, what each matcher filters, events that ignore matchers, and input fields per event.${CLAUDE_SKILL_DIR}/references/handlers.md: command, http, mcp_tool, prompt and agent handlers, environment variables, async, CLAUDE_ENV_FILE, combining handlers, script skeletons and frontmatter hooks.${CLAUDE_SKILL_DIR}/references/decisions.md: exit 2 per event, JSON output fields, PreToolUse and PermissionRequest specifics, updatedToolOutput and additionalContext.
Read before writing any handler that returns JSON.${CLAUDE_SKILL_DIR}/references/templates.md: complete configurations for common hooks.${CLAUDE_SKILL_DIR}/references/troubleshooting.md: hooks that never fire, do not block, error, loop or break JSON, plus security review.${CLAUDE_SKILL_DIR}/assets/acceptance-template.sh: a stdin acceptance test for PreToolUse command hooks.What SKILL.md sets; muted values are Claude Code's defaults
highnpx claudepluginhub carelvniekerk/agentic-skills --plugin meta4 skills in this plugin
/create-agentAuthor, review and debug Claude Code subagents: Markdown agent files under .claude/agents/, ~/.claude/agents/ or a plugin's agents/, and --agents JSON. Use when the user wants an agent or subagent for a task, such as "make a code-reviewer agent", "a subagent that runs the tests" or "an agent to triage CI logs", or asks whether work should be a subagent, a fork, a skill or an agent team. Also use for agent frontmatter (tools, disallowedTools, model, permissionMode, skills, mcpServers, hooks, memory, background, isolation, effort), agents Claude never delegates to or picks wrongly, agents that dump raw output into the main conversation, plugin agents whose fields are ignored, and whole-session agents run with --agent, even if the user does not say "subagent". Skills and hooks on their own belong to the sibling create-skill and create-hook skills./create-instructionsAuthor, audit, update and restructure Claude Code instruction files: CLAUDE.md at user, project and subdirectory level, CLAUDE.local.md, and the .claude/rules/ directory with its `paths:` scoping. Use when the user wants to write or tidy a CLAUDE.md, says the file is too long or Claude ignores parts of it, asks whether content belongs in a rule, a skill, a hook or an agent prompt, wants rules that apply only to some files or folders, has user-level and project-level instructions that conflict, or asks how a subagent sees their CLAUDE.md, even if they do not say "rules". For a first draft generated from a fresh codebase the built-in init skill is the starting point, and this skill takes over to review, split and maintain the result. A one-off preference such as "remember that I prefer X" belongs to auto memory, and skills, hooks and subagents on their own belong to the sibling create-skill, create-hook and create-agent skills./create-skillAuthor, review, evaluate and improve Claude Code skills: SKILL.md files, their references/ and scripts/, and the plugins and marketplace entries that ship them. Use when the user wants to write, edit or review a SKILL.md or a skill, turn a workflow into a skill, says "add a skill for X", or has a skill that triggers too often or not at all. Also use for skill frontmatter (allowed-tools, disable-model-invocation, context fork, paths), skillOverrides and the skill listing budget, dynamic context injection, skill instructions lost after compaction, packaging skills in a plugin (plugin.json, marketplace.json, plugin names, claude plugin validate), and testing skills with claude plugin eval cases, graders or skill-creator, even if the user does not say "skill". Hooks and subagents on their own belong to the sibling create-hook and create-agent skills.Other plugins' skills for the same job