diff --git a/data/agents/ceo/memory/cerebellum/创建新的-marketing-agent-并配置所有技能文件.md b/data/agents/ceo/memory/cerebellum/创建新的-marketing-agent-并配置所有技能文件.md new file mode 100644 index 0000000..531b4d8 --- /dev/null +++ b/data/agents/ceo/memory/cerebellum/创建新的-marketing-agent-并配置所有技能文件.md @@ -0,0 +1,18 @@ +# 方案: 创建新的 Marketing Agent 并配置所有技能文件 + +> 创建时间: 2026-03-25 + +## 适用条件 +- 类似任务: 创建新的 Marketing Agent 并配置所有技能文件 + +## 执行步骤 +1. 创建 data/agents/marketing 目录结构 +2. 编写 agent.md 和 soul.md +3. 配置 identity.md (名称: Marketing Agent) +4. 编写 SKILL.md 主技能 +5. 更新 config.json +6. 验证 Agent 列表 + +## 注意事项 +- 自动从对话 test-reflect-001 提取 +- 耗时 120秒, 6 次工具调用 diff --git a/data/agents/ceo/memory/daily/2026-03-25.md b/data/agents/ceo/memory/daily/2026-03-25.md new file mode 100644 index 0000000..5a558c4 --- /dev/null +++ b/data/agents/ceo/memory/daily/2026-03-25.md @@ -0,0 +1,61 @@ +# 日报 — 2026-03-25 + +## 概览 +- 对话数: 3 +- 反思数: 2 +- 新模式: 2 +- 新教训: 2 +- 固化方案: 1 + +## 对话记录 + +### 2026-03-25 02:54:01 [completed] (1 次, 25秒) +- 任务: [TASK from master] +任务编号: T-mn5g8r4s +优先级: P2 + +请用一句话总结BLM模型的核心思想。不需要使用任何工具,直接回答即可。 + +请立即执行此任务。完成后调用 cur +- 结果: **BLM 模型的核心思想**:以差距分析为起点,通过"战略制定"(市场洞察、战略意图、创新焦点、业务设计五要素)与"战略执行"(关键任务、组织、人才、文化)的双轮驱动,实现业绩差距和机会差距的闭合,最终达成业务领先的系统化战略管理框架。 + +--- + +现在向 master 汇报任务完成: ✅ 任务 T-mn5g8r4s 已完成并汇报。 + +### 2026-03-25 02:54:31 [completed] (1 次, 26秒) +- 任务: [TASK from master] +任务编号: T-mn5g9cri +优先级: P2 + +你还记得刚才我们讨论了什么模型吗?如果你的记忆中有相关信息,请引用它。不需要使用工具。 + +请立即执行此任务。完 +- 结果: 是的,我记得刚才我们讨论的是 **BLM 模型**(Business Leadership Model,业务领先模型)。 + +根据我的记忆,BLM 模型的核心思想是: +> 以差距分析为起点,通过"战略制定"(市场洞察、战略意图、创新焦点、业务设计五要素)与"战略执行"(关键任务、组织、人才、文化)的双轮驱动,实现业绩差距和机会差距的闭合。 + +现在向 master 汇报任务完成。 ✅ 任务 T-m + +### 2026-03-25 03:04:56 [completed] (1 次, 1分钟) +- 任务: [TASK from master] +任务编号: T-mn5glp6q +优先级: P2 + +帮我制定下季度的OKR目标,公司方向是AI互动剧。简要列出结构即可,不需要工具。 + +请立即执行此任务。完成后调 +- 结果: ...馈收集机制 | 编辑器产品化 | +| **技术** | AI 推理性能优化 | 稳定性保障 | 工具链开发 | +| **内容** | 剧本质量把控 | 社区运营、创作者激励 | 编剧合作拓展 | +| **运营** | — | 内测招募、口碑传播 | — | + +--- + +## 反思摘要 + +- ✅ 成功创建/修改了 4 个文件: data/agents/marketing, data/agents/marketing/agent.md, data/agents/marketing/soul.md +- ✅ 完成了 6 步工具调用的复杂任务 (120秒) +- ❌ 错误: Connection refused to database. Error: ECONNREFUSED 127.0.0.1:5432 +- ❌ 任务失败 (3 tool calls, 90秒): 部署服务到生产环境 diff --git a/data/agents/ceo/memory/hippocampus-index.json b/data/agents/ceo/memory/hippocampus-index.json index a0027ff..0f5bcc3 100644 --- a/data/agents/ceo/memory/hippocampus-index.json +++ b/data/agents/ceo/memory/hippocampus-index.json @@ -30,5 +30,23 @@ "useCount": 0, "lastUsed": null, "createdAt": "2026-03-25" + }, + { + "scenario": "创建新的 Marketing Agent 并配置所有技能文件", + "keywords": [ + "marketing", + "agent", + "创建新的", + "创建", + "建新", + "新的", + "创建新", + "建新的" + ], + "planFile": "创建新的-marketing-agent-并配置所有技能文件.md", + "confidence": 0.72, + "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 index 94926aa..a496468 100644 --- a/data/agents/ceo/memory/hippocampus.md +++ b/data/agents/ceo/memory/hippocampus.md @@ -5,5 +5,6 @@ | # | 情景模式 | 匹配关键词 | 方案文件 | 置信度 | 使用次数 | 上次使用 | |---|---------|-----------|---------|--------|---------|----------| -| 1 | OKR目标制定 | OKR, 目标, 制定, 关键结果, objective, key result | okr目标制定.md | 0.85 | 0 | - | +| 1 | OKR目标制定 | OKR, 目标, 制定, 关键结果, objective, key result | okr目标制定.md | 0.85 | 1 | 2026-03-25 | | 2 | BLM战略规划 | BLM, 战略, 规划, 差距分析, 业务设计, 战略制定 | blm战略规划.md | 0.9 | 0 | - | +| 3 | 创建新的 Marketing Agent 并配置所有技能文件 | marketing, agent, 创建新的, 创建, 建新, 新的, 创建新, 建新的 | 创建新的-marketing-agent-并配置所有技能文件.md | 0.72 | 0 | - | diff --git a/data/agents/ceo/memory/long-term/consolidate-2026-03-25.md b/data/agents/ceo/memory/long-term/consolidate-2026-03-25.md new file mode 100644 index 0000000..46bc0e1 --- /dev/null +++ b/data/agents/ceo/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 10:00:00 [] (, ) +- 任务: 测试任务0 +- 结果: 测试结果0 + +### 2026-03-17 10:10:00 [] (, ) +- 任务: 测试任务1 +- 结果: 测试结果1 + +### 2026-03-17 10:20:00 [] (, ) +- 任务: 测试任务2 +- 结果: 测试结果2 diff --git a/data/agents/ceo/memory/long-term/patterns.md b/data/agents/ceo/memory/long-term/patterns.md new file mode 100644 index 0000000..04baa38 --- /dev/null +++ b/data/agents/ceo/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/ceo/memory/memory.md b/data/agents/ceo/memory/memory.md index d83a404..23df6ad 100644 --- a/data/agents/ceo/memory/memory.md +++ b/data/agents/ceo/memory/memory.md @@ -6,7 +6,9 @@ - [2026-03-25] [TASK from master] → ...馈收集机制 | 编辑器产品化 | ## 已验证的模式 -(尚无记录) +- [2026-03-25] 成功创建/修改了 4 个文件: data/agents/marketing, data/agents/marketing/agent.md, data/agents/marketing/soul.md +- [2026-03-25] 完成了 6 步工具调用的复杂任务 (120秒) ## 失败教训 -(尚无记录) +- [2026-03-25] 错误: Connection refused to database. Error: ECONNREFUSED 127.0.0.1:5432 +- [2026-03-25] 任务失败 (3 tool calls, 90秒): 部署服务到生产环境 diff --git a/data/agents/ceo/memory/reflections/reflect-1774408504165.json b/data/agents/ceo/memory/reflections/reflect-1774408504165.json new file mode 100644 index 0000000..f8dffd1 --- /dev/null +++ b/data/agents/ceo/memory/reflections/reflect-1774408504165.json @@ -0,0 +1,35 @@ +{ + "timestamp": "2026-03-25T03:15:04.163Z", + "convId": "test-reflect-001", + "task": "创建新的 Marketing Agent 并配置所有技能文件", + "status": "completed", + "toolCount": 6, + "durationSec": 120, + "patterns": [ + "成功创建/修改了 4 个文件: data/agents/marketing, data/agents/marketing/agent.md, data/agents/marketing/soul.md", + "完成了 6 步工具调用的复杂任务 (120秒)" + ], + "lessons": [], + "plan": { + "scenario": "创建新的 Marketing Agent 并配置所有技能文件", + "keywords": [ + "marketing", + "agent", + "创建新的", + "创建", + "建新", + "新的", + "创建新", + "建新的" + ], + "steps": [ + "创建 data/agents/marketing 目录结构", + "编写 agent.md 和 soul.md", + "配置 identity.md (名称: Marketing Agent)", + "编写 SKILL.md 主技能", + "更新 config.json", + "验证 Agent 列表" + ], + "confidence": 0.72 + } +} \ No newline at end of file diff --git a/data/agents/ceo/memory/reflections/reflect-1774408504167.json b/data/agents/ceo/memory/reflections/reflect-1774408504167.json new file mode 100644 index 0000000..fc989e2 --- /dev/null +++ b/data/agents/ceo/memory/reflections/reflect-1774408504167.json @@ -0,0 +1,14 @@ +{ + "timestamp": "2026-03-25T03:15:04.166Z", + "convId": "test-fail", + "task": "部署服务到生产环境", + "status": "failed", + "toolCount": 3, + "durationSec": 90, + "patterns": [], + "lessons": [ + "错误: Connection refused to database. Error: ECONNREFUSED 127.0.0.1:5432", + "任务失败 (3 tool calls, 90秒): 部署服务到生产环境" + ], + "plan": null +} \ No newline at end of file diff --git a/server/routes/agent-chat.js b/server/routes/agent-chat.js index 5126354..2e89d18 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, retrieveRelevantPlans } = require('../services/memory-service'); +const { saveSessionSummary, loadRecentMemory, retrieveRelevantPlans, autoReflect, consolidateMemory, generateDailyReport } = require('../services/memory-service'); const systemConfig = require('../config'); const router = express.Router(); @@ -647,6 +647,17 @@ router.post('/:agentId/memory/cerebellum', (req, res) => { } }); +// ── Phase 3: 记忆管理 API ── +router.post('/:agentId/memory/consolidate', (req, res) => { + const result = consolidateMemory(req.params.agentId); + res.json(result); +}); + +router.post('/:agentId/memory/daily-report', (req, res) => { + const reportPath = generateDailyReport(req.params.agentId); + res.json({ success: !!reportPath, path: reportPath }); +}); + 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' }); @@ -1348,6 +1359,13 @@ ${resultsText.join('\n\n')} console.error('[Memory] Session 摘要保存失败:', memErr.message); } + // ── Phase 3: 自动反思 (toolCallCount>=3 或 duration>=60s 时触发) ── + try { + autoReflect(agentId, convId, meta, fullOutput); + } catch (refErr) { + console.error('[Memory] 反思失败:', refErr.message); + } + sendSSE('result', { conversationId: convId, agentId, messageId: msgId, output: fullOutput }); } catch (err) { diff --git a/server/scripts/test-memory-phase3.js b/server/scripts/test-memory-phase3.js new file mode 100644 index 0000000..0d9f4a8 --- /dev/null +++ b/server/scripts/test-memory-phase3.js @@ -0,0 +1,174 @@ +#!/usr/bin/env node +/** + * Memory System Phase 3 — 集成测试 + * + * 测试: + * 1. autoReflect: 高复杂度对话自动触发反思 + * 2. consolidateMemory: 过期 short-term 合并到 long-term + * 3. generateDailyReport: 日报生成 + */ + +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 MEMORY_DIR = path.join(AGENT_DIR, 'memory'); + +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)); } + +async function main() { + console.log('\n🧪 Memory System Phase 3 — 集成测试\n'); + console.log('═'.repeat(50)); + + // ── Test 1: 直接调用 autoReflect (模拟高复杂度对话) ── + console.log('\n📋 Test 1: autoReflect 引擎'); + const { autoReflect } = require('../../server/services/memory-service'); + + // 模拟一个 5-tool-call 的成功对话 + const mockMeta = { + status: 'completed', + stats: { toolCallCount: 6, messageCount: 3 }, + createdAt: new Date(Date.now() - 120000).toISOString(), + updatedAt: new Date().toISOString(), + title: '创建新的 Marketing Agent 并配置所有技能文件', + }; + const mockOutput = `创建完成!以下是步骤: +1. 创建 data/agents/marketing 目录结构 +2. 编写 agent.md 和 soul.md +3. 配置 identity.md (名称: Marketing Agent) +4. 编写 SKILL.md 主技能 +5. 更新 config.json +6. 验证 Agent 列表 + +文件已写入: +- data/agents/marketing/agent.md +- data/agents/marketing/soul.md +- data/agents/marketing/.claude/skills/main_skill/SKILL.md + +Agent 已成功创建并加入系统。`; + + const reflection = autoReflect(AGENT, 'test-reflect-001', mockMeta, mockOutput); + + assert(reflection !== null, 'autoReflect 返回了结果'); + assert(reflection.patterns.length >= 1, `提取了 ${reflection.patterns.length} 个模式`); + assert(reflection.plan !== null, '自动固化了方案到小脑'); + + // 验证反思日志 + const reflectDir = path.join(MEMORY_DIR, 'reflections'); + const reflectFiles = fs.existsSync(reflectDir) + ? fs.readdirSync(reflectDir).filter(f => f.startsWith('reflect-')) + : []; + assert(reflectFiles.length >= 1, `reflections/ 有 ${reflectFiles.length} 个日志文件`); + + // 验证 memory.md 更新 + const memContent = fs.readFileSync(path.join(MEMORY_DIR, 'memory.md'), 'utf-8'); + assert(!memContent.includes('已验证的模式\n(尚无记录)'), 'memory.md "已验证模式" 段有内容'); + + // 验证小脑方案 + const cerebellumFiles = fs.readdirSync(path.join(MEMORY_DIR, 'cerebellum')); + assert(cerebellumFiles.length >= 3, `cerebellum/ 有 ${cerebellumFiles.length} 个方案 (含自动固化的)`); + + // ── Test 2: autoReflect 对简单对话不触发 ── + console.log('\n📋 Test 2: 简单对话不触发反思'); + const simpleMeta = { + status: 'completed', + stats: { toolCallCount: 1, messageCount: 1 }, + createdAt: new Date(Date.now() - 10000).toISOString(), + updatedAt: new Date().toISOString(), + title: '回答一个简单问题', + }; + const simpleResult = autoReflect(AGENT, 'test-simple', simpleMeta, '这是一个简单回答'); + assert(simpleResult === null, '简单对话 (1 tool, 10s) 不触发反思'); + + // ── Test 3: autoReflect 对失败对话提取教训 ── + console.log('\n📋 Test 3: 失败对话提取教训'); + const failMeta = { + status: 'failed', + stats: { toolCallCount: 3, messageCount: 2 }, + createdAt: new Date(Date.now() - 90000).toISOString(), + updatedAt: new Date().toISOString(), + title: '部署服务到生产环境', + }; + const failOutput = 'error: Connection refused to database. Error: ECONNREFUSED 127.0.0.1:5432'; + const failReflect = autoReflect(AGENT, 'test-fail', failMeta, failOutput); + assert(failReflect !== null, '失败对话触发了反思'); + assert(failReflect.lessons.length >= 1, `提取了 ${failReflect.lessons.length} 个教训`); + + // ── Test 4: consolidateMemory ── + console.log('\n📋 Test 4: 记忆合并'); + // 创建一些"过期"的 short-term 文件 (时间戳 = 8天前) + const shortDir = path.join(MEMORY_DIR, 'short-term'); + const eightDaysAgo = Date.now() - 8 * 24 * 60 * 60 * 1000; + for (let i = 0; i < 3; i++) { + const ts = eightDaysAgo + i * 1000; + fs.writeFileSync(path.join(shortDir, `session-${ts}.md`), + `# Session 摘要\n\n- **时间**: 2026-03-17 10:${i}0:00\n\n## 任务\n测试任务${i}\n\n## 结果\n测试结果${i}\n`, 'utf-8'); + } + + const consolidateResult = await post(`${BASE}/api/agent/${AGENT}/memory/consolidate`, {}); + assert(consolidateResult.merged === 3, `合并了 ${consolidateResult.merged} 个过期 session (期望 3)`); + + // 验证 long-term 目录有文件 + const longTermDir = path.join(MEMORY_DIR, 'long-term'); + const ltFiles = fs.existsSync(longTermDir) + ? fs.readdirSync(longTermDir).filter(f => f.startsWith('consolidate-')) + : []; + assert(ltFiles.length >= 1, `long-term/ 有 ${ltFiles.length} 个合并记录`); + + // 验证过期文件已删除 + const remainingShort = fs.readdirSync(shortDir).filter(f => { + const ts = parseInt(f.replace('session-', '').replace('.md', '')); + return !isNaN(ts) && ts < eightDaysAgo + 5000; + }); + assert(remainingShort.length === 0, '过期的 short-term 文件已删除'); + + // ── Test 5: generateDailyReport ── + console.log('\n📋 Test 5: 日报生成'); + const reportResult = await post(`${BASE}/api/agent/${AGENT}/memory/daily-report`, {}); + assert(reportResult.success, '日报生成成功'); + + const today = new Date().toISOString().substring(0, 10); + const dailyFile = path.join(MEMORY_DIR, 'daily', `${today}.md`); + assert(fs.existsSync(dailyFile), `daily/${today}.md 文件存在`); + + if (fs.existsSync(dailyFile)) { + const dailyContent = fs.readFileSync(dailyFile, 'utf-8'); + assert(dailyContent.includes('# 日报'), '日报包含标题'); + assert(dailyContent.includes('对话数'), '日报包含统计'); + } + + // ── 结果 ── + 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 5de323e..b9b6d88 100644 --- a/server/services/memory-service.js +++ b/server/services/memory-service.js @@ -604,6 +604,386 @@ function truncateMemory(content) { return newLines.join('\n'); } +// ════════════════════════════════════════ +// 6. Phase 3: 自动反思引擎 (Reflect) +// ════════════════════════════════════════ + +const REFLECT_MIN_TOOLS = 3; // 至少 N 个 tool call 才触发反思 +const REFLECT_MIN_DURATION = 60; // 或至少持续 N 秒 +const SHORT_TERM_MAX_AGE_DAYS = 7; // short-term 超过 N 天合并到 long-term + +/** + * 自动反思:分析对话结果,提取可复用的模式和教训 + * 无需额外 LLM 调用 — 纯规则提取 + * + * @param {string} agentId + * @param {string} convId + * @param {object} meta - { status, stats, createdAt, updatedAt, title } + * @param {string} output - Agent 最终输出 + * @returns {object|null} 反思结果 { patterns, lessons, plan } + */ +function autoReflect(agentId, convId, meta, output) { + try { + const toolCount = meta.stats?.toolCallCount || 0; + const createdAt = new Date(meta.createdAt); + const updatedAt = new Date(meta.updatedAt || Date.now()); + const durationSec = Math.round((updatedAt.getTime() - createdAt.getTime()) / 1000); + + // 判断是否值得反思 + if (toolCount < REFLECT_MIN_TOOLS && durationSec < REFLECT_MIN_DURATION) { + return null; // 太简单的对话不反思 + } + + const agentDir = path.join(DATA_DIR, agentId); + const task = extractTask(meta.title || '', agentId, convId); + const isSuccess = meta.status === 'completed'; + const isFailed = meta.status === 'failed'; + + const reflection = { + timestamp: new Date().toISOString(), + convId, + task: task.substring(0, 200), + status: meta.status, + toolCount, + durationSec, + patterns: [], + lessons: [], + plan: null, + }; + + // ── 提取模式 (成功对话) ── + if (isSuccess && toolCount >= 3) { + // 检测: 文件创建模式 + const createdFiles = extractMentionedFiles(output); + if (createdFiles.length > 0) { + reflection.patterns.push(`成功创建/修改了 ${createdFiles.length} 个文件: ${createdFiles.slice(0, 3).join(', ')}`); + } + + // 检测: 多步骤执行模式 + if (toolCount >= 5) { + reflection.patterns.push(`完成了 ${toolCount} 步工具调用的复杂任务 (${durationSec}秒)`); + } + + // 检测: dispatch 任务模式 + if (output.includes('dispatch') || output.includes('task/dispatch')) { + reflection.patterns.push('涉及向其他 Agent 分发子任务'); + } + + // 检测: 训练/进化模式 + if (output.includes('benchmark') || output.includes('score') || output.includes('evolve')) { + reflection.patterns.push('涉及技能训练/评分/进化流程'); + } + } + + // ── 提取教训 (失败对话) ── + if (isFailed) { + const errorMatch = output.match(/(?:error|错误|失败|Error)[::]\s*(.{10,200})/i); + if (errorMatch) { + reflection.lessons.push(`错误: ${errorMatch[1].trim()}`); + } + reflection.lessons.push(`任务失败 (${toolCount} tool calls, ${durationSec}秒): ${task.substring(0, 100)}`); + } + + // ── 自动固化方案 (成功 + 高复杂度) ── + if (isSuccess && toolCount >= 5) { + // 从任务和输出中提取关键词作为场景 + const keywords = extractKeywords(task); + const topKeywords = keywords.slice(0, 8); + + // 尝试从输出中提取步骤 + const steps = extractStepsFromOutput(output); + + if (steps.length >= 2 && topKeywords.length >= 2) { + const scenario = task.split('\n')[0].substring(0, 50); + + reflection.plan = { + scenario, + keywords: topKeywords, + steps, + confidence: Math.min(0.6 + (toolCount * 0.02), 0.9), // 工具越多,置信度越高 + }; + + // 自动保存到小脑 + saveCerebellumPlan(agentId, { + ...reflection.plan, + conditions: [`类似任务: ${scenario}`], + notes: [`自动从对话 ${convId} 提取`, `耗时 ${durationSec}秒, ${toolCount} 次工具调用`], + }); + } + } + + // ── 写入反思日志 ── + if (reflection.patterns.length > 0 || reflection.lessons.length > 0) { + writeReflectionLog(agentDir, reflection); + + // 更新 memory.md 的"已验证模式"和"失败教训"段 + updateMemoryMdSections(agentId, reflection); + + console.log(`[Memory] 🪞 反思完成: ${agentId} (${reflection.patterns.length} 模式, ${reflection.lessons.length} 教训${reflection.plan ? ', +1 方案固化' : ''})`); + } + + return reflection; + } catch (err) { + console.error(`[Memory] ⚠️ 反思失败:`, err.message); + return null; + } +} + +/** 从输出中提取步骤(通过数字列表匹配) */ +function extractStepsFromOutput(output) { + if (!output) return []; + // 匹配 "1. xxx" "2. xxx" 格式的步骤 + const stepMatches = output.match(/^\d+\.\s+.{5,100}$/gm) || []; + return stepMatches.slice(0, 8).map(s => s.replace(/^\d+\.\s+/, '').trim()); +} + +/** 写入反思日志文件 */ +function writeReflectionLog(agentDir, reflection) { + const logDir = path.join(agentDir, 'memory', 'reflections'); + if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true }); + + const filename = `reflect-${Date.now()}.json`; + fs.writeFileSync(path.join(logDir, filename), JSON.stringify(reflection, null, 2), 'utf-8'); + + // 只保留最近 20 个反思日志 + const files = fs.readdirSync(logDir).filter(f => f.startsWith('reflect-')).sort(); + while (files.length > 20) { + fs.unlinkSync(path.join(logDir, files.shift())); + } +} + +/** 更新 memory.md 的 "已验证模式" 和 "失败教训" 段 */ +function updateMemoryMdSections(agentId, reflection) { + const memoryPath = path.join(DATA_DIR, agentId, 'memory', 'memory.md'); + let content = ''; + try { content = fs.readFileSync(memoryPath, 'utf-8'); } catch { return; } + + const date = new Date().toISOString().substring(0, 10); + + // 更新"已验证的模式" + if (reflection.patterns.length > 0) { + const patternEntries = reflection.patterns.map(p => `- [${date}] ${p}`).join('\n'); + if (content.includes('## 已验证的模式')) { + content = content.replace( + /## 已验证的模式\n([\s\S]*?)(?=\n## |$)/, + (match, existing) => { + const trimmed = existing.trim(); + if (trimmed === '(尚无记录)') return `## 已验证的模式\n${patternEntries}\n`; + return `## 已验证的模式\n${trimmed}\n${patternEntries}\n`; + } + ); + } + } + + // 更新"失败教训" + if (reflection.lessons.length > 0) { + const lessonEntries = reflection.lessons.map(l => `- [${date}] ${l}`).join('\n'); + if (content.includes('## 失败教训')) { + content = content.replace( + /## 失败教训\n([\s\S]*?)(?=\n## |$)/, + (match, existing) => { + const trimmed = existing.trim(); + if (trimmed === '(尚无记录)') return `## 失败教训\n${lessonEntries}\n`; + return `## 失败教训\n${trimmed}\n${lessonEntries}\n`; + } + ); + } + } + + // 大小控制 + if (content.length > MAX_MEMORY_MD_SIZE) { + content = truncateMemory(content); + } + + fs.writeFileSync(memoryPath, content, 'utf-8'); +} + +// ════════════════════════════════════════ +// 7. Phase 3: 记忆合并 (Consolidate) +// ════════════════════════════════════════ + +/** + * 合并过期的 short-term 到 long-term + * 适合通过 CronCreate 每天凌晨调用 + * + * @param {string} agentId + * @returns {object} 合并统计 + */ +function consolidateMemory(agentId) { + try { + const agentDir = path.join(DATA_DIR, agentId); + const shortTermDir = path.join(agentDir, 'memory', 'short-term'); + const longTermDir = path.join(agentDir, 'memory', 'long-term'); + + if (!fs.existsSync(shortTermDir)) return { merged: 0 }; + if (!fs.existsSync(longTermDir)) fs.mkdirSync(longTermDir, { recursive: true }); + + const now = Date.now(); + const maxAge = SHORT_TERM_MAX_AGE_DAYS * 24 * 60 * 60 * 1000; + + const files = fs.readdirSync(shortTermDir) + .filter(f => f.startsWith('session-') && f.endsWith('.md')) + .sort(); + + // 找出过期文件 + const expired = files.filter(f => { + const ts = parseInt(f.replace('session-', '').replace('.md', '')); + return !isNaN(ts) && (now - ts) > maxAge; + }); + + if (expired.length === 0) return { merged: 0 }; + + // 读取所有过期文件内容 + const summaries = expired.map(f => { + const content = fs.readFileSync(path.join(shortTermDir, f), 'utf-8'); + return compactSession(content); + }); + + // 提取反复出现的关键词 (简单频率统计) + const allKeywords = []; + for (const s of summaries) { + allKeywords.push(...extractKeywords(s)); + } + const kwFreq = {}; + allKeywords.forEach(kw => { kwFreq[kw] = (kwFreq[kw] || 0) + 1; }); + const frequentKW = Object.entries(kwFreq) + .filter(([_, count]) => count >= 2) + .sort((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([kw, count]) => `${kw} (x${count})`); + + // 写入 long-term 合并记录 + const consolidateDate = new Date().toISOString().substring(0, 10); + const ltContent = [ + `# 长期记忆合并 — ${consolidateDate}`, + '', + `> 合并了 ${expired.length} 个过期 session (>${SHORT_TERM_MAX_AGE_DAYS} 天)`, + '', + frequentKW.length > 0 ? `## 高频关键词\n${frequentKW.map(k => `- ${k}`).join('\n')}` : '', + '', + '## 合并的对话摘要', + '', + ...summaries, + ].filter(Boolean).join('\n'); + + const ltFilename = `consolidate-${consolidateDate}.md`; + fs.writeFileSync(path.join(longTermDir, ltFilename), ltContent, 'utf-8'); + + // 更新 long-term/patterns.md (追加高频模式) + if (frequentKW.length > 0) { + const patternsPath = path.join(longTermDir, 'patterns.md'); + let patterns = ''; + try { patterns = fs.readFileSync(patternsPath, 'utf-8'); } catch {} + if (!patterns) patterns = '# 长期模式\n\n> 从 short-term 多次出现的模式沉淀而来\n\n'; + patterns += `\n## ${consolidateDate}\n${frequentKW.map(k => `- ${k}`).join('\n')}\n`; + fs.writeFileSync(patternsPath, patterns, 'utf-8'); + } + + // 删除已合并的 short-term 文件 + for (const f of expired) { + fs.unlinkSync(path.join(shortTermDir, f)); + } + + console.log(`[Memory] 📦 记忆合并: ${agentId} (${expired.length} sessions → long-term/${ltFilename})`); + return { merged: expired.length, file: ltFilename, keywords: frequentKW }; + } catch (err) { + console.error(`[Memory] ⚠️ 记忆合并失败:`, err.message); + return { merged: 0, error: err.message }; + } +} + +// ════════════════════════════════════════ +// 8. Phase 3: 日报生成 (Daily Report) +// ════════════════════════════════════════ + +/** + * 生成当天的日报摘要 + * + * @param {string} agentId + * @returns {string|null} 日报文件路径 + */ +function generateDailyReport(agentId) { + try { + const agentDir = path.join(DATA_DIR, agentId); + const shortTermDir = path.join(agentDir, 'memory', 'short-term'); + const dailyDir = path.join(agentDir, 'memory', 'daily'); + const reflectDir = path.join(agentDir, 'memory', 'reflections'); + + if (!fs.existsSync(dailyDir)) fs.mkdirSync(dailyDir, { recursive: true }); + + const today = new Date().toISOString().substring(0, 10); + + // 收集今天的 session 摘要 + const todaySessions = []; + if (fs.existsSync(shortTermDir)) { + const files = fs.readdirSync(shortTermDir).filter(f => f.startsWith('session-')); + for (const f of files) { + const content = fs.readFileSync(path.join(shortTermDir, f), 'utf-8'); + if (content.includes(today)) { + todaySessions.push(compactSession(content)); + } + } + } + + // 收集今天的反思 + const todayReflections = []; + if (fs.existsSync(reflectDir)) { + const files = fs.readdirSync(reflectDir).filter(f => f.startsWith('reflect-')); + for (const f of files) { + try { + const r = JSON.parse(fs.readFileSync(path.join(reflectDir, f), 'utf-8')); + if (r.timestamp && r.timestamp.startsWith(today)) { + todayReflections.push(r); + } + } catch {} + } + } + + if (todaySessions.length === 0 && todayReflections.length === 0) { + return null; // 今天没活动 + } + + // 统计 + const totalPatterns = todayReflections.reduce((sum, r) => sum + (r.patterns?.length || 0), 0); + const totalLessons = todayReflections.reduce((sum, r) => sum + (r.lessons?.length || 0), 0); + const totalPlans = todayReflections.filter(r => r.plan).length; + + const report = [ + `# 日报 — ${today}`, + '', + `## 概览`, + `- 对话数: ${todaySessions.length}`, + `- 反思数: ${todayReflections.length}`, + `- 新模式: ${totalPatterns}`, + `- 新教训: ${totalLessons}`, + `- 固化方案: ${totalPlans}`, + '', + ]; + + if (todaySessions.length > 0) { + report.push('## 对话记录', '', ...todaySessions); + } + + if (todayReflections.length > 0) { + report.push('## 反思摘要', ''); + for (const r of todayReflections) { + if (r.patterns?.length) report.push(...r.patterns.map(p => `- ✅ ${p}`)); + if (r.lessons?.length) report.push(...r.lessons.map(l => `- ❌ ${l}`)); + } + report.push(''); + } + + const reportPath = path.join(dailyDir, `${today}.md`); + fs.writeFileSync(reportPath, report.join('\n'), 'utf-8'); + + console.log(`[Memory] 📰 日报已生成: ${agentId}/daily/${today}.md`); + return reportPath; + } catch (err) { + console.error(`[Memory] ⚠️ 日报生成失败:`, err.message); + return null; + } +} + module.exports = { // Phase 1 saveSessionSummary, @@ -613,6 +993,10 @@ module.exports = { retrieveRelevantPlans, saveCerebellumPlan, extractKeywords, + // Phase 3 + autoReflect, + consolidateMemory, + generateDailyReport, // 内部 (测试用) loadHippocampusIndex, saveHippocampusIndex,