Claude Code Compaction: How Context Compaction Works and How to Avoid It
Claude Code context compaction condenses terminal history, tool results, and bash logs into a summary when sessions approach token limits. While compaction prevents session crashes, it discards intermediate diffs, debug outputs, and path-scoped rules. Controlling compaction with focus prompts, project-root directives, and external MCP storage preserves critical developer context.
The Context Ceiling: How Claude Code Reaches Compaction
Anthropic's documented limits establish that standard Claude chats accept up to 20 files at up to 500MB each, while Claude Projects accept files up to 30MB each with no fixed file count cap, bounded solely by the model's context window per Anthropic file upload documentation. In Claude Code, that boundary is the working memory of your terminal session. Developers executing multi-step refactoring, running local test suites, and inspecting large codebases discover that a 200,000 token context window fills up within hours of active command-line work.
To understand why terminal sessions reach their token boundaries so quickly, developers must track how Claude Code constructs its prompt payload. Unlike browser-based chat interfaces where text turns are brief, Claude Code operates as an autonomous agent. Every tool execution, bash command output, file read, and git diff appends tokens directly to the ongoing context buffer.
The session context window fills from several distinct token consumers:
- System prompts and output styles: Base agent instructions and formatting rules inject thousands of tokens at session startup.
- Project instructions and auto memory: Files like project-root
CLAUDE.md, unscoped rule files, andMEMORY.mdload automatically before you type your first command. - Model Context Protocol (MCP) server schemas: Every connected MCP tool definition exposes its JSON schema to the context window, reserving space for tool definitions.
- Command execution logs: Output from bash commands, test runners, package managers, and compilers streams directly into the message history.
- File content buffers: Viewing source files loads raw code into memory, consuming tokens proportional to file length.
- Git diffs and patch reviews: Tracking unstaged changes and reviewing diffs before commits injects large blocks of code changes.
- Reasoning and conversational history: Previous user queries, agent explanations, and internal planning steps compound across turns.
Claude Code initiates context compaction when approaching the 200,000 token context window boundary (typically at ~80% capacity or 160k tokens). Understanding this Claude compaction limit prevents sessions from exhausting their prompt memory mid-generation, which would otherwise force the developer to discard their work and restart from scratch.
Claude Code compaction is an automated process where Anthropic's terminal agent summarizes prior conversation turns, tool outputs, and bash logs into a condensed context block when approaching token limits.
When compaction occurs, Claude Code executes a structured multi-step sequence to compress the working memory:
- Threshold detection: The runtime monitors cumulative token consumption. When active context reaches the auto-compact threshold, or when a developer explicitly runs
/compact, the system pauses tool execution to start the compaction pass. - Content segmentation: The agent analyzes conversation history, separating permanent project requirements from disposable execution logs such as raw compiler outputs, temporary grep results, and intermediate bash traces.
- Server-side summary generation: Claude generates a structured executive summary that condenses completed steps, active architectural decisions, modified files, and pending objectives into a compact context block.
- Working context reconstruction: The runtime discards raw intermediate message turns, retains the newly generated summary, re-reads up to five recently modified files from disk, re-injects foundational project directives, and resumes the interactive session.
Related guides
- Claude Compaction Failed Unexpectedly: Causes, Fixes, and Context OffloadingClaude Code triggers automated compaction when session context approaches the 200,000-token boundary, summarizing prior...
- Manus AI Agent: Capabilities and How It WorksManus is an autonomous general AI agent that plans, executes, and returns finished work inside a sandbox computer. This...
- Claude Code Message Limit: Quotas, Compaction, and Large-Context WorkaroundsClaude Code message limits define the maximum prompt token size and message frequency allowed in a CLI session before...
- Claude Code Context Window: Managing Token Limits in Terminal AgentsThe Claude Code context window determines how much conversation history, source code, and command output a terminal...
- Claude Code Memory Limits: CLAUDE.md Sizing, Auto-Memory, and Context WorkaroundsClaude Code memory limits represent the size thresholds and retention boundaries governing CLAUDE.md files, persistent...
- Claude Code Session Limit Reached: Causes, Compaction, and WorkaroundsClaude Code session limits occur when cumulative terminal output, command history, and file reads saturate the agent...
More on this subject: Claude and Claude Code (255 guides)
What Survives Compaction and What Gets Lost
Forum discussions frequently recommend running /compact when Claude Code feels sluggish, but few explain the specific information loss that occurs during the summarization pass. Compaction is a lossy operation. Understanding exactly what gets pruned and what persists is necessary for maintaining code correctness during complex refactors, as outlined in the Claude Code context window documentation.
When Claude Code compacts a session, it intentionally discards high-volume, ephemeral data:
- Intermediate bash outputs: Verbose test results, linter reports, and package installation logs vanish. If Claude resolved a subtle dependency conflict or compiler error ten turns earlier, the exact error trace disappears from memory.
- Multi-turn diff histories: Claude retains the final state of code written to disk, but the chronological sequence of trial-and-error attempts, intermediate patches, and discarded implementations is purged.
- Path-scoped rules: Rules defined with
paths:frontmatter and nestedCLAUDE.mdfiles located in subdirectories load into message history only when their target files are modified. Compaction summarizes them away. If you need a rule to stay active permanently across compaction, you must place it in the project-rootCLAUDE.mdor remove itspaths:constraint. - Ephemeral reasoning steps: The exploratory thought process that led to an architectural decision is condensed into a brief factual conclusion, dropping detailed constraints that were not explicitly written down.
Conversely, Claude Code actively protects critical structural components. Anthropic designs the post-compaction context to reconstruct core project state fresh from disk rather than relying on summarized memory:
- System prompt and output styles: The foundational runtime instructions and output formatting rules remain completely intact.
- Project-root
CLAUDE.mdand unscoped rules: These files reload fresh from disk immediately after compaction, preventing rule drift. - Auto memory (
MEMORY.md): Claude's persistent memory file re-injects directly from disk, ensuring cross-session recollections survive. - Git status snapshot: Claude Code executes a fresh
git statuscheck against your local repository, restoring awareness of modified, untracked, and staged files. - Plan mode documents (
PLAN.md): Any task plan or roadmap produced in plan mode reloads fresh from disk. - Recent file re-reads: Right after compaction, Claude Code re-reads up to five of the files Claude has read or edited in the session, choosing the ones modified most recently. However, any file exceeding 5,000 tokens is downgraded to a path reference without its content, marked as
Referenced fileinstead ofRead. - Invoked skill bodies: Active skill instructions re-inject into context, capped at 5,000 tokens per skill and 25,000 tokens total across all skills, with the oldest invoked skills dropped first.
- Running background tasks: Background bash commands and background subagents continue running uninterrupted. Claude Code provides the model with reminders of active task identifiers to prevent duplicate jobs.
The table below details how different context elements behave across a compaction boundary:
Controlling Compaction with Manual Triggers, Focus Prompts, and Rules
Relying solely on automatic compaction introduces operational risk. Because auto-compaction fires only when the context window reaches near-capacity limits, the model must summarize a massive, noisy conversation history all at once. The resulting summary often misses subtle architectural constraints while retaining irrelevant debugging chatter.
Developers can take control of the compaction lifecycle using three built-in mechanisms: manual slash commands, custom focus prompts, and permanent configuration rules.
The primary manual control is the /compact command. Running /compact allows you to trigger summarization at a logical milestone, such as immediately after finishing a sub-feature, resolving a major bug, or running a large test suite. This cleans your prompt buffer while your recent technical accomplishments are distinct and easy to summarize.
To prevent the summarizer from discarding critical context, you can append focus instructions directly to the command:
/compact Focus on the authentication refactor and database schema migration. Discard test failure logs and curl outputs.
Using a tailored Claude Code compact prompt guides the summarization model to prioritize your specified topics, preserving exact function signatures, interface changes, or upcoming implementation steps.
You can also establish permanent compaction directives inside your project-root CLAUDE.md file. By defining standard compaction expectations in version control, you ensure every compaction pass, whether triggered manually or automatically, respects your project boundaries:
Project Compaction Directives:
When compacting session history, always preserve:
1. The list of modified API endpoints and exported TypeScript interfaces.
2. The active database migration sequence and applied schema changes.
3. Unresolved edge cases identified during code review.
4. Next implementation steps outlined in the active sprint task.
Discard raw compiler dumps, standard output from test runners, and ephemeral package installation logs.
For developers who prefer predictable context buffers, Claude Code supports tuning the auto-compaction threshold via the /autocompact command or environment variables, as described in the Claude Code model configuration guide. Running /autocompact 160k sets the automatic trigger to run whenever context hits 160,000 tokens, leaving a 40,000 token buffer for complex generations. You can also export CLAUDE_CODE_AUTO_COMPACT_WINDOW=160000 in your shell profile to apply this boundary across all projects.
If you discover that recent conversational turns contain unnecessary noise, you can use /rewind instead of full compaction. The /rewind command allows you to select a specific point in the session history and choose Summarize from here or Summarize up to here, giving you surgical control over which conversation spans are compressed.
Keep Agent Reference Docs Out of Claude's Context Window
Store large schemas, API specs, and project docs in an indexed Fast.io workspace. Connect Claude Code over MCP so your agent queries only what it needs, keeping the context window lean. Monthly plans start with a 14-day free trial.
Architectural Workflows to Prevent Unnecessary Compaction
Frequent compaction is a symptom of an underlying workflow issue: treating the agent's context window as an active file storage drive. A 200,000 token context window corresponds to roughly 150,000 words or 600KB of raw text. When developers ask Claude Code to inspect entire documentation directories, third-party SDK source trees, or large log archives, the window saturates within minutes.
To prevent continuous compaction cycles, teams implement three architectural patterns that keep the primary context window lean:
First, delegate large file reads and exploratory searches to subagents. Claude Code supports launching subagents to execute auxiliary tasks in isolated context windows. When an agent needs to scan forty test files to identify flaky assertions, running that investigation inside a subagent keeps the thousands of lines of code and execution output inside the subagent's temporary context. Only the concise final summary returns to your main session.
Second, persist mutable state to dedicated markdown files rather than keeping state in conversation history. If you discuss design trade-offs, architecture decisions, or sprint roadmaps in plain chat, that context degrades once compaction runs. Writing those decisions to disk in files like DECISIONS.md or TODO.md preserves them across sessions, because project files on disk reload fresh after compaction.
Third, isolate large reference materials from the local file system. Software projects frequently rely on large external assets: third-party API specifications, OpenAPI JSON definitions, compliance documentation, database schemas, and architectural guidelines. Placing these documents inside the local repository causes file search tools (grep, find, glob) to index and load them into context repeatedly.
Developers typically manage these external reference corpora across three storage tiers:
- Local project directories: Simple to set up, but file exploration tools inadvertently read large files into context, triggering premature auto-compaction.
- Raw object storage (AWS S3, Google Cloud Storage): Decouples files from the local repository, but lacks semantic indexing, forcing agents to download entire multi-megabyte files locally before reading them.
- Traditional cloud storage (Google Drive, Dropbox, Box, OneDrive): Synchronizes team documents, but offers no native agent integration or granular token-level excerpting for command-line coding assistants.
The sustainable pattern is connecting Claude Code to an external intelligent workspace that indexes technical documentation in the cloud and serves precise excerpts over the Model Context Protocol. For teams looking to organize their setup, explore how storage for agents solves context exhaustion.
Offloading Reference Corpora to Fast.io via the MCP Server
The most effective way to eliminate context compaction caused by reference documents is to move those files into a shared Fast.io workspace. Instead of attaching large files or forcing Claude Code to read 10,000-token specification sheets into its 200,000 token working memory, the agent accesses an indexed external workspace through the Fast.io remote MCP server.
Fast.io workspaces provide native Intelligence Mode, which automatically indexes uploaded files for hybrid search combining semantic meaning, full-text keyword matching, and metadata filtering. When Claude Code needs an answer from an API manual, database architecture guide, or vendor contract, it queries Fast.io over MCP. The server returns only the specific 200-token passage required to complete the task, leaving nearly the entire context window free for actual code generation.
Connecting Claude Code to Fast.io takes less than two minutes using Streamable HTTP. In your terminal, run:
claude mcp add --transport http fast-io https://mcp.fast.io/mcp/code
Once added, start Claude Code and run /mcp to authenticate via browser OAuth. The OAuth authorization screen allows you to select which organizations and workspaces Claude Code can access, with either Read Only or Read & Write permissions. Full setup instructions are documented on the Fast.io MCP setup guide, while developer tools are detailed in the Fast.io MCP documentation and agent onboarding guide.
For teams sharing project configurations in version control, you can define the MCP connection directly in your repository's .mcp.json file:
{
"mcpServers": {
"fast-io": {
"type": "http",
"url": "https://mcp.fast.io/mcp/code"
}
}
}
On the /mcp/code endpoint, Claude Code interacts with a consolidated MCP toolset designed for coding agents: auth, auth_manage, upload, upload_manage, search, execute, execute_manage, and how-to. The agent calls search to run semantic queries across your indexed workspaces, extracting exact technical requirements without pulling full files into its terminal buffer. Writes and modifications are handled safely through execute_manage.
Teams with documentation dispersed across existing storage platforms can connect their folders directly. Cloud Sync connects Google Drive, Dropbox, Box and OneDrive folders to a workspace, one-way or two-way, on a schedule or on demand. Reference manuals and project briefs sync into Fast.io, where Intelligence Mode automatically indexes them for Claude Code access.
Beyond context reduction, Fast.io provides persistent collaboration infrastructure for engineering teams. Every file maintains a per-file version history, allowing developers to review edits or revert modifications made during automated agent runs. Changes are tracked in a detailed activity log that records uploads, edits, moves, and permission updates. Team members can also leave Collaborative Notes directly beside files, giving human developers and AI agents a shared notebook for ongoing work.
Monthly plans start with a 14-day free trial, which requires a credit card; annual plans start paid with no trial. Creating an account is free; doing real work requires an organization on a paid subscription. Plans are Starter at $9.99/mo, Business at $49.99/mo, and Enterprise at $199.99/mo on the Fast.io pricing page. Offloading reference materials to an external indexed workspace protects your agent's context window, eliminates repetitive compaction cycles, and keeps terminal sessions fast.
Sources
References used to verify factual claims in this guide.
-
Claude Projects accept files up to 30MB each with no fixed file count limit, bounded only by the context window, while chat uploads allow up to 20 files at 500MB each.
-
Right after compaction, Claude Code re-reads up to 5 recently modified files, falling back to a path reference if a file exceeds 5,000 tokens, preserving core instructions while managing context limits up to 80% capacity or 200,000 tokens.
Frequently Asked Questions
What does /compact do in Claude Code?
/compact summarizes previous conversation turns, tool results, and bash command logs into a condensed state block. It reduces token consumption in long terminal sessions while keeping your active working directory, project rules, and immediate coding objectives.
When does Claude Code trigger auto-compaction?
Claude Code triggers auto-compaction when active session history approaches the model's context window limit, typically at roughly 80% capacity (around 160,000 tokens on a standard 200,000 token window). You can customize this threshold using the /autocompact command or the CLAUDE_CODE_AUTO_COMPACT_WINDOW environment variable.
How can I prevent Claude Code from losing context during compaction?
To prevent context loss during compaction, place permanent architectural rules in your project-root CLAUDE.md, write active plans to files like PLAN.md on disk, and run /compact manually with custom focus instructions before auto-compaction triggers. For large technical manuals or API specs, store documents in an external indexed Fast.io workspace and query them over MCP so raw reference texts never enter the conversational context.
What is the difference between /compact and /clear in Claude Code?
The /compact command summarizes existing conversation history to reclaim token space while maintaining ongoing project continuity. The /clear command resets the session entirely, wiping all conversation history and starting from a blank prompt buffer.
How does Claude Code handle large files after compaction?
Right after compaction, Claude Code re-reads up to five recently modified files. If a file contains more than 5,000 tokens, Claude Code avoids loading its full text back into the context window, storing it as a path reference instead.
Can I customize what Claude Code preserves during automatic compaction?
Yes, you can add explicit compaction directives to your project-root CLAUDE.md under a dedicated compaction instructions section. Claude Code incorporates these directives when constructing its summary during both automatic compaction and manual /compact passes.
Related Resources
Keep Agent Reference Docs Out of Claude's Context Window
Store large schemas, API specs, and project docs in an indexed Fast.io workspace. Connect Claude Code over MCP so your agent queries only what it needs, keeping the context window lean. Monthly plans start with a 14-day free trial.