From c45e4968ce99ae34497882b18c805f3420814d6e Mon Sep 17 00:00:00 2001 From: yibo Date: Wed, 25 Mar 2026 11:50:15 +0800 Subject: [PATCH] fix(memory): prioritize current task relative to history for hippocampus; optimize Chinese keyword extraction --- data/agents/poet/.claude/scheduled_tasks.lock | 1 + data/agents/poet/memory/cerebellum/为国庆节创作一组主题诗集-包含5首诗.md | 20 ++++++++++++++++++++ data/agents/poet/memory/cerebellum/写古典诗词.md | 20 ++++++++++++++++++++ data/agents/poet/memory/daily/2026-03-25.md | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ data/agents/poet/memory/hippocampus-index.json | 38 ++++++++++++++++++++++++++++++++++++++ data/agents/poet/memory/hippocampus.md | 8 +++++--- data/agents/poet/memory/long-term/consolidate-2026-03-25.md | 25 +++++++++++++++++++++++++ data/agents/poet/memory/long-term/patterns.md | 16 ++++++++++++++++ data/agents/poet/memory/memory.md | 10 +++++++--- data/agents/poet/memory/reflections/reflect-1774410599260.json | 37 +++++++++++++++++++++++++++++++++++++ data/agents/poet/memory/reflections/reflect-1774410599261.json | 14 ++++++++++++++ data/agents/poet/todo.md | 22 ++++++++++++++++++++++ server/routes/agent-chat.js | 9 +++++---- server/scripts/test-memory-e2e.js | 348 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ server/services/memory-service.js | 31 +++++++++++++------------------ 15 files changed, 670 insertions(+), 28 deletions(-) create mode 100644 data/agents/poet/.claude/scheduled_tasks.lock create mode 100644 data/agents/poet/memory/cerebellum/为国庆节创作一组主题诗集-包含5首诗.md create mode 100644 data/agents/poet/memory/cerebellum/写古典诗词.md create mode 100644 data/agents/poet/memory/daily/2026-03-25.md create mode 100644 data/agents/poet/memory/hippocampus-index.json create mode 100644 data/agents/poet/memory/long-term/consolidate-2026-03-25.md create mode 100644 data/agents/poet/memory/long-term/patterns.md create mode 100644 data/agents/poet/memory/reflections/reflect-1774410599260.json create mode 100644 data/agents/poet/memory/reflections/reflect-1774410599261.json create mode 100644 server/scripts/test-memory-e2e.js diff --git a/data/agents/poet/.claude/scheduled_tasks.lock b/data/agents/poet/.claude/scheduled_tasks.lock new file mode 100644 index 0000000..44d24a7 --- /dev/null +++ b/data/agents/poet/.claude/scheduled_tasks.lock @@ -0,0 +1 @@ +{"sessionId":"151999eb-9535-4a75-9abe-b6a0f9383139","pid":55368,"acquiredAt":1774410478451} \ No newline at end of file diff --git a/data/agents/poet/memory/cerebellum/为国庆节创作一组主题诗集-包含5首诗.md b/data/agents/poet/memory/cerebellum/为国庆节创作一组主题诗集-包含5首诗.md new file mode 100644 index 0000000..137bac9 --- /dev/null +++ b/data/agents/poet/memory/cerebellum/为国庆节创作一组主题诗集-包含5首诗.md @@ -0,0 +1,20 @@ +# 方案: 为国庆节创作一组主题诗集,包含5首诗 + +> 创建时间: 2026-03-25 + +## 适用条件 +- 类似任务: 为国庆节创作一组主题诗集,包含5首诗 + +## 执行步骤 +1. 确定国庆主题和5个子题材(国旗、山河、英雄、和平、未来) +2. 分别确定每首诗的体裁(五绝、七绝、五律、七律、词) +3. 创作第一首《旗颂》五言绝句 +4. 创作第二首《山河赋》七言律诗 +5. 创作第三首《英雄辞》五言律诗 +6. 创作第四首《和平吟》七言绝句 +7. 创作第五首《展望》词·水调歌头 +8. 整体校对格律和意境 + +## 注意事项 +- 自动从对话 test-complex 提取 +- 耗时 180秒, 8 次工具调用 diff --git a/data/agents/poet/memory/cerebellum/写古典诗词.md b/data/agents/poet/memory/cerebellum/写古典诗词.md new file mode 100644 index 0000000..52fabc9 --- /dev/null +++ b/data/agents/poet/memory/cerebellum/写古典诗词.md @@ -0,0 +1,20 @@ +# 方案: 写古典诗词 + +> 创建时间: 2026-03-25 + +## 适用条件 +- 需要创作古典诗词 +- 需要遵循格律 + +## 执行步骤 +1. 确认体裁(五绝/七绝/五律/七律/词) +2. 确认主题和意境 +3. 起句: 点明时间/地点/情境 +4. 承句: 展开描写,丰富画面 +5. 转句: 转折或深化情感 +6. 合句: 收束全诗,升华主题 + +## 注意事项 +- 五绝20字,七绝28字 +- 注意平仄和押韵 +- 避免直白说理,用意象表达 diff --git a/data/agents/poet/memory/daily/2026-03-25.md b/data/agents/poet/memory/daily/2026-03-25.md new file mode 100644 index 0000000..33c20ed --- /dev/null +++ b/data/agents/poet/memory/daily/2026-03-25.md @@ -0,0 +1,99 @@ +# 日报 — 2026-03-25 + +## 概览 +- 对话数: 3 +- 反思数: 2 +- 新模式: 2 +- 新教训: 2 +- 固化方案: 1 + +## 对话记录 + +### 2026-03-25 03:48:29 [completed] (2 次, 47秒) +- 任务: [TASK from master] +任务编号: T-mn5i6b4q +优先级: P2 + +请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 + +请立即执行此任务。完成后调用 c +- 结果: ...墨为君绘就一方诗意天地。 + +先恢复我的定时任务,然后为您创作这首踏青绝句。 定时任务已恢复。现在为您创作这首踏青绝句: + +--- + +【作品】 +《踏青》 +(五言绝句,平水韵 十三元) + +草色侵衣绿,花风拂面温。 +踏青人醉处,春在小溪痕。 + +【格律】 +``` +平仄:仄仄平平仄,平平仄仄平。 + 仄平平仄仄,平仄仄平平。 +押韵:温、痕(上平声 十三元韵部) +``` + +【简评】 +此诗以" + +### 2026-03-25 03:49:14 [completed] (1 次, 42秒) +- 任务: [TASK from master] +任务编号: T-mn5i7dqk +优先级: P2 + +你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 + +请立即执行此任务。 +- 结果: 我记得刚才创作了一首关于春天踏青的五言绝句。根据我的近期记忆,任务编号 **T-mn5i6b4q** 中我完成了以下作品: + +--- + +**【作品】《踏青》** +(五言绝句,平水韵 十三元) + +草色侵衣绿,花风拂面温。 +踏青人醉处,春在小溪痕。 + +--- + +此诗通过「草色」「花风」「溪痕」等意象,描绘春日踏青时衣染草绿、面拂花香的惬意场景,末句以"春在小溪痕"收束,将抽象的春意化为流水留下的痕迹, + +### 2026-03-25 03:49:50 [completed] (1 次, 33秒) +- 任务: [TASK from master] +任务编号: T-mn5i8d96 +优先级: P2 + +请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 + +请立即执行此任务。完成后调用 curl 汇报: +- 结果: 在下诗人,愿以笔墨为君绘就一方诗意天地。 + +--- + +【作品】 +《中秋望月》 +(七言绝句,平水韵 十四寒) + +玉轮初上碧云端,万里清辉照画栏。 +此夜人间同仰望,不知秋思落谁边。 + +【格律】 +``` +平仄:仄平平仄仄平平,仄仄平平仄仄平。 + 仄仄平平平仄仄,仄平平仄仄平平。 +押韵:端、栏、边(上平声 十四寒韵部) +``` + +【简评】 +首句"玉轮初上"点出中秋月升之景,次句"万里清辉"写月光 + +## 反思摘要 + +- ✅ 成功创建/修改了 2 个文件: workspace/poet/guoqing-collection.md, workspace/poet/guoqing-notes.md +- ✅ 完成了 8 步工具调用的复杂任务 (180秒) +- ❌ 错误: 输入格式无法解析 Error: Invalid poem format at line 3 +- ❌ 任务失败 (4 tool calls, 60秒): 翻译古诗为英文但格式错误 diff --git a/data/agents/poet/memory/hippocampus-index.json b/data/agents/poet/memory/hippocampus-index.json new file mode 100644 index 0000000..03b7738 --- /dev/null +++ b/data/agents/poet/memory/hippocampus-index.json @@ -0,0 +1,38 @@ +[ + { + "scenario": "写古典诗词", + "keywords": [ + "写诗", + "诗词", + "古诗", + "五言", + "七言", + "绝句", + "律诗", + "创作" + ], + "planFile": "写古典诗词.md", + "confidence": 0.9, + "useCount": 1, + "lastUsed": "2026-03-25", + "createdAt": "2026-03-25" + }, + { + "scenario": "为国庆节创作一组主题诗集,包含5首诗", + "keywords": [ + "为国", + "国庆", + "庆节", + "节创", + "创作", + "作一", + "一组", + "组主" + ], + "planFile": "为国庆节创作一组主题诗集-包含5首诗.md", + "confidence": 0.76, + "useCount": 0, + "lastUsed": null, + "createdAt": "2026-03-25" + } +] \ No newline at end of file diff --git a/data/agents/poet/memory/hippocampus.md b/data/agents/poet/memory/hippocampus.md index f1f6a63..a93eba7 100644 --- a/data/agents/poet/memory/hippocampus.md +++ b/data/agents/poet/memory/hippocampus.md @@ -1,7 +1,9 @@ # 海马体 — 经验记忆索引 > 记录过往处理过的情景模式。遇到相似任务时,优先调用小脑中的固化方案。 +> ⚠️ 此文件由系统自动生成,勿手动编辑。真实数据在 hippocampus-index.json。 -| # | 情景模式 | 匹配条件 | 方案文件 | 置信度 | 使用次数 | 上次使用 | -|---|---------|---------|---------|--------|---------|----------| -| | (暂无经验记录) | | | | | | +| # | 情景模式 | 匹配关键词 | 方案文件 | 置信度 | 使用次数 | 上次使用 | +|---|---------|-----------|---------|--------|---------|----------| +| 1 | 写古典诗词 | 写诗, 诗词, 古诗, 五言, 七言, 绝句, 律诗, 创作 | 写古典诗词.md | 0.9 | 1 | 2026-03-25 | +| 2 | 为国庆节创作一组主题诗集,包含5首诗 | 为国, 国庆, 庆节, 节创, 创作, 作一, 一组, 组主 | 为国庆节创作一组主题诗集-包含5首诗.md | 0.76 | 0 | - | diff --git a/data/agents/poet/memory/long-term/consolidate-2026-03-25.md b/data/agents/poet/memory/long-term/consolidate-2026-03-25.md new file mode 100644 index 0000000..43ac970 --- /dev/null +++ b/data/agents/poet/memory/long-term/consolidate-2026-03-25.md @@ -0,0 +1,25 @@ +# 长期记忆合并 — 2026-03-25 +> 合并了 3 个过期 session (>7 天) +## 高频关键词 +- 任务 (x3) +- 旧任务 (x3) +- 旧任 (x3) +- 写一 (x3) +- 一首 (x3) +- 首关 (x3) +- 关于 (x3) +- 于秋 (x3) +- 秋天 (x3) +- 天的 (x3) +## 合并的对话摘要 +### 2026-03-17 00:00:00 [] (, ) +- 任务: 旧任务-0: 写一首关于秋天的诗 +- 结果: 秋诗完成-0 + +### 2026-03-17 01:00:00 [] (, ) +- 任务: 旧任务-1: 写一首关于秋天的诗 +- 结果: 秋诗完成-1 + +### 2026-03-17 02:00:00 [] (, ) +- 任务: 旧任务-2: 写一首关于秋天的诗 +- 结果: 秋诗完成-2 diff --git a/data/agents/poet/memory/long-term/patterns.md b/data/agents/poet/memory/long-term/patterns.md new file mode 100644 index 0000000..fb3654e --- /dev/null +++ b/data/agents/poet/memory/long-term/patterns.md @@ -0,0 +1,16 @@ +# 长期模式 + +> 从 short-term 多次出现的模式沉淀而来 + + +## 2026-03-25 +- 任务 (x3) +- 旧任务 (x3) +- 旧任 (x3) +- 写一 (x3) +- 一首 (x3) +- 首关 (x3) +- 关于 (x3) +- 于秋 (x3) +- 秋天 (x3) +- 天的 (x3) diff --git a/data/agents/poet/memory/memory.md b/data/agents/poet/memory/memory.md index 388601c..6387544 100644 --- a/data/agents/poet/memory/memory.md +++ b/data/agents/poet/memory/memory.md @@ -1,10 +1,14 @@ # 我的记忆 ## 关键事实 -(尚无记录) +- [2026-03-25] [TASK from master] → ...墨为君绘就一方诗意天地。 +- [2026-03-25] [TASK from master] → 我记得刚才创作了一首关于春天踏青的五言绝句。根据我的近期记忆,任务编号 **T-mn5i6b4q** 中我完成了以下作品: +- [2026-03-25] [TASK from master] → 在下诗人,愿以笔墨为君绘就一方诗意天地。 ## 已验证的模式 -(尚无记录) +- [2026-03-25] 成功创建/修改了 2 个文件: workspace/poet/guoqing-collection.md, workspace/poet/guoqing-notes.md +- [2026-03-25] 完成了 8 步工具调用的复杂任务 (180秒) ## 失败教训 -(尚无记录) +- [2026-03-25] 错误: 输入格式无法解析 Error: Invalid poem format at line 3 +- [2026-03-25] 任务失败 (4 tool calls, 60秒): 翻译古诗为英文但格式错误 diff --git a/data/agents/poet/memory/reflections/reflect-1774410599260.json b/data/agents/poet/memory/reflections/reflect-1774410599260.json new file mode 100644 index 0000000..d785f3f --- /dev/null +++ b/data/agents/poet/memory/reflections/reflect-1774410599260.json @@ -0,0 +1,37 @@ +{ + "timestamp": "2026-03-25T03:49:59.259Z", + "convId": "test-complex", + "task": "为国庆节创作一组主题诗集,包含5首诗", + "status": "completed", + "toolCount": 8, + "durationSec": 180, + "patterns": [ + "成功创建/修改了 2 个文件: workspace/poet/guoqing-collection.md, workspace/poet/guoqing-notes.md", + "完成了 8 步工具调用的复杂任务 (180秒)" + ], + "lessons": [], + "plan": { + "scenario": "为国庆节创作一组主题诗集,包含5首诗", + "keywords": [ + "为国", + "国庆", + "庆节", + "节创", + "创作", + "作一", + "一组", + "组主" + ], + "steps": [ + "确定国庆主题和5个子题材(国旗、山河、英雄、和平、未来)", + "分别确定每首诗的体裁(五绝、七绝、五律、七律、词)", + "创作第一首《旗颂》五言绝句", + "创作第二首《山河赋》七言律诗", + "创作第三首《英雄辞》五言律诗", + "创作第四首《和平吟》七言绝句", + "创作第五首《展望》词·水调歌头", + "整体校对格律和意境" + ], + "confidence": 0.76 + } +} \ No newline at end of file diff --git a/data/agents/poet/memory/reflections/reflect-1774410599261.json b/data/agents/poet/memory/reflections/reflect-1774410599261.json new file mode 100644 index 0000000..cc99546 --- /dev/null +++ b/data/agents/poet/memory/reflections/reflect-1774410599261.json @@ -0,0 +1,14 @@ +{ + "timestamp": "2026-03-25T03:49:59.260Z", + "convId": "test-fail", + "task": "翻译古诗为英文但格式错误", + "status": "failed", + "toolCount": 4, + "durationSec": 60, + "patterns": [], + "lessons": [ + "错误: 输入格式无法解析 Error: Invalid poem format at line 3", + "任务失败 (4 tool calls, 60秒): 翻译古诗为英文但格式错误" + ], + "plan": null +} \ No newline at end of file diff --git a/data/agents/poet/todo.md b/data/agents/poet/todo.md index 9e861eb..804dd7a 100644 --- a/data/agents/poet/todo.md +++ b/data/agents/poet/todo.md @@ -5,3 +5,25 @@ | # | 任务 | 状态 | 分配人 | 优先级 | 接收时间 | 上次检查 | |---|------|------|--------|--------|----------|----------| | T-mn405cps | 测试你的诗词创作功能。请创作一首七言绝句,主题:春天,情感基调:明快。要求:1) 严格按照七律格律;2) 标注平仄和韵部;3) 提供简评赏析 | ✅ 完成 | master-001 | P1 | 2026-03-24 02:35 | - | +| T-mn5h7iux | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:20 | - | +| T-mn5h8dr7 | 你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:21 | - | +| T-mn5h95kh | 请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 | ✅ 完成 | master | P2 | 2026-03-25 03:21 | - | +| T-mn5hcpbb | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:24 | - | +| T-mn5hdrxo | 你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:25 | - | +| T-mn5hei6x | 请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 | ✅ 完成 | master | P2 | 2026-03-25 03:26 | - | +| T-mn5hgw6y | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:27 | - | +| T-mn5hkltv | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:30 | - | +| T-mn5hlt3f | 你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:31 | - | +| T-mn5hmx9j | 请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 | ✅ 完成 | master | P2 | 2026-03-25 03:32 | - | +| T-mn5hpbq3 | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:34 | - | +| T-mn5hqqp4 | 你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:35 | - | +| T-mn5hr98v | 请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 | ✅ 完成 | master | P2 | 2026-03-25 03:35 | - | +| T-mn5hxnyf | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:40 | - | +| T-mn5hyke4 | 你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:41 | - | +| T-mn5hzjx9 | 请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 | ✅ 完成 | master | P2 | 2026-03-25 03:42 | - | +| T-mn5i2hot | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:44 | - | +| T-mn5i3ne9 | 你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:45 | - | +| T-mn5i4rjr | 请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 | ✅ 完成 | master | P2 | 2026-03-25 03:46 | - | +| T-mn5i6b4q | 请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。 | ✅ 完成 | master | P2 | 2026-03-25 03:47 | - | +| T-mn5i7dqk | 你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:48 | - | +| T-mn5i8d96 | 请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。 | ✅ 完成 | master | P2 | 2026-03-25 03:49 | - | diff --git a/server/routes/agent-chat.js b/server/routes/agent-chat.js index 2e89d18..29a5a67 100644 --- a/server/routes/agent-chat.js +++ b/server/routes/agent-chat.js @@ -241,7 +241,7 @@ const BASE_DIR = path.join(__dirname, '../../packages/agent-core/base'); * - tools.md: base/common/tools-base.md + agent/tools.md (追加) * - 其他文件 (soul.md, identity.md 等): 只从 agent/ 读取(纯个性化) */ -function buildSystemPrompt(agentDir) { +function buildSystemPrompt(agentDir, userMessage) { const config = loadAgentConfig(agentDir); const agentType = config?.type || 'skill'; @@ -298,9 +298,10 @@ function buildSystemPrompt(agentDir) { if (recentMemory) parts.push('---\n\n' + recentMemory); // hippocampus — 海马体检索相关经验 (Phase 2) - // 使用当前任务文本作为检索 key(从 todo.md 或最后一条消息提取) + // 将 userMessage 放在前,避免 todo.md 历史堆积导致当前任务的关键词被截断 const todoContent = loadFile(agentDir, 'todo.md'); - const hippocampusPlans = retrieveRelevantPlans(agentIdForMemory, todoContent); + const searchText = [userMessage || '', todoContent].join('\n\n'); + const hippocampusPlans = retrieveRelevantPlans(agentIdForMemory, searchText); if (hippocampusPlans) parts.push('---\n\n' + hippocampusPlans); // skills @@ -551,7 +552,7 @@ function buildPrompt(agentDir, agentId, convId, userMessage, isNewSession) { return userMessage; } - const systemPrompt = buildSystemPrompt(agentDir); + const systemPrompt = buildSystemPrompt(agentDir, userMessage); const cronInstructions = buildCronInstructions(agentDir); const history = loadHistory(agentId, convId); diff --git a/server/scripts/test-memory-e2e.js b/server/scripts/test-memory-e2e.js new file mode 100644 index 0000000..badf012 --- /dev/null +++ b/server/scripts/test-memory-e2e.js @@ -0,0 +1,348 @@ +#!/usr/bin/env node +/** + * Memory System — 完整端到端测试 + * + * 用真实 Agent 对话验证三个 Phase 的完整效果: + * + * Phase 1 验证: + * ① 对话完成 → short-term/ 自动出现 session 文件 + * ② memory.md 自动追加关键事实 + * ③ 第二次对话 → Agent 能引用第一次的内容(近期记忆注入) + * + * Phase 2 验证: + * ④ 保存小脑方案 → hippocampus-index.json 更新 + * ⑤ 发送匹配任务 → 海马体命中方案 → prompt 体积增大 + * ⑥ 使用次数自动递增 + * + * Phase 3 验证: + * ⑦ 复杂任务(多 tool call)→ 自动触发反思 → reflections/ 出现日志 + * ⑧ memory.md "已验证模式" / "失败教训" 段被更新 + * ⑨ 过期 short-term 合并 → long-term/ 出现合并记录 + * ⑩ 日报 API → daily/{today}.md 生成 + */ + +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +const BASE = 'http://localhost:3000'; +const AGENT = 'poet'; // 用 poet 做测试(轻量级、不影响 ceo 数据) +const DATA_DIR = path.resolve(__dirname, '../../data/agents'); +const AGENT_DIR = path.join(DATA_DIR, AGENT); +const MEM = path.join(AGENT_DIR, 'memory'); + +let passed = 0, failed = 0, total = 0; + +function test(condition, msg) { + total++; + if (condition) { passed++; console.log(` ✅ ${msg}`); } + else { failed++; console.log(` ❌ FAIL: ${msg}`); } +} + +// ── HTTP 工具 ── +function post(urlStr, body) { + return new Promise((resolve, reject) => { + const data = JSON.stringify(body); + const u = new URL(urlStr); + const req = http.request({ + hostname: u.hostname, port: u.port, path: u.pathname, method: 'POST', + headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } + }, res => { + let buf = ''; + res.on('data', c => buf += c); + res.on('end', () => { try { resolve(JSON.parse(buf)); } catch { resolve(buf); } }); + }); + req.on('error', reject); + req.write(data); + req.end(); + }); +} + +function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } + +function waitForStatus(agentId, convId, timeoutMs = 120000) { + const start = Date.now(); + return new Promise((resolve, reject) => { + const check = () => { + if (Date.now() - start > timeoutMs) return reject(new Error(`Timeout waiting for ${convId}`)); + try { + const metaPath = path.join(DATA_DIR, agentId, 'conversations', convId, 'meta.json'); + const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')); + if (meta.status === 'completed' || meta.status === 'failed') return resolve(meta); + } catch {} + setTimeout(check, 2000); + }; + check(); + }); +} + +function readFile(p) { try { return fs.readFileSync(p, 'utf-8'); } catch { return ''; } } +function listDir(p) { try { return fs.readdirSync(p); } catch { return []; } } + +// ════════════════════════════════════════ +// Clean Slate +// ════════════════════════════════════════ +function cleanMemory() { + const dirs = ['short-term', 'long-term', 'reflections', 'cerebellum', 'daily']; + for (const d of dirs) { + const dir = path.join(MEM, d); + if (fs.existsSync(dir)) { + for (const f of fs.readdirSync(dir)) { + if (f === '.' || f === '..') continue; + try { fs.unlinkSync(path.join(dir, f)); } catch {} + } + } + } + // 重置 memory.md + fs.writeFileSync(path.join(MEM, 'memory.md'), + '# 我的记忆\n\n## 关键事实\n(尚无记录)\n\n## 已验证的模式\n(尚无记录)\n\n## 失败教训\n(尚无记录)\n', 'utf-8'); + // 清 hippocampus + const hippIdx = path.join(MEM, 'hippocampus-index.json'); + if (fs.existsSync(hippIdx)) fs.unlinkSync(hippIdx); +} + +// ════════════════════════════════════════ +// Main Test +// ════════════════════════════════════════ +async function main() { + console.log('\n🧠 Memory System — 端到端集成测试'); + console.log('═'.repeat(56)); + console.log(` Agent: ${AGENT}`); + console.log(` Server: ${BASE}`); + console.log('═'.repeat(56)); + + // ── 0. Clean ── + console.log('\n🗑️ Step 0: 清理历史数据'); + cleanMemory(); + console.log(' Done.\n'); + + // ═══════════════════════════════════ + // PHASE 1: 基础记忆读写 + // ═══════════════════════════════════ + console.log('┌──────────────────────────────────┐'); + console.log('│ PHASE 1: 基础记忆读写 │'); + console.log('└──────────────────────────────────┘'); + + // ── 1a. 第一次对话 ── + console.log('\n📋 1a. 发送第一次对话:让 Poet 写一首关于春天的五言绝句'); + const r1 = await post(`${BASE}/api/agent/task/dispatch`, { + from: 'master', to: AGENT, + task: '请写一首关于春天的五言绝句,主题是踏青。不需要使用任何工具,直接创作即可。', + priority: 'P2', autoExecute: true, + }); + test(r1.success, `Dispatch 成功 (taskId: ${r1.taskId})`); + const conv1 = r1.executionConvId; + + console.log(' ⏳ 等待对话完成...'); + const meta1 = await waitForStatus(AGENT, conv1); + test(meta1.status === 'completed', `对话完成 (toolCalls: ${meta1.stats?.toolCallCount})`); + await sleep(2000); + + // ① session 文件 + const sessions1 = listDir(path.join(MEM, 'short-term')).filter(f => f.startsWith('session-')); + test(sessions1.length >= 1, `① short-term/ 有 ${sessions1.length} 个 session 文件`); + + // ② memory.md 更新 + const mem1 = readFile(path.join(MEM, 'memory.md')); + const hasFact = mem1.includes('[2026-') || !mem1.includes('(尚无记录)'); + test(hasFact, `② memory.md 已更新关键事实`); + + // ── 1b. 第二次对话(验证近期记忆注入) ── + console.log('\n📋 1b. 发送第二次对话:要求 Agent 回忆之前写了什么'); + const r2 = await post(`${BASE}/api/agent/task/dispatch`, { + from: 'master', to: AGENT, + task: '你还记得刚才写了什么内容吗?如果你的近期记忆中有相关信息,请引用它回答。不需要使用工具。', + priority: 'P2', autoExecute: true, + }); + test(r2.success, `Dispatch 成功 (taskId: ${r2.taskId})`); + const conv2 = r2.executionConvId; + + console.log(' ⏳ 等待对话完成...'); + const meta2 = await waitForStatus(AGENT, conv2); + test(meta2.status === 'completed', `对话完成`); + await sleep(2000); + + // ③ 验证 Agent 引用了之前的内容 + const log2Path = path.join(AGENT_DIR, 'conversations', conv2, 'messages.log'); + const log2 = readFile(log2Path); + const remembered = log2.includes('春') || log2.includes('踏青') || log2.includes('诗') || log2.includes('记忆'); + test(remembered, `③ Agent 在第二次对话中引用了之前的春天/踏青内容`); + + const sessions2 = listDir(path.join(MEM, 'short-term')).filter(f => f.startsWith('session-')); + test(sessions2.length >= 2, `short-term/ 现在有 ${sessions2.length} 个 session 文件`); + + // ═══════════════════════════════════ + // PHASE 2: 海马体检索 + 小脑 + // ═══════════════════════════════════ + console.log('\n┌──────────────────────────────────┐'); + console.log('│ PHASE 2: 海马体检索 + 小脑固化 │'); + console.log('└──────────────────────────────────┘'); + + // ④ 保存小脑方案 + console.log('\n📋 2a. 保存一个"写诗"小脑方案'); + const planRes = await post(`${BASE}/api/agent/${AGENT}/memory/cerebellum`, { + scenario: '写古典诗词', + keywords: ['写诗', '诗词', '古诗', '五言', '七言', '绝句', '律诗', '创作'], + conditions: ['需要创作古典诗词', '需要遵循格律'], + steps: [ + '确认体裁(五绝/七绝/五律/七律/词)', + '确认主题和意境', + '起句: 点明时间/地点/情境', + '承句: 展开描写,丰富画面', + '转句: 转折或深化情感', + '合句: 收束全诗,升华主题', + ], + notes: ['五绝20字,七绝28字', '注意平仄和押韵', '避免直白说理,用意象表达'], + confidence: 0.9, + }); + test(planRes.success, `④ 小脑方案保存成功`); + + // 验证 hippocampus 索引 + const hippIdx = readFile(path.join(MEM, 'hippocampus-index.json')); + test(hippIdx.includes('写古典诗词'), `hippocampus-index.json 包含新条目`); + + // ⑤ 发送匹配任务 → 验证海马体命中 + console.log('\n📋 2b. 发送"写诗"任务 → 验证海马体检索'); + const r3 = await post(`${BASE}/api/agent/task/dispatch`, { + from: 'master', to: AGENT, + task: '请写一首七言绝句,主题是中秋月夜。不需要使用工具,直接创作。', + priority: 'P2', autoExecute: true, + }); + test(r3.success, `Dispatch 成功 (taskId: ${r3.taskId})`); + const conv3 = r3.executionConvId; + + console.log(' ⏳ 等待对话完成...'); + await waitForStatus(AGENT, conv3); + await sleep(2000); + + // ⑥ 验证使用次数递增 + // 海马体 useCount 在 buildSystemPrompt 时更新,需等服务端写完文件 + await sleep(5000); + const hippRaw = readFile(path.join(MEM, 'hippocampus-index.json')); + console.log(` 🔍 hippocampus raw: ${hippRaw.substring(0, 200)}`); + const hippIdxAfter = JSON.parse(hippRaw || '[]'); + const poetryEntry = hippIdxAfter.find(e => e.scenario === '写古典诗词'); + console.log(` 🔍 poetryEntry: ${JSON.stringify(poetryEntry)}`); + test(poetryEntry && poetryEntry.useCount >= 1, `⑥ 海马体使用次数: ${poetryEntry?.useCount} (期望 ≥1)`); + test(poetryEntry && poetryEntry.lastUsed !== null, `lastUsed 已更新: ${poetryEntry?.lastUsed}`); + + // ═══════════════════════════════════ + // PHASE 3: 反思 + 合并 + 日报 + // ═══════════════════════════════════ + console.log('\n┌──────────────────────────────────┐'); + console.log('│ PHASE 3: 反思 + 合并 + 日报 │'); + console.log('└──────────────────────────────────┘'); + + // ⑦ 模拟复杂对话触发反思 + console.log('\n📋 3a. 模拟复杂对话 → 验证自动反思'); + const { autoReflect } = require('../../server/services/memory-service'); + const complexMeta = { + status: 'completed', + stats: { toolCallCount: 8, messageCount: 4 }, + createdAt: new Date(Date.now() - 180000).toISOString(), + updatedAt: new Date().toISOString(), + title: '为国庆节创作一组主题诗集,包含5首诗', + }; + const complexOutput = `创作完成!以下是创作步骤: +1. 确定国庆主题和5个子题材(国旗、山河、英雄、和平、未来) +2. 分别确定每首诗的体裁(五绝、七绝、五律、七律、词) +3. 创作第一首《旗颂》五言绝句 +4. 创作第二首《山河赋》七言律诗 +5. 创作第三首《英雄辞》五言律诗 +6. 创作第四首《和平吟》七言绝句 +7. 创作第五首《展望》词·水调歌头 +8. 整体校对格律和意境 + +产出文件: +- workspace/poet/guoqing-collection.md +- workspace/poet/guoqing-notes.md`; + + const reflectResult = autoReflect(AGENT, 'test-complex', complexMeta, complexOutput); + test(reflectResult !== null, `⑦ 复杂对话触发了反思`); + test(reflectResult?.patterns?.length >= 1, `提取了 ${reflectResult?.patterns?.length} 个模式`); + test(reflectResult?.plan !== null, `自动固化了方案`); + + // 验证 reflections 目录 + const reflectFiles = listDir(path.join(MEM, 'reflections')).filter(f => f.startsWith('reflect-')); + test(reflectFiles.length >= 1, `reflections/ 有 ${reflectFiles.length} 个日志`); + + // ⑧ memory.md 更新 + const mem3 = readFile(path.join(MEM, 'memory.md')); + test(!mem3.includes('已验证的模式\n(尚无记录)'), `⑧ memory.md "已验证模式" 段有内容`); + + // 模拟失败对话 + console.log('\n📋 3b. 模拟失败对话 → 验证教训提取'); + const failReflect = autoReflect(AGENT, 'test-fail', { + status: 'failed', + stats: { toolCallCount: 4, messageCount: 2 }, + createdAt: new Date(Date.now() - 60000).toISOString(), + updatedAt: new Date().toISOString(), + title: '翻译古诗为英文但格式错误', + }, 'error: 输入格式无法解析 Error: Invalid poem format at line 3'); + + test(failReflect?.lessons?.length >= 1, `失败对话提取了 ${failReflect?.lessons?.length} 个教训`); + const mem3b = readFile(path.join(MEM, 'memory.md')); + test(!mem3b.includes('失败教训\n(尚无记录)'), `memory.md "失败教训" 段有内容`); + + // ⑨ 记忆合并 + console.log('\n📋 3c. 记忆合并 (short-term → long-term)'); + // 创建 3 个"过期"session(8天前) + const shortDir = path.join(MEM, 'short-term'); + const oldTs = Date.now() - 8 * 24 * 60 * 60 * 1000; + for (let i = 0; i < 3; i++) { + fs.writeFileSync(path.join(shortDir, `session-${oldTs + i}.md`), + `# Session 摘要\n\n- **时间**: 2026-03-17 0${i}:00:00\n\n## 任务\n旧任务-${i}: 写一首关于秋天的诗\n\n## 结果\n秋诗完成-${i}\n`, 'utf-8'); + } + + const shortBefore = listDir(shortDir).filter(f => f.startsWith('session-')); + console.log(` short-term/ 合并前: ${shortBefore.length} 文件`); + + const consolidateRes = await post(`${BASE}/api/agent/${AGENT}/memory/consolidate`, {}); + test(consolidateRes.merged === 3, `⑨ 合并了 ${consolidateRes.merged} 个过期 session (期望 3)`); + + const ltFiles = listDir(path.join(MEM, 'long-term')); + test(ltFiles.some(f => f.startsWith('consolidate-')), `long-term/ 有合并记录`); + + const shortAfter = listDir(shortDir).filter(f => { + const ts = parseInt(f.replace('session-', '').replace('.md', '')); + return !isNaN(ts) && ts < oldTs + 5; + }); + test(shortAfter.length === 0, `过期 session 已从 short-term/ 删除`); + + // ⑩ 日报 + console.log('\n📋 3d. 日报生成'); + const dailyRes = await post(`${BASE}/api/agent/${AGENT}/memory/daily-report`, {}); + test(dailyRes.success, `⑩ 日报生成成功`); + + const today = new Date().toISOString().substring(0, 10); + const dailyContent = readFile(path.join(MEM, 'daily', `${today}.md`)); + test(dailyContent.includes('# 日报'), `daily/${today}.md 包含日报标题`); + test(dailyContent.includes('对话数'), `日报包含统计数据`); + test(dailyContent.includes('反思摘要') || dailyContent.includes('反思数'), `日报包含反思信息`); + + // ═══════════════════════════════════ + // 最终汇总 + // ═══════════════════════════════════ + console.log('\n' + '═'.repeat(56)); + console.log('\n📊 Memory 目录最终状态:'); + const finalState = { + 'short-term/': listDir(path.join(MEM, 'short-term')).filter(f => f.endsWith('.md')).length, + 'long-term/': listDir(path.join(MEM, 'long-term')).length, + 'cerebellum/': listDir(path.join(MEM, 'cerebellum')).length, + 'reflections/': listDir(path.join(MEM, 'reflections')).length, + 'daily/': listDir(path.join(MEM, 'daily')).filter(f => f.endsWith('.md')).length, + 'memory.md': `${readFile(path.join(MEM, 'memory.md')).length} 字`, + 'hippocampus': hippIdxAfter.length + ' 条索引', + }; + for (const [k, v] of Object.entries(finalState)) { + console.log(` 📁 ${k.padEnd(18)} ${typeof v === 'number' ? v + ' 文件' : v}`); + } + + console.log('\n' + '═'.repeat(56)); + const status = failed === 0 ? '🎉 ALL PASSED' : '⚠️ SOME FAILED'; + console.log(`\n${status}: ${passed}/${total} 通过, ${failed} 失败\n`); + + if (failed > 0) process.exit(1); +} + +main().catch(err => { console.error('💥 测试崩溃:', err); process.exit(1); }); diff --git a/server/services/memory-service.js b/server/services/memory-service.js index b9b6d88..6dca2de 100644 --- a/server/services/memory-service.js +++ b/server/services/memory-service.js @@ -222,6 +222,7 @@ function retrieveRelevantPlans(agentId, taskText) { const score = entryKeywords.length > 0 ? hits.length / entryKeywords.length // 命中了 entry 的多少比例关键词 : 0; + console.log(`[HippocampusDebug] agent=${agentId} scenario="${entry.scenario}" score=${score} hits=${hits.length} taskKwLength=${taskKeywords.length} entryKws=${entryKeywords.length}`); return { ...entry, score, hits }; }); @@ -440,35 +441,22 @@ const STOP_WORDS = new Set([ /** * 从文本中提取关键词 - * 策略: 中文按 2-4 字切片 + 英文按空格分词 + 去停用词 + * 取前 1500 字符,优先处理中文分词(重要任务内容),再处理英文,避免英文占位符号挤占中文。 */ function extractKeywords(text) { if (!text || text.length < 2) return []; + text = text.trim().substring(0, 1500); // 截断避免太长 const keywords = new Set(); - // 1. 英文词 (≥2字母) - const englishWords = text.match(/[a-zA-Z]{2,}/g) || []; - englishWords.forEach(w => { - const lower = w.toLowerCase(); - if (!STOP_WORDS.has(lower) && lower.length >= 3) { - keywords.add(lower); - } - }); - - // 2. 中文:提取连续中文字符序列,再分割成 2-4 字的 ngram + // 1. 中文:提取连续中文字符序列,再分割成 2-4 字的 ngram const chineseSegments = text.match(/[\u4e00-\u9fff]{2,}/g) || []; for (const seg of chineseSegments) { - // 完整段 (如果 ≤6 字) - if (seg.length <= 6 && !STOP_WORDS.has(seg)) { - keywords.add(seg); - } - // 2-gram + if (seg.length <= 6 && !STOP_WORDS.has(seg)) keywords.add(seg); for (let i = 0; i <= seg.length - 2; i++) { const bi = seg.substring(i, i + 2); if (!STOP_WORDS.has(bi)) keywords.add(bi); } - // 3-gram (如果段够长) if (seg.length >= 3) { for (let i = 0; i <= seg.length - 3; i++) { const tri = seg.substring(i, i + 3); @@ -477,7 +465,14 @@ function extractKeywords(text) { } } - return [...keywords].slice(0, 30); // 最多 30 个关键词 + // 2. 英文词 (≥2字母) + const englishWords = text.match(/[a-zA-Z]{2,}/g) || []; + englishWords.forEach(w => { + const lower = w.toLowerCase(); + if (!STOP_WORDS.has(lower) && lower.length >= 3) keywords.add(lower); + }); + + return [...keywords].slice(0, 50); // 最多 50 个关键词 } // ════════════════════════════════════════ -- libgit2 0.21.4