feat(memory): M3 recall 回忆工具——更早日记翻页 + 旧会话成果文件定位/取件

用户拍板 B 方案(极简 tool,不走 skill:执行器沙箱跨不了会话目录,回连 core 反而重)。
日记存储本就永久(上一版定稿),本工具把「查得到」补齐——开场注入只是嘴边的,回忆才是全部:

- op=list:翻开场注入窗之外的更早碎片(memory.olderFragments 与 journalFor 同展开序,
  默认跳过注入窗,skip/count 翻页,尾部如实标注剩余条数与续翻参数;
  越界/空态给友好文案引导 op=files)。
- op=files:按日记碎片里的会话 id 现查那次会话任务目录的顶层成果文件——
  按磁盘实况列出,天然完成存在性判定(文件被删/目录已清都有交代);
  同用户校验防互探,id 形态白名单校验。
- op=link:对清单里的文件产临时下载外链(复用 mint_public_link 同机制同 public_link 配置,
  resolveInTask 沙箱限该会话目录内,嵌套路径可取,穿越拒绝)——微信端发链接即交付,
  网页端浏览器直下。
- advisor 白名单加 recall(config.js):顾问只聊和读,翻日记查旧成果正属其分内;
  开场日记头行同步改为指路 recall 三 op(AI 自然知道怎么下钻)。

