犀牛鸟 2026 研究笔记 estelledc.github.io

Codex Memory 系统精读

调研时间:2026-06-22 源码 commit:98845e4 本地 CLI:codex-cli 0.125.0

一句话定位

Codex Memory 是一个异步两阶段 AI pipeline——Phase 1 从每次对话中并行提取结构化记忆,Phase 2 用一个隔离的 consolidation sub-agent 把碎片记忆合并为持久化的知识库。它不是向量数据库,而是面向 coding session 的文件系统工件。


日常类比

把 Codex Memory 想象成一个公司的「知识管理系统」:

类比边界:公司 wiki 是人写人读的,Codex Memory 是 AI 写 AI 读的——Phase 2 的 consolidation agent 本身就是一个 Codex 实例,在隔离环境中运行。


架构总览

flowchart TB
    subgraph phase1["Phase 1: Rollout Extraction(并行)"]
        R1[Rollout 1 .jsonl] --> W1[Worker 1]
        R2[Rollout 2 .jsonl] --> W2[Worker 2]
        R3[Rollout N .jsonl] --> W3[Worker N]
        W1 --> DB1[(State DB: stage-1 outputs)]
        W2 --> DB1
        W3 --> DB1
    end

    subgraph phase2["Phase 2: Global Consolidation(串行)"]
        DB1 --> LOAD[加载 top-N outputs]
        LOAD --> SYNC[同步文件系统 artifacts]
        SYNC --> DIFF[Git diff vs baseline]
        DIFF --> |有变更| AGENT[Consolidation Sub-Agent]
        DIFF --> |无变更| SKIP[标记成功退出]
        AGENT --> RESET[Reset git baseline]
    end

    subgraph artifacts["文件系统 Artifacts (~/.codex/memories/)"]
        MM[MEMORY.md<br/>核心知识库]
        MS[memory_summary.md<br/>摘要索引]
        RM[raw_memories.md<br/>原始记忆合集]
        RS[rollout_summaries/<br/>每个 rollout 一行摘要]
        SK[skills/<br/>技能文档]
        GIT[.git/<br/>baseline 追踪]
    end

    subgraph read["Read Path: 记忆注入"]
        MS --> INJ[Developer Instructions 注入]
        INJ --> TOOLS[Memory Tools<br/>read/search/list/add_ad_hoc_note]
        TOOLS --> MODEL[模型上下文]
    end

    RESET --> artifacts
    artifacts --> read

Phase 1:Rollout Extraction

触发条件

Phase 1 在每次 root session 启动时自动触发(后台异步),条件:

[源码][文档]

Pipeline 步骤

1. Claim eligible rollouts(从 DB 按规则认领)
   - 来源:交互式 session(排除自动化/测试)
   - 时间窗口内
   - 空闲足够久(避免总结仍活跃的对话)
   - 未被其他 worker 占用
   - 数量有上限(bounded work per startup)

2. 并行提取(concurrency cap)
   - 加载 rollout .jsonl 文件
   - 过滤:只保留 memory-relevant 的 response items
   - 构建 prompt:stage_one_system.md + stage_one_input.md(注入 rollout 内容)
   - 调用模型(structured output schema)
   - 解析输出:{ raw_memory, rollout_summary, rollout_slug }
   - 密钥脱敏:redact_secrets()
   - 写入 DB

3. Job outcomes
   - succeeded(产出记忆)
   - succeeded_no_output(有效运行但无有用内容)
   - failed(标记 retry backoff)

Phase 1 Prompt 设计

system prompt(stage_one_system.md)定义了 Memory Writing Agent 的角色:

[源码]

关键代码

文件:codex-rs/memories/write/src/phase1.rs

// Phase 1 输出结构
struct StageOneOutput {
    raw_memory: String,           // 详细 markdown 记忆
    rollout_summary: String,      // 紧凑一行摘要(索引用)
    rollout_slug: Option<String>, // 可选文件名 slug
}

Phase 2:Global Consolidation

核心设计

Phase 2 的关键约束:全局只有一个 consolidation 实例在运行——通过 DB 层的全局锁保证。

Pipeline 步骤

1. 获取全局 Phase 2 锁(DB 层面,防并发合并)

2. 准备 memory workspace
   - 确保 ~/.codex/memories/ 存在
   - 确保有 .git/ baseline(git init + first commit)
   - 清理旧的 phase2_workspace_diff.md

3. 加载 Phase 2 输入
   - 从 DB 选 top-N stage-1 outputs
   - 排序:usage_count -> last_usage/generated_at
   - 排除超 max_unused_days 的

4. 同步文件系统 artifacts
   - rollout_summaries/<slug>.md(每个 rollout 一个文件)
   - raw_memories.md(合并所有,按 thread id 升序排列——稳定避免 churn)
   - 清理过期 extension resources

