From 2e6f62a519aca4f3e0d99110a2455adfd3c1739e Mon Sep 17 00:00:00 2001 From: yibo Date: Wed, 25 Mar 2026 11:06:47 +0800 Subject: [PATCH] feat: implement Memory Phase 2 — hippocampus retrieval + cerebellum plans --- data/agents/ceo/memory/cerebellum/blm战略规划.md | 19 +++++++++++++++++++ data/agents/ceo/memory/cerebellum/okr目标制定.md | 19 +++++++++++++++++++ data/agents/ceo/memory/hippocampus-index.json | 34 ++++++++++++++++++++++++++++++++++ data/agents/ceo/memory/hippocampus.md | 9 +++++++++ data/agents/ceo/memory/memory.md | 4 +++- data/agents/ceo/todo.md | 3 +++ server/routes/agent-chat.js | 28 ++++++++++++++++++++++++++-- server/scripts/test-memory.js | 157 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ server/services/memory-service.js | 307 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 9 files changed, 573 insertions(+), 7 deletions(-) create mode 100644 data/agents/ceo/memory/cerebellum/blm战略规划.md create mode 100644 data/agents/ceo/memory/cerebellum/okr目标制定.md create mode 100644 data/agents/ceo/memory/hippocampus-index.json create mode 100644 data/agents/ceo/memory/hippocampus.md create mode 100644 server/scripts/test-memory.js diff --git a/data/agents/ceo/memory/cerebellum/blm战略规划.md b/data/agents/ceo/memory/cerebellum/blm战略规划.md new file mode 100644 index 0000000..4ebd43c --- /dev/null +++ b/data/agents/ceo/memory/cerebellum/blm战略规划.md @@ -0,0 +1,19 @@ +# 方案: BLM战略规划 + +> 创建时间: 2026-03-25 + +## 适用条件 +- 需要做年度或长期战略规划 +- 需要分析业绩/机会差距 + +## 执行步骤 +1. 双差分析:业绩差距+机会差距 +2. 战略意图四维度(愿景→目标→近期→指标) +3. 市场洞察(PEST+5Forces) +4. 创新焦点识别 +5. 业务设计五要素(客户×价值×盈利×范围×控制) +6. 执行体系(关键任务+组织+人才+氛围) + +## 注意事项 +- 差距是战略的起点不是终点 +- 业务设计必须有战略控制点 diff --git a/data/agents/ceo/memory/cerebellum/okr目标制定.md b/data/agents/ceo/memory/cerebellum/okr目标制定.md new file mode 100644 index 0000000..d06bb4e --- /dev/null +++ b/data/agents/ceo/memory/cerebellum/okr目标制定.md @@ -0,0 +1,19 @@ +# 方案: OKR目标制定 + +> 创建时间: 2026-03-25 + +## 适用条件 +- 需要制定季度/年度目标 +- 需要将战略分解为可衡量指标 + +## 执行步骤 +1. 从战略目标出发识别3-5个Objective +2. 每个Objective制定2-4个Key Result +3. 用SMART原则检查每个KR +4. 层层对齐:公司OKR→部门OKR→个人OKR +5. 设定每周跟踪和月度复盘节奏 + +## 注意事项 +- O要有鼓舞性,KR要可量化 +- 目标完成率70%为最佳(太高说明目标太保守) +- 避免把KR当成任务清单 diff --git a/data/agents/ceo/memory/hippocampus-index.json b/data/agents/ceo/memory/hippocampus-index.json new file mode 100644 index 0000000..a0027ff --- /dev/null +++ b/data/agents/ceo/memory/hippocampus-index.json @@ -0,0 +1,34 @@ +[ + { + "scenario": "OKR目标制定", + "keywords": [ + "OKR", + "目标", + "制定", + "关键结果", + "objective", + "key result" + ], + "planFile": "okr目标制定.md", + "confidence": 0.85, + "useCount": 1, + "lastUsed": "2026-03-25", + "createdAt": "2026-03-25" + }, + { + "scenario": "BLM战略规划", + "keywords": [ + "BLM", + "战略", + "规划", + "差距分析", + "业务设计", + "战略制定" + ], + "planFile": "blm战略规划.md", + "confidence": 0.9, + "useCount": 0, + "lastUsed": null, + "createdAt": "2026-03-25" + } +] \ No newline at end of file diff --git a/data/agents/ceo/memory/hippocampus.md b/data/agents/ceo/memory/hippocampus.md new file mode 100644 index 0000000..94926aa --- /dev/null +++ b/data/agents/ceo/memory/hippocampus.md @@ -0,0 +1,9 @@ +# 海马体 — 经验记忆索引 + +> 记录过往处理过的情景模式。遇到相似任务时,优先调用小脑中的固化方案。 +> ⚠️ 此文件由系统自动生成,勿手动编辑。真实数据在 hippocampus-index.json。 + +| # | 情景模式 | 匹配关键词 | 方案文件 | 置信度 | 使用次数 | 上次使用 | +|---|---------|-----------|---------|--------|---------|----------| +| 1 | OKR目标制定 | OKR, 目标, 制定, 关键结果, objective, key result | okr目标制定.md | 0.85 | 0 | - | +| 2 | BLM战略规划 | BLM, 战略, 规划, 差距分析, 业务设计, 战略制定 | blm战略规划.md | 0.9 | 0 | - | diff --git a/data/agents/ceo/memory/memory.md b/data/agents/ceo/memory/memory.md index 081d9e4..d83a404 100644 --- a/data/agents/ceo/memory/memory.md +++ b/data/agents/ceo/memory/memory.md @@ -1,7 +1,9 @@ # 我的记忆 ## 关键事实 -- [2026-03-25] [TASK from master] → ## 战略规划的 3 个核心要点 +- [2026-03-25] [TASK from master] → **BLM 模型的核心思想**:以差距分析为起点,通过"战略制定"(市场洞察、战略意图、创新焦点、业务设计五要素)与"战略执行"(关键任务、组织、人才、文化)的双轮驱动,实现业绩差距和机会差距的闭合, +- [2026-03-25] [TASK from master] → 是的,我记得刚才我们讨论的是 **BLM 模型**(Business Leadership Model,业务领先模型)。 +- [2026-03-25] [TASK from master] → ...馈收集机制 | 编辑器产品化 | ## 已验证的模式 (尚无记录) diff --git a/data/agents/ceo/todo.md b/data/agents/ceo/todo.md index 61682bc..aaa5e48 100644 --- a/data/agents/ceo/todo.md +++ b/data/agents/ceo/todo.md @@ -10,3 +10,6 @@ | T-mn4aq3tt | 【完成首个项目剧本大纲】首个互动剧项目《深渊回响》已立项,现在需要完成详细剧本大纲。具体要求:1) 参考 workspace/project_001_proposal.md 中的项目设定;2) 设计完整的故事结构:开端(研究站失联)、发展(救援队员逐步发现真相)、高潮(核心秘密揭露)、结局(多重分支结局);3) 设计核心角色及其对话风格;4) 设计关键互动节点和分支逻辑;5) 将剧本大纲输出到 workspace/project_001_script_outline.md;6) 完成后向我汇报 | ✅ 完成 | master-001 | P1 | 2026-03-24 07:31 | - | | T-mn4b2s1a | 【完成技术架构搭建】首个互动剧项目《深渊回响》剧本大纲已完成,现在需要完成技术架构搭建。具体要求:1) 参考 workspace/project_001_proposal.md 和 workspace/project_001_script_outline.md;2) 设计技术架构方案,包括:AI对话引擎选型、分支逻辑系统、用户状态管理、内容存储方案;3) 明确技术选型理由和依赖库;4) 输出技术架构文档到 workspace/project_001_tech_architecture.md;5) 完成后向我汇报,标志着 NarrativeAI Inc. 公司设立任务全部完成 | ✅ 完成 | master-001 | P0 | 2026-03-24 07:41 | - | | T-mn5g4hlb | 列出你知道的关于战略规划的3个核心要点,简要回答即可,不需要使用工具。 | ✅ 完成 | master | P1 | 2026-03-25 02:50 | - | +| T-mn5g8r4s | 请用一句话总结BLM模型的核心思想。不需要使用任何工具,直接回答即可。 | ✅ 完成 | master | P2 | 2026-03-25 02:53 | - | +| T-mn5g9cri | 你还记得刚才我们讨论了什么模型吗?如果你的记忆中有相关信息,请引用它。不需要使用工具。 | ✅ 完成 | master | P2 | 2026-03-25 02:54 | - | +| T-mn5glp6q | 帮我制定下季度的OKR目标,公司方向是AI互动剧。简要列出结构即可,不需要工具。 | ✅ 完成 | master | P2 | 2026-03-25 03:03 | - | diff --git a/server/routes/agent-chat.js b/server/routes/agent-chat.js index 8bcf37a..c21efbe 100644 --- a/server/routes/agent-chat.js +++ b/server/routes/agent-chat.js @@ -20,7 +20,7 @@ const { ClaudeCliProtocol } = require('@mas/acp-core'); const { Parser } = require('../src/core/parser'); const AgentManager = require('../src/core/agent-manager'); const { GoalsService } = require('../services/goals'); -const { saveSessionSummary, loadRecentMemory } = require('../services/memory-service'); +const { saveSessionSummary, loadRecentMemory, retrieveRelevantPlans } = require('../services/memory-service'); const systemConfig = require('../config'); const router = express.Router(); @@ -293,9 +293,16 @@ function buildSystemPrompt(agentDir) { if (memory.trim()) parts.push('---\n\n# 我的记忆\n\n' + memory.trim()); // short-term — 近期对话摘要 (Phase 1 MVP) - const recentMemory = loadRecentMemory(config?.id || path.basename(agentDir)); + const agentIdForMemory = config?.id || path.basename(agentDir); + const recentMemory = loadRecentMemory(agentIdForMemory); if (recentMemory) parts.push('---\n\n' + recentMemory); + // hippocampus — 海马体检索相关经验 (Phase 2) + // 使用当前任务文本作为检索 key(从 todo.md 或最后一条消息提取) + const todoContent = loadFile(agentDir, 'todo.md'); + const hippocampusPlans = retrieveRelevantPlans(agentIdForMemory, todoContent); + if (hippocampusPlans) parts.push('---\n\n' + hippocampusPlans); + // skills let mainSkill = loadFile(agentDir, '.claude/skills/main_skill/SKILL.md'); if (mainSkill.trim()) { @@ -623,6 +630,23 @@ router.get('/list', (req, res) => { } catch (err) { res.status(500).json({ error: err.message }); } }); +// ── Phase 2: 小脑方案固化 API ── +router.post('/:agentId/memory/cerebellum', (req, res) => { + const { saveCerebellumPlan } = require('../services/memory-service'); + const { scenario, keywords, steps, conditions, notes, rawContent, confidence } = req.body; + if (!scenario) return res.status(400).json({ error: 'scenario is required' }); + + const result = saveCerebellumPlan(req.params.agentId, { + scenario, keywords, steps, conditions, notes, rawContent, + confidence: confidence || 0.7, + }); + if (result) { + res.json({ success: true, path: result }); + } else { + res.status(500).json({ error: 'Failed to save cerebellum plan' }); + } +}); + router.get('/:agentId/info', (req, res) => { const agentDir = path.join(DATA_DIR, req.params.agentId); if (!fs.existsSync(agentDir)) return res.status(404).json({ error: 'Agent not found' }); diff --git a/server/scripts/test-memory.js b/server/scripts/test-memory.js new file mode 100644 index 0000000..2c735ac --- /dev/null +++ b/server/scripts/test-memory.js @@ -0,0 +1,157 @@ +#!/usr/bin/env node +/** + * Memory System Phase 1 MVP — 集成测试 + * + * 测试流程: + * 1. 清理 CEO 的 short-term 和 memory.md + * 2. 发送第一次对话 → 验证 session 摘要和 memory.md 写入 + * 3. 发送第二次对话 → 验证 prompt 中包含近期记忆 + */ + +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +const BASE = 'http://localhost:3000'; +const AGENT = 'ceo'; +const AGENT_DIR = path.resolve(__dirname, '../../data/agents', AGENT); +const SHORT_TERM_DIR = path.join(AGENT_DIR, 'memory', 'short-term'); +const MEMORY_MD = path.join(AGENT_DIR, 'memory', 'memory.md'); + +let passed = 0, failed = 0; + +function assert(condition, msg) { + if (condition) { passed++; console.log(` ✅ ${msg}`); } + else { failed++; console.log(` ❌ ${msg}`); } +} + +function post(url, body) { + return new Promise((resolve, reject) => { + const data = JSON.stringify(body); + const u = new URL(url); + 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 waitForCompletion(agentId, convId, timeoutMs = 120000) { + const metaPath = path.join(AGENT_DIR, '..', agentId, 'conversations', convId, 'meta.json'); + const start = Date.now(); + return new Promise((resolve, reject) => { + const check = () => { + if (Date.now() - start > timeoutMs) return reject(new Error('Timeout')); + try { + const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')); + if (meta.status === 'completed' || meta.status === 'failed') return resolve(meta); + } catch {} + setTimeout(check, 2000); + }; + check(); + }); +} + +async function main() { + console.log('\n🧪 Memory System Phase 1 — 集成测试\n'); + console.log('═'.repeat(50)); + + // ── Step 0: 清理 ── + console.log('\n📋 Step 0: 清理历史数据'); + // 清理 short-term + if (fs.existsSync(SHORT_TERM_DIR)) { + const files = fs.readdirSync(SHORT_TERM_DIR).filter(f => f.startsWith('session-')); + files.forEach(f => fs.unlinkSync(path.join(SHORT_TERM_DIR, f))); + console.log(` 🗑️ 清理了 ${files.length} 个 session 文件`); + } + // 重置 memory.md + fs.writeFileSync(MEMORY_MD, '# 我的记忆\n\n## 关键事实\n(尚无记录)\n\n## 已验证的模式\n(尚无记录)\n\n## 失败教训\n(尚无记录)\n', 'utf-8'); + console.log(' 🗑️ memory.md 已重置'); + + // ── Step 1: 第一次对话 ── + console.log('\n📋 Step 1: 发送第一次对话'); + const resp1 = await post(`${BASE}/api/agent/task/dispatch`, { + from: 'master', to: AGENT, + task: '请用一句话总结BLM模型的核心思想。不需要使用任何工具,直接回答即可。', + priority: 'P2', autoExecute: true, + }); + assert(resp1.success, `dispatch 成功 (taskId: ${resp1.taskId})`); + const convId1 = resp1.executionConvId; + + console.log(' ⏳ 等待对话完成...'); + const meta1 = await waitForCompletion(AGENT, convId1); + assert(meta1.status === 'completed', `对话完成 (status: ${meta1.status})`); + + // 等待 memory 写入(异步) + await sleep(2000); + + // 验证 short-term + const sessions1 = fs.existsSync(SHORT_TERM_DIR) + ? fs.readdirSync(SHORT_TERM_DIR).filter(f => f.startsWith('session-')) + : []; + assert(sessions1.length === 1, `short-term 有 ${sessions1.length} 个 session 文件`); + + if (sessions1.length > 0) { + const sessionContent = fs.readFileSync(path.join(SHORT_TERM_DIR, sessions1[0]), 'utf-8'); + assert(sessionContent.includes('# Session 摘要'), 'session 包含标题'); + assert(sessionContent.includes('BLM') || sessionContent.includes('战略'), 'session 包含任务关键词'); + assert(sessionContent.includes('工具调用'), 'session 包含 toolCall 统计'); + console.log(` 📄 Session 文件: ${sessions1[0]} (${sessionContent.length} 字)`); + } + + // 验证 memory.md + const memContent1 = fs.readFileSync(MEMORY_MD, 'utf-8'); + const hasNewFact = !memContent1.includes('(尚无记录)') || memContent1.match(/- \[202/); + assert(hasNewFact, `memory.md 有新事实记录`); + console.log(` 📝 memory.md: ${memContent1.length} 字`); + + // ── Step 2: 第二次对话 ── + console.log('\n📋 Step 2: 发送第二次对话 (验证近期记忆注入)'); + const resp2 = await post(`${BASE}/api/agent/task/dispatch`, { + from: 'master', to: AGENT, + task: '你还记得刚才我们讨论了什么模型吗?如果你的记忆中有相关信息,请引用它。不需要使用工具。', + priority: 'P2', autoExecute: true, + }); + assert(resp2.success, `第二次 dispatch 成功 (taskId: ${resp2.taskId})`); + const convId2 = resp2.executionConvId; + + console.log(' ⏳ 等待第二次对话完成...'); + const meta2 = await waitForCompletion(AGENT, convId2); + assert(meta2.status === 'completed', `第二次对话完成 (status: ${meta2.status})`); + + await sleep(2000); + + // 验证 short-term 增长 + const sessions2 = fs.readdirSync(SHORT_TERM_DIR).filter(f => f.startsWith('session-')); + assert(sessions2.length === 2, `short-term 有 ${sessions2.length} 个 session 文件 (期望 2)`); + + // 验证 memory.md 条目增长 + const memContent2 = fs.readFileSync(MEMORY_MD, 'utf-8'); + const factCount = (memContent2.match(/- \[202/g) || []).length; + assert(factCount >= 2, `memory.md 有 ${factCount} 条事实 (期望 ≥2)`); + + // 检查最后的 messages.log 是否表明 Agent "记住了" + try { + const logPath = path.join(AGENT_DIR, 'conversations', convId2, 'messages.log'); + const log2 = fs.readFileSync(logPath, 'utf-8'); + const mentionsBLM = log2.includes('BLM') || log2.includes('记忆') || log2.includes('之前'); + assert(mentionsBLM, `Agent 在第二次对话中引用了之前的信息`); + } catch { console.log(' ⚠️ 无法检查 messages.log'); } + + // ── 结果 ── + console.log('\n' + '═'.repeat(50)); + console.log(`\n🏁 测试结果: ${passed} 通过, ${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 948f065..5de323e 100644 --- a/server/services/memory-service.js +++ b/server/services/memory-service.js @@ -6,9 +6,10 @@ * - 对话结束 → 关键事实追加 → memory.md * - 新对话开始 → 加载最近 N 个 session 摘要注入 prompt * - * Phase 2 (TODO): - * - 海马体关键词匹配 - * - 小脑方案固化 + * Phase 2: + * - 海马体关键词匹配 → 检索相关小脑方案 + * - 小脑方案固化 → cerebellum/ 存储成功方案 + * - 海马体索引自动更新 */ const fs = require('fs'); @@ -18,6 +19,8 @@ const DATA_DIR = path.resolve(__dirname, '../../data/agents'); const MAX_SHORT_TERM = 10; // 最多保留最近 N 个 session 摘要 const MAX_MEMORY_MD_SIZE = 3000; // memory.md 最大字符数 const INJECT_SESSION_COUNT = 5; // prompt 注入最近 N 个 session +const HIPPOCAMPUS_MIN_SCORE = 0.3; // 海马体匹配最低分 +const MAX_CEREBELLUM_INJECT = 2; // 最多注入 N 个小脑方案 // ════════════════════════════════════════ // 1. 对话结束 → 自动保存 Session 摘要 @@ -190,7 +193,295 @@ function appendToMemoryMd(agentId, task, result, meta) { } // ════════════════════════════════════════ -// 内部工具函数 +// 4. Phase 2: 海马体检索 (Hippocampus) +// ════════════════════════════════════════ + +/** + * 根据任务文本检索海马体,返回匹配的小脑方案 + * + * @param {string} agentId + * @param {string} taskText - 用户的任务文本 + * @returns {string} 格式化的小脑方案文本(用于注入 prompt) + */ +function retrieveRelevantPlans(agentId, taskText) { + try { + const agentDir = path.join(DATA_DIR, agentId); + const index = loadHippocampusIndex(agentDir); + if (index.length === 0) return ''; + + // 从任务文本提取关键词 + const taskKeywords = extractKeywords(taskText); + if (taskKeywords.length === 0) return ''; + + // 计算每个索引条目的匹配分数 + const scored = index.map(entry => { + const entryKeywords = (entry.keywords || []).map(k => k.toLowerCase()); + const hits = taskKeywords.filter(kw => + entryKeywords.some(ek => ek.includes(kw) || kw.includes(ek)) + ); + const score = entryKeywords.length > 0 + ? hits.length / entryKeywords.length // 命中了 entry 的多少比例关键词 + : 0; + return { ...entry, score, hits }; + }); + + // 过滤 + 排序 + const matches = scored + .filter(e => e.score >= HIPPOCAMPUS_MIN_SCORE) + .sort((a, b) => { + // 先按分数,再按置信度,最后按使用次数 + if (b.score !== a.score) return b.score - a.score; + if ((b.confidence || 0) !== (a.confidence || 0)) return (b.confidence || 0) - (a.confidence || 0); + return (b.useCount || 0) - (a.useCount || 0); + }) + .slice(0, MAX_CEREBELLUM_INJECT); + + if (matches.length === 0) return ''; + + // 加载对应的小脑方案文件 + const cerebellumDir = path.join(agentDir, 'memory', 'cerebellum'); + const plans = []; + + for (const match of matches) { + const planPath = path.join(cerebellumDir, match.planFile); + if (fs.existsSync(planPath)) { + const planContent = fs.readFileSync(planPath, 'utf-8').trim(); + plans.push(`### 经验方案: ${match.scenario} (置信度 ${Math.round((match.confidence || 0) * 100)}%, 使用 ${match.useCount || 0} 次)\n\n${planContent}`); + + // 更新原始索引中的使用次数 + 最后使用时间 + const origEntry = index.find(e => e.planFile === match.planFile); + if (origEntry) { + origEntry.useCount = (origEntry.useCount || 0) + 1; + origEntry.lastUsed = new Date().toISOString().substring(0, 10); + } + } + } + + if (plans.length > 0) { + // 保存更新后的使用统计 + saveHippocampusIndex(agentDir, index); + console.log(`[Memory] 🐴 海马体命中 ${plans.length} 个方案 (agent: ${agentId})`); + } + + if (plans.length === 0) return ''; + + return [ + `# 经验参考(海马体检索)`, + '', + '> 以下是你过去处理类似任务的成功经验。可以参考,但不必完全照搬。', + '', + ...plans, + ].join('\n'); + } catch (err) { + console.error(`[Memory] ⚠️ 海马体检索失败:`, err.message); + return ''; + } +} + +// ════════════════════════════════════════ +// 5. Phase 2: 小脑固化 (Cerebellum) +// ════════════════════════════════════════ + +/** + * 保存一个成功方案到小脑,并更新海马体索引 + * + * @param {string} agentId + * @param {object} plan - { scenario, keywords, steps, notes } + * @returns {string|null} 保存成功返回文件路径 + */ +function saveCerebellumPlan(agentId, plan) { + try { + const agentDir = path.join(DATA_DIR, agentId); + const cerebellumDir = path.join(agentDir, 'memory', 'cerebellum'); + + if (!fs.existsSync(cerebellumDir)) { + fs.mkdirSync(cerebellumDir, { recursive: true }); + } + + // 生成文件名: 基于 scenario 的 slug + const slug = (plan.scenario || 'plan') + .toLowerCase() + .replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-') + .replace(/^-|-$/g, '') + .substring(0, 40); + const filename = `${slug}.md`; + const filepath = path.join(cerebellumDir, filename); + + // 构造方案内容 + const content = [ + `# 方案: ${plan.scenario}`, + '', + `> 创建时间: ${new Date().toISOString().substring(0, 10)}`, + '', + ]; + + if (plan.conditions) { + content.push('## 适用条件', ...plan.conditions.map(c => `- ${c}`), ''); + } + + if (plan.steps) { + content.push('## 执行步骤', ...plan.steps.map((s, i) => `${i + 1}. ${s}`), ''); + } + + if (plan.notes) { + content.push('## 注意事项', ...plan.notes.map(n => `- ${n}`), ''); + } + + if (plan.rawContent) { + content.push('## 详细内容', plan.rawContent, ''); + } + + fs.writeFileSync(filepath, content.join('\n'), 'utf-8'); + + // 更新海马体索引 + const index = loadHippocampusIndex(agentDir); + + // 检查是否已有同名条目 + const existing = index.findIndex(e => e.planFile === filename); + const entry = { + scenario: plan.scenario, + keywords: plan.keywords || [], + planFile: filename, + confidence: plan.confidence || 0.7, + useCount: 0, + lastUsed: null, + createdAt: new Date().toISOString().substring(0, 10), + }; + + if (existing >= 0) { + // 更新已有条目(保留使用次数) + entry.useCount = index[existing].useCount || 0; + entry.lastUsed = index[existing].lastUsed; + index[existing] = entry; + } else { + index.push(entry); + } + + saveHippocampusIndex(agentDir, index); + + // 同步更新 hippocampus.md (人类可读版) + syncHippocampusMd(agentDir, index); + + console.log(`[Memory] 🧩 小脑方案已固化: ${agentId}/cerebellum/${filename}`); + return filepath; + } catch (err) { + console.error(`[Memory] ⚠️ 小脑方案保存失败:`, err.message); + return null; + } +} + +// ════════════════════════════════════════ +// 海马体索引 JSON 读写 +// ════════════════════════════════════════ + +/** + * 加载海马体索引 (JSON 格式,比 md 表格更可靠) + * 文件: memory/hippocampus-index.json + */ +function loadHippocampusIndex(agentDir) { + const indexPath = path.join(agentDir, 'memory', 'hippocampus-index.json'); + try { + return JSON.parse(fs.readFileSync(indexPath, 'utf-8')); + } catch { + return []; + } +} + +/** 保存海马体索引 */ +function saveHippocampusIndex(agentDir, index) { + const indexPath = path.join(agentDir, 'memory', 'hippocampus-index.json'); + const dir = path.dirname(indexPath); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(indexPath, JSON.stringify(index, null, 2), 'utf-8'); +} + +/** + * 同步 hippocampus.md — 人类可读的 markdown 表格 + * (JSON 是程序真正使用的,md 只是给人看) + */ +function syncHippocampusMd(agentDir, index) { + const mdPath = path.join(agentDir, 'memory', 'hippocampus.md'); + const rows = index.map((e, i) => + `| ${i + 1} | ${e.scenario} | ${(e.keywords || []).join(', ')} | ${e.planFile} | ${e.confidence} | ${e.useCount || 0} | ${e.lastUsed || '-'} |` + ); + + const content = [ + '# 海马体 — 经验记忆索引', + '', + '> 记录过往处理过的情景模式。遇到相似任务时,优先调用小脑中的固化方案。', + '> ⚠️ 此文件由系统自动生成,勿手动编辑。真实数据在 hippocampus-index.json。', + '', + '| # | 情景模式 | 匹配关键词 | 方案文件 | 置信度 | 使用次数 | 上次使用 |', + '|---|---------|-----------|---------|--------|---------|----------|', + ...(rows.length > 0 ? rows : ['| | (暂无经验记录) | | | | | |']), + '', + ].join('\n'); + + fs.writeFileSync(mdPath, content, 'utf-8'); +} + +// ════════════════════════════════════════ +// 关键词提取 +// ════════════════════════════════════════ + +/** 中文停用词表(常见无意义词) */ +const STOP_WORDS = new Set([ + '的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', + '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', + '自己', '这', '他', '她', '它', '那', '些', '所以', '因为', '但是', '而且', '或者', + '如果', '虽然', '所有', '可以', '应该', '需要', '能够', '已经', '正在', '请', + '把', '被', '让', '给', '从', '对', '将', '于', '之', '等', '以', '及', '与', + 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', + 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', + 'should', 'may', 'might', 'can', 'shall', 'to', 'of', 'in', 'for', + 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'about', 'and', 'or', + 'but', 'not', 'this', 'that', 'it', 'its', 'my', 'your', 'his', 'her', +]); + +/** + * 从文本中提取关键词 + * 策略: 中文按 2-4 字切片 + 英文按空格分词 + 去停用词 + */ +function extractKeywords(text) { + if (!text || text.length < 2) return []; + + 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 + 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 + 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); + if (!STOP_WORDS.has(tri)) keywords.add(tri); + } + } + } + + return [...keywords].slice(0, 30); // 最多 30 个关键词 +} + +// ════════════════════════════════════════ +// Phase 1 内部工具函数 // ════════════════════════════════════════ /** 从 title 提取任务描述 */ @@ -314,7 +605,15 @@ function truncateMemory(content) { } module.exports = { + // Phase 1 saveSessionSummary, loadRecentMemory, appendToMemoryMd, + // Phase 2 + retrieveRelevantPlans, + saveCerebellumPlan, + extractKeywords, + // 内部 (测试用) + loadHippocampusIndex, + saveHippocampusIndex, }; -- libgit2 0.21.4