> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zeus.agentspro.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 记忆系统

> Zeus Memory System — 架构、实现与个性化

## 概述

Zeus 的记忆系统为 Agent 提供跨会话的用户认知能力。通过从对话中提取、存储并检索关键信息，Agent 能够持续积累对用户和项目的理解，从而提供个性化、有上下文连贯性的交互体验。

记忆系统解决三个核心问题：

* **个性化**：记住用户偏好（编程风格、语言、工具链），无需每次重复说明
* **上下文连续性**：跨会话保持对项目背景、技术决策的认知
* **智能推理**：基于历史记忆做出更准确的判断和建议

***

## 架构

### 四层记忆模型

Zeus 的记忆系统由四个生命周期不同的层级组成，从短暂的运行时状态到永久的用户画像，形成一个完整的认知体系。

```mermaid theme={null}
graph TB
    subgraph WM["Working Memory"]
        direction LR
        wm_desc["todo_list · tool_calls · 中间推理状态"]
    end

    subgraph STM["Short-term Memory"]
        direction LR
        stm_desc["当前会话消息列表 · 对话上下文"]
    end

    subgraph LTM["Long-term Memory"]
        direction LR
        ltm_desc["用户偏好 · 项目上下文 · 技能 · 决策记录"]
    end

    subgraph EM["Episodic Memory"]
        direction LR
        em_desc["会话快照 · Agent 状态 · 待批准操作"]
    end

    WM -->|"任务完成后销毁"| STM
    STM -->|"重要信息提取"| LTM
    STM -->|"状态持久化"| EM
    EM -->|"中断恢复"| STM

    WM -.- mem["内存"]
    STM -.- pg1["PostgreSQL · message"]
    LTM -.- pg2["PostgreSQL + pgvector"]
    EM -.- pg3["PostgreSQL · checkpoint"]
```

| 层级                | 生命周期        | 存储                        | 职责                                        |
| ----------------- | ----------- | ------------------------- | ----------------------------------------- |
| Working Memory    | 单次 Agent 调用 | 内存                        | 任务执行的临时上下文：todo\_list、tool\_calls、推理状态    |
| Short-term Memory | 单个会话        | PostgreSQL (message 表)    | 当前会话的对话历史，通过 SummarizationMiddleware 自动压缩 |
| Long-term Memory  | 永久（用户可管理）   | PostgreSQL + pgvector     | 跨会话的用户/项目信息，支持语义检索                        |
| Episodic Memory   | 可恢复         | PostgreSQL (checkpoint 表) | 会话状态快照，支持页面刷新、中断后继续、错误重试                  |

### 三层数据架构 (memU)

Long-term Memory 采用 memU 启发的三层结构，将原始资源逐步抽象为结构化画像：

| 层级      | 名称                | 内容                                                            | 说明                                                                          |
| ------- | ----------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------- |
| Layer 1 | Resource Layer    | Chat 对话、Knowledge Base 文档、Project Resource                    | 原始数据来源 — 记忆提取的原始素材                                                          |
| Layer 2 | Memory Item Layer | preference、fact、skill、habit、event、context、constraint、decision | 从原始数据中提取的结构化记忆条目，按类型分类                                                      |
| Layer 3 | Profile Layer     | User Profile（全局偏好、专业背景）、Project Profile（技术栈、约束、决策）            | 由记忆条目聚合而成的画像，直接注入[系统提示词](/zh/documentation/core-capabilities/system-prompt) |

数据自下而上流动：Layer 1 原始资源被**提取**为 Layer 2 记忆条目，再**聚合**为 Layer 3 画像。

***

## 数据模型

### Memory Item

记忆条目是系统的核心数据单元，每条记忆包含内容、分类、作用域和元数据。主要字段包括：

* **content**：记忆内容文本
* **memory\_type**：记忆类型分类
* **scope** / **scope\_id**：作用域（user / project / session）及对应 ID
* **source** / **source\_id**：来源（user / ai / knowledge\_base / project\_resource）及关联 ID
* **confidence**：置信度（0.0 \~ 1.0）
* **visibility**：可见范围（public / members / owner\_only），仅 project scope 生效
* **status**：状态（active / archived / superseded）
* **last\_used\_at**：最后被检索的时间

