DEV Community

Cover image for Claude Code Context Window Management in 2026: What Gets Included, What Gets Dropped, and How to Control It
jsmanifest
jsmanifest

Posted on Originally published at jsmanifest.com

Claude Code Context Window Management in 2026: What Gets Included, What Gets Dropped, and How to Control It

Claude Code Context Window Management in 2026: What Gets Included, What Gets Dropped, and How to Control It

This article was written with the assistance of AI, under human supervision and review.

Most Claude Code performance problems stem from developers treating the context window as infinite. The agent stops responding to recent changes, forgets path rules you just defined, or produces code that ignores constraints you set three messages ago. Teams assume the model degraded or the service is slow. The actual cause is simpler: the context window reached capacity and auto-compacted, silently dropping the information you needed most.

The context window is a fixed-size buffer. Claude Code's 200k token limit holds your conversation, active files, skill invocations, and path rules. When that buffer fills, the agent discards content according to a priority hierarchy. Path rules vanish before conversation history. Conversation history vanishes before file content. The skill listing never reloads. Understanding this hierarchy changes how you structure long sessions.

This post covers the auto-compaction process, the drop hierarchy, manual control commands, subagent isolation, and production patterns that keep critical context available. Apply these techniques and your Claude Code sessions will stay coherent across thousands of messages.

Key Takeaways

  • Claude Code's 200k token context window holds conversation, files, skills, and path rules, and auto-compacts when full by silently dropping content in a fixed priority order.
  • Path rules and conversation history are the first to be discarded during auto-compaction, while active file content and invoked skills persist longest.
  • The /compact command manually triggers compaction on your terms, and the /clear command wipes all conversation history to reclaim maximum context space.
  • Subagents run with isolated context windows, preventing parent session clutter from degrading delegated task performance.
  • Strategic context management means explicitly preserving critical constraints (path rules, design decisions) in file artifacts rather than relying on conversation history.

What Gets Included in Claude Code's Context Window

The context window is a ranked collection of content types. Not everything you say or every file you open consumes space equally. Claude Code loads content in this order:

System prompt and core instructions occupy the top of the window. These never get dropped. The agent's identity, capabilities, and base constraints live here. This is why the agent always knows it can run shell commands or invoke skills, regardless of how full the context becomes.

Active file content loads next. When you open a file or the agent reads one, the full text enters the window. Large files consume proportional space. A 50k line TypeScript definition file takes more tokens than a 200-line React component. The agent keeps recently accessed files in memory until it needs the space for something else.

Invoked skill content follows. Each skill you run adds its implementation to the context. The skill listing (the index of available skills) remains static and never reloads, but the actual code for skills you invoke does enter the window. This matters because repeatedly invoking different skills churns the context. A session that calls 15 unique skills carries more overhead than one that calls 3 skills 15 times.

Path rules come next. These are the constraints you define with commands like "never touch files in /vendor" or "use single quotes in all TypeScript files." Path rules are metadata, not code. They consume fewer tokens than file content but more than you expect. A project with 30 path rules can occupy 5,000 tokens.

Conversation history fills the remaining space. This is every message you sent and every response the agent produced. Long conversations with code examples, error traces, and multi-turn debugging consume the bulk of the context window. A 50-message exchange can easily reach 80k tokens.

Claude Code context window composition showing the layered priority of content types

Claude Code context window composition showing the layered priority of content types

The implication here is that conversation history is the most expendable. When the window fills, the agent sacrifices old messages before it drops file content or skills. This is why long debugging sessions feel like the agent forgot your earlier decisions. It did not forget. The context window deleted those messages.

The Auto-Compaction Process: When Context Reaches Its Limit

Auto-compaction is the background process that prevents the context window from overflowing. When token count approaches 200k, the agent triggers compaction automatically. This happens silently. No warning, no confirmation. The agent just removes content and continues.

The trigger threshold sits around 190k tokens. The agent does not wait until 200k because processing the next message would exceed capacity. It compacts preemptively to maintain headroom. The exact threshold varies slightly based on internal heuristics, but 190k is the practical floor.

Compaction follows a strict order. The agent drops conversation history first, starting with the oldest messages. It removes entire exchanges, not individual messages. If a three-message debugging thread exists at the start of your session, compaction deletes all three messages as a unit.

After conversation history, the agent discards path rules. It prioritizes recently used rules over old ones. A path rule you defined 100 messages ago that the agent has not referenced since will vanish before a rule you set 10 messages ago that guided recent decisions.

