Add `OnContextThreshold` hook for programmatic mid-session handoff
Summary
Expose a hook that fires when session context crosses a configurable percentage threshold (e.g., 65%, 80%), so users can automate state-saving and session handoff before auto-compaction kicks in around 95%.
Use case
I run multi-day autonomous build pipelines where a single CLI session can chew through context over the course of a long task. The current options are bad:
- Auto-compaction at ~95% is too late — by then the model has lost coherence on early decisions and compaction itself can drop important state.
- Manual monitoring of the statusline context % works but defeats the point of an autonomous pipeline.
- No hook today exposes context usage to programmatic logic.
PreCompactfires too late and gets no token-count payload.
What I want is to fire a hook at 65%, save my memory files (auto-memory dir + Mem0 entries) with full fidelity, write a handoff note, then exit cleanly so a wrapper can spawn a fresh session that reads the handoff and continues.
Proposed shape
// settings.json
{
"hooks": {
"OnContextThreshold": [{
"threshold": 0.65, // fires once when crossed
"command": "bash ~/.claude/handoff.sh"
}]
}
}
Hook input (stdin JSON):
{
"tokens_used": 130000,
"tokens_remaining": 70000,
"percent": 0.65,
"session_id": "...",
"transcript_path": "..."
}
Multiple thresholds should be allowed (e.g., 65% warn, 85% hard-stop).
Why this is broadly useful
- Long-running agentic pipelines (autonomous builds, monitoring loops, multi-stage refactors)
- Context-budget enforcement in CI/CD-style Claude Code usage
- Graceful handoff between sessions without relying on auto-compaction quality
- Pairs naturally with the existing memory/Mem0 ecosystem — finally lets persistence be triggered by time-to-overflow instead of guesswork
What exists today doesn't cover this
- \
PreCompact\hook → fires too late, no token data in payload - Statusline → rendered for the user, not piped anywhere programmable
- \
/context\slash command → display only, not a trigger - Cowork / \
schedule\routines → external scheduled processes can't read the running session's context % - Wrapper scripts that tail the transcript file → fragile (file size ≠ tokens, no graceful exit signal)
A first-class \OnContextThreshold\ hook would unlock a clean primitive that today requires brittle wrappers.
Workaround I'm using meanwhile
Wrapper script that estimates tokens from transcript file size + a CLAUDE.md rule telling the model to self-check \/context\ every ~20 turns and write a handoff if over threshold. Both are heuristic.
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