Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Claude Code Context Management

Claude Code Context Management

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; as the context fills up, model performance gradually declines (known as 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 means to keep Claude efficient in long and cross-session conversations.


Context Window Basics

1. What Does the Context Window Contain

Claude Code's context window size is 1,000,000 tokens. It holds everything Claude "sees" in the current session:

Content source When loaded Token usage
System prompt (Claude Code behavior specifications) At each session start Fixed usage
CLAUDE.md files Fully loaded at startup Depends on file size
Auto memory Loaded at startup (first 200 lines or 25KB) Has a limit
Conversation history Accumulates and grows Continuously increases with the session
Tool results (file reads, command output, etc.) Appended after each tool call Logs/large files consume extremely fast
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 declines, because attention is spread across more tokens, old and irrelevant content begins to interfere with the current task. Specific symptoms include:

If the above symptoms appear, it means the context has been "polluted"; at this point you should proactively use /compact or /clear to handle it, rather than continuing to correct within the same session.

Use /context The command can show 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 gives optimization suggestions. It is recommended to check once before starting an important task.


CLAUDE.md Instruction Files

CLAUDE.md is the core file in Claude Code for recording static instructions and project specifications. At each session start, Claude automatically loads it into the context window.

1. Storage Locations and Scope

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

Range File path Applicable scenarios Whether to 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 centrally by IT
Project-level ./CLAUDE.md or ./.claude/CLAUDE.md Project architecture, coding standards, workflows Yes, shared with the team
User level ~/.claude/CLAUDE.md Personal coding preferences, applicable to all projects No, private to the individual
Local private ./CLAUDE.local.md(added to .gitignore) Personal project-specific configuration, not committed to git No, added to .gitignore

CLAUDE.local.md This 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 than in CLAUDE.md . When running /init , select the "Personal" option, and 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,/init it will suggest improvements rather than overwriting 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 the # shortcut to quickly append a memory to CLAUDE.md:

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

Press # then enter the content and press 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 every CLAUDE.md filebe kept within 200 lines. The larger the file, the more startup tokens it consumes, and the lower Claude's compliance rate. Here is the content guidance:

What should be written:

What should not be written:

Example

CLAUDE.md Example (concise and specific, each file kept within 200 lines)

Common Commands

Code Standards

Constraints

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

For larger projects, you can use the .claude/rules/ directory to split instructions into fine-grained rules that take effect by file path, avoiding all rules piling up in 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-based rules are only loaded when Claude reads files in the corresponding directory, and do not occupy the full context 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 lets Claude autonomously record discovered build commands, debugging experiences, code style preferences, and other information as it works.

1. How It Works

2. Viewing and Editing Memories (/memory)

Use /memory The command views and edits 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 switch to disable the auto memory feature. You can also temporarily disable it via an environment variable:

CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 claude

3. Proactively Having Claude Remember Things

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

记住:我们的 API 测试需要本地运行一个 Redis 实例

以后请记住:处理错误时,统一返回 { code, message } 结构

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


Context Window Optimization Commands

1. Auto-compaction

Claude Codeautomatically triggers compaction when the context approaches the limit(at around 75% usage), summarizing the conversation history into a summary and then continuing work. But the official recommendation is not to wait for auto-compaction; you shouldproactively trigger it manually at 60-70%, avoiding interruptions in the middle of critical tasks, and proactive compaction allows you to control what content is retained via instructions.

2. Compacting Context (/compact)

Manually compact the conversation history, summarizing a long session into a concise summary to continue work:

/compact

/compact Supports passing custom instructions to control what content is prioritized for retention 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; without instructions, it may lose content you consider important.Proactively compact immediately after major decisions and use instructions to specify what to retain, which is far more effective than waiting for auto-compaction.

3. Clearing Context (/clear)

Clear 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 the new session. Official recommendation:If you have corrected the same issue more than twice in the same session, it is better to just /clear and restart with a more precise prompt incorporating what you've learned—a clean session plus a better prompt is almost always better than continuing to correct in a polluted context.

4. Rewinding to a Checkpoint (/rewind)

Claude Code automatically creates a checkpoint before each file modification. Double-click Esc or run /rewind to open the rewind menu and select the checkpoint to restore:

/rewind

(或双击 Esc 键)

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

Operation effect Applicable scenarios
Restore conversation + code Rewind conversation history and file changes, fully restoring Claude went off track, the changes are problematic, undo everything
Restore conversation only Rewind conversation history, keeping file changes Want to try a different approach, but the code changes can be kept
Restore code only Restore files to the checkpoint state, keeping the conversation The code was broken, but the analysis in the conversation is valuable
Summarize from here Compact the conversation after this checkpoint into a summary, keeping the complete history before it Only want to clean up redundant conversation in the latter half, keeping the complete early context

Checkpoints persist across sessions—you can still rewind to a previous checkpoint after closing the terminal. This is not a replacement for git, but it is 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 this Q&A to enter the conversation history (consuming context), use /btw:

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

The answer is displayed in an overlay; neither the question nor the answer enters the conversation history, suitable for looking up one-off information that does not need to be retained, such as configuration and version numbers.


Session management commands

Command Function Use Cases
/context View detailed token usage analysis of each part of the context Identify which part consumes too many tokens
/compact [指令] Compact conversation history into a summary, with the option to specify what to retain Proactively compact at 60-70% context usage
/clear Clear all conversation history, keeping CLAUDE.md and memories Switch to a new task, or when the context is already heavily polluted
/rewind(or double-click Esc) Open the checkpoint menu to restore conversation/code/both, or summarize from a point Claude went off track and needs to rewind and retry
/memory View and edit CLAUDE.md and auto memory content Check whether memories are accurate, delete outdated entries
/btw Quick questions whose answers do not enter the 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 specifications or conventions at any time
claude --continue Continue the most recent session Resume work after reopening the terminal
claude --resume Select a session from the history list to continue Resume a specific task from a few days ago

Common Problems and Solutions

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

Problem 2: Claude starts being self-contradictory, "forgetting" previous decisions

Problem 3: Key information is lost after /compact

Problem 4: How to resume previous work after closing the terminal

Problem 5: A large task generates a lot of tool output; how to avoid filling up the context