← All guides

Claude Code Context Management: Keep Sessions Sharp (2026)

Claude Code context management: /compact cuts 200K sessions to ~40K while preserving intent, CLAUDE.md loads permanent context once, 4 session.

Claude Code has a 200K-token context window, but filling it indiscriminately is the fastest way to degrade response quality. After 60+ messages, Claude may miss recent instructions or contradict earlier decisions β€” response accuracy drops measurably. Effective context management (what to include, when to compress, when to reset) is the single biggest productivity variable beyond raw prompt quality.

Why Context Management Matters

As a session grows, Claude spends more tokens "reading its own history" than thinking about your actual task. The degradation curve:

The fix isn't a bigger context window β€” it's strategic compression.

The CLAUDE.md: Permanent Context

The most impactful context management move: write a CLAUDE.md in your project root. Claude reads it automatically at session start, every time.

# Project: e-commerce platform

## Architecture
- Next.js 15 App Router (app/ directory)
- Prisma ORM β†’ PostgreSQL (Neon)
- Stripe for payments, Resend for email
- Deployed on Vercel

## File Structure
src/
  app/         # Pages and API routes
  components/  # React components (shadcn/ui)
  lib/         # Utilities, DB client, auth
  types/       # TypeScript interfaces

## Conventions
- API routes: return NextResponse.json(), always handle errors
- DB queries: lib/db/*.ts, never inline in routes  
- Env vars: access via lib/config.ts, never process.env directly
- Tests: vitest + @testing-library/react, files in __tests__/

## Active Work
Sprint: Payment flow redesign
Files in scope: src/app/api/checkout/, src/components/checkout/
Do not modify: src/auth/ (security audit in progress)

## Run Commands
bun dev          # local dev server
bun test         # run all tests  
bun run build    # production build (must pass before deploy)

This replaces the 5-minute "here's what our project looks like" intro at every session start. With a good CLAUDE.md, you can jump straight to the task.

/compact: Session Context Compression

When a session gets long, use /compact with a task-focused summary:

/compact We're implementing Stripe subscription flow.
Completed:
- POST /api/stripe/checkout-session β€” creates Checkout Session, returns URL
- POST /api/stripe/webhook β€” handles subscription_created, subscription_cancelled
- User model updated with: plan (free/pro/enterprise), stripeCustomerId, planExpiresAt

Currently debugging: webhook signature verification fails in production (works locally).
Suspect: Vercel strips body before verification. Need to use raw body.

After /compact, Claude has a clean slate with just the essential context. The full history is gone β€” you trade history for focus.

When to use /compact:

Selective File Loading

# Wrong: loads everything
/add src/

# Right: load task-relevant files only
/add src/app/api/webhook/route.ts
/add src/lib/stripe.ts
/add src/types/subscription.ts

Rule of thumb: load the 3-5 files most directly relevant to the current task. If you find yourself loading 10+ files, the task is probably too broad β€” split it.

Loading Strategy by Task Type

Bug fix: Load the file with the bug + the test file for it

/add src/lib/auth/session.ts
/add src/lib/auth/__tests__/session.test.ts

New feature: Load the interface definitions + closest related implementation

/add src/types/payment.ts
/add src/app/api/payments/route.ts  # closest existing route

Refactoring: Load only the file being refactored (full file, not partial)

/add src/services/order-processor.ts

Code review: Load the file + its test file

/add src/components/CheckoutForm.tsx
/add src/components/__tests__/CheckoutForm.test.tsx

Context Recovery After /compact

After compacting, Claude loses earlier decisions. When asking about code that was discussed previously:

"We already established that the webhook handler should use raw body for
Stripe signature verification (see src/app/api/stripe/webhook/route.ts line 12).
The issue is: production body is being parsed by Next.js before we can read the raw buffer."

Explicitly re-introduce the constraint. Don't assume Claude remembers what it doesn't have in context.

The Session Lifecycle

Optimal session structure for a feature:

Session start
  β†’ CLAUDE.md auto-loaded
  β†’ /add relevant files (3-5)
  β†’ Task 1: Implement X
      β†’ Test and verify
  β†’ Task 2: Add tests for X
      β†’ Verify test pass
  β†’ /compact with summary of X
  β†’ Task 3: Implement Y
      β†’ Test and verify
  β†’ Final: build gate, commit
Session end

Key: compress before switching major tasks, not after things go wrong.

Multi-Session Context Persistence

For work that spans multiple days:

Option 1: Update CLAUDE.md with Current State

At the end of each session, add a ## Current State section:

## Current State (updated 2026-05-14)
Working on: Subscription upgrade flow
Completed: Checkout session API, webhook handlers
Next: User dashboard showing current plan
Known issues: Webhook sometimes fires twice (idempotency key needed)

Next session, Claude reads this and you start informed.

Option 2: Commit a Work-in-Progress Note

git commit -m "WIP: subscription flow β€” webhook verification working locally

Remaining:
- Production body parsing issue (Vercel strips raw body?)  
- Plan upgrade email not triggering
- Test coverage for cancellation flow needed"

The WIP commit message becomes your session handoff note.

Token Budget Awareness

The context window has costs:

Content Type Approximate Tokens
100-line TypeScript file ~300-500 tokens
500-line file ~1,500-2,500 tokens
30-message session history ~3,000-8,000 tokens
Typical CLAUDE.md ~300-600 tokens
One code review cycle ~2,000-5,000 tokens

With a 200K window, you can fit a lot β€” but quality degrades when context fills with old, irrelevant decisions. Keep it focused.

When to Start a Fresh Session

Start fresh (not /compact) when:

Start fresh with intention: load only CLAUDE.md and the relevant files for the new task.

Frequently Asked Questions

What happens to files I loaded with /add after /compact?

File contents are included in the compact summary if Claude considers them relevant to the summary. If you need them to be in context post-compact, re-add them with /add.

Can I see how much context I've used?

Not directly in the UI, but you can estimate from message count: each back-and-forth exchange with code adds roughly 500-2,000 tokens. At 60+ messages, you're likely past 50K tokens of history.

Does /compact save money?

Not directly β€” you're billed for the full context window on each API call, so compression doesn't save on past calls. It saves on future calls by reducing history tokens. The real value is quality: a clean, focused context produces significantly better outputs.

Should every project have a CLAUDE.md?

Yes, for any project you work on more than once. The break-even point is about 3 sessions: session 1 costs time to write it, sessions 2+ save 5+ minutes each. After a week of daily use, you've saved 30+ minutes while getting better outputs.


Related guides: How to Use Claude Code Effectively Β· Claude Code Complete Guide Β· Claude Code Hooks Guide

P1 Claude Code Power Prompts 300 β€” includes 25 prompts specifically for context management, session handoff, and long-running project workflows. Get it β†’

AI Disclosure: Drafted with Claude Code; all examples tested in Claude Code sessions.

Tools and references