### Memory Type

每种类型对应不同性质的信息，Agent 在提取记忆时需选择正确的类型：

| Type         | 语义    | 示例                      |
| ------------ | ----- | ----------------------- |
| `preference` | 用户偏好  | 喜欢简洁代码、偏好深色主题           |
| `fact`       | 事实信息  | 用户是前端工程师、名字叫张三          |
| `skill`      | 技能水平  | 熟悉 React、精通 TypeScript  |
| `habit`      | 使用习惯  | 常用 VS Code、习惯用 Git Flow |
| `event`      | 重要事件  | 完成了项目 A 的上线             |
| `context`    | 项目上下文 | 当前在开发支付模块               |
| `constraint` | 约束条件  | 项目必须支持 PostgreSQL 16    |
| `decision`   | 决策记录  | 选择了 Next.js 而不是 Remix   |

### Memory Scope

作用域决定记忆的可见范围和生命周期：

```mermaid theme={null}
graph LR
    subgraph UserScope["user scope"]
        direction TB
        us_desc["跨项目、跨会话<br/>个人专属信息<br/>例: 职业、偏好、技能"]
    end
    subgraph ProjectScope["project scope"]
        direction TB
        ps_desc["项目成员共享<br/>项目专属上下文<br/>例: 技术栈、规范、约束"]
    end
    subgraph SessionScope["session scope"]
        direction TB
        ss_desc["仅当前会话<br/>临时信息<br/>例: 中间结果、临时决定"]
    end

    SessionScope -->|"优先级最高"| ProjectScope -->|"次优先"| UserScope
```

### User Profile

用户画像聚合了用户的全局特征，在每次对话时注入到系统提示词。主要字段包括：

* **username**：用户名
* **background**：用户背景描述
* **profession**：职业
* **communication\_style**：沟通风格（concise / detailed / technical）
* **response\_format**：响应格式偏好（markdown / plain / code）
* **language\_preference**：语言偏好（zh-CN / en / ja 等）
* **characteristics**：个性特征
* **content**：自定义指令（Custom Instructions）
* **expertise\_areas**：专业领域
* **programming\_languages**：编程语言
* **frequently\_used\_tools**：常用工具

### Project Profile

项目画像记录团队共享的项目上下文。主要字段包括：

* **project\_goal**：项目目标
* **tech\_stack**：技术栈
* **constraints**：约束条件
* **key\_decisions**：关键决策（含决策内容、原因和时间）
* **team\_conventions**：团队规范
* **current\_phase**：当前阶段

***

## 核心组件

### MemoryService

`MemoryService` 是记忆系统的核心服务，统一管理记忆的读写和检索。它同时与 PostgreSQL（元数据）和 pgvector（向量索引）交互。

```mermaid theme={null}
graph TD
    subgraph MemoryService["MemoryService"]
        gate["Gate 门控<br/>validate_memory()<br/>check_duplicate()<br/>check_rate_limit()"]
        write["写入<br/>add_explicit_memory()"]
        search["检索<br/>search_memories()"]
        profile["画像<br/>get_profile_for_agent()"]
        format["格式化<br/>format_memories_for_prompt()"]
    end

    gate -->|"验证通过"| write
    write -->|"1. 向量写入"| pgvector["pgvector<br/>collection: memory"]
    write -->|"2. 元数据写入"| nextjs["Next.js API<br/>POST /api/memory"]
    search -->|"语义搜索"| pgvector
    profile -->|"获取画像"| nextjs2["Next.js API<br/>GET /api/memory/profile"]
```

#### 关键方法

| 方法                             | 职责                                        |
| ------------------------------ | ----------------------------------------- |
| `add_explicit_memory()`        | 保存记忆 — 门控验证 → pgvector 写入 → PostgreSQL 写入 |
| `search_memories()`            | 语义检索 — 多 scope 搜索 → 合并排序 → 返回 Top K       |
| `validate_memory()`            | 内容验证 — 置信度、敏感信息、内容长度                      |
| `check_duplicate()`            | 去重检测 — pgvector 相似度 ≥ 0.85 判定为重复          |
| `check_rate_limit()`           | 速率限制 — 每 session 每 24h 最多 3 次提取           |
| `get_profile_for_agent()`      | 获取用户/项目画像，用于注入系统提示词                       |
| `format_memories_for_prompt()` | 将记忆格式化为 prompt 可读文本                       |

