Long Claude Code sessions eventually compact: the conversation gets summarized to free up context. Usually that's fine, but sometimes the detail you needed (an error message, a decision, a file list) gets squashed. A PreCompact hook lets you save a copy first.
What a PreCompact hook does
PreCompact runs right before Claude Code compacts, whether you typed /compact (manual) or the context filled up (auto). The hook gets JSON on stdin that includes transcript_path and trigger.
Add this to .claude/settings.json:
{
"hooks": {
"PreCompact": [
{
"matcher": "manual|auto",
"hooks": [
{
"type": "command",
"command": "mkdir -p .claude/backups && jq -r '.transcript_path' | xargs -I{} cp {} .claude/backups/pre-compact-$(date +%Y%m%d-%H%M%S).jsonl"
}
]
}
]
}
}
Every time the session compacts, the full transcript gets copied to .claude/backups/ with a timestamp. If the summary loses something, grep the backup.
Tips
- Add
.claude/backups/to.gitignore. Transcripts can contain secrets and file contents. - Clear old backups now and then:
find .claude/backups -mtime +7 -delete. - Want only manual compacts? Set the matcher to
manual. - Run
/hooksto check the hook is loaded.
Shared settings, safety hooks, a short CLAUDE.md and a read-only reviewer subagent ship ready to copy in Vildanden Agent Config. The free sample is enough to get started today.
Top comments (0)