跳到主要内容

Long Conversation Context Compaction

As conversations grow, the message list approaches the model's context window limit. Claude Code uses multi-layer compaction strategies to manage context size.

Strategy Overview​

StrategyTriggerMethodImpact
MicrocompactEvery iterationShrink old tool resultsIncremental token reduction
AutocompactToken thresholdFork agent to summarizeMajor token reduction
Force compactStill over limit after normalizeImmediate compactPrevents API errors

Autocompact​

Trigger​

getAutoCompactThreshold() calculates a threshold based on context window size, with buffer to prevent prompt_too_long errors. calculateTokenWarningState() tracks usage.

Compaction Flow​

compactConversation() groups messages by API turns, sends to a forked summarization agent, builds post-compact messages (user summary + compact boundary marker), optionally re-attaches skills/plans/deltas with token budgets, and strips images.

Microcompact​

Lightweight incremental compaction running each iteration without calling LLM. Selectively shrinks whitelisted tool results (Bash, FileRead, etc.), preserving recent results and errors.

Integration with Session Memory​

Compact explicitly integrates with SessionMemory: waits for ongoing extraction to complete, preserves session notes references across compact boundaries, and clears systemPromptSections cache so dynamic prompt pieces refresh.

Key Source Files​

FileResponsibility
src/services/compact/autoCompact.tsAuto-compact triggers and thresholds
src/services/compact/compact.tsCore: compactConversation
src/services/compact/microCompact.tsMicrocompact
src/services/compact/prompt.tsCompact prompt template
src/services/compact/sessionMemoryCompact.tsSession memory integration

Next​

Go to 15-command-system.md to learn about the slash command system.

Hands-on Experiment​

This chapter has a corresponding Python experiment:

Lab 14 — Context Compaction

Covers: microcompact, autocompact, force compact, session memory

cd experiments && python -m exp_14_context_compaction.main --mock