Feature request: PreCompact hook fired at configurable context threshold
Summary
Add a PreCompact hook (or a context-threshold hook) that fires when the context window reaches a configurable percentage (e.g. 90%), giving agents and users a chance to save state before auto-compaction discards mid-session work.
Problem
When Claude Code auto-compacts a long session, any in-flight state — memory file writes, task updates, checkpoint notes — that hasn't been committed yet is lost. There is currently no way to detect "I'm near the context limit" from within a hook, so nothing can be automated to save state before the compaction happens.
The existing hooks (PreToolUse, PostToolUse, Stop) don't expose context window usage, so there's no way to trigger behavior at a specific threshold.
Proposed solution
A new hook event, PreCompact, that fires before auto-compaction begins. Configuration could look like:
{
"hooks": {
"PreCompact": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "chezmoi apply && echo 'Memory checkpoint saved'"
}
]
}
]
}
}
Optionally, a contextThreshold setting (0–100) could control when the hook fires, e.g.:
{
"contextThreshold": 90
}
Use cases
- Auto-save memory/notes files to git before context is summarized
- Notify the user that context is near limit so they can run
/compactmanually at a good stopping point - Allow agents doing long multi-step tasks to write a checkpoint before state is lost
Workaround today
A Stop hook running chezmoi apply partially mitigates this — it flushes any memory files written during the turn to git after each response. But it doesn't help if the agent is mid-turn when compaction is triggered, and it doesn't give the agent itself a chance to write a checkpoint summary first.
This issue has 2 comments on GitHub. Read the full discussion on GitHub ↗