Feature Request: Add PreCompact and PostCompact hooks for custom context management
Description
I'd like to request hooks that fire before and after Claude Code's autocompact process, allowing users to run custom logic when context is being summarized.
Use Case
When building systems that need long-term memory across sessions (personal knowledge bases, project documentation, ops tooling), valuable structured data gets lost during autocompact summarization. Things like:
- Key decisions made during the session
- IP addresses, device info, or other structured data discovered
- Code snippets worth preserving
- Conclusions and root causes identified
Currently there's no way to extract or preserve this data before it gets summarized into prose.
Proposed Solution
Add PreCompact and PostCompact hooks similar to existing PreToolUse/PostToolUse hooks:
{
"hooks": {
"PreCompact": [
{
"command": "/path/to/extract-before-compact.sh"
}
],
"PostCompact": [
{
"command": "/path/to/after-compact.sh"
}
]
}
}
PreCompact hook input (JSON via stdin):
{
"messages_to_compact": [...],
"current_summary": "...",
"session_id": "...",
"cwd": "..."
}
PreCompact hook output (optional, via stdout):
{
"inject_into_summary": "Additional context to preserve: ...",
"extracted_data": {...}
}
Benefits
- Users can extract structured data before summarization loses it
- Enables integration with external memory/knowledge systems
- Allows project-specific context preservation (security ops extracts IPs/MACs, dev projects extract function signatures)
- Gives users control over what context survives compaction
- Consistent with existing hook architecture
Workaround
Currently using SessionEnd hooks to parse transcripts after the fact, but this misses data already lost to earlier autocompacts during long sessions.
This issue has 9 comments on GitHub. Read the full discussion on GitHub ↗