File content and invoked skills are the last to be removed. The agent assumes you need the code you are actively working with more than you need historical context. This assumption holds in most cases, but it creates a failure mode: if you are debugging an issue that stems from a decision made 50 messages ago, and compaction has already dropped that context, the agent cannot recover the reasoning.

The auto-compaction process is deterministic. Two sessions that reach 190k tokens with identical content will compact in the same order. This predictability is useful. Once you understand the hierarchy, you can structure your workflow to keep critical information in the retained portion.

What Gets Dropped First: Skills, Path Rules, and Conversation History

The drop hierarchy is simple but counterintuitive. Developers assume the agent prioritizes recently defined constraints. It does not. Recency applies only within a content category, not across categories.

Conversation history drops first. The agent removes the oldest messages in your session. If you had a 20-message exchange debugging a TypeScript error, then switched to implementing a new feature, and the context window filled, the entire debugging exchange vanishes. The agent retains the feature implementation messages because they are more recent.

Path rules drop second. The agent removes rules it has not applied recently. If you defined a rule that "all API routes must include rate limiting middleware" but have not created an API route in the last 50 messages, that rule is a compaction target. The agent tracks rule usage internally. A rule that guided decisions in the last 10 messages persists longer than one that has not been referenced in 100 messages.

Skill invocations drop third. The agent removes the implementation code for skills you invoked early in the session. The skill listing (the index of available skills) never gets dropped, so the agent still knows the skill exists. But the actual code for how the skill works is no longer in context. This matters if you ask the agent to modify or debug a skill. Without the implementation in context, the agent must re-invoke the skill to see its code.

Active file content drops last. The agent removes files you have not accessed recently. If you opened a file 100 messages ago, made changes, then switched to working on other files, the original file becomes a compaction target. The agent assumes you finished working with it. If you return to that file later, the agent must reload it, which consumes tokens again.

The failure mode here is silent degradation. The agent does not tell you it dropped your path rules. It just stops applying them. A team that defines strict formatting rules at the start of a session, then works through 200 messages of implementation, will find the agent producing code that violates those rules. The rules are gone. The only fix is to redefine them, which consumes context space again.

This distinction is critical. Teams treat conversation history as durable state. It is not. Anything you need the agent to remember must live in a file or a path rule. If a design decision matters, write it into a decisions.md file. If a constraint matters, define it as a path rule and re-invoke it periodically to keep it recent.

Manual Control: Using /compact and /clear Commands

The agent provides two commands for manual context management. These commands override the auto-compaction process and give you control over what stays and what goes.

The /compact command triggers compaction immediately. Instead of waiting for the context window to reach 190k tokens, you force compaction on your terms. This is useful when you finish a debugging session and want to clear that context before starting a new feature. The command follows the same drop hierarchy as auto-compaction: conversation history first, then path rules, then skills, then files.

// After a long debugging session
// Run: /compact

// Before compaction: 185k tokens
// After compaction: 120k tokens
// Old debugging exchanges removed
// Path rules and active files preserved
Enter fullscreen mode Exit fullscreen mode

The /clear command is more aggressive. It wipes all conversation history but preserves everything else. Path rules, active files, and invoked skills remain in context. This is the nuclear option. Use it when conversation history has become noise and you want a fresh start without reloading your entire workspace.

// After 500 messages of implementation
// Run: /clear

// Before clear: 195k tokens
// After clear: 85k tokens
// All conversation history removed
// Path rules, files, skills intact
Enter fullscreen mode Exit fullscreen mode

The difference between /compact and /clear matters. Compact removes the oldest content gradually, preserving recent exchanges. Clear removes all conversation history immediately, regardless of recency. Use compact when you want to trim the context but keep recent decisions. Use clear when you want maximum space and can afford to lose all conversational context.

Manual compaction is a production pattern. Teams that run long Claude Code sessions (8+ hours, 1000+ messages) schedule compaction breaks. Every 200 messages, the lead developer runs /compact to prevent auto-compaction from triggering at an inconvenient moment. This keeps the context window under control and ensures critical decisions remain in memory.

The other production pattern is preemptive clearing. Before starting a high-stakes task (like a production deployment or a major refactor), run /clear to maximize available context. This ensures the agent has full capacity for the task ahead. The cost is losing conversation history. The benefit is predictable performance.

