Claude Code Memory


注意:源码未开源,以下主要基于部分逆向/混淆源码片段综合分析,与真实实现可能存在出入

Coding场景的LLM系统记忆机制设计, 总的来说比较复杂,工程细节比较多,也不乏巧妙设计

优质材料推荐

https://zhuanlan.zhihu.com/p/1935431442432778433

https://southbridge-research.notion.site/claude-code-an-agentic-cleanroom-analysis

https://github.com/shareAI-lab/analysis_claude_code?tab=readme-ov-file

层次存储方式访问速度持久性
短期记忆压缩摘要<100ms单论会话
长期记忆CLAUDE.md<1000ms永久存储

短期记忆

上下文管理,会话级别的上下文存储

三级记忆预警

上下文包含:文件元信息,文件信息,用户query,历史对话,git操作,工具信息,error信息,图片等

触发条件显示信息系统行为(用户透明)预估对话轮数
Normal用户主动触发
/compact 命令
触发消息智能压缩算法-
WarningToken使用率>60%
记忆使用量较高
增加监控频率25~30
UrgentToken使用率>80%
建议手动清理
额外Token检查,压缩预热8~12
CriticalToken使用率>92%
记忆已满,正在整理
触发消息智能压缩算法-

消息智能压缩算法

平均70-80%的长度减少,95%以上关键信息保留

触发条件

  • 上下文使用率>92%

源自多目标优化:用户体验0.4+性能开销0.3+信息保真0.2+压缩频率0.1

  • 消息条数>20条
  • 花费>5$ (存疑)

消息压缩

  • 场景专用的压缩结构设计
  • 专用压缩模型
  • Coding场景设计的8段式压缩结构
    1. Primary Request and Intent (主要请求和意图)
    2. Key Technical Concepts (关键技术概念)
    3. Files and Code Sections (文件和代码段)
    4. Errors and fixes (错误和修复)
    5. Problem Solving (问题解决)
    6. All user messages (所有用户消息)
    7. Pending Tasks (待处理任务)
    8. Current Work (当前工作)
  • 专用压缩模型(J7)
// 8段式消息智能压缩Prompt
// 文件位置: improved-claude-code-5.mjs:44771-44967
// 功能:生成结构化的压缩提示词
function AU2(A) {
  // 基础压缩提示模板
  let basePrompt = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.

Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:

1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
   - The user's explicit requests and intents
   - Your approach to addressing the user's requests
   - Key decisions, technical concepts and code patterns
   - Specific details like:
     - file names
     - full code snippets
     - function signatures
     - file edits
  - Errors that you ran into and how you fixed them
  - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.

Your summary should include the following sections:

1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests without confirming with the user first.

If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.

Here's an example of how your output should be structured:

<example>
<analysis>
[Your thought process, ensuring all points are covered thoroughly and accurately]
</analysis>

<summary>
1. Primary Request and Intent:
   [Detailed description]

2. Key Technical Concepts:
   - [Concept 1]
   - [Concept 2]
   - [...]

3. Files and Code Sections:
   - [File Name 1]
      - [Summary of why this file is important]
      - [Summary of the changes made to this file, if any]
      - [Important Code Snippet]
   - [File Name 2]
      - [Important Code Snippet]
   - [...]

4. Errors and fixes:
    - [Detailed description of error 1]:
      - [How you fixed the error]
      - [User feedback on the error if any]
    - [...]

5. Problem Solving:
   [Description of solved problems and ongoing troubleshooting]

6. All user messages: 
    - [Detailed non tool use user message]
    - [...]

7. Pending Tasks:
   - [Task 1]
   - [Task 2]
   - [...]

8. Current Work:
   [Precise description of current work]

9. Optional Next Step:
   [Optional Next step to take]

</summary>
</example>

Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response. 

There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
<example>
## Compact Instructions
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
</example>

<example>
# Summary instructions
When you are using compact - please focus on test output and code changes. Include file reads verbatim.
</example>

`;

  // 如果有附加指令,则追加
  if (A && A.trim() !== "") {
    return basePrompt + `\n\nAdditional Instructions:\n${A}`;
  }
  
  return basePrompt;
}

压缩质量验证

Claude Code 使用多维度评分体系来量化压缩质量,确保在减少上下文长度的同时最大程度保留关键信息。

信息保留率验证

压缩评分公式设计基于四个维度:

各维度定义如下:

  • SC (Section Completeness) = 8段结构完整率
  • KP (Key Info Preservation) = = {文件名、错误信息、用> 户指令、技术关键词}
  • CC (Context Continuity) = ,连续词 = {首尾/然后/接来/下一步/…}
  • CR (Compression Ratio) = 压缩比例

根据压缩评分和压缩结果生成改进建议(推测借助LLM)

(改进意见推测用于:1.后续修复逻辑 2.数据采集 )

优雅降级

处理方案触发条件备注
重新压缩压缩评分70~791. 采用改进意见
2. 提升关键信息保留权重
3. 降低压缩比例
片段保留某些段落信息丢失严重压缩摘要+原关键信息片段
直接截断多次压缩不达标保留最近30%的消息历史

关键信息恢复

智能文件恢复

  • 文件相关性计算
  • 恢复文件选取

经典0-1背包优化问题求解

待办事项恢复
重要信息补充(丰富8段式结构中的待办事项)

长期记忆

基于 CLAUDE.md 的项目级持久化记忆系统

阶段产品形态方案备注
记忆提取/init 生成项目基础信息
#+内容 添加
• 用户主动要求记住偏好
• 用户主动编辑
• 用户Query请求LLM提取
从对话和项目中识别值得长期保存的知识
记忆存储• 全局级别(/etc)
• 代码库级(项目目录)
• 用户级别(用户目录)
• 用户项目偏好(CLAUDE.local.md)
多级CLAUDE.md文件分层组织,支持项目级和子目录级配置
记忆检索/memory 命令查看当前记忆• 启动时,从当前目录向根目录搜索载入
• 子目录中的文件,读到相关目录再载入
智能加载相关上下文
记忆应用对用户透明,用户可主动询问触发• 通过上下文的方式引入
• 读到的记忆内容做语义级覆盖
自动融入工作流程

记忆应用

上下文拼装

策略Token预算备注
系统提示5%内置Prompt+长期记忆
多级CLAUDE.md装载,并做语义级别覆盖
压缩摘要(短期记忆)20%消息智能压缩算法
文件内容45%文件内容+安全装配Prompt
安全装配 防止恶意注入
最近消息30%消息优先级排序
1. 用户消息>其他
2. 错误/修复信息>其他
3. 时间戳排序