Claude Code — context window exhausted mid-task, /compact triggered (2026) — Fix Guide (2026) | AI Error Hub
Home Providers Claude Code context exhaustion
Claude Claude Code · Context Window Severity: Medium HTTP n/a

Claude Code — context window exhausted mid-task

Agentic coding sessions burn through context faster than any other Claude workflow. Files read into context, tool outputs, and long chains of edits saturate the 200K window quickly. Managing it is a skill.

By Ahmed R. · Senior AI Infrastructure Engineer Published 2026-07-26 Verified 2026-07-26

Quick fix (TL;DR)

Resolution: Claude Code sessions accumulate every file read, every tool output, and every message in the working context. When you approach the model's context limit (200K on Sonnet/Opus 4.7), the client auto-compacts or refuses new turns. Fix by (a) running /compact preemptively at natural breakpoints, (b) using /clear between unrelated subtasks, (c) reading large files with line ranges instead of full contents, and (d) splitting genuinely-long tasks across sessions with checkpointed state.

Real error messages you'll see

These are the exact strings returned by the Claude API service and its SDKs when this error occurs. Copy-paste-searching any of them should land on this page.

Context near capacity warning
⚠ Context window at 92% (183,254 / 200,000 tokens)
Run /compact to summarise older messages, or /clear to reset the session.
Turn refused — auto-compact failed
Error: Context window exhausted (204,832 tokens > 200,000 limit).
Auto-compact could not free enough space. Run /clear or start a new session.
Model call fails with token overflow
anthropic.BadRequestError: Error code: 400 - prompt is too long: 208912 tokens > 200000 maximum

Reference

What consumes context in a Claude Code session

SourceTypical footprintReduction technique
Full-file ReadWhole file tokenizedUse line ranges
Bash outputEntire stdout/stderrRedirect to a file, read summary
Tool calls (MCP)Result payloadReturn trimmed data server-side
System prompt + tools~10-20K tokensFixed cost
Prior turnsAccumulates/compact or /clear
SKILL.md files loaded2-8K eachLoad only what is needed
Screenshot / image1-2.5K eachDownscale before send

Session-management commands (Claude Code)

CommandEffect
/compactSummarise older turns, keeping recent context
/compact <instructions>Compact with focus (e.g. "keep all bash commands used")
/clearFull reset — new session, no history
/contextShow token counts by source
/resumeResume a previous session by ID

Root causes, ranked by frequency

Based on developer reports across Claude API forums, GitHub issues, and Anthropic community during 2025–2026.

  • 24%
    Full-file reads of large sources. Read(./src/main.py) on a 3K-line file adds ~15K tokens. Multiple such reads exhaust context before the task begins.
  • 18%
    Verbose bash output cached in context. Running npm test or a large build dumps 20-50K tokens of logs. All retained in context.
  • 14%
    Long-running task without /compact. 50-turn coding session with no compaction; context creeps toward the limit.
  • 10%
    Multiple MCP tools returning large payloads. Database queries returning full rows; Github API returning entire diff.
  • 8%
    Screenshots in Computer Use mode. Every screenshot is 1.5-2.5K tokens; 20-iteration session accumulates 30-50K.
  • 7%
    SKILL.md over-loading. Many skills loaded proactively even when the task uses one.
  • 8%
    Repeated file re-reads. Agent forgets it read a file already and reads it again — every duplicate wastes tokens.
  • 11%
    Deep tool-use chains preserved verbatim. Long tool_use → tool_result → tool_use sequences; each result adds context that stays for later turns.

Fixes — copy-paste solutions

Fix #1

Compact preemptively at natural task boundaries

Do not wait for the auto-compact warning.

Run /compact after completing a distinct subtask. This summarises older messages so the current context has room for the next subtask. Optional instructions preserve details you know you will need.

compact_workflow.md
# Session flow that keeps context healthy

# --- Phase 1: implement feature A ---
> Read the existing auth module and add a new SSO provider.
[Claude reads files, edits code, runs tests]
> Great. Now /compact "keep the file paths I edited and the new provider name for future reference"
# Claude summarises phase 1 in a few hundred tokens

# --- Phase 2: implement feature B ---
> Add a settings page for the new SSO provider.
[Claude works on phase 2 with room to spare]
> Ok. /compact "keep the file paths and route names"