探针 13 项全过(跳窗/翻页/尾页标注/越界/文件列出过滤 dot 与目录/外链格式/嵌套/穿越拒绝/
跨用户拒绝/不存在报错/空用户友好),临时目录探针自清。
This commit is contained in:
2026-09-29 12:30:20 +08:00
parent 2369471ed5
commit ff2f153db0
4 changed files with 133 additions and 7 deletions
+4 -3
View File
@@ -108,11 +108,12 @@ const DEFAULTS = {
// 模型 profile(prompt + tools 名单组合):platforms 里的模型用 profile: <名> 引用。
model_profiles: {
// advising:顾问阶段(sessions.phase)专用组合——不由模型配置引用,而是 resolveProfileName 在
// advising 时强制命中:顾问只聊和读、不写(write_file 已移除,批内幻觉调用另由引擎挡下),
// 例外是 profile(画像元信息,不碰任务目录;顾问问答恰是收集称谓/偏好密度最高的时刻);
// advising 时强制命中:顾问只聊和读、不写(write_file 已移除,批内幻觉调用另由引擎挡下),
// 例外是 profile(画像元信息,不碰任务目录;顾问问答恰是收集称谓/偏好密度最高的时刻)
// 与 recall(日记只读翻阅;用户和顾问聊「上次那个事」恰是回忆查询的高峰场景);
// 唯一出口是 handoff;tools_deny 必须显式清空:不配 = 继承全局 ['lab','handoff'],
// allow 滤完再叠 deny 会把 handoff 自己禁掉(同 lab 组合的教训)。
advising: { tools_allow: ['read_file', 'fetch', 'handoff', 'profile'], tools_deny: [], system_prompt_file: 'advising-system.txt' },
advising: { tools_allow: ['read_file', 'fetch', 'handoff', 'profile', 'recall'], tools_deny: [], system_prompt_file: 'advising-system.txt' },
// lab:统一入口元工具自测组合——tools 收缩到 1 个,其余能力经 lab(help) 现场发现。
// tools_deny 必须显式清空:不配 = 继承全局 ['lab'],deny 后叠加会把 lab 自己禁掉 → 零工具。
lab: { tools_allow: ['lab'], tools_deny: [], system_prompt_file: 'lab-system.txt' },
+29 -4
View File
@@ -6,8 +6,8 @@
// - 存储默认永久:会话收口(4h 空闲 / 设定定时任务)= 一条几十字的第一人称碎片,按【收口当日】
// 入 (user, day) 条目;同日多片按到达顺序拼接,不做 LLM 二次合并(确定性、零成本)——
// 虚拟人的过去不能到点就抹,「只记 7 天」会把人做成金鱼;
// - 注入 =「嘴上的工作记忆」:新会话开场只带最近 inject_max 条碎片(默认 10),更早的记忆
// 不自动出现但也没消失——等 M3 回忆工具按会话 id 下钻;
// - 注入 =「嘴上的工作记忆」:新会话开场只带最近 inject_max 条碎片(默认 10);更早的记忆
// 不自动出现但也没消失——recall 工具按会话 id 下钻(op=list 翻旧条目 / files/link 查成果文件);
// - retain_days > 0 才按天硬裁(默认 0 = 永不删除),留给确要自动清理/隐私抹除的场景。
// - sid 去重:同一会话只贡献一条碎片(防收口竞态双写;主闸是 sessions.journaled_at 物理占坑,
// 这里是末道防线)。
@@ -87,12 +87,37 @@ function journalFor(db, cfg, user) {
groups[groups.length - 1].frags.unshift(p.frag);
}
const head = '【长期记忆·日记(最近' + picked.length + '条)】收工时的当日事件摘要,近日的在前、天内按发生顺序;'
+ '每条【编号】是来源会话 id,可用于回溯那次工作的对话与成果。';
+ '每条【编号】是来源会话 id:更早的日记用 recall 工具 op=list 翻,那次工作的成果文件用 op=files 查、op=link 取。';
const parts = [head];
for (const g of groups) parts.push('=== ' + g.day + ' ===\n' + g.frags.join('\n\n'));
return parts.join('\n\n');
}
// ---------- 读:回忆更早碎片(recall 工具 op=list 的数据源) ----------
// 与 journalFor 同展开顺序(全局新在前);skip 默认跳过开场注入窗,count 默认 20 上限 50。
// 尾部标注剩余更早条数与续翻参数,AI 读完自然知道怎么翻页。
function olderFragments(db, cfg, user, skip, count) {
const rows = db.prepare('SELECT day, content FROM memory_entries WHERE user = ? ORDER BY day DESC').all(String(user || ''));
const flat = [];
for (const r of rows) {
const frags = String(r.content || '').split('\n\n').filter(Boolean);
for (let i = frags.length - 1; i >= 0; i--) flat.push({ day: r.day, frag: frags[i] });
}
const skipN = Number.isFinite(Number(skip)) ? Math.max(0, Math.floor(Number(skip))) : injectMax(cfg);
const lim = Math.max(1, Math.min(50, Number(count) || 20));
const page = flat.slice(skipN, skipN + lim);
if (!page.length) return '';
const groups = [];
for (const p of page) {
if (!groups.length || groups[groups.length - 1].day !== p.day) groups.push({ day: p.day, frags: [] });
groups[groups.length - 1].frags.unshift(p.frag);
}
const rest = flat.length - skipN - page.length;
const parts = ['【更早的日记】第 ' + (skipN + 1) + ' 条起共 ' + page.length + ' 条' + (rest > 0 ? ',继续翻:skip=' + (skipN + page.length) : ',这已是全部记忆')];
for (const g of groups) parts.push('=== ' + g.day + ' ===\n' + g.frags.join('\n\n'));
return parts.join('\n\n');
}
// ---------- 裁剪:day 为 ISO 串,字典序即日期序;默认永久存储为 no-op ----------
function prune(db, cfg) {
const cutoff = cutoffDay(cfg);
@@ -103,6 +128,6 @@ function prune(db, cfg) {
module.exports = {
retainDays, injectMax, dayString, cutoffDay,
appendFragment, markJournaled, journalFor, prune,
appendFragment, markJournaled, journalFor, olderFragments, prune,
INJECT_CAP, DAY_MAX, FRAG_MAX,
};
+40
View File
@@ -231,6 +231,46 @@
}
}
},
{
"type": "function",
"function": {
"name": "recall",
"description": "Access your long-term memory: the work diary. Each finished session leaves one short fragment (a few dozen characters, headed by the source session id), stored permanently; only the newest fragments were injected at session start. Read-only.\n\nop=list Older diary fragments beyond the injected window. Optional: skip (default = skip the injected window), count (default 20, max 50).\nop=files List files of a past session that still exist on disk right now. Requires id (the session id from a diary fragment's 【…】 heading).\nop=link Mint a temporary download link for one of those files. Requires id and path (a name from op=files).",
"parameters": {
"type": "object",
"required": [
"op"
],
"properties": {
"op": {
"type": "string",
"enum": [
"list",
"files",
"link"
],
"description": "What to recall: list = older diary fragments; files = a past session's current artifacts; link = a download link for one of them."
},
"skip": {
"type": "integer",
"description": "op=list: how many newest fragments to skip. Default = the window already injected at session start."
},
"count": {
"type": "integer",
"description": "op=list: fragments to return (default 20, max 50)."
},
"id": {
"type": "string",
"description": "op=files / op=link: the source session id as written inside a diary fragment's 【…】 heading (e.g. 'task-20260929-003')."
},
"path": {
"type": "string",
"description": "op=link: file name inside that session's task directory, exactly as listed by op=files."
}
}
}
}
},
{
"type": "function",
"function": {
+60
View File
@@ -11,6 +11,7 @@ const rexec = require('../remote-exec');
const publicFiles = require('../public-files');
const scheduler = require('../scheduler'); // 只依赖 log/cron-parser,不成环(engine→executor→scheduler 单向)
const profile = require('../user-profile'); // profile 工具的数据面(仅 llm/log 依赖,无环)
const memory = require('../memory'); // recall 工具的数据面(日记翻阅;零依赖模块,无环)
// lab 的 help 伪工具要读全量定义:与 engine 同路径 require → node 缓存同一对象,单一事实源。
const BUILTIN_TOOL_DEFS = require('./definitions.json');
@@ -1188,6 +1189,64 @@ async function toolHandoff(ctx, args) {
return '已接收交接(reason: ' + reason + '),本批工具跑完后系统将切换到执行阶段。';
}
// recall:长期记忆(工作日记)的回忆入口(定稿 B 方案:极简三 op,描述短不挤占工具位)。
// 日记按会话收口持久存储(memory.js),开场只注入最近 N 条;更早的条目与某次工作的成果文件由本工具按需取。
// 只读数据面:仅能碰本用户的日记与会话(id 同用户校验防互探);link 产出的外链与 mint_public_link 同机制同时效。
function toolRecall(ctx, args) {
const op = String(args.op || '').trim().toLowerCase();
const db = ctx.db;
const me = db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId);
const user = String((me && me.user) || '');
// files/link 共用:解析并校验目标会话(存在 + 同用户 + id 形态),返回 {sid, title, dir}
const resolveSession = () => {
const sid = String(args.id || '').trim();
if (!/^task-[0-9A-Za-z_\-]+$/.test(sid)) throw new Error('需要 id:日记碎片【编号】里的会话 id(形如 task-YYYYMMDD-NNN)');
const s = db.prepare('SELECT id, user, title FROM sessions WHERE id = ?').get(sid);
if (!s) throw new Error('会话 ' + sid + ' 不存在(可能已删除)');
if (String(s.user || '') !== user) throw new Error('无权访问该会话(非当前用户)');
const root = String((ctx.cfg && ctx.cfg.workspace_root) || '');
if (!root) throw new Error('workspace_root 未配置');
return { sid: sid, title: s.title || sid, dir: path.join(root, sid) };
};
switch (op) {
case 'list': {
const txt = memory.olderFragments(db, ctx.cfg, user, args.skip, args.count);
return txt || '更早的日记没有了:开场注入的就是全部记忆。需要某次工作的成果文件用 op=files。';
}
case 'files': {
const t = resolveSession();
let names = [];
try {
names = fs.readdirSync(t.dir, { withFileTypes: true })
.filter(d => d.isFile() && !d.name.startsWith('.'))
.map(d => d.name)
.sort();
} catch (_) {
return '会话「' + t.title + '」的任务目录不存在(已删或未产出),无成果文件。';
}
if (!names.length) return '会话「' + t.title + '」没有成果文件。';
const shown = names.slice(0, 80);
return '会话「' + t.title + '」当前存在的文件(' + shown.length + (names.length > shown.length ? '/共 ' + names.length : '') + ' 个):\n'
+ shown.map(n => '- ' + n).join('\n')
+ '\n(按磁盘实况列出:存在即未被删;取内容用 op=link {id, path})';
}
case 'link': {
const t = resolveSession();
const rel = String(args.path || '').trim();
if (!rel) throw new Error('op=link 需要 path(op=files 清单里的文件名)');
const abs = resolveInTask(t.dir, rel); // 路径沙箱:只允许该会话任务目录内
let st;
try { st = fs.statSync(abs); } catch (_) { throw new Error('文件不存在:' + rel + '(先 op=files 看现存清单)'); }
if (!st.isFile()) throw new Error('不是普通文件:' + rel);
const pl = ctx.cfg && ctx.cfg.public_link;
if (!pl || !pl.base_url) throw new Error('public_link 未配置,无法生成外链');
return pl.base_url + '/p/' + publicFiles.mint({ sessionId: t.sid, rel: rel, ttlMs: pl.ttl_ms });
}
default:
throw new Error('未知的 op:"' + op + '"。可用:list(翻更早日记,可选 skip/count)/ files(需 id,列那次会话现存成果文件)/ link(需 id+path,产临时下载链接)');
}
}
const HANDLERS = {
read_file: toolReadFile,
handoff: toolHandoff,
@@ -1198,6 +1257,7 @@ const HANDLERS = {
fetch: toolFetch,
schedule: toolScheduleTask,
profile: toolProfile,
recall: toolRecall,
db: toolDb,
skill: toolSkill,
lab: toolLab,