DEV Community

shohei-ai-lab
shohei-ai-lab

Posted on

Stop Losing Context Mid-Session: A Practical Guide to Claude Code's /compact, /clear, and /context Commands

You're deep into a refactoring session. Claude Code has been reading files, running tests, and building features for an hour. Then suddenly — it asks you a question you already answered 20 minutes ago.

Or worse: it suggests an approach that contradicts the design decision you both agreed on at the start of the session.

The problem isn't that Claude is broken. It's that the context window is full, and important information got silently compressed away.

Every Claude Code user hits this wall eventually. Here's how to manage it deliberately instead of reactively.


Why Context Overflows Faster Than You Think

Claude Code's context window accumulates everything:

  • Your prompts and Claude's responses
  • Every file read (hundreds to thousands of tokens each)
  • Command outputs (test results, build logs, error traces)
  • Generated code diffs

A single cat of a 200-line file can burn 500+ tokens. Read 10 files, run a test suite, and inspect the error output? You've easily consumed half your context budget before the real work begins.

When the window fills up, Claude Code auto-compacts — summarizing older messages to free space. This is a safety net, not an optimization. The auto-compaction doesn't know which parts of your conversation are critical to preserve.


The 4 Commands You Need

/context — Check Your Budget

Before you act, know where you stand.

/context
Enter fullscreen mode Exit fullscreen mode

This renders a colored grid showing how much context is consumed. It also flags optimization suggestions: tools consuming excessive tokens, memory bloat, and capacity warnings.

Add all for a per-item breakdown:

/context all
Enter fullscreen mode Exit fullscreen mode

When to use it: Whenever responses feel slow or lower quality. Think of it as checking fuel level before a long drive.

/compact — Summarize and Continue

This is the command you'll use most. It summarizes the conversation so far, freeing context while keeping the session alive.

/compact
Enter fullscreen mode Exit fullscreen mode

The key feature: you can tell it what to preserve.

/compact Keep the auth module design decisions and the list of remaining edge cases
Enter fullscreen mode Exit fullscreen mode

With focus instructions, Claude prioritizes retaining what you specify and aggressively compresses everything else (setup discussions, failed debug attempts, resolved issues).

When to use it:

  • Transitioning between work phases (design → implementation)
  • After solving a bug (keep the fix, drop the trial-and-error)
  • When /context shows 70%+ usage

/autocompact — Tune the Safety Net

Controls when auto-compaction triggers.

/autocompact 500k
Enter fullscreen mode Exit fullscreen mode

This sets the threshold to 500k tokens. Use auto to reset to the model-optimized default:

/autocompact auto
Enter fullscreen mode Exit fullscreen mode

The setting persists across sessions.

When to use it:

  • Large refactoring (raise it — you need more info retained)
  • Quick single-file fixes (leave at default)
  • After switching models (different models have different optimal thresholds)

/clear — Full Reset

Wipes everything and starts fresh. Unlike /compact, no summary is kept.

/clear
Enter fullscreen mode Exit fullscreen mode

Name the cleared session so you can resume it later:

/clear auth-bugfix
Enter fullscreen mode Exit fullscreen mode

Now you can get back to that conversation anytime with /resume auth-bugfix.

When to use it: Switching to a completely unrelated task where previous context adds zero value.


Practical Patterns

Pattern 1: Phase-Based Compaction

For multi-hour sessions, compact at every phase transition:

Design discussion (30 min)
  └── /compact Keep design conclusions and open questions

Implementation phase 1 (60 min)
  └── /context → /compact if > 70%

Debug session (45 min)
  └── /compact Keep: root cause was X, fix is Y. Drop: failed attempts

Implementation phase 2 (60 min)
  └── final push
Enter fullscreen mode Exit fullscreen mode

The trial-and-error from phase N is rarely useful in phase N+1.

Pattern 2: Task Switching

Task A: Fix login bug
  └── Done → /clear login-fix

Task B: Dashboard redesign
  └── Done → /clear dashboard-v2

Task C: New API endpoint
  └── Working...
Enter fullscreen mode Exit fullscreen mode

Zero context overlap between tasks = use /clear. Name them for future reference.

Pattern 3: Debug Cleanup

Debugging is a context hog. Error traces, stack dumps, hypothesis testing — it all piles up.

Once you find the fix:

/compact Root cause: race condition in auth middleware.
Fix: added mutex lock in handleRequest.
Hypotheses A and B were dead ends — discard.
Enter fullscreen mode Exit fullscreen mode

You keep the conclusion, drop the journey.


Common Mistakes

Mistake 1: Compacting Too Often

Over-compacting loses the "why" behind decisions. Claude starts making suggestions that contradict earlier agreements because the reasoning was compressed away.

Fix: Put persistent design decisions in CLAUDE.md. It's re-read on every compaction — nothing in that file gets lost.

Mistake 2: Using /compact When You Need /clear

Compacting a session about login bugs before starting dashboard work = leftover login context polluting your dashboard session.

Rule of thumb: If zero information from the previous task helps the next one, /clear. If there's any thread connecting them, /compact with focus.

Mistake 3: Never Checking /context

You only discover the problem when auto-compaction silently fires and drops something important.

Fix: Check /context before reading large files or running verbose commands. If you're at 70%+, compact first.

Mistake 4: Compacting Without Focus Instructions

Without guidance, Claude decides what's important on its own. Its priorities may not match yours.

Fix: Always add a one-liner. Focus on: "what's next", "what constraints must survive", "what's the current state". Takes 5 seconds, saves you from repeating yourself later.


Quick Reference

Command Effect Session When
/context Show usage Continues Quality feels off
/context all Detailed breakdown Continues Need to find what's consuming tokens
/compact Summarize conversation Continues Phase transition, 70%+ usage
/compact [focus] Summarize with priority Continues Keep specific info alive
/autocompact [size] Set auto-trigger threshold Persists Adjust safety net timing
/clear Full reset New session Switching to unrelated task
/clear [name] Named reset New session Might need to return later

The Takeaway

Context management is the difference between a productive 4-hour session and a frustrating one that degrades after 45 minutes.

The shift is simple: move from reactive (waiting for auto-compaction to save you) to proactive (compacting deliberately, with intent, at natural breakpoints).

Your context window is a resource. Manage it like you manage memory in production code.


For more Claude Code configuration tips, check out our free starter templates:

Top comments (0)