### Memory Gate（门控）

门控层在记忆写入前执行多维验证，防止低质量、敏感或重复的信息进入记忆库：

```mermaid theme={null}
flowchart TD
    input["记忆写入请求"]
    conf{"置信度 ≥ 0.7?"}
    sensitive{"包含敏感信息?<br/>password · api_key<br/>credit card · token"}
    length{"内容长度<br/>5 ~ 2000 字符?"}
    dup{"语义重复?<br/>similarity ≥ 0.85"}
    rate{"速率限制?<br/>≤ 3次/session/24h"}
    pass["✅ 验证通过 → 写入"]
    reject["❌ 拒绝写入"]

    input --> conf
    conf -->|"否"| reject
    conf -->|"是"| sensitive
    sensitive -->|"是"| reject
    sensitive -->|"否"| length
    length -->|"否"| reject
    length -->|"是"| dup
    dup -->|"是"| reject
    dup -->|"否"| rate
    rate -->|"超限"| reject
    rate -->|"通过"| pass
```

门控配置支持环境变量覆盖：

| 参数     | 默认值             | 环境变量                         |
| ------ | --------------- | ---------------------------- |
| 最低置信度  | 0.7             | `MEMORY_MIN_CONFIDENCE`      |
| 去重阈值   | 0.85            | `MEMORY_DUPLICATE_THRESHOLD` |
| 速率限制   | 3 次/session/24h | `MEMORY_MAX_EXTRACTIONS`     |
| 最小内容长度 | 5 字符            | `MEMORY_MIN_LENGTH`          |
| 最大内容长度 | 2000 字符         | `MEMORY_MAX_LENGTH`          |

### Memory Tools

Agent 通过两个内置工具自主管理记忆：

```mermaid theme={null}
graph LR
    Agent["Agent"]
    add["memory_add<br/>保存记忆"]
    search["memory_search<br/>搜索记忆"]

    Agent --> add
    Agent --> search

    add --> MS["MemoryService"]
    search --> MS
```

| 工具              | 触发场景                | 参数                                   |
| --------------- | ------------------- | ------------------------------------ |
| `memory_add`    | 用户说「记住」「帮我记住」「我是…」等 | `content`, `memory_type`, `scope`    |
| `memory_search` | Agent 需要回忆用户信息      | `query`, `k`, `memory_type`, `scope` |

工具通过 `RunnableConfig` 接收 `user_id`、`project_id`、`session_id`，在 Agent 模式下默认启用 (`enable_memory=True`)。

***

## 上下文集成

记忆通过两种机制参与 Agent 的[上下文（Context）](/zh/documentation/core-capabilities/context)：

1. **被动注入**：在[系统提示词](/zh/documentation/core-capabilities/system-prompt)组装阶段，系统自动获取用户/项目画像和语义相关的记忆条目，以结构化文本追加到提示词末尾
2. **主动提取**：在 Agent 执行阶段，Agent 主动调用 `memory_add` 提取并持久化重要信息

**被动注入流程**：在上下文组装阶段，`_init_context()` 调用 `_fetch_profile()` 获取用户/项目画像，调用 `_fetch_relevant_memories()` 进行语义检索获取 Top K 记忆条目，两者格式化后追加到系统提示词末尾。

**主动提取流程**：在 Agent 执行阶段，Agent 调用 `memory_add` 工具，经 Gate 门控验证后，同时写入 pgvector（向量索引）和 PostgreSQL（元数据）。

完整的系统提示词组装流程参见[系统提示词](/zh/documentation/core-capabilities/system-prompt)，更广泛的上下文组装参见[上下文](/zh/documentation/core-capabilities/context)。

### 检索排序算法

