Guide
Managing context in a long Claude Code session
Anthropic's own best-practices page opens by naming the constraint everything else follows from: "Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills." Not rate limits, not model choice, not prompt phrasing. The window. Everything you notice in hour three of a session — the agent re-reading a file it already read, forgetting a convention you stated at the start, re-proposing an approach you rejected twice — is that constraint expressing itself.
This is the practical guide to keeping a session useful past the first hour: where the tokens
actually go, what /compact and /clear each do, what compaction quietly
throws away, and the structural habit that beats all of the tactics. Everything below was checked
against the Claude Code documentation on August 2, 2026, against release
2.1.220 (25 July 2026, the current release that day). Where the docs decline to
give a number, so do I.
Where the tokens actually go
Anthropic publishes an interactive walkthrough of a full session, from launch to compaction, with representative token counts attached to every event. It is the single most useful page for building intuition here, and it produces a breakdown most people guess wrong. The session runs 22,225 tokens end to end:
| What | Tokens | Share | Visible to you? |
|---|---|---|---|
| System prompt | 4,200 | 19% | Never |
| Project CLAUDE.md | 1,800 | 8% | Never |
| Auto memory, env info, skill list, MCP tool names, global CLAUDE.md | 1,850 | 8% | Never |
| File reads (4 files) | 6,900 | 31% | One line each |
| Claude's own responses and diffs | 3,480 | 16% | Yes |
Command + search output (grep, npm test) | 1,800 | 8% | A summary line |
| Path-scoped rules, hook output, one invoked skill | 1,510 | 7% | A "loaded" notice |
| Subagent's returned summary | 420 | 2% | Yes |
| Your prompts | 265 | 1% | Yes |
Three things fall out of that table. First, you pay roughly 7,850 tokens before you type
anything — a floor set by your configuration, not your task. Second, file reads
dominate the working portion: 6,900 tokens across four files, about half of everything
added after startup. Anthropic's own tip on that line reads "File reads dominate context
usage. Be specific in prompts so Claude reads fewer files." Third, almost none of it is
visible in your terminal. A Read src/api/auth.ts line takes one row of your screen
and 2,400 tokens of the window.
These are representative numbers from a simulation, not a measurement of your repo. For your
actual session, run /context — it prints a live breakdown by category with
optimization suggestions, including which CLAUDE.md and auto-memory files loaded. Pass
/context all for the per-item expansion. It is the first command to reach for when a
session starts feeling stupid.
The two categories people misjudge
MCP tool schemas used to be the classic context sink, and mostly aren't any more.
Tool search is on by default: MCP tool definitions are deferred rather than loaded upfront, so
only tool names and server instructions cost you anything at startup — 120 tokens in the
walkthrough — and full schemas load on demand when a task needs them. The docs put it plainly:
"adding more MCP servers has minimal impact on your context window." If you have
ENABLE_TOOL_SEARCH=false in your environment, or you're on a custom
ANTHROPIC_BASE_URL that disables it, you are back to paying for every schema on every
request. ENABLE_TOOL_SEARCH=auto is the middle setting: load schemas upfront if they
fit within 10% of the context window, defer the overflow. Run /mcp to see per-server
cost. Our guide to MCP servers in Claude Code covers
the setup side.
What MCP still costs you is results. Claude Code warns when any MCP tool output exceeds
10,000 tokens and caps output at 25,000 tokens by default, raisable with
MAX_MCP_OUTPUT_TOKENS. One chatty database query can be worth four file reads.
Long command output is the category with no documented ceiling. The docs specify
limits for MCP results; I could not find an equivalent documented cap for Bash output, and I am
not going to invent one. Treat it as unbounded and act accordingly: a full test suite in verbose
mode, a docker build log, a thousand-line git log all land in the window
at full size. Ask for npm test 2>&1 | tail -40 rather than
npm test, and grep logs rather than catting them. This is the cheapest habit on the
list and the one most people never adopt.
/compact versus /clear
Two commands, one distinction: continuity.
/compact [instructions] | /clear [name] | |
|---|---|---|
| What it does | Replaces the conversation with a structured summary | Starts a new conversation with empty context |
| Session | Same one, continues | New one; the old is labelled in the /resume picker if you name it |
| Keeps | A model's guess at what mattered | Nothing from the conversation |
| Use when | Same task, out of room | Different task |
| Cost | A summarization round-trip, plus silent losses (below) | Re-establishing context yourself |
The under-used half of /compact is the argument. /compact focus on the auth bug
fix keeps what you choose instead of what the automatic pass guesses is important. If you
are about to compact, you already know which thread matters; spending six words saying so is the
highest-leverage thing you can do at that moment.
Two smaller instruments are worth knowing. /rewind (or a double Esc)
opens the checkpoint menu, which offers Summarize from here and
Summarize up to here — partial compaction, so you can crush a failed
investigation in the middle of a session while keeping the good reasoning on either side of it.
And /btw answers a side question in a dismissible overlay that never enters
conversation history at all, which is the right home for "wait, what does this flag do" detours.
How auto-compaction actually behaves
Here is the honest version, because the internet is full of confidently-stated percentages.
The docs do not publish a fill-ratio threshold. What they publish is a token
window. autoCompactWindow is "how full the context window gets before Claude Code
compacts automatically, in tokens", it accepts 100K to 1M, and you can set it four ways:
/autocompact 500k— saves to user settings and applies to the current session;/autocompact autoreturns to the model-tuned window.claude --autocompact 500k— one launch, does not change your saved setting.autoCompactWindowinsettings.json.CLAUDE_CODE_AUTO_COMPACT_WINDOW— takes precedence over all three, for scripts and cloud environments.
With nothing set anywhere, Claude Code compacts when the conversation reaches the model's context limit — with named exceptions the docs spell out: cloud sessions compact as they approach the limit; Sonnet 4.6 and Opus 4.6 without extended context compact at the 200K boundary, as do Opus 4.8 and Opus 5 when they run in a 200K deployment such as Bedrock or Microsoft Foundry; Sonnet 5 compacts at its own default threshold. So "when does it fire" genuinely depends on your model and where it runs, which is exactly why no single percentage would be true.
The order of operations matters more than the trigger. When the window fills, Claude Code "clears older tool outputs first, then summarizes the conversation if needed." Tool results are the cheap sacrifice; your conversation is the expensive one. And if a single file or tool output is so large that context refills immediately after each summary, Claude Code stops auto-compacting after a few attempts and raises a thrashing error rather than looping — a good signal that something enormous is being pulled into the window on every turn.
You can turn the whole thing off with autoCompactEnabled: false in
settings.json (or DISABLE_AUTO_COMPACT in the environment). I would not,
unless you are deliberately running short sessions and would rather hit a wall than get a summary
you didn't ask for. Which, to be fair, is a defensible way to work.
Why the session sometimes gets worse right after compaction
This is the part nobody warns you about, and it is documented in a table most people never open. Compaction does not restore your session to a clean state. It restores some of it:
| Mechanism | After compaction |
|---|---|
| System prompt and output style | Unchanged — never part of message history |
| Project-root CLAUDE.md, unscoped rules | Re-injected from disk |
| Auto memory | Re-injected from disk |
Rules with paths: frontmatter | Lost until a matching file is read again |
| Nested CLAUDE.md in subdirectories | Lost until a file in that directory is read again |
| The skill listing | Not re-injected — only skills you actually invoked survive |
| Invoked skill bodies | Re-injected, capped at 5,000 tokens per skill and 25,000 total, oldest dropped first |
| Hooks | Unaffected — they run as code, not context |
Read the two bold rows again, because together they explain a very specific failure. Path-scoped
rules and nested CLAUDE.md files enter the conversation as message history when their
trigger file is read — so compaction summarizes them away with everything else. After a compact,
the agent still has your global conventions and has silently lost your local ones.
It knows the repo builds with pnpm; it no longer knows that everything under src/api/
must return a typed error envelope. The first edit after a compact is disproportionately likely to
violate a rule the agent can no longer see, and it will do it with total confidence.
Two mitigations, both cheap. If a rule genuinely must survive compaction, drop the
paths: frontmatter or move it into the project-root CLAUDE.md — the
tradeoff is that it then loads in every session whether or not it is relevant. And because skill
bodies are truncated from the end when they exceed the cap, put the instructions that matter at
the top of a SKILL.md, not the bottom.
You can also steer the summary itself. Add a Compact Instructions section to
CLAUDE.md with something like "When compacting, always preserve the full list of
modified files and any test commands", and it applies to every automatic pass, not just the
ones you remember to type an argument for.
Write a handoff before you compact
Everything above is damage control on a lossy process. The move that changes the outcome is to stop treating the summary as the artifact.
A compaction summary is a model's reconstruction of a transcript. A handoff is your decisions, written down, in a file. The difference shows up on the next window: a summary hands the next context a compressed history of what happened; a handoff hands it the conclusions. One makes the agent re-derive why you rejected the queue-based approach. The other tells it.
So before you compact — or better, before you /clear — spend one turn on this:
Before we run out of room: write HANDOFF.md in the repo root.
- Goal, in one paragraph. What "done" looks like.
- Decisions made, each with the reason. Include what we
rejected and why, so nobody relitigates it.
- Files touched so far, and what changed in each.
- The exact command that verifies this work.
- What is left, in order.
- Traps: things that looked right and weren't.
No transcript. No narration. Someone with zero context
should be able to continue from this file alone.
Then /clear and open the next session with @HANDOFF.md continue from step
3. You have replaced a lossy compression with a lossless one that you can read, edit,
disagree with, and commit. The documented version of this pattern is Anthropic's spec workflow —
interview, write the spec, then "start a fresh session to execute it", because "the new
session has clean context focused entirely on implementation, and you have a written spec to
reference." The advice about what makes a good spec applies verbatim to a handoff:
"self-contained: they name the files and interfaces involved, state what is out of scope, and
end with an end-to-end verification step that proves the feature works."
The habit compounds. A handoff file is also a code-review artifact, a PR description draft, and the thing you read on Monday when you have forgotten the whole shape of Friday's work.
Subagents: the search happens in someone else's window
Subagents get sold on parallelism. The parallelism is real, but it is the second-best reason to use them. The first is that a subagent runs in its own fresh context window, "completely separate from your main conversation. Their work doesn't bloat your context. When done, they return a summary. This isolation is why subagents help with long sessions."
The walkthrough puts a number on it. The research subagent reads session.ts,
timeouts.ts and config/*.ts — 6,100 tokens of files — and returns a
420-token summary plus a small metadata trailer. 6,100 in, 420 out. Had the main
agent done that research inline, those 6,100 tokens would sit in your window for the rest of the
session, and you would still only have used the conclusion.
That is the whole strategy, and it generalises past research. Anything where the process is large and the answer is small belongs in a subagent: find every call site, audit a diff, work out which of four libraries the repo already depends on, read a 900-line config and report the three lines that matter. Anthropic lists the failure it prevents under common failure patterns — "the infinite exploration: you ask Claude to 'investigate' something without scoping it. Claude reads hundreds of files, filling the context."
Two caveats, so this doesn't read as a free lunch. A subagent has its own startup cost — its own
system prompt, its own copy of CLAUDE.md, the same MCP and skill setup — but it pays
that in its window, not yours. (The built-in Explore and Plan agents skip CLAUDE.md
for a smaller footprint.) And a subagent cannot ask you a clarifying question mid-flight, so a
badly scoped brief burns a whole window and returns a confidently wrong paragraph. Write the brief
like you would write a ticket.
CLAUDE.md is in every single request
In the walkthrough, the project CLAUDE.md is 1,800 tokens — 8% of the entire session,
loaded before you type, and part of the context on every turn thereafter. The documented target is
under 200 lines, and Anthropic's phrasing about overshooting it is unusually
direct: "Bloated CLAUDE.md files cause Claude to ignore your actual instructions!"
The test for each line is "would removing this cause Claude to make mistakes?" If not, cut it. What earns its place: commands the agent can't guess, style rules that differ from defaults, repo etiquette, environment quirks, non-obvious gotchas. What doesn't: anything inferable from the code, standard language conventions, API documentation that should be a link, file-by-file descriptions of the repo, and the self-evident. Two diagnostics worth internalising — if the agent keeps breaking a rule you wrote down, the file is probably too long and the rule is getting lost in it; if it asks you something the file answers, the phrasing is ambiguous.
The escape valve is that not everything needs to be resident. Domain knowledge and occasional
workflows belong in skills, which load on
demand; directory-specific conventions belong in path-scoped rules, which load when a matching
file is read. Both keep the always-on file small — just remember from the compaction table that
the path-scoped ones do not survive a compact. If you are working out which project rules live in
which file, we compare the options in
CLAUDE.md vs AGENTS.md. Auto memory follows the same
discipline from the other side: only the first 200 lines or 25KB of MEMORY.md load,
whichever comes first.
The structural advice: many short sessions beat one long one
Every tactic above buys you room inside a session. The habit that matters more is knowing when the session is over.
Anthropic states it about as plainly as a vendor can: "If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run /clear and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections."
That second sentence is the whole post in one line. The long session feels more productive because the agent already knows things. But what it knows is a diluted mixture of the right answer and every wrong turn taken to get there, and those wrong turns are still in the window, still being attended to, still shaping the next token. A fresh session with a good prompt starts from your best current understanding rather than the full record of how you arrived at it.
The tell is behavioural, not numeric. Stop and restart when the agent re-reads a file it read an hour ago; when it re-proposes something you explicitly rejected; when it asks a question that was answered forty messages back; when your corrections start needing corrections. None of those show up as a percentage — they show up as a feeling that you are managing the agent instead of directing it. That feeling is the metric.
And the honest counterweight, also from the docs: "Sometimes you should let context accumulate because you're deep in one complex problem and the history is valuable." This is judgement, not a rule. A tricky debugging session where every dead end narrows the search space is exactly the case where the transcript is the asset. Knowing which situation you are in is the skill; the commands are just how you act on it.
The short version
- Run
/contextbefore you guess. The category eating your window is rarely the one you assumed. - Be specific in prompts so the agent reads fewer files. File reads are about half of everything added after startup.
- Pipe long command output through
tailorgrep. There is no documented cap on how much of it lands in the window. - Delegate anything where the process is large and the answer is small. 6,100 tokens read, 420 returned.
- Compact with a focus argument, and put a Compact Instructions section in
CLAUDE.mdfor the automatic passes. - Expect local rules to vanish after a compact. Promote the ones that must survive to the project root.
- Write
HANDOFF.mdand/clearrather than compacting into a fourth hour. - Keep
CLAUDE.mdunder 200 lines. It is in every request you will ever send. - After two failed corrections, start over. It is not giving up; it is the documented advice.
Where Backgrind fits
Nothing here needs a product — these are commands you already have. But the advice has a side-effect worth naming honestly: working this way means more sessions, not fewer. Short, scoped, cleared between tasks, handed off in files, with research fanned out to subagents. That is more finishing moments, more permission prompts, more "done, what next" pauses spread across more windows than one terminal can show you at once.
That is the part Backgrind handles. It runs your real CLI in an always-on-top overlay with a tab per session and a background daemon that keeps them alive when the window is closed, so the session you handed off is still there while you work the new one — and the tab that needs a decision pings with an accent ring and a chime instead of waiting silently for you to check on it. It doesn't manage your context; Claude Code does that. It manages the consequence of managing it well. See the loop in the live demo.
Frequently asked questions
What actually fills up a Claude Code context window?
File reads, mostly. In Anthropic's representative session walkthrough, four file reads account for about 31% of a 22,225-token session and roughly half of everything added after startup. Startup itself — system prompt, CLAUDE.md, auto memory, skill descriptions, MCP tool names — is another 35%, paid before you type a word. Command and search output is around 8%. Your own prompts are about 1%.
Should I use /compact or /clear?
/compact replaces the conversation with a summary and continues the same session — right when you are still on the same task and out of room. /clear starts a new conversation with empty context — right when you switch to unrelated work. Anthropic recommends /clear frequently between tasks, and /compact with focus instructions such as /compact focus on the auth bug fix when you need continuity.
At what percentage does Claude Code auto-compact?
The docs do not state a percentage. Auto-compaction is governed by a token window, not a fill ratio: autoCompactWindow accepts 100K to 1M tokens and can be set with /autocompact 500k, the --autocompact flag, or CLAUDE_CODE_AUTO_COMPACT_WINDOW. With nothing set, Claude Code compacts when the conversation reaches the model's context limit, with documented exceptions for cloud sessions, Sonnet 4.6 and Opus 4.6 without extended context, 200K deployments of Opus 4.8 and Opus 5, and Sonnet 5.
Why does Claude get worse right after compacting?
Because not everything comes back. Project-root CLAUDE.md, unscoped rules and auto memory are re-injected from disk, but rules with paths: frontmatter and nested CLAUDE.md files are lost until a matching file is read again. The skill listing is not re-injected after /compact, and invoked skill bodies return capped at 5,000 tokens per skill and 25,000 total, oldest dropped first. The agent keeps your global rules and loses your local ones.
Do subagents actually save context?
Yes, and the docs quantify it: in the walkthrough a research subagent reads 6,100 tokens of files in its own window and returns a 420-token summary to yours. The reads never touch the parent conversation. A subagent is not free — it loads its own system prompt, its own copy of CLAUDE.md, and the MCP and skill setup — but it spends that in its window, not yours.
How long should CLAUDE.md be?
Under 200 lines. It loads at the start of every conversation, so every line is paid on every request. The documented test for each line is "would removing this cause Claude to make mistakes?" — if not, cut it. Anthropic is blunt that bloated CLAUDE.md files cause Claude to ignore your actual instructions.
Sources
Verified on 2 August 2026 against Claude Code 2.1.220 (released 25 July 2026, the current release that day). Token breakdown of a representative session, the compaction-survival table, /autocompact, autoCompactWindow and the model-specific compaction exceptions: Anthropic — Explore the context window. The "clears older tool outputs first" ordering, Compact Instructions, and the thrashing error: How Claude Code works. The context-as-primary-constraint framing, the two-correction rule, the failure patterns, CLAUDE.md length guidance and the spec-then-fresh-session workflow: Best practices. /compact, /clear, /context and /btw syntax: slash commands. Summarize-from-here and summarize-up-to-here: checkpointing. autoCompactEnabled and DISABLE_AUTO_COMPACT: settings. Tool search defaults, the 10% threshold mode, and the 10,000-token warning / 25,000-token default output cap: MCP. Subagent context isolation: subagents. Memory file locations, the 200-line target and the 200-line / 25KB auto-memory load: memory. The token figures are Anthropic's own representative numbers for a simulated session, not measurements of any real repository; percentages are arithmetic on them. No documented cap on Bash output length was found — that claim is an absence of evidence, not evidence of absence.