dsh-sixlayer-memory 0.0.0-stage → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/README.md +292 -3
  3. package/catalog/.index.json +111704 -0
  4. package/catalog/parts.json +8808 -0
  5. package/cordis.patch.yml +8 -0
  6. package/docs/DETAIL.md +1 -0
  7. package/docs/DETAIL.zh.md +1 -0
  8. package/docs/preview.svg +51 -0
  9. package/docs//347/224/237/345/221/275/345/221/250/346/234/237-/350/207/252/345/212/250/345/217/254/345/233/236/344/270/216/345/200/231/351/200/211.md +103 -0
  10. package/icon.svg +8 -0
  11. package/lib/client.js +1209 -0
  12. package/lib/index.js +741 -0
  13. package/lib/memory/affect-alert.js +60 -0
  14. package/lib/memory/affect-events.js +201 -0
  15. package/lib/memory/affect-report.js +61 -0
  16. package/lib/memory/api.js +194 -0
  17. package/lib/memory/crypto.js +68 -0
  18. package/lib/memory/detail.js +43 -0
  19. package/lib/memory/embed.js +394 -0
  20. package/lib/memory/emotion.js +99 -0
  21. package/lib/memory/explain.js +207 -0
  22. package/lib/memory/importer.js +215 -0
  23. package/lib/memory/inject.js +193 -0
  24. package/lib/memory/ledger.js +101 -0
  25. package/lib/memory/lifecycle.js +491 -0
  26. package/lib/memory/notify.js +164 -0
  27. package/lib/memory/policy.js +182 -0
  28. package/lib/memory/qq-official.js +196 -0
  29. package/lib/memory/qq.js +326 -0
  30. package/lib/memory/recorder.js +241 -0
  31. package/lib/memory/redact.js +120 -0
  32. package/lib/memory/scanners.js +142 -0
  33. package/lib/memory/schema.js +205 -0
  34. package/lib/memory/service-plugin.js +69 -0
  35. package/lib/memory/service.js +123 -0
  36. package/lib/memory/shadow.js +133 -0
  37. package/lib/memory/store.js +1138 -0
  38. package/lib/memory/timeline.js +74 -0
  39. package/lib/memory/tokenize.js +66 -0
  40. package/lib/memory/tools.js +1371 -0
  41. package/lib/memory/util.js +129 -0
  42. package/lib/parts/index.js +154 -0
  43. package/lib/parts/installer.js +294 -0
  44. package/lib/parts/jobs.js +91 -0
  45. package/lib/parts/library.js +91 -0
  46. package/lib/probe-plugin.js +38 -0
  47. package/lib/voice/board-asr.js +31 -0
  48. package/locale/en.json +7 -0
  49. package/locale/zh.json +7 -0
  50. package/package.json +114 -3
  51. package/tools/backfill-affect.mjs +82 -0
  52. package/tools/eval.mjs +88 -0
  53. package/tools/p1.mjs +108 -0
  54. package/tools/p10.mjs +36 -0
  55. package/tools/p11.mjs +51 -0
  56. package/tools/p12.mjs +53 -0
  57. package/tools/p13.mjs +65 -0
  58. package/tools/p14.mjs +66 -0
  59. package/tools/p15.mjs +43 -0
  60. package/tools/p16.mjs +42 -0
  61. package/tools/p17.mjs +29 -0
  62. package/tools/p18.mjs +48 -0
  63. package/tools/p19.mjs +50 -0
  64. package/tools/p2.mjs +59 -0
  65. package/tools/p20.mjs +54 -0
  66. package/tools/p21.mjs +42 -0
  67. package/tools/p22.mjs +32 -0
  68. package/tools/p23.mjs +43 -0
  69. package/tools/p24.mjs +40 -0
  70. package/tools/p25.mjs +151 -0
  71. package/tools/p26.mjs +113 -0
  72. package/tools/p27.mjs +89 -0
  73. package/tools/p28.mjs +60 -0
  74. package/tools/p3.mjs +54 -0
  75. package/tools/p4.mjs +73 -0
  76. package/tools/p5.mjs +117 -0
  77. package/tools/p6.mjs +122 -0
  78. package/tools/p8.mjs +50 -0
  79. package/tools/p9.mjs +35 -0
  80. package/tools/phase2.mjs +159 -0
  81. package/tools/preflight.mjs +320 -0
  82. package/tools/push-via-api.mjs +187 -0
  83. package/tools/quarterly.mjs +129 -0
  84. package/tools/refresh-catalog.mjs +60 -0
  85. package/tools/register-bundle.mjs +38 -0
  86. package/tools/review.mjs +156 -0
  87. package/tools/selfcheck.mjs +80 -0
  88. package/tools/smoke.mjs +112 -0
  89. package/tools/testset-v1.json +70 -0
  90. package/tools/validate-tools.mjs +150 -0
  91. package/tools/verify-all.mjs +39 -0
  92. package/tools/write-chain.mjs +139 -0
