Files
claudetools/.claude/hooks
Mike Swanson 359c2cf1b4 Fix zombie process accumulation and broken context recall (Phase 1 - Emergency Fixes)
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>
2026-01-17 13:51:22 -07:00
..

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:

  1. Recalling context - Automatically inject relevant context from previous sessions before each message
  2. Saving context - Automatically save conversation summaries after task completion
  3. 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/recall to 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-contexts to 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:

  1. Create a JWT token
  2. Detect or create your project
  3. Configure environment variables
  4. Make hooks executable
  5. Test the system

Manual Setup

  1. Get JWT Token
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "your-password"}'
  1. 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"
  }'
  1. 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
  1. 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:

  1. Git config - git config --local claude.projectid
  2. Git remote URL hash - Consistent ID from remote URL
  3. 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:

  1. Start Claude Code - Context is automatically recalled
  2. Work normally - All your conversations happen as usual
  3. Complete tasks - Context is automatically saved
  4. Next session - Previous context is automatically available

Troubleshooting

Context not appearing?

  1. Enable debug mode:

    echo "DEBUG_CONTEXT_RECALL=true" >> .claude/context-recall-config.env
    
  2. Check API is running:

    curl http://localhost:8000/health
    
  3. Verify JWT token:

    curl -H "Authorization: Bearer $JWT_TOKEN" http://localhost:8000/api/projects
    
  4. Check hooks are executable:

    ls -la .claude/hooks/
    

Context not saving?

  1. Check task-complete hook output:

    bash -x .claude/hooks/task-complete
    
  2. Verify project ID:

    source .claude/context-recall-config.env
    echo $CLAUDE_PROJECT_ID
    
  3. Check API logs for errors

Hooks not running?

  1. Verify hook permissions:

    chmod +x .claude/hooks/*
    
  2. Test hook manually:

    bash .claude/hooks/user-prompt-submit
    
  3. Check Claude Code hook documentation: https://docs.claude.com/claude-code/hooks

API connection errors?

  1. Verify API is running:

    curl http://localhost:8000/health
    
  2. Check firewall/port blocking

  3. 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 contexts
  • POST /api/conversation-contexts - Save new context
  • POST /api/project-states - Update project state
  • GET /api/projects - Get project information
  • POST /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:

  1. Check troubleshooting section above
  2. Review API logs: tail -f api/logs/app.log
  3. Test with scripts/test-context-recall.sh
  4. Check hook output with bash -x .claude/hooks/[hook-name]