Claude Code Context Management

Context management is a core skill for using Claude Code efficiently.

The official documentation explicitly states:"The context window is Claude Code's most important resource"As the context fills up, model performance gradually declines (called context rot) — this is a core issue to actively combat when using Claude Code.

This chapter explains in depth how to use CLAUDE.md instruction files, the auto memory system, and context window optimization commands to keep Claude efficient in long sessions and across sessions.


Context Window Basics

1. What Does the Context Window Contain

Claude Code's context window size is1,000,000 tokens (1 million tokens)It contains everything Claude "sees" in the current session:

Content Source Loading Timing Token Usage
System Prompt (Claude Code Behavioral Guidelines) Loaded at every session start Fixed usage
CLAUDE.md File Fully loaded at startup Depends on file size
Auto Memory Loaded at startup (first 200 lines or 25KB) Has a cap
Conversation History Accumulates Continuously increases with the session
Tool Results (file reads, command outputs, etc.) Appended after each tool call Logs/large files consume tokens very quickly
MCP tool names, Skills descriptions, etc. Loaded at startup Medium

2. Context Rot

The official docs explicitly state: as the context fills up,LLM performance will declinebecause attention is spread across more tokens, and old, irrelevant content begins to interfere with the current task. Specific symptoms include:

  • Claude becomes contradictory and forgets previously agreed decisions
  • Responses become vague and general, with fewer details
  • Asking the same question repeatedly even though it has already been answered
  • Correcting the same issue more than twice in the same session

If the above symptoms occur, it means the context is already "polluted." At this point you should proactively use/compactor/clearto handle it, rather than continuing to correct within the same session.

Use the/contextcommand to view a detailed usage analysis of the current context at any time:

/context

It lists token usage by category (system prompt, CLAUDE.md, memory files, session history, etc.) and provides optimization suggestions. It is recommended to check once before starting important tasks.


CLAUDE.md Instruction File

CLAUDE.md is the core file in Claude Code that records static instructions and project conventions. At the start of each session, Claude automatically loads it into the context window.

1. Storage Location and Scope

CLAUDE.md supports multiple locations,more specific locations have higher priority:

Scope File path Use case Commit to git?
Organization-level macOS: /Library/Application Support/ClaudeCode/CLAUDE.md
Linux/WSL: /etc/claude-code/CLAUDE.md
Company coding standards, compliance requirements Centrally managed by IT
Project-level ./CLAUDE.mdor./.claude/CLAUDE.md Project architecture, coding standards, workflows Yes, shared with the team
User-level ~/.claude/CLAUDE.md Personal coding preferences, applies to all projects No, personally private
Local private ./CLAUDE.local.md(add to .gitignore) Personal project-specific configuration, not committed to git No, add to .gitignore

CLAUDE.local.mdThis is the officially recommended way for personal private configuration: sandbox URLs, local test accounts, personal debugging habits, and other content that should not be shared should be placed here rather thanCLAUDE.mdin. Run/initwhen selecting the "Personal" option, it will automatically add the file to.gitignore。

2. Creating CLAUDE.md

Run the following command, and Claude will automatically analyze the project and generate an initial CLAUDE.md:

/init

If a CLAUDE.md already exists,/initit will suggest improvements rather than overwriting it directly. After generation, manually add content that Claude cannot discover automatically (such as files that must not be modified, special constraints, etc.).

You can also use in the session#the shortcut key to quickly append a memory to CLAUDE.md:

# 所有 API 错误响应必须使用 { code, message } 格式

Press#after entering content and pressing Enter, Claude will write it to the CLAUDE.md at the corresponding level and save it as a persistent instruction.

3. CLAUDE.md Content Requirements

The official requirement is that each CLAUDE.md filebe kept within 200 lines. The larger the file, the more startup tokens it consumes, and the lower Claude's compliance rate becomes. Here are content recommendations:

Should include:

  • Common commands for build, test, and deployment
  • Code style: naming conventions, indentation, prohibited patterns
  • Key constraints: "always use pnpm", "do not modify the migrations/ directory"
  • Project architecture description: the purpose of major directories

Should not include:

  • Multi-step operational workflows (should be placed in the Skills file)
  • Rules relevant only to a specific part of the codebase (should use.claude/rules/path-based scoping)
  • Information that Claude can discover on its own by reading the code

Examples

# CLAUDE.md example (concise and specific, keep each file within 200 lines)

## Common commands
- Package management: always use pnpm, do not use npm or yarn
- Run tests: pnpm test:watch
- Build: pnpm build

## Code style
- TypeScript strict mode, `any` is not allowed
- Component files use PascalCase naming (e.g., UserProfile.tsx)
- Database timestamps consistently use UTC format

## Constraints
- Directly modifying existing files under the prisma/migrations/ directory is prohibited
- .env.local contains real secrets; reading or outputting the file contents is prohibited
- API endpoints are uniformly managed under the src/api/ directory; do not make requests directly elsewhere

4. Path-Based Scoped Rules (.claude/rules/)

For larger projects, you can use.claude/rules/directory to split instructions into fine-grained rules that apply by file path, avoiding all rules being piled into the root CLAUDE.md and consuming startup tokens:

.claude/
└── rules/
    ├── api.md         # 只对 src/api/**/*.ts 文件生效
    ├── frontend.md    # 只对 src/components/**/*.tsx 文件生效
    └── testing.md     # 只对 *.test.ts 文件生效

Path-scoped rules are only loaded when Claude reads files under the corresponding directory; they do not occupy the full context at startup.


Auto Memory

Auto memory is a cross-session memory system built into Claude Code v2.1.59 and above.It is enabled by defaultand requires no configuration. It lets Claude autonomously record information discovered during work, such as build commands, debugging experience, and code style preferences.

1. How It Works

  • Claude doesn't write memory every session; it judges whether the 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 worktrees of the same repository share one auto memory.
  • When writing memory, the terminal shows "Writing memory"; on later retrieval, it shows "Recalled memory".

2. Viewing and Editing Memory (/memory)

Use the/memorycommand to view and edit all memory content, including CLAUDE.md at various levels and auto memory:

/memory

In the editor, you can delete inaccurate entries, or use the Auto memory switch to disable auto memory. You can also temporarily disable it via environment variables:

CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 claude

3. Proactively Making Claude Remember Content

In conversation, you can directly ask Claude to write memory:

记住:我们的 API 测试需要本地运行一个 Redis 实例
以后请记住:处理错误时,统一返回 { code, message } 结构

If you want to upgrade it to a mandatory rule rather than just a preference memory, you can say: "Write this rule into CLAUDE.md", and Claude will write it into the corresponding CLAUDE.md file.


Context Window Optimization Commands

1. Auto-compaction

Claude Code automatically triggers compaction when thecontext approaches the limit(at around 75% usage), summarizing conversation history into a digest and continuing to work. However, the official recommendation is not to wait for auto-compaction; instead,proactively trigger it manually at 60~70%.This avoids being interrupted in the middle of critical tasks, and manual compaction lets you control what content is retained via instructions.

2. Compacting Context (/compact)

Manually compact conversation history, summarizing long sessions into a concise digest to continue working:

/compact

/compactSupports passing custom instructions to control what content is prioritized during compaction:

/compact Focus on the API changes
/compact 保留认证流程的架构决策,丢弃调试过程中的无效尝试

Compaction is a lossy operation. During compaction, Claude is in the state of fullest context and weakest performance. If you don't give instructions, it may drop content you consider important.Proactively compact immediately after major decisions, and use instructions to specify what to keep.This works much better than waiting for auto-compaction.

3. Clearing Context (/clear)

Clears all conversation history when switching to a completely new task:

/clear

After clearing, CLAUDE.md and auto memory are unaffected and will still be loaded in new sessions. Official recommendation:If you've corrected the same issue more than twice in the same session, just /clear and restart with a more precise prompt carrying the constraints you've learned.—A clean session with a better prompt is almost always better than continuing to correct in a polluted context.

4. Rolling Back to a Checkpoint (/rewind)

Claude Code automatically creates a checkpoint before each file modification. Double-clickEscor run/rewindto open the rollback menu and select the checkpoint to restore:

/rewind
(或双击 Esc 键)

In the rollback menu, you can choose the following actions:

Action Effect Use case
Restore conversation + code Reverts conversation history and file changes, fully restoring the state. When Claude went off track and the changes are problematic; undo everything.
Restore conversation only Reverts conversation history, keeps file changes. When you want to retry a different approach but keep the code changes.
Restore code only Restores files to checkpoint state, keeps conversation. When code is broken but the analysis in the conversation is still valuable.
Summarize from here Compresses conversation after the checkpoint into a summary, preserving the full history before it. When you just want to clean up redundant conversation in the latter part while keeping the full earlier context.

Checkpoints persist across sessions—you can still roll back to previous checkpoints after closing the terminal. This is not a replacement for git, but it's more convenient than manual git stash in exploratory experiments.

5. Quick Questions Without Polluting Context (/btw)

If you need to quickly look up a small detail but don't want the Q&A to enter conversation history (consuming context), use/btw:

/btw 这个项目的 TypeScript 版本是多少?

The answer will be displayed in a floating layer, and neither the question nor the answer will enter the conversation history. Suitable for looking up configuration, version numbers, and other one-off information that doesn't need to be retained.


Session Management Commands

Command Function Use case
/context View detailed token usage analysis for each part of the context Troubleshoot which part consumed too many tokens
/compact [指令] Compress conversation history into a summary, with the option to specify what to keep Proactively compress when context is at 60~70%
/clear Clear all conversation history, keeping CLAUDE.md and memory Switch to a new task, or when the context is severely polluted
/rewind(or double-press Esc) Open the checkpoint menu to choose to restore conversation/code/both, or resume from a certain summary Claude has gone off track, need to roll back and retry
/memory View and edit CLAUDE.md and auto-memory content Check whether memory is accurate, delete outdated entries
/btw Quick question, the answer does not go into conversation history Look up small details without polluting the context
/init Analyze the project and generate or improve CLAUDE.md First use in a new project, or when the 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 the terminal
claude --resume Choose a session from the history list to continue Resume a specific task from a few days ago

Common Issues and Solutions

Issue 1: Claude does not follow the rules in CLAUDE.md

  • Check whether CLAUDE.md is too large (compliance rate drops when it exceeds 200 lines)
  • Change vague wording to specific instructions: don't say "write clean code", say "use 2-space indentation"
  • use/memoryCheck for conflicting auto-memory entries
  • Consider using.claude/rules/Split rules by file path to reduce the loading amount each time

Issue 2: Claude starts contradicting itself and "forgets" previous decisions

  • This is a typical symptom of context decay. Do not keep correcting in the same session
  • Run/compact 保留关键决策, or directly/clearthen restart with a summary
  • Use for important conclusions#Write to CLAUDE.md via shortcut to ensure it remains effective in the next session

Issue 3: Key information lost after /compact

  • Pass specific instructions when compacting:/compact 保留认证流程的架构决策和已确认的 API 格式
  • Write the most important conclusions into CLAUDE.md before compacting
  • Failed debugging attempts are not worth keeping; you can compact more aggressively or use /clear

Issue 4: How to continue last time's work after closing the terminal

  • Useclaude --continueContinue the most recent session
  • Useclaude --resumeSelect a specific session from the history list
  • use/renameGive important sessions a descriptive name (e.g., "oauth-migration") to make them easier to find later

Issue 5: A large task generates a lot of tool output. How to avoid the context overflowing

  • Use subagents for delegation: the main conversation only receives the summary, while intermediate output stays in the subagent's independent context
  • For example:Use sub-agents to analyze all log files, identify performance bottlenecks, and only report the conclusions to me.
Other extensions