-
-
Notifications
You must be signed in to change notification settings - Fork 108
Memory Awareness Hooks Detailed Guide
This is the comprehensive guide for Claude Code Memory Awareness Hooks, providing detailed installation, configuration, troubleshooting, and architecture information.
🚀 v7.1.4 Update: All installation commands in this guide now use the new unified Python installer (
python install_hooks.py
) which replaced the legacy shell scripts. This provides enhanced cross-platform compatibility, intelligent configuration merging, and comprehensive safety features.
🆕 Natural Memory Triggers v7.1.0 Available! This guide covers the foundational memory hooks system. For the latest intelligent trigger detection with automatic pattern recognition, see our Natural Memory Triggers v7.1.0 Guide which builds upon this foundation with 85%+ trigger accuracy and multi-tier performance.
- Evolution to Natural Memory Triggers
- Architecture
- Installation Methods
- Configuration Details
- Troubleshooting
- Advanced Usage
- Development
The memory awareness system has evolved significantly:
Feature | Memory Hooks (Legacy) | Natural Memory Triggers v7.1.0 |
---|---|---|
Activation | Manual session events | Automatic pattern detection |
Intelligence | Static rule-based | AI-powered semantic analysis |
Performance | Single processing tier | Multi-tier optimization (50ms/150ms/500ms) |
Management | JSON file editing | CLI controller with real-time updates |
Learning | Fixed behavior | Adaptive user preference learning |
Context | Basic project detection | Git-integrated repository awareness |
For new installations, we recommend Natural Memory Triggers v7.1.0 which provides:
- ✅ Intelligent Trigger Detection: Automatic memory retrieval with 85%+ accuracy
- ✅ CLI Management: Real-time configuration without editing files
- ✅ Performance Optimization: Multi-tier processing for optimal response times
- ✅ Git Integration: Repository-aware context for enhanced relevance
This guide remains relevant for:
- Understanding the foundational architecture
- Troubleshooting legacy hook installations
- Custom hook development
- Advanced integration scenarios
- Educational purposes and system understanding
The memory awareness system consists of three main components:
-
session-start.js
- Automatic memory injection at session initialization -
session-end.js
- Memory consolidation and outcome storage -
topic-change.js
- Dynamic memory loading based on conversation evolution
-
project-detector.js
- Project context detection and analysis -
memory-scorer.js
- Relevance scoring algorithms for memory selection -
context-formatter.js
- Memory formatting for Claude Code injection
-
config.json
- Hook configuration and memory service endpoints -
config.template.json
- Configuration template with defaults
- Session Startup: Automatically loads relevant project memories
- Dynamic Updates: Real-time memory injection based on conversation topics
- Cross-Session Continuity: Links conversations across different sessions
- Project Awareness: Detects current project and loads relevant context
- Relevance Scoring: AI-powered memory selection based on conversation topics
- Time Decay: Prioritizes recent memories while maintaining historical context
- Session Outcomes: Automatically stores conversation insights
- Auto-Tagging: Intelligent categorization of memory content
- Knowledge Building: Progressive memory organization and linking
The automated installer handles the complete setup:
cd claude-hooks
python install_hooks.py --basic
What the installer does:
- Creates
~/.claude/hooks/
directory - Copies all hook files to correct location
- Configures
~/.claude/settings.json
with hook integration - Backs up existing configuration
- Runs comprehensive integration tests (14 tests)
- Tests memory service connectivity
- Provides detailed installation report
Installation Options:
python install_hooks.py --basic # Basic memory hooks
python install_hooks.py --natural-triggers # With Natural Memory Triggers
python install_hooks.py --all # Full installation
python install_hooks.py --help # Show help
python install_hooks.py --uninstall # Remove hooks
For users who prefer manual control or need custom configurations:
- Copy Hook Files:
# Create directory structure
mkdir -p ~/.claude/hooks/{core,utilities,tests}
# Copy files
cp claude-hooks/core/*.js ~/.claude/hooks/core/
cp claude-hooks/utilities/*.js ~/.claude/hooks/utilities/
cp claude-hooks/tests/*.js ~/.claude/hooks/tests/
cp claude-hooks/config.* ~/.claude/hooks/
cp claude-hooks/README.md ~/.claude/hooks/
- Configure Claude Code Settings:
# Create or edit ~/.claude/settings.json
cat > ~/.claude/settings.json << 'EOF'
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "node ~/.claude/hooks/core/session-start.js",
"timeout": 10
}
]
}
],
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "node ~/.claude/hooks/core/session-end.js",
"timeout": 15
}
]
}
]
}
}
EOF
- Configure Memory Service:
cd ~/.claude/hooks
cp config.template.json config.json
# Edit config.json with your settings
- Test Installation:
cd ~/.claude/hooks
node tests/integration-test.js
Edit ~/.claude/hooks/config.json
:
{
"memoryService": {
"endpoint": "https://your-server:8443",
"apiKey": "your-api-key",
"defaultTags": ["claude-code", "auto-generated"],
"maxMemoriesPerSession": 10
},
"projectDetection": {
"gitRepository": true,
"packageFiles": ["package.json", "pyproject.toml", "Cargo.toml"],
"frameworkDetection": true,
"languageDetection": true
},
"sessionAnalysis": {
"extractTopics": true,
"extractDecisions": true,
"extractInsights": true,
"extractCodeChanges": true,
"extractNextSteps": true,
"minSessionLength": 100
}
}
The system detects projects based on:
-
Git Repository: Checks for
.git
directory -
Package Files: Looks for
package.json
,pyproject.toml
,Cargo.toml
, etc. - Framework Detection: Identifies React, Vue, Django, etc.
- Language Detection: Analyzes file extensions and content
Configure memory selection preferences:
{
"memoryFilters": {
"timeDecay": {
"enabled": true,
"decayFactor": 0.95,
"maxAge": "30d"
},
"relevanceThreshold": 0.3,
"excludeTags": ["temporary", "draft"],
"priorityTags": ["architecture", "decision", "bug-fix"]
}
}
{
"hooks": {
"sessionStart": {
"enabled": true,
"timeout": 10,
"retries": 2,
"verboseLogging": false
},
"sessionEnd": {
"enabled": true,
"timeout": 15,
"consolidationEnabled": true,
"autoTagging": true
}
},
"performance": {
"cacheMemories": true,
"cacheDuration": "1h",
"maxConcurrentRequests": 3
}
}
Problem: Claude Code shows "Found 0 hook matchers in settings"
Diagnosis:
# Check settings file exists and is valid
ls ~/.claude/settings.json
cat ~/.claude/settings.json | jq .hooks
# Verify hook files exist
ls -la ~/.claude/hooks/core/
Solutions:
-
Reinstall hooks:
cd claude-hooks && python install_hooks.py --basic
- Check settings format: Settings must be valid JSON with proper structure
-
Verify file permissions:
chmod +x ~/.claude/hooks/core/*.js
-
Test Claude Code:
claude --debug hooks
Problem: "Parse error: Expected property name or '}' in JSON"
Cause: Memory service returns Python dictionary format with single quotes
Solutions:
- Update to latest version: The current version includes Python→JSON conversion
-
Verify fix is applied: Check that
session-start.js
includes string replacement logic - Test parsing manually:
node -e "
const testData = '{\"results\": [{\"content\": \"test\"}]}';
console.log(JSON.parse(testData));
"
Problem: "Network error" or "ENOTFOUND" in hook output
Diagnosis:
# Test service availability
curl -k https://your-endpoint:8443/api/health
# Check configuration
cat ~/.claude/hooks/config.json | jq .memoryService
# Test network connectivity
ping your-server-hostname
Solutions:
- Verify service is running: Check memory service status
-
Update endpoint URL: Edit
~/.claude/hooks/config.json
- Check API key: Ensure correct API key is configured
- Firewall/network: Verify port 8443 is accessible
- SSL certificates: Self-signed certs may need special handling
Problem: Hooks installed but Claude Code can't find them
Diagnosis:
# Check for hooks in wrong location
ls ~/.claude-code/hooks/
ls ~/.claude/hooks/
Solutions:
- Move to correct location:
mkdir -p ~/.claude/hooks
mv ~/.claude-code/hooks/* ~/.claude/hooks/
-
Update settings paths: Ensure settings.json points to
~/.claude/hooks/
-
Reinstall:
cd claude-hooks && python install_hooks.py --basic
Problem: "node: command not found" or version conflicts
Solutions:
- Install Node.js: Version 14 or higher required
- Update PATH: Ensure Node.js is in system PATH
-
Check version:
node --version && npm --version
-
Use full path: Edit hooks to use
/usr/bin/node
instead ofnode
Problem: "Permission denied" when running hooks
Solutions:
# Fix hook file permissions
chmod +x ~/.claude/hooks/core/*.js
chmod +x ~/.claude/hooks/tests/*.js
# Fix directory permissions
chmod 755 ~/.claude/hooks
chmod -R 644 ~/.claude/hooks/*.json
Enable verbose logging:
# Set debug environment variable
export CLAUDE_HOOKS_DEBUG=true
# Run Claude Code with debug output
claude --debug hooks
# Test individual hooks
node ~/.claude/hooks/core/session-start.js
Test hooks individually:
cd ~/.claude/hooks
# Test session start hook
node core/session-start.js
# Test session end hook
node core/session-end.js
# Test project detection
node -e "
const { detectProjectContext } = require('./utilities/project-detector');
detectProjectContext('.').then(console.log);
"
# Test memory scoring
node -e "
const { scoreMemoryRelevance } = require('./utilities/memory-scorer');
const mockMemories = [{content: 'test', tags: ['test']}];
const mockProject = {name: 'test', language: 'JavaScript'};
console.log(scoreMemoryRelevance(mockMemories, mockProject));
"
Run specific test categories:
cd ~/.claude/hooks
# Run all integration tests
node tests/integration-test.js
# Test specific components (modify test file to run subset)
# Tests available:
# - Project Detection
# - Memory Relevance Scoring
# - Context Formatting
# - Session Hook Structure
# - Configuration Loading
# - File Structure Validation
# - Mock Session Execution
# - Package Dependencies
# - Claude Code Settings Validation
# - Hook Files Location Validation
# - Claude Code CLI Availability
# - Memory Service Protocol
# - Memory Service Connectivity
Hook logs appear in Claude Code debug output:
# Look for these log patterns:
claude --debug hooks 2>&1 | grep -E "\[Memory Hook\]|\[Project Detector\]|\[Memory Scorer\]"
# Common log messages:
# [Memory Hook] Session starting - initializing memory awareness...
# [Memory Hook] Found X relevant memories
# [Memory Hook] Successfully injected memory context
# [Memory Hook] Session ending - consolidating outcomes...
# [Memory Hook] Parse error: [details]
# [Memory Hook] Network error: [details]
Create custom filtering logic by editing memory-scorer.js
:
// Add custom scoring factors
function calculateRelevanceScore(memory, projectContext) {
let score = 0;
// Time decay
const ageInDays = (Date.now() - new Date(memory.created_at_iso)) / (1000 * 60 * 60 * 24);
score += Math.exp(-ageInDays / 30) * 0.3;
// Tag matching
const projectTags = [projectContext.name, projectContext.language];
const tagMatches = memory.tags.filter(tag => projectTags.includes(tag)).length;
score += tagMatches * 0.4;
// Custom business logic
if (memory.memory_type === 'decision') score += 0.2;
if (memory.tags.includes('critical')) score += 0.3;
return Math.min(score, 1.0);
}
Modify session-end.js
to extract custom insights:
// Add custom conversation analysis
function analyzeConversation(conversationData) {
const analysis = {
// ... existing analysis
customInsights: [],
businessDecisions: [],
technicalDebts: []
};
// Extract business decisions
const businessPatterns = [
/decided.*business/gi,
/business.*decision/gi,
/strategic.*choice/gi
];
// Extract technical debt mentions
const techDebtPatterns = [
/technical.*debt/gi,
/refactor.*needed/gi,
/todo.*later/gi
];
// Process messages for custom patterns
conversationData.messages.forEach(msg => {
businessPatterns.forEach(pattern => {
if (pattern.test(msg.content)) {
analysis.businessDecisions.push(extractSentence(msg.content, pattern));
}
});
});
return analysis;
}
Configure project-specific memory loading:
{
"projectSpecific": {
"enabled": true,
"projects": {
"my-app": {
"memoryTags": ["my-app", "react", "frontend"],
"maxMemories": 15,
"priorityTypes": ["architecture", "bug-fix"]
},
"api-service": {
"memoryTags": ["api-service", "nodejs", "backend"],
"maxMemories": 10,
"priorityTypes": ["performance", "security"]
}
}
}
}
Create custom hooks by following this structure:
/**
* Custom Hook Template
*/
async function customHook(context) {
try {
console.log('[Custom Hook] Starting...');
// Your custom logic here
const result = await performCustomOperation(context);
console.log('[Custom Hook] Completed successfully');
return result;
} catch (error) {
console.error('[Custom Hook] Error:', error.message);
// Fail gracefully
}
}
module.exports = {
name: 'custom-hook',
version: '1.0.0',
description: 'Custom hook description',
trigger: 'custom-event',
handler: customHook,
config: {
async: true,
timeout: 10000,
priority: 'normal'
}
};
Add custom tests to integration-test.js
:
// Add custom test
results.test('Custom Feature Test', () => {
// Your test logic
const result = testCustomFeature();
if (!result.success) {
return { success: false, error: result.error };
}
console.log(' Custom feature working correctly');
return { success: true };
});
Test memory service integration:
// Test custom memory operations
async function testMemoryService() {
const config = loadConfig();
// Store test memory
const storeResult = await storeMemory(config.endpoint, config.apiKey, {
content: 'Test memory content',
tags: ['test', 'integration'],
memory_type: 'test'
});
// Retrieve memories
const retrieveResult = await retrieveMemories(config.endpoint, config.apiKey, {
query: 'test content',
limit: 5
});
return { storeResult, retrieveResult };
}
To contribute to the hooks system:
- Fork the repository
- Create feature branch:
git checkout -b feature/new-hook
- Add your hook in appropriate directory (
core/
,utilities/
, etc.) - Add tests in
tests/
directory - Update documentation
- Test thoroughly:
python install_hooks.py --dry-run --basic
- Submit pull request
Session Start → Project Detection → Memory Query → Relevance Scoring → Context Injection
↓ ↓ ↓ ↓ ↓
Hook Event Git/Package MCP Protocol Scoring Algorithm Claude Context
Triggered File Analysis JSON-RPC Call Time/Tag/Content System Message
Topic Change → Semantic Analysis → Additional Memory Query → Context Update
↓ ↓ ↓ ↓
Conversation NLP Processing Enhanced Query Live Injection
Analysis Topic Extraction Refined Parameters Memory Append
Session End → Conversation Analysis → Auto-Tagging → Memory Storage → Cross-Linking
↓ ↓ ↓ ↓ ↓
Hook Event Extract Insights Generate Tags Store via API Update Relations
Triggered Parse Decisions ML Classification REST/MCP Build Knowledge Graph
This comprehensive system transforms Claude Code into a memory-aware development assistant that maintains perfect context across all interactions, learns from every session, and provides increasingly relevant suggestions over time.