PreCompact hook: allow Claude to take actions before context compaction (write session state)
Feature Request: Reliable session state persistence across context compactions
Problem
When automatic context compaction fires, Claude loses all conversation context. The only mitigation today is manually maintaining a session state file (e.g. SESSION.md) — but this requires Claude to proactively write it before compaction happens, which is unreliable. Claude often doesn't write session state until after compaction has already occurred, meaning critical context (current task, pending work, decisions made) is lost.
Post-compact, even with a SessionStart (compact) hook that injects "read SESSION.md", it's hit or miss whether Claude reliably re-reads the right files and reconstructs full context before responding.
This is a significant friction point in long-running, multi-session engineering work — particularly in production systems where the session state represents hours of accumulated context about a complex codebase.
Requested Features
1. PreCompact hook with action capability
Allow the PreCompact hook to trigger a Claude action (e.g. a tool call or structured response) before compaction proceeds. Specifically: the ability to have Claude write a session state summary to a file as part of the compaction process, not just run a shell command.
Something like:
{
"hooks": {
"PreCompact": [
{
"type": "claude_action",
"prompt": "Before this compaction, write a complete summary of current session state to /path/to/SESSION.md covering: current task, pending work, key decisions, files modified, and what the next step is."
}
]
}
}
2. Guaranteed post-compact context injection
Currently SessionStart with compact matcher injects text into Claude's context, but it's inconsistent whether Claude acts on it reliably. A stronger guarantee that injected post-compact context is processed before Claude responds to the user would significantly improve reliability.
3. Built-in session state mechanism
A first-class "session anchor" concept — a file or structured data store that Claude automatically reads at session start and after compaction, and that Claude is prompted to update at task boundaries. This would be opt-in via project config.
Current Workaround
PreCompacthook prints a warning to stderr (user sees it, Claude cannot act on it)SessionStart (compact)hook injects a reminder to read SESSION.md- Manually maintained SESSION.md file updated by Claude when remembered
- Significant context loss still occurs regularly
Impact
Production engineering environments with long-running sessions, complex state, and USDA/regulatory compliance requirements where losing session context mid-task can have real consequences.
This issue has 4 comments on GitHub. Read the full discussion on GitHub ↗