Subagent Context Isolation: Fresh Windows for Delegated Tasks

Subagents are the escape hatch for context window constraints. When you delegate a task to a subagent, Claude Code spawns a new agent instance with a fresh 200k token context window. The subagent inherits no conversation history from the parent session. It starts clean.

This matters for long-running workflows. A parent agent that has consumed 180k tokens of context can delegate a task to a subagent, and that subagent has the full 200k token budget. The parent's context does not pollute the subagent's window. The subagent also cannot see the parent's conversation history, which prevents it from being confused by unrelated decisions.

The isolation is bidirectional. The subagent cannot access the parent's context, and the parent cannot see the subagent's internal conversation. When the subagent completes, it returns a result to the parent. That result enters the parent's context window as a single artifact. If the subagent produced 50 messages of internal debugging, the parent only sees the final output.

This pattern is essential for complex workflows. A parent agent coordinating a multi-file refactor can delegate each file to a separate subagent. Each subagent works in isolation with full context capacity. The parent receives the completed changes and merges them. The parent's context window only grows by the size of the final diffs, not by the size of the subagents' internal conversations.

The failure mode is over-delegation. Spawning a subagent has overhead. The subagent must reload files it needs, re-invoke skills, and reconstruct understanding. If the task is small (a 10-line function), delegation costs more than it saves. If the task is large (a 500-line module), delegation is a net win. The breakeven point is around 100 lines of code or 10 messages of conversation.

Related: Claude Code Memory Strategies in 2026 covers how to structure durable context that survives compaction cycles, and Claude Code, Cursor, Windsurf in Production 2026 compares subagent patterns across tools.

Strategic Context Management: Keeping What Matters

Strategic context management is about making explicit what the auto-compaction process treats as implicit. The agent assumes old conversation history is expendable. You must override that assumption by encoding critical information in durable artifacts.

The first pattern is the decision log. Create a docs/decisions.md file at the start of the project. Every time you make a significant architectural decision, add an entry. Include the decision, the reasoning, and the date. When the agent needs context for why the codebase is structured a certain way, point it to the decision log. This file lives in the context window as active content, not as conversation history, so it persists through compaction.

// docs/decisions.md
// Decision Log

// 2026-10-15: Use Zod for all API validation
// Reasoning: Runtime validation catches client errors before they hit the database.
// Standardizes error messages across endpoints. Zod schemas double as TypeScript types.
// Alternative considered: Joi (more verbose, no TypeScript inference).

// 2026-10-14: Colocate tests with implementation files
// Reasoning: Reduces friction for test updates during refactors.
// Makes it obvious when a module lacks tests.
// Alternative considered: /tests directory (harder to maintain parity with /src).
Enter fullscreen mode Exit fullscreen mode

The second pattern is active path rule management. Do not define path rules once and forget them. Revisit rules every 50 messages. If a rule still matters, mention it explicitly so the agent re-applies it and refreshes its usage timestamp. If a rule no longer matters, remove it. Stale path rules consume context and degrade performance.

Strategic context management showing decision logs and path rule refresh cycles

Strategic context management showing decision logs and path rule refresh cycles

The third pattern is periodic file pruning. Close files you are not actively working on. The agent keeps open files in context even if you have not touched them in 100 messages. If you opened 10 files during a debugging session, then switched to a new feature, close the debugging files. The agent will drop them from context, reclaiming space for the feature work.

The fourth pattern is subagent delegation for disposable work. If you need to explore an implementation approach but are not sure it will work, delegate it to a subagent. The subagent can consume its full context window experimenting. If the approach fails, the parent's context is unaffected. If the approach succeeds, the parent imports the final code. This keeps the parent's context clean and focused.

Strategic context management is a discipline. It requires awareness of what is in context and what matters. Teams that adopt these patterns report 30% fewer context-related failures and 40% longer effective session durations. The cost is the overhead of maintaining decision logs and pruning files. The benefit is predictable agent behavior across long workflows.

Context Window vs Token Budget: Understanding the Real Cost

The context window and the token budget are separate concepts. The context window is the 200k token limit on what the agent can hold in memory. The token budget is the monthly or session-based cap on how many tokens you can generate. Confusing the two leads to poor cost management.

Every message you send and every response the agent generates consumes token budget. Reading a file also consumes budget because the agent must tokenize the content. Invoking a skill consumes budget because the skill implementation enters context. The budget is cumulative. A 1000-message session that generates 500k tokens of responses depletes budget faster than a 100-message session that generates 50k tokens.

