Claude Code Context Recovery: Never Lose Progress to Compaction Again
Stop losing context when Claude Code compacts. This hook backs up transcripts and automatically injects recovery instructions when your session resumes.
Problem: You are deep in a complex implementation. Claude's context fills up and compacts. Suddenly Claude has forgotten everything - your session file, project rules, what you were building. You spend 10 minutes re-explaining context that should have been preserved.
Quick Win: Add this to .claude/settings.json and Claude will automatically know to re-read critical files after compaction:
Why Two Hooks?
Here is the key insight: PreCompact cannot inject context to Claude. It only supports common JSON fields for output. Only SessionStart and UserPromptSubmit can inject additionalContext.
The solution is a marker file pattern:
- PreCompact fires before compaction - backs up transcript, creates marker file
- Compaction happens - context is reduced
- SessionStart fires when session resumes - detects marker, injects recovery instructions, deletes marker
The PreCompact Hook
This hook runs before every compaction (manual /compact or automatic):
Transcripts save to .claude/backups/ with session ID and timestamp. The marker goes to ~/.claude/ so it persists across projects.
The SessionStart Hook
This hook detects the marker and injects recovery instructions:
The additionalContext field is what makes this work. Claude receives these instructions as part of its context, prompting it to reload critical files.
When Things Go Wrong
Context recovery not triggering Check if the marker is being created:
Stale marker causing repeated recovery Delete it manually:
Backups not appearing Check the hook logs:
Customize the Recovery Message
Edit buildContextRecoveryMessage() in session-start.mjs to add project-specific instructions. Common additions:
- Active feature branch context
- Database migration state
- Test suite status
- Custom skill loading instructions
Next Steps
- Set up the Hooks Guide for all 8 hook types
- Learn context engineering strategies
- Configure Skill Activation for automatic skill loading
Last updated on