Claude Code context management: when to /clear and when to /compact
9m read time verified against Claude Code 2.1.220

Claude Code context management: when to /clear and when to /compact

Context management in Claude Code got harder when the window got bigger. What /context actually measures, why /compact is a lossy re-encode of your session, and the rule I use for when to clear instead.

The window empties on /clear and on a new session, and nowhere else. /compact does not start over: it has a model summarise the conversation and carries on from that summary, so something always goes missing. To see how much room is left, run /context. And yes, it matters if you use that room up entirely, because auto-compact only fires when you have almost nothing left, which means the summary gets written by the worst version of your session.

That is the mechanical answer. The useful answer is that you should not be waiting for any of those moments.

Run /context in a session that has been going since breakfast. Mine reports a wall of free space. No warning, no compaction notice, nothing red.

The session is still worse than it was at nine in the morning. The meter just has no way to say so.

Degradation starts long before the window fills

Chroma's context-rot work tested 18 frontier models and found every one of them gets less reliable as input grows, on tasks as simple as repeating words back. Their LongMemEval run is the cleanest illustration: the same question, answered from a focused ~300-token prompt or from the full ~113k-token conversation it was buried in. Same information present in both. Large gap in the answers.

NoLiMa puts a number on where it starts. Across 13 models that all advertise at least 128k of context, 11 dropped below half their short-context baseline at 32k tokens. GPT-4o went from 99.3% to 69.7%.

Thirty-two thousand tokens. On a 1M window that is three percent of the way in.

Anthropic describes the mechanism as an attention budget: every token attends to every other token, so n tokens means n² pairwise relationships, and each new token you add spends from a finite pool. Their own guidance is to find the smallest set of high-signal tokens that gets the job done. That is a strange thing to publish alongside a million-token window, and it is also correct.

What a long session does to the code

SlopCodeBench (arXiv 2603.24755, March 2026) is the study I have been waiting for on this. Instead of one-shot benchmarks it makes agents extend their own prior code across 93 checkpoints, with evolving specs and no corrected reference implementation handed back between turns. Eleven models, from Sonnet 4.5 up to Opus 4.6 and the GPT-5.x Codex variants.

The correctness numbers are grim on their own: no agent solved a single problem end to end, the best checkpoint solve rate was 17.2%, and by the final checkpoint strict solve rates collapsed to 0.5%. Cost grew 2.9× across a problem while correctness did not improve.

The quality numbers are the ones that should change your habits:

  • Structural erosion rose in 80% of trajectories. High-complexity functions went from 4.1 to 37.0 per codebase, peak cyclomatic complexity from 27.1 to 68.2.
  • Verbosity rose in 89.8%, with structural duplication up 66% across most trajectories.
  • Human-maintained repositories stay roughly flat on the same measures. Agent trajectories deteriorate with nearly every iteration.

Those are the same instruments I wrote about in the dashboard beyond coverage and mutation testing: complexity concentration and clone detection. Point them at a long agent session and they read as a downward slope.

The paper also tried the obvious fix. Quality-aware prompting cut initial verbosity by 34.5% on GPT-5.4, and the degradation slopes stayed parallel. You get a better starting point and the same decline. Session length is the lever.

The case for long sessions is real

A March 2026 paper argues that coding agents are effective long-context processors, beating published state of the art by 17.3% on corpora up to three trillion tokens. It is good work and worth reading before you take my side of this.

Read how it wins, though. The agents organise the text into a file system and manipulate it with ordinary tools. The corpus stays on disk and the window holds a working set. That result is not evidence that a bloated window is fine, it is evidence that the filesystem is where bulk belongs.

Which is the same conclusion from the other direction.

What /context actually measures

/context in Claude Code 2.1.220 breaks your window into named categories: system prompt, system tools, MCP tools, custom agents, memory files, messages, free space, and a line most people scroll past called Autocompact buffer. The status readout tells you the percentage until auto-compact, and there is a "Context low" warning further down the line.

That buffer line is the useful one. It is space you cannot spend, reserved so the model still has room to write a summary of itself when the moment comes. Your usable window is smaller than the number on the box, and it always was.

In a big repository the memory-files line is worth a second look, because every subdirectory's CLAUDE.md joins it as soon as Claude reads a file there. Scoping the agent to one package keeps that line short before compaction ever becomes the question.

The /doctor command audits the other half of this: what your install loads into every session before you type anything. It scopes itself to disk-based estimates and explicitly points you at /context for the live measurement. Install hygiene and session hygiene are separate problems, and only one of them has a linter.

/compact is a model summarising itself

Pull the compaction prompts out of the binary and the design is right there. Three variants: one that summarises the whole conversation, one that summarises only the recent portion when an earlier prefix is being kept intact, and one written to sit at the head of a continuing session.

