[Feature] Graceful context compaction — PreCompact hook data + background compaction option
Problem
Context compaction is currently a hard wall — a synchronous operation that pauses the session, lossy-compresses the conversation history, and resumes with degraded context. For long sessions (200+ tool calls), this happens multiple times and each compaction loses nuance, reasoning chains, and momentum.
The PreCompact hook type exists (thank you!) but fires with minimal data — there's no way to know:
- How much context is about to be compacted
- What the estimated post-compaction size will be
- Which messages/tool outputs are being dropped vs preserved
Proposed Enhancements
1. Enriched PreCompact hook data
Currently the PreCompact hook receives minimal context. Enriching it would enable intelligent pre-compaction strategies:
{
"hook": "PreCompact",
"context_tokens_before": 180000,
"context_tokens_after_estimate": 60000,
"messages_count": 142,
"tool_calls_count": 87,
"compaction_reason": "context_limit"
}
This lets hooks serialize critical state before the lossy compression occurs.
2. Expose context utilization to hooks
A context_utilization_pct field in all hook events (PostToolUse, UserPromptSubmit, etc.) would enable proactive context management — users could build systems that checkpoint, offload, or restructure context BEFORE hitting the wall.
3. Background / incremental compaction (longer term)
Instead of one catastrophic compaction at the limit, compact incrementally:
- Rolling window: after every N tool calls, summarize the oldest 20% of context
- Recent messages stay at full fidelity, older ones degrade gracefully
- The "wall" becomes a gentle slope
This is analogous to log-structured merge trees in databases — recent data is hot, old data is progressively compacted.
Use Case
We run a production AI operations platform with 25+ hooks, baton-based session continuity, and a context governor that monitors pressure levels. We've built workarounds (PreCompact snapshot hooks, observation masking, relay batons) but they're fighting the system instead of working with it. Enriched PreCompact data would let our existing infrastructure work WITH Claude Code's compaction rather than guessing when it's about to fire.
Current Workaround
We monitor context pressure via token counting from the active .jsonl transcript, fire relay baton checkpoints at 60% and 70% thresholds, and use a PreCompact hook to create emergency snapshots. This works but is fragile — the token count heuristic doesn't always match Claude Code's internal measurement, so we sometimes miss the window.
---
Built from daily production usage on Claude Code Max. The context wall is the single biggest friction point in long autonomous sessions.
This issue has 8 comments on GitHub. Read the full discussion on GitHub ↗