Context Management

Control what enters your AI agent's context window. The difference between 2,000 and 60,000 tokens is often not task complexity - it's context discipline.

Intermediate 10 min read

What Goes into Context

In every AI agent call, the full context window is built from these components (in order):

Context Window Anatomy
┌─────────────────────────────────────────────┐
│  SYSTEM PROMPT (your CLAUDE.md rules)       │  <- stable, cache this
│  ~200-2,000 tokens                          │
├─────────────────────────────────────────────┤
│  CONVERSATION HISTORY (all prior turns)     │  <- grows every message
│  ~0 to 100,000+ tokens                     │
├─────────────────────────────────────────────┤
│  TOOL RESULTS (file reads, grep, bash)      │  <- added as history grows
│  ~100 to 5,000 tokens per tool call         │
├─────────────────────────────────────────────┤
│  CURRENT USER MESSAGE                       │  <- your latest prompt
│  ~20 to 500 tokens                          │
└─────────────────────────────────────────────┘

The system prompt and CLAUDE.md are the one part you fully control. The conversation history grows with every turn. Tool results are added each time the agent reads a file or runs a command. Managing all three is what context management is about.

CLAUDE.md - Your Context Blueprint

CLAUDE.md is a special file read by Claude Code at session start. It is your opportunity to give the agent exactly the context it needs - and nothing more. A well-written CLAUDE.md prevents the agent from doing exploratory reads to orient itself.

CLAUDE.md - Token-Efficient Template
# Project: MyApp

## Architecture (read this before touching any file)
- PHP 8.2 backend, MySQL 8, Bootstrap 5 frontend
- Entry: /public/index.php -> routes to /app/controllers/
- Config: /config/app.php (DB creds, constants)
- All DB queries via PDO in /app/models/ (no raw SQL in controllers)

## Key files by area
- Auth: /app/controllers/AuthController.php, /app/models/UserModel.php
- Billing: /app/services/BillingService.php, /config/razorpay.php
- Admin: /admin/index.php (separate session namespace)

## Conventions
- Functions: snake_case. Classes: PascalCase
- Error handling: throw exceptions, caught in /app/middleware/ErrorHandler.php
- No inline CSS - use /assets/css/app.css only

## What to NOT read
- /vendor/ (Composer dependencies - never touch)
- /storage/logs/ (log files, irrelevant)
- /node_modules/ (never exists, just in case)

## Testing
- PHPUnit in /tests/, run: composer test
- All model methods must have a corresponding test

Notice what this CLAUDE.md does: it tells the agent the directory structure so it can grep directly instead of reading everything. It names key files by area so the agent reads only what is relevant. It explicitly lists what to ignore.

What to Include vs Exclude

Include in contextExclude from context
The file directly containing the bug or featureAll unrelated files in the project
The interface/contract a file must implementFull vendor/node_modules directories
The test that is failing (exact file)Build artifacts, compiled output, logs
A short schema definition for DB tasksFull database dumps or migrations history
Error messages (trimmed to relevant lines)Full stack traces with 50+ frames
The specific function signature to matchAn entire 500-line library file
Architectural rules (in CLAUDE.md)Redundant comments that explain obvious code

Session Hygiene

Every message in a session adds to the context window permanently (within that session). Good session hygiene prevents runaway token growth:

  • One task per session - do not mix "fix auth bug" and "add new feature" in one session
  • Start fresh for unrelated work - prior conversation about a different file adds noise
  • Avoid test-and-iterate loops in one session - each failed test run adds output tokens to history; start a new session if stuck
  • Trim error output before pasting - paste only the relevant error lines, not the full 200-line log
Anti-pattern vs Best practice
# Anti-pattern: one session for everything
Turn 1: Fix the login bug              (accumulates 3,000 tokens)
Turn 2: Also add dark mode CSS         (adds 4,000 tokens - unrelated)
Turn 3: And update the README          (adds 1,500 tokens)
Turn 4: Back to login - still broken   (now 8,500 tokens of noise in context)

# Best practice: focused sessions
Session A: Fix login bug (3 turns, ~6,000 tokens total, done)
Session B: Add dark mode CSS (2 turns, ~4,000 tokens total, done)
Session C: Update README (1 turn, ~1,500 tokens total, done)

.claudeignore

Claude Code respects a .claudeignore file in your project root (same syntax as .gitignore). Files and directories listed here will not be read by the agent even if it tries to access them. This is your safety net for large directories.

.claudeignore
# Never include these in agent context
vendor/
node_modules/
storage/logs/
storage/cache/
*.log
*.lock
dist/
build/
coverage/
.git/
# Large generated files
database/seeds/large_seed.sql
docs/api-full.json

Context Checklist

Before each session, run through this mental checklist:

  • [ ] Does my CLAUDE.md point to the right files for this area of the codebase?
  • [ ] Am I starting a new session (or is prior history genuinely relevant)?
  • [ ] Have I trimmed any error messages or logs to just the essential lines?
  • [ ] Is my task focused enough for one session, or should I split it?
  • [ ] Does my .claudeignore exclude vendor/, logs/, and build artifacts?
  • [ ] Am I asking the agent to read a whole file, or just the relevant function?
Reference by line range, not whole files

When you know the issue is in a specific function, ask the agent to read lines 45-90 of the file rather than the full file. In Claude Code you can say "Read auth.php lines 45-90" and the agent will use the Read tool with an offset, using a fraction of the tokens.

Frequently Asked Questions

For unrelated tasks - yes. Each session starts with only your system prompt and CLAUDE.md, keeping context minimal. For related tasks (debugging the same feature, iterating on the same file), continuing the session is fine because the shared history is relevant.

Aim for 200-500 lines of high-signal content. Every line of CLAUDE.md is re-sent (or cached) on every call, so avoid padding it with obvious information. Include architecture decisions, key conventions, non-obvious constraints, and tool preferences. Skip things the AI can infer from the code itself.

No - Claude Code reads files only when it decides they are needed via tool calls, or when you explicitly reference them. However without good CLAUDE.md guidance the agent may read broadly to orient itself. A good CLAUDE.md tells the agent exactly where to look, preventing exploratory reads.

In a running session, prior messages cannot be truly "forgotten" - they remain in the context window. The practical solution is to start a new session. For automated workflows, use the API directly and construct only the messages you need each call rather than maintaining a long conversation history.