xiaohongshu
xiaohongshu
hooks-mastery
This skill should be used when the user asks to "create a hook", "configure hooks", "validate hook configuration", "add a PreToolUse hook", "add a PostToolUse hook", "add a SessionStart hook", mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, UserPromptSubmit, Permi...
Full skill instructions
Claude Code hooks are event-driven extensions that execute commands or LLM evaluations at specific lifecycle points. This skill provides guidance for creating production-ready hooks following the official protocol specification.
Command Hooks: Execute bash scripts with JSON input via stdin
{
"type": "command",
"command": "python3 /path/to/script.py",
"timeout": 60
}
Prompt-Based Hooks: Use LLM (Haiku) for intelligent evaluation
{
"type": "prompt",
"prompt": "Evaluate if Claude should stop: $ARGUMENTS",
"timeout": 30
}
| Event | Matcher | Purpose | Common Use Cases |
|---|---|---|---|
| PreToolUse | Yes | Before tool execution | Validation, modification, blocking |
| PermissionRequest | Yes | Permission dialog | Auto-approve/deny |
| PostToolUse | Yes | After tool execution | Formatting, validation |
| UserPromptSubmit | No | Before prompt processing | Context injection, validation |
| Stop/SubagentStop | No | Agent finishing | Determine if work complete |
| SessionStart | Yes | Session start/resume | Environment setup, context loading |
| SessionEnd | No | Session end | Cleanup, logging |
| Notification | Yes | Notifications sent | External alerting |
| PreCompact | Yes | Before compact | Validation, logging |
Hooks are configured in settings files (user, project, or local scope):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Write|Edit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validator.py",
"timeout": 30
}
]
}
]
}
}
Identify which lifecycle point to hook into:
Input Protocol: Hooks receive JSON via stdin with these common fields:
{
"session_id": "string",
"transcript_path": "string",
"cwd": "string",
"permission_mode": "default|plan|acceptEdits|bypassPermissions",
"hook_event_name": "EventName",
// Event-specific fields...
}
Output Protocol: Respond via exit codes and stdout:
Exit Code 0 (Success):
Exit Code 2 (Blocking):
Exit Code 1+ (Non-blocking):
Add to appropriate settings file:
~/.claude/settings.json - User-level.claude/settings.json - Project-level (team-shared).claude/settings.local.json - Local (git-ignored)Enable debug mode to see hook execution:
claude --debug
Use verbose mode (Ctrl+O) during session to see hook output.
Validate and potentially block tool calls:
#!/usr/bin/env python3
import json
import sys
# Read input
input_data = json.load(sys.stdin)
# Validate
if should_block(input_data):
print("Validation failed: reason", file=sys.stderr)
sys.exit(2) # Block execution
# Allow with optional modification
output = {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"updatedInput": {
"modified_field": "new_value"
}
}
}
print(json.dumps(output))
sys.exit(0)
Add context before Claude processes prompt:
#!/usr/bin/env python3
import json
import sys
import datetime
input_data = json.load(sys.stdin)
# Add context (plain text stdout with exit 0)
context = f"Current time: {datetime.datetime.now()}\n"
context += f"Current directory: {input_data['cwd']}"
print(context)
sys.exit(0)
Initialize environment variables and context:
#!/bin/bash
# Setup environment
source ~/.nvm/nvm.sh
nvm use 20
# Persist variables
if [ -n "$CLAUDE_ENV_FILE" ]; then
echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
fi
# Add context
echo "Environment initialized: Node $(node --version)"
exit 0
Use LLM for context-aware decisions:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Context: $ARGUMENTS\n\nDetermine if all tasks are complete. Check for:\n1. All user requests fulfilled\n2. No errors requiring fixes\n3. Tests passing\n\nRespond: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"
}
]
}
]
}
}
Matchers determine when hooks execute (PreToolUse, PostToolUse, PermissionRequest, Notification, PreCompact, SessionStart):
Exact match: "matcher": "Write" - Only Write tool
Regex: "matcher": "Edit|Write" - Multiple tools
All tools: "matcher": "*" or "matcher": ""
MCP tools: "matcher": "mcp__github__.*" - All GitHub server tools
Available in all hooks:
CLAUDE_PROJECT_DIR - Project root directoryCLAUDE_CODE_REMOTE - "true" if web environmentSessionStart hooks only:
CLAUDE_ENV_FILE - File path for persisting environment variablesPlugin hooks only:
CLAUDE_PLUGIN_ROOT - Plugin directoryInput Validation: Always validate and sanitize inputs
if '..' in file_path or file_path.startswith('/'):
print("Path traversal detected", file=sys.stderr)
sys.exit(2)
Shell Safety: Quote all variables
command="$CLAUDE_PROJECT_DIR/script.sh"
Sensitive Files: Skip .env, .git/, keys, etc.
sensitive = ['.env', '.git/', 'id_rsa', '*.pem']
if any(p in file_path for p in sensitive):
sys.exit(2)
Hook not executing:
/hooks commandclaude --debugHook timing out:
JSON parsing errors:
jqPermission denied:
chmod +x script.sh$CLAUDE_PROJECT_DIR| Event | Allow Action | Block Action | Modify Input |
|---|---|---|---|
| PreToolUse | permissionDecision: "allow" | permissionDecision: "deny" | updatedInput: {} |
| PermissionRequest | behavior: "allow" | behavior: "deny" | updatedInput: {} |
| PostToolUse | - | decision: "block" | - |
| UserPromptSubmit | - | decision: "block" | - |
| Stop/SubagentStop | - | decision: "block" | - |
| Code | stdout | stderr | Continues |
|---|---|---|---|
| 0 | Parsed as JSON/text | Ignored | Yes |
| 2 | Ignored | Fed to Claude/User | Depends |
| Other | Ignored | Logged | Yes |
For detailed protocol specifications:
references/protocol-specification.md - Complete protocol documentationreferences/event-reference.md - Detailed event specificationsFor working examples:
examples/pretooluse-validator/ - Bash command validationexamples/userprompt-enricher/ - Context injectionexamples/sessionstart-setup/ - Environment initializationexamples/stop-evaluator/ - Prompt-based decision makingFor validation and testing:
scripts/validate-hook-config.py - Validate hooks.json against schemascripts/test-hook-io.py - Test hook input/output locallyscripts/generate-hook-template.sh - Generate hook boilerplateFor schema validation:
assets/hooks-schema.json - JSON schema for hooks configurationxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience