Skip to content

How to Manage Context Window in Claude Code: Practical Strategies for Token Management

Problem

I lost hours of work because Claude Code compacted my context at the wrong moment.

I was debugging a complex authentication flow. I had spent 45 minutes reading files, tracing through the codebase, and building a mental model of how the OAuth integration worked. Then suddenly, Claude asked me a basic question:

“What authentication system are you using?”

I had already explained this three times. All that exploration context was gone. The auto-compaction had wiped my research from Claude’s memory.

But the worst part? I had no idea when the compaction happened. There’s no sidebar showing token count. No warning before context is cleared. No way to know if my important findings survived.

A Reddit user captured this frustration perfectly:

“No sidebar like OpenCode that shows you how many tokens your context window has consumed. All compactions happen automatically when LLM wants, so experienced users that know how to manage that window, when to compact, when to write a plan file and execute with a fresh session, gets impossible to be applied.”

I needed to figure out how to manage context when there’s no visibility into context.

What I discovered

I researched strategies from experienced Claude Code users and found a fundamental principle: Context window is RAM, files are disk.

Context Window vs Files
Context Window = RAM (Volatile, Limited)
- Holds recent conversation, file reads, tool outputs
- ~200K tokens capacity for Claude models
- Gets compacted automatically when approaching limits
- Important information CAN BE LOST during auto-compaction
Files = Disk (Persistent, Unlimited)
- Plans survive context compaction
- Findings can be referenced later
- Progress tracking persists across sessions
- No practical limit on storage

The problem is Claude Code provides no visibility into:

What You Can’t SeeWhy It Matters
Current token countDon’t know how close to limit
When auto-compaction triggersCan’t prepare for context loss
What gets preservedMay lose critical findings
Context health statusCan’t proactively manage

Strategy 1: Strategic Compaction

Instead of waiting for auto-compaction, I trigger /compact at logical boundaries.

When to compact

TimingReason
After exploration, before executionResearch context is summarized, implementation plan preserved
After completing a milestoneFresh start for next phase
Before major context shiftsClear old context before different task
After debugging sessionRemove error-resolution noise

When NOT to compact

  • Mid-implementation of related changes
  • During multi-step refactoring
  • While maintaining complex state
Strategic Compact Workflow
# After reading several files and understanding the codebase
/compact
# Now start fresh with only your plan in context
# The AI will ask clarifying questions based on your summary

The key difference: I control when context is compressed, not the model.

Strategy 2: File-Based Planning

I create three planning files in every project:

FilePurposeUpdate Frequency
task_plan.mdPhases, progress, decisionsAfter each phase
findings.mdResearch, discoveriesAfter ANY discovery
progress.mdSession log, test resultsThroughout session

Template for task_plan.md

task_plan.md
# Task: [Your Task Name]
## Goal
[Clear, specific goal statement]
## Phases
- [ ] Phase 1: [Name] - Status: pending
- Key steps: ...
- [ ] Phase 2: [Name] - Status: pending
- Key steps: ...
## Current State
Phase: [current phase]
Next Action: [what to do next]
## Decisions Made
| Decision | Rationale | Date |
|----------|-----------|------|
| ... | ... | ... |
## Errors Encountered
| Error | Attempt | Resolution |
|-------|---------|------------|
| ... | ... | ... |

Template for findings.md

findings.md
# Findings
## Codebase Structure
[Key discoveries about the code]
## APIs/Functions
[Important APIs discovered]
## Constraints
[Technical constraints found]
## Risks
[Potential issues identified]

When context is compacted, I just read these files to restore my place.

Strategy 3: The 2-Action Rule

After every 2 view/browser/search operations, I save key findings to text files.

This prevents:

  • Multimodal information loss (screenshots, images)
  • Context overflow from large file reads
  • Loss of research during exploration
2-Action Rule Workflow
1. Read file A (context used: 1 read)
2. Read file B (context used: 2 reads) -> WRITE findings.md
3. Read file C (context used: 1 read)
4. Read file D (context used: 2 reads) -> WRITE findings.md

I learned this from a user on Reddit:

“One thing that has helped me is treating the agent like a system you instrument: explicit plans, tool-call boundaries, small sessions, and checkpoints so it cannot drift for hours.”

Strategy 4: Read Before Decide

Before major decisions, I read my planning files:

  1. Read task_plan.md - Re-orient to goals
  2. Read findings.md - Recall what I learned
  3. Read progress.md - Check what’s done

Why? Context window may have been compacted. Reading brings current state back into attention.

This simple habit has saved me multiple times from making decisions based on stale context.

Strategy 5: Session Boundaries

I work in small, focused sessions instead of marathon runs:

Session TypeDurationWhen to End
Exploration15-30 minAfter mapping codebase
Planning10-20 minAfter creating task_plan.md
Implementation30-60 minAfter completing a feature
Debugging15-30 minAfter finding root cause

End-of-session checklist

  • Update task_plan.md with current state
  • Write findings to findings.md
  • Log progress in progress.md
  • Note next action for next session

Strategy 6: The 5-Question Reboot Test

If I can answer these questions, my context management is solid:

QuestionAnswer Source
Where am I?Current phase in task_plan.md
Where am I going?Remaining phases
What’s the goal?Goal statement in plan
What have I learned?findings.md
What have I done?progress.md

If I can’t answer: I read my planning files immediately.

Advanced: Hook-Based Reminders

For users comfortable with hooks, create a strategic compact reminder:

~/.claude/settings.json
{
"hooks": {
"PreToolUse": [{
"matcher": "tool == \"Edit\" || tool == \"Write\"",
"hooks": [{
"type": "command",
"command": "~/.claude/skills/strategic-compact/suggest-compact.sh"
}]
}]
}
}

This tracks tool calls and suggests compaction at thresholds.

Context Management Decision Matrix

When I face specific situations, I follow this decision tree:

Context Decision Matrix
| Situation | Action | Reason |
|-----------|--------|--------|
| Starting complex task | Create task_plan.md | Plan persists across compaction |
| After reading 3+ files | Write to findings.md | Prevents information loss |
| Before major decision | Read planning files | Re-orient if context stale |
| Session > 1 hour | Consider /compact | Fresh context for next phase |
| Error occurred | Log to progress.md | Prevents repeating mistakes |
| Switching tasks | /compact + new plan | Clear previous context |

Workarounds for Missing Features

Since Claude Code lacks visibility features, I adapted my workflow:

Missing: Token Counter

  • Workaround: Track tool calls manually or via hooks
  • Metric: ~50 tool calls = consider compaction
  • Proxy: 1 hour session = high context usage

Missing: Context Health Indicator

  • Workaround: Can’t answer the 5-question test? Context is stale
  • Metric: AI asks questions about things already explained = context lost

Missing: Manual Compaction Control

  • Workaround: /compact command exists but timing is manual
  • Strategy: Compact at MY boundaries, not the model’s

Missing: Sidebar Visibility

  • Workaround: Use external terminal or note-taking
  • Metric: Track session duration and complexity

Comparison: OpenCode vs Claude Code

FeatureOpenCode CLIClaude Code
Token CounterYes (sidebar)No
Context HealthVisibleHidden
CompactionManual controlAuto + /compact
VisibilityHighLow
Workaround NeededNoYes

For OpenCode users transitioning: Your token-watching habits remain valuable. Apply them to session duration and tool call counts instead of a visible counter.

Summary

In this post, I showed how to manage context window in Claude Code despite the lack of visibility. The key points are:

  1. Embrace file-based planning - Files are unlimited persistent memory
  2. Compact strategically - At logical boundaries, not arbitrary points
  3. Small sessions - Work in focused bursts, not marathon sessions
  4. Write immediately - The 2-action rule prevents information loss
  5. Read before decide - Re-orient from files when context may be stale

The fundamental insight: You can’t see the context window, but you can manage it through external discipline. Treat context as finite RAM and files as infinite disk. Plan, persist, and compact on your terms.

Why context compaction matters

Context compaction in LLMs happens because:

  1. Token limit economics: Each token costs money and memory. Models can’t hold infinite context.
  2. Attention decay: Even within limits, older context gets less “attention” than newer tokens.
  3. Summarization trade-offs: Auto-compaction summarizes old context, but summarization loses detail.

How auto-compaction likely works

While Anthropic hasn’t published exact details, auto-compaction typically:

  • Keeps the most recent N tokens
  • Summarizes older conversation into a compressed form
  • Preserves system instructions and key file contents
  • May lose specific details from earlier exploration

Future developments

Anthropic is actively working on context management. Follow the Anthropic blog and release notes for:

  • Potential token counter feature
  • Better visibility into context health
  • Manual compaction controls
  • Improved summarization algorithms

Final Words + More Resources

My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!

Comments