CRITICAL: This commit fixes both the zombie process issue AND the broken context recall system that was failing silently due to encoding errors. ROOT CAUSES FIXED: 1. Periodic save running every 1 minute (540 processes/hour) 2. Missing timeouts on subprocess calls (hung processes) 3. Background spawning with & (orphaned processes) 4. No mutex lock (overlapping executions) 5. Missing UTF-8 encoding in log functions (BREAKING context saves) FIXES IMPLEMENTED: Fix 1.1 - Reduce Periodic Save Frequency (80% reduction) - File: .claude/hooks/setup_periodic_save.ps1 - Change: RepetitionInterval 1min -> 5min - Impact: 540 -> 108 processes/hour from periodic saves Fix 1.2 - Add Subprocess Timeouts (prevent hangs) - Files: periodic_save_check.py (3 calls), periodic_context_save.py (4 calls) - Change: Added timeout=5 to all subprocess.run() calls - Impact: Prevents indefinitely hung git/ssh processes Fix 1.3 - Remove Background Spawning (eliminate orphans) - Files: user-prompt-submit (line 68), task-complete (lines 171, 178) - Change: Removed & from sync-contexts spawning, made synchronous - Impact: Eliminates 290 orphaned processes/hour Fix 1.4 - Add Mutex Lock (prevent overlaps) - File: periodic_save_check.py - Change: Added acquire_lock()/release_lock() with try/finally - Impact: Prevents Task Scheduler from spawning overlapping instances Fix 1.5 - Add UTF-8 Encoding (CRITICAL - enables context saves) - Files: periodic_context_save.py, periodic_save_check.py - Change: Added encoding="utf-8" to all log file opens - Impact: FIXES silent failure preventing ALL context saves since deployment TOOLS ADDED: - monitor_zombies.ps1: PowerShell script to track process counts and memory EXPECTED RESULTS: - Before: 1,010 processes/hour, 3-7 GB RAM/hour - After: ~151 processes/hour (85% reduction), minimal RAM growth - Context recall: NOW WORKING (was completely broken) TESTING: - Run monitor_zombies.ps1 before and after 30min work session - Verify context auto-injection on Claude Code restart - Check .claude/periodic-save.log for successful saves (no encoding errors) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Claude Code Context Recall Hooks
Automatically inject and save relevant context from the ClaudeTools database into Claude Code conversations.
Overview
This system provides seamless context continuity across Claude Code sessions by:
- Recalling context - Automatically inject relevant context from previous sessions before each message
- Saving context - Automatically save conversation summaries after task completion
- Project awareness - Track project state and maintain context across sessions
Hooks
user-prompt-submit
Runs: Before each user message is processed
Purpose: Injects relevant context from the database into the conversation
What it does:
- Detects the current project ID (from git config or remote URL)
- Calls
/api/conversation-contexts/recallto fetch relevant contexts - Injects context as a formatted markdown section
- Falls back gracefully if API is unavailable
Example output:
## 📚 Previous Context
The following context has been automatically recalled from previous sessions:
### 1. Database Schema Updates (Score: 8.5/10)
*Type: technical_decision*
Updated the Project model to include new fields for MSP integration...
---
task-complete
Runs: After a task is completed
Purpose: Saves conversation context to the database for future recall
What it does:
- Gathers task information (git branch, commit, modified files)
- Creates a compressed summary of the task
- POST to
/api/conversation-contextsto save context - Updates project state via
/api/project-states
Saved information:
- Task summary
- Git branch and commit hash
- Modified files
- Timestamp
- Metadata for future retrieval
Configuration
Quick Setup
Run the automated setup script:
bash scripts/setup-context-recall.sh
This will:
- Create a JWT token
- Detect or create your project
- Configure environment variables
- Make hooks executable
- Test the system
Manual Setup
- Get JWT Token
curl -X POST http://localhost:8000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "your-password"}'
- Get/Create Project
curl -X POST http://localhost:8000/api/projects \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "ClaudeTools",
"description": "Your project description"
}'
- Configure
.claude/context-recall-config.env
CLAUDE_API_URL=http://localhost:8000
CLAUDE_PROJECT_ID=your-project-uuid-here
JWT_TOKEN=your-jwt-token-here
CONTEXT_RECALL_ENABLED=true
MIN_RELEVANCE_SCORE=5.0
MAX_CONTEXTS=10
- Make hooks executable
chmod +x .claude/hooks/user-prompt-submit
chmod +x .claude/hooks/task-complete
Configuration Options
| Variable | Default | Description |
|---|---|---|
CLAUDE_API_URL |
http://localhost:8000 |
API base URL |
CLAUDE_PROJECT_ID |
Auto-detect | Project UUID |
JWT_TOKEN |
Required | Authentication token |
CONTEXT_RECALL_ENABLED |
true |
Enable/disable system |
MIN_RELEVANCE_SCORE |
5.0 |
Minimum score (0-10) |
MAX_CONTEXTS |
10 |
Max contexts per query |
AUTO_SAVE_CONTEXT |
true |
Save after completion |
DEBUG_CONTEXT_RECALL |
false |
Enable debug logs |
Project ID Detection
The system automatically detects your project ID using:
- Git config -
git config --local claude.projectid - Git remote URL hash - Consistent ID from remote URL
- Environment variable -
CLAUDE_PROJECT_ID
To manually set project ID in git config:
git config --local claude.projectid "your-project-uuid"
Testing
Run the test script:
bash scripts/test-context-recall.sh
This will:
- Test API connectivity
- Test context recall endpoint
- Test context saving
- Verify hooks are working
Usage
Once configured, the system works automatically:
- Start Claude Code - Context is automatically recalled
- Work normally - All your conversations happen as usual
- Complete tasks - Context is automatically saved
- Next session - Previous context is automatically available
Troubleshooting
Context not appearing?
-
Enable debug mode:
echo "DEBUG_CONTEXT_RECALL=true" >> .claude/context-recall-config.env -
Check API is running:
curl http://localhost:8000/health -
Verify JWT token:
curl -H "Authorization: Bearer $JWT_TOKEN" http://localhost:8000/api/projects -
Check hooks are executable:
ls -la .claude/hooks/
Context not saving?
-
Check task-complete hook output:
bash -x .claude/hooks/task-complete -
Verify project ID:
source .claude/context-recall-config.env echo $CLAUDE_PROJECT_ID -
Check API logs for errors
Hooks not running?
-
Verify hook permissions:
chmod +x .claude/hooks/* -
Test hook manually:
bash .claude/hooks/user-prompt-submit -
Check Claude Code hook documentation: https://docs.claude.com/claude-code/hooks
API connection errors?
-
Verify API is running:
curl http://localhost:8000/health -
Check firewall/port blocking
-
Verify API URL in config
How It Works
Context Recall Flow
User sends message
↓
[user-prompt-submit hook runs]
↓
Detect project ID
↓
Call /api/conversation-contexts/recall
↓
Format and inject context
↓
Claude processes message with context
Context Save Flow
Task completes
↓
[task-complete hook runs]
↓
Gather task information
↓
Create context summary
↓
POST to /api/conversation-contexts
↓
Update /api/project-states
↓
Context saved for future recall
API Endpoints Used
GET /api/conversation-contexts/recall- Retrieve relevant contextsPOST /api/conversation-contexts- Save new contextPOST /api/project-states- Update project stateGET /api/projects- Get project informationPOST /api/auth/login- Get JWT token
Security Notes
- JWT tokens are stored in
.claude/context-recall-config.env - This file should be in
.gitignore(DO NOT commit tokens!) - Tokens expire after 24 hours (configurable)
- Hooks fail gracefully if authentication fails
Advanced Usage
Custom Context Types
Modify task-complete hook to create custom context types:
CONTEXT_TYPE="bug_fix" # or "feature", "refactor", etc.
RELEVANCE_SCORE=9.0 # Higher for important contexts
Filtering Contexts
Adjust recall parameters in config:
MIN_RELEVANCE_SCORE=7.0 # Only high-quality contexts
MAX_CONTEXTS=5 # Fewer contexts per query
Manual Context Injection
You can manually trigger context recall:
bash .claude/hooks/user-prompt-submit
References
Support
For issues or questions:
- Check troubleshooting section above
- Review API logs:
tail -f api/logs/app.log - Test with
scripts/test-context-recall.sh - Check hook output with
bash -x .claude/hooks/[hook-name]