Initial commit: Claude Code Hooks with Diátaxis documentation

 Features:
- 🧠 Shadow learner that builds intelligence from command patterns
- 🛡️ Smart command validation with safety checks
- 💾 Automatic context monitoring and backup system
- 🔄 Session continuity across Claude restarts

📚 Documentation:
- Complete Diátaxis-organized documentation
- Learning-oriented tutorial for getting started
- Task-oriented how-to guides for specific problems
- Information-oriented reference for quick lookup
- Understanding-oriented explanations of architecture

🚀 Installation:
- One-command installation script
- Bootstrap prompt for installation via Claude
- Cross-platform compatibility
- Comprehensive testing suite

🎯 Ready for real-world use and community feedback!

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Ryan Malloy 2025-07-19 18:25:34 -06:00
commit 162ca67098
34 changed files with 5904 additions and 0 deletions

View file

@ -0,0 +1,208 @@
# How to Add Custom Command Validation Patterns
**When to use this guide**: You want to block specific commands or add warnings for commands that are problematic in your environment.
## Add a Dangerous Command Pattern
If you have commands that should never be run in your environment:
1. **Edit the command validator**:
```bash
nano hooks/command_validator.py
```
2. **Find the dangerous_patterns list** (around line 23):
```python
self.dangerous_patterns = [
r'rm\s+-rf\s+/', # Delete root
r'mkfs\.', # Format filesystem
# Add your pattern here
]
```
3. **Add your pattern**:
```python
self.dangerous_patterns = [
r'rm\s+-rf\s+/', # Delete root
r'mkfs\.', # Format filesystem
r'docker\s+system\s+prune\s+--all', # Delete all Docker data
r'kubectl\s+delete\s+namespace\s+production', # Delete prod namespace
]
```
4. **Test your pattern**:
```bash
echo '{"tool": "Bash", "parameters": {"command": "docker system prune --all"}}' | python3 hooks/command_validator.py
```
Should return: `{"allow": false, "message": "⛔ Command blocked: Dangerous command pattern detected"}`
## Add Warning Patterns
For commands that are risky but sometimes legitimate:
1. **Find the suspicious_patterns list**:
```python
self.suspicious_patterns = [
r'sudo\s+rm', # Sudo with rm
r'chmod\s+777', # Overly permissive
# Add your pattern here
]
```
2. **Add patterns that should warn but not block**:
```python
self.suspicious_patterns = [
r'sudo\s+rm', # Sudo with rm
r'chmod\s+777', # Overly permissive
r'npm\s+install\s+.*--global', # Global npm installs
r'pip\s+install.*--user', # User pip installs
]
```
## Customize for Your Tech Stack
### For Docker Environments
Add Docker-specific protections:
```python
# In dangerous_patterns:
r'docker\s+rm\s+.*-f.*', # Force remove containers
r'docker\s+rmi\s+.*-f.*', # Force remove images
# In suspicious_patterns:
r'docker\s+run.*--privileged', # Privileged containers
r'docker.*-v\s+/:/.*', # Mount root filesystem
```
### For Kubernetes
Protect production namespaces:
```python
# In dangerous_patterns:
r'kubectl\s+delete\s+.*production.*',
r'kubectl\s+delete\s+.*prod.*',
r'helm\s+delete\s+.*production.*',
# In suspicious_patterns:
r'kubectl\s+apply.*production.*',
r'kubectl.*--all-namespaces.*delete',
```
### For Database Operations
Prevent destructive database commands:
```python
# In dangerous_patterns:
r'DROP\s+DATABASE.*',
r'TRUNCATE\s+TABLE.*',
r'DELETE\s+FROM.*WHERE\s+1=1',
# In suspicious_patterns:
r'UPDATE.*SET.*WHERE\s+1=1',
r'ALTER\s+TABLE.*DROP.*',
```
## Environment-Specific Patterns
### For Production Servers
```python
# In dangerous_patterns:
r'systemctl\s+stop\s+(nginx|apache|mysql)',
r'service\s+(nginx|apache|mysql)\s+stop',
r'killall\s+-9.*',
# In suspicious_patterns:
r'sudo\s+systemctl\s+restart.*',
r'sudo\s+service.*restart.*',
```
### For Development Machines
```python
# In suspicious_patterns:
r'rm\s+-rf\s+node_modules', # Can break local dev
r'git\s+reset\s+--hard\s+HEAD~[0-9]+', # Lose multiple commits
r'git\s+push\s+.*--force.*', # Force push
```
## Test Your Custom Patterns
Create a test script to verify your patterns work:
```bash
cat > test_patterns.sh << 'EOF'
#!/bin/bash
# Test dangerous pattern (should block)
echo "Testing dangerous pattern..."
echo '{"tool": "Bash", "parameters": {"command": "docker system prune --all"}}' | python3 hooks/command_validator.py
# Test suspicious pattern (should warn)
echo "Testing suspicious pattern..."
echo '{"tool": "Bash", "parameters": {"command": "npm install -g dangerous-package"}}' | python3 hooks/command_validator.py
# Test normal command (should pass)
echo "Testing normal command..."
echo '{"tool": "Bash", "parameters": {"command": "ls -la"}}' | python3 hooks/command_validator.py
EOF
chmod +x test_patterns.sh
./test_patterns.sh
```
## Advanced: Context-Aware Patterns
For patterns that depend on file context:
1. **Edit the validation function** to check current directory or files:
```python
def validate_command_safety(self, command: str) -> ValidationResult:
# Your existing patterns...
# Context-aware validation
if "git push" in command.lower():
# Check if we're in a production branch
try:
current_branch = subprocess.check_output(['git', 'branch', '--show-current'],
text=True).strip()
if current_branch in ['main', 'master', 'production']:
return ValidationResult(
allowed=True,
reason="⚠️ Pushing to protected branch",
severity="warning"
)
except:
pass
```
## Pattern Syntax Reference
Use Python regex patterns:
- `\s+` - One or more whitespace characters
- `.*` - Any characters (greedy)
- `.*?` - Any characters (non-greedy)
- `[0-9]+` - One or more digits
- `(option1|option2)` - Either option1 or option2
- `^` - Start of string
- `$` - End of string
**Examples**:
- `r'rm\s+-rf\s+/'` - Matches "rm -rf /"
- `r'git\s+push.*--force'` - Matches "git push" followed by "--force" anywhere
- `r'^sudo\s+'` - Matches commands starting with "sudo"
## Reload Changes
After modifying patterns:
1. **Test the changes**:
```bash
./test_patterns.sh
```
2. **No restart needed** - changes take effect immediately since hooks are called fresh each time
3. **Verify in Claude** by trying a command that should trigger your new pattern

