teachyou.ai academy
← All posts
Claude Code

Claude Code Context Window Management: Avoiding Context Rot

Pramod Dutta · Jun 25, 2026 · 15 min read

Why your Claude Code session gets dumber the longer it runs

You've felt it. An hour into a Claude Code session, the model starts forgetting decisions you made twenty minutes ago. It re-reads a file it already read. It "fixes" a bug you already fixed, undoing your fix in the process. It gives you a vague, hedge-everything answer instead of the sharp, specific one it gave you at the start of the session. Nothing crashed. No error appeared. The model just quietly got worse at the job.

This is context rot, and it is one of the most under-discussed failure modes in agentic coding. It isn't a bug in Claude Code — it's a structural property of how large language models process long inputs. Every model has a finite context window, a maximum number of tokens it can hold in a single conversation. Claude Code fills that window with your prompts, the assistant's replies, file contents it reads, shell command output, tool call results, and a running summary of everything that happened before. As that pile grows, two things happen at once: you get closer to the hard token ceiling, and — well before you hit that ceiling — the model's ability to attend to any single piece of information inside a bloated context degrades.

That second part is the part people miss. You don't need to fill the context window to 100% for quality to drop. Long, noisy, redundant context makes it harder for the model to locate the one relevant line in a 400-line file dump from three tool calls ago. Attention is a finite resource even inside a technically "available" context budget. A context window at 60% capacity but full of stale grep output and abandoned exploration paths often performs worse than a tight, curated 20% window.

This article is a practical guide to managing the Claude Code context window: what actually consumes it, how to read the warning signs of context rot before it wrecks your session, and the concrete workflow habits — /clear, /compact, subagents, and deliberate context curation — that keep long engineering sessions sharp from the first prompt to the last commit.

What actually fills up the context window