@@ -0,0 +1,1371 @@
1
+ /**
2
+ * tools.js — 工具定义(手写 JSON Schema,不 import 任何 @deepseek-ai 包)。
3
+ *
4
+ * 为什么手写:这个插件以 file:// 方式加载,目录里没有 node_modules,
5
+ * 运行期解析不到 @deepseek-ai/dsh-tools。registry 只要求
6
+ * { name, description, parameters(JSON Schema), output:{schema,render}, execute },
7
+ * 所以手写形状与 defineTool 的产物等价,同时把依赖降到零。
8
+ */
9
+ import { canWrite } from './policy.js'
10
+ import { explainRecord } from './explain.js'
11
+ import { listParts, compose } from '../parts/index.js'
12
+ import { ingestQqSessions, affectReport } from './affect-events.js'
13
+ import { ledgerInit, ledgerSync, ledgerVerify, healthLine } from './ledger.js'
14
+ import { saveAffectReport } from './affect-report.js'
15
+
16
+ const textOut = (extra = {}) => ({
17
+ type: 'object',
18
+ additionalProperties: false,
19
+ properties: { text: { type: 'string' }, ...extra },
20
+ required: ['text'],
21
+ })
22
+
23
+ const renderText = (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }]
24
+
25
+ /** 所有工具的注册表:name → { label, argsHint, needsOpen, build(store, host) } */
26
+ export function buildRegistry(store, host) {
27
+ /** @type {Map<string, {label:string, argsHint:string, needsOpen:boolean, definition:object}>} */
28
+ const registry = new Map()
29
+
30
+ const add = (definition, meta) => {
31
+ registry.set(definition.name, { ready: true, ...meta, definition })
32
+ }
33
+
34
+ // ---------- 常驻:能力目录 ----------
35
+
36
+ add(
37
+ {
38
+ name: 'mem_admin_catalog',
39
+ description:
40
+ '六层记忆底座的能力目录。返回:四个服务(storage/search/graph/crypto)的可用状态、可注入工具清单(含一行描述与调用签名)、' +
41
+ '当前已注入的工具、权威源开关(legacy/shadow/new)与库统计。默认只常驻这一个工具,其他工具用 mem_admin_open 按需注入。',
42
+ parameters: {
43
+ type: 'object',
44
+ additionalProperties: false,
45
+ properties: {
46
+ include_signatures: { type: 'boolean', description: '是否返回每个工具的参数签名(默认 true)' },
47
+ },
48
+ },
49
+ output: {
50
+ schema: textOut({
51
+ authority: { type: 'string' },
52
+ services: { type: 'object', additionalProperties: true },
53
+ tools: { type: 'array', items: { type: 'object', additionalProperties: true } },
54
+ injected: { type: 'array', items: { type: 'string' } },
55
+ stats: { type: 'object', additionalProperties: true },
56
+ }),
57
+ render: renderText,
58
+ },
59
+ isConcurrencySafe: () => true,
60
+ execute: async (args) => {
61
+ const withSignatures = args?.include_signatures !== false
62
+ const stats = store.stats()
63
+ const injected = host.injected()
64
+ const services = {
65
+ storage: { ready: true, required: true, detail: 'node:sqlite 内置,schema v3' },
66
+ search: { ready: true, optional: true, detail: 'FTS5 + bigram 分词;向量路在三期' },
67
+ audit: { ready: stats.audit?.ok !== false, required: true, detail: `JSONL 哈希链 ${stats.audit?.lines ?? 0} 行` },
68
+ graph: { ready: true, optional: true, detail: '标签/同批次共现图,BFS 查询(v9)' },
69
+ crypto: { ready: true, optional: true, detail: 'AES-256-GCM 静态加密(默认关,mem_crypto 开)' },
70
+ }
71
+ const tools = [...registry.entries()].map(([name, item]) => {
72
+ const row = {
73
+ name,
74
+ label: item.label,
75
+ injected: injected.includes(name),
76
+ ready: item.ready !== false,
77
+ }
78
+ if (withSignatures) row.signature = item.argsHint
79
+ return row
80
+ })
81
+
82
+ const lines = [
83
+ `权威源开关 authority = ${stats.authority}(legacy=只走旧源 / shadow=新旧并读 / new=新库为准)`,
84
+ `库:${stats.records} 条记录(active ${stats.active},quarantined ${stats.quarantined},S 级 ${stats.sLevel}),FTS ${stats.fts} 行,schema v${stats.schemaVersion}`,
85
+ `数据目录:${stats.dataDir}`,
86
+ `记录仪:${stats.audit?.ok === false ? '⚠ 断链' : '链一致'} / ${stats.audit?.lines ?? 0} 行 / ${stats.audit?.files ?? 0} 个文件`,
87
+ `导入:legacy_import ${stats.legacy ?? 0} 条 traces ${stats.traces ?? 0} 条`,
88
+ '服务:' + Object.entries(services).map(([k, v]) => `${k}=${v.ready ? 'ready' : 'degraded'}`).join(' '),
89
+ `已注入:${injected.length ? injected.join(', ') : '(无,只有本目录)'}`,
90
+ '可注入工具:',
91
+ ...tools.map((t) => ` - ${t.name}(${t.label})${t.injected ? ' [已注入]' : ''}${t.signature ? `\n ${t.signature}` : ''}`),
92
+ '用法:mem_admin_open({ tools: ["mem_search","mem_read"] }) 注入;mem_admin_call({ tool, arguments }) 单次调用。',
93
+ ]
94
+
95
+ return { text: lines.join('\n'), authority: stats.authority, services, tools, injected, stats }
96
+ },
97
+ },
98
+ { label: '能力目录', argsHint: 'mem_admin_catalog({ include_signatures?: boolean })', needsOpen: false },
99
+ )
100
+
101
+ // ---------- 常驻:按需注入 ----------
102
+
103
+ add(
104
+ {
105
+ name: 'mem_admin_open',
106
+ description:
107
+ '把指定工具注册进当前会话(按需注入)。空列表或缺失列表会被拒绝 —— 不默认全开。' +
108
+ '已注入的工具在会话结束或插件卸载时自动清理。',
109
+ parameters: {
110
+ type: 'object',
111
+ additionalProperties: false,
112
+ properties: {
113
+ tools: { type: 'array', items: { type: 'string' }, description: '要注入的工具名列表,至少一个' },
114
+ },
115
+ required: ['tools'],
116
+ },
117
+ output: { schema: textOut({ injected: { type: 'array', items: { type: 'string' } } }), render: renderText },
118
+ isConcurrencySafe: () => false,
119
+ execute: async (args) => {
120
+ const names = Array.isArray(args?.tools) ? args.tools.filter((n) => typeof n === 'string' && n.trim()) : []
121
+ if (names.length === 0) throw new Error('mem_admin_open: tools 不能为空(不默认全开)')
122
+ const unknown = names.filter((n) => !registry.has(n))
123
+ if (unknown.length) throw new Error(`mem_admin_open: 未知工具 ${unknown.join(', ')}`)
124
+ const skip = names.filter((n) => n === 'mem_admin_catalog')
125
+ const injected = host.open(names.filter((n) => n !== 'mem_admin_catalog'))
126
+ const lines = [`已注入 ${injected.length} 个工具:${injected.join(', ') || '(无)'}`]
127
+ if (skip.length) lines.push('提示:mem_admin_catalog 常驻,无需注入。')
128
+ return { text: lines.join('\n'), injected }
129
+ },
130
+ },
131
+ { label: '按需注入', argsHint: 'mem_admin_open({ tools: string[] })', needsOpen: false },
132
+ )
133
+
134
+ add(
135
+ {
136
+ name: 'mem_admin_call',
137
+ description: '单次直接调用一个工具,不把它注册为常驻工具。用于一次性操作。',
138
+ parameters: {
139
+ type: 'object',
140
+ additionalProperties: false,
141
+ properties: {
142
+ tool: { type: 'string', description: '工具名,例如 mem_search' },
143
+ arguments: { type: 'object', additionalProperties: true, description: '该工具的参数对象' },
144
+ },
145
+ required: ['tool'],
146
+ },
147
+ output: { schema: textOut({ tool: { type: 'string' }, result: { type: 'object', additionalProperties: true } }), render: renderText },
148
+ isConcurrencySafe: () => false,
149
+ execute: async (args) => {
150
+ const name = String(args?.tool ?? '').trim()
151
+ const item = registry.get(name)
152
+ if (!item) throw new Error(`mem_admin_call: 未知工具 ${name}`)
153
+ const value = await item.definition.execute(args?.arguments ?? {})
154
+ return { text: String(value?.text ?? ''), tool: name, result: value ?? {} }
155
+ },
156
+ },
157
+ { label: '单次调用', argsHint: 'mem_admin_call({ tool: string, arguments?: object })', needsOpen: false },
158
+ )
159
+
160
+ // ---------- 可注入:写入 ----------
161
+
162
+ add(
163
+ {
164
+ name: 'mem_write',
165
+ description:
166
+ '写入一条记忆。走完整写入链:通道×身份信任判定 → 投毒/凭证扫描 → 沉淀前决策(低价值不落库)→ S/A 分级 → 内容去重 → 冲突与疑似矛盾标记 → 落库。' +
167
+ '凭证类判 S 级(不进自动召回);命中投毒特征进隔离区;与既有记录疑似矛盾则进待审区。',
168
+ parameters: {
169
+ type: 'object',
170
+ additionalProperties: false,
171
+ properties: {
172
+ content: { type: 'string', description: '正文(必填,≤200k 字符)' },
173
+ layer: { type: 'string', enum: ['L0', 'L1', 'L2', 'L3', 'L4', 'L5'], description: '层,默认 L2' },
174
+ summary: { type: 'string', description: '一行摘要;缺省取正文前 120 字' },
175
+ source_channel: { type: 'string', description: '来源通道:user / host / tool / web / mcp / import / legacy_import' },
176
+ identity_id: { type: 'string', description: '调用方身份:owner / agent / unknown(缺省 agent)' },
177
+ trust_level: { type: 'string', enum: ['trusted', 'unverified', 'tainted'], description: '覆盖默认信任级(默认由通道×身份决定)' },
178
+ sad_level: { type: 'string', enum: ['S', 'A', 'D'], description: '覆盖默认分级(默认凭证→S,其余 A)' },
179
+ principal_id: { type: 'string' },
180
+ project_id: { type: 'string' },
181
+ session_id: { type: 'string' },
182
+ tags: { type: 'array', items: { type: 'string' } },
183
+ },
184
+ required: ['content'],
185
+ },
186
+ output: {
187
+ schema: textOut({
188
+ record_id: { type: 'string' },
189
+ dedup: { type: 'boolean' },
190
+ skipped: { type: 'boolean' },
191
+ reason: { type: 'string' },
192
+ layer: { type: 'string' },
193
+ sad_level: { type: 'string' },
194
+ trust_level: { type: 'string' },
195
+ status: { type: 'string' },
196
+ conflict: { type: 'boolean' },
197
+ conflict_of: { type: 'string' },
198
+ contradiction: { type: 'boolean' },
199
+ scanned: { type: 'array', items: { type: 'string' } },
200
+ }),
201
+ render: renderText,
202
+ },
203
+ isConcurrencySafe: () => false,
204
+ execute: async (args) => {
205
+ const r = store.write({
206
+ content: args?.content,
207
+ layer: args?.layer,
208
+ summary: args?.summary,
209
+ sourceChannel: args?.source_channel,
210
+ identityId: args?.identity_id,
211
+ trustLevel: args?.trust_level,
212
+ sadLevel: args?.sad_level,
213
+ principalId: args?.principal_id,
214
+ projectId: args?.project_id,
215
+ sessionId: args?.session_id,
216
+ tags: args?.tags,
217
+ origin: 'manual',
218
+ explicit: true,
219
+ })
220
+
221
+ const lines = []
222
+ if (r.skipped) {
223
+ lines.push(`未落库(沉淀前决策):${r.reason}`)
224
+ } else if (r.dedup) {
225
+ lines.push(`已存在相同内容,未重复写入:${r.record_id}`)
226
+ } else {
227
+ lines.push(`已写入 ${r.record_id}`)
228
+ }
229
+ lines.push(`层 ${r.layer} / 分级 ${r.sad_level} / 信任 ${r.trust_level} / 状态 ${r.status}`)
230
+ lines.push(r.scanned?.length ? `扫描命中:${r.scanned.join(', ')}` : '扫描无命中')
231
+ if (r.conflict) lines.push(`与既有记录主题重叠:${r.conflict_of}(已并存,未覆盖)`)
232
+ if (r.contradiction) lines.push('疑似与既有记录结论相反:已进待审区,需 mem_review 审核后才参与召回')
233
+
234
+ return {
235
+ text: lines.join('\n'),
236
+ record_id: r.record_id ?? '',
237
+ dedup: r.dedup,
238
+ skipped: r.skipped,
239
+ reason: r.reason ?? '',
240
+ layer: r.layer,
241
+ sad_level: r.sad_level,
242
+ trust_level: r.trust_level,
243
+ status: r.status,
244
+ conflict: r.conflict,
245
+ conflict_of: r.conflict_of ?? '',
246
+ contradiction: r.contradiction,
247
+ scanned: r.scanned ?? [],
248
+ }
249
+ },
250
+ },
251
+ { label: '写入记忆', argsHint: 'mem_write({ content, layer?, identity_id?, source_channel?, ... })', needsOpen: true },
252
+ )
253
+
254
+ // ---------- 可注入:检索 ----------
255
+
256
+ add(
257
+ {
258
+ name: 'mem_search',
259
+ description:
260
+ '三路混合检索的一期版本:BM25(FTS5 + 中文 bigram 分词)。无命中返回空数组,不注入任何说明性文字。' +
261
+ '默认只返回 active 且非 S 级的记录。',
262
+ parameters: {
263
+ type: 'object',
264
+ additionalProperties: false,
265
+ properties: {
266
+ query: { type: 'string', description: '检索词(中文按二字组切分)' },
267
+ layer: { type: 'string', enum: ['L0', 'L1', 'L2', 'L3', 'L4', 'L5'] },
268
+ top_k: { type: 'integer', description: '返回条数,默认 10,上限 50' },
269
+ include_sensitive: { type: 'boolean', description: '是否包含 S 级记录(默认 false)' },
270
+ },
271
+ required: ['query'],
272
+ },
273
+ output: {
274
+ schema: textOut({
275
+ hits: { type: 'array', items: { type: 'object', additionalProperties: true } },
276
+ count: { type: 'integer' },
277
+ }),
278
+ render: (args, value) => [{ type: 'text', text: value.text }],
279
+ },
280
+ isConcurrencySafe: () => true,
281
+ execute: async (args) => {
282
+ const hits = store.search({
283
+ query: args?.query,
284
+ layer: args?.layer,
285
+ topK: args?.top_k,
286
+ includeSensitive: args?.include_sensitive === true,
287
+ })
288
+ // 给每条挂上"人话":模型读着顺手,用户看到的卡片也不用再解 record_id
289
+ const decorated = hits.map((h) => {
290
+ try {
291
+ return { ...h, display: explainRecord(h) }
292
+ } catch {
293
+ return h
294
+ }
295
+ })
296
+ const text = decorated.length === 0
297
+ ? ''
298
+ : decorated
299
+ .map((h, i) => {
300
+ const mark = h.scored ? '' : '·未评分'
301
+ const caveat = h.caveat ? ` ⚠ ${h.caveat}` : ''
302
+ const d = h.display || {}
303
+ const head = d.title ? `【${d.kind}】${d.title}` : h.snippet
304
+ const body = d.plain ? ` —— ${d.plain}` : ''
305
+ return `${i + 1}. ${head}${body} [${h.layer}/${h.sad_level} · ${h.trust_level}${mark} · 来源 ${h.source_channel} · score ${h.score.toFixed(2)}]${caveat}`
306
+ })
307
+ .join('\n')
308
+ return { text, hits: decorated, count: decorated.length }
309
+ },
310
+ },
311
+ { label: '检索', argsHint: 'mem_search({ query, layer?, top_k?, include_sensitive? })', needsOpen: true },
312
+ )
313
+
314
+ add(
315
+ {
316
+ name: 'mem_affect_report',
317
+ description: '情绪报告:区间内的情绪分布、负面占比、高频触发词、时段分布(目前数据源只采 QQ)。',
318
+ parameters: { type: 'object', additionalProperties: false, properties: { range: { type: 'string', enum: ['day', 'week', 'month'] }, save: { type: 'boolean', description: '是否落盘成 Markdown 报告' } } },
319
+ output: { schema: textOut({ report: { type: 'object', additionalProperties: true } }), render: renderText },
320
+ isConcurrencySafe: () => true,
321
+ execute: async (args) => {
322
+ const range = args?.range ?? 'day'
323
+ if (args?.save) {
324
+ const saved = saveAffectReport({ store, dataDir: store.dataDir ?? 'D:/001/CH002/dsh-memory-data', range })
325
+ return { text: '已生成报告:' + saved.path + '\n\n' + saved.text, report: saved.report }
326
+ }
327
+ const report = affectReport({ store, range })
328
+ const labels = report.byLabel
329
+ const lines = [
330
+ '区间:' + report.range + '(自 ' + report.since.slice(0, 10) + ')',
331
+ '事件 ' + report.total + ' 条:中性 ' + (labels.neutral || 0) + ' · 正面 ' + (labels.positive || 0) + ' · 负面 ' + (labels.negative || 0) + ' · 紧急 ' + (labels.urgent || 0),
332
+ '负面占比 ' + Math.round(report.negativeRatio * 100) + '%',
333
+ ]
334
+ if (report.topTriggers.length) lines.push('高频触发:' + report.topTriggers.map((x) => x.word + '×' + x.n).join('、'))
335
+ if (report.byHour.length) lines.push('时段:' + report.byHour.map((x) => x.hour + '时×' + x.n).join(' '))
336
+ return { text: lines.join('\n'), report }
337
+ },
338
+ },
339
+ { label: '情绪报告', argsHint: 'mem_affect_report({ range?: day|week|month })', needsOpen: true },
340
+ )
341
+
342
+ add(
343
+ {
344
+ name: 'mem_affect_ingest',
345
+ description: '立即采集 QQ 会话里的用户消息,标注情绪写入情绪事件表(默认最近 20 个会话)。',
346
+ parameters: { type: 'object', additionalProperties: false, properties: { limit: { type: 'integer' } } },
347
+ output: { schema: textOut({ result: { type: 'object', additionalProperties: true } }), render: renderText },
348
+ isConcurrencySafe: () => true,
349
+ execute: async (args) => {
350
+ const result = ingestQqSessions({ store, limit: args?.limit ?? 20 })
351
+ return {
352
+ text: '扫描会话 ' + result.files + ' 个,用户消息 ' + result.scanned + ' 条,新增 ' + result.added + ' 条,已存在 ' + result.skipped + ' 条',
353
+ result,
354
+ }
355
+ },
356
+ },
357
+ { label: '情绪采集', argsHint: 'mem_affect_ingest({ limit? })', needsOpen: true },
358
+ )
359
+
360
+ add(
361
+ {
362
+ name: 'mem_resume',
363
+ description: '续跑:列出未完成任务 + 对应交接 + 相关记忆,一句话接上上次的工作。新会话或 QQ 里说「接着上次的干」时调它。',
364
+ parameters: {
365
+ type: 'object',
366
+ additionalProperties: false,
367
+ properties: {
368
+ scene: { type: 'string', description: '限定场景(to_scene/from_scene 或交接头)' },
369
+ limit: { type: 'integer', description: '任务条数,默认 5' },
370
+ },
371
+ },
372
+ output: {
373
+ schema: textOut({
374
+ tasks: { type: 'array', items: { type: 'object', additionalProperties: true } },
375
+ handoff: { type: 'object', additionalProperties: true },
376
+ }),
377
+ render: renderText,
378
+ },
379
+ isConcurrencySafe: () => true,
380
+ execute: async (args) => {
381
+ const scene = String(args?.scene ?? '').trim()
382
+ const limit = Math.min(Math.max(Number(args?.limit ?? 5), 1), 20)
383
+ const params = []
384
+ let where = "status NOT IN ('done','closed','failed')"
385
+ if (scene) {
386
+ where += ' AND (to_scene = ? OR from_scene = ?)'
387
+ params.push(scene, scene)
388
+ }
389
+ const rows = store.db
390
+ .prepare(
391
+ `SELECT task_id, kind, from_scene, to_scene, title, status, phenomenon, how_to, how_verify, created_at, deadline_at
392
+ FROM tasks WHERE ${where} ORDER BY created_at DESC LIMIT ?`,
393
+ )
394
+ .all(...params, limit)
395
+
396
+ let handoff = null
397
+ if (scene) {
398
+ try {
399
+ handoff = store.handoffRead(scene)
400
+ } catch {
401
+ handoff = null
402
+ }
403
+ }
404
+
405
+ const lines = []
406
+ if (handoff) {
407
+ lines.push(`交接(${scene}):${handoff.title ?? ''}`)
408
+ const sections = handoff.sections
409
+ if (Array.isArray(sections)) {
410
+ for (const s of sections) lines.push(`- ${s.title ?? s.name ?? '段落'}:${String(s.body ?? s.content ?? '').slice(0, 200)}`)
411
+ } else if (sections && typeof sections === 'object') {
412
+ for (const [k, v] of Object.entries(sections)) lines.push(`- ${k}:${String(v).slice(0, 200)}`)
413
+ }
414
+ lines.push('')
415
+ }
416
+
417
+ if (!rows.length) {
418
+ lines.push('没有未完成的任务。')
419
+ } else {
420
+ lines.push(`未完成任务 ${rows.length} 条:`)
421
+ for (const r of rows) {
422
+ lines.push(`- ${r.task_id} [${r.status}] ${r.title}(${r.from_scene} → ${r.to_scene})`)
423
+ if (r.phenomenon) lines.push(` 现象:${r.phenomenon}`)
424
+ if (r.how_to) lines.push(` 做法:${r.how_to}`)
425
+ if (r.how_verify) lines.push(` 验收:${r.how_verify}`)
426
+ }
427
+ }
428
+
429
+ const related = []
430
+ for (const r of rows.slice(0, 3)) {
431
+ try {
432
+ const hits = store.search({ query: r.title, topK: 2 })
433
+ for (const h of hits) related.push(`- [${h.layer}] ${h.summary} | 相关任务 ${r.task_id}`)
434
+ } catch {
435
+ /* 检索失败不影响续跑 */
436
+ }
437
+ }
438
+ if (related.length) lines.push('', '相关记忆:', ...related)
439
+
440
+ return { text: lines.join('\n'), tasks: rows, handoff: handoff ?? {} }
441
+ },
442
+ },
443
+ { label: '续跑', argsHint: 'mem_resume({ scene?, limit? })', needsOpen: true },
444
+ )
445
+
446
+ add(
447
+ {
448
+ name: 'mem_parts',
449
+ description: '零件清单:列出记忆可装配的零件(名称/版本/用途)。记忆不是黑盒,是一组可替换的零件。',
450
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
451
+ output: {
452
+ schema: textOut({ parts: { type: 'array', items: { type: 'object', additionalProperties: true } } }),
453
+ render: renderText,
454
+ },
455
+ isConcurrencySafe: () => true,
456
+ execute: async () => {
457
+ const parts = listParts()
458
+ return {
459
+ text: parts.map((p) => `- ${p.name} v${p.version}:${p.describe}`).join('\n'),
460
+ parts,
461
+ }
462
+ },
463
+ },
464
+ { label: '零件清单', argsHint: 'mem_parts()', needsOpen: true },
465
+ )
466
+
467
+ add(
468
+ {
469
+ name: 'mem_compose',
470
+ description: '按零件装配一段上下文:给定场景与零件列表,拼出可直接使用的记忆包(去重、限长、带来源标注)。',
471
+ parameters: {
472
+ type: 'object',
473
+ additionalProperties: false,
474
+ properties: {
475
+ scene: { type: 'string', description: '场景名(scene 零件按 tag 匹配)' },
476
+ parts: { type: 'array', items: { type: 'string' }, description: '零件名列表,默认 ["profile","lessons","recent"]' },
477
+ seed: { type: 'string', description: 'associations 零件的种子(record_id 或文本)' },
478
+ max_chars: { type: 'integer', description: '总长度上限,默认 1200' },
479
+ },
480
+ },
481
+ output: {
482
+ schema: textOut({
483
+ text: { type: 'string' },
484
+ parts: { type: 'array', items: { type: 'object', additionalProperties: true } },
485
+ }),
486
+ render: renderText,
487
+ },
488
+ isConcurrencySafe: () => true,
489
+ execute: async (args) => {
490
+ const result = compose(store, {
491
+ scene: args?.scene,
492
+ parts: args?.parts,
493
+ seed: args?.seed,
494
+ maxChars: args?.max_chars,
495
+ })
496
+ return { text: result.text || '(没有可装配的内容)', parts: result.parts }
497
+ },
498
+ },
499
+ { label: '装配', argsHint: 'mem_compose({ scene?, parts?, seed?, max_chars? })', needsOpen: true },
500
+ )
501
+
502
+ add(
503
+ {
504
+ name: 'mem_associate',
505
+ description: '联想:给一条记忆 ID 或一句话,返回标签、语义、情绪上相近的其他记忆(带联想理由与权重)。用于「由 A 想到 B」。',
506
+ parameters: {
507
+ type: 'object',
508
+ additionalProperties: false,
509
+ properties: {
510
+ record_id: { type: 'string', description: '种子记录 ID(ULID)' },
511
+ query: { type: 'string', description: '种子文本;没有 record_id 时用它' },
512
+ top_k: { type: 'integer', description: '返回条数,默认 5,最多 20' },
513
+ },
514
+ },
515
+ output: {
516
+ schema: textOut({
517
+ seed: { type: 'object', additionalProperties: true },
518
+ items: { type: 'array', items: { type: 'object', additionalProperties: true } },
519
+ }),
520
+ render: renderText,
521
+ },
522
+ isConcurrencySafe: () => true,
523
+ execute: async (args) => {
524
+ const result = store.associate({
525
+ recordId: args?.record_id,
526
+ query: args?.query,
527
+ topK: args?.top_k,
528
+ })
529
+ const lines = []
530
+ if (result.seed) {
531
+ lines.push(
532
+ `种子:${result.seed.record_id}(${result.seed.layer}${result.seed.affect_label ? ' / ' + result.seed.affect_label : ''})${result.seed.summary}`,
533
+ )
534
+ } else if (args?.query) {
535
+ lines.push(`种子:${args.query}`)
536
+ }
537
+ if (!result.items.length) lines.push('没有找到相关联的记忆。')
538
+ for (const item of result.items) {
539
+ lines.push(
540
+ `- ${item.record_id} [${item.layer}${item.affect_label ? '/' + item.affect_label : ''}] ${item.summary} | 理由:${item.reasons.join('、')} | 权重 ${item.weight}`,
541
+ )
542
+ }
543
+ return { text: lines.join('\n'), seed: result.seed ?? {}, items: result.items }
544
+ },
545
+ },
546
+ { label: '联想', argsHint: 'mem_associate({ record_id? | query?, top_k? })', needsOpen: true },
547
+ )
548
+
549
+ add(
550
+ {
551
+ name: 'mem_read',
552
+ description: '按 record_id 读全文。S 级记录默认只返回摘要与哈希,需要 include_sensitive=true 才给正文。',
553
+ parameters: {
554
+ type: 'object',
555
+ additionalProperties: false,
556
+ properties: {
557
+ record_id: { type: 'string', description: '记录 ID(ULID)' },
558
+ include_sensitive: { type: 'boolean', description: 'S 级是否返回正文' },
559
+ },
560
+ required: ['record_id'],
561
+ },
562
+ output: {
563
+ schema: textOut({
564
+ record: { type: 'object', additionalProperties: true },
565
+ denied: { type: 'boolean' },
566
+ }),
567
+ render: renderText,
568
+ },
569
+ isConcurrencySafe: () => true,
570
+ execute: async (args) => {
571
+ const record = store.read(String(args?.record_id ?? ''), { includeSensitive: args?.include_sensitive === true })
572
+ if (!record) return { text: `没有找到记录 ${args?.record_id}`, record: {}, denied: false }
573
+ if (record.denied) {
574
+ return {
575
+ text: [
576
+ `记录 ${record.record_id}(${record.layer}/${record.sad_level})被权限拦下:${record.reason}`,
577
+ `摘要:${record.summary}`,
578
+ `哈希:${record.content_hash}`,
579
+ ].join('\n'),
580
+ record,
581
+ denied: true,
582
+ }
583
+ }
584
+ return {
585
+ text: [
586
+ `${record.record_id}(${record.layer}/${record.sad_level}/${record.trust_level}/${record.status})`,
587
+ `来源 ${record.source_channel},写入 ${record.created_at}`,
588
+ `哈希 ${record.content_hash}`,
589
+ '',
590
+ record.content,
591
+ ].join('\n'),
592
+ record,
593
+ denied: false,
594
+ }
595
+ },
596
+ },
597
+ { label: '读全文', argsHint: 'mem_read({ record_id, include_sensitive? })', needsOpen: true },
598
+ )
599
+
600
+ // ---------- 可注入:评分与审核(写入链的配套出口) ----------
601
+
602
+ add(
603
+ {
604
+ name: 'mem_judge',
605
+ description:
606
+ '给一条记忆补评 α(重要度 0.01–1)与 β(可信度 0–1)。评分不阻塞写入:未评分的记忆可以召回,' +
607
+ '但注入时会带"未评分"标记,且 β 不参与权重。',
608
+ parameters: {
609
+ type: 'object',
610
+ additionalProperties: false,
611
+ properties: {
612
+ record_id: { type: 'string', description: '记录 ID' },
613
+ alpha: { type: 'number', description: '重要度 0.01–1' },
614
+ beta: { type: 'number', description: '可信度 0–1' },
615
+ },
616
+ required: ['record_id'],
617
+ },
618
+ output: {
619
+ schema: textOut({
620
+ record_id: { type: 'string' },
621
+ alpha: { type: 'string' },
622
+ beta: { type: 'string' },
623
+ scored: { type: 'boolean' },
624
+ }),
625
+ render: renderText,
626
+ },
627
+ isConcurrencySafe: () => false,
628
+ execute: async (args) => {
629
+ const r = store.judge(String(args?.record_id ?? ''), { alpha: args?.alpha, beta: args?.beta })
630
+ return {
631
+ text: `已评分 ${r.record_id}:α=${r.alpha ?? '—'},β=${r.beta ?? '—'}`,
632
+ record_id: r.record_id,
633
+ alpha: String(r.alpha ?? ''),
634
+ beta: String(r.beta ?? ''),
635
+ scored: true,
636
+ }
637
+ },
638
+ },
639
+ { label: '评分', argsHint: 'mem_judge({ record_id, alpha?, beta? })', needsOpen: true },
640
+ )
641
+
642
+ add(
643
+ {
644
+ name: 'mem_review',
645
+ description:
646
+ '审核待审区/隔离区的记录。approve / release → 回到 active(参与召回);reject → 标记 rejected(保留正文,不物理删除)。' +
647
+ '没有这个出口,隔离区会变成垃圾场。',
648
+ parameters: {
649
+ type: 'object',
650
+ additionalProperties: false,
651
+ properties: {
652
+ record_id: { type: 'string', description: '记录 ID' },
653
+ decision: { type: 'string', enum: ['approve', 'reject', 'release'], description: 'approve=通过 / reject=否决 / release=解除隔离' },
654
+ note: { type: 'string', description: '决定理由(记入 review_queue)' },
655
+ },
656
+ required: ['record_id', 'decision'],
657
+ },
658
+ output: {
659
+ schema: textOut({
660
+ record_id: { type: 'string' },
661
+ status: { type: 'string' },
662
+ decision: { type: 'string' },
663
+ }),
664
+ render: renderText,
665
+ },
666
+ isConcurrencySafe: () => false,
667
+ execute: async (args) => {
668
+ const r = store.review(String(args?.record_id ?? ''), String(args?.decision ?? ''), args?.note ?? null)
669
+ return { text: `${r.record_id} 已 ${r.decision},当前状态 ${r.status}`, record_id: r.record_id, status: r.status, decision: r.decision }
670
+ },
671
+ },
672
+ { label: '审核', argsHint: 'mem_review({ record_id, decision: approve|reject|release, note? })', needsOpen: true },
673
+ )
674
+
675
+ add(
676
+ {
677
+ name: 'mem_pending',
678
+ description: '列待审区与隔离区(pending / quarantined),含原因与冲突对象。审核前先看这个。',
679
+ parameters: {
680
+ type: 'object',
681
+ additionalProperties: false,
682
+ properties: {
683
+ limit: { type: 'integer', description: '最多返回条数,默认 20' },
684
+ },
685
+ },
686
+ output: {
687
+ schema: textOut({
688
+ items: { type: 'array', items: { type: 'object', additionalProperties: true } },
689
+ count: { type: 'integer' },
690
+ }),
691
+ render: renderText,
692
+ },
693
+ isConcurrencySafe: () => true,
694
+ execute: async (args) => {
695
+ const items = store.pendingReview(args?.limit)
696
+ const text = items.length === 0
697
+ ? '待审区与隔离区都是空的。'
698
+ : items
699
+ .map((r, i) => `${i + 1}. ${r.record_id} [${r.status}/${r.sad_level}/${r.trust_level}] ${r.summary ?? ''}${r.reason ? `(${r.reason})` : ''}`)
700
+ .join('\n')
701
+ return { text, items, count: items.length }
702
+ },
703
+ },
704
+ { label: '待审清单', argsHint: 'mem_pending({ limit? })', needsOpen: true },
705
+ )
706
+
707
+ // ---------- 交接与体检(迁移自 luanyujia-workbench 记忆机制) ----------
708
+
709
+ const SECTION_LABELS = {
710
+ last: '1) 上次交接',
711
+ projects: '2) 当前项目',
712
+ changes: '3) 私有记忆变更',
713
+ next: '4) 下一步',
714
+ blockers: '5) 卡点',
715
+ }
716
+ const renderSections = (sections) =>
717
+ ['last', 'projects', 'changes', 'next', 'blockers']
718
+ .filter((k) => sections && sections[k])
719
+ .map((k) => `### ${SECTION_LABELS[k]}\n${sections[k]}`)
720
+ .join('\n\n')
721
+
722
+ add(
723
+ {
724
+ name: 'mem_handoff',
725
+ description:
726
+ '读写场景的「§〇 交接」:覆盖写、只留最新一份、≤4 KB、五小节固定键(last / projects / changes / next / blockers)。' +
727
+ '换会话前必须先写交接;写不出"下一步"说明这轮白干了。',
728
+ parameters: {
729
+ type: 'object',
730
+ additionalProperties: false,
731
+ properties: {
732
+ scene: { type: 'string', description: '场景名(通常是项目 id)' },
733
+ mode: { type: 'string', enum: ['read', 'write'], description: 'read 读取(默认)/ write 覆盖写' },
734
+ title: { type: 'string', description: '可选标题' },
735
+ sections: {
736
+ type: 'object',
737
+ additionalProperties: false,
738
+ description: '五小节(写模式必填至少一节)',
739
+ properties: {
740
+ last: { type: 'string', description: '上次交接:做了什么 / 结果 / 证据' },
741
+ projects: { type: 'string', description: '当前项目表' },
742
+ changes: { type: 'string', description: '私有记忆变更' },
743
+ next: { type: 'string', description: '下一步' },
744
+ blockers: { type: 'string', description: '卡点(没有就写"无")' },
745
+ },
746
+ },
747
+ },
748
+ required: ['scene'],
749
+ },
750
+ output: {
751
+ schema: textOut({
752
+ scene: { type: 'string' },
753
+ bytes: { type: 'integer' },
754
+ updated_at: { type: 'string' },
755
+ }),
756
+ render: renderText,
757
+ },
758
+ isConcurrencySafe: () => false,
759
+ execute: async (args) => {
760
+ const scene = String(args?.scene ?? '').trim()
761
+ if (!scene) return { text: '需要 scene 参数。', scene: '', bytes: 0, updated_at: '' }
762
+ if (args?.mode === 'write') {
763
+ const r = store.handoffWrite({ scene, title: args?.title ?? null, sections: args?.sections ?? {} })
764
+ return {
765
+ text: `已覆盖写 ${scene} 的 §〇 交接(${r.bytes}/4096 字节,${r.updated_at})\n\n${renderSections(r.sections)}`,
766
+ scene,
767
+ bytes: r.bytes,
768
+ updated_at: r.updated_at,
769
+ }
770
+ }
771
+ const h = store.handoffRead(scene)
772
+ if (!h) return { text: `场景 ${scene} 还没有交接。`, scene, bytes: 0, updated_at: '' }
773
+ return {
774
+ text: `${renderSections(h.sections)}\n\n(${h.bytes}/4096 字节,更新于 ${h.updated_at})`,
775
+ scene,
776
+ bytes: h.bytes,
777
+ updated_at: h.updated_at,
778
+ }
779
+ },
780
+ },
781
+ { label: '场景交接', argsHint: 'mem_handoff({ scene, mode?, sections? })', needsOpen: true },
782
+ )
783
+
784
+ add(
785
+ {
786
+ name: 'mem_check',
787
+ description:
788
+ '体量体检:交接 ≤4 KB、场景记忆 ≤25 KB、待审 ≤20、审计链一致。换会话前跑一次,不过就别换。',
789
+ parameters: {
790
+ type: 'object',
791
+ additionalProperties: false,
792
+ properties: {
793
+ scene: { type: 'string', description: '只看某个场景(可选)' },
794
+ },
795
+ },
796
+ output: {
797
+ schema: textOut({
798
+ ok: { type: 'boolean' },
799
+ items: { type: 'array', items: { type: 'object', additionalProperties: true } },
800
+ }),
801
+ render: renderText,
802
+ },
803
+ isConcurrencySafe: () => true,
804
+ execute: async (args) => {
805
+ const r = store.checkBudgets(args?.scene ?? null)
806
+ const lines = r.items.map((i) => `${i.ok ? '✓' : '✗'} ${i.name}: ${i.value}/${i.limit}`)
807
+ return {
808
+ text: lines.join('\n') + (r.ok ? '\n\n全部在红线内。' : '\n\n有超线项:先减肥(历史搬归档),再换会话。'),
809
+ ok: r.ok,
810
+ items: r.items,
811
+ }
812
+ },
813
+ },
814
+ { label: '体量体检', argsHint: 'mem_check({ scene? })', needsOpen: true },
815
+ )
816
+
817
+ // ---------- 协作:派单 / 回执 / 台账 / 修改权 ----------
818
+
819
+ add(
820
+ {
821
+ name: 'mem_dispatch',
822
+ description:
823
+ '建一条派单(要对方动手)或公告(只知悉)。派单四件套缺一不可:现象 / 照哪做 / 怎么验 / 回一句;' +
824
+ '公告不需要四件套,但也不会唤醒对方。派单默认 24 小时未回执进 overdue。',
825
+ parameters: {
826
+ type: 'object',
827
+ additionalProperties: false,
828
+ properties: {
829
+ kind: { type: 'string', enum: ['dispatch', 'notice'], description: 'dispatch=派单(默认)/ notice=公告' },
830
+ from: { type: 'string', description: '发起方场景' },
831
+ to: { type: 'string', description: '执行方场景' },
832
+ title: { type: 'string', description: '一句话标题' },
833
+ phenomenon: { type: 'string', description: '① 现象:现在什么样(可观察,不要形容词)' },
834
+ how_to: { type: 'string', description: '② 照哪做:文档哪一节 / 哪个工具(唯一出处)' },
835
+ how_verify: { type: 'string', description: '③ 怎么验:跑什么、看到什么算通过' },
836
+ deadline_minutes: { type: 'integer', description: '超时阈值(分钟),默认 1440' },
837
+ },
838
+ required: ['from', 'to', 'title'],
839
+ },
840
+ output: {
841
+ schema: textOut({ task_id: { type: 'string' }, status: { type: 'string' }, deadline_at: { type: 'string' } }),
842
+ render: renderText,
843
+ },
844
+ isConcurrencySafe: () => false,
845
+ execute: async (args) => {
846
+ const t = store.dispatchCreate({
847
+ kind: args?.kind ?? 'dispatch',
848
+ from: args?.from,
849
+ to: args?.to,
850
+ title: args?.title,
851
+ phenomenon: args?.phenomenon,
852
+ howTo: args?.how_to,
853
+ howVerify: args?.how_verify,
854
+ deadlineMinutes: args?.deadline_minutes,
855
+ })
856
+ return {
857
+ text:
858
+ `已建 ${t.kind === 'dispatch' ? '派单' : '公告'} ${t.task_id}\n` +
859
+ ` ${t.from_scene} → ${t.to_scene}:${t.title}\n` +
860
+ ` 状态 ${t.status}${t.deadline_at ? ',回执期限 ' + t.deadline_at : ''}\n` +
861
+ (t.kind === 'dispatch' ? ' 记得在正文里写「我在等你的回执」。' : ' 公告只落盘,不唤醒。'),
862
+ task_id: t.task_id,
863
+ status: t.status,
864
+ deadline_at: t.deadline_at ?? '',
865
+ }
866
+ },
867
+ },
868
+ { label: '派单', argsHint: 'mem_dispatch({ kind?, from, to, title, phenomenon?, how_to?, how_verify? })', needsOpen: true },
869
+ )
870
+
871
+ add(
872
+ {
873
+ name: 'mem_receipt',
874
+ description:
875
+ '给一条派单回执:结论 + 证据 + 落盘路径(+ 还差什么)。只在自己窗口说"做完了"等于没交付;' +
876
+ '同一件事最多 3 条消息,到上限会拒绝。',
877
+ parameters: {
878
+ type: 'object',
879
+ additionalProperties: false,
880
+ properties: {
881
+ task_id: { type: 'string', description: '派单 id' },
882
+ conclusion: { type: 'string', description: '结论(一行)' },
883
+ evidence: { type: 'string', description: '证据:跑了什么、几条通过、差异集合' },
884
+ path: { type: 'string', description: '落盘路径(回执给指针,报告放文件)' },
885
+ remaining: { type: 'string', description: '还差什么(没有就不填)' },
886
+ },
887
+ required: ['task_id', 'conclusion', 'evidence'],
888
+ },
889
+ output: {
890
+ schema: textOut({ task_id: { type: 'string' }, status: { type: 'string' } }),
891
+ render: renderText,
892
+ },
893
+ isConcurrencySafe: () => false,
894
+ execute: async (args) => {
895
+ const t = store.taskReceipt({
896
+ taskId: args?.task_id,
897
+ conclusion: args?.conclusion,
898
+ evidence: args?.evidence,
899
+ path: args?.path,
900
+ remaining: args?.remaining,
901
+ })
902
+ return {
903
+ text: `已回执 ${t.task_id}(${t.status})。\n结论:${t.ack.conclusion}\n证据:${t.ack.evidence}`,
904
+ task_id: t.task_id,
905
+ status: t.status,
906
+ }
907
+ },
908
+ },
909
+ { label: '回执', argsHint: 'mem_receipt({ task_id, conclusion, evidence, path?, remaining? })', needsOpen: true },
910
+ )
911
+
912
+ add(
913
+ {
914
+ name: 'mem_task',
915
+ description:
916
+ '派单台账:scope=outbound 看我发出没回的;inbound 看别人等我回的;open 看全部未办结。' +
917
+ '带 task_id + status 时推进状态(delivered / done / failed / closed)。',
918
+ parameters: {
919
+ type: 'object',
920
+ additionalProperties: false,
921
+ properties: {
922
+ scene: { type: 'string', description: '场景名(outbound/inbound 必填)' },
923
+ scope: { type: 'string', enum: ['outbound', 'inbound', 'open', 'all'], description: '默认 open' },
924
+ task_id: { type: 'string', description: '要推进状态的任务 id' },
925
+ status: { type: 'string', enum: ['delivered', 'done', 'failed', 'closed'], description: '目标状态' },
926
+ },
927
+ },
928
+ output: {
929
+ schema: textOut({
930
+ items: { type: 'array', items: { type: 'object', additionalProperties: true } },
931
+ count: { type: 'integer' },
932
+ }),
933
+ render: renderText,
934
+ },
935
+ isConcurrencySafe: () => true,
936
+ execute: async (args) => {
937
+ if (args?.task_id && args?.status) {
938
+ const t = store.taskMark({ taskId: args.task_id, status: args.status })
939
+ return { text: `${t.task_id} → ${t.status}`, items: [t], count: 1 }
940
+ }
941
+ const items = store.taskList({ scene: args?.scene ?? null, scope: args?.scope ?? 'open' })
942
+ const text = items.length === 0
943
+ ? '台账是空的。'
944
+ : items
945
+ .map((t) => {
946
+ const flag = t.overdue ? '⚠ 超时未回执' : t.effective_status
947
+ return `- ${t.task_id} [${t.kind}/${flag}] ${t.from_scene} → ${t.to_scene}:${t.title}`
948
+ })
949
+ .join('\n')
950
+ return { text, items, count: items.length }
951
+ },
952
+ },
953
+ { label: '派单台账', argsHint: 'mem_task({ scene?, scope?, task_id?, status? })', needsOpen: true },
954
+ )
955
+
956
+ add(
957
+ {
958
+ name: 'mem_scope',
959
+ description:
960
+ '修改权判定(A 宪法 / C 工具 / B 板 / D 自己 / E 别人):告诉我这个 actor 能不能写这个目标,' +
961
+ '越界时给出"写请求"的写法。',
962
+ parameters: {
963
+ type: 'object',
964
+ additionalProperties: false,
965
+ properties: {
966
+ actor: { type: 'string', description: '谁在写(场景名)' },
967
+ target: { type: 'string', description: '写谁的东西(场景名)' },
968
+ kind: { type: 'string', enum: ['rule', 'tool', 'board', 'own'], description: '默认 own' },
969
+ rule_owner: { type: 'string', description: 'A/C 档负责人(可选)' },
970
+ row_owner: { type: 'string', description: 'B 档行归属(可选)' },
971
+ },
972
+ required: ['actor', 'target'],
973
+ },
974
+ output: {
975
+ schema: textOut({
976
+ tier: { type: 'string' },
977
+ allowed: { type: 'boolean' },
978
+ reason: { type: 'string' },
979
+ request: { type: 'string' },
980
+ }),
981
+ render: renderText,
982
+ },
983
+ isConcurrencySafe: () => true,
984
+ execute: async (args) => {
985
+ const r = canWrite({
986
+ actor: args?.actor,
987
+ target: args?.target,
988
+ kind: args?.kind ?? 'own',
989
+ ruleOwner: args?.rule_owner ?? null,
990
+ rowOwner: args?.row_owner ?? null,
991
+ })
992
+ return {
993
+ text: `${r.allowed ? '✓ 可以写' : '✗ 不能写'}(${r.tier} 档):${r.reason}${r.request ? '\n' + r.request : ''}`,
994
+ tier: r.tier,
995
+ allowed: r.allowed,
996
+ reason: r.reason,
997
+ request: r.request ?? '',
998
+ }
999
+ },
1000
+ },
1001
+ { label: '修改权判定', argsHint: 'mem_scope({ actor, target, kind?, rule_owner?, row_owner? })', needsOpen: true },
1002
+ )
1003
+
1004
+ // ---------- 二期:导入 / 影子读 / 回放 / 审计 ----------
1005
+
1006
+ add(
1007
+ {
1008
+ name: 'mem_import',
1009
+ description:
1010
+ '把旧记忆(~/.mnemon 的 memories.json 与 documents)只读导入本库。凭证类正文替换成 «REDACTED:kind» 并记 S 级,' +
1011
+ '原值留在原处;按内容哈希去重,重复跑不会重复导入。dry_run=true 只算不写。',
1012
+ parameters: {
1013
+ type: 'object',
1014
+ additionalProperties: false,
1015
+ properties: {
1016
+ dry_run: { type: 'boolean', description: '只统计不写库' },
1017
+ home: { type: 'string', description: '旧记忆根目录,缺省 ~/.mnemon' },
1018
+ },
1019
+ },
1020
+ output: {
1021
+ schema: textOut({
1022
+ imported: { type: 'integer' },
1023
+ skipped: { type: 'integer' },
1024
+ redacted: { type: 'integer' },
1025
+ dry_run: { type: 'boolean' },
1026
+ errors: { type: 'integer' },
1027
+ report: { type: 'object', additionalProperties: true },
1028
+ }),
1029
+ render: renderText,
1030
+ },
1031
+ isConcurrencySafe: () => false,
1032
+ execute: async (args) => {
1033
+ const report = store.importLegacy({ dryRun: args?.dry_run === true, home: args?.home })
1034
+ const lines = [
1035
+ `${report.dry_run ? '【演练】' : ''}扫描:记忆 ${report.scanned.memory} 条 / 文档 ${report.scanned.documents} 条`,
1036
+ `导入 ${report.imported} · 跳过(已存在) ${report.skipped} · 脱敏 ${report.redacted} 条`,
1037
+ report.redacted_kinds && Object.keys(report.redacted_kinds).length
1038
+ ? `脱敏类型:${Object.entries(report.redacted_kinds).map(([k, v]) => `${k}×${v}`).join('、')}`
1039
+ : '脱敏类型:无',
1040
+ `分层:${Object.entries(report.by_layer).map(([k, v]) => `${k}:${v}`).join(' ') || '(无)'}`,
1041
+ ]
1042
+ if (report.errors.length) {
1043
+ lines.push(`错误 ${report.errors.length} 条:`)
1044
+ for (const e of report.errors.slice(0, 5)) lines.push(` - ${e.ref}: ${e.reason}`)
1045
+ }
1046
+ return {
1047
+ text: lines.join('\n'),
1048
+ imported: report.imported,
1049
+ skipped: report.skipped,
1050
+ redacted: report.redacted,
1051
+ dry_run: report.dry_run,
1052
+ errors: report.errors.length,
1053
+ report,
1054
+ }
1055
+ },
1056
+ },
1057
+ { label: '导入旧记忆', argsHint: 'mem_import({ dry_run?, home? })', needsOpen: true },
1058
+ )
1059
+
1060
+ add(
1061
+ {
1062
+ name: 'mem_shadow',
1063
+ description:
1064
+ '影子读:同一次查询同时走旧记忆(~/.mnemon)与本库,并排给出结果与差异(只有旧有 / 只有新有 / 都有)。' +
1065
+ 'authority=shadow 时用它确认"新库没有漏掉旧记忆"。',
1066
+ parameters: {
1067
+ type: 'object',
1068
+ additionalProperties: false,
1069
+ properties: {
1070
+ query: { type: 'string', description: '查询词' },
1071
+ top_k: { type: 'integer', description: '每路返回条数,默认 5' },
1072
+ home: { type: 'string', description: '旧记忆根目录,缺省 ~/.mnemon' },
1073
+ },
1074
+ required: ['query'],
1075
+ },
1076
+ output: {
1077
+ schema: textOut({
1078
+ legacy: { type: 'array', items: { type: 'object', additionalProperties: true } },
1079
+ mine: { type: 'array', items: { type: 'object', additionalProperties: true } },
1080
+ consistent: { type: 'boolean' },
1081
+ only_legacy: { type: 'integer' },
1082
+ only_new: { type: 'integer' },
1083
+ both: { type: 'integer' },
1084
+ }),
1085
+ render: renderText,
1086
+ },
1087
+ isConcurrencySafe: () => true,
1088
+ execute: async (args) => {
1089
+ const r = store.shadow({ query: args?.query, topK: args?.top_k, home: args?.home })
1090
+ const lines = [
1091
+ `查询:${r.query} 旧库 ${r.legacy_count} 条 / 新库 ${r.mine.length} 条命中`,
1092
+ `一致性:${r.consistent ? '旧库命中项都能在新库找到' : `有 ${r.diff.only_legacy.length} 条旧库命中项在新库缺失`}`,
1093
+ `交集 ${r.diff.both.length} · 只有旧 ${r.diff.only_legacy.length} · 只有新 ${r.diff.only_new.length}`,
1094
+ '',
1095
+ '旧:',
1096
+ ...(r.legacy.length ? r.legacy.map((h, i) => ` ${i + 1}. [${h.legacy_id}] ${h.snippet}${h.record_id ? ` → ${h.record_id}` : ' (新库无对应)'}`) : [' (无)']),
1097
+ '新:',
1098
+ ...(r.mine.length ? r.mine.map((h, i) => ` ${i + 1}. ${h.record_id} ${h.snippet}`) : [' (无)']),
1099
+ ]
1100
+ return {
1101
+ text: lines.join('\n'),
1102
+ legacy: r.legacy,
1103
+ mine: r.mine,
1104
+ consistent: r.consistent,
1105
+ only_legacy: r.diff.only_legacy.length,
1106
+ only_new: r.diff.only_new.length,
1107
+ both: r.diff.both.length,
1108
+ }
1109
+ },
1110
+ },
1111
+ { label: '影子读', argsHint: 'mem_shadow({ query, top_k?, home? })', needsOpen: true },
1112
+ )
1113
+
1114
+ add(
1115
+ {
1116
+ name: 'mem_prompt_inspector',
1117
+ description: '按 trace_id 回放:那次操作的参数摘要、命中了哪些记录、耗时、以及哈希链上的前后指针。',
1118
+ parameters: {
1119
+ type: 'object',
1120
+ additionalProperties: false,
1121
+ properties: {
1122
+ trace_id: { type: 'string', description: '记录仪里的 trace_id' },
1123
+ },
1124
+ required: ['trace_id'],
1125
+ },
1126
+ output: {
1127
+ schema: textOut({
1128
+ trace: { type: 'object', additionalProperties: true },
1129
+ found: { type: 'boolean' },
1130
+ }),
1131
+ render: renderText,
1132
+ },
1133
+ isConcurrencySafe: () => true,
1134
+ execute: async (args) => {
1135
+ const trace = store.traceLookup(String(args?.trace_id ?? ''))
1136
+ if (!trace) return { text: `没有找到 trace ${args?.trace_id}(记录仪里没有这一条)`, trace: {}, found: false }
1137
+ const lines = [
1138
+ `trace ${trace.trace_id} #${trace.seq}`,
1139
+ `操作 ${trace.op} 时间 ${trace.at}`,
1140
+ `查询:${trace.query_preview ?? '(无)'}${trace.query_hash ? `\n查询哈希 ${trace.query_hash.slice(0, 16)}…` : ''}`,
1141
+ `命中 ${trace.hits.length} 条:${trace.hits.slice(0, 8).join(', ') || '(无)'}`,
1142
+ `token:入 ${trace.tokens_in ?? '—'} / 出 ${trace.tokens_out ?? '—'} 耗时 ${trace.duration_ms ?? '—'} ms`,
1143
+ `哈希链:prev ${String(trace.prev_hash ?? '').slice(0, 12)}… → hash ${String(trace.hash ?? '').slice(0, 12)}…`,
1144
+ ]
1145
+ return { text: lines.join('\n'), trace, found: true }
1146
+ },
1147
+ },
1148
+ { label: '注入回放', argsHint: 'mem_prompt_inspector({ trace_id })', needsOpen: true },
1149
+ )
1150
+
1151
+ add(
1152
+ {
1153
+ name: 'mem_audit',
1154
+ description: '记录仪体检:校验哈希链(deep=true 逐行重算)、统计行数与体积、列出最近 5 条 trace。',
1155
+ parameters: {
1156
+ type: 'object',
1157
+ additionalProperties: false,
1158
+ properties: {
1159
+ deep: { type: 'boolean', description: '逐行重算整条链(慢,但能定位断点)' },
1160
+ },
1161
+ },
1162
+ output: {
1163
+ schema: textOut({
1164
+ ok: { type: 'boolean' },
1165
+ lines: { type: 'integer' },
1166
+ files: { type: 'integer' },
1167
+ broken_at: { type: 'string' },
1168
+ recent: { type: 'array', items: { type: 'object', additionalProperties: true } },
1169
+ }),
1170
+ render: renderText,
1171
+ },
1172
+ isConcurrencySafe: () => true,
1173
+ execute: async (args) => {
1174
+ const a = store.audit({ deep: args?.deep === true })
1175
+ const lines = [
1176
+ `哈希链:${a.ok ? '一致' : `断链(${a.brokenAt?.file ?? '?'} ${a.brokenAt?.reason ?? ''})`}`,
1177
+ `记录 ${a.lines} 行 / ${a.files} 个文件 / ${(a.bytes / 1024).toFixed(1)} KB`,
1178
+ `最近 trace:`,
1179
+ ...(a.recent.length ? a.recent.map((t) => ` #${t.trace_id} ${t.op} ${t.at}`) : [' (无)']),
1180
+ ]
1181
+ return { text: lines.join('\n'), ok: Boolean(a.ok), lines: a.lines, files: a.files, broken_at: a.brokenAt ? JSON.stringify(a.brokenAt) : '', recent: a.recent }
1182
+ },
1183
+ },
1184
+ { label: '记录仪体检', argsHint: 'mem_audit({ deep? })', needsOpen: true },
1185
+ )
1186
+
1187
+ // ---------- 账本 / 健康线(补齐自实施单 5.2 / 5.3) ----------
1188
+
1189
+ add(
1190
+ {
1191
+ name: 'mem_ledger',
1192
+ description: '文本账本:init 拍快照、sync 只补新记录、verify 校验每条正文指纹。先 sync 再 verify。',
1193
+ parameters: {
1194
+ type: 'object',
1195
+ additionalProperties: false,
1196
+ properties: { action: { type: 'string', enum: ['init', 'sync', 'verify'] } },
1197
+ required: ['action'],
1198
+ },
1199
+ output: { schema: textOut({ result: { type: 'object', additionalProperties: true } }), render: renderText },
1200
+ isConcurrencySafe: () => true,
1201
+ execute: async (args) => {
1202
+ const action = String(args?.action ?? 'verify')
1203
+ if (action === 'init') {
1204
+ const r = ledgerInit({ store })
1205
+ return { text: '账本已初始化:' + r.initialized + ' 条\n' + r.path, result: r }
1206
+ }
1207
+ if (action === 'sync') {
1208
+ const r = ledgerSync({ store })
1209
+ return { text: '账本已同步:新增 ' + r.added + ' 条,共 ' + r.total + ' 条', result: r }
1210
+ }
1211
+ const r = ledgerVerify({ store })
1212
+ return {
1213
+ text: r.ok ? '账本校验通过:' + r.total + ' 条全部一致' : '账本校验失败:丢失 ' + r.missing.length + ' 条,被改 ' + r.changed.length + ' 条',
1214
+ result: r,
1215
+ }
1216
+ },
1217
+ },
1218
+ { label: '账本', argsHint: 'mem_ledger({ action: init|sync|verify })', needsOpen: true },
1219
+ )
1220
+
1221
+ add(
1222
+ {
1223
+ name: 'mem_health',
1224
+ description: '每日健康一行:记录数 / 待审 / 账本 / 审计链,一眼看全线是否正常。',
1225
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
1226
+ output: { schema: textOut({ line: { type: 'string' } }), render: renderText },
1227
+ isConcurrencySafe: () => true,
1228
+ execute: async () => {
1229
+ const line = healthLine({ store })
1230
+ return { text: line, line }
1231
+ },
1232
+ },
1233
+ { label: '健康一行', argsHint: 'mem_health({})', needsOpen: true },
1234
+ )
1235
+
1236
+ // ---------- 四期:加密 ----------
1237
+
1238
+ add(
1239
+ {
1240
+ name: 'mem_crypto',
1241
+ description: '静态加密:status 看状态、enable 生成密钥、encrypt/decrypt 单条记录。只加密 content,摘要与标签保持明文。',
1242
+ parameters: {
1243
+ type: 'object',
1244
+ additionalProperties: false,
1245
+ properties: {
1246
+ action: { type: 'string', enum: ['status', 'enable', 'encrypt', 'decrypt'] },
1247
+ record_id: { type: 'string' },
1248
+ },
1249
+ required: ['action'],
1250
+ },
1251
+ output: { schema: textOut({ result: { type: 'object', additionalProperties: true } }), render: renderText },
1252
+ isConcurrencySafe: () => true,
1253
+ execute: async (args) => {
1254
+ const action = String(args?.action ?? 'status')
1255
+ if (action === 'status') {
1256
+ const s = store.cryptoStatus()
1257
+ return { text: '加密:' + (s.enabled ? '已启用' : '未启用') + '\n密钥:' + s.keyPath, result: s }
1258
+ }
1259
+ if (action === 'enable') {
1260
+ const s = store.enableCrypto()
1261
+ return { text: '加密已启用' + (s.created ? '(已生成新密钥)' : '(沿用已有密钥)') + '\n密钥:' + s.keyPath, result: s }
1262
+ }
1263
+ const id = String(args?.record_id ?? '')
1264
+ if (!id) return { text: 'record_id 必填', result: {} }
1265
+ const r = action === 'encrypt' ? store.encryptRecord(id) : store.decryptRecord(id)
1266
+ return { text: (r.encrypted ? '已加密 ' : '已解密 ') + r.record_id, result: r }
1267
+ },
1268
+ },
1269
+ { label: '加密', argsHint: 'mem_crypto({ action: status|enable|encrypt|decrypt, record_id? })', needsOpen: true },
1270
+ )
1271
+
1272
+ // ---------- 图查询(v9 实现:标签/同批次共现) ----------
1273
+
1274
+ add(
1275
+ {
1276
+ name: 'mem_graph_view',
1277
+ description: '图邻域:从一条记忆出发,按标签/同批次共现关系做 BFS,返回邻近记忆与边(hops 1-3)。',
1278
+ parameters: {
1279
+ type: 'object',
1280
+ additionalProperties: false,
1281
+ properties: {
1282
+ record_id: { type: 'string', description: '起点记录 ID' },
1283
+ hops: { type: 'integer', description: '跳数,默认 1,最多 3' },
1284
+ edge_types: { type: 'array', items: { type: 'string' }, description: '只保留这些边类型(tag/batch)' },
1285
+ rebuild: { type: 'boolean', description: '是否先重建全量边' },
1286
+ },
1287
+ required: ['record_id'],
1288
+ },
1289
+ output: {
1290
+ schema: textOut({
1291
+ root: { type: 'string' },
1292
+ nodes: { type: 'array', items: { type: 'object', additionalProperties: true } },
1293
+ edges: { type: 'array', items: { type: 'object', additionalProperties: true } },
1294
+ }),
1295
+ render: renderText,
1296
+ },
1297
+ isConcurrencySafe: () => true,
1298
+ execute: async (args) => {
1299
+ if (args?.rebuild || store.db.prepare('SELECT COUNT(*) AS n FROM edges').get().n === 0) store.buildEdges()
1300
+ const result = store.graphNeighbors(String(args?.record_id ?? ''), {
1301
+ hops: args?.hops ?? 1,
1302
+ edgeTypes: args?.edge_types ?? null,
1303
+ })
1304
+ const lines = [`起点 ${result.root}:${result.nodes.length - 1} 个邻近记忆,${result.edges.length} 条边`]
1305
+ for (const node of result.nodes.filter((n) => n.depth > 0).slice(0, 20)) {
1306
+ lines.push(`- [d${node.depth}] ${node.record_id} [${node.layer}] ${String(node.summary ?? '').slice(0, 50)}`)
1307
+ }
1308
+ return { text: lines.join('\n'), root: result.root, nodes: result.nodes, edges: result.edges }
1309
+ },
1310
+ },
1311
+ { label: '图邻域', argsHint: 'mem_graph_view({ record_id, hops?, edge_types?, rebuild? })', needsOpen: true },
1312
+ )
1313
+
1314
+ add(
1315
+ {
1316
+ name: 'mem_graph_traverse',
1317
+ description: '图扩散:从多个种子记忆出发一起做 BFS,返回合并后的节点与边(去重)。',
1318
+ parameters: {
1319
+ type: 'object',
1320
+ additionalProperties: false,
1321
+ properties: {
1322
+ seed_ids: { type: 'array', items: { type: 'string' }, description: '种子记录 ID 列表' },
1323
+ hops: { type: 'integer', description: '跳数,默认 2,最多 3' },
1324
+ edge_types: { type: 'array', items: { type: 'string' }, description: '只保留这些边类型' },
1325
+ rebuild: { type: 'boolean', description: '是否先重建全量边' },
1326
+ },
1327
+ required: ['seed_ids'],
1328
+ },
1329
+ output: {
1330
+ schema: textOut({
1331
+ seeds: { type: 'array', items: { type: 'string' } },
1332
+ nodes: { type: 'array', items: { type: 'object', additionalProperties: true } },
1333
+ edges: { type: 'array', items: { type: 'object', additionalProperties: true } },
1334
+ }),
1335
+ render: renderText,
1336
+ },
1337
+ isConcurrencySafe: () => true,
1338
+ execute: async (args) => {
1339
+ if (args?.rebuild || store.db.prepare('SELECT COUNT(*) AS n FROM edges').get().n === 0) store.buildEdges()
1340
+ const seeds = Array.isArray(args?.seed_ids) ? args.seed_ids.map(String) : []
1341
+ const result = store.graphTraverse(seeds, { hops: args?.hops ?? 2, edgeTypes: args?.edge_types ?? null })
1342
+ const lines = [`种子 ${result.seeds.length} 个 → 节点 ${result.nodes.length} 个,边 ${result.edges.length} 条`]
1343
+ for (const node of result.nodes.slice(0, 25)) {
1344
+ lines.push(`- ${node.record_id} [${node.layer}] ${String(node.summary ?? '').slice(0, 50)}`)
1345
+ }
1346
+ return { text: lines.join('\n'), seeds: result.seeds, nodes: result.nodes, edges: result.edges }
1347
+ },
1348
+ },
1349
+ { label: '图扩散', argsHint: 'mem_graph_traverse({ seed_ids, hops?, edge_types?, rebuild? })', needsOpen: true },
1350
+ )
1351
+
1352
+ // ---------- 未实现项:显式 degraded,不伪造 ----------
1353
+
1354
+ const stub = (name, label, hint, reason) =>
1355
+ add(
1356
+ {
1357
+ name,
1358
+ description: `${label}(未实现)`,
1359
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
1360
+ output: { schema: textOut({ degraded: { type: 'boolean' }, reason: { type: 'string' } }), render: renderText },
1361
+ isConcurrencySafe: () => true,
1362
+ execute: async () => ({ text: `${name} 暂不可用:${reason}`, degraded: true, reason }),
1363
+ },
1364
+ { label, argsHint: hint, needsOpen: true, ready: false },
1365
+ )
1366
+
1367
+ stub('mem_archive', '降层归档', 'mem_archive({ record_id, target_depth })', '降层与回升指针排在认知层(三期)')
1368
+ stub('mem_fetch_media', '拉取媒体', 'mem_fetch_media({ record_id })', '加密与 R2 在四期')
1369
+
1370
+ return registry
1371
+ }