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

28
docs/BOOTSTRAP_PROMPT.md Normal file
View file

@ -0,0 +1,28 @@
# Claude Hooks Bootstrap Prompt
*Copy this prompt and paste it into a fresh Claude Code session to install Claude Hooks*
---
I want to install Claude Hooks - an intelligent system that will make you smarter and safer by learning from my environment and preventing common mistakes.
**What it does:**
- Learns which commands fail in my environment and suggests working alternatives
- Automatically backs up my work before context limits
- Blocks dangerous commands before they execute
- Maintains session history across Claude restarts
**Installation steps:**
1. `git clone https://github.com/anthropics/claude-hooks.git`
2. `cd claude-hooks`
3. `./scripts/install.sh`
4. `./scripts/test.sh`
**After installation:**
- Restart Claude Code to activate the hooks
- Try `claude-hooks status` to see it working
- Try `pip install requests` to see intelligent command suggestions
Please guide me through this installation step-by-step. Handle any errors that come up and make sure everything works. After installation, help me test it by trying some commands that commonly fail on different systems (like `pip` vs `pip3`, `python` vs `python3`) so I can see the intelligence in action.
The goal is to have a working Claude Hooks system that starts learning from my environment immediately.

99
docs/README.md Normal file
View file

@ -0,0 +1,99 @@
# Claude Code Hooks Documentation
This documentation is organized using the [Diátaxis framework](https://diataxis.fr/) to serve different types of user needs.
## 📚 Documentation Types
### 🎓 [Tutorial](tutorial/getting-started.md)
**Learning-oriented** - For newcomers who want to gain confidence and skill
Start here if you're new to Claude Hooks. We'll guide you through your first experience, showing you how the system works by watching it in action.
**Time commitment**: 30-45 minutes
**What you'll gain**: Confidence using Claude with intelligent assistance
---
### 🛠️ How-To Guides
**Task-oriented** - For competent users solving specific problems
Choose the guide that matches your current need:
- **[How to restore from backups](how-to/restore-backup.md)** - When your session crashed or you need to recover work
- **[How to customize command patterns](how-to/customize-patterns.md)** - Add your own dangerous command patterns or warnings
- **[How to share learned patterns](how-to/share-patterns.md)** - Share intelligence with your team or across projects
---
### 📖 Reference
**Information-oriented** - For looking up facts while working
Quick reference for when you need specific details:
- **[CLI Commands](reference/cli-commands.md)** - Complete command reference with options and examples
- **[Hook API](reference/hook-api.md)** - Technical specification for hook input/output
---
### 💡 Explanation
**Understanding-oriented** - For gaining deeper insight
Read when you want to understand the "why" behind Claude Hooks:
- **[Why Claude Code needs intelligent hooks](explanation/why-hooks.md)** - The problems that Claude Hooks solves
- **[Understanding the shadow learner](explanation/shadow-learner.md)** - How the system builds intelligence through observation
- **[The architecture of intelligent assistance](explanation/architecture.md)** - How the components work together to create emergent intelligence
---
## 🚀 Quick Start
**New to Claude Hooks?** → Start with the [Tutorial](tutorial/getting-started.md)
**Need to solve a problem?** → Check the [How-To Guides](#-how-to-guides)
**Looking up syntax or options?** → Use the [Reference](#-reference)
**Want to understand how it works?** → Read the [Explanations](#-explanation)
---
## 🤔 Which Type of Documentation Do I Need?
Use this decision tree:
```
Are you currently working on a task?
├─ Yes → Do you know what you want to accomplish?
│ ├─ Yes → How-To Guides 📋
│ └─ No → Reference 📖
└─ No → Are you learning or exploring?
├─ Learning → Tutorial 🎓
└─ Understanding → Explanation 💡
```
---
## 📁 Project Navigation
- **[Main README](../README.md)** - Project overview and installation
- **[DEMO](../DEMO.md)** - Quick feature showcase
- **[Architecture](../CLAUDE.md)** - Technical architecture details
---
## 🔍 Finding What You Need
**Can't find what you're looking for?**
1. **Search tip**: Use your browser's find function (Ctrl+F / Cmd+F) on the reference pages
2. **GitHub search**: Use the repository search to find specific terms across all documentation
3. **Start broader**: If a specific how-to doesn't exist, try the tutorial or explanation first
**Common documentation patterns**:
- All tutorials use "we" language and step-by-step instruction
- All how-to guides start with "when to use this guide"
- All reference pages are organized alphabetically and consistently formatted
- All explanations can be read away from the computer
This organization ensures you get the right type of help for your current situation.

183
docs/WEBSITE_COPY.md Normal file
View file

@ -0,0 +1,183 @@
# Claude Hooks Website Copy
## Hero Section
### Make Claude Code Smarter
**Claude Hooks adds intelligence, safety, and memory to your AI assistant**
Claude Code is powerful, but it forgets everything between sessions and repeats the same mistakes. Claude Hooks fixes that.
**Learns from your environment** - Remembers which commands work and suggests alternatives for ones that fail
🛡️ **Prevents dangerous operations** - Blocks risky commands before they execute
💾 **Never lose work** - Automatic backups before context limits
🔄 **Seamless continuity** - Pick up exactly where you left off
---
## Get Started in 60 Seconds
**Already using Claude Code?** Install Claude Hooks in one minute:
### Step 1: Start Claude Code
```bash
mkdir hookie && cd hookie && claude
```
### Step 2: Copy & Paste This Prompt
*Click to copy the installation prompt*
<div class="copy-prompt-box">
I want to install Claude Hooks - an intelligent system that will make you smarter and safer by learning from my environment and preventing common mistakes.
**What it does:**
- Learns which commands fail in my environment and suggests working alternatives
- Automatically backs up my work before context limits
- Blocks dangerous commands before they execute
- Maintains session history across Claude restarts
**Installation steps:**
1. `git clone https://github.com/anthropics/claude-hooks.git`
2. `cd claude-hooks`
3. `./scripts/install.sh`
4. `./scripts/test.sh`
**After installation:**
- Restart Claude Code to activate the hooks
- Try `claude-hooks status` to see it working
- Try `pip install requests` to see intelligent command suggestions
Please guide me through this installation step-by-step. Handle any errors that come up and make sure everything works. After installation, help me test it by trying some commands that commonly fail on different systems (like `pip` vs `pip3`, `python` vs `python3`) so I can see the intelligence in action.
The goal is to have a working Claude Hooks system that starts learning from my environment immediately.
[📋 Copy Prompt]
</div>
### Step 3: Watch Claude Install It For You
Claude will guide you through the installation and help you test it immediately.
**That's it!** You now have an AI assistant that gets smarter every time you use it.
---
## See It In Action
### Before Claude Hooks
```bash
$ pip install requests
bash: pip: command not found
```
*You repeat this mistake in every session*
### After Claude Hooks
```bash
$ pip install requests
⚠️ Warning: pip commands often fail (confidence: 88%)
💡 Suggestion: Use "pip3 install requests"
```
*Claude Hooks learned from your environment and prevents the mistake*
---
## Why Claude Hooks?
### The Problem
Claude Code is incredibly powerful, but it has fundamental limitations:
- **No memory** between sessions - repeats the same mistakes
- **No environmental awareness** - doesn't know what works on your system
- **Context limits** - loses everything when conversations get too long
- **No safety checks** - can suggest dangerous operations
### The Solution
Claude Hooks adds persistent intelligence that:
- **Learns from every command** you run and every mistake made
- **Builds environmental knowledge** specific to your system
- **Automatically backs up** your work before context limits
- **Validates commands** before execution to prevent problems
### The Result
An AI assistant that doesn't just help you code - it **gets better at helping you** over time.
---
## Features
### 🧠 Shadow Learning
- Observes every command execution and outcome
- Builds patterns of what works vs. what fails in your environment
- Suggests working alternatives when you try something that typically fails
- Gets more accurate over time as it learns your specific setup
### 🛡️ Intelligent Safety
- Blocks dangerous operations like `rm -rf /` before execution
- Warns about risky commands with explanations
- Learns what's safe vs. dangerous in your specific context
- Provides alternatives when blocking operations
### 💾 Smart Backups
- Monitors conversation context usage in real-time
- Automatically backs up your work before context limits
- Creates git commits with descriptive messages
- Generates session summaries for easy restoration
### 🔄 Session Continuity
- Maintains `LAST_SESSION.md` with complete session history
- Preserves `ACTIVE_TODOS.md` across Claude restarts
- Tracks all file modifications and command history
- Creates recovery guides when sessions are interrupted
---
## Documentation
**📚 [Complete Documentation](docs/README.md)** - Organized by what you need right now
**🎓 New to Claude Hooks?** → [30-minute tutorial](docs/tutorial/getting-started.md)
**🛠️ Need to solve a problem?** → [How-to guides](docs/README.md#-how-to-guides)
**📖 Looking up commands?** → [Reference documentation](docs/README.md#-reference)
**💡 Want to understand how it works?** → [Architecture explanations](docs/README.md#-explanation)
---
## Community
- **⭐ Star us on GitHub** - [github.com/anthropics/claude-hooks](https://github.com/anthropics/claude-hooks)
- **🐛 Report issues** - Help us make it better
- **💬 Discuss** - Share patterns and tips with other users
- **🤝 Contribute** - Add new features and improvements
---
## FAQ
**Q: Will this slow down Claude?**
A: No. Hooks add <50ms of processing time and often save time by preventing failures.
**Q: Is it safe?**
A: Yes. Hooks are designed to fail safely - if anything goes wrong, Claude continues working normally.
**Q: Do I need to configure anything?**
A: No. The system learns automatically from your actual usage patterns.
**Q: Can I share patterns with my team?**
A: Yes. You can export and share learned patterns across team members.
**Q: What if Claude Hooks breaks?**
A: Claude Code continues working normally. Hooks enhance but never interfere with core functionality.
---
## Get Started Now
Ready to make Claude Code smarter? Copy the prompt above and paste it into Claude Code.
**Installation takes 60 seconds. The benefits last forever.**
[📋 Copy Installation Prompt](#step-2-copy--paste-this-prompt)
---
*Claude Hooks is open source and MIT licensed. Built by developers, for developers.*

View file

@ -0,0 +1,376 @@
# The Architecture of Intelligent Assistance
*How Claude Hooks creates intelligence through careful separation of concerns*
## The Core Insight
Claude Hooks represents a particular approach to enhancing AI systems: rather than modifying the AI itself, we create an intelligent wrapper that observes, learns, and intervenes at strategic points. This architectural choice has profound implications for how the system works and why it's effective.
## The Layered Intelligence Model
Think of Claude Hooks as creating multiple layers of intelligence, each operating at different timescales and with different responsibilities:
### Layer 1: Claude Code (Real-time Intelligence)
- **Timescale**: Milliseconds to seconds
- **Scope**: Single tool execution
- **Knowledge**: General AI training knowledge
- **Responsibility**: Creative problem-solving, code generation, understanding user intent
### Layer 2: Hook Validation (Reactive Intelligence)
- **Timescale**: Milliseconds
- **Scope**: Single command validation
- **Knowledge**: Static safety rules + learned patterns
- **Responsibility**: Immediate safety checks, failure prevention
### Layer 3: Shadow Learning (Adaptive Intelligence)
- **Timescale**: Hours to weeks
- **Scope**: Pattern recognition across many interactions
- **Knowledge**: Environmental adaptation and workflow patterns
- **Responsibility**: Building intelligence through observation
### Layer 4: Session Management (Continuity Intelligence)
- **Timescale**: Sessions to months
- **Scope**: Long-term context and progress tracking
- **Knowledge**: Project history and developer workflows
- **Responsibility**: Maintaining context across time boundaries
This layered approach means each component can focus on what it does best, while the combination provides capabilities that none could achieve alone.
## The Event-Driven Architecture
Claude Hooks works by intercepting specific events in Claude's workflow and responding appropriately. This event-driven design is crucial to its effectiveness.
### The Hook Points
```mermaid
graph TD
A[User submits prompt] --> B[UserPromptSubmit Hook]
B --> C[Claude processes prompt]
C --> D[Claude chooses tool]
D --> E[PreToolUse Hook]
E --> F{Allow tool?}
F -->|Yes| G[Tool executes]
F -->|No| H[Block execution]
G --> I[PostToolUse Hook]
H --> I
I --> J[Claude continues]
J --> K[Claude finishes]
K --> L[Stop Hook]
```
Each hook point serves a specific architectural purpose:
**UserPromptSubmit**: *Context Awareness*
- Monitors conversation growth
- Triggers preventive actions (backups)
- Updates session tracking
**PreToolUse**: *Proactive Protection*
- Last chance to prevent problematic operations
- Applies learned patterns to suggest alternatives
- Enforces safety constraints
**PostToolUse**: *Learning and Adaptation*
- Observes outcomes for pattern learning
- Updates intelligence databases
- Tracks session progress
**Stop**: *Continuity and Cleanup*
- Preserves session state for future restoration
- Finalizes learning updates
- Prepares continuation documentation
### Why This Event Model Works
The event-driven approach provides several architectural advantages:
**Separation of Concerns**: Each hook has a single, clear responsibility
**Composability**: Hooks can be developed and deployed independently
**Resilience**: Failure in one hook doesn't affect others or Claude's core functionality
**Extensibility**: New capabilities can be added by creating new hooks
## The Intelligence Flow
Understanding how intelligence flows through the system reveals why the architecture is so effective.
### Information Gathering
```
User Interaction
Hook Observation
Pattern Extraction
Confidence Scoring
Knowledge Storage
```
Each user interaction generates multiple data points:
- What Claude attempted to do
- Whether it succeeded or failed
- What the error conditions were
- What alternatives might have worked
- What the user's reaction was
### Intelligence Application
```
New Situation
Pattern Matching
Confidence Assessment
Decision Making
User Guidance
```
When a new situation arises, the system:
- Compares it to known patterns
- Calculates confidence in predictions
- Decides whether to intervene
- Provides guidance to prevent problems
### The Feedback Loop
The architecture creates a continuous improvement cycle:
```
Experience → Learning → Intelligence → Better Experience → More Learning
```
This feedback loop is what transforms Claude from a stateless assistant into an adaptive partner that gets better over time.
## Component Architecture
### The Shadow Learner: Observer Pattern
The shadow learner implements a classic observer pattern, but with sophisticated intelligence:
```python
class ShadowLearner:
def observe(self, execution: ToolExecution):
# Extract patterns from execution
patterns = self.extract_patterns(execution)
# Update confidence scores
self.update_confidence(patterns)
# Store new knowledge
self.knowledge_base.update(patterns)
def predict(self, proposed_action):
# Match against known patterns
similar_patterns = self.find_similar(proposed_action)
# Calculate confidence
confidence = self.calculate_confidence(similar_patterns)
# Return prediction
return Prediction(confidence, similar_patterns)
```
The key insight is that the learner doesn't just record what happened - it actively builds predictive models that can guide future decisions.
### Context Monitor: Resource Management Pattern
The context monitor implements a resource management pattern, treating Claude's context as a finite resource that must be carefully managed:
```python
class ContextMonitor:
def estimate_usage(self):
# Multiple estimation strategies
estimates = [
self.token_based_estimate(),
self.activity_based_estimate(),
self.time_based_estimate()
]
# Weighted combination
return self.combine_estimates(estimates)
def should_backup(self):
usage = self.estimate_usage()
# Adaptive thresholds based on session complexity
threshold = self.calculate_threshold()
return usage > threshold
```
This architectural approach means the system can make intelligent decisions about when to intervene, rather than using simple rule-based triggers.
### Backup Manager: Strategy Pattern
The backup manager implements a strategy pattern, using different backup approaches based on circumstances:
```python
class BackupManager:
def __init__(self):
self.strategies = [
GitBackupStrategy(),
FilesystemBackupStrategy(),
EmergencyBackupStrategy()
]
def execute_backup(self, context):
for strategy in self.strategies:
try:
result = strategy.backup(context)
if result.success:
return result
except Exception:
continue # Try next strategy
return self.emergency_backup(context)
```
This ensures that backups almost always succeed, gracefully degrading to simpler approaches when sophisticated methods fail.
## Data Flow Architecture
### The Knowledge Pipeline
Data flows through the system in a carefully designed pipeline:
```
Raw Events → Preprocessing → Pattern Extraction → Confidence Scoring → Storage → Retrieval → Application
```
**Preprocessing**: Clean and normalize data
- Remove sensitive information
- Standardize formats
- Extract relevant features
**Pattern Extraction**: Identify meaningful patterns
- Command failure patterns
- Workflow sequences
- Environmental constraints
**Confidence Scoring**: Quantify reliability
- Evidence strength
- Recency weighting
- Context consistency
**Storage**: Persist knowledge efficiently
- Optimized for fast retrieval
- Handles concurrent access
- Provides data integrity
**Retrieval**: Find relevant patterns quickly
- Fuzzy matching algorithms
- Context-aware filtering
- Performance optimization
**Application**: Apply knowledge effectively
- Real-time decision making
- User-friendly presentation
- Graceful degradation
### State Management
The system maintains several types of state, each with different persistence requirements:
**Session State**: Current conversation context
- Persisted every few operations
- Restored on session restart
- Includes active todos and progress
**Learning State**: Accumulated knowledge
- Persisted after pattern updates
- Shared across sessions
- Includes confidence scores and evidence
**Configuration State**: User preferences and settings
- Persisted on changes
- Controls system behavior
- Includes thresholds and preferences
**Backup State**: Historical snapshots
- Persisted on backup creation
- Enables recovery operations
- Includes metadata and indexing
## Why This Architecture Enables Intelligence
### Emergent Intelligence
The architecture creates intelligence through emergence rather than explicit programming. No single component is "intelligent" in isolation, but their interaction creates sophisticated behavior:
- **Pattern recognition** emerges from observation + storage + matching
- **Predictive guidance** emerges from patterns + confidence + decision logic
- **Adaptive behavior** emerges from feedback loops + learning + application
### Scalable Learning
The separation of concerns allows each component to scale independently:
- **Pattern storage** can grow to millions of patterns without affecting hook performance
- **Learning algorithms** can become more sophisticated without changing the hook interface
- **Backup strategies** can be enhanced without modifying the learning system
### Robust Operation
The architecture provides multiple levels of resilience:
- **Component isolation**: Failure in one component doesn't cascade
- **Graceful degradation**: System provides value even when components fail
- **Recovery mechanisms**: Multiple backup strategies ensure data preservation
- **Fail-safe defaults**: Unknown situations default to allowing operations
## Architectural Trade-offs
### What We Gained
**Modularity**: Each component can be developed, tested, and deployed independently
**Resilience**: Multiple failure modes are handled gracefully
**Extensibility**: New capabilities can be added without changing existing components
**Performance**: Event-driven design minimizes overhead
**Intelligence**: Learning improves system effectiveness over time
### What We Sacrificed
**Simplicity**: More complex than a simple rule-based system
**Immediacy**: Learning requires time to become effective
**Predictability**: Adaptive behavior can be harder to debug
**Resource usage**: Multiple components require more memory and storage
### Why the Trade-offs Make Sense
For an AI assistance system, the trade-offs strongly favor the intelligent architecture:
- **Complexity is hidden** from users who just see better suggestions
- **Learning delay is acceptable** because the system provides immediate safety benefits
- **Adaptive behavior is desired** because it personalizes the experience
- **Resource usage is reasonable** for the intelligence gained
## Future Architectural Possibilities
The current architecture provides a foundation for even more sophisticated capabilities:
### Distributed Intelligence
Multiple Claude installations could share learned patterns, creating collective intelligence that benefits everyone.
### Multi-Modal Learning
The architecture could be extended to learn from additional signals like execution time, resource usage, or user satisfaction.
### Predictive Capabilities
Rather than just reacting to patterns, the system could predict when certain types of failures are likely and proactively suggest preventive measures.
### Collaborative Intelligence
Different AI assistants could use the same architectural pattern to build their own environmental intelligence, creating a ecosystem of adaptive AI tools.
## The Deeper Principle
At its core, Claude Hooks demonstrates an important principle for AI system design: **intelligence emerges from the careful orchestration of simple, focused components rather than from building ever-more-complex monolithic systems**.
This architectural approach - observation, learning, pattern matching, and intelligent intervention - provides a blueprint for how AI systems can become genuinely adaptive to real-world environments while maintaining reliability, extensibility, and user trust.
The result is not just a more capable AI assistant, but a demonstration of how we can build AI systems that genuinely learn and adapt while remaining comprehensible, controllable, and reliable.

View file

@ -0,0 +1,225 @@
# Understanding the Shadow Learner
*How Claude Hooks builds intelligence through observation*
## What Is Shadow Learning?
The term "shadow learner" describes a system that observes and learns from another system's behavior without directly controlling it. In Claude Hooks, the shadow learner watches every command Claude executes, every success and failure, and gradually builds intelligence about what works in your environment.
Think of it like an experienced colleague watching over your shoulder - not interrupting your work, but quietly noting patterns and ready to offer advice when you're about to repeat a known mistake.
## Why "Shadow" Learning?
The name captures several key characteristics of how this learning system operates:
### It Operates in the Background
Like a shadow, the learning system is always present but rarely noticed. You don't actively teach it or configure it - it simply observes your normal work and extracts patterns.
### It Follows Your Actual Behavior
Just as a shadow faithfully follows your movements, the shadow learner learns from what you actually do, not what you say you do or what you intend to do. This makes the intelligence remarkably accurate because it's based on real behavior patterns.
### It Doesn't Interfere with the Primary System
A shadow doesn't change the object casting it - similarly, the shadow learner observes Claude's behavior without modifying Claude itself. This separation is crucial for system reliability and ensures that learning failures never break core functionality.
### It Provides Insight from a Different Perspective
Your shadow reveals aspects of your movement that you might not notice directly. Similarly, the shadow learner can identify patterns in your command usage that might not be obvious - like the fact that certain commands consistently fail in specific contexts.
## How Shadow Learning Differs from Traditional ML
Most machine learning systems require explicit training phases, labeled datasets, and careful feature engineering. Shadow learning operates very differently:
### Continuous Learning
Instead of batch training, shadow learning happens continuously as you work. Every command executed adds to the knowledge base. There's no distinction between "training time" and "inference time" - the system is always both learning and applying its knowledge.
### Self-Labeling
Traditional supervised learning requires humans to label data as "good" or "bad." Shadow learning uses the natural outcomes of commands as labels - if a command succeeds, that's a positive example; if it fails, that's a negative example.
### Context-Aware Patterns
Rather than learning general rules, shadow learning captures context-dependent patterns. It doesn't just learn that "pip fails" - it learns that "pip fails on systems that use python3" or "pip fails in virtualenvs without system packages."
### Incremental Intelligence
Traditional ML models are trained once and deployed. Shadow learners improve incrementally with each interaction, becoming more accurate and more personalized over time.
## The Learning Process
### Pattern Recognition
The shadow learner identifies several types of patterns:
**Command Patterns**: Which commands tend to succeed or fail in your environment
- `pip install` fails 90% of the time → suggest `pip3 install`
- `python script.py` fails on your system → suggest `python3 script.py`
- `npm install` without `--save` in certain projects → warn about dependency tracking
**Sequence Patterns**: Common workflows and command chains
- `git add . && git commit` often follows file edits
- `npm install` typically precedes `npm test`
- Reading config files often precedes configuration changes
**Context Patterns**: Environmental factors that affect command success
- Commands fail differently in Docker containers vs. native environments
- Certain operations require different approaches based on project type
- Time-of-day patterns (builds failing during peak hours due to resource contention)
**Error Patterns**: Common failure modes and their solutions
- "Permission denied" errors often require sudo or chmod
- "Command not found" errors have specific alternative commands
- Network timeouts suggest retry strategies
### Confidence Building
The shadow learner doesn't just record patterns - it builds confidence scores based on:
**Evidence Strength**: How many times has this pattern been observed?
- A pattern seen once has low confidence
- A pattern seen 20 times with consistent results has high confidence
**Recency**: How recently has this pattern been confirmed?
- Recent observations carry more weight
- Old patterns decay in confidence over time
**Context Consistency**: Does this pattern hold across different contexts?
- Patterns that work in multiple projects are more reliable
- Context-specific patterns are marked as such
**Success Rate**: What percentage of the time does this pattern hold?
- Patterns with 95% success rate are treated differently than 60% patterns
- Confidence reflects the reliability of the pattern
## Types of Intelligence Developed
### Environmental Intelligence
The shadow learner develops deep knowledge about your specific development environment:
- Which Python version is actually available
- How package managers are configured
- What development tools are installed and working
- How permissions are set up
- What network restrictions exist
This environmental map becomes incredibly detailed over time, capturing nuances that would be impossible to document manually.
### Workflow Intelligence
By observing command sequences, the shadow learner understands your common workflows:
- How you typically start new projects
- Your testing and debugging patterns
- How you deploy and release code
- Your preferred tools for different tasks
This workflow intelligence enables predictive suggestions - when you start a familiar pattern, the system can anticipate what you'll need next.
### Error Intelligence
Perhaps most valuably, the shadow learner becomes an expert on what goes wrong in your environment and how to fix it:
- Common failure modes for different types of commands
- Environmental factors that cause failures
- Which alternative approaches work when the obvious approach fails
- How to recover from different types of errors
This error intelligence is what makes the system feel genuinely helpful - it prevents you from repeating mistakes and guides you toward solutions that actually work.
### Preference Intelligence
Over time, the shadow learner also learns your preferences and working style:
- Which tools you prefer for different tasks
- How you like to structure projects
- Your tolerance for different types of warnings
- When you want suggestions vs. when you want to be left alone
## The Feedback Loop
Shadow learning creates a positive feedback loop that makes Claude increasingly effective:
1. **Claude suggests a command** based on its general knowledge
2. **Shadow learner checks** if this type of command typically works in your environment
3. **If there's a known issue**, the shadow learner suggests an alternative
4. **The command is executed** and the outcome is observed
5. **The pattern database is updated** with this new evidence
6. **Future suggestions become more accurate** based on accumulated knowledge
This loop means that Claude doesn't just maintain its effectiveness over time - it actually gets better at working in your specific environment.
## Learning from Collective Intelligence
While each shadow learner is personalized to your environment, the architecture also supports sharing learned patterns across teams or projects:
### Team Learning
Teams can share pattern databases, allowing new team members to benefit from the collective experience of their colleagues. This is particularly valuable for learning environment-specific knowledge that might take months to accumulate individually.
### Project-Specific Learning
Different projects often have different constraints and conventions. The shadow learner can maintain separate pattern sets for different projects, switching context automatically based on the current working directory.
### Community Learning
In principle, anonymized patterns could be shared across the broader community, creating a collective intelligence about what works and what doesn't across different development environments.
## Limitations and Challenges
### The Cold Start Problem
A new shadow learner has no knowledge and must learn everything from scratch. This means the system provides little value initially and only becomes helpful after observing many interactions.
### Context Sensitivity
Patterns that work in one context might not apply in another. The shadow learner must be sophisticated about when to apply learned patterns and when to defer to Claude's general knowledge.
### Overfitting Risk
If the learning system becomes too specialized to past behavior, it might prevent discovery of better approaches. The system needs to balance exploitation of known patterns with exploration of new possibilities.
### Privacy and Security
Learning from all command executions means the shadow learner inevitably observes sensitive information. Careful design is needed to ensure this intelligence doesn't create security vulnerabilities.
## The Future of Shadow Learning
The shadow learning approach points toward several interesting possibilities:
### Multi-Modal Learning
Future versions might observe not just command outcomes, but also factors like execution time, resource usage, and even developer satisfaction signals.
### Predictive Intelligence
Rather than just reacting to patterns, shadow learners might predict when certain types of failures are likely and proactively suggest preventive measures.
### Explanatory Intelligence
Advanced shadow learners might not just suggest alternatives, but explain why certain approaches are recommended based on accumulated evidence.
### Collaborative Intelligence
Shadow learners might communicate with each other, sharing insights and learning from each other's observations to build more comprehensive intelligence.
## Why This Approach Works
Shadow learning succeeds because it addresses fundamental limitations in how AI assistants interact with real-world environments:
**It bridges the gap** between general AI knowledge and specific environmental reality.
**It provides continuity** across sessions, accumulating wisdom over time.
**It learns from actual behavior** rather than intended or theoretical behavior.
**It operates safely** without interfering with core AI functionality.
**It personalizes intelligence** to your specific context and needs.
In essence, shadow learning makes AI assistants genuinely adaptive - capable of learning not just how to work in general, but how to work effectively in your particular corner of the world.
This represents a crucial step toward AI systems that don't just provide general intelligence, but develop specific expertise through experience - much like human experts do.

View file

@ -0,0 +1,121 @@
# Why Claude Code Needs Intelligent Hooks
*Understanding the problem that Claude Hooks solves*
## The Context Problem
Claude Code represents a new paradigm in software development - an AI assistant that can read, write, and execute code with human-level understanding. But this power creates unique challenges that traditional development tools weren't designed to handle.
### The Disappearing Context
Traditional IDEs maintain state through your project files, git history, and your memory. But Claude operates within conversation contexts that have hard limits. When you hit that limit, your entire working context - the problems you were solving, the patterns you discovered, the mistakes you made and learned from - simply disappears.
This creates a jarring experience: you're deep in a debugging session, making progress, building understanding, and suddenly you have to start over with a fresh Claude session that knows nothing about your journey.
### The Repetitive Failure Problem
Human developers naturally learn from mistakes. Try a command that fails, remember not to do it again, adapt. But each new Claude session starts with no memory of previous failures. You find yourself watching Claude repeat the same mistakes - `pip` instead of `pip3`, `python` instead of `python3`, dangerous operations that you know will fail.
This isn't Claude's fault - it's a fundamental limitation of the stateless conversation model. But it creates frustration and inefficiency.
### The Trust Problem
When you're working with an AI assistant that can execute powerful commands, you need confidence that it won't accidentally destroy your work. But without memory of past failures and without understanding of your specific environment, Claude can't provide that confidence.
You find yourself constantly second-guessing: "Will this command work on my system?" "Have we tried this before?" "What if this destroys my work?"
## Why Hooks Are the Solution
The hook architecture provides the missing memory and intelligence that Claude Code needs to work reliably in the real world.
### Hooks as Claude's Memory
Think of hooks as giving Claude a persistent memory that survives across sessions. Every command tried, every failure encountered, every successful pattern discovered - all of this becomes part of Claude's accumulated knowledge about your environment.
This isn't just logging - it's active intelligence. When Claude suggests a command, the hooks can say "that failed 5 times before, try this instead." When you start a new session, the hooks can remind Claude what you were working on and what approaches you'd already tried.
### Hooks as Safety Net
Hooks provide a safety layer that operates independently of Claude's decision-making. Even if Claude suggests something dangerous, the hooks can catch it. Even if you accidentally approve a destructive command, the hooks can block it.
This creates a collaborative safety model: Claude provides the intelligence and creativity, while hooks provide the guardrails and institutional memory.
### Hooks as Learning System
Perhaps most importantly, hooks transform Claude from a stateless assistant into a learning partner. Every interaction teaches the system something about your environment, your preferences, your common tasks.
Over time, this creates an increasingly intelligent assistant that not only knows how to code, but knows how to code effectively *in your specific environment*.
## The Shadow Learner Concept
The term "shadow learner" captures something important about how this intelligence operates. It's not the primary AI (Claude) making decisions, but a secondary system that observes, learns, and provides guidance.
This shadow intelligence operates at a different timescale than Claude:
- Claude operates within single conversations
- The shadow learner operates across weeks and months of usage
- Claude sees individual problems
- The shadow learner sees patterns across problems
### Why Not Just Better Training?
You might wonder: why not just train Claude to be better at avoiding these problems? Why do we need a separate learning system?
The answer lies in the fundamental difference between general intelligence and environmental adaptation:
**General intelligence** (what Claude provides) is knowledge that applies across all contexts - how to write Python, how to use git, how to debug problems.
**Environmental adaptation** (what shadow learning provides) is knowledge specific to your setup - which commands work on your system, what your typical workflows are, what mistakes you commonly make.
No amount of general training can capture the infinite variety of individual development environments, personal preferences, and project-specific constraints.
## The Philosophy of Intelligent Assistance
Claude Hooks embodies a particular philosophy about how AI assistants should work:
### Augmentation, Not Replacement
The hooks don't replace Claude's intelligence - they augment it with environmental awareness and institutional memory. Claude remains the creative, problem-solving intelligence, while hooks provide the accumulated wisdom of experience.
### Learning Through Observation
Rather than requiring explicit configuration or training, the system learns by observing your actual work patterns. This creates intelligence that's perfectly tailored to your reality, not some theoretical ideal.
### Fail-Safe by Design
Every component is designed to fail safely. If hooks break, Claude continues working. If learning fails, operations still proceed. If backups fail, work continues but with warnings.
This reflects a crucial insight: intelligence systems should enhance reliability, not create new points of failure.
### Transparency and Control
You can always see what the system has learned (`claude-hooks patterns`), what it's doing (`claude-hooks status`), and override its decisions. The intelligence is helpful but never hidden or controlling.
## Why This Matters for the Future
Claude Hooks represents more than just a useful tool - it's a preview of how AI systems will need to evolve to work effectively in real-world environments.
### The Personalization Problem
As AI assistants become more powerful, the need for personalization becomes critical. A general-purpose AI is incredibly useful, but an AI that understands your specific context, preferences, and environment is transformative.
### The Continuity Problem
Current AI interactions are episodic - each conversation starts fresh. But real work is continuous, building on previous efforts, learning from past mistakes, refining approaches over time. AI systems need mechanisms for bridging these episodes.
### The Trust Problem
As we delegate more critical tasks to AI systems, we need confidence in their reliability. This confidence comes not just from the AI's general capabilities, but from its demonstrated competence in our specific context.
Claude Hooks shows how these problems can be solved through intelligent observation, learning, and memory systems that operate alongside, rather than within, the primary AI.
## The Bigger Picture
In a sense, Claude Hooks is solving the same problem that human developers have always faced: how to accumulate and apply knowledge across many working sessions. Experienced developers build up mental models of their tools, remember which approaches work, develop habits that avoid common pitfalls.
What's new is that we're now building these same capabilities for AI assistants - creating systems that can accumulate experience, learn from mistakes, and provide increasingly intelligent guidance.
This points toward a future where AI assistants don't just provide general intelligence, but develop genuine expertise in your specific domain, environment, and working style. They become not just tools, but experienced partners in your work.
The hooks architecture provides a blueprint for how this kind of intelligent assistance can be built: through observation, learning, memory, and gradual accumulation of environmental wisdom.
In this view, Claude Hooks isn't just a utility for managing context and preventing errors - it's a step toward AI assistants that truly understand not just how to work, but how to work well in your world.

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

View file

@ -0,0 +1,394 @@
# CLI Commands Reference
## claude-hooks
Main command-line interface for managing Claude Hooks.
### Synopsis
```
claude-hooks <command> [options]
```
### Commands
#### status
Display current session status and metrics.
**Usage**: `claude-hooks status`
**Output**:
- Session ID and duration
- Context usage percentage
- Tool execution count
- Files modified count
- Commands executed count
- Backup recommendation status
**Exit codes**:
- `0` - Success
- `1` - Error accessing session data
---
#### list-backups
List all available backups with metadata.
**Usage**: `claude-hooks list-backups`
**Output format**:
```
🗂️ backup_YYYYMMDD_HHMMSS
📅 ISO timestamp
📝 backup reason
```
**Exit codes**:
- `0` - Success, backups listed
- `0` - Success, no backups found
---
#### patterns
Display learned command and context patterns.
**Usage**: `claude-hooks patterns [--limit N]`
**Options**:
- `--limit N` - Show only top N patterns (default: 10)
**Output sections**:
- Command Patterns: Command name, confidence %, evidence count, success rate %
- Context Patterns: Error type, confidence %, evidence count
**Exit codes**:
- `0` - Success
- `1` - Error accessing patterns database
---
#### clear-patterns
Remove all learned patterns from the database.
**Usage**: `claude-hooks clear-patterns`
**Interactive confirmation**: Prompts for `y/N` confirmation before deletion.
**Exit codes**:
- `0` - Success, patterns cleared
- `0` - Success, operation cancelled by user
- `1` - Error accessing patterns database
---
#### export
Export all hook data to a directory.
**Usage**: `claude-hooks export [directory]`
**Arguments**:
- `directory` - Target directory (default: `claude_hooks_export`)
**Creates**:
- `session_data.json` - Current session state and history
- `patterns.json` - All learned patterns
- `logs/` - Copy of all log files
**Exit codes**:
- `0` - Success
- `1` - Export failed
- `2` - Permission denied
---
## Hook Scripts
### context_monitor.py
**Type**: UserPromptSubmit hook
**Purpose**: Monitor context usage and trigger backups
**Input format**:
```json
{
"prompt": "string"
}
```
**Output format**:
```json
{
"allow": true,
"message": "Context usage: X.X%"
}
```
**Exit codes**:
- `0` - Always (non-blocking hook)
---
### command_validator.py
**Type**: PreToolUse[Bash] hook
**Purpose**: Validate bash commands for safety and success probability
**Input format**:
```json
{
"tool": "Bash",
"parameters": {
"command": "string"
}
}
```
**Output format**:
```json
{
"allow": boolean,
"message": "string"
}
```
**Exit codes**:
- `0` - Command allowed
- `1` - Command blocked
**Messages**:
- `⛔ Command blocked: <reason>` - Dangerous pattern detected
- `⚠️ <warning>` - Suspicious pattern detected
- `🚨 <warning>` - High-confidence failure prediction
- `💡 Suggestion: <alternative>` - Alternative command suggested
---
### session_logger.py
**Type**: PostToolUse[*] hook
**Purpose**: Log tool executions and update learning data
**Input format**:
```json
{
"tool": "string",
"parameters": {},
"success": boolean,
"error": "string",
"execution_time": number
}
```
**Output format**:
```json
{
"allow": true,
"message": "Logged <tool> execution"
}
```
**Exit codes**:
- `0` - Always (post-execution hook)
---
### session_finalizer.py
**Type**: Stop hook
**Purpose**: Create session documentation and save state
**Input format**:
```json
{}
```
**Output format**:
```json
{
"allow": true,
"message": "Session finalized. Modified X files, used Y tools."
}
```
**Exit codes**:
- `0` - Always (cleanup hook)
**Side effects**:
- Creates/updates `LAST_SESSION.md`
- Creates/updates `ACTIVE_TODOS.md`
- May create `RECOVERY_GUIDE.md`
- Saves patterns database
- Logs session completion
---
## Configuration Files
### config/hooks.json.template
Template for Claude Code hooks configuration.
**Template variables**:
- `{{INSTALL_PATH}}` - Absolute path to claude-hooks installation
**Structure**:
```json
{
"hooks": {
"UserPromptSubmit": "string",
"PreToolUse": {
"Bash": "string"
},
"PostToolUse": {
"*": "string"
},
"Stop": "string"
}
}
```
---
### config/settings.json
Configuration parameters for hook behavior.
**Schema**:
```json
{
"context_monitor": {
"backup_threshold": number, // 0.0-1.0, default 0.85
"emergency_threshold": number, // 0.0-1.0, default 0.95
"max_context_tokens": number, // default 200000
"tokens_per_char": number, // default 0.25
"tool_overhead": number, // default 200
"system_overhead": number // default 500
},
"backup_manager": {
"max_backups": number, // default 10
"backup_on_critical_ops": boolean, // default true
"git_enabled": boolean, // default true
"filesystem_backup_enabled": boolean // default true
},
"shadow_learner": {
"max_patterns": number, // default 10000
"confidence_threshold": number, // 0.0-1.0, default 0.8
"evidence_threshold": number, // default 5
"cache_ttl_seconds": number, // default 300
"learning_enabled": boolean // default true
},
"security": {
"dangerous_commands_blocked": boolean, // default true
"suspicious_commands_warned": boolean, // default true
"path_traversal_protection": boolean, // default true
"system_files_protection": boolean // default true
},
"performance": {
"rate_limit_ms": number, // default 100
"max_hook_execution_time": number, // milliseconds, default 5000
"async_logging": boolean, // default true
"cache_predictions": boolean // default true
},
"logging": {
"log_level": "DEBUG|INFO|WARNING|ERROR", // default "INFO"
"log_executions": boolean, // default true
"log_retention_days": number, // default 7
"detailed_errors": boolean // default false
}
}
```
---
## File Locations
### Runtime Data
- `.claude_hooks/` - Main data directory
- `backups/` - Session backup files
- `logs/` - Execution and error logs
- `patterns/` - Learned patterns database
- `session_state.json` - Current session state
### Generated Files
- `LAST_SESSION.md` - Session summary for continuity
- `ACTIVE_TODOS.md` - Persistent task list
- `RECOVERY_GUIDE.md` - Created when session interrupted
### Log Files
- `.claude_hooks/logs/executions_YYYYMMDD.jsonl` - Daily execution logs
- `.claude_hooks/logs/session_completions.jsonl` - Session completion events
- `.claude_hooks/backups/backup.log` - Backup operation log
---
## Data Formats
### Pattern Database Schema
```json
{
"command_patterns": {
"command_name": {
"pattern_id": "string",
"pattern_type": "command_execution",
"trigger": {"command": "string"},
"prediction": {
"success_count": number,
"failure_count": number,
"common_errors": ["string"]
},
"confidence": number,
"evidence_count": number,
"last_seen": "ISO timestamp",
"success_rate": number
}
},
"context_patterns": {
"pattern_id": {
"pattern_type": "context_error",
"trigger": {
"tool": "string",
"error_type": "string"
},
"prediction": {
"likely_error": "string",
"suggestions": ["string"]
},
"confidence": number,
"evidence_count": number,
"last_seen": "ISO timestamp"
}
}
}
```
### Session State Schema
```json
{
"session_id": "string",
"start_time": "ISO timestamp",
"last_activity": "ISO timestamp",
"modified_files": ["string"],
"commands_executed": [
{
"command": "string",
"timestamp": "ISO timestamp"
}
],
"tool_usage": {
"tool_name": number
},
"backup_history": [
{
"backup_id": "string",
"timestamp": "ISO timestamp",
"reason": "string",
"success": boolean
}
]
}
```

382
docs/reference/hook-api.md Normal file
View file

@ -0,0 +1,382 @@
# Hook API Reference
## Hook Input/Output Protocol
All hooks communicate with Claude Code via JSON over stdin/stdout.
### Input Format
Hooks receive a JSON object via stdin containing:
```json
{
"tool": "string", // Tool being used (e.g., "Bash", "Read", "Edit")
"parameters": {}, // Tool-specific parameters
"success": boolean, // Tool execution result (PostToolUse only)
"error": "string", // Error message if failed (PostToolUse only)
"execution_time": number, // Execution time in seconds (PostToolUse only)
"prompt": "string" // User prompt text (UserPromptSubmit only)
}
```
### Output Format
Hooks must output a JSON response to stdout:
```json
{
"allow": boolean, // Required: true to allow, false to block
"message": "string" // Optional: message to display to user
}
```
### Exit Codes
- `0` - Allow operation (success)
- `1` - Block operation (for PreToolUse hooks only)
- Any other code - Treated as hook error, operation allowed
---
## Hook Types
### UserPromptSubmit
**Trigger**: When user submits a prompt to Claude
**Purpose**: Monitor session state, trigger backups
**Input**:
```json
{
"prompt": "Create a new Python script that..."
}
```
**Expected behavior**:
- Always return `"allow": true`
- Update context usage estimates
- Trigger backups if thresholds exceeded
- Update session tracking
**Example response**:
```json
{
"allow": true,
"message": "Context usage: 67%"
}
```
---
### PreToolUse
**Trigger**: Before Claude executes any tool
**Purpose**: Validate operations, block dangerous commands
#### PreToolUse[Bash]
**Input**:
```json
{
"tool": "Bash",
"parameters": {
"command": "rm -rf /tmp/myfiles",
"description": "Clean up temporary files"
}
}
```
**Expected behavior**:
- Return `"allow": false` and exit code 1 to block dangerous commands
- Return `"allow": true` with warnings for suspicious commands
- Check against learned failure patterns
- Suggest alternatives when blocking
**Block response**:
```json
{
"allow": false,
"message": "⛔ Command blocked: Dangerous pattern detected"
}
```
**Warning response**:
```json
{
"allow": true,
"message": "⚠️ Command may fail (confidence: 85%)\n💡 Suggestion: Use 'python3' instead of 'python'"
}
```
#### PreToolUse[Edit]
**Input**:
```json
{
"tool": "Edit",
"parameters": {
"file_path": "/etc/passwd",
"old_string": "user:x:1000",
"new_string": "user:x:0"
}
}
```
**Expected behavior**:
- Validate file paths for security
- Check for system file modifications
- Prevent path traversal attacks
#### PreToolUse[Write]
**Input**:
```json
{
"tool": "Write",
"parameters": {
"file_path": "../../sensitive_file.txt",
"content": "malicious content"
}
}
```
**Expected behavior**:
- Validate file paths
- Check file extensions
- Detect potential security issues
---
### PostToolUse
**Trigger**: After Claude executes any tool
**Purpose**: Learn from outcomes, log activity
**Input**:
```json
{
"tool": "Bash",
"parameters": {
"command": "pip install requests",
"description": "Install requests library"
},
"success": false,
"error": "bash: pip: command not found",
"execution_time": 0.125
}
```
**Expected behavior**:
- Always return `"allow": true`
- Update learning patterns based on success/failure
- Log execution for analysis
- Update session state
**Example response**:
```json
{
"allow": true,
"message": "Logged Bash execution (learned failure pattern)"
}
```
---
### Stop
**Trigger**: When Claude session ends
**Purpose**: Finalize session, create documentation
**Input**:
```json
{}
```
**Expected behavior**:
- Always return `"allow": true`
- Create LAST_SESSION.md
- Update ACTIVE_TODOS.md
- Save learned patterns
- Generate recovery information if needed
**Example response**:
```json
{
"allow": true,
"message": "Session finalized. Modified 5 files, used 23 tools."
}
```
---
## Error Handling
### Hook Errors
If a hook script:
- Exits with non-zero code (except 1 for PreToolUse)
- Produces invalid JSON
- Times out (> 5 seconds default)
- Crashes or cannot be executed
Then Claude Code will:
- Log the error
- Allow the operation to proceed
- Display a warning message
### Recovery Behavior
Hooks are designed to fail safely:
- Operations are never blocked due to hook failures
- Invalid responses are treated as "allow"
- Missing hooks are ignored
- Malformed JSON output allows operation
---
## Performance Requirements
### Execution Time
- **UserPromptSubmit**: < 100ms recommended
- **PreToolUse**: < 50ms recommended (blocking user)
- **PostToolUse**: < 200ms recommended (can be async)
- **Stop**: < 1s recommended (cleanup operations)
### Memory Usage
- Hooks should use < 50MB memory
- Avoid loading large datasets on each execution
- Use caching for expensive operations
### I/O Operations
- Minimize file I/O in PreToolUse hooks
- Batch write operations where possible
- Use async operations for non-blocking hooks
---
## Security Considerations
### Input Validation
Always validate hook input:
```python
def validate_input(input_data):
if not isinstance(input_data, dict):
raise ValueError("Input must be JSON object")
tool = input_data.get("tool", "")
if not isinstance(tool, str):
raise ValueError("Tool must be string")
# Validate other fields...
```
### Output Sanitization
Ensure hook output is safe:
```python
def safe_message(text):
# Remove potential injection characters
return text.replace('\x00', '').replace('\r', '').replace('\n', '\\n')
response = {
"allow": True,
"message": safe_message(user_input)
}
```
### File Path Validation
For hooks that access files:
```python
def validate_file_path(path):
# Convert to absolute path
abs_path = os.path.abspath(path)
# Check if within project boundaries
project_root = os.path.abspath(".")
if not abs_path.startswith(project_root):
raise ValueError("Path outside project directory")
# Check for system files
system_paths = ['/etc', '/usr', '/var', '/sys', '/proc']
for sys_path in system_paths:
if abs_path.startswith(sys_path):
raise ValueError("System file access denied")
```
---
## Testing Hooks
### Unit Testing
Test hooks with sample inputs:
```python
def test_command_validator():
import subprocess
import json
# Test dangerous command
input_data = {
"tool": "Bash",
"parameters": {"command": "rm -rf /"}
}
process = subprocess.run(
["python3", "hooks/command_validator.py"],
input=json.dumps(input_data),
capture_output=True,
text=True
)
assert process.returncode == 1 # Should block
response = json.loads(process.stdout)
assert response["allow"] == False
```
### Integration Testing
Test with Claude Code directly:
```bash
# Test in development environment
echo '{"tool": "Bash", "parameters": {"command": "ls"}}' | python3 hooks/command_validator.py
# Test hook registration
claude-hooks status
```
### Performance Testing
Measure hook execution time:
```python
import time
import subprocess
import json
def benchmark_hook(hook_script, input_data, iterations=100):
times = []
for _ in range(iterations):
start = time.time()
subprocess.run(
["python3", hook_script],
input=json.dumps(input_data),
capture_output=True
)
times.append(time.time() - start)
avg_time = sum(times) / len(times)
max_time = max(times)
print(f"Average: {avg_time*1000:.1f}ms, Max: {max_time*1000:.1f}ms")
```

View file

@ -0,0 +1,217 @@
# Your First Hour with Claude Hooks
**Time required**: 30-45 minutes
**What you'll gain**: Confidence using Claude with intelligent assistance
We're going to experience Claude Hooks by watching it learn from your commands and automatically protect your work. By the end, you'll have seen the system in action and feel comfortable relying on it.
## What We'll Do Together
We'll set up Claude Hooks, then deliberately make mistakes and watch the system learn and adapt. You'll see:
- A dangerous command get blocked automatically
- The system learn from a failed command and suggest alternatives
- An automatic backup triggered before context gets full
- Your session seamlessly continue after Claude restarts
Let's begin.
## Step 1: Install Claude Hooks
First, we'll get Claude Hooks installed. Don't worry about understanding the configuration yet - we'll experience how it works first.
Open your terminal and navigate to where you downloaded claude-hooks:
```bash
cd claude-hooks
./scripts/install.sh
```
You should see output like this:
```
Claude Code Hooks Installation
==================================
Checking Python version... Python 3.11 found
✓ Python version is compatible
Installing Python dependencies... SUCCESS
```
**Notice** that the installer found your Python version and installed dependencies automatically.
The installer will ask if you want to automatically configure Claude Code. Say **yes** - we want to see this working right away:
```
Would you like to automatically add hooks to your Claude settings? (y/n): y
Updating Claude settings... SUCCESS
🎉 Hooks have been automatically configured!
```
You now have Claude Hooks installed and configured. We haven't learned how it works yet, but it's ready to assist you.
## Step 2: Restart Claude Code
Close Claude Code completely and start it again. This loads the hooks we just installed.
When Claude starts, the hooks are now silently running in the background. You won't see anything different yet - the magic happens when you start working.
## Step 3: Watch Command Validation in Action
Let's deliberately try a command that often fails to see the validation in action.
Start a new Claude conversation and try this:
> "Run `pip install requests` to add the requests library"
Watch what happens. You should see something like:
```
⚠️ Warning: pip commands often fail (confidence: 88%)
💡 Suggestion: Use "pip3 install requests"
```
**Notice** that Claude Hooks warned you about the command before it ran. The system doesn't have any learned patterns yet (it's brand new), but it has built-in knowledge about common failures.
Now try the suggested command:
> "Run `pip3 install requests`"
This time it should work without warnings. The system is learning that `pip3` succeeds where `pip` fails on your system.
## Step 4: Experience the Shadow Learner
Let's make another common mistake and watch the system learn from it.
Try this command:
> "Run `python --version` to check the Python version"
If you're on a system where `python` isn't available, you'll see it fail. Now try the same command again:
> "Run `python --version` again"
**Notice** what happens this time. The system should now warn you:
```
⛔ Blocked: python commands often fail (confidence: 95%)
💡 Suggestion: Use "python3 --version"
```
The shadow learner observed that `python` failed and is now protecting you from repeating the same mistake. This is intelligence building in real-time.
## Step 5: See Context Monitoring
Let's trigger the context monitoring system. The hooks track how much of Claude's conversation context you're using and automatically back up your work when it gets full.
Create several files to simulate a longer session:
> "Create a file called `test1.py` with a simple hello world script"
> "Now create `test2.py` with a different example"
> "Create `test3.py` with some more code"
> "Show me the current git status"
As you work, you might see messages like:
```
Context usage: 23%
```
or
```
Auto-backup created: activity_threshold (usage: 78%)
```
**Notice** how the system is quietly tracking your session and automatically creating backups. You don't have to think about it - your work is being preserved.
## Step 6: Experience Session Continuity
Now let's see session continuity in action. The system has been creating documentation about your session.
Run this command:
> "Show me the contents of LAST_SESSION.md"
You should see a file that looks like:
```markdown
# Last Claude Session Summary
**Session ID**: abc12345
**Duration**: 2024-01-15T14:30:00 → 2024-01-15T14:45:00
## Files Modified (3)
- test1.py
- test2.py
- test3.py
## Tools Used (8 total)
- Write: 3 times
- Bash: 2 times
- Read: 3 times
## Recent Commands (5)
- `pip3 install requests` (2024-01-15T14:32:00)
- `python3 --version` (2024-01-15T14:35:00)
...
```
**This is your session history**. If Claude ever restarts or you lose context, you can reference this file to see exactly what you were working on.
## Step 7: Check What You've Accomplished
Let's see what the system has learned about your environment:
> "Run the command `claude-hooks status` to see session information"
You should see output showing:
- How many tools you've used
- Files you've modified
- Current context usage
- Whether a backup is recommended
Now check the learned patterns:
> "Run `claude-hooks patterns` to see what the system has learned"
You should see entries like:
```
🖥️ Command Patterns:
pip
Confidence: 88%
Evidence: 2 samples
Success Rate: 0%
python3
Confidence: 95%
Evidence: 1 samples
Success Rate: 100%
```
**This is the intelligence you've built**. The system now knows that on your machine, `pip` fails but `pip3` works, and `python3` works better than `python`.
## What You've Experienced
In the last 30 minutes, you've experienced all the core capabilities of Claude Hooks:
**Command validation** - Dangerous commands blocked, alternatives suggested
**Shadow learning** - System learned from your failures and successes
**Context monitoring** - Automatic backups triggered by usage
**Session continuity** - Complete history preserved in LAST_SESSION.md
Most importantly, **none of this required you to configure anything or learn complex concepts**. The system worked intelligently in the background while you focused on your actual work.
## Next Steps
You now have Claude Hooks working and have experienced its core benefits. The system will continue learning from every command you run and every session you have.
When you're ready to go deeper:
- Read [How to restore from backups](../how-to/restore-backup.md) when you need to recover work
- Check [How to customize command patterns](../how-to/customize-patterns.md) to add your own validations
- Explore [Understanding the shadow learner](../explanation/shadow-learner.md) to understand how the intelligence works
**The most important thing**: Keep using Claude normally. Claude Hooks is now silently making your experience better, learning from every interaction, and protecting your work automatically.
You've gained a new superpower - Claude that gets smarter with every use.