moyu12-ae f4eee4e3a5 feat(cache): multi-level compaction thresholds and CCH optimization
Implement 6 cache optimization improvements inspired by Reasonix:

1. **CCH attribution header**: Disabled by default to prevent per-turn
   cache invalidation. The `x-anthropic-billing-header` was embedded in
   `system[0]` of every prompt, and its xxHash value changed per-turn,
   causing full cache prefix misses. Users can re-enable via env var
   `CLAUDE_CODE_ATTRIBUTION_HEADER` or GrowthBook flag.

2. **Multi-level percentage compaction thresholds**: Supplement the
   existing fixed 13K buffer with percentage-based levels (75%/78%/80%/
   90%) that work correctly across all context window sizes from 200K
   to 1M+. The fixed buffer remains as "final defense" at 93-98%.

3. **Turn-start token pre-estimation**: Feature-flagged checkpoint
   (`TURN_START_PRE_ESTIMATION`) before API calls to detect when
   context approaches 90% capacity before the passive check catches it.

4. **Cache-aligned compaction**: Already implemented (CacheSafeParams
   in forkedAgent.ts). No changes needed — verified.

5. **Token-based tool result truncation**: `truncateToolResultByTokens()`
   replaces char-based counting with rough token estimation for CJK-
   aware truncation at clean line boundaries.

6. **Minimum savings check**: `isCompactionWorthwhile()` skips compaction
   when the head portion is less than 30% of the context window,
   preventing waste when the summary costs nearly as much as it saves.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 14:40:16 +08:00
..