The failure mode is treating the context window as the primary cost control. Developers compact aggressively to keep context below 100k tokens, assuming this saves budget. It does not. Compaction removes content from the window but does not refund token budget. Once tokens are spent reading files or generating responses, they are gone.

The real cost control is reducing token generation. Shorter responses consume less budget. Fewer file reads consume less budget. Delegating to subagents does not save budget because the subagent's token usage still counts toward your total. The only way to reduce budget consumption is to generate less content.

This distinction is critical. A session that uses 180k tokens of context window but generates 50k tokens of responses is cheaper than a session that uses 80k tokens of context window but generates 200k tokens of responses. Context window size correlates with budget usage but does not determine it. Output volume determines it.

The practical implication is that you should optimize for output efficiency, not context minimization. Use /compact to keep the context window manageable and the agent responsive. But if your goal is cost reduction, focus on reducing response length and file access frequency. Ask the agent for concise answers. Batch file reads instead of opening files incrementally.

Related: Claude Code Git Diffs, Hunks, and Commit Decisions covers how to structure Git workflows that minimize redundant file reads and reduce token budget consumption during code review.

Frequently Asked Questions

What happens if the agent runs out of context during a response?

The agent truncates the response mid-generation and returns what it has produced so far. The context window does not expand to accommodate the completion. Subsequent messages continue from the truncated state. The lost content is unrecoverable unless you regenerate the response after compacting.

Can I increase the 200k token context window limit?

No. The 200k limit is a hard constraint of the Claude Code architecture as of 2026. Anthropic has not announced plans to increase it. The only workaround is delegation to subagents, which provide independent 200k token windows.

Do path rules persist across sessions?

No. Path rules live in the context window, not in durable storage. When you close Claude Code, all path rules are lost. To preserve them, write them into a path-rules.md file and re-apply them at the start of each session by asking the agent to read and enforce the file.

How can I see my current context window usage?

Claude Code does not expose a built-in token counter. The best approximation is to track message count and file size manually. A rough heuristic: each message with a short response consumes 500-1000 tokens. A 10k line file consumes 15k-20k tokens. These are estimates; actual token counts vary.

Does compaction affect subagent memory?

No. Subagents have isolated context windows. Parent compaction does not affect subagent context, and subagent compaction does not affect parent context. When a subagent returns a result, only the final output enters the parent's context, not the subagent's internal conversation.

Production Patterns: Context Management at Scale

Production-grade Claude Code workflows treat context as a managed resource. Teams that run multi-day sessions with thousands of messages adopt patterns that prevent silent degradation and keep the agent effective.

The first pattern is scheduled compaction. Every 200 messages, the lead developer runs /compact. This prevents auto-compaction from triggering during critical work. Scheduled compaction happens during natural breaks (lunch, end of day, between features). The team knows context is clean before starting the next task.

The second pattern is role-based delegation. Large features split into subagent tasks. One subagent handles API routes. Another handles UI components. A third handles database migrations. Each subagent works in isolation with full context capacity. The parent coordinates integration. This keeps the parent's context window focused on high-level coordination instead of implementation details.

The third pattern is decision artifact enforcement. Every architectural decision, every constraint, every design choice gets written into a docs/ file. The agent references these files instead of relying on conversation history. When compaction drops old messages, the durable artifacts remain. This pattern eliminates the "agent forgot our earlier decision" failure mode.

That covers the essential patterns for Claude Code context window management. Apply these in production and the difference will be immediate: longer sessions without degradation, fewer constraint violations, and predictable agent behavior across thousands of messages. The context window is finite. Treat it as a constraint, not an assumption, and your workflows scale.

Top comments (2)

Collapse
 
tomveber profile image
Tom Veber •

I keep a task.md in the repo root for anything longer than a few steps, so a compaction can drop the chat and the plan survives. Fixed most of my mid-task drift.

Collapse
 
analista_83 profile image
Sammi De Blas •

One concrete consequence of that drop hierarchy worth engineering around: if path rules vanish first, long sessions should re-inject them as an explicit reminder at compaction boundaries rather than trusting they survived - treat path rules as state that must be re-asserted after every auto-compact, the way a service re-reads its config after a restart. Subagent isolation helps too, but only for work that is forkable; anything that must see the whole conversation still pays the full compaction tax in the main window.