OpenProgram Docs

Claude Code compaction

Research note, not an OpenProgram design. Only a single compact mechanism (over a token threshold, LLM summary) is in Anthropic's API docs. The cascade below is a client implementation detail from third-party reverse engineering, following Inside Claude Code; sources differ slightly on order, and numbers vary by version.

TierActionTriggerLLMBreaks cacheLoses
Budget Reduction (routine, outside the cascade)Truncate one oversized outputA tool_result over 4000 charactersNoNoMiddle
1 MicrocompactClear old tool outputs50 tool calls, then every 25; or 90 minutes idleNoCache-aware: noOld outputs
2 SnipDelete oldest turnsStill over after 1NoYesWhole turns
3 Context CollapseSegmented summariesStill over after 2, about 90%YesYesDetail
4 Auto-CompactFull summaryStill over after 3, or /compactYesYesMost; a digest stays
5 ReactiveEmergency compactionAPI returns 413 prompt_too_longYesYesAs tier 4

Before every LLM call: Budget Reduction, then check from tier 1; after each tier recheck and advance if still over. On a 413, tier 5 and retry; terminate on failure. Tiers 3 and 4 are described as overlapping strategies: some configurations skip 3, and /compact skips 1–3.

Principles

PrincipleMeaning
Lazy degradationCheapest first
Old tool outputs firstOld grep, read and bash outputs are the largest and least important
Microcompact carries daily useSnip and Compact rarely run
Cache protectionCache-aware clears on the server; content is fixed after truncation
Whole turns onlyUser and assistant messages are never truncated individually: a whole turn is deleted or summarized
CLAUDE.mdReloaded from disk, never compacted
User leads/compact and /context; automatic is the fallback

Tier detail

Budget Reduction

Tool outputs only. Over 4000 characters (about 1000 tokens): keep the first 2400 and last 1600.

Before (50000 chars): "src/a.py:12: TODO fix this\nsrc/b.py:34: ..."
After  (4000 chars):  "src/a.py:12: TODO fix this\n...[46000 chars removed]...\nsrc/z.py:99: TODO cleanup"
Tier 1 Microcompact

Processes FileRead, Shell, Grep, Glob, WebSearch, WebFetch, FileEdit, FileWrite.

Cache-aware (primary)Time-based (fallback)
ActionServer clears old tool_result through the Context Editing APIClient replaces it with a sentinel
Breaks cacheNoYes
Trigger50 calls, every 25Idle about 90 minutes
RecoverableNoNo
NeedsAnthropic Context Editing; other providers have no equivalentNothing
Each output becomes0 tokensAbout 20 tokens: [content no longer available]

Content already in cache is cleared by the server; content not in cache is replaced by the client. Sentinels use a byte-stable canonical form, so repeats do not change cached content. Example: clearing 10 results averaging 500 tokens frees about 4800.

Context Editing API

Public beta (context-management-2025-06-27), not exclusive to Claude Code; merged into a normal call. The client sends unmodified history plus cache_edits; the server replaces old blocks inside the cache, the prefix stays valid, and the client need not know which were cleared. Tiers 2–5 edit the client's message list instead.

StrategyEffect
clear_tool_usesClears old tool_result, keeps the most recent N (N unconfirmed)
clear_thinkingClears old thinking blocks
clear_at_leastMinimum tokens to clear
Tier 2 Snip
  • Trigger: still over after tier 1 (a buffer of about 13K tokens is reported; varies by version).
  • Deletes whole turns (user, assistant and all tool calls), oldest first, recounting after each, until under the threshold.
  • No summary, no disk copy, no marker; the model does not know what was discussed.
  • Total loss and a broken cache prefix, but free and fast.
Tier 3 Context Collapse
  • Trigger: still over after tier 2, about 90% non-blocking, forced and blocking at 95%.
  • Segments of 5–10 turns (unconfirmed), each summarized independently in about 100–300 tokens (estimated). LLM calls equal segments. The most recent N turns stay whole (N unconfirmed).
  • Originals stay in the collapse store: a read-time projection, like a database view, so rollback is possible in theory.
  • Keeps segment boundaries and timeline; tier 4 does not.
Before (35 turns):
[turns 6-10] read code, find bug, fix, test
[turns 11-15] refactor config module
[turns 16-35] modify API module...

After:
[summary] "Turns 6-10: fixed a bug in utils.py, added a rollback script"
[summary] "Turns 11-15: refactored the config module, extracted the Settings class"
[turns 16-35] ... (kept in full)
Tier 4 Auto-Compact
  • One LLM call summarizes the whole history into a block of about 2000–5000 tokens, replacing old messages with no rollback. The latest 1–2 turns stay whole. Context falls from 70–90% to about 15–25%.
  • Threshold override: CLAUDE_AUTOCOMPACT_PCT_OVERRIDE.
  • /compact or /compact keep the discussion about database migration: a prompt improves the summary. Officially recommended at 60%.
  • Lost: early instructions, design discussions, reasoning, code from 50+ turns ago, style preferences. Kept: current task, recently modified filenames, recent errors and fixes, CLAUDE.md.
  • Chained: each pass compacts the previous summary, so information decays. A long session may compact 3–5 times.
  1. Run PreCompact hooks.
  2. Build the prompt with getCompactPrompt().
  3. Send the whole history to the LLM.
  4. Build messages with buildPostCompactMessages().
  5. Reload the system prompt from CLAUDE.md.
Before (35 turns, 150K tokens): [system prompt] [35 turns]
After (~30K tokens):
[system prompt] (reloaded from CLAUDE.md)
[compaction block]
"Session summary: The user is refactoring a Python project.
Completed: fixed a bug in utils.py, refactored the config module, added 3 tests.
Current state: all tests pass. The user is working on the API module.
Key decisions: replace Flask with FastAPI, use PostgreSQL for the database.
Modified files: src/utils.py, src/config.py, tests/test_utils.py"
[most recent 1-2 turns]
Tier 5 Reactive

Tries context-collapse overflow recovery, then an emergency compact, at most once per turn. If both fail, the session ends.

A long session, 200K context
ContextWhat runs
0–30%Budget Reduction only
30–50%Past 50 tool calls, Microcompact clears the first 30 outputs, about 15K tokens, then every 25
Over thresholdMicrocompact is not enough; Snip deletes the oldest 5 turns, about 25K tokens
Over againMicrocompact and Snip repeat
Extreme and rareFew old turns remain, so Context Collapse, then Auto-Compact
Sources, most reliable first
Last updated · 2026-11-25