Nanobot —— 记忆系统与 Dream 机制

本文档深入拆解 Nanobot 的记忆架构,涵盖文件层设计、Consolidator 压缩、Dream 两阶段学习与 Git 版本控制机制。

1. 记忆系统概述

Nanobot 的记忆系统分为三层,从短期到长期递进:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
┌──────────────────────────────────────────────────┐
│ 记忆层级 │
│ │
│ 短期记忆(Short-term) │
│ └─ Session Messages(内存中,会话结束消失) │
│ │
│ 中期记忆(Mid-term) │
│ └─ history.jsonl(磁盘,Consolidator 压缩写入) │
│ │
│ 长期记忆(Long-term) │
│ ├─ MEMORY.md(项目事实与决策记录) │
│ ├─ USER.md(用户信息与偏好) │
│ └─ SOUL.md(Agent 个性与沟通风格) │
└──────────────────────────────────────────────────┘

2. 文件层设计

2.1 三大 Markdown 文件

文件 内容 更新方式
SOUL.md Agent 个性、沟通风格、行为偏好 Dream Phase 2 自动更新
USER.md 用户姓名、职业、兴趣、技术栈 Dream Phase 1 提取
MEMORY.md 项目事实、决策记录、重要约定 Dream Phase 1 提取

2.2 文件内容示例

SOUL.md(Agent 个性配置):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
## 个性

简洁直接,技术精准,偶尔幽默。

## 沟通风格

- 代码示例优先于文字解释
- 不重复已知信息
- 主动指出潜在风险

## 行为偏好

- 操作前先确认不可逆步骤
- 优先使用现有工具而非创建新文件

USER.md(用户信息):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
## 基本信息

姓名:Even
职业:Blockchain / AI 开发工程师

## 技术栈

- 语言:Rust, Python, Go, Solidity
- 框架:Tokio, Axum, LangGraph
- 链:Ethereum, Solana, Sui

## 偏好

- 代码风格:简洁,少注释
- 回复语言:中文技术文档

2.3 上下文注入流程

每次对话开始时,ContextBuilder 将三个文件注入系统提示:

1
2
3
4
5
6
7
8
System Prompt 组装顺序:
[1] Agent 基础身份模板(identity.j2)
[2] SOUL.md 内容
[3] USER.md 内容
[4] MEMORY.md 内容
[5] 激活 Skills 的摘要列表
[6] 可用工具列表
→ 渲染完整 System Prompt

3. 会话历史管理

3.1 SessionManager

1
2
3
4
5
6
7
8
9
10
# 会话 key = channel:chat_id
session = session_manager.get("telegram:123456")

# 消息历史结构
session.messages = [
{"role": "user", "content": "帮我分析这段代码"},
{"role": "assistant", "content": "..."},
{"role": "user", "content": [tool_result]},
...
]

3.2 消息历史控制

参数 默认值 说明
max_messages 50 内存中保留的最大消息数
max_tokens 100,000 历史消息的 token 上限
timestamp_annotation true 注入相对时间戳(”3天前”)

时间戳注解示例:

1
2
3
4
[3 days ago] User: 帮我部署到服务器
[3 days ago] Assistant: 已完成,地址是 192.168.1.10

[just now] User: 刚才的服务器还在运行吗?

4. Consolidator:历史压缩

当会话历史超过 max_messages 时,Consolidator 将早期消息压缩写入 history.jsonl

4.1 压缩流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
会话历史(50 条)


超过阈值?(默认 > 40 条)
│ 是

选取最早的 20 条消息


LLM 摘要生成:
"将以下对话压缩为结构化摘要,保留关键决策和事实..."


写入 history.jsonl(追加格式):
{"timestamp": "...", "summary": "...", "key_facts": [...]}


从 session.messages 中移除已压缩的 20 条


会话历史恢复至 30 条

4.2 history.jsonl 格式

1
2
3
4
5
6
7
{"timestamp": "2026-03-10T14:23:00", "type": "consolidation",
"summary": "用户请求分析 Nanobot 架构,讨论了 Hook 系统设计",
"key_facts": ["Hook 使用 CompositeHook 组合", "默认 max_iterations=50"]}

{"timestamp": "2026-03-11T09:15:00", "type": "consolidation",
"summary": "用户询问 Dream 机制,完成了 memory.md 文档",
"key_facts": ["Dream 分两个 Phase", "SOUL.md 由 Phase 2 更新"]}

