Added three new major feature categories with complete documentation and examples: ## New Features ### 07-hooks/ - Event-driven automation with 6 example hook scripts - Pre/post tool hooks, session hooks, and git hooks - Auto-formatting, security scanning, test automation - Complete documentation with best practices ### 08-checkpoints/ - Conversation state snapshots and rewind capability - Safe experimentation and approach comparison - Real-world examples: DB migration, performance optimization, UI iteration - Checkpoint management commands and workflows ### 09-advanced-features/ - Planning Mode: detailed implementation plans before coding - Extended Thinking: deep reasoning for complex problems - Background Tasks: long-running operations without blocking - Permission Modes: unrestricted, confirm, read-only, custom - Headless Mode: CI/CD integration and automation - Session Management: multiple work sessions - Interactive Features: keyboard shortcuts, command history - 10+ configuration examples for different scenarios ## Documentation Updates - README.md: Added sections for all new features with examples - INDEX.md: Updated with new categories, file listings, and search keywords - QUICK_REFERENCE.md: Added quick reference for new features - claude_concepts_guide.md: Comprehensive guide sections for new concepts ## Statistics - Total files: 90+ (up from 71) - Categories: 9 (up from 6) - New hook scripts: 6 - New documentation files: 10+ - Configuration examples: 10+ scenarios All examples are production-ready and follow Claude Code best practices. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
6.5 KiB
6.5 KiB
Hooks
Hooks are shell commands that execute automatically in response to specific events in Claude Code. They enable custom workflows, validation, and automation.
What Are Hooks?
Hooks are event-driven scripts that run at specific points during Claude Code's operation:
- Pre-hooks: Run before an action
- Post-hooks: Run after an action
- Validation hooks: Check conditions before proceeding
Available Hook Types
1. Tool Hooks
Execute before/after tool usage:
PreToolUse:{ToolName}- Before a tool is usedPostToolUse:{ToolName}- After a tool completes- Examples:
PreToolUse:Edit,PostToolUse:Bash,PreToolUse:Write
2. Session Hooks
Execute during session lifecycle:
UserPromptSubmit- Before processing user inputSessionStart- When a new session beginsSessionEnd- When a session ends
3. Git Hooks
Execute during git operations:
PreCommit- Before creating a commitPostCommit- After commit completesPrePush- Before pushing to remote
Configuration
Hooks are configured in Claude Code settings:
{
"hooks": {
"PreToolUse:Edit": "eslint --fix ${file_path}",
"PostToolUse:Bash": "echo 'Command completed' >> /tmp/bash.log",
"UserPromptSubmit": "~/.claude/hooks/validate-prompt.sh",
"PreCommit": "npm test"
}
}
Hook Variables
Available variables in hook commands:
${file_path}- Path to file being edited/written${command}- Command being executed (Bash hooks)${tool_name}- Name of the tool being used${session_id}- Current session identifier
Examples
Example 1: Auto-format Code on Edit
Hook: PreToolUse:Write
#!/bin/bash
# ~/.claude/hooks/format-code.sh
FILE=$1
# Detect file type and format accordingly
case "$FILE" in
*.js|*.jsx|*.ts|*.tsx)
prettier --write "$FILE"
;;
*.py)
black "$FILE"
;;
*.go)
gofmt -w "$FILE"
;;
esac
Configuration:
{
"hooks": {
"PreToolUse:Write": "~/.claude/hooks/format-code.sh ${file_path}"
}
}
Example 2: Run Tests Before Commit
Hook: PreCommit
#!/bin/bash
# ~/.claude/hooks/pre-commit.sh
echo "Running tests before commit..."
# Run tests
npm test
# Check exit code
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked."
exit 1
fi
echo "✅ Tests passed! Proceeding with commit."
exit 0
Configuration:
{
"hooks": {
"PreCommit": "~/.claude/hooks/pre-commit.sh"
}
}
Example 3: Security Scan on File Write
Hook: PostToolUse:Write
#!/bin/bash
# ~/.claude/hooks/security-scan.sh
FILE=$1
# Check for common security issues
if grep -q "password\s*=\s*['\"]" "$FILE"; then
echo "⚠️ WARNING: Potential hardcoded password detected in $FILE"
fi
if grep -q "api[_-]key\s*=\s*['\"]" "$FILE"; then
echo "⚠️ WARNING: Potential hardcoded API key detected in $FILE"
fi
# Scan with semgrep if available
if command -v semgrep &> /dev/null; then
semgrep --config=auto "$FILE" --quiet
fi
Configuration:
{
"hooks": {
"PostToolUse:Write": "~/.claude/hooks/security-scan.sh ${file_path}"
}
}
Example 4: Log All Bash Commands
Hook: PostToolUse:Bash
#!/bin/bash
# ~/.claude/hooks/log-bash.sh
COMMAND=$1
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
LOGFILE="$HOME/.claude/bash-commands.log"
echo "[$TIMESTAMP] $COMMAND" >> "$LOGFILE"
Configuration:
{
"hooks": {
"PostToolUse:Bash": "~/.claude/hooks/log-bash.sh '${command}'"
}
}
Example 5: Validate User Prompts
Hook: UserPromptSubmit
#!/bin/bash
# ~/.claude/hooks/validate-prompt.sh
# Read prompt from stdin
PROMPT=$(cat)
# Check for prohibited patterns
if echo "$PROMPT" | grep -qi "delete database"; then
echo "❌ Blocked: Dangerous operation detected"
exit 1
fi
# Check for required context
if echo "$PROMPT" | grep -qi "deploy to production"; then
if [ ! -f ".deployment-approved" ]; then
echo "❌ Blocked: Production deployment requires approval file"
exit 1
fi
fi
exit 0
Configuration:
{
"hooks": {
"UserPromptSubmit": "~/.claude/hooks/validate-prompt.sh"
}
}
Hook Exit Codes
Hooks communicate results via exit codes:
0- Success, continue operation1- Failure, block operation (for pre-hooks)- Other codes - Treated as warnings
Best Practices
Do's ✅
- Keep hooks fast (< 1 second when possible)
- Use hooks for validation and automation
- Log important events
- Make hooks idempotent
- Handle errors gracefully
- Use absolute paths in hooks
Don'ts ❌
- Don't make hooks interactive (no user input)
- Don't use hooks for long-running tasks
- Don't hardcode credentials in hooks
- Don't ignore hook failures silently
- Don't modify files unexpectedly
Common Use Cases
Code Quality
{
"hooks": {
"PreToolUse:Write": "eslint --fix ${file_path}",
"PostToolUse:Write": "prettier --check ${file_path}"
}
}
Security
{
"hooks": {
"PostToolUse:Write": "~/.claude/hooks/security-scan.sh ${file_path}",
"PreCommit": "git secrets --scan"
}
}
Testing
{
"hooks": {
"PreCommit": "npm test",
"PostToolUse:Edit": "jest --findRelatedTests ${file_path}"
}
}
Deployment
{
"hooks": {
"PrePush": "npm run build && npm run test:e2e",
"PostPush": "~/.claude/hooks/notify-team.sh"
}
}
Debugging Hooks
Enable hook debugging:
{
"hooks": {
"debug": true
}
}
View hook execution logs:
tail -f ~/.claude/hooks.log
Installation
- Create hooks directory:
mkdir -p ~/.claude/hooks
- Copy example hooks:
cp 07-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
- Configure in settings:
Edit
~/.claude/settings.jsonto add hook configurations.
Troubleshooting
Hook Not Executing
- Check hook path is correct
- Verify file has execute permissions
- Check hook name matches event exactly
- Enable debug mode
Hook Blocking Operations
- Check hook exit code
- Review hook output/logs
- Test hook independently
- Add error handling
Performance Issues
- Profile hook execution time
- Optimize slow operations
- Consider async execution
- Cache results when possible
Advanced Examples
See the example files in this directory:
format-code.sh- Auto-format code before writingpre-commit.sh- Run tests before commitssecurity-scan.sh- Scan for security issueslog-bash.sh- Log all bash commandsvalidate-prompt.sh- Validate user promptsnotify-team.sh- Send notifications on events