Before you can manage context, you need to know what's eating it. In a typical Claude Code session, the context window is consumed by:

  • The system prompt and tool definitions. Every available tool (Bash, Read, Edit, Write, Grep, MCP servers you've connected) has a schema description that gets sent on every turn. A session with a dozen MCP servers attached carries meaningfully more baseline overhead than a bare-bones setup.
  • CLAUDE.md and project instructions. Global and project-level memory files get loaded up front. A sprawling CLAUDE.md with every convention your team has ever written is convenient to write but expensive to carry on every single turn.
  • File reads. Every time Claude reads a file, the full (or truncated) content lands in context. Read a 2,000-line config file three times across a session and you've paid for it three times unless something dedupes it.
  • Tool call outputs. Shell command output, test runs, build logs, git diff output, grep results — these are often the biggest silent consumer. A verbose npm install log or a failing test suite's full stack trace can be thousands of tokens for information you needed for ten seconds.
  • The conversation itself. Every explanation, every "let me think about this," every intermediate plan the model wrote out loud is still sitting in the transcript, still being re-read on every subsequent turn.

None of this is wasteful in the moment — it's how the model reasons. The problem is that none of it disappears on its own. Context is append-only by default. Unless you actively intervene, a three-hour session accumulates every file read, every log dump, and every dead-end investigation from hour one, and all of it competes for the model's attention when you ask your hour-three question.

The warning signs of context rot

Context rot rarely announces itself. It shows up as a gradual texture change in the quality of responses. Watch for these signals in a long Claude Code session:

  • Re-reading files it already has. If Claude re-opens a file it read fifteen minutes ago to answer a question about it, that's a sign the earlier read has been pushed so far back in context (or buried under noise) that it's effectively forgotten.
  • Contradicting earlier decisions. You agreed on an approach, moved on, and now the model proposes the approach you already rejected. This is classic evidence that the decision lives in a part of the context the model is no longer weighting heavily.
  • Vaguer, more hedged answers. Early in a session, responses tend to be direct and specific. As context balloons, answers get longer, more qualified, and less committal — a symptom of the model spreading attention thin across a cluttered window.
  • Slower responses and higher latency. More tokens in, more tokens the model has to process before producing the first output token. If a session that used to respond quickly now visibly lags, that's a mechanical, not just qualitative, symptom.
  • Small edits causing large, unrelated diffs. When a model loses track of the actual current state of a file versus an earlier version discussed in the conversation, it can produce edits that don't match what's really on disk.
  • Repeating the same clarifying question. If you already answered something and it's asked again, the answer is still "in" the context technically, but it's not being surfaced.

None of these individually proves context rot — models make mistakes for other reasons too. But when you see two or three of these cluster together in a session that has been running a long time, treat it as a signal to intervene rather than push through.

/clear: the reset button you should use more often

The single highest-leverage habit for context management in Claude Code is using /clear aggressively between unrelated units of work.

/clear wipes the conversation history and starts a fresh context window. It sounds drastic, but the mental model to adopt is: a Claude Code session should map to one coherent task, not one calendar day. If you finished implementing a feature, wrote the tests, and got them passing, that's a natural end. Don't keep the same session open to start an unrelated bug fix in a different part of the codebase "because it's already warmed up." That warmth is exactly the stale context that will bite you later.

A good rule of thumb: run /clear whenever you cross one of these boundaries.

  • You've completed a task and are about to start a functionally unrelated one.
  • You've merged or committed your changes and the working tree is clean again.
  • You spent a while going down an investigation path that turned out to be a dead end, and you now know the right approach — clear and restate the *conclusion*, not the *journey*.
  • You're switching from implementation mode to a different mode entirely (for example, from writing code to writing documentation about it).

The instinct to keep one long session running "for continuity" is usually backwards. Continuity of *decisions* matters — continuity of raw conversation history does not. If a decision matters, write it down somewhere durable (a CLAUDE.md note, a comment, a commit message, a short recap) and let the surrounding noise go. A fresh context window that's told "we decided to use Postgres row-level security for multi-tenancy, now implement X" will outperform a stale, cluttered window that technically contains that decision buried under forty tool calls.

# Bad habit: one mega-session all day
/start session -> feature A -> bug B -> refactor C -> feature D (8 hours later, same context)

# Better habit: clear boundaries
/start session -> feature A -> /clear
/start session -> bug B -> /clear
/start session -> refactor C -> /clear

/compact: summarizing instead of discarding

/clear is a hard reset — sometimes too hard, because you're mid-task and genuinely need what came before. That's what /compact is for. /compact asks Claude to summarize the existing conversation into a condensed form and continue from that summary, rather than either carrying the full history forward or wiping it entirely.

Use /compact when:

  • You're deep into a multi-hour task (a large refactor, a multi-file migration) and can't cleanly /clear without losing important state, but the context is clearly getting heavy.
  • You've done a lot of exploration — reading files, running greps, testing hypotheses — and now know what needs to change, but the exploration itself doesn't need to be preserved verbatim.
  • You notice early context-rot symptoms (re-reading files, slower responses) but you're not at a natural stopping point.

The key difference from /clear is that /compact preserves the *gist* — decisions made, current state of the task, open questions — while discarding the token-heavy raw material that produced that gist (full file contents, full command output, the back-and-forth reasoning that led to a conclusion). Think of it as the difference between keeping your entire browser history versus keeping your bookmarks. You want the bookmarks.

A practical pattern: when you're about to kick off a long-running operation (a large test suite, a big build, an extensive multi-file search), consider whether you actually need the exploration that preceded it in full fidelity going forward. If not, /compact first, then proceed. You'll get faster, more focused responses for the rest of the session, and you avoid the compaction happening automatically at an inconvenient moment with less control over what gets kept.

It's also worth compacting proactively rather than reactively. Waiting until the context window is nearly full to compact means the summarization step itself has to work with an already-degraded, noisy context. Compacting earlier — say, at the halfway point of a task you know will be long — produces a cleaner summary because there's less junk to compress.

Subagents: the real fix for exploration-heavy work

/clear and /compact manage context you've already accumulated. Subagents prevent the accumulation in the first place, and for exploration-heavy or research-heavy work, they are the single most effective tool available.

Here's the underlying problem they solve: a lot of what Claude Code does in a session is *investigation* — searching the codebase for where a function is defined, reading through five candidate files to find the one that actually matters, running a broad grep and sifting the results, checking how a library is used elsewhere in the repo. All of that investigation produces tokens. Almost none of those tokens are useful once the investigation concludes. You don't need the forty lines of grep output that led you to file X — you need the fact that "the auth logic lives in file X, line 120."

Subagents let you delegate that investigation to a separate context entirely. A subagent runs its own isolated conversation, does the reading and searching and dead-end-chasing, and then returns a single, condensed answer to the main session. The exploration noise — the file reads, the failed greps, the "let me check this other file too" tangents — stays inside the subagent's context and never touches your main conversation. Your main session's context window only grows by the size of the subagent's final report, not by everything it did to produce that report.

This is why, for large or unfamiliar codebases, launching a research subagent before writing any code is dramatically more context-efficient than doing the exploration inline. Compare:

# Context-heavy: inline exploration
Read file1.ts (400 lines)
Read file2.ts (250 lines)
Grep "handleAuth" across repo (60 matches)
Read file3.ts (180 lines)
-> now write the fix, with all 890+ lines still sitting in context
# Context-efficient: delegated exploration
Launch subagent: "Find where auth token refresh is implemented
and explain the current flow in under 150 words"
-> subagent does all the reading/grepping internally
-> main session receives a 150-word answer
-> write the fix with a fraction of the token cost

The same principle applies to code review, test running, and documentation generation — any task that's naturally "go look at a lot of things and report back a small conclusion" is a candidate for a subagent. It's also why running multiple independent subagents in parallel (when tasks don't depend on each other) is both faster and more context-efficient than doing them one after another in the main thread: each one's noise is contained, and only the summaries come back.

The trade-off is real and worth naming: subagents add coordination overhead, and a subagent that isn't briefed with enough context of its own can waste effort re-deriving things you already know. The fix isn't to avoid subagents — it's to brief them properly. Tell a subagent what you've already ruled out, what specifically you need answered, and how long the answer should be. A well-briefed subagent that returns a tight, useful summary is a much better use of your main context budget than doing the same digging inline.

Curating CLAUDE.md and project instructions

Context management isn't only about runtime behavior — it starts with what gets loaded before you type your first prompt. CLAUDE.md files (global and per-project) are loaded into context automatically, on every session, whether or not their contents are relevant to what you're about to do.

This makes CLAUDE.md an easy place to quietly bloat every single session you ever run. A 300-line CLAUDE.md with exhaustive documentation of every subsystem, every past decision, and every edge case is expensive baseline weight carried into every conversation, most of which is irrelevant to any given task.

Practical guidelines:

  • Keep CLAUDE.md focused on things that are *true for almost every task* in the project — build commands, coding conventions, architectural constraints, things that would otherwise need re-explaining every session. Don't use it as a dumping ground for one-off notes.
  • Push task-specific or rarely-needed detail into separate files that get read on demand, rather than a monolithic file loaded unconditionally every time.
  • Periodically prune it. Instructions that were critical during an early migration and are no longer relevant should be removed, not left to accumulate indefinitely.
  • Be as specific and information-dense as possible per line. A short, precise instruction earns its keep across hundreds of future sessions; a vague, wordy one costs the same tokens for less value.

The same discipline applies to the instructions you give inline during a session. Long-winded prompts with excessive preamble cost tokens on every turn they remain relevant to. Specific, concrete instructions are both easier for the model to follow and cheaper to carry forward.

Structuring long sessions to minimize rot

Beyond the specific commands, a few structural habits make context rot far less likely to set in during long working sessions:

  • Front-load research, then clear or compact before implementation. Do your investigation (ideally via subagents), reach a conclusion, write that conclusion down explicitly, then start implementation with a clean or compacted context that contains the conclusion but not the investigation trail.
  • Summarize your own decisions out loud. Periodically state, in plain language, "here's what we've decided and why" as a message in the conversation. This isn't just for your own tracking — it gives the model a dense, recent, high-signal anchor point that's easier to attend to than reconstructing the decision from scattered earlier turns.
  • Avoid pasting large blobs you don't need in full. If you only need to reference three lines of a stack trace, paste three lines, not the full scrollback. If you need the model to see a large file, consider whether a subagent summarizing the relevant section is more efficient than a raw dump.
  • Match session scope to task scope. One session per coherent unit of work, as discussed above, is the single biggest lever. Resist the urge to keep a session alive purely out of habit.
  • Watch token/context indicators if your setup surfaces them. Some Claude Code configurations surface context usage. Treat rising numbers as a prompt to consider /compact, not just a number to ignore until it forces an automatic compaction at a worse moment.
  • Isolate risky or exploratory branches of work. If you're trying something you're not sure will pan out, consider a separate session or subagent rather than letting a failed experiment's full trail sit in your primary working context.

None of these habits require new tooling. They're workflow discipline — the same kind of discipline that separates an engineer who keeps forty browser tabs open indefinitely from one who closes what they're done with. The context window is a shared, finite resource for the duration of a session, and treating it that way is what keeps Claude Code performing at the level it's capable of, hours into a session, rather than degrading quietly while looking fine on the surface.

Bringing it together

Context rot is not a Claude Code bug to wait out — it's an inherent property of long-running conversations with any LLM-based agent, and it responds directly to how deliberately you manage the context window. The habits are simple to state and easy to under-use in practice: clear the session when you cross a real task boundary instead of riding one long conversation across unrelated work, compact when you need continuity but the accumulated exploration has become dead weight, and delegate investigation-heavy work to subagents so their noise never enters your main context at all. Layer on a lean, high-signal CLAUDE.md and a habit of writing decisions down explicitly rather than trusting them to survive buried in a long transcript, and you get sessions that stay sharp for hours instead of degrading after the first thirty minutes.

If you want to go deeper on how Claude Code actually works under the hood — how it plans, uses tools, manages context across sessions, and where these habits fit into a broader agentic workflow — that's exactly what we cover, hands-on, in our Claude Code Tutorial for Beginners course at TeachYouAI. It walks through real sessions, real context-management decisions, and the reasoning behind them, so you're not just copying commands but understanding why they work.