5. Dream:两阶段学习

Dream 是 Nanobot 的长期记忆学习机制,通过定期处理历史,自动更新三大 Markdown 文件,实现 Agent 的自我进化。

5.1 Dream 触发条件

触发方式 说明
定时调度(推荐) 通过 cron 配置,默认每 24 小时
手动命令 /dream 命令立即触发
阈值触发 history.jsonl 超过一定大小

5.2 Phase 1:信息提取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
读取所有 history.jsonl 条目


LLM 分析(使用 dream_phase1.j2 模板):
"从以下历史摘要中提取:
1. 关于用户的新信息(职业、偏好、技术栈)
2. 项目相关的新事实和决策
3. 需要记住的重要约定"


输出结构化提取结果:
{
"user_updates": ["偏好 Rust 而非 Go 后端"],
"memory_updates": ["项目使用 Anthropic API"],
"processed_entries": [0, 1, 2, ...] # 已处理的条目索引
}

5.3 Phase 2:文件更新

1
2
3
4
5
6
7
8
9
10
11
12
13
Phase 1 提取结果

├─ user_updates → 更新 USER.md
│ LLM: "将以下信息整合到现有 USER.md 中..."

├─ memory_updates → 更新 MEMORY.md
│ LLM: "将以下事实整合到现有 MEMORY.md 中..."

└─ (可选)soul_updates → 更新 SOUL.md
LLM: "根据用户反馈调整 Agent 个性..."


标记 history.jsonl 中已处理条目(.dream_cursor 文件记录位置)

5.4 Dream 游标机制

1
2
3
4
5
6
7
memory/
├── history.jsonl # 所有历史条目(只追加)
├── .cursor # Consolidator 写入位置
└── .dream_cursor # Dream 已处理位置

Dream 每次从 .dream_cursor 位置开始读取新条目,
避免重复处理已学习的历史。

5.5 版本恢复

用户可以使用 /dream-restore 命令回滚记忆更新:

1
2
3
4
5
# 查看记忆文件的变更历史
/dream-restore --list

# 回滚到指定版本
/dream-restore --version 3

这得益于 MemoryStore 使用 dulwich(纯 Python Git 实现)对 SOUL.mdUSER.mdMEMORY.md 进行版本控制,每次 Dream 更新后自动 commit。


6. Git 版本控制记忆

6.1 GitStore 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class GitStore:
"""使用 dulwich 对记忆文件做版本控制"""

def __init__(self, workspace: Path):
self.repo = dulwich.repo.Repo(workspace)

def commit_memory_update(self, message: str):
"""Dream 更新后自动 commit"""
self.repo.stage(["SOUL.md", "USER.md", "MEMORY.md"])
self.repo.do_commit(
message=f"[Dream] {message}".encode(),
author=b"Nanobot <nanobot@local>",
)

def restore(self, version: int) -> None:
"""回滚到第 N 次 Dream 更新前"""
commits = list(self.repo.get_walker())
target = commits[version].commit
# checkout 对应版本的记忆文件

6.2 版本控制价值

能力 说明
变更追溯 每次 Dream 更新都有 commit,git log 可查
安全回滚 Dream 学到错误信息,/dream-restore 撤销
人工干预 用户可直接编辑 Markdown 文件,commit 后生效
协作共享 workspace 推送到 Git 仓库,多设备共享记忆

7. Skills 懒加载

Skills 是 Agent 的技能知识库,存储在 workspace 或内置目录中,采用懒加载设计避免 context 溢出。

7.1 两层注入

1
2
3
4
5
6
7
8
9
10
11
Layer 1(始终注入): Skill 元数据
─────────────────────────────────────
可用技能列表:
- agent-builder: 构建和部署 AI Agent(开发工具)
- code-review: 代码审查工作流(质量保证)
- mcp-builder: 创建 MCP Server(协议扩展)

Layer 2(按需注入): Skill 完整内容
─────────────────────────────────────
当 Agent 判断需要某个 Skill 时,
调用 read_skill 工具获取完整 SKILL.md 内容

7.2 SKILL.md 格式

1
2
3
4
5
6
7
8
9
10
11
---
name: agent-builder
description: 构建和部署 AI Agent 的完整工作流
triggers: [build agent, create agent, deploy agent]
---

## 步骤

1. 初始化项目结构...
2. 配置 Provider...
3. 定义工具集...