Claude Code - Memory
Claude Code - Memory
Memory
1
2
3
4
5
6
export const MEMORY_TYPES = [
'user', // 用户画像
'feedback', // 偏好
'project', // 项目动态
'reference', // 外部指针
] as const
- feedback和project都是记录规则/事实/决定
- 同时也要记录原因和何时规则生效
- project要记录绝对日期
- project记录项目正在发生什么, 比如移动端3月5号开始合并冻结
1
2
3
规则本身
**Why:** 用户为什么这么要求(往往是踩过的坑)
**How to apply:** 什么情况下生效
- reference记录去哪查什么
- 单文件 + 索引
- 每个记忆是一个独立的md文件
- 用yml frontmatter指定name, description, type
1
2
3
4
5
6
7
8
9
10
---
name: 不要用 mock 数据库
description: 集成测试必须连真实数据库
type: feedback
---
集成测试必须连真实数据库,不要用 mock。
**Why:** 上季度 mock 测试通过了但 prod 迁移挂了
**How to apply:** 所有标了「集成测试」的 case 都适用
- 记忆文件放在一个目录下, 用MEMORY.md作为所有记忆文件的索引
- 解决如何写记忆的问题
- 在每轮对话结束后, 后台跑一个代理抽取记忆
- extractMeomries, 在每轮query loop结束后通过stopHood触发
- fork一个subagent
1
2
3
// 源码注释
// Uses the forked agent pattern (runForkedAgent) — a perfect fork of the main
// conversation that shares the parent's prompt cache.
抽取记忆逻辑
- 扫描本轮对话中用户的反馈、纠正、信息等
- 跟现有记忆比对, 不要重复记录
- 为避免重复记忆, 代理会主动检查hasMemoryWritesSince, 过滤掉刚写过的内容
- 如果有新的内容要记忆, 按4种类型分类, 写一个新文件
记忆检索
- 用小模型去选
- 扫描所有记忆文件的头部(前30行)
- 将标题清单拼成一段文本给小模型
1
2
3
4
5
6
7
Query: 用户当前的问题
Available memories:
- user_role.md — 后端工程师,新接触 React
- feedback_no_mock.md — 测试不要用 mock
- project_freeze.md — 3 月 5 号开始合并冻结
...
- 小模型用json schema返回top-k文件名
1
2
3
4
<!-- 部分提示词 -->
Only include memories that you are certain will be
helpful based on their name and description.
Be selective and discerning.
- alreadySurfaced过滤
- 上一轮对话已经在的记忆, 这一轮不选了
- recentTools过滤
- 选出记忆后塞回对话
- 使用
标签包裹后注入
1
2
3
4
5
<system-reminder>
This memory was saved 5 days ago. Verify it's still accurate before acting on it.
[记忆内容]
</system-reminder>
- 记忆老化
- 2天以前的记忆主动加警告, 告诉模型这是过去的内容
This post is licensed under CC BY 4.0 by the author.