All of them demand the same eight sections. Primary request and intent. Key technical concepts. Files and code sections, with full snippets. Errors and fixes. Problem solving. All user messages. Pending tasks. Current work.

The spec is thorough. The summariser is a model grading its own session with the context you already suspect is degraded, and everything that did not get nominated into one of those eight buckets is gone.

Two details in that prompt are worth your attention. The summariser is told to preserve security-relevant user instructions verbatim so they remain in effect afterwards, which tells you plainly that constraints can otherwise evaporate in the re-encode. And it is warned never to attribute transcript-shaped text inside assistant messages to the user, because a summary is a soft target for anything that wants to launder a fake instruction into your next window.

Then the resumption prompt tells the model to pick up without acknowledging the summary, as if the break never happened. Smooth by design. You will not feel the seam, which is exactly why you should not let it happen on autopilot.

Clear early, compact rarely, write the brief yourself

Auto-compaction fires when you are nearly out of room. The summary is therefore written by the worst version of the session, long past the 32k mark where accuracy starts sliding. If you are going to compact, do it with headroom left, deliberately, while recall is still good.

Better: do not need it. Clear on task boundaries, and put what should survive into a file instead of a summary. CLAUDE.md is the memory that outlives every session, and unlike a compaction summary you wrote it, you can read it, and you can delete a line that has gone wrong. Keep it to conventions, pitfalls and rationale that the agent cannot derive from the repo, or you end up with memory that confidently lies to you six weeks later.

The rule I actually follow:

SituationMove
Task done, next task unrelated/clear, then a fresh brief
Same task, window filling with tool output/compact now, while you still have room
Model keeps reverting to a wrong assumption/clear. The assumption is in the history, and a summary will carry it forward
"% until auto-compact" is in single digitsYou already missed both windows. Clear and rewrite the brief by hand

Writing that brief takes two minutes and it is a better artefact than any generated summary, because you know which four things mattered and the model is guessing at eight.

There is a third instrument between clearing and compacting. The /rewind menu can summarise one chosen stretch of the session, forward from a message or back to it, which beats compacting the lot when a single verbose debugging detour is what filled the window.

The question underneath is what fills your window that fast. A tool that answers in formatted prose spends your window on layout, which is the argument for keeping agent output plain.

One clean session per task is easy advice until you want three tasks running at once. That is what git worktrees are for, with the caveat that they isolate your files and remarkably little else. Sessions running side by side can also hand each other a one-line finding rather than waiting for you to relay it.

Clearing is easier to do when you know the session is not gone. Everything you clear was written to disk on the way past, and stays findable if you index it. That holds when the session ends on your terms and when it does not: a crash leaves the transcript behind even where the client will not offer it back.

The measurement problem here is the same one as with generated code. The instruments exist, they are free, and nobody opens them because nothing has broken yet.

Complexity and duplication tell you the codebase is drifting. /context tells you the session is. Both go quiet the moment you stop looking, and both are cheapest to act on while the answer is still boring.

(26 of 36)
01My Claude Code setup: status line, plugins and terminal02Superpowers: teaching Claude Code to think before it types03Claude Code hooks: deterministic control over AI workflows04The CLAUDE.md file: give your AI permanent memory05Stop asking your agent nicely06What's new in Claude Code: notes from the London talk07The best number in Opus 4.8 isn't a benchmark08Stale memory is worse than no memory09The agent is just a loop10Build an MCP server, then ask whether it should exist11Skill, subagent, hook, or slash command? Pick the right one12Log in to MCP servers from your shell13How to give Claude safe access to your SQL database14The day 'default' became 'Manual'15Claude Code skills: how to write one that works16How to write a proper Claude Code subagent17Claude Code permissions: the guide I wish the docs were18Sandboxing Claude Code: put your agent in a box that holds19Prompt injection defense for developers who ship agents20Best Claude model for coding: which one for which task21Refactoring legacy code with a coding agent: start with characterization tests22MCP server authentication: OAuth, scopes and rate limits23Opus 5 is here and your effort settings just expired24AI agent incident response: what to do when your coding agent goes wrong25Claude Code /doctor: what it checks and what changed26Claude Code context management: when to /clear and when to /compact27Git worktrees for parallel coding agents: what they isolate and what they share28Claude Code plan mode: decide before the agent writes29Debugging with a coding agent: give it the search, keep the hypothesis30Claude Code checkpoints and /rewind: how to undo an agent's changes31Claude Code cross-session messaging: how to make your sessions talk to each other32Audit logging for AI agents: what Claude Code records and what deserves a human33Sharing Claude Code config across a team: what a repo can and cannot enforce34Your Claude Code session has no clock35Claude Code in a large codebase: scoping an agent to the part that matters36Recovering a Claude Code session your picker will not show you