[BUG] Auto-compaction cannot prevent context overflow from atomic background agent result injection
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
Auto-compaction triggers when context usage exceeds a threshold (e.g., CLAUDE_AUTOCOMPACT_PCT_OVERRIDE). However, when a background agent completes and its result is injected into the main context, no pre-injection compaction check occurs. The entire agent output (potentially 50-100K tokens) is injected atomically in a single turn, pushing context directly from ~75% to 100%+ — bypassing compaction entirely.
This is related to but distinct from #52390 (AUTOCOMPACT_PCT_OVERRIDE not triggering). Even if autocompact fires correctly at the threshold, it cannot prevent overflow from a single oversized injection because compaction only runs between turns, not during a turn.
The key insight: normal conversation grows context incrementally (small steps between turns), giving compaction a chance to intervene. Background agent results grow context atomically (one large injection within a turn), giving compaction no opportunity.
What Should Happen?
Before injecting any background agent result into the main context, the system should:
- Estimate the token count of the incoming result
- 2. Check if injection would exceed the autocompact threshold
- 3. If yes, run compaction FIRST to free up space
- 4. After compaction, check again — if still too large, truncate the result
- 5. Only then inject the result
This ensures compaction always runs BEFORE oversized content arrives, not after.
Error Messages/Logs
Steps to Reproduce
- Set CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=80
- 2. Use context until ~75%
- 3. Launch a background agent that returns ~50K tokens of output
- 4. Agent completes — its result is injected, pushing context from ~75% to ~100%
- 5. Autocompact never ran because the injection happened atomically within a single turn
Claude Model
Not sure / Multiple models
Is this a regression?
No, this never worked
Last Working Version
_No response_
Claude Code Version
2.1.177
Platform
Anthropic API
Operating System
macOS
Terminal/Shell
Terminal.app (macOS)
Additional Information
See companion issue #68582 for the broader context overflow problem. This issue focuses specifically on the compaction timing gap.
Related: #52390, #53065, #17208
This issue has 1 comment on GitHub. Read the full discussion on GitHub ↗