View file

@ -0,0 +1,176 @@
# How to Restore Your Work from a Backup
**When to use this guide**: Your Claude session crashed, lost context, or you need to recover previous work.
## Quick Recovery (Most Common)
If you just lost context but your files are still there:
1. **Check for session recovery files**:
```bash
ls -la | grep -E "(LAST_SESSION|ACTIVE_TODOS|RECOVERY_GUIDE)"
```
2. **Read your session summary**:
```bash
cat LAST_SESSION.md
```
3. **Continue from your todos**:
```bash
cat ACTIVE_TODOS.md
```
This covers 90% of recovery scenarios. If you need to restore actual files, continue below.
## Full File Recovery
### Find Available Backups
List all available backups:
```bash
claude-hooks list-backups
```
Or check the backups directory directly:
```bash
ls -la .claude_hooks/backups/
```
You'll see entries like:
```
🗂️ backup_20240115_143022
📅 2024-01-15T14:30:22
📝 context_threshold
🗂️ backup_20240115_141856
📅 2024-01-15T14:18:56
📝 critical_operation
```
### Choose the Right Backup
**For context-related crashes**: Use the most recent `context_threshold` backup
**For command failures**: Use the backup before the problematic operation
**For file corruption**: Use the backup with the timestamp just before your issue
### Restore Files from Backup
1. **Navigate to the backup directory**:
```bash
cd .claude_hooks/backups/backup_20240115_143022
```
2. **Check what files are available**:
```bash
ls -la files/
```
3. **Copy specific files back**:
```bash
cp files/important_script.py ../../
```
Or restore all modified files:
```bash
cp -r files/* ../../
```
### Restore from Git Backup
If git backups were enabled:
1. **Check git history**:
```bash
git log --oneline | grep "Claude hooks auto-backup"
```
2. **See what changed in a backup commit**:
```bash
git show abc1234
```
3. **Restore specific files**:
```bash
git checkout abc1234 -- path/to/file.py
```
4. **Or reset to a backup completely** (careful - loses recent work):
```bash
git reset --hard abc1234
```
## Restore Session State
If you want to continue exactly where you left off:
1. **Restore the patterns database**:
```bash
cp .claude_hooks/backups/backup_20240115_143022/state/patterns/* .claude_hooks/patterns/
```
2. **Review the session state**:
```bash
cat .claude_hooks/backups/backup_20240115_143022/state/session.json
```
3. **Check what commands were running**:
```bash
jq '.commands_executed[-5:]' .claude_hooks/backups/backup_20240115_143022/state/session.json
```
## Emergency Recovery
If something went very wrong and you need to recover everything:
1. **Find the most recent emergency backup**:
```bash
ls -la .claude_hooks/emergency_backup.json
```
2. **Extract the session data**:
```bash
jq '.session_state.modified_files[]' .claude_hooks/emergency_backup.json
```
3. **Manually locate and recover files** using the file paths from the emergency backup
## Validate Your Recovery
After restoring:
1. **Check that your files are correct**:
```bash
git status
git diff
```
2. **Verify Claude Hooks is working**:
```bash
claude-hooks status
```
3. **Test a simple command** to ensure hooks are functioning:
```bash
echo 'print("test")' > test_recovery.py
python3 test_recovery.py
rm test_recovery.py
```
## Prevention for Next Time
To make future recovery easier:
- Enable git backups: Set `"git_enabled": true` in config/settings.json
- Lower backup threshold: Set `"backup_threshold": 0.75` to backup more frequently
- Create manual backups before risky operations: Run `claude-hooks backup`
## Troubleshooting
**No backups found**: Check if hooks were properly installed with `claude-hooks status`
**Backup files corrupted**: Try the git backup method or emergency recovery
**Can't find recent work**: Check if files are in a different directory - backups preserve the relative path structure
**Git backups not working**: Ensure git is initialized in your project: `git init`