# --- Phase 3: run the full test suite and fix regressions ---
> Run npm test and fix anything that broke.
[Long output, many edits — but we have context because we compacted]

# --- If a truly unrelated task ---
> /clear    # full reset, start fresh
> Now, unrelated: refactor the analytics module.
The instructions passed to /compact are gold. "Keep the file paths and function signatures I introduced" is much better than a bare /compact, which uses a generic summarisation.
Fix #2

Read files with line ranges instead of full contents

Read exactly what you need, not the whole file.

Ask Claude to use the Read tool's offset and limit parameters when navigating large files. Also encourage grep-first workflows — find the range first, then read only that range.

ranged_reads.md
# Guide the agent toward line-scoped reads

# --- BAD: whole-file read ---
> Read src/big_module.py     # → 15K tokens

# --- GOOD: grep, then range-read ---
> Find the definition of process_batch in src/big_module.py, then read a
> 40-line window around it.
[Claude runs: rg -n "def process_batch" src/big_module.py
 → line 847
 Reads src/big_module.py, offset=827, limit=40  → ~1K tokens]

# --- Codify in .claude/CLAUDE.md ---
# CLAUDE.md is auto-loaded per project. Add:

```
When reading files larger than 500 lines, first use grep or ripgrep to
locate the relevant symbol, then Read with offset/limit for a 30-50 line
window. Do NOT read whole large files.
```

# Now every session in this project follows the pattern automatically
For 200-500 line files, whole-file reads are fine. The rule kicks in above ~500 lines where the token cost starts to bite.
Fix #3

Split truly-long tasks across sessions with checkpointed state

Some tasks legitimately exceed one session — plan for handoff.

For migrations, large refactors, or long bulk operations, checkpoint state to disk. End the session with a written summary that a fresh session can pick up from.

session_handoff.md
# Pattern for multi-session tasks

# End of session 1:
> We're at 85% context. Before we hit the limit, write a handoff file
> ./HANDOFF.md that documents:
>   1. What we've done (files edited, tests written)
>   2. What remains (with specific file paths and line refs)
>   3. Any decisions we made and why
>   4. Commands to re-establish the working state (branch name, npm version)

[Claude writes HANDOFF.md]

> /exit

# Start of session 2 (fresh /clear):
> Read HANDOFF.md and continue the task from where we left off.

[Claude reads a few KB of structured handoff, starts fresh with full context budget]

# For very long tasks, do this every 2-3 hours:
> Update HANDOFF.md with today's progress. Then /compact.
HANDOFF.md files are also invaluable across teammates. If another engineer picks up the task, they read one file instead of scrolling through a long chat.

Prevention checklist

Ship these seven safeguards once and this error stops appearing in your logs.

  • Run /compact at every natural task boundary — before you need it.
  • For files > 500 lines, always grep first and Read with offset/limit.
  • Redirect large bash output to a file (> /tmp/build.log) and only Read the tail.
  • Add a project CLAUDE.md encoding your team's context-hygiene rules.
  • For multi-session work, checkpoint state to a HANDOFF.md file explicitly.
  • Watch the token counter — /context tells you where the tokens went.
  • Split unrelated subtasks across separate sessions with /clear; do not mix them in one long session.

Frequently asked questions

Same as the underlying model — 200K tokens on Claude Sonnet/Opus 4.6 and 4.7. Extended context (1M+) is available on some model tiers but not always exposed to Claude Code. Check the current docs for your version.
Yes — that is the point. Older detailed turns are replaced with summarised versions. Pass explicit instructions to preserve what matters ("keep the file paths I edited"). Never rely on post-compact context to have exact prior code — it may only have summaries.
/compact summarises older turns and keeps the compacted history plus recent turns — Claude "remembers" the task. /clear is a full reset — Claude has no prior context. Use /clear when switching to a truly unrelated task.
Yes — every turn re-sends the full working context as input. Prompt caching helps: the stable prefix (system prompt + tools + CLAUDE.md) is cached at 10% cost after first send. Volatile recent context and tool outputs are not cached.
Not really — the limit is set by the model. What you can do: reduce what fills it (tighter reads, MCP servers that return summaries, more /compact) and split tasks across sessions. Extended-context model variants may be available at higher cost tiers.

Get the weekly AI-error digest

New fixes, provider status recaps, and one deep tutorial — every Tuesday. 8,400+ engineers.