# 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.

| Tier | Action | Trigger | LLM | Breaks cache | Loses |
| --- | --- | --- | --- | --- | --- |
| Budget Reduction (routine, outside the cascade) | Truncate one oversized output | A `tool_result` over 4000 characters | No | No | Middle |
| 1 Microcompact | Clear old tool outputs | 50 tool calls, then every 25; or 90 minutes idle | No | Cache-aware: no | Old outputs |
| 2 Snip | Delete oldest turns | Still over after 1 | No | Yes | Whole turns |
| 3 Context Collapse | Segmented summaries | Still over after 2, about 90% | Yes | Yes | Detail |
| 4 Auto-Compact | Full summary | Still over after 3, or `/compact` | Yes | Yes | Most; a digest stays |
| 5 Reactive | Emergency compaction | API returns 413 `prompt_too_long` | Yes | Yes | As 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

| Principle | Meaning |
| --- | --- |
| Lazy degradation | Cheapest first |
| Old tool outputs first | Old grep, read and bash outputs are the largest and least important |
| Microcompact carries daily use | Snip and Compact rarely run |
| Cache protection | Cache-aware clears on the server; content is fixed after truncation |
| Whole turns only | User and assistant messages are never truncated individually: a whole turn is deleted or summarized |
| `CLAUDE.md` | Reloaded 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) |
| --- | --- | --- |
| Action | Server clears old `tool_result` through the Context Editing API | Client replaces it with a sentinel |
| Breaks cache | No | Yes |
| Trigger | 50 calls, every 25 | Idle about 90 minutes |
| Recoverable | No | No |
| Needs | Anthropic Context Editing; other providers have no equivalent | Nothing |
| Each output becomes | 0 tokens | About 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.

| Strategy | Effect |
| --- | --- |
| `clear_tool_uses` | Clears old `tool_result`, keeps the most recent N (N unconfirmed) |
| `clear_thinking` | Clears old thinking blocks |
| `clear_at_least` | Minimum 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**

| Context | What 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 threshold | Microcompact is not enough; Snip deletes the oldest 5 turns, about 25K tokens |
| Over again | Microcompact and Snip repeat |
| Extreme and rare | Few old turns remain, so Context Collapse, then Auto-Compact |

**Sources, most reliable first**

- [Compaction, Claude Platform Docs](https://platform.claude.com/docs/en/build-with-claude/compaction) (official, API level only)
- [Context editing, Claude API Docs](https://platform.claude.com/docs/en/build-with-claude/context-editing) (official)
- [Inside Claude Code: Context Compaction](https://y-agent.github.io/inside-claude-code/04-compaction-diagram.html) (reverse engineering, most detailed)
- [Dive into Claude Code](https://arxiv.org/html/2604.14228v1) (arXiv 2604.14228, VILA-Lab)
- [DeepWiki: Context Window and Compaction](https://deepwiki.com/anthropics/claude-code/3.3-context-window-and-compaction) (community)
- [Claude Code VS OpenCode §5.3](https://0xtresser.github.io/Claude-Code-VS-OpenCode/en/Chapter_05_Session_and_Context/5.3_Context_Compaction.html) (comparison)