View file

@ -0,0 +1,277 @@
# How to Share Learned Patterns with Your Team
**When to use this guide**: You want to share the intelligence your Claude Hooks has learned with teammates or across projects.
## Export Your Patterns
### Export Everything
Create a complete export of your learned patterns:
```bash
claude-hooks export
```
This creates a `claude_hooks_export/` directory with:
- `patterns.json` - All learned command patterns
- `session_data.json` - Session history and statistics
- `logs/` - Execution logs for analysis
### Export Just Patterns
If you only want to share the learned intelligence:
```bash
cp .claude_hooks/patterns/patterns.json team_patterns_$(date +%Y%m%d).json
```
## Share Patterns with Teammates
### Method 1: Direct File Sharing
1. **Export your patterns**:
```bash
cp .claude_hooks/patterns/patterns.json my_patterns_$(whoami).json
```
2. **Share the file** via your usual method (Slack, email, git repo, etc.)
3. **Teammates import** by copying to their patterns directory:
```bash
# Backup their existing patterns first
cp .claude_hooks/patterns/patterns.json .claude_hooks/patterns/patterns.backup.json
# Merge your patterns
cp received_patterns.json .claude_hooks/patterns/patterns.json
```
### Method 2: Git Repository Sharing
Create a shared patterns repository:
1. **In your team's patterns repo**:
```bash
mkdir team-claude-patterns
cd team-claude-patterns
git init
```
2. **Add patterns from team members**:
```bash
mkdir patterns
cp ~/.../teammate1_patterns.json patterns/
cp ~/.../teammate2_patterns.json patterns/
git add . && git commit -m "Initial team patterns"
```
3. **Team members sync** their patterns:
```bash
git clone git@company:team-claude-patterns.git
# Merge latest team patterns
python3 merge_team_patterns.py
```
### Method 3: Centralized Pattern Server
For larger teams, set up a simple pattern sharing server:
1. **Create a patterns API endpoint** (simple HTTP server):
```python
# patterns_server.py
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
@app.route('/patterns', methods=['GET'])
def get_patterns():
with open('team_patterns.json', 'r') as f:
return json.load(f)
@app.route('/patterns', methods=['POST'])
def update_patterns():
# Merge submitted patterns with team patterns
pass
```
2. **Team members sync** with the server:
```bash
curl https://patterns.company.com/patterns > .claude_hooks/patterns/patterns.json
```
## Merge Multiple Pattern Sets
When combining patterns from multiple sources:
1. **Create a merge script**:
```bash
cat > merge_patterns.py << 'EOF'
#!/usr/bin/env python3
import json
import sys
from datetime import datetime
def merge_patterns(base_file, new_file, output_file):
# Load both pattern sets
with open(base_file, 'r') as f:
base_patterns = json.load(f)
with open(new_file, 'r') as f:
new_patterns = json.load(f)
# Merge command patterns (keep highest confidence)
for cmd, pattern in new_patterns.get('command_patterns', {}).items():
if cmd not in base_patterns['command_patterns']:
base_patterns['command_patterns'][cmd] = pattern
else:
# Keep pattern with higher confidence
if pattern['confidence'] > base_patterns['command_patterns'][cmd]['confidence']:
base_patterns['command_patterns'][cmd] = pattern
# Merge other pattern types similarly...
# Save merged patterns
with open(output_file, 'w') as f:
json.dump(base_patterns, f, indent=2)
if __name__ == "__main__":
merge_patterns(sys.argv[1], sys.argv[2], sys.argv[3])
EOF
chmod +x merge_patterns.py
```
2. **Use the merge script**:
```bash
./merge_patterns.py .claude_hooks/patterns/patterns.json teammate_patterns.json merged_patterns.json
cp merged_patterns.json .claude_hooks/patterns/patterns.json
```
## Team Pattern Standards
### Establish Team Conventions
Create a team agreement on pattern sharing:
1. **Pattern Quality Standards**:
- Minimum confidence threshold (e.g., 0.8)
- Minimum evidence count (e.g., 5 samples)
- Maximum pattern age (e.g., 30 days)
2. **Sharing Frequency**:
- Weekly pattern sync meetings
- After major project milestones
- When discovering important new patterns
3. **Pattern Categories**:
- `production-safe` - Patterns safe for production environments
- `development-only` - Patterns specific to dev environments
- `experimental` - New patterns needing validation
### Filter Patterns for Sharing
Only share high-quality, relevant patterns:
```bash
cat > filter_patterns.py << 'EOF'
#!/usr/bin/env python3
import json
import sys
from datetime import datetime, timedelta
def filter_patterns(input_file, output_file, min_confidence=0.8, min_evidence=3):
with open(input_file, 'r') as f:
patterns = json.load(f)
filtered = {'command_patterns': {}, 'context_patterns': {}}
# Filter command patterns
for cmd, pattern in patterns.get('command_patterns', {}).items():
if (pattern['confidence'] >= min_confidence and
pattern['evidence_count'] >= min_evidence):
filtered['command_patterns'][cmd] = pattern
# Filter context patterns similarly...
with open(output_file, 'w') as f:
json.dump(filtered, f, indent=2)
print(f"Filtered {len(patterns.get('command_patterns', {}))} to {len(filtered['command_patterns'])} patterns")
if __name__ == "__main__":
filter_patterns(sys.argv[1], sys.argv[2])
EOF
chmod +x filter_patterns.py
```
Use it:
```bash
./filter_patterns.py .claude_hooks/patterns/patterns.json team_ready_patterns.json
```
## Environment-Specific Pattern Sets
Maintain different pattern sets for different environments:
```bash
# Directory structure
team_patterns/
├── production/
│ └── patterns.json # Only production-safe patterns
├── development/
│ └── patterns.json # Dev-specific patterns
├── staging/
│ └── patterns.json # Staging environment patterns
└── global/
└── patterns.json # Patterns safe everywhere
```
Load appropriate patterns:
```bash
# For production deployment
cp team_patterns/production/patterns.json .claude_hooks/patterns/
cp team_patterns/global/patterns.json .claude_hooks/patterns/global_patterns.json
# Merge them
./merge_patterns.py .claude_hooks/patterns/patterns.json .claude_hooks/patterns/global_patterns.json .claude_hooks/patterns/patterns.json
```
## Validate Shared Patterns
Before using patterns from others:
1. **Review dangerous patterns**:
```bash
jq '.command_patterns | to_entries[] | select(.value.confidence > 0.9 and .value.success_rate < 0.1)' patterns.json
```
2. **Check for environment conflicts**:
```bash
# Test patterns against your system
claude-hooks test-patterns shared_patterns.json
```
3. **Gradually adopt** new patterns rather than importing everything at once
## Monitor Pattern Effectiveness
Track how shared patterns perform:
```bash
# See which patterns are actually being used
tail -f .claude_hooks/logs/executions_$(date +%Y%m%d).jsonl | grep "pattern_matched"
# Check pattern success rates
claude-hooks patterns --stats
```
## Troubleshooting
**Patterns not taking effect**: Ensure patterns.json is valid JSON and in the right location
**Conflicts between patterns**: Use the merge script to combine patterns intelligently
**Too many false positives**: Increase confidence thresholds or add environment-specific filtering
**Patterns missing context**: Include the original environment info when sharing patterns