mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-15 12:55:51 +00:00
* docs: 修复文档巡检发现的 4 处错误 - daemon.md: 反映实际实现状态(supervisor/worker 已实现而非 stub) - bridge-mode.md: API 操作数量从 7 修正为 9 - web-search-tool.md: 文件路径从 src/tools/ 修正为 packages/builtin-tools/src/tools/ - remote-control-self-hosting.md: 补充缺失的 RCS_WS_IDLE_TIMEOUT 和 RCS_WS_KEEPALIVE_INTERVAL 配置项 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 Safety 和 Context 文档中的代码引用和类型错误 - permission-model: 修正规则来源从"五层"到八层,优先级顺序对齐代码 - permission-model: PermissionUpdate 类型改为实际的 addRules/replaceRules 等 - permission-model: 补充 acceptEdits 和 dontAsk 两种权限模式 - permission-model: DENIAL_LIMITS 字段名对齐实际代码 - plan-mode: 工具路径从 src/tools/ 改为 packages/builtin-tools/src/tools/ - compaction: 修正 COMPACTABLE_TOOLS 和 POST_COMPACT_* 的行号 - project-memory: 修正 ENTRYPOINT_NAME 常量的行号 - system-prompt: 修正 SystemPrompt 类型定义文件路径和多个行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复 introduction 文档中的错误路径和行号引用 - why-this-whitepaper.mdx: BashTool 路径从 src/tools/ 修正为 packages/builtin-tools/src/tools/ - what-is-claude-code.mdx: 移除不存在的 Azure provider,改为实际的 7 种 provider - architecture-overview.mdx: State 类型行号从 204 修正为 207 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复 conversation/features 文档中的错误 - streaming.mdx: queryStreamRaw → queryModelWithStreaming 函数名修正 - streaming.mdx: Azure 提供商不存在,替换为实际 7 个提供商 - debug-mode.mdx: --inspect-wait 描述错误,实际使用 BUN_INSPECT 环境变量 - buddy.mdx: 补充缺失的 companionReact.ts、CompanionCard.tsx、index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复文档巡检中的源码引用错误 - feature-flags.mdx: 修正 feature() 兜底描述,实际从 bun:bundle 导入而非 cli.tsx:3 内联 - feature-flags.mdx: 修正工具 require 路径为 @claude-code-best/builtin-tools 包路径 - ant-only-world.mdx: 修正 tools.ts 中 require 路径为包路径 - ant-only-world.mdx: 修正 INTERNAL_ONLY_COMMANDS 行号 (267-295) 和数量 (24+) - skills.mdx: 修正 COMMANDS memoize 行号 258 → 299 - mcp-protocol.mdx: 修正 fetchToolsForClient LRU 缓存上限 20 → 100 - streaming.mdx: 修正流式事件引用 - file-operations.mdx: 修正工具路径引用 - search-and-navigation.mdx: 修正搜索工具引用 - shell-execution.mdx: 修正 shell 工具引用 - buddy.mdx: 补充缺失的 frontmatter 字段 - debug-mode.mdx: 修正调试模式描述 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 tools/agent 文档中的文件路径和行号引用 - 修正 TodoWriteTool、AgentTool、ToolSearchTool 等工具路径 src/tools/ → packages/builtin-tools/src/tools/ - 更新 Tool.ts、tools.ts、BashTool.tsx 中过时的行号引用 - 修正 WebSearchTool/WebFetchTool/EnterWorktreeTool/ExitWorktreeTool 路径 - 修正 AgentTool.tsx 中多行行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature 文档中的文件路径和行号引用 - ultraplan.md: 更新文件行数(525/349/127) - fork-subagent.md: 路径迁移 src/tools/ → packages/builtin-tools/ - mcp-skills.md: 修正 getMcpSkillCommands 行号 547→604,client.ts 行号 117→129 - kairos.md: 修正 getBriefSection/getProactiveSection 行号 - proactive.md: 修正 getProactiveSection 行号 860→864 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正顶层文档中的路径迁移和行号引用 - auto-updater.md: config.ts 行号 1735→1737,标注未接入启动流程的函数 - external-dependencies.md: WebSearchTool/WebFetchTool 路径迁移到 builtin-tools 包,Vertex 行号修正 - lsp-integration.md: LSPTool 路径从 src/tools/ 迁移到 packages/builtin-tools/ - stub-recovery-design-1-4.md: 修正 Windows 绝对路径链接为标准代码引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 task 文档中的文件扩展名和路径引用 - task-004: AssistantSessionChooser.ts → .tsx, assistant.ts → .tsx - task-003: cli.tsx 行号 249→272, markdownConfigLoader.ts 行号 29→35 - lan-pipes: SendMessageTool 路径迁移到 packages/builtin-tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 补充 computer-use-tools-reference 缺失的 Windows 工具 添加遗漏的 open_terminal 和 activate_window 两个 Windows 专属工具, 修正工具总数 37→39,Windows 工具数 10→12。 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 audit/bash-classifier/token-budget/tree-sitter 文档 - feature-flags-audit: ScheduleCronTool 路径迁移、DAEMON 状态更新为 COMPLETE、assistant 文件标记已补全、UDS 标记已实现 - bash-classifier: BashPermissionRequest 文件路径修正、withRetry 行号移除 - token-budget: attachments.ts 行号范围修正 - tree-sitter-bash: bashPermissions.ts 路径迁移到 packages/builtin-tools Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 langfuse-monitoring AgentTool 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 bridgeApi 行号和 Tool.ts 行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 Safety/Extensibility 文档中的工具路径迁移和行号引用 - sandbox.mdx: shouldUseSandbox.ts 和 bashPermissions.ts 路径迁移至 packages/builtin-tools - why-safety-matters.mdx: bashPermissions.ts 路径迁移(3 处) - plan-mode.mdx: EnterPlanModeTool/prompt.ts 路径迁移 - auto-mode.mdx: Auto mode 指令行号 3464→3481 - hooks.mdx: AgentTool/runAgent.ts 路径迁移 - skills.mdx: SkillTool.ts 路径迁移 - custom-agents.mdx: Agent built-in 目录和 exploreAgent.ts 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 internals 文档引用计数和路径 - ant-only-world: USER_TYPE 引用计数 465→410+,工具路径迁移到 builtin-tools - growthbook-ab-testing: growthbook.ts 行数 1156→1258 - hidden-features: 语音模式状态更新(audio-napi 已恢复) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正工具文档中的行号引用 - sub-agents: AgentTool.call 入口行号 340→387 - shell-execution: ShellCommand onTimeout 行号 129→144 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature 文档中的状态、路径和计数 - all-features-guide: 修正 feature flag 启用范围(dev only vs dev+build) - tier3-stubs: 大量状态修正(stub→已实现),缩减过时条目 - workflow-scripts: 路径迁移到 builtin-tools,状态更新 - web-browser-tool: 工具状态缺失→已实现,路径迁移 - context-collapse: CtxInspectTool 状态缺失→已实现 - computer-use: 行号引用更新,平台分发描述修正 - computer-use-tools-reference: 工具数 39→38 - voice-mode: voiceModeEnabled 行数 55→54 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 更新 the-loop 查询循环行号引用 query.ts 代码变更后终止原因行号整体偏移约 40 行 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 补充 feature-flags-audit 完整 build 默认 feature 列表 添加 ULTRATHINK/LODESTONE/ACP/DAEMON 等 19 个缺失的 build 默认 feature, 修正 dev-only 特征标注(UDS_INBOX/LAN_PIPES/BG_SESSIONS/TEMPLATES) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit ConfigTool 路径迁移 ConfigTool 路径从 src/tools/ 迁移到 packages/builtin-tools/src/tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit BashTool 路径迁移 BashTool 路径从 src/tools/ 迁移到 packages/builtin-tools/src/tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit SkillTool 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 更新 feature-flags-audit WorkflowTool 状态为已实现 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
227 lines
9.4 KiB
Plaintext
227 lines
9.4 KiB
Plaintext
---
|
||
title: "项目记忆系统 - 文件级跨对话记忆架构"
|
||
description: "深度解析 Claude Code 记忆系统:基于文件的持久化存储、MEMORY.md 索引结构、四类型分类法、Sonnet 智能召回、Session Memory 压缩集成。"
|
||
keywords: ["项目记忆", "MEMORY.md", "AI 记忆", "跨对话", "自动记忆", "memdir"]
|
||
---
|
||
|
||
{/* 本章目标:从源码层面剖析记忆系统的存储架构、召回机制和注入链路 */}
|
||
|
||
## 记忆系统的存储架构
|
||
|
||
源码路径:`src/memdir/paths.ts`、`src/memdir/memdir.ts`
|
||
|
||
Claude Code 的记忆系统是**纯文件**的——没有数据库、没有向量存储,只有 Markdown 文件和目录结构。
|
||
|
||
### 目录布局
|
||
|
||
```
|
||
~/.claude/projects/<sanitized-git-root>/memory/
|
||
├── MEMORY.md ← 入口索引(每次对话加载)
|
||
├── user_role.md ← 用户记忆
|
||
├── feedback_testing.md ← 反馈记忆
|
||
├── project_mobile_release.md ← 项目记忆
|
||
├── reference_linear_ingest.md ← 参考记忆
|
||
└── logs/ ← KAIROS 模式:每日日志
|
||
└── 2026/
|
||
└── 04/
|
||
└── 2026-04-01.md
|
||
```
|
||
|
||
路径解析链路(`getAutoMemPath()`):
|
||
1. `CLAUDE_COWORK_MEMORY_PATH_OVERRIDE` 环境变量(Cowork SDK 全路径覆盖)
|
||
2. `autoMemoryDirectory` 设置(仅限 `policySettings`/`localSettings`/`userSettings`——**故意排除** `projectSettings`,防止恶意仓库将记忆路径指向 `~/.ssh`)
|
||
3. 默认:`<memoryBase>/projects/<sanitized-git-root>/memory/`
|
||
|
||
同一个 Git 仓库的所有 worktree 共享一个记忆目录(通过 `findCanonicalGitRoot()` 找到真正的 `.git` 根)。
|
||
|
||
### MEMORY.md 索引
|
||
|
||
`MEMORY.md` 是记忆的入口索引,每次对话都完整加载到上下文中:
|
||
|
||
```typescript
|
||
// memdir.ts:34-38
|
||
export const ENTRYPOINT_NAME = 'MEMORY.md'
|
||
export const MAX_ENTRYPOINT_LINES = 200
|
||
export const MAX_ENTRYPOINT_BYTES = 25_000
|
||
```
|
||
|
||
索引有**双重上限**:200 行 AND 25KB。超过任何一条都会被 `truncateEntrypointContent()` 截断并追加警告。设计原因:p97 的索引文件用 200 行就能覆盖,但有些索引条目特别长(p100 观测到 197KB/200 行),字节上限捕捉这种长行异常。
|
||
|
||
索引条目格式:
|
||
```markdown
|
||
- [Title](file.md) — one-line hook
|
||
```
|
||
|
||
每条一行,~150 字符以内。`MEMORY.md` 本身没有 frontmatter——它只是一个链接列表,不是记忆内容。
|
||
|
||
## 四类型分类法
|
||
|
||
源码路径:`src/memdir/memoryTypes.ts`
|
||
|
||
记忆被约束为一个**封闭的四类型系统**,每种类型有明确的 `<when_to_save>`、`<how_to_use>` 和 `<body_structure>` 规范:
|
||
|
||
| 类型 | 存储内容 | 典型触发 |
|
||
|------|---------|---------|
|
||
| **user** | 用户角色、偏好、技术背景 | "我是数据科学家"、"我写了十年 Go" |
|
||
| **feedback** | 用户对 AI 行为的纠正和确认 | "别 mock 数据库"、"单 PR 更好" |
|
||
| **project** | 非代码可推导的项目上下文 | "合并冻结从周四开始"、"auth 重写是合规要求" |
|
||
| **reference** | 外部系统指针 | "pipeline bugs 在 Linear INGEST 项目" |
|
||
|
||
关键设计约束:**只存储无法从当前项目状态推导的信息**。代码架构、文件路径、git 历史都可以实时获取,不需要记忆。
|
||
|
||
### 反馈类型的双通道捕获
|
||
|
||
`feedback` 类型的 `when_to_save` 指令特别强调:
|
||
|
||
> Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.
|
||
|
||
这意味着 AI 不仅在用户说"不要这样做"时保存,也在用户说"对,就是这样"时保存。后一种更难捕捉,但同等重要——它防止 AI 的行为随时间漂移。
|
||
|
||
### 每条记忆的 Frontmatter 格式
|
||
|
||
```markdown
|
||
---
|
||
name: {{memory name}}
|
||
description: {{one-line description — 用于未来判断相关性}}
|
||
type: {{user, feedback, project, reference}}
|
||
---
|
||
|
||
{{memory content — feedback/project 类型建议包含 **Why:** 和 **How to apply:** 行}}
|
||
```
|
||
|
||
`description` 字段是关键:它不是给人读的摘要,而是给 AI 召回系统做相关性判断的搜索关键词。
|
||
|
||
## 智能召回机制
|
||
|
||
源码路径:`src/memdir/findRelevantMemories.ts`、`src/memdir/memoryScan.ts`
|
||
|
||
不是所有记忆都适合每次对话。系统使用一个**轻量级 Sonnet 侧查询**来筛选最相关的记忆。
|
||
|
||
### 召回流程
|
||
|
||
```
|
||
用户消息 → findRelevantMemories(query, memoryDir)
|
||
├── scanMemoryFiles() — 扫描所有记忆文件的 frontmatter
|
||
├── selectRelevantMemories() — Sonnet 侧查询,从清单中选出 ≤5 条
|
||
└── 返回 [{path, mtimeMs}, ...]
|
||
```
|
||
|
||
核心是 `selectRelevantMemories()` 函数,它调用 `sideQuery()`(一个独立的轻量 API 调用):
|
||
|
||
```typescript
|
||
// findRelevantMemories.ts:98-121
|
||
const result = await sideQuery({
|
||
model: getDefaultSonnetModel(), // 用 Sonnet 做筛选(非主模型)
|
||
system: SELECT_MEMORIES_SYSTEM_PROMPT,
|
||
messages: [{
|
||
role: 'user',
|
||
content: `Query: ${query}\n\nAvailable memories:\n${manifest}${toolsSection}`
|
||
}],
|
||
max_tokens: 256,
|
||
output_format: { type: 'json_schema', schema: { ... } },
|
||
})
|
||
```
|
||
|
||
### 近期工具去噪
|
||
|
||
当 AI 正在使用某个工具时,召回该工具的使用文档是噪音(对话中已有工作上下文)。`recentTools` 参数让召回系统跳过这些记忆:
|
||
|
||
```typescript
|
||
// findRelevantMemories.ts:92-95
|
||
const toolsSection = recentTools.length > 0
|
||
? `\n\nRecently used tools: ${recentTools.join(', ')}`
|
||
: ''
|
||
```
|
||
|
||
System Prompt 明确指示:"如果已提供最近使用的工具列表,不要选择该工具的使用参考或 API 文档。**仍然要选择**关于这些工具的警告、陷阱或已知问题——这正是使用时最关键的信息。"
|
||
|
||
### 已展示去重
|
||
|
||
`alreadySurfaced` 参数过滤之前轮次已展示过的文件路径,让 Sonnet 的 5 槽预算花在新的候选上,而不是重复召回同一文件。
|
||
|
||
## 记忆注入 System Prompt 的链路
|
||
|
||
源码路径:`src/memdir/memdir.ts` → `src/context.ts`
|
||
|
||
`loadMemoryPrompt()` 是记忆注入的入口,每会话调用一次(通过 `systemPromptSection('memory', ...)` 缓存):
|
||
|
||
```typescript
|
||
// memdir.ts:419-507
|
||
export async function loadMemoryPrompt(): Promise<string | null> {
|
||
// 优先级:KAIROS 日志模式 → TEAMMEM 组合模式 → 纯自动记忆
|
||
if (feature('KAIROS') && autoEnabled && getKairosActive()) {
|
||
return buildAssistantDailyLogPrompt(skipIndex)
|
||
}
|
||
if (feature('TEAMMEM') && teamMemPaths!.isTeamMemoryEnabled()) {
|
||
return teamMemPrompts!.buildCombinedMemoryPrompt(...)
|
||
}
|
||
if (autoEnabled) {
|
||
return buildMemoryLines('auto memory', autoDir, ...).join('\n')
|
||
}
|
||
return null
|
||
}
|
||
```
|
||
|
||
注入时机:`context.ts` 中 `getSystemContext()` 调用时,记忆 Prompt 作为 system prompt 的一个 section 被组装。`MEMORY.md` 的内容作为 **user context message** 注入(而非 system prompt),这样可以利用 Prompt Cache 的 prefix 共享。
|
||
|
||
## KAIROS 模式:每日日志
|
||
|
||
源码路径:`src/memdir/memdir.ts`(`buildAssistantDailyLogPrompt`)
|
||
|
||
长期运行的 assistant 会话使用不同的记忆策略:
|
||
|
||
- **标准模式**:AI 维护 `MEMORY.md` 作为实时索引 + 独立记忆文件
|
||
- **KAIROS 模式**:AI 只往日期文件追加日志(`logs/YYYY/MM/YYYY-MM-DD.md`),不做重组
|
||
|
||
```typescript
|
||
// 日志路径模式(非字面路径——因为 Prompt 被缓存)
|
||
const logPathPattern = join(memoryDir, 'logs', 'YYYY', 'MM', 'YYYY-MM-DD.md')
|
||
```
|
||
|
||
一个独立的夜间 `/dream` 技能负责将日志蒸馏为主题文件 + `MEMORY.md` 索引。
|
||
|
||
## 记忆漂移防御
|
||
|
||
源码路径:`src/memdir/memoryTypes.ts`(`TRUSTING_RECALL_SECTION`)
|
||
|
||
记忆可能过期。系统在 Prompt 中设置了一个专门的 section "Before recommending from memory":
|
||
|
||
```
|
||
A memory that names a specific function, file, or flag is a claim
|
||
that it existed *when the memory was written*. It may have been
|
||
renamed, removed, or never merged. Before recommending it:
|
||
|
||
- If the memory names a file path: check the file exists.
|
||
- If the memory names a function or flag: grep for it.
|
||
```
|
||
|
||
这个 section 的标题经过 A/B 测试验证:"Before recommending from memory"(行动导向)比 "Trusting what you recall"(抽象描述)效果好(3/3 vs 0/3)。
|
||
|
||
### 忽略记忆的严格语义
|
||
|
||
```
|
||
If the user says to *ignore* or *not use* memory:
|
||
proceed as if MEMORY.md were empty.
|
||
Do not apply remembered facts, cite, compare against,
|
||
or mention memory content.
|
||
```
|
||
|
||
这解决了 AI 的一个常见反模式:用户说"忽略关于 X 的记忆",AI 虽然正确识别了代码但仍然加上"不像记忆中说的 Y"——这不是"忽略",而是"承认然后覆盖"。
|
||
|
||
## Session Memory 与压缩的联动
|
||
|
||
源码路径:`src/services/compact/sessionMemoryCompact.ts`
|
||
|
||
记忆系统与上下文压缩有深度集成。当 `tengu_session_memory` 和 `tengu_sm_compact` 两个 feature flag 同时开启时,压缩优先使用 Session Memory 而非传统摘要:
|
||
|
||
```typescript
|
||
// sessionMemoryCompact.ts:57-61
|
||
const DEFAULT_SM_COMPACT_CONFIG = {
|
||
minTokens: 10_000, // 压缩后至少保留 10K token
|
||
minTextBlockMessages: 5, // 至少保留 5 条文本消息
|
||
maxTokens: 40_000, // 最多保留 40K token
|
||
}
|
||
```
|
||
|
||
SM-compact 不调用压缩 API(没有摘要模型),而是直接使用已有的 Session Memory 作为摘要——更快、更便宜、且不会丢失信息。
|