多 scope 记忆检索后，通过加权评分进行合并排序：

**final\_score = similarity × 0.5 + confidence × 0.3 + scope\_priority × 0.2**

其中 scope 优先级：

| Scope   | 优先级权重 | 说明      |
| ------- | ----- | ------- |
| session | 1.0   | 当前会话最相关 |
| project | 0.8   | 项目上下文次之 |
| user    | 0.6   | 全局信息基础  |

同类型记忆去重后保留分数最高的条目，最终返回 Top K 结果。

***

## 权限模型

项目级记忆具有细粒度的权限控制：

```mermaid theme={null}
graph TD
    subgraph Roles["项目角色"]
        owner["Owner"]
        admin["Admin"]
        editor["Editor"]
        viewer["Viewer"]
    end

    subgraph Actions["操作权限"]
        read["Read"]
        create["Create"]
        edit["Edit"]
        del["Delete"]
    end

    owner --> read & create & edit & del
    admin --> read & create & edit & del
    editor --> read & create
    editor -->|"仅自己创建的"| edit & del
    viewer --> read
```

| 角色     | 读取 | 创建 | 编辑    | 删除    |
| ------ | -- | -- | ----- | ----- |
| Owner  | 全部 | 全部 | 全部    | 全部    |
| Admin  | 全部 | 全部 | 全部    | 全部    |
| Editor | 全部 | 全部 | 仅自己创建 | 仅自己创建 |
| Viewer | 全部 | 不可 | 不可    | 不可    |

`visibility` 字段进一步控制可见范围：

* `public`：所有项目成员可见
* `members`：项目成员可见（默认）
* `owner_only`：仅创建者可见

***

## 向量存储

记忆的向量存储使用 **PostgreSQL pgvector** 扩展，与 RAG 知识库共享底层基础设施：

```mermaid theme={null}
graph LR
    subgraph VectorStore["VectorStore (Singleton)"]
        direction TB
        cache["collection 缓存池"]
        embed["Embedding 配置<br/>支持用户自定义"]
    end

    memory_col["collection: memory"]
    rag_col["collection: knowledge_base"]

    VectorStore --> memory_col
    VectorStore --> rag_col
    memory_col --> pgvector["PostgreSQL pgvector"]
    rag_col --> pgvector
```

| 配置项               | 默认值                      | 说明        |
| ----------------- | ------------------------ | --------- |
| Embedding Model   | `text-embedding-3-small` | 支持用户自定义模型 |
| Vector Dimensions | 1536                     | 与模型对应     |
| Similarity Metric | Cosine                   | 余弦相似度     |
| Collection Name   | `memory`                 | 记忆专用集合    |

每位用户可以配置自己的 Embedding API（模型、Base URL、API Key），系统通过 `create_embeddings(user_id)` 自动加载对应配置。

***

## Episodic Memory 与 Checkpoint

Episodic Memory 通过 LangGraph 的 `PostgresSaver` 实现，负责会话状态的持久化与恢复：

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Agent
    participant Checkpoint as PostgresSaver
    participant PG as PostgreSQL

    Note over Agent,PG: 正常执行
    Agent->>Checkpoint: 自动保存 checkpoint
    Checkpoint->>PG: INSERT langgraph_checkpoint

    Note over User,Agent: 页面刷新 / 中断
    User->>Agent: resume(session_id)
    Agent->>Checkpoint: aget_state(thread_id)
    Checkpoint->>PG: SELECT checkpoint
    PG-->>Checkpoint: messages + agent_state + pending_tool_calls
    Checkpoint-->>Agent: 恢复状态
    Agent->>Agent: 从断点继续执行
```

Checkpoint 存储的内容：

| 数据                   | 说明                           |
| -------------------- | ---------------------------- |
| messages             | 完整消息历史                       |
| agent\_state         | Agent 内部状态（todo\_list、推理上下文） |
| tool\_states         | 工具执行状态                       |
| pending\_tool\_calls | 待用户审批的操作 (HITL)              |

此外，`session_state_snapshot` 表和 `checkpoint_archive` 表分别用于会话状态快照和过期 checkpoint 归档。
