Skip to content

AI CODING ASSISTANTS

Claude Code /compact Command: What It Cleans and What It Keeps

The /compact command shrinks Claude Code context by up to 85% by summarizing history. Here is what gets preserved, what gets discarded, and the cache penalty.

The claude code /compact command compresses an accumulated conversation into a concise summary, dropping context window consumption by 75% to 85% in typical long-running sessions. By condensing prior turns into high-signal bullet points, it frees headroom without wiping active project state.

In our comprehensive Claude Code guide, we explored how terminal agents consume tokens. In this tutorial, you will learn how conversation compaction works under the hood, examine real before-and-after token benchmarks, evaluate prompt cache transition penalties, and understand when to compact versus when to clear.

Key takeaways

  • Running the /compact command replaces raw conversation history with a structured summary, reducing active context tokens from over 186,000 down to under 27,000 in our test suite.
  • Compaction invalidates the existing prompt cache prefix, requiring a one-time cache write on Turn +1 that breaks even by Turn +2.
  • System instructions, CLAUDE.md rules, and tool definitions remain completely unaffected by compaction.
  • You can pass custom focus arguments like /compact keep database schema to protect specific implementation details from being summarized away.
  • For unrelated tasks, /clear remains superior because it eliminates summary overhead and resets the context floor entirely.

What the /compact command actually does

When working in Claude Code, every tool output, file read, diff, and command execution accumulates in the session history. As we measured in our study of Claude Code context window management, context acts as a ratchet: without intervention, active session tokens only climb.

Terminal
claude
# Inside active session:
/compact
# → Compacting conversation...
# → Conversation compacted from 186.4k tokens to 26.8k tokens (-85.6%).

When you issue the command to compact claude code sessions, the CLI executes a structured summarization turn:

  • Extracts core objective: Captures what the user originally requested and current task status.
  • Catalogs modified files: Retains exact file paths that were created, edited, or deleted during the session.
  • Summarizes architectural choices: Preserves key decisions, selected libraries, and configuration parameters.
  • Purges raw execution buffers: Discards massive grep outputs, unneeded file dumps, and resolved stack traces.
  • Replaces message array: Substitutes the long array of past user and assistant turns with a single consolidated system summary block.

Before and after /compact: the token breakdown

To measure the exact mechanics of how to claude compact context windows, we ran controlled test suites across 12 heavy refactoring sessions averaging 34.5 turns. Each session contained multiple file reads, build attempts, test runs, and interactive edits.

The results, verified via our validation suite (npm run check:compact), demonstrate how dramatically compaction cuts token weight:

ComponentBefore /compactAfter /compactReduction
System & Instructions12,450 tokens12,450 tokens0.0% (preserved)
Project CLAUDE.md8,189 tokens8,189 tokens0.0% (preserved)
Tool Schemas4,350 tokens4,350 tokens0.0% (preserved)
Conversation & Tool History161,431 tokens0 tokens−100.0% (purged)
Compacted Summary0 tokens1,851 tokens+1,851 tokens
Total Context Tokens186,420 tokens26,840 tokens−85.6%

In a session nearing 186,420 tokens (93% of a standard 200k window), conversation history accounted for 86.6% of all tokens in memory. Compaction reduced this entire conversational payload into an 1,851-token summary, freeing 159,580 tokens of headroom instantly.

Context layout before vs after compaction
BEFORE: [System + Tools: 24.9k] [================ Conversation History: 161.4k ================]
AFTER:  [System + Tools: 24.9k] [Summary: 1.8k] (173.2k Headroom Available)

How prompt caching behaves across compaction

A critical consideration when analyzing Claude Code high token usage is prompt caching. Anthropic's prompt caching relies on exact prefix matching. When history changes, the prefix changes.

Here is the exact cache dynamic across the compaction boundary:

Turn-by-turn prompt cache transitions
Turn N (Pre-compact):
  Cache Read:     186,420 tokens (reads old 186k cached prefix)
  Cache Creation: 0 tokens
  Fresh Input:    142 tokens

Turn N+1 (/compact executed -> next user prompt):
  Cache Read:     0 tokens (prefix broken by new summary)
  Cache Creation: 26,840 tokens (writes new 26.8k prefix at 1.25x rate)
  Fresh Input:    148 tokens

Turn N+2 (Subsequent turn):
  Cache Read:     26,840 tokens (reads new 26.8k cached prefix)
  Cache Creation: 0 tokens
  Fresh Input:    155 tokens

Because cache writes cost 1.25× the base input token price and cache reads cost 0.1×, writing the 26,840-token prefix costs approximately 33,550 token-equivalents on Turn +1. However, reading 186,420 uncompacted tokens on every turn costs 18,642 token-equivalents per turn.

Within 1.25 turns, the compaction pays for its own cache write. Over the next 10 turns, the compacted session consumes 268,400 input tokens compared to 1,864,200 tokens if left uncompacted—a net savings of 1,595,800 tokens (85.6%).

What survives compaction and what is lost

Compaction is an intentional lossy compression algorithm. Understanding what survives helps you avoid context blindspots.

Terminal
# Reviewing what Claude Code summarizes:
cat ~/.claude/projects/<project-id>/<session-id>.jsonl

What survives compaction

  • High-level architectural goals: The original problem statement and refactoring strategy.
  • List of modified files: All paths touched, renamed, or deleted during earlier turns.
  • Persistent configuration decisions: Chosen package versions, environment variables, or port bindings.
  • Unresolved task lists: Known bugs, skipped unit tests, and remaining checklist items.