5. Git diff(对比当前 vs baseline)
   -> 无变更 -> 标记成功退出
   -> 有变更 -> 继续

6. 生成 phase2_workspace_diff.md
   - 变更文件列表 + bounded unified diff

7. Spawn consolidation sub-agent
   - 使用 consolidation.md 模板渲染 prompt
   - 隔离配置:无网络、无 MCP、无审批、只能写 memory root
   - 禁止递归记忆生成

8. Agent 完成后
   - 删除 diff 文件
   - Reset git baseline(git add -A + commit)
   - 标记 DB 中 selected_for_phase2 = 1
   - 持久化 watermark

Consolidation Agent 的职责

consolidation.md 模板定义了 agent 的行为:

[源码][文档]

Git-Baseline 机制

初始化: git init -> git add -A -> git commit (empty baseline)
      |
Phase2 run:
      sync artifacts -> git diff (worktree vs HEAD)
        -> 有变更 -> 写 diff 文件 -> agent 处理 -> git add -A -> git commit (new baseline)
        -> 无变更 -> skip

[源码] 这比向量数据库更简单可靠——变更检测基于 git diff,精确到行级。


Read Path:记忆注入

Developer Instructions 注入

每次 session 启动时,memory_summary.md 的内容被注入到模型的 system prompt:

[System Prompt]
  ...其他 developer instructions...
  [Memory Summary]
  <memory_summary.md 内容,按 token 上限截断>
  [/Memory Summary]

[源码] 注入使用 read_path.md 模板,包含 Quick Memory Pass 协议。

Quick Memory Pass 协议

模板中定义的记忆使用流程:

  1. 先看内联的 MEMORY_SUMMARY
  2. 提取关键词
  3. 用 codex_memory.search 搜索 MEMORY.md
  4. 按需打开 rollout_summaries/ 或 skills/
  5. 预算:4-6 步内完成

Memory Tools(运行时可用工具)

工具 用途
codex_memory.read 读取指定 memory 文件
codex_memory.search 关键词搜索 memory 文件
codex_memory.list 列出 memory 目录结构
codex_memory.add_ad_hoc_note 用户要求时写临时备注

Memory Citation

模型使用记忆后在回复末尾附加 citation 块:

<oai-mem-citation>
file: MEMORY.md
lines: 42-58
rollout_ids: ["abc123", "def456"]
</oai-mem-citation>

[源码] citation 用于遥测——追踪哪些记忆被实际使用。


文件系统 Artifacts 结构

~/.codex/memories/
  +-- .git/                    # baseline 追踪
  +-- MEMORY.md                # 核心知识库(consolidation agent 产出)
  +-- memory_summary.md        # 摘要索引(注入 prompt 用)
  +-- raw_memories.md          # Phase 1 原始记忆合集
  +-- rollout_summaries/       # 每个 rollout 一个摘要文件
  |   +-- refactor-auth.md
  |   +-- fix-db-migration.md
  |   +-- ...
  +-- skills/                  # 技能文档(agent 自动提炼)
  +-- extensions/              # 扩展资源
  |   +-- ad_hoc/notes/        # 用户显式添加的备注
  +-- phase2_workspace_diff.md # 临时文件(Phase 2 运行时生成)

与开源 Memory 框架的对比

维度 Codex Memory mem0 Letta (MemGPT) LangGraph Memory
存储 文件系统 + SQLite 向量数据库 多层 memory(core/archival/recall) Checkpoint store
提取方式 AI pipeline(Phase 1 模型调用) Embedding + 事件触发 LLM 自主管理 开发者代码
合并 AI sub-agent(Phase 2 consolidation) 去重 + 更新 LLM 编辑/搜索/归档 开发者代码
变更检测 git diff 向量相似度 LLM 自省 N/A
面向场景 Coding session 专用 通用对话 通用长期记忆 通用工作流
异步性 后台 pipeline 同步/异步 同步(每次对话内) 同步

关键差异:Codex Memory 是产品内建、面向 coding session 的——它知道什么是”好的记忆”(用户偏好、架构决策、解决方案),而通用框架需要开发者自己定义。


与 Claude Code 的差异(待 Agent A 核对)


局限性


证据等级汇总

结论 来源
两阶段 pipeline:Phase 1 并行提取 + Phase 2 串行合并 [源码][文档] memories/README.md
Phase 1 并发上限 + DB lease 防重复 [源码] memories/write/src/phase1.rs
Phase 2 全局锁 + git-baseline 变更检测 [源码] memories/write/src/phase2.rs
Consolidation sub-agent 在隔离环境运行 [源码] phase2.rs spawn agent
Read path 通过 memory_summary.md 注入 prompt [源码] ext/memories/
Memory tools: read/search/list/add_ad_hoc_note [源码] ext/memories
Citation 格式用于遥测追踪 [源码] memories/read/src/citations.rs
文件系统 artifacts 结构 [源码][文档] memories/README.md