06. Memory

遗忘的问题

AI 有一个根本性的弱点:它没有持久记忆。每一次对话都是从零开始。昨天你告诉 Claude 的项目规范、编码风格、部署流程——今天它全部忘记了。上下文窗口就像一块白板,对话结束的那一刻,一切都被擦除。

这对于一个需要深度理解项目的编码助手来说是致命的。想象一个新同事,每天早上来上班都失忆了——你必须从头解释一切。这就是没有记忆系统的 AI。

Claude Code 通过多层记忆机制来解决这个问题。

记忆层级

┌─────────────────────────────────────────────────┐ │ Memory Hierarchy │ │ │ │ ┌─────────────────────────────────────────┐ │ │ │ Layer 1: CLAUDE.md (持久化) │ │ │ │ 每次对话自动加载的项目说明书 │ │ │ │ ├── /project/CLAUDE.md │ │ │ │ ├── ~/.claude/CLAUDE.md │ │ │ │ └── /project/.claude/CLAUDE.md │ │ │ └─────────────────────────────────────────┘ │ │ ▲ │ │ ┌─────────────────────────────────────────┐ │ │ │ Layer 2: Auto Memory (跨会话) │ │ │ │ AI 自动记录的笔记 │ │ │ │ ├── ~/.claude/projects/MEMORY.md │ │ │ │ └── 用户偏好、项目发现、反馈记录 │ │ │ └─────────────────────────────────────────┘ │ │ ▲ │ │ ┌─────────────────────────────────────────┐ │ │ │ Layer 3: Conversation Context (临时) │ │ │ │ 当前对话中的所有消息和工具结果 │ │ │ │ 对话结束后消失 │ │ │ └─────────────────────────────────────────┘ │ └─────────────────────────────────────────────────┘

CLAUDE.md:持久化记忆

CLAUDE.md 是 Claude Code 最重要的记忆机制。它是一个 Markdown 文件,在每次对话开始时自动加载到上下文中。你可以把它看作是给 Claude 写的”员工手册”。

Claude Code 会从三个位置读取 CLAUDE.md:

  • ~/. claude/CLAUDE.md — 全局配置,适用于所有项目
  • /project/CLAUDE.md — 项目级配置,提交到 Git 与团队共享
  • /project/.claude/CLAUDE.md — 个人项目配置,可加入 .gitignore

如何有效地编写 CLAUDE.md

一个好的 CLAUDE.md 应该包含:

# 项目名称

## 技术栈
- 框架: Next.js 14 (App Router)
- 语言: TypeScript (strict mode)
- 样式: Tailwind CSS v4
- 数据库: PostgreSQL + Prisma ORM
- 测试: Vitest + Playwright

## 项目结构
src/
app/          # 页面和路由
components/   # React 组件
lib/          # 工具函数和业务逻辑
prisma/       # 数据库 schema

## 开发命令
npm run dev     # 启动开发服务器
npm run test    # 运行测试
npm run lint    # 代码检查

## 编码规范
- 使用函数式组件和 hooks
- 所有组件需要有 TypeScript 类型定义
- 变量命名使用 camelCase
- 文件命名使用 kebab-case
- 提交信息使用 Conventional Commits

## 重要约定
- API 路由统一在 src/app/api/ 下
- 所有数据库操作通过 Prisma Client
- 不要直接修改 prisma/migrations/ 目录

关键原则:简洁、具体、可操作。不要写散文,写指令。Claude 会忠实地遵循 CLAUDE.md 中的每一条规则。

“记忆”与”上下文”的区别

理解这两个概念的区别至关重要:

  • 记忆(Memory):持久化的信息,跨对话存在。包括 CLAUDE.md、项目配置、用户偏好。每次对话都可以访问。
  • 上下文(Context):临时的信息,仅存在于当前对话。包括对话消息、工具调用结果、读取的文件内容。对话结束后消失。
Memory (持久)                    Context (临时)
┌─────────────┐                ┌─────────────┐
│ CLAUDE.md   │  ──加载──▶    │ 系统提示词   │
│ settings    │                │ 对话历史     │
│ 用户偏好    │                │ 工具结果     │
│ 项目配置    │                │ 文件内容     │
└─────────────┘                └─────────────┘
跨会话保留                      对话结束消失

Claude Code 的记忆类型

Claude Code 管理几种不同类型的记忆:

用户偏好

存储在 ~/.claude/ 中。包括全局设置、常用的 MCP 配置、个人编码偏好。适用于所有项目。

项目上下文

存储在项目的 CLAUDE.md.claude/ 目录中。包括技术栈、编码规范、项目结构。与团队共享。

会话反馈

当你在对话中纠正 Claude 的行为时(“不要用 var,用 const”),Claude 可以将这个反馈保存为持久记忆,下次对话自动遵循。

自动记忆

Claude Code 可以在对话结束时自动提取关键信息并保存。例如,如果它在调试过程中发现了项目的一个重要模式,它会建议将其记录到 CLAUDE.md 中。

实际工作流

把这些机制组合起来,Claude Code 在一次典型的编码会话中是这样工作的:

  1. 加载记忆:读取 CLAUDE.md,加载项目配置
  2. 理解任务:解析用户的请求
  3. 按需检索:使用 Glob/Grep/Read 获取相关代码
  4. 执行任务:在 Agentic Loop 中编辑代码、运行测试
  5. 压缩上下文:如果对话太长,自动摘要早期内容
  6. 更新记忆:如果发现新的重要信息,建议保存到 CLAUDE.md