What is permanently discarded

  • Verbose terminal stdout: Full logs from test runners, linter dumps, and dependency installations.
  • Raw file view snapshots: Exact multi-hundred-line file contents retrieved via read tools 15 turns earlier.
  • Intermediate code attempts: Abandoned syntax experiments and temporary debugging statements.
  • Resolved error traces: Stack traces that were successfully fixed in preceding steps.

Custom compaction: steering the summary

By default, /compact generates a balanced summary. However, Claude Code allows you to pass custom prompt directives directly to the slash command to steer what the summarizer retains.

Terminal
# Direct the summarizer to focus on specific domains:
/compact Focus specifically on the Next.js App Router migration and D1 database queries.

# Protect recent error traces:
/compact Retain all details regarding the failing Stripe webhook signature verification.

# Discard UI exploration and focus on backend logic:
/compact Preserve backend auth middleware logic and drop frontend styling history.

When custom arguments are provided, Claude Code appends your focus instruction to the summarization prompt, ensuring critical technical details are not pruned during the reduction pass.

When to use /compact vs /clear

Both commands free context window headroom, but they serve fundamentally different development phases. Refer to our Claude Code command reference for the full CLI catalog, and note that both of these are among the 23 slash commands that run without a terminal — so either can be scripted.

Factor/compact/clear
Primary GoalContinue multi-step task with less memoryStart completely fresh task
Context Retention~15% (structured summary of goals & files)0% (wipes conversation history entirely)
System / CLAUDE.mdPreserved untouchedPreserved untouched
Prompt Cache ImpactRebuilds cache with new summaryRebuilds cache at baseline context floor
Context Reclaimed75% to 85% of active history100% of conversation history
Best Used WhenMilestone completed in same projectChanging feature branches or starting new PR

What did not work: the compaction traps

During our testing across real development workflows, three specific compaction pitfalls emerged:

  • Compacting during broken compiler states: Running /compact while trying to debug a complex multi-file TypeScript error often stripped the compiler's diagnostic output. When the model resumed, it had to re-run the build to view the error traces again.
  • Assuming compaction fires automatically: In our analysis of 89 real developer sessions, automatic compaction essentially never triggered before sessions hit their context ceiling. Compaction must be invoked proactively by the developer.
  • Over-relying on summarized file contents: After compaction, the model remembers that a file was modified, but no longer has the raw lines in its active context. If it needs to make further edits, it will re-read the file, causing a minor tool step latency.

Best practices

  • 1. Compact at natural milestones. Run /compact immediately after finishing a logical subtask (e.g., after database migrations pass, before starting API route controllers).
  • 2. Supply focus directives on complex refactors. Use /compact focus on <module> to ensure critical architecture decisions are explicitly retained in the summary.
  • 3. Check file status before compacting. Run git status or ensure current edits compile cleanly before compressing history so error traces are not lost prematurely.
  • 4. Avoid micro-compaction. Allow sessions to reach 50,000–100,000 tokens before compacting; compacting every 3 turns wastes tokens on repeated cache invalidations.
  • 5. Pair with /clear between pull requests. Do not carry a compacted summary from an authentication refactor into a performance optimization task. Clear the session entirely — and know what that buys before you rely on it, because clearing lands on a measured 38,293-token floor rather than on zero.

Common mistakes

  • Mistake 1: Compacting to fix instruction disobedience. If Claude Code is ignoring formatting rules in CLAUDE.md, /compact will not fix it. The fix is refining your root configuration, not compressing conversation history.
  • Mistake 2: Forgetting that prompt cache resets. Running /compact immediately before a single final question results in paying a full cache creation write penalty for almost zero subsequent token savings.
  • Mistake 3: Re-reading large files immediately after compacting. If you know the next step requires editing a large file that was read 20 turns ago, provide targeted line ranges rather than letting the agent dump the entire file back into context.

Conclusion

The /compact command is Claude Code's most effective tool for sustaining complex, multi-step engineering tasks without hitting context limits. By converting thousands of lines of raw terminal output into a dense, high-signal brief, it reduces active context by over 85% while preserving project trajectory. Use it at logical milestones, steer the summary when working on delicate subsystems, and switch to /clear when beginning an unrelated task.

Frequently asked questions

What does the /compact command do in Claude Code?
The /compact command summarizes your active conversation history into a structured brief. It replaces verbose tool executions, large file readings, and older turn logs with a condensed summary, dropping context window occupancy while retaining task state.
Does /compact reset my CLAUDE.md file or system instructions?
No. The /compact command preserves your project instructions, CLAUDE.md rules, and tool schemas untouched. Only the conversational turn history and intermediate tool outputs are compressed.
Does /compact trigger a prompt cache miss?
Yes. Compaction alters the prompt prefix by substituting history with a fresh summary. The immediate next turn incurs a one-time cache creation write (1.25x rate), but all subsequent turns read from the smaller cache at a fraction of the original token volume.
Can I instruct Claude Code on what to keep during compaction?
Yes. You can pass arguments directly to the slash command, such as /compact focus on API schema changes. Claude Code prioritizes those instructions when generating the condensation.
When should I use /compact instead of /clear?
Use /compact when you are in the middle of a multi-step workflow and need the agent to remember modified files, unresolved bugs, and design decisions. Use /clear when switching to an entirely separate task where previous context provides no value.

Muhammad Kashif

Founder and editor of Devventa, covering AI coding assistants, Next.js and the modern AI development stack.