Claude Code Context
Context management is a core skill for using Claude Code efficiently.
The official documentation clearly states: **The context window is Claude Code's most important resource**, and as the context fills up, model performance gradually degrades (called context rot) β this is the core problem you need to actively combat when using Claude Code.
This chapter explains in depth how to use CLAUDE.md instruction files, the auto memory system, context window optimization commands, and other methods to keep Claude efficient during long sessions and across sessions.
* * *
## Context Window Basics
### 1γWhat the Context Window Contains
Claude Code's context window size is **1,000,000 tokens (1 million tokens)**. It holds everything Claude "sees" in the current session:
| Content Source | Loading Timing | Token Usage |
| --- | --- | --- |
| System prompt (Claude Code behavioral norms) | Every session start | Fixed usage |
| CLAUDE.md file | Loaded completely at startup | Depends on file size |
| Auto memory | Loaded at startup (first 200 lines or 25KB) | Has a limit |
| Conversation history | Accumulates over time | Increases with session duration |
| Tool results (file reads, command outputs, etc.) | Appended after each tool call | Logs/large files consume very quickly |
| MCP tool names, Skills descriptions, etc. | Loaded at startup | Medium |
### 2γContext Rot
The official documentation clearly states: as the context fills up, **LLM performance degrades** because attention is scattered across more tokens, and old, irrelevant content starts to interfere with current tasks. Specific symptoms include:
* Claude starts contradicting itself and forgets decisions made earlier
* Responses become vague and generic, with less detail
* Asks the same questions repeatedly that have already been answered
* Corrects the same issue more than twice in the same session
If you notice these symptoms, the context is already "contaminated" β you should proactively use `/compact` or `/clear` instead of continuing to correct in the same session.
Use the `/context` command to view detailed usage analysis of the current context at any time:
/context
It will list token usage by category (system prompt, CLAUDE.md, memory files, session history, etc.) and provide optimization suggestions. It's recommended to check once before starting important tasks.
* * *
## CLAUDE.md Instruction File
CLAUDE.md is the core file for recording static instructions and project specifications in Claude Code. Every time a session starts, Claude automatically loads it into the context window.
### 1γStorage Location and Scope
CLAUDE.md supports multiple locations, **with more specific locations having higher priority**:
| Scope | File Path | Applicable Scenario | Commit to git |
| --- | --- | --- | --- |
| **Organization level** | macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md` Linux/WSL: `/etc/claude-code/CLAUDE.md` | Company coding standards, compliance requirements | Managed by IT |
| **Project level** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Project architecture, coding conventions, workflows | Yes, shared with team |
| **User level** | `~/.claude/CLAUDE.md` | Personal coding preferences, applies to all projects | No, personal private |
| **Local private** | `./CLAUDE.local.md` (added to .gitignore) | Personal project-specific configuration, not committed to git | No, added to .gitignore |
> `CLAUDE.local.md` is the officially recommended way for personal private configuration: sandbox URLs, local test accounts, personal debugging habits, and other content that shouldn't be shared should be placed here instead of in `CLAUDE.md`. When running `/init` and selecting the "Personal" option, it will automatically add this file to `.gitignore`.
### 2γCreating CLAUDE.md
Execute the following command, and Claude will automatically analyze the project and generate an initial CLAUDE.md:
/init
If a CLAUDE.md already exists, `/init` will suggest improvements instead of directly overwriting it. After generation, manually add content that Claude cannot automatically discover (such as files that must not be modified, special constraints, etc.).
You can also use the `#` shortcut in a session to quickly append a memory to CLAUDE.md:
# All API error responses must use { code, message } format
After pressing `#`, enter the content and press Enter. Claude will write it to the CLAUDE.md at the corresponding level as a persistent instruction.
### 3γCLAUDE.md Content Requirements
The official requirement is that each CLAUDE.md file **should be kept under 200 lines**. The larger the file, the more startup tokens it consumes, and Claude's compliance rate actually decreases. Here are content suggestions:
**Should write:**
* Common commands for building, testing, and deploying
* Code conventions: naming conventions, indentation, prohibited patterns
* Key constraints: "Always use pnpm", "Do not modify the migrations/ directory"
* Project architecture description: purpose of main directories
**Should not write:**
* Multi-step operation procedures (should be placed in Skills files)
* Rules that only relate to a specific part of the codebase (should use `.claude/rules/` with path restrictions)
* Information that Claude can discover by reading the code itself
## Example
# CLAUDE.md Example (concise and specific, each file under 200 lines)
## Common Commands
- Package management: Always use pnpm, do not use npm or yarn
- Run tests: pnpm test:watch
- Build: pnpm build
## Code Conventions
- TypeScript strict mode, no any allowed
- Component files use PascalCase naming (e.g., UserProfile.tsx)
- Database timestamps use UTC format uniformly
## Constraints
- Do not directly modify existing files in the prisma/migrations/ directory
- .env.local contains real keys, do not read or output file contents
- API endpoints are managed uniformly in the src/api/ directory, do not make requests directly elsewhere
### 4γPath-Restricted Rules (.claude/rules/)
For larger projects, you can use the `.claude/rules/` directory to split instructions into granular rules that apply based on file paths, avoiding having all rules piled in the root CLAUDE.md that consume startup tokens:
.claude/
βββ rules/
βββ api.md # Only applies to src/api/**/*.ts files
βββ frontend.md # Only applies to src/components/**/*.tsx files
βββ testing.md # Only applies to *.test.ts files
Path-restricted rules only load when Claude reads files in the corresponding directories, and do not consume context in bulk at startup.
* * *
## Auto Memory
Auto memory is a built-in cross-session memory system in Claude Code v2.1.59 and above, **enabled by default**, requiring no configuration. It allows Claude to autonomously record build commands, debugging experiences, code style preferences, and other information discovered during work.
### 1γHow It Works
* Claude doesn't write memory every session β it judges whether information is worth keeping (whether it will be useful in future conversations)
* Memory is isolated by git repository path and stored in `~/.claude/projects//memory/`
* All working trees of the same repository share one set of auto memory
* When writing memory, the terminal displays "Writing memory"; when retrieving next time, it displays "Recalled memory"
### 2γViewing and Editing Memory (/memory)
Use the `/memory` command to view and edit all memory content, including CLAUDE.md at all levels and auto memory:
/memory
In the editor, you can delete inaccurate entries, or use the Auto memory toggle to disable the auto memory feature. You can also temporarily disable it via environment variable:
CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 claude
### 3γActively Making Claude Remember Content
You can directly ask Claude to write memory in conversation:
Remember: Our API tests need a local Redis instance running
From now on: When handling errors, return { code, message } structure uniformly
If you want to upgrade it to a mandatory specification rather than just a preference memory, you can say: "Write this rule to CLAUDE.md", and Claude will write it to the corresponding CLAUDE.md file.
* * *
## Context Window Optimization Commands
### 1γAuto-compaction
Claude Code **automatically triggers compaction** when the context approaches the limit (around 75% usage), summarizing the conversation history and continuing work. However, the official recommendation is not to wait for auto-compaction β you should **proactively trigger it manually at 60~70%** to avoid being interrupted during critical tasks, and manual compaction allows you to control what content to preserve via instructions.
### 2γCompact Context (/compact)
Manually compact conversation history, summarizing a long session into a concise summary to continue working:
/compact
`/compact` supports passing custom instructions to control what content to focus on preserving during compaction:
/compact Focus on the API changes
/compact Preserve the architectural decisions for the authentication flow, discard the invalid attempts during debugging
> Compaction is a lossy operation. During compaction, Claude is in the state of the most full context and weakest performance. If you don't give instructions, it may discard content you consider important. **Proactively compact immediately after major decisions and use instructions to specify what to preserve** β this is much better than waiting for auto-compaction.
### 3γClear Context (/clear)
Clear all conversation history when switching to a new task:
/clear
After clearing, CLAUDE.md and auto memory are not affected and will still load in the new session. The official recommendation: **If you've corrected the same issue more than twice in the same session, just /clear β start over with a more precise prompt carrying the learned constraints**. A clean session with a better prompt is almost always better than continuing to correct in a contaminated context.
### 4γRewind to Checkpoint (/rewind)
Claude Code automatically creates checkpoints before each file modification. Double-click `Esc` or execute `/rewind` to open the rewind menu and select a checkpoint to restore:
/rewind (or double-click Esc key)
In the rewind menu, you can choose the following operations:
| Operation | Effect | Applicable Scenario |
| --- | --- | --- |
| **Restore conversation + code** | Rewind conversation history and file changes, complete restore | Claude went off track, changes have problems, undo everything |
| **Restore conversation only** | Rewind conversation history, preserve file changes | Want to try different approaches, but code changes can be kept |
| **Restore code only** | Restore files to checkpoint state, preserve conversation | Code got broken, but the analysis in conversation has reference value |
| **Summarize from here** | Compress the conversation after this checkpoint into a summary, preserve complete history before it | Only want to clean up the redundant conversation in the second half, preserve complete context from the first half |
> Checkpoints persist across sessions β you can still rewind to previous checkpoints after closing the terminal. This is not a replacement for git, but it's more convenient than manual git stash during exploratory experiments.
### 5γQuick Questions Without Contaminating Context (/btw)
If you need to quickly look up a small detail but don't want this Q&A to enter the conversation history (consuming context), use `/btw`:
/btw What is the TypeScript version in this project?
The answer will be displayed as a floating layer, and neither the question nor answer will enter the conversation history β suitable for looking up configuration, version numbers, and other one-time information that doesn't need to be preserved.
* * *
## Session Management Commands
| Command | Function | Usage Scenario |
| --- | --- | --- |
| `/context` | View detailed token usage analysis for each part of context | Troubleshoot which part consumes too many tokens |
| `/compact ` | Compress conversation history into summary, can specify what to preserve | Proactively compact at 60~70% context usage |
| `/clear` | Clear all conversation history, preserve CLAUDE.md and memory | Switch to new task, or context is severely contaminated |
| `/rewind` (or double-click Esc) | Open checkpoint menu, can choose to restore conversation/code/both, or summarize from a point | Claude went off track, need to rewind and retry |
| `/memory` | View and edit CLAUDE.md and auto memory content | Check if memory is accurate, delete outdated entries |
| `/btw` | Quick question, answer doesn't enter conversation history | Look up small details, don't want to contaminate context |
| `/init` | Analyze project and generate or improve CLAUDE.md | First use in new project, or project has major changes |
| `#` (shortcut) | Quickly add a persistent instruction to CLAUDE.md | Record conventions or agreements at any time |
| `claude --continue` | Continue the most recent session | Continue working after reopening terminal |
| `claude --resume` | Select a session from history list to continue | Restore a specific task from a few days ago |
* * *
## Common Problems and Solutions
**Problem One: Claude doesn't follow the rules in CLAUDE.md**
* Check if CLAUDE.md is too large (compliance rate drops when it exceeds 200 lines)
* Change vague statements to specific instructions: not "write clean code", but "use 2 spaces for indentation"
* Use `/memory` to check for conflicting auto memory entries
* Consider using `.claude/rules/` to split rules by file path to reduce loading each time
**Problem Two: Claude starts contradicting itself and "forgets" previous decisions**
* This is a typical symptom of context rot β don't continue correcting in the same session
* Run `/compact Preserve key decisions`, or directly `/clear` and start over with a summary
* Write important conclusions to CLAUDE.md using the `#` shortcut to ensure they remain effective in the next session
**Problem Three: Key information is lost after /compact**
* Pass specific instructions during compaction: `/compact Preserve the architectural decisions for the authentication flow and the confirmed API format`
* Write the most important conclusions to CLAUDE.md before compaction
* Failed debugging attempts aren't worth preserving β you can compact more aggressively or use /clear
**Problem Four: How to continue previous work after closing terminal**
* Use `claude --continue` to continue the most recent session
* Use `claude --resume` to select a specific session from the history list
* Use `/rename` to give important sessions a descriptive name (e.g., "oauth-migration") to make them easier to find later
**Problem Five: A large task will generate a lot of tool output β how to avoid context overflow**
* Use subagent to delegate execution: the main conversation only receives summaries, intermediate outputs stay in the subagent's independent context
* For example: `Use a subagent to analyze all log files, find performance bottlenecks, and just tell me the conclusions`
YouTip