正是这套多层记忆系统,让 Claude Code 能够跨越遗忘的鸿沟——虽然每次对话仍然从新的上下文开始,但持久化的记忆确保了关键知识永不丢失。

The Forgetting Problem

AI has a fundamental weakness: it has no persistent memory. Every conversation starts from scratch. The project specs, coding styles, and deployment processes you told Claude yesterday — today it has forgotten everything. The context window is like a whiteboard that gets erased the moment the conversation ends.

This is fatal for a coding assistant that needs deep project understanding. Imagine a new colleague who wakes up with amnesia every morning — you have to explain everything from the beginning. That is AI without a memory system.

Claude Code solves this with a multi-layered memory mechanism.

Memory Hierarchy

┌─────────────────────────────────────────────────┐ │ Memory Hierarchy │ │ │ │ ┌─────────────────────────────────────────┐ │ │ │ Layer 1: CLAUDE.md (Persistent) │ │ │ │ Project manual loaded every conversation │ │ │ │ ├── /project/CLAUDE.md │ │ │ │ ├── ~/.claude/CLAUDE.md │ │ │ │ └── /project/.claude/CLAUDE.md │ │ │ └─────────────────────────────────────────┘ │ │ ▲ │ │ ┌─────────────────────────────────────────┐ │ │ │ Layer 2: Auto Memory (Cross-session) │ │ │ │ Notes the AI records while working │ │ │ │ ├── ~/.claude/projects/MEMORY.md │ │ │ │ └── Preferences, discoveries, feedback │ │ │ └─────────────────────────────────────────┘ │ │ ▲ │ │ ┌─────────────────────────────────────────┐ │ │ │ Layer 3: Conversation Context (Ephemeral)│ │ │ │ All messages and tool results │ │ │ │ Disappears after conversation ends │ │ │ └─────────────────────────────────────────┘ │ └─────────────────────────────────────────────────┘

CLAUDE.md: Persistent Memory

CLAUDE.md is Claude Code’s most important memory mechanism. It is a Markdown file that is automatically loaded into context at the start of every conversation. Think of it as an “employee handbook” written for Claude.

Claude Code reads CLAUDE.md from three locations:

  • ~/.claude/CLAUDE.md — Global config, applies to all projects
  • /project/CLAUDE.md — Project-level config, committed to Git and shared with the team
  • /project/.claude/CLAUDE.md — Personal project config, can be added to .gitignore

How to Write an Effective CLAUDE.md

A good CLAUDE.md should contain:

# Project Name

## Tech Stack
- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode)
- Styling: Tailwind CSS v4
- Database: PostgreSQL + Prisma ORM
- Testing: Vitest + Playwright

## Project Structure
src/
app/          # Pages and routes
components/   # React components
lib/          # Utilities and business logic
prisma/       # Database schema

## Dev Commands
npm run dev     # Start dev server
npm run test    # Run tests
npm run lint    # Lint code

## Coding Standards
- Use functional components and hooks
- All components must have TypeScript type definitions
- Variable naming: camelCase
- File naming: kebab-case
- Commit messages: Conventional Commits

## Important Conventions
- API routes go under src/app/api/
- All DB operations through Prisma Client
- Never directly modify prisma/migrations/

Key principles: concise, specific, actionable. Don’t write prose — write directives. Claude faithfully follows every rule in CLAUDE.md.

The Difference Between “Memory” and “Context”

Understanding the distinction between these two concepts is crucial:

  • Memory: Persistent information that exists across conversations. Includes CLAUDE.md, project settings, user preferences. Accessible in every conversation.
  • Context: Ephemeral information that exists only in the current conversation. Includes conversation messages, tool call results, file contents read. Disappears when the conversation ends.
Memory (Persistent)              Context (Ephemeral)
┌─────────────┐                ┌─────────────┐
│ CLAUDE.md   │  ──loaded──▶  │ System prompt│
│ settings    │                │ Chat history │
│ Preferences │                │ Tool results │
│ Project cfg │                │ File content │
└─────────────┘                └─────────────┘
Persists across                Disappears after
sessions                       conversation ends

Memory Types in Claude Code

Claude Code manages several different types of memory:

User Preferences

Stored in ~/.claude/. Includes global settings, common MCP configurations, personal coding preferences. Applies to all projects.

Project Context

Stored in the project’s CLAUDE.md and .claude/ directory. Includes tech stack, coding standards, project structure. Shared with the team.

Session Feedback

When you correct Claude’s behavior during a conversation (“don’t use var, use const”), Claude can save this feedback as persistent memory, automatically following it in future conversations.

Auto Memory

Claude Code can automatically extract key information at the end of a conversation and save it. For example, if it discovers an important pattern in the project during debugging, it will suggest recording it in CLAUDE.md.

The Complete Workflow

Combining all these mechanisms, here is how Claude Code works in a typical coding session:

  1. Load memory: Read CLAUDE.md, load project configuration
  2. Understand task: Parse the user’s request
  3. On-demand retrieval: Use Glob/Grep/Read to fetch relevant code
  4. Execute task: Edit code, run tests in the Agentic Loop
  5. Compact context: If conversation is too long, auto-summarize earlier content
  6. Update memory: If important new info is discovered, suggest saving to CLAUDE.md

It is this multi-layered memory system that allows Claude Code to bridge the gap of forgetting — though each conversation still starts with a fresh context, persistent memory ensures critical knowledge is never lost.

上一章 / PreviousCh.5 MCP下一章 / NextCh.7 Codebase Intelligence