hook-authoring
Creates and configures Claude Code hooks for lifecycle automation. Covers all 17 hook events, 4 hook types (command, prompt, agent, http), matchers, input/output formats, and exit codes. Follows official Anthropic best practices. USE WHEN: user mentions "hook", "hooks", "auto-format", "pre tool use", "post tool use", "session start", "notification hook", "block command", "validate tool", "lifecycle event", "PostToolUse", "PreToolUse" DO NOT USE FOR: creating skills - use `skill-authoring`; creating agents - use `agent-authoring`; webhook endpoints - different concept
What this skill does
# Hook Authoring — Official Best Practices
## What Hooks Do
Hooks are deterministic shell commands (or LLM prompts) that execute at specific lifecycle points. They provide guaranteed behavior — not relying on the LLM to choose to run them.
## Configuration Locations
| Location | Scope | Shareable |
|----------|-------|-----------|
| `~/.claude/settings.json` | All projects | No |
| `.claude/settings.json` | Single project | Yes (commit) |
| `.claude/settings.local.json` | Single project | No (gitignored) |
| Agent/skill frontmatter | While component active | Yes |
| Plugin `hooks/hooks.json` | When plugin enabled | Yes |
## Hook Types
| Type | How it works | Use when |
|------|-------------|----------|
| `command` | Runs shell command, reads stdin JSON, uses exit codes | Deterministic validation, formatting, logging |
| `prompt` | Single-turn LLM call, returns `{ok, reason}` | Judgment-based decisions without tool access |
| `agent` | Multi-turn subagent with tool access | Verification requiring file reads or commands |
| `http` | POSTs event data to URL endpoint | External service integration, audit logging |
## Hook Events
See [quick-ref/events-reference.md](quick-ref/events-reference.md) for full input/output schemas.
| Event | Matcher input | Can block? | Common use |
|-------|--------------|------------|------------|
| `SessionStart` | startup/resume/clear/compact | No | Re-inject context after compaction |
| `UserPromptSubmit` | (none) | Yes | Validate/transform user input |
| `PreToolUse` | Tool name | Yes | Block commands, validate operations |
| `PermissionRequest` | Tool name | Yes | Auto-allow/deny permissions |
| `PostToolUse` | Tool name | No* | Auto-format files, logging |
| `PostToolUseFailure` | Tool name | No | Error handling |
| `Notification` | Notification type | No | Desktop alerts |
| `SubagentStart` | Agent type | No | Setup before agent runs |
| `SubagentStop` | Agent type | No | Cleanup after agent |
| `Stop` | (none) | Yes | Verify completeness |
| `ConfigChange` | Config source | Yes | Audit, block unauthorized changes |
| `PreCompact` | manual/auto | No | Save context before compaction |
| `SessionEnd` | Exit reason | No | Cleanup |
*PostToolUse `Stop` hooks can return `{"decision": "block"}` to keep Claude working.
## Configuration Format
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write",
"timeout": 30
}
]
}
]
}
}
```
## Input/Output Protocol
### Input (stdin JSON)
Every hook receives JSON on stdin with common fields + event-specific data:
```json
{
"session_id": "abc123",
"cwd": "/path/to/project",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": { "command": "npm test" }
}
```
### Output (exit codes)
| Exit code | Effect |
|-----------|--------|
| `0` | Allow — action proceeds. Stdout added to context (SessionStart, UserPromptSubmit) |
| `2` | Block — action cancelled. Stderr sent to Claude as feedback |
| Other | Allow — stderr logged (visible in verbose mode Ctrl+O) |
### Structured JSON output (exit 0 + JSON on stdout)
```json
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Use rg instead of grep"
}
}
```
PreToolUse decisions: `"allow"`, `"deny"`, `"ask"`.
## Common Patterns
### Auto-format after edits
```json
{
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]
}]
}
```
### Block protected files
```bash
#!/bin/bash
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
for pattern in ".env" "package-lock.json" ".git/"; do
if [[ "$FILE" == *"$pattern"* ]]; then
echo "Blocked: matches protected pattern '$pattern'" >&2
exit 2
fi
done
exit 0
```
### Re-inject context after compaction
```json
{
"SessionStart": [{
"matcher": "compact",
"hooks": [{ "type": "command", "command": "echo 'Reminder: use Bun, not npm. Run tests before commits.'" }]
}]
}
```
### Notification on idle
```json
{
"Notification": [{
"matcher": "",
"hooks": [{ "type": "command", "command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'" }]
}]
}
```
## Stop Hook Infinite Loop Prevention
Always check `stop_hook_active` to avoid loops:
```bash
INPUT=$(cat)
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
exit 0 # Let Claude stop
fi
# ... your logic
```
## Anti-Patterns
| Anti-Pattern | Fix |
|--------------|-----|
| Shell profile `echo` breaks JSON | Wrap in `if [[ $- == *i* ]]` |
| Stop hook without loop guard | Check `stop_hook_active` field |
| Using PostToolUse to undo actions | Too late — use PreToolUse to block instead |
| Relying on PermissionRequest in headless mode | Doesn't fire in `-p` mode. Use PreToolUse |
## Checklist
- [ ] Correct event chosen for the use case
- [ ] Matcher pattern tested (case-sensitive, regex)
- [ ] Script is executable (`chmod +x`)
- [ ] Uses `jq` for JSON parsing (or Python/Node)
- [ ] Exit code 2 for blocking, 0 for allowing
- [ ] Stop hooks check `stop_hook_active`
- [ ] Tested with sample JSON piped to stdin
- [ ] Hook script uses absolute paths or `$CLAUDE_PROJECT_DIR`
## Reference
- [All events with input/output schemas](quick-ref/events-reference.md)
- [Hook types comparison](quick-ref/